repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
QuietWind/find-imports
|
src/file.ts
|
<gh_stars>0
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import * as Dstore from "data-store";
const store = Dstore("FILENAME");
store.clear();
export const extensions = [".js", ".jsx", ".ts", ".tsx"];
export interface PathOption {
baseUrl: string[];
}
export function digest(str: string): string {
return crypto
.createHash("md5")
.update(str)
.digest("hex");
}
export function genPath(root: string, filename: string): string | null {
const abPath = path.resolve(root, filename);
if (fs.existsSync(abPath) && fs.lstatSync(abPath).isFile()) {
return abPath;
}
return null;
}
function storePathKey(rootfile: string, filename: string) {
return digest(`path_${rootfile}_${filename}`);
}
const DEFAULT_OPTIONS = {
baseUrl: [process.cwd(), `${process.cwd()}/node_modules`],
node_modules: false
};
/**
* node_modules do not thinks
* @param filename_rootfile
* @param filename
* @param options
*/
export function findModulePath(
filename_rootfile: string,
filename: string,
options: PathOption = DEFAULT_OPTIONS
): string | null {
/**
* . 相对路径
* . 绝对路径
*/
const ext = path.extname(filename);
if (ext && extensions.indexOf(ext) === -1) {
return null;
}
if (path.dirname(filename_rootfile) !== filename_rootfile) {
filename_rootfile = path.dirname(filename_rootfile);
}
const storeKey = storePathKey(filename_rootfile, filename);
const storeKeyVal = store.get(storeKey);
const { baseUrl = DEFAULT_OPTIONS.baseUrl } = options;
if (storeKeyVal) {
return storeKeyVal === "null" ? null : storeKeyVal;
}
// save result path and return pathname
const storeAndReturn = (rpath: string | null) => {
store.set(storeKey, String(rpath));
return rpath;
};
const roots = baseUrl.concat(filename_rootfile);
let r: string | null = null;
roots.some(baseRoot => {
if (ext) {
const namepath = genPath(baseRoot, filename);
r = namepath;
return !!namepath;
}
let namepath2: string | null = null;
extensions.some(extname => {
namepath2 = genPath(baseRoot, `${filename}${extname}`);
if (!namepath2) {
namepath2 = genPath(baseRoot, `${filename}/index${extname}`);
}
return !!namepath2;
});
if (namepath2) {
r = namepath2;
return true;
}
return false;
});
return storeAndReturn(r);
}
|
QuietWind/find-imports
|
lib/index.d.ts
|
export interface TFindImportsOptions {
findChild: boolean;
log: boolean;
baseUrl: string[];
}
export declare function findImports(filename: string, options: TFindImportsOptions): string[];
declare const _default: {
findImports: (filename: string, options: TFindImportsOptions) => string[];
findImportsByName: (filename: string) => string[];
findImportsByNameAsync: (filename: string) => Promise<string[]>;
};
export default _default;
|
QuietWind/find-imports
|
test/files/data.ts
|
<reponame>QuietWind/find-imports<gh_stars>0
interface TodoItem {
title: string;
check?: boolean;
}
const baseData: TodoItem[] = [
{ title: "融合知识图谱的文本异构信息网络构建以及在机器学习中的应用" },
{ title: "金融反欺诈中,社交网络算法有用吗?" },
{ title: "用动态自服务的队列和容量管理来帮助用户" },
{ title: "Twitter实时计算平台" },
{ title: "周六欢迎致辞" },
{ title: "Big data, big value" },
{ title: "基于大数据的人工智能应用" },
{ title: "大数据分析,不再是工程师的禁脔!" },
{ title: "从大数据到大价值的道路" },
{ title: "数据如何驱动增长" },
{ title: "Better data, better finance" },
{ title: "结束致辞" },
{ title: "通告及介绍" },
{ title: "Spark 2.0及其下一步发展" },
{ title: "小米大数据和黑科技" },
{ title: "互联网+制造:在物联和数据时代的创新和引领" },
{ title: "结束致辞" },
{ title: "小米数据平台的实践" },
{ title: "滴滴出行实时计算系统架构及实践" },
{ title: "针对大规模机器/深度学习的分布式参数服务器" },
{ title: "大学习时代:应对大数据和大模型的挑战" },
{ title: "YARN集群上的分布式深度学习" },
{ title: "构建基于Apache Kylin的大数据分析平台" },
{ title: "Spark和YARN:最好一起工作" },
{ title: "HDFS erasure coding: 一半的成本,更快的速度" },
{ title: "基于Mesos DCOS的大数据云计算平台架构" },
{ title: "基于Kafka以及Spark Streaming的高扩展性数据质量保证平台" },
{ title: "工业大数据系统及其应用实践" },
{ title: "基于Druid和Drill的OLAP引擎" },
{ title: "Druid: 助力大规模交互式应用" },
{ title: "Alluxio帮助去哪儿网酒店数据业务最高提速300x" },
{ title: "Spark中结构化流计算的深度介绍" },
{ title: "深度学习在Spark平台上进入生产环境" },
{ title: "Apache Kylin的Streaming OLAP实现" },
{ title: "如何高效高质低成本构建和管理大数据研发体系?" },
{ title: "无人机— 海量数据的新领域" },
{ title: "周六午餐时间的行业桌会" }
];
let testData: TodoItem[] = [];
let count = 100;
do {
testData = testData.concat(baseData);
count--;
} while (count > 0);
console.log("data len: " + testData.length);
export default testData;
|
QuietWind/find-imports
|
test/test.ts
|
<gh_stars>0
import { findImports } from "qw-find-imports";
const strs2 = findImports(
"XXXXXXXX/index.js",
{
findChild: true,
log: false,
baseUrl: ["XXXXXXXX"]
}
);
console.log(JSON.stringify(strs2, null, 2));
|
QuietWind/find-imports
|
src/find.by.str.ts
|
<gh_stars>0
import * as babylon from "babylon";
import { default as traverse } from "babel-traverse";
import * as ts from "typescript";
/**
*
* @param ts_str typescript string
* @param filename filename
*/
function transferTsToJs(ts_str: string, filename: string = "demo.ts"): string {
const tsConfig: ts.CompilerOptions = {
jsx: ts.JsxEmit.Preserve,
target: ts.ScriptTarget.ES2015,
sourceMap: false,
module: ts.ModuleKind.CommonJS
};
return ts.transpileModule(ts_str, {
fileName: filename,
compilerOptions: tsConfig
}).outputText;
}
const ARG_TYPES = ["StringLiteral", "Literal"];
const NODE_TYPES = [
"ImportDeclaration",
"ExportNamedDeclaration",
"ExportAllDeclaration"
];
export interface TFindImportsByStrOptions {
isTS: boolean;
filename: string;
}
export function findImportsByStr(
str: string,
options: TFindImportsByStrOptions
): string[] {
const strImports: string[] = [];
const parseStr = options.isTS ? transferTsToJs(str, options.filename) : str;
const astTree = babylon.parse(parseStr, {
sourceType: "module",
allowImportExportEverywhere: true,
plugins: [
"estree",
"decorators",
"classProperties",
"jsx",
"flow",
"dynamicImport",
"objectRestSpread",
"exportExtensions"
]
});
traverse(astTree, {
enter(path: any) {
if (path.node.type === "CallExpression") {
const callee = path.get("callee");
const isDynamicImport = callee.isImport(); // dynamic import
if (callee.isIdentifier({ name: "require" }) || isDynamicImport) {
const arg = path.node.arguments[0];
if (ARG_TYPES.find(t => t === arg.type)) {
strImports.push(arg.value);
}
}
} else if (NODE_TYPES.find(t => t === path.node.type)) {
const { source } = path.node;
if (source && source.value) {
strImports.push(source.value);
}
}
}
});
return strImports;
}
|
Pepijn98/AniNotifs
|
@types/global/index.d.ts
|
<reponame>Pepijn98/AniNotifs<filename>@types/global/index.d.ts<gh_stars>0
interface String {
replaceAll(searchValue: string | RegExp, replaceValue: string): string
}
|
Pepijn98/AniNotifs
|
src/extensions.ts
|
String.prototype.replaceAll = function (searchValue: string | RegExp, replaceValue: string): string {
// Return if both values are the exact same
if (searchValue === replaceValue) return this;
// Save string in variable so we don't modify the original string
let self = this; // eslint-disable-line @typescript-eslint/no-this-alias
// Check if seachValue is a regular expression
if (searchValue instanceof RegExp) {
// To work the regex has to be global
if (!searchValue.global) throw new TypeError("Regex has to be global");
return self.replace(searchValue, replaceValue);
}
// Replace all values from string
let index = self.indexOf(searchValue);
while (index != -1) {
self = self.replace(searchValue, replaceValue);
index = self.indexOf(searchValue);
}
return self;
};
|
Pepijn98/AniNotifs
|
src/feeds.ts
|
import git from "git-rev-sync";
import settings from "./settings";
import pkg from "@/package.json";
import TurndownService from "turndown";
import { Client } from "eris";
import { FeedItem, ValidateFeed } from "./types";
import { shows, exceptions } from "./anime.json";
// matches anything between v2 and vInfinity
const rversion = /v([1-9]\d+|[2-9])/iu;
abstract class IndexSignature {
[k: string]: any;
[k: number]: undefined;
}
export default class Feeds extends IndexSignature {
client: Client;
tds: TurndownService;
constructor(client: Client) {
super();
this.client = client;
this.tds = new TurndownService({
headingStyle: "atx",
bulletListMarker: "-",
codeBlockStyle: "fenced",
emDelimiter: "*"
});
this.tds.addRule("cite", {
filter: ["cite"],
replacement: (content: string) => `*${content}*`
});
}
private validate(item: FeedItem): ValidateFeed {
let watching = false;
let name = "";
for (const anime of shows) {
// Check if the anime is something we're watching and if it isn't a v2, v3... release
if (item.title.includes(anime) && !item.title.match(rversion)) {
watching = true;
name = anime;
}
}
return {
watching,
name
};
}
private async sendWebhook(item: FeedItem, name: string): Promise<void> {
const description = this.tds.turndown(item.description).split("|");
const urls = description.splice(0, 2);
const numbers = item.title.match(/\d{2,3}/giu) || ["00", "00"];
const episode = exceptions.includes(name) ? numbers[1] : numbers[0];
console.info(`[NEW] |> ${name.replaceAll("_", " ")}`);
try {
const message = await this.client.executeWebhook(settings.webhook.id, settings.webhook.token, {
wait: true,
username: "Your daily dose of anime",
avatarURL: settings.avatars[Math.floor(Math.random() * settings.avatars.length)],
embeds: [
{
title: `${episode} | ${name.replaceAll("_", " ")}`,
color: Math.floor(Math.random() * 16777215),
url: item.guid,
description: `${urls.join("|")}\n${description.join("\n")}`,
fields: [
{
name: "Seeders",
value: item["nyaa:seeders"]["#"] || "0",
inline: true
},
{
name: "Leechers",
value: item["nyaa:leechers"]["#"] || "0",
inline: true
},
{
name: "Downloads",
value: item["nyaa:downloads"]["#"] || "0",
inline: true
}
],
timestamp: item.pubdate ? item.pubdate.toISOString() : "",
footer: {
text: `AniNotifs (${pkg.version}) [${git.branch()}@${git.short()}]`
}
}
]
});
message.addReaction("🗑️");
} catch (e) {
console.error(`Error: Failed to send webhook\n${e.stack}`);
}
}
async subsplease(item: FeedItem): Promise<void> {
const { watching, name } = this.validate(item);
if (watching) {
this.sendWebhook(item, name);
}
}
async pokemon(item: FeedItem): Promise<void> {
const { watching, name } = this.validate(item);
if (watching) {
this.sendWebhook(item, name);
}
}
async shamanking(item: FeedItem): Promise<void> {
const { watching, name } = this.validate(item);
if (watching) {
this.sendWebhook(item, name);
}
}
}
|
Pepijn98/AniNotifs
|
src/types.ts
|
// Since rss-feed-emitter has horrible ungly bad types I'll use my own
import { Client, Message } from "eris";
import { Item, Meta, Image, Enclosure } from "feedparser";
export interface FeedConfig {
url: string;
eventName: string;
refresh: number;
userAgent?: string;
}
export interface FeedItem extends Item {
title: string;
description: string;
summary: string;
date: Date | null;
pubdate: Date | null;
link: string;
origlink: string;
author: string;
guid: string;
comments: string;
image: Image;
categories: string[];
enclosures: Enclosure[];
meta: Meta;
[x: string]: any;
}
export declare class FeedError extends Error {
type: string;
message: string;
feed: string;
constructor(type: string, message: string, feed?: string);
}
export interface Webhook {
id: string;
token: string;
channel: string;
}
export interface Settings {
prefix: string;
owner: string;
guild: string;
id: string;
token: string;
webhook: Webhook;
feeds: FeedConfig[];
avatars: string[];
}
export interface ValidateFeed {
watching: boolean;
name: string;
}
export interface CommandContext {
client: Client;
}
export interface Command {
name: string;
aliases?: string[];
run(msg: Message, args: string[], context: CommandContext): Promise<unknown>;
}
export abstract class Command implements Command {}
export interface Imported {
command: Command;
}
|
Pepijn98/AniNotifs
|
src/index.ts
|
import "./extensions";
import settings from "./settings";
import chalk from "chalk";
import path from "path";
import Collection from "@kurozero/collection";
import FeedEmitter from "rss-feed-emitter";
import Feeds from "./feeds";
import { promises as fs } from "fs";
import { Client, TextChannel } from "eris";
import { Command, FeedError, FeedItem, Imported } from "./types";
import { intents, isGuildChannel } from "./utils";
let ready = false;
const emitter = new FeedEmitter({
skipFirstLoad: true
});
const client = new Client(settings.token, {
autoreconnect: true,
compress: true,
getAllUsers: true,
restMode: true,
defaultImageFormat: "webp",
defaultImageSize: 2048,
intents: intents
});
const feeds = new Feeds(client);
for (const feed of settings.feeds) {
emitter.on(feed.eventName, (item: FeedItem) => feeds[feed.eventName](item));
}
emitter.on("error", (error: FeedError) => {
console.error(chalk.bold.redBright(`Error: ${error.name} (${error.feed})`) + "\n" + error.message);
});
emitter.add(...settings.feeds);
client.on("ready", async () => {
if (!ready) {
client.commands = new Collection(Command);
const commandDir = path.join(__dirname, "commands");
const files = await fs.readdir(commandDir);
for (const file of files) {
if (/\.(j|t)s$/iu.test(file)) {
const commandPath = path.join(commandDir, file);
try {
const { command } = (await import(commandPath)) as Imported;
if (client.commands.contains(command)) {
return console.warn(`[COMMAND_HANDLER] |> A command with the name ${command.name} already exists and has been skipped`);
}
client.commands.add(command);
console.info(`[COMMAND_HANDLER] |> Loaded command ${command.name}`);
} catch (e) {
console.warn(`[COMMAND_HANDLER] |> ${commandPath} - ${e.stack}`);
}
}
}
console.log(`[INIT] |>\n${emitter.list.map((item) => ` ${item.url}`).join("\n")}`);
}
ready = true;
});
client.on("messageCreate", async (msg) => {
if (!ready) return; // Bot not ready yet
if (!msg.author) return; // Probably system message
if (msg.author.discriminator === "0000") return; // Probably a webhook
if (msg.author.id === client.user.id) return; // Ignore self
if (!isGuildChannel(msg.channel)) return; // Ignore all DMs
if (msg.content.startsWith(settings.prefix)) {
const parts = msg.content.split(" ");
const name = parts[0].slice(settings.prefix.length);
const args = parts.splice(1);
const context = { client };
const command = client.commands.find((c) => c.name === name || c.aliases?.includes(name))?.value;
if (!command) return;
try {
await command.run(msg, args, context);
} catch (e) {
console.error(e);
try {
await msg.channel.createMessage({
embed: {
color: 0xdc143c,
description: e.toString()
}
});
} catch (e) {}
}
}
});
client.on("messageReactionAdd", async (msg, emoji, member) => {
if (member.id === settings.owner && msg.channel.id === settings.webhook.channel && emoji.name === "🗑️") {
const guild = client.guilds.get(settings.guild);
const channel = guild.channels.get(settings.webhook.channel) as TextChannel;
const message = channel.messages.get(msg.id) || (await channel.getMessage(msg.id));
await message.delete();
}
});
client.on("error", (e: any) => {
if (e.code === 1001) {
client.disconnect({ reconnect: true });
} else {
console.error(e);
}
});
process.on("unhandledRejection", (reason) => {
console.error(`[UNHANDLED_REJECTION] |> ${reason}`);
});
process.on("uncaughtException", (e: any) => {
console.error(`[UNCAUGHT_EXCEPTION] |> ${e}`);
});
process.on("SIGINT", () => {
client.disconnect({ reconnect: false });
process.exit(0);
});
client.connect().catch((e) => console.error(`[CONNECT] |> ${e}`));
|
Pepijn98/AniNotifs
|
src/commands/ping.ts
|
<reponame>Pepijn98/AniNotifs
import { Command } from "~/types";
export const command: Command = {
name: "ping",
async run(msg): Promise<void> {
await msg.channel.createMessage("Pong!");
}
};
|
Pepijn98/AniNotifs
|
@types/eris/index.d.ts
|
<filename>@types/eris/index.d.ts<gh_stars>0
import { Collection as RealCollection } from "@kurozero/collection";
import { Command as RealCommand } from "~/types";
declare module "eris" {
interface Client {
commands: RealCollection<RealCommand>
}
}
|
Pepijn98/AniNotifs
|
src/utils.ts
|
import { Channel, GuildChannel, Constants } from "eris";
const { Intents } = Constants;
// prettier-ignore
export const intents =
Intents.guilds |
Intents.guildMembers |
Intents.guildEmojis |
Intents.guildMembers |
Intents.guildMessages |
Intents.guildMessageReactions;
export const isGuildChannel = (channel: Channel): channel is GuildChannel => channel instanceof GuildChannel;
|
samuel2749/license_test_ts
|
src/models/ReviewQuestionModel.ts
|
<gh_stars>0
import QuestionModel from './QuestionModel';
export default class extends QuestionModel {
public wrongAnswer: string[];
constructor(wrongAnswer: string[] = []) {
super();
this.wrongAnswer = wrongAnswer;
}
}
|
samuel2749/license_test_ts
|
src/router/index.ts
|
<filename>src/router/index.ts
import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';
// import Home from '@/views/Home.vue';
// import PM from '@/views/pm/Index.vue';
// import Normal from '@/views/normal/Index.vue';
// import SwiperTest from '@/views/swiper-test/Index.vue';
const Home = () => import(/* webpackChunkName: "home" */ '@/views/Home.vue');
const PM = () => import(/* webpackChunkName: "pm" */ '@/views/pm/Index.vue');
const Normal = () =>
import(/* webpackChunkName: "normal" */ '@/views/normal/Index.vue');
const SwiperTest = () =>
import(
/* webpackChunkName: "swiper-test" */ '@/views/swiper-test/Index.vue'
);
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/pm',
name: 'pm',
component: PM
},
{
path: '/normal/:type',
name: 'normal',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: Normal
},
{
path: '/swiper-test',
name: 'SwiperTest',
component: SwiperTest
}
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
export default router;
|
samuel2749/license_test_ts
|
src/constants/QuestionBank.ts
|
class JsonModel {
public title: string;
public jsonPath: string;
constructor(title = '', jsonPath = '') {
this.title = title;
this.jsonPath = jsonPath;
}
}
export default class {
private jsonModel: JsonModel;
constructor(type: string) {
this.jsonModel = this.getQuestionList(type);
}
private getQuestionList(type: string): JsonModel {
switch (type) {
case 'ebc':
return new JsonModel('EBC', 'ebc.json');
case 'erp':
return new JsonModel('ERP', 'erp.json');
case 'mkp':
return new JsonModel('MKP', 'mkp.json');
case 'bulldozer':
return new JsonModel('推土機', 'bulldozer.json');
}
return new JsonModel();
}
public get title(): string {
return this.jsonModel.title;
}
public get jsonPath(): string {
return this.jsonModel.jsonPath;
}
}
|
samuel2749/license_test_ts
|
src/store/index.ts
|
<reponame>samuel2749/license_test_ts
import Vue from 'vue';
import Vuex from 'vuex';
import test from './module1';
Vue.use(Vuex);
const SET_DEVICE = 'SET_DEVICE';
export default new Vuex.Store({
state: {
isMobile: false,
name: ''
},
mutations: {
SET_DEVICE(state, value) {
state.isMobile = value;
}
},
actions: {
SetDevice: function(context, val) {
context.commit(SET_DEVICE, val);
}
},
modules: {
test
}
});
|
samuel2749/license_test_ts
|
src/store/module1.ts
|
<reponame>samuel2749/license_test_ts<filename>src/store/module1.ts
import { Commit } from 'vuex';
const state = {
menulist: [],
name: 'test'
};
const mutations = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
saveMenuList(states: any, params: object) {
states.menulist = params;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setName(states: any, value: string) {
states.name = value;
}
};
const actions = {
saveMenuListFN(context: { commit: Commit }, params: object) {
context.commit('saveMenuList', params);
},
setName(context: { commit: Commit }, value: string) {
context.commit('setName', value);
}
};
export default {
namespaced: true, // namespaced为false的时候,state,mutations,actions全局可以调用,为true,生成作用域,引用时要声明模块名称
state,
mutations,
actions
};
|
samuel2749/license_test_ts
|
src/models/QuestionModel.ts
|
export default class {
public no = '';
public question = '';
public option: string[] = [];
public answer: string[] = [];
}
|
zealic/vanitygen-hd
|
test/hd.test.ts
|
<gh_stars>1-10
import * as assert from 'assert';
import { HD } from '../src';
import { bip32 } from 'bitcoinjs-lib';
describe('HDWallet', function () {
it('From mnemonic and get first address', async () => {
let wallet = await HD.HDWallet.from('rookie message fee quarter dream shoulder frown lady best wisdom hurdle hub');
assert.strict.equal(wallet.firstAddress, '1AgCEXtJURBQZw9Ds8ziQsGo1dUdbT64Lo');
});
});
describe('HDMWallet', function () {
it('From mnemonic and get first address of multisig', async () => {
let multisigFixture = {
"expectedFirstAddress": "37ovvbYcDEzteTPPfaNk6KUq5t7Zp6kNHY",
"cosigner-0": {
"mnemonic": "ignore off draw destroy obtain resist absent machine modify gym brave glow photo upon creek",
"keys": {
"m/45'": "<KEY>",
"m/45'/0-prv": "<KEY>",
"m/45'/0-pub": "<KEY>"
}
},
"cosigner-1": {
"mnemonic": "aware roast goose prosper dismiss reason runway stick subway rhythm fold girl salon edit ramp absurd double stuff neither scout topic animal brick benefit",
"keys": {
"m/45'": "<KEY>",
"m/45'/1-prv": "<KEY>",
"m/45'/1-pub": "<KEY>"
}
},
"cosigner-2": {
"mnemonic": "brass innocent roof corn bounce project other hundred pause luggage pull panic immense praise join meadow album fiscal door around crunch trap infant report",
"keys": {
"m/45'": "<KEY>",
"m/45'/2-prv": "<KEY>",
"m/45'/2-pub": "<KEY>"
}
}
}
let wallet = await HD.HDWallet.from(multisigFixture["cosigner-0"]["mnemonic"]);
let cosigner1 = multisigFixture["cosigner-1"];
let cosigner2 = multisigFixture["cosigner-2"];
let cosignerStrKeys = [cosigner1.keys["m/45'/1-pub"], cosigner2.keys["m/45'/2-pub"]];
let cosignerKeys = cosignerStrKeys.map(k => bip32.fromBase58(k));
let mwallet = new HD.HDMWallet(wallet, cosignerKeys);
assert.strict.equal(mwallet.firstAddress, multisigFixture["expectedFirstAddress"]);
});
});
|
zealic/vanitygen-hd
|
src/classic/wallet.ts
|
import * as bitcoin from 'bitcoinjs-lib';
export interface IWallet {
readonly privateKey: Buffer;
readonly publicKey: Buffer;
readonly address: string;
}
export class Wallet implements IWallet {
private pair: bitcoin.ECPairInterface;
constructor() {
this.pair = bitcoin.ECPair.makeRandom();
}
static fromWif(wif: string): Wallet {
let wallet = <Wallet>Object.create(Wallet.prototype);
wallet.pair = bitcoin.ECPair.fromWIF(wif);
return wallet;
}
get privateKey(): Buffer {
return this.pair.privateKey;
}
get publicKey(): Buffer {
return this.pair.publicKey;
}
get address(): string {
return bitcoin.payments.p2pkh({ pubkey: this.pair.publicKey }).address;
}
}
|
zealic/vanitygen-hd
|
vanitygen-hd.ts
|
<reponame>zealic/vanitygen-hd<filename>vanitygen-hd.ts
import * as fs from 'fs';
import * as os from 'os';
import * as cluster from 'cluster';
import * as yaml from 'js-yaml';
import { Command } from 'commander';
import { HD } from './src';
function initializeProgram() {
let program = new Command();
program.version("0.2.0");
program.command("generate")
.option("-b, --bits <int>", "BIP32 specifies the entropy length to be tween 128 and 256 bits and a multiple of 32 bits.", Number, 256)
.option("-w, --workers <int>", "Numeber of parallel worker, use 0 as CPU num.", parseInt, 0)
.option("-s, --co-signers <yaml-file>", "Co-signers YAML file, include m/45'/{1~n} public key array.")
.option("-m, --co-members <int>", "Co-signers member num, use 0 as 'MAX(1,LEN(co_signers))'.", parseInt, 0)
.option("-t, --co-last-signer <bool>", "Generated vanity address is last signer, public key path is : m/45'/{n}.", Boolean, false)
.option("-f, --rules-file <rules-file>", "One rule per line, allowing '#' to be a comment.", "rules.txt")
.arguments("[rule-list]")
.action(function (_, cmd: Command) {
generateRun(cmd.opts(), cmd.args);
});
return program;
}
async function* createGenerator(hdGenerator: HD.HDWalletGenerator, matcher: HD.HDWalletMatcher) {
let gen = async () => {
let wallet = await hdGenerator.generate(matcher);
let output: any;
if (wallet.parent) {
output = {
"address": wallet.firstAddress,
"parentAddress": wallet.parent.firstAddress,
"mnemonic": wallet.mnemonic
}
} else {
output = {
"address": wallet.firstAddress,
"mnemonic": wallet.mnemonic
}
}
return output;
};
while (true) {
yield await gen();
}
}
async function parallelRun(generator: HD.HDWalletGenerator, matcher: HD.HDWalletMatcher, workers: number = 0) {
let numCPUs = os.cpus().length;
if(!workers || workers < 0 || workers > numCPUs) {
workers = os.cpus().length;
}
if (cluster.isMaster) {
for (let i = 0; i < workers; i++) {
cluster.fork();
}
cluster.on("message", (_, msg) => {
console.log(yaml.dump([msg], { lineWidth: -1 }));
})
} else {
let matchedGenerator = createGenerator(generator, matcher);
let worker = cluster.worker;
for await (let output of matchedGenerator) {
worker.send(output);
}
}
}
function generateRun(options:any, rules: string[]) {
let bits = options.bits;
let cosiginers: string[] = null;
if (options.coSigners) {
if(!fs.existsSync(options.coSigners)) {
console.error(`Co-signers file '${options.coSigners}' can not be found.`);
process.exit(1);
}
cosiginers = yaml.load(fs.readFileSync(options.coSigners).toString());
}
let generator = new HD.HDWalletGenerator(bits, cosiginers, options.coMembers, options.coLastSigner);
var matcher = new HD.HDWalletMatcher();
if(options.rulesFile) {
let rulesFromFile = matcher.loadRules(options.rulesFile);
if(rulesFromFile.length > 0) {
rules = rulesFromFile.concat(rules);
}
}
if (rules.length > 0) {
matcher.setRules(rules);
}
parallelRun(generator, matcher, options.workers);
}
function main() {
let command = initializeProgram();
command.parse(process.argv);
}
main();
|
zealic/vanitygen-hd
|
src/classic/index.ts
|
<gh_stars>1-10
import { IWallet, Wallet } from './wallet';
export {
IWallet, Wallet
};
|
zealic/vanitygen-hd
|
src/index.ts
|
<gh_stars>1-10
import * as Blackhole from './blackhole';
import * as Classic from './classic';
import * as HD from './hd';
export {
Blackhole,
Classic,
HD,
};
|
zealic/vanitygen-hd
|
src/blackhole/generator.ts
|
<reponame>zealic/vanitygen-hd<filename>src/blackhole/generator.ts
//http://gobittest.appspot.com/ProofOfBurn
|
zealic/vanitygen-hd
|
test/classic.test.ts
|
import * as assert from 'assert';
import { Classic } from '../src';
describe('ClassicWallet', function () {
it('From wif', async () => {
let fixture = {
"brainMnemonic": "?",
"WIF": "L1s3Qpc5G8hs8V24FubcdxcBHPVzfwwD4vGWddRijXjejZKwQbyM",
"address":"19fMFMdS9bi4CwmXVsbAMgNw9RrsgBUPB3"
};
let wallet = Classic.Wallet.fromWif(fixture.WIF);
assert.strict.equal(wallet.address, fixture["address"]);
});
});
|
zealic/vanitygen-hd
|
src/blackhole/wallet.ts
|
const bs58 = require('bs58check')
export interface IWallet {
readonly address: string;
}
const PKH_VERSION = 0;
export class Wallet implements IWallet {
private _address: string;
static fromPublicKeyHash(publicKeyHash: Buffer | string): Wallet {
let wallet = <Wallet>Object.create(Wallet.prototype);
let pkh: Buffer;
if (publicKeyHash instanceof Buffer) {
pkh = <Buffer>publicKeyHash;
} else {
pkh = Buffer.from(<string><unknown>publicKeyHash, "hex");
}
let version: Uint8Array = new Uint8Array([PKH_VERSION]);
wallet._address = bs58.encode(Buffer.concat([version, pkh]));
return wallet;
}
get address(): string {
return this._address;
}
}
|
zealic/vanitygen-hd
|
src/hd/wallet.ts
|
<reponame>zealic/vanitygen-hd
import * as bitcoin from 'bitcoinjs-lib';
import { bip32 } from 'bitcoinjs-lib';
import * as bip39 from 'bip39';
export interface IHDWallet {
readonly parent: IHDWallet;
readonly mnemonic: string;
readonly rootKey: bip32.BIP32Interface;
readonly firstAddress: string;
getAddress(path: string): string;
}
export class HDWallet implements IHDWallet {
static async make(bits: number = 256) {
if(!bits || bits < 128 || bits > 256 || (bits % 32) !== 0) {
bits = 256;
}
let mnemonic = await bip39.generateMnemonic(bits)
let wallet = await HDWallet.from(mnemonic);
return wallet;
}
static async from(mnemonic: string) {
let wallet = new HDWallet();
wallet._mnemonic = mnemonic;
let seed = await bip39.mnemonicToSeed(mnemonic);
wallet._rootKey = bip32.fromSeed(seed);
return wallet;
}
private _mnemonic: string;
private _firstAddress: string;
private _rootKey: bip32.BIP32Interface;
get parent(): IHDWallet {
return null;
}
get mnemonic(): string {
return this._mnemonic;
}
get rootKey(): bip32.BIP32Interface {
return this._rootKey;
}
get firstAddress() {
// Use a BIP44 derivation path for coin #1 (Bitcoin)
const FIRST_PATH = "m/44'/0'/0'/0/0";
if (!this._firstAddress) {
this._firstAddress = this.getAddress(FIRST_PATH);
}
return this._firstAddress;
}
getAddress(path: string): string {
let key = this._rootKey.derivePath(path);
let pkh = bitcoin.payments.p2pkh({ pubkey: key.publicKey });
return pkh.address;
}
}
export class HDMWallet implements IHDWallet {
private wallet: IHDWallet;
private cosigners: bip32.BIP32Interface[];
private _firstMAddress: string;
private _coMembers: number;
private _lastSigner: boolean;
constructor(wallet: IHDWallet, cosigners: bip32.BIP32Interface[], coMembers: number = null, lastSigner: boolean = false) {
this.wallet = wallet;
this.cosigners = cosigners;
this._lastSigner = lastSigner;
if(!coMembers || coMembers <= 0) {
coMembers = Math.max(1, this.cosigners.length);
}
if(!coMembers || coMembers > this.cosigners.length + 1) {
throw Error(`Invalid coMembers ${coMembers}`);
}
this._coMembers = coMembers;
}
get parent(): IHDWallet {
return this.wallet;
}
get mnemonic(): string {
return this.wallet.mnemonic;
}
get rootKey(): bip32.BIP32Interface {
return this.wallet.rootKey;
}
get firstAddress() {
if (!this._firstMAddress) {
this._firstMAddress = this.getAddress('0');
}
return this._firstMAddress;
}
getAddress(path: string) {
// Prepare siginers
let signers: bitcoin.BIP32Interface[];
if(this._lastSigner) {
let solt = this.cosigners.length;
let extKey = this.wallet.rootKey.derivePath(`m/45'/${solt}`);;
signers = this.cosigners.concat([extKey]);
} else {
let extKey = this.wallet.rootKey.derivePath(`m/45'/0`);;
signers = [extKey].concat(this.cosigners);
}
// Generate specify path public keys
let keys = signers.map((signer, i) => {
return signer.derivePath(`0/${path}`).publicKey;
});
let sortedKeys = keys.sort();
// Gernate multisig p2sh address
let p2sh = bitcoin.payments.p2sh({
redeem: bitcoin.payments.p2ms({ m: this._coMembers, pubkeys: sortedKeys })
});
return p2sh.address;
}
}
|
zealic/vanitygen-hd
|
src/hd/generator.ts
|
<gh_stars>1-10
import { bip32 } from 'bitcoinjs-lib';
import { IHDWallet, HDWallet, HDMWallet } from './wallet';
import { HDWalletMatcher } from './matcher';
export class HDWalletGenerator {
private bits: number;
private cosigners: bip32.BIP32Interface[];
private coMembers: number;
private lastSigner: boolean;
constructor(bits: number = 256, strCosigner: string[] = null, coMembers: number = 2, lastSigner: boolean = false) {
this.bits = bits;
if (strCosigner) {
this.cosigners = strCosigner.map(m => bip32.fromBase58(m));
this.coMembers = coMembers;
this.lastSigner = lastSigner;
}
}
async generate(matcher: HDWalletMatcher): Promise<IHDWallet> {
let wallet: IHDWallet;
do {
wallet = await HDWallet.make(this.bits);
if (this.cosigners) {
wallet = new HDMWallet(wallet, this.cosigners, this.coMembers, this.lastSigner);
if (matcher.matchHDM(wallet)) break;
} else {
if (matcher.matchHD(wallet)) break;
}
} while (true);
return wallet;
}
}
|
zealic/vanitygen-hd
|
src/hd/matcher.ts
|
import * as _ from 'lodash';
import * as fs from 'fs';
import { IHDWallet } from './wallet';
const PREFIX_P2PHK = '1';
const PREFIX_P2SH = '3';
export class HDWalletMatcher {
private commonRules: string[];
private hdRules: string[];
private hdmRules: string[];
setRules(rules: string[], hdRules: string[] = [], hdmRules: string[] = []) {
this.commonRules = rules;
this.hdRules = this.commonRules.map(m => PREFIX_P2PHK + m).concat(hdRules);
this.hdmRules = this.commonRules.map(m => PREFIX_P2SH + m).concat(hdmRules);
}
loadRules(fileName: string): string[] {
var rules: string[] = [];
if (fs.existsSync(fileName)) {
rules = fs.readFileSync(fileName).toString().split(/\r?\n/);
rules = rules.map(m => m.trim());
// Remove empty word
rules = <string[]>_.filter(rules, _.size);
// Remove with comment
rules = <string[]>_.filter(rules, m => !m.startsWith('#'));
// Unique
rules = <string[]>_.uniq(rules);
}
return rules;
}
matchHD(wallet: IHDWallet) {
var address = wallet.firstAddress;
let result = _.filter(this.hdRules, rule => address.startsWith(rule));
return result.length > 0;
}
matchHDM(wallet: IHDWallet) {
var address = wallet.firstAddress;
let result = _.filter(this.hdmRules, rule => address.startsWith(rule));
return result.length > 0;
}
}
|
zealic/vanitygen-hd
|
src/hd/index.ts
|
import { IHDWallet, HDWallet, HDMWallet } from './wallet';
import { HDWalletGenerator } from './generator';
import { HDWalletMatcher } from './matcher';
export {
IHDWallet, HDWallet, HDMWallet,
HDWalletMatcher, HDWalletGenerator,
};
|
zealic/vanitygen-hd
|
test/blackhole.test.ts
|
<filename>test/blackhole.test.ts
import * as assert from 'assert';
import { Blackhole } from '../src';
describe('BlackholeWallet', function () {
it('From full zero publicKeyHash', async () => {
let fixture = {
"publicKeyHash": "0000000000000000000000000000000000000000",
"address":"1111111111111111111114oLvT2"
};
let wallet = Blackhole.Wallet.fromPublicKeyHash(fixture.publicKeyHash);
assert.strict.equal(wallet.address, fixture["address"]);
});
});
|
HsiehMinChien/analysis-phone-number
|
pages/index.tsx
|
<reponame>HsiehMinChien/analysis-phone-number
import React, { useState } from "react";
import { compose } from "redux";
import withApollo from "../lib/with-apollo";
import { withRedux } from "../lib/redux";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import Divider from "@material-ui/core/Divider";
import Paper from "../components/paper";
import AppBar from "../components/appbar";
import Drawer from "../components/drawer";
import "./style.styl";
function Home() {
const [isOpen, setIsOpen] = useState(false);
const [isAnalysis, setIsAnalysis] = useState(false);
const [phoneNumber, setPhoneNumber] = useState("");
function _renderAnalysis() {
if (isAnalysis) {
return (
<Paper>
<Typography>您的手機號碼:{phoneNumber}</Typography>
<Divider />
<Typography>
解析:
<br />
有主見、目標。注意工作或感情上太付出而累垮自己。容易白忙一場。
*容易壓力大、操勞而導致肩緊痠痛、 睡不好、嗜睡或失眠
</Typography>
<Divider />
<Typography>
數字磁場: <br />
[91]:延年1 <br />
[12]:絕命1 <br />
[23]:禍害4 <br />
[34]:延年3 <br />
[456]:禍害3 <br />
[67]:生氣2 <br />
[78]:延年2
</Typography>
</Paper>
);
}
return (
<>
<Typography variant="subtitle1" gutterBottom>
當您申購電話、大哥大、車牌....等等,號碼確定時,即已注定您未來運勢,是好?是壞?是吉?或凶?一目了然,因此,千萬疏忽不得。數字號碼顯現吉凶禍福,若能進而轉號開運,則歧嶇鋪平,宏業大展。
</Typography>
<TextField
id="outlined-basic"
label="輸入您的手機號碼"
variant="outlined"
onChange={(e) => setPhoneNumber(e.target.value)}
/>
</>
);
}
return (
<div className="number-analysis">
<div>
<AppBar title="手機數字磁場分析" onClickIconButton={setIsOpen} />
<Drawer isOpen={isOpen} onClickListItem={setIsOpen} />
<Grid container justify="center">
<div className="phone">
<div className="speaker">
<div className="front-camera" />
</div>
<div className="screen">
{_renderAnalysis()}
<Button
variant="contained"
disabled={phoneNumber.length < 1}
onClick={() => {
setIsAnalysis(!isAnalysis);
if (isAnalysis) setPhoneNumber("");
}}
>
{isAnalysis ? "再度測試" : "馬上測試"}
</Button>
</div>
<div className="home"></div>
</div>
</Grid>
<footer>Version 2.5, Power by YPL.</footer>
</div>
</div>
);
}
export default compose(withRedux, withApollo)(Home);
|
HsiehMinChien/analysis-phone-number
|
pages/resume/about-me.tsx
|
<reponame>HsiehMinChien/analysis-phone-number
import { memo } from 'react';
import ContentContainer from '../../components/content-container';
import DownloadButton from '../../components/download-button';
function AboutMe() {
return (
<ContentContainer title="About me" className="about-me">
<div className="personal-photo">
<img src="https://avatars0.githubusercontent.com/u/32015904?s=400&u=018f30fa634d9c6b16f8cf401c652c73fb55e7e5&v=4"/>
</div>
<div className="intrduction">
<h3>Hello,</h3>
<div>I am Jeff, an frontend developr from Taiwan. I have two years experience in frontend region. Currently main skill with react.js</div>
<div className="detail">
<div>Name: <p><NAME></p></div>
<div>Location: <p>Taiwan</p></div>
</div>
<div className="detail">
<div>Birthday: <p>05/28/1985</p></div>
<div>Email: <p><EMAIL></p></div>
</div>
<DownloadButton
fileUrl="https://raw.githubusercontent.com/HsiehMinChien/hsiehminchien.github.io/f4e501e0220ea76174b82142d69ba3a9d32702ae/Hsieh_Min_Chieh___Resume.pdf"
downloadText="Download My Resume"
/>
</div>
</ContentContainer>
);
}
export default memo(AboutMe);
|
HsiehMinChien/analysis-phone-number
|
pages/resume/projects.tsx
|
import { memo } from 'react';
import ContentContainer from '../../components/content-container';
const projectInfoList = [
{
title: 'GraphQL demo project',
description: 'Use open GraphQL api to build an demo project.',
codeUrl: 'https://github.com/HsiehMinChien/graphql-demo-project/',
demoUrl: 'https://graphql-demo-project.mediocre0528.now.sh/',
},
{
title: 'Mobile website demo with onsenui',
description: 'Use Onsen UI lib and open pokemon api to build demo project.',
codeUrl: 'https://github.com/HsiehMinChien/mobile-website-demo-with-onsenui',
demoUrl: 'https://mobile-website-demo-with-onsenui.mediocre0528.now.sh/',
},
{
title: 'GraphQL Server side demo project with nest.js',
description: 'Use Nest.js to build an GraphQL server side.',
codeUrl: 'https://github.com/HsiehMinChien/nestjs-with-graphql',
demoUrl: 'https://nestjs-demo-project.herokuapp.com/graphql/',
},
];
function Projects() {
return (
<ContentContainer title="Personal side-projects" className="projects">
{projectInfoList.map((projectInfo, index) => (
<div key={`${projectInfo.title}${index}`} className="detail">
<div className="title">{projectInfo.title}</div>
<div className="description">{`* ${projectInfo.description}`}</div>
<a className="codeUrl" href={projectInfo.codeUrl} target="_blank">Source Code Link</a>{' / '}
<a className="demoUrl" href={projectInfo.demoUrl} target="_blank">Online Demo Link</a>
</div>
))}
</ContentContainer>
);
}
export default memo(Projects);
|
HsiehMinChien/analysis-phone-number
|
graphql/generate_file/index.tsx
|
import { GraphQLResolveInfo } from 'graphql';
import gql from 'graphql-tag';
import * as React from 'react';
import * as ApolloReactCommon from '@apollo/react-common';
import * as ApolloReactComponents from '@apollo/react-components';
import * as ApolloReactHoc from '@apollo/react-hoc';
export type Maybe<T> = T | null;
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> };
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string,
String: string,
Boolean: boolean,
Int: number,
Float: number,
};
export type PokemonAllUrl = {
__typename?: 'PokemonAllUrl',
ability?: Maybe<Scalars['String']>,
berry?: Maybe<Scalars['String']>,
characteristic?: Maybe<Scalars['String']>,
gender?: Maybe<Scalars['String']>,
generation?: Maybe<Scalars['String']>,
item?: Maybe<Scalars['String']>,
language?: Maybe<Scalars['String']>,
location?: Maybe<Scalars['String']>,
machine?: Maybe<Scalars['String']>,
move?: Maybe<Scalars['String']>,
nature?: Maybe<Scalars['String']>,
pokedex?: Maybe<Scalars['String']>,
pokemon?: Maybe<Scalars['String']>,
region?: Maybe<Scalars['String']>,
stat?: Maybe<Scalars['String']>,
type?: Maybe<Scalars['String']>,
version?: Maybe<Scalars['String']>,
};
export type PokemonInfo = {
__typename?: 'PokemonInfo',
count?: Maybe<Scalars['Int']>,
next?: Maybe<Scalars['String']>,
previous?: Maybe<Scalars['String']>,
results?: Maybe<Array<Maybe<PokemonResults>>>,
};
export type PokemonResults = {
__typename?: 'PokemonResults',
name?: Maybe<Scalars['String']>,
url?: Maybe<Scalars['String']>,
};
export enum PokemonUrlPathType {
Type = 'type',
Pokemon = 'pokemon',
Ability = 'ability'
}
export type Query = {
__typename?: 'Query',
getPokemonAllUrl?: Maybe<PokemonAllUrl>,
getPokemonInfo?: Maybe<PokemonInfo>,
getSystemInfo?: Maybe<System>,
};
export type QueryGetPokemonInfoArgs = {
type: PokemonUrlPathType,
offset?: Maybe<Scalars['Int']>,
limit?: Maybe<Scalars['Int']>
};
export type System = {
__typename?: 'System',
title?: Maybe<Scalars['String']>,
describe?: Maybe<Scalars['String']>,
createdAt?: Maybe<Scalars['String']>,
tags?: Maybe<Array<Maybe<Scalars['String']>>>,
createdBy?: Maybe<Scalars['String']>,
};
export type GetSystemInfoQueryVariables = {};
export type GetSystemInfoQuery = (
{ __typename?: 'Query' }
& { getSystemInfo: Maybe<(
{ __typename?: 'System' }
& SystemFragment
)> }
);
export type SystemFragment = (
{ __typename?: 'System' }
& Pick<System, 'title' | 'describe' | 'createdAt' | 'tags' | 'createdBy'>
);
export const SystemFragmentDoc = gql`
fragment System on System {
title
describe
createdAt
tags
createdBy
}
`;
export const GetSystemInfoDocument = gql`
query GetSystemInfo {
getSystemInfo {
...System
}
}
${SystemFragmentDoc}`;
export type GetSystemInfoComponentProps = Omit<ApolloReactComponents.QueryComponentOptions<GetSystemInfoQuery, GetSystemInfoQueryVariables>, 'query'>;
export const GetSystemInfoComponent = (props: GetSystemInfoComponentProps) => (
<ApolloReactComponents.Query<GetSystemInfoQuery, GetSystemInfoQueryVariables> query={GetSystemInfoDocument} {...props} />
);
export type GetSystemInfoProps<TChildProps = {}> = ApolloReactHoc.DataProps<GetSystemInfoQuery, GetSystemInfoQueryVariables> & TChildProps;
export function withGetSystemInfo<TProps, TChildProps = {}>(operationOptions?: ApolloReactHoc.OperationOption<
TProps,
GetSystemInfoQuery,
GetSystemInfoQueryVariables,
GetSystemInfoProps<TChildProps>>) {
return ApolloReactHoc.withQuery<TProps, GetSystemInfoQuery, GetSystemInfoQueryVariables, GetSystemInfoProps<TChildProps>>(GetSystemInfoDocument, {
alias: 'getSystemInfo',
...operationOptions
});
};
export type GetSystemInfoQueryResult = ApolloReactCommon.QueryResult<GetSystemInfoQuery, GetSystemInfoQueryVariables>;
export interface IntrospectionResultData {
__schema: {
types: {
kind: string;
name: string;
possibleTypes: {
name: string;
}[];
}[];
};
}
const result: IntrospectionResultData = {
"__schema": {
"types": []
}
};
export default result;
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type StitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes>;
export type isTypeOfResolverFn<T = {}> = (obj: T, info: GraphQLResolveInfo) => boolean;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
Query: ResolverTypeWrapper<{}>,
PokemonAllUrl: ResolverTypeWrapper<PokemonAllUrl>,
String: ResolverTypeWrapper<Scalars['String']>,
PokemonUrlPathType: PokemonUrlPathType,
Int: ResolverTypeWrapper<Scalars['Int']>,
PokemonInfo: ResolverTypeWrapper<PokemonInfo>,
PokemonResults: ResolverTypeWrapper<PokemonResults>,
System: ResolverTypeWrapper<System>,
Boolean: ResolverTypeWrapper<Scalars['Boolean']>,
};
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
Query: {},
PokemonAllUrl: PokemonAllUrl,
String: Scalars['String'],
PokemonUrlPathType: PokemonUrlPathType,
Int: Scalars['Int'],
PokemonInfo: PokemonInfo,
PokemonResults: PokemonResults,
System: System,
Boolean: Scalars['Boolean'],
};
export type PokemonAllUrlResolvers<ContextType = any, ParentType extends ResolversParentTypes['PokemonAllUrl'] = ResolversParentTypes['PokemonAllUrl']> = {
ability?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
berry?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
characteristic?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
gender?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
generation?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
item?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
language?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
location?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
machine?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
move?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
nature?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
pokedex?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
pokemon?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
region?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
stat?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
type?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
version?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
__isTypeOf?: isTypeOfResolverFn<ParentType>,
};
export type PokemonInfoResolvers<ContextType = any, ParentType extends ResolversParentTypes['PokemonInfo'] = ResolversParentTypes['PokemonInfo']> = {
count?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>,
next?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
previous?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
results?: Resolver<Maybe<Array<Maybe<ResolversTypes['PokemonResults']>>>, ParentType, ContextType>,
__isTypeOf?: isTypeOfResolverFn<ParentType>,
};
export type PokemonResultsResolvers<ContextType = any, ParentType extends ResolversParentTypes['PokemonResults'] = ResolversParentTypes['PokemonResults']> = {
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
url?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
__isTypeOf?: isTypeOfResolverFn<ParentType>,
};
export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = {
getPokemonAllUrl?: Resolver<Maybe<ResolversTypes['PokemonAllUrl']>, ParentType, ContextType>,
getPokemonInfo?: Resolver<Maybe<ResolversTypes['PokemonInfo']>, ParentType, ContextType, RequireFields<QueryGetPokemonInfoArgs, 'type'>>,
getSystemInfo?: Resolver<Maybe<ResolversTypes['System']>, ParentType, ContextType>,
};
export type SystemResolvers<ContextType = any, ParentType extends ResolversParentTypes['System'] = ResolversParentTypes['System']> = {
title?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
describe?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
createdAt?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
tags?: Resolver<Maybe<Array<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>,
createdBy?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>,
__isTypeOf?: isTypeOfResolverFn<ParentType>,
};
export type Resolvers<ContextType = any> = {
PokemonAllUrl?: PokemonAllUrlResolvers<ContextType>,
PokemonInfo?: PokemonInfoResolvers<ContextType>,
PokemonResults?: PokemonResultsResolvers<ContextType>,
Query?: QueryResolvers<ContextType>,
System?: SystemResolvers<ContextType>,
};
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType>;
// Generated in 2020-10-25T11:01:21+08:00
// Demo for nextjs with typescript graphql redux
|
HsiehMinChien/analysis-phone-number
|
__mocks__/styleMock.ts
|
export default module.exports = {};
|
HsiehMinChien/analysis-phone-number
|
components/clock.tsx
|
import React from "react";
import { useSelector, shallowEqual } from "react-redux";
import cx from "classnames";
import "./style.styl";
const useClock = () => {
return useSelector(
(state: any) => ({
lastUpdate: state.lastUpdate,
light: state.light
}),
shallowEqual
);
};
const formatTime = (time: any) => {
// cut off except hh:mm:ss
return new Date(time).toJSON().slice(11, 19);
};
const Clock = () => {
const { lastUpdate, light } = useClock();
return (
<div className={cx("clock", { light: light })}>
{formatTime(lastUpdate)}
</div>
);
};
export default Clock;
|
HsiehMinChien/analysis-phone-number
|
pages/resume/skills.tsx
|
import { memo } from 'react';
import ContentContainer from '../../components/content-container';
const skillList = [
'Javascript',
'Typescript',
'CSS',
'HTML',
'React.js',
'Redux',
'Bootstrap',
'GraphQL',
'Apollo',
'Next.js',
'SASS',
'style-components',
'Stylus',
'Antd(Ant desing)',
'Nightwatch',
'Jest',
'Nest.js',
'git',
'source tree',
];
function Skills() {
return (
<ContentContainer title="Skills" className="skills">
{skillList.map((skill, index) => (<div key={skill+index} className="detail">{skill}</div>))}
</ContentContainer>
);
}
export default memo(Skills);
|
HsiehMinChien/analysis-phone-number
|
redux/store/index.ts
|
<filename>redux/store/index.ts
import { createStore } from "redux";
const initialState = {
lastUpdate: 0,
light: false,
data: {}
};
const reducer = (state = initialState, action: any) => {
switch (action.type) {
case "TICK":
return {
...state,
lastUpdate: action.lastUpdate,
light: !!action.light
};
case "ALL_DATA":
return {
...state,
data: action.data
};
default:
return state;
}
};
export const initializeStore = (preloadedState = initialState) => {
return createStore(reducer, preloadedState);
};
|
HsiehMinChien/analysis-phone-number
|
pages/count-stock-price/index.tsx
|
<filename>pages/count-stock-price/index.tsx
import { useState } from "react";
import cx from "classnames";
import ReactCalander from "react-calendar";
import { InputNumber, Input } from "antd";
import Moment from "moment";
import Big from "big.js";
import "./style.styl";
const PREFIX_CLASS = "count-stock-price-page";
export default function CountStockPrice() {
const [stockName, setStockName] = useState("");
const [money, onChangeMomey] = useState(0);
const [rate, onChangeRage] = useState(0);
const [value, onChangeDate] = useState([new Date(), new Date()]);
const [startDate, endDate] = value;
function _handleOnChangeDate(date: Date | Date[]) {
onChangeDate(date as any);
}
function _handleOnChangeMomey(value: any) {
onChangeMomey(value);
}
function _handleOnChangeRate(value: any) {
onChangeRage(value);
}
return (
<div className={PREFIX_CLASS}>
<h1 className="page-title">股票月曆表</h1>
<div className="basic-input">
<div>
<label className="stock-name" htmlFor="stock-name">股票名稱:</label>
<Input id="stock-name" size="large" onChange={(e) => setStockName(e.target.value)} />
</div>
<div>
<label className="stock-start-price" htmlFor="stock-start-price">起始股價:</label>
<InputNumber
id="stock-start-price"
size="large"
onChange={_handleOnChangeMomey}
value={money}
min={0}
/>
</div>
<div>
<label className="rate" htmlFor="rate">漲跌率(%):</label>
<InputNumber
id="rate"
size="large"
onChange={_handleOnChangeRate}
value={rate}
min={-10}
max={10}
/>
</div>
<p className="notice">請選擇下方的月曆,選定開始跟結束日期後會自動算出漲跌價格</p>
</div>
<h1 className={cx('stock-name', { isRise: rate > 0 }, { isDown: rate < 0 })}>
{`股票名稱: ${stockName}`}
</h1>
<ReactCalander
selectRange
onChange={_handleOnChangeDate}
value={value}
tileContent={(args: any) => {
const { date } = args;
if (inSelectedRegion(date, startDate, endDate)) {
const range = getRange(date, startDate);
const totalRate = new Big(100 + rate || 0).div(100).pow(range);
const currentMomey = new Big(money || 0).times(totalRate);
if (isTranstionDay(date)) {
return (
<div>
<div
className={cx({ isRise: rate > 0 }, { isDown: rate < 0 })}
>
股價:{currentMomey.toFixed(2)}元
</div>
</div>
);
}
return <div>沒開市</div>;
}
return (
<div>
<div>股價:0.00元</div>
</div>
);
}}
/>
<div className="calender-notice">本試算表僅供參考,實際金額以股市為準。</div>
</div>
);
}
function inSelectedRegion(date: Date, startDate: Date, endDate: Date) {
return (
date.getTime() >= startDate.getTime() &&
date.getTime() <= endDate.getTime()
);
}
function isTranstionDay(date: Date) {
return Moment(date).weekday() !== 0 && Moment(date).weekday() !== 6
}
function getRange(endDate: Date, startDate: Date) {
const endDateMoment = Moment(endDate || Date());
const startDateMoment = Moment(startDate || Date());
const diffOfWeek = endDateMoment.week() - startDateMoment.week();
const endDay = endDateMoment.weekday() < 6 ? endDateMoment.weekday() : 5;
const startDay =
startDateMoment.weekday() < 6 ? startDateMoment.weekday() : 5;
let offsetDay = 0;
let diffOfYear = endDateMoment.year() - startDateMoment.year();
if (
endDateMoment.weekday() > 0 &&
endDateMoment.weekday() < 6 &&
startDateMoment.weekday() > 0 &&
startDateMoment.weekday() < 6
) {
offsetDay = 1;
}
if (diffOfWeek < 0 && diffOfYear === 0) {
diffOfYear += 1;
}
return (diffOfYear * 52 + diffOfWeek) * 5 + endDay - startDay + offsetDay;
}
|
HsiehMinChien/analysis-phone-number
|
components/download-button/index.tsx
|
import { memo, useCallback } from 'react';
import { Button, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import cx from 'classnames';
const PREFIX_CLASS = 'download-button';
function DownloadButton({
className,
fileUrl,
downloadText,
}: {
className?: string,
fileUrl: string,
downloadText: string,
}) {
const _handleDownloadPdfFile = useCallback(() => {
message.info('Start to download!', 3)
const a = document.createElement("a");
a.href = fileUrl;
a.download = 'download.pdf';
a.click();
}, [fileUrl])
return (
<Button
className={cx(PREFIX_CLASS, className)}
onClick={_handleDownloadPdfFile}
type="primary"
shape="round"
icon={<DownloadOutlined />}
>
{downloadText}
</Button>
);
}
export default memo(DownloadButton);
|
HsiehMinChien/analysis-phone-number
|
__tests__/index.test.tsx
|
<filename>__tests__/index.test.tsx
import { shallow } from "enzyme";
import React from "react";
import Clock from "../components/clock";
import { Provider } from "react-redux";
import configureStore from "redux-mock-store";
describe("With Enzyme", () => {
const initialState = { lastUpdate: 0, light: false };
const mockStore = configureStore();
let store;
it("Clock component first test", () => {
store = mockStore(initialState);
const clock = shallow(
<Provider store={store}>
<Clock />
</Provider>
);
expect(clock.props().children).toEqual(<Clock />);
expect(clock).toMatchSnapshot();
});
});
|
HsiehMinChien/analysis-phone-number
|
components/drawer/index.tsx
|
<filename>components/drawer/index.tsx
import { withRouter } from "next/router";
import Drawer from "@material-ui/core/Drawer";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
const DrawerItemList = [
{ text: "手機數字分析", path: "/" },
{ text: "日曆計價表", path: "/count-stock-price" },
];
function CostomizeDrawer({
router,
isOpen,
onClickListItem,
}: {
router: any;
isOpen: boolean;
onClickListItem: (value: boolean) => void;
}) {
const { push } = router;
return (
<Drawer open={isOpen}>
<div role="presentation">
<List>
{DrawerItemList.map((data, index) => (
<ListItem
button
key={data.text}
onClick={() => {
onClickListItem(false);
push(data.path);
}}
>
<ListItemIcon>
{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
</ListItemIcon>
<ListItemText primary={data.text} />
</ListItem>
))}
</List>
</div>
</Drawer>
);
}
export default withRouter(CostomizeDrawer);
|
HsiehMinChien/analysis-phone-number
|
components/appbar/index.tsx
|
<reponame>HsiehMinChien/analysis-phone-number
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
function CostomizeAppBar({
title,
onClickIconButton,
}: {
title: string;
onClickIconButton: (value: boolean) => void;
}) {
return (
<AppBar position="fixed">
<Toolbar variant="dense">
<IconButton
edge="start"
color="inherit"
aria-label="menu"
onClick={() => {
onClickIconButton(true);
}}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit">
{title}
</Typography>
</Toolbar>
</AppBar>
);
}
export default CostomizeAppBar;
|
HsiehMinChien/analysis-phone-number
|
components/content-container/index.tsx
|
<gh_stars>1-10
import { memo, ReactNode } from 'react';
import cx from 'classnames';
import './style.styl';
const PREFIX_CLASS = 'content-container';
function ContentContainer({
className,
title,
children,
}: {
className?: string,
title?: string,
children?: ReactNode,
}) {
return (
<div className={cx(PREFIX_CLASS, className)}>
<div>
{title && <h2 className={`${PREFIX_CLASS}__title`}>{title}</h2>}
<div className={`${PREFIX_CLASS}__content`}>{children}</div>
</div>
</div>
);
}
export default memo(ContentContainer);
|
HsiehMinChien/analysis-phone-number
|
pages/resume/home.tsx
|
<reponame>HsiehMinChien/analysis-phone-number
import { memo } from 'react';
import ContentContainer from '../../components/content-container';
function Home() {
return (
<ContentContainer className="home">
<h1>I'm <NAME><span>.</span></h1>
<h2>An frontend engineer</h2>
</ContentContainer>
);
}
export default memo(Home);
|
HsiehMinChien/analysis-phone-number
|
components/fixed-icon/index.tsx
|
import { ForwardRefExoticComponent, memo } from 'react';
import cx from 'classnames';
import './style.styl';
const PREFIX_CLASS = 'fixed-icon';
function FixedIcon({
className,
IconComponent,
onClickIcon,
}: {
className: string,
IconComponent: ForwardRefExoticComponent<any>,
onClickIcon: () => void,
}) {
return (
<div className={cx(PREFIX_CLASS, className)}>
<IconComponent onClick={onClickIcon} />
</div>
);
}
export default memo(FixedIcon);
|
HsiehMinChien/analysis-phone-number
|
pages/resume/index.tsx
|
<gh_stars>1-10
import { useState, useCallback, memo } from 'react';
import { Modal, Switch } from 'antd';
import cx from 'classnames';
import { SettingOutlined } from '@ant-design/icons';
import FixedIcon from '../../components/fixed-icon';
import Home from './home';
import AboutMe from './about-me';
import ExperienceAndEducation from './experience';
import Skills from './skills';
import Projects from './projects';
import './style.styl';
const PREFIX_CLASS = 'resume';
function Resume() {
const [isDarkMode, setIsDarkMode] = useState(false);
const [isSettingModalVisible, setIsSettingModalVisible] = useState(false);
const _handleCloseModal = useCallback(() => {
setIsSettingModalVisible(false);
}, [])
const _handleOpenModal = useCallback(() => {
setIsSettingModalVisible(true);
}, [])
return (
<div className={cx(PREFIX_CLASS, { 'dark-mode': isDarkMode })}>
<div className={`${PREFIX_CLASS}__left`}>
<div>
</div>
</div>
<div className={`${PREFIX_CLASS}__right`}>
<div>
<Home />
<AboutMe />
<ExperienceAndEducation />
<Skills />
<Projects />
</div>
</div>
<Modal
title="Page Setting"
okText="Close"
visible={isSettingModalVisible}
onCancel={_handleCloseModal}
onOk={_handleCloseModal}
cancelButtonProps={{ style: { display: 'none' } }}
>
<Switch
checkedChildren="dark mode"
unCheckedChildren="light mode"
checked={isDarkMode}
onChange={value => setIsDarkMode(value)}
/>
</Modal>
<FixedIcon
IconComponent={SettingOutlined}
className="setting-icon"
onClickIcon={_handleOpenModal}
/>
</div>
);
}
export default memo(Resume);
|
HsiehMinChien/analysis-phone-number
|
pages/resume/experience.tsx
|
import { memo } from 'react';
import { Timeline } from 'antd';
import ContentContainer from '../../components/content-container';
function ExperienceAndEducation() {
return (
<ContentContainer title="Experience & Education" className="experience">
<Timeline mode="left">
<Timeline.Item>Aug 2019 - currently, ljit tech corp - Frontend Developr</Timeline.Item>
<Timeline.Item>Sep 2018 - June 2019, PressLogic - Frontend Developr</Timeline.Item>
<Timeline.Item>June 2014 - Feb 2017, Quanta - BIOS Engineer</Timeline.Item>
<Timeline.Item color="green"> Sep 2010 - Sep 2012, NTU GIPO - Master degree</Timeline.Item>
<Timeline.Item color="green">Sep 2003 - Sep 2008, NCU Physics - Bachelor degree</Timeline.Item>
</Timeline>
</ContentContainer>
);
}
export default memo(ExperienceAndEducation);
|
HsiehMinChien/analysis-phone-number
|
pages/_app.tsx
|
import Head from "next/head";
import "antd/dist/antd.css";
const metaList = ["description", "keywords", "title", "name"];
export default function MyApp({
Component,
pageProps,
}: {
Component: any;
pageProps: any;
}) {
return (
<>
<Head>
<title><NAME> personal demo projects</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
{metaList.map(meta => (
<meta
key={meta}
name={meta}
property={`og:${meta}`}
content={`<NAME> personal demo projects with Typescript, react.js, stylus, Next.js ... ect`}
/>
))}
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</Head>
<Component {...pageProps} />
</>
);
}
|
HsiehMinChien/analysis-phone-number
|
components/paper.tsx
|
import React from "react";
import cx from "classnames";
import Paper from "@material-ui/core/Paper";
const PREFIX_CLASS = "customize-paper";
const CustomizedPaper = ({
className,
children
}: {
className?: string;
children: any;
}) => {
return (
<Paper className={cx(PREFIX_CLASS, className)} variant="outlined">
{children}
</Paper>
);
};
export default CustomizedPaper;
|
tashian/google-auth-library-nodejs
|
src/index.ts
|
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {GoogleAuth} from './auth/googleauth';
export {Compute, ComputeOptions} from './auth/computeclient';
export {
CredentialBody,
CredentialRequest,
Credentials,
JWTInput,
} from './auth/credentials';
export {GCPEnv} from './auth/envDetect';
export {GoogleAuthOptions} from './auth/googleauth';
export {IAMAuth, RequestMetadata} from './auth/iam';
export {Claims, JWTAccess} from './auth/jwtaccess';
export {JWT, JWTOptions} from './auth/jwtclient';
export {
Certificates,
CodeChallengeMethod,
GenerateAuthUrlOpts,
GetTokenOptions,
OAuth2Client,
OAuth2ClientOptions,
RefreshOptions,
TokenInfo,
VerifyIdTokenOptions,
} from './auth/oauth2client';
export {
UserRefreshClient,
UserRefreshClientOptions,
} from './auth/refreshclient';
export {DefaultTransporter} from './transporters';
const auth = new GoogleAuth();
export {auth, GoogleAuth};
|
Baoyuantop/wasmed
|
test/parser.spec.ts
|
import { depsParser } from "../rpc/parser";
describe("deps parser test", () => {
const modules = [
{
name: "A",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: []
},
{
name: "B",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["A"]
},
{
name: "C",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["A", "B", "D"]
},
{
name: "D",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["F"]
},
{
name: "E",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["D", "C"]
},
{
name: "F",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: []
},
{
name: "G",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["H"]
},
{
name: "H",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["G"]
},
];
const expectRes = [
{
name: "A",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: []
},
{
name: "F",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: []
},
{
name: "B",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["A"]
},
{
name: "D",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["F"]
},
{
name: "C",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["A", "B", "D"]
},
{
name: "E",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["D", "C"]
},
{
name: "G",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["H"]
},
{
name: "H",
path: "target/wasm32-unknown-unknown/release/actor.wasm",
deps: ["G"]
},
]
it("should return expectRes", () => {
const result = depsParser(modules);
expect(result).toStrictEqual(expectRes);
})
});
|
Baoyuantop/wasmed
|
storage/index.ts
|
<filename>storage/index.ts
export * from "./json";
export * from "./wasm";
export * from "./cbmap";
|
Baoyuantop/wasmed
|
debug/index.ts
|
<filename>debug/index.ts
import * as util from "util";
import { getWasmExport } from "../storage";
import { log } from "../utils/log";
export const print = (wasmName: string) => {
return function print (ptr: number, length: number) {
const wasm_exports = getWasmExport(wasmName);
log().star(ptr, length, "from js print");
const value = wasm_exports.memory.buffer.slice(ptr, ptr + length);
const utf8decoder = new util.TextDecoder();
log().star(utf8decoder.decode(value));
};
};
|
Baoyuantop/wasmed
|
storage/cbmap.ts
|
const cbmap = new Map();
type MapPayload = {
cb: number;
user_data: number;
moduleName: string;
funcName: string;
};
export const getIndex = (index: number) => {
return cbmap.get(index);
};
export const setIndex = (index: number, payload: MapPayload) => {
cbmap.set(index, payload);
};
|
Baoyuantop/wasmed
|
sqlite/index.ts
|
import * as sqlite from "sqlite3";
import * as protobuf from "protobufjs";
import { getWasmExport } from "../storage";
import { getValue, setValue, getValueByBytes } from "../utils";
import { log } from "../utils/log";
const db = new sqlite.Database("test.db");
export const _sql_run_callback = (moduleName: string) => {
return function _sql_run_callback (ptr: number, path_length: number, fn: number, addr: number) {
const wasm_exports = getWasmExport(moduleName);
const Sql = getSqlByProto(moduleName, ptr, path_length).toJSON();
log().info(Sql, "sql");
let params = [];
if (Sql.params) {
params = Sql.params.map((item: any) => {
if (item.tp === "bytes") {
return Buffer.from(item.buffer, "base64");
}
if (item.tp === "number") {
return Number(item.number);
}
if (item.tp === "string") {
return item.s;
}
});
}
db.run(Sql.sql, params, (err: any) => {
if (err) {
log().error(err, "err");
const { ptr, length } = setValue(moduleName, "fail");
wasm_exports.call_sql_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
} else {
const { ptr, length } = setValue(moduleName, "ok");
wasm_exports.call_sql_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
}
});
};
};
export const _sql_query_callback = (moduleName: string) => {
return function _sql_query_callback (ptr: number, path_length: number, fn: number, addr: number) {
const wasm_exports = getWasmExport(moduleName);
const sql = getValue(moduleName, ptr, path_length);
log().info(sql, "db.all sql");
db.all(sql, (err, data) => {
if (err) {
log().info(err, "db.all sql fail");
const { ptr, length } = setValue(moduleName, "fail");
wasm_exports.call_sql_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
} else {
log().info(data, "db.all sql success");
const { ptr, length } = setValue(moduleName, JSON.stringify(data));
wasm_exports.call_sql_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
}
});
};
};
export const _sql_operate_callback = (moduleName: string) => {
return function _sql_operate_callback (ptr: number, size: number, fn: number, addr: number) {
const wasm_exports = getWasmExport(moduleName);
const tableName = getValue(moduleName, ptr, size);
log().info(`judge table ${tableName} does it exist`);
db.get(`SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}'`, (error, row) => {
if (error) {
log().error(error);
}
if (row === undefined) {
log().info(`${tableName} table does not exist`);
wasm_exports.call_sql_operate_callback_fn(1, fn, addr);
} else {
log().info(`${tableName} table exist`);
wasm_exports.call_sql_operate_callback_fn(0, fn, addr);
}
});
};
};
const getSqlByProto = (moduleName: string, ptr: number, length: number) => {
log().info(ptr, length, "sql proto from wasm");
const buffer = getValueByBytes(moduleName, ptr, length);
const typedArray = new Uint8Array(buffer);
try {
const root = protobuf.loadSync("common/proto/common.proto");
const Sql = root.lookupType("Sql");
const result = Sql.decodeDelimited(typedArray);
if (result) {
return result;
}
} catch (error) {
log().error("protobuf decode sql error", error);
}
};
|
Baoyuantop/wasmed
|
utils/index.ts
|
<filename>utils/index.ts
import * as util from "util";
import { wasm_modules_amount } from "../index";
import { log } from "../utils/log";
import { event } from "../rpc/parser";
import { getContract, runContract } from "../contract";
import { getWasmExport } from "../storage";
export const setValue = (moduleName: string, value: string) => {
const wasm_exports = getWasmExport(moduleName);
const textEncoder = new util.TextEncoder();
const typedArray = textEncoder.encode(value);
const ptr = wasm_exports._wasm_malloc(typedArray.length);
const Uint8Memory = new Uint8Array(wasm_exports.memory.buffer);
Uint8Memory.subarray(ptr, ptr + typedArray.length).set(typedArray);
return {ptr, length: typedArray.length};
};
export const getValue = (moduleName: string, ptr: number, length: number) => {
const wasm_exports = getWasmExport(moduleName);
const value = wasm_exports.memory.buffer.slice(ptr, ptr + length);
const utf8decoder = new util.TextDecoder();
return utf8decoder.decode(value);
};
export const setValueByBytes = (moduleName: string, bytes: any) => {
const wasm_exports = getWasmExport(moduleName);
const typedArray = new Uint8Array(bytes);
const ptr = wasm_exports._wasm_malloc(typedArray.length);
const Uint8Memory = new Uint8Array(wasm_exports.memory.buffer);
Uint8Memory.subarray(ptr, ptr + typedArray.length).set(typedArray);
return {ptr, length: typedArray.length };
};
export const getValueByBytes = (moduleName: string, ptr: number, length: number) => {
const wasm_exports = getWasmExport(moduleName);
const buffer = wasm_exports.memory.buffer.slice(ptr, ptr + length);
return buffer;
};
export const _get_timestamp = () => {
return Date.now();
};
export const _gen_rand32_callback = (fn: number, addr: number) => {};
export const _load_callback = (moduleName: string) => {
return async function _load_callback (ptr: number, size: number, cb: number, user_data: number) {
const wasm_exports = getWasmExport(moduleName);
log().info(ptr, size, cb, user_data, "from load callback");
const index = await getContract(moduleName, ptr, size);
wasm_exports.call_loader_callback_fn(index, cb, user_data);
};
};
export const _load_run = () => {
return function _load_run (index: number, ptr: number, size: number) {
const result = runContract(index, ptr, size);
return result;
};
};
let wasm_init_next = 1;
// When the previous wasm init is completed, this method will
// be notified to call the next wasm init
export const _callback_number = (index: number, num: number) => {
if (wasm_init_next >= wasm_modules_amount) {
log().info("wasm modules init complate");
return;
} else {
log().info(`wasm entry callback, begin init module ${wasm_init_next}`);
event.emit("next_wasm_init", wasm_init_next);
wasm_init_next++;
}
};
|
Baoyuantop/wasmed
|
notify/index.ts
|
<reponame>Baoyuantop/wasmed<gh_stars>0
import { socket } from "../rpc/server";
export const sendResponseSync = ({ code, index, result, jsonrpc = "2.0" }: RPCResponse) => {
const response = {
jsonrpc,
code,
index,
result,
};
socket.send(JSON.stringify(response));
};
|
Baoyuantop/wasmed
|
fs/index.ts
|
<reponame>Baoyuantop/wasmed
import * as fs from "fs";
import * as util from "util";
import { getWasmExport } from "../storage";
export const _read_file_callback = (ptr: number, path_length: number, fn: number, addr: number) => {
const wasm_exports = getWasmExport();
const value = wasm_exports.memory.buffer.slice(ptr, ptr + path_length);
const utf8decoder = new util.TextDecoder();
const path = utf8decoder.decode(value);
fs.readFile(path, (err, data) => {
// console.log(fn, addr);
wasm_exports.call_read_file_callback_fn(1, fn, addr);
});
return 0;
};
|
Baoyuantop/wasmed
|
utils/log.ts
|
import * as signale from "signale";
signale.config({
displayFilename: true,
displayTimestamp: true,
});
export const log = () => {
return signale;
};
|
Baoyuantop/wasmed
|
notify/callback.ts
|
<gh_stars>0
import { log } from "../utils/log";
import { getIndex, getWasmExport } from "../storage";
import { sendResponseSync } from "./index";
const __callback_u32 = (index: number, result: number) => {
};
const __callback_i32 = (index: number, result: number) => {
if (index > 10) {
log().info(index, result, "from notify i32");
const { cb, user_data, moduleName, funcName } = getIndex(index);
const wasm_exports = getWasmExport(moduleName);
log().info(`call_${funcName}`, result, user_data, cb);
wasm_exports[`call_${funcName}`](result, user_data, cb);
} else {
log().info(index, result, "from notify i32");
const response = {
code: 0,
jsonrpc: "2.0",
index,
result: "",
};
sendResponseSync(response);
}
};
const __callback_u64 = (index: number, result: number) => {
};
const __callback_i64 = (index: number, result: number) => {
};
const __callback_isize = (index: number, result: number) => {
};
const __callback_usize = (index: number, result: number) => {
};
const __callback_bytes = (index: number, ptr: number, length: number) => {
// todo: use protobuf decode result
log().info(index, ptr, length, "from notify bytes");
};
const __callback_null = (index: number) => {
};
export const mw_rt = {
__callback_u32,
__callback_i32,
__callback_i64,
__callback_u64,
__callback_isize,
__callback_usize,
__callback_bytes,
__callback_null,
};
|
Baoyuantop/wasmed
|
storage/wasm.ts
|
<filename>storage/wasm.ts
import { log } from "../utils/log";
const modulesList: ParseModuleList = [];
let curWasm: string;
export const getWasmExport = (name?: string): any => {
const wasmName = name || curWasm;
log().info(`get ${wasmName} module exports`);
const curModule = modulesList.find(item => item.name === wasmName);
return curModule.instance.exports;
};
export const addModuleInstance = (data: ParseModule) => {
modulesList.push(data);
};
export const changeCurWasm = (name: string) => {
if (isModuleExist(name)) {
curWasm = name;
log().info(`change current wasm to ${name}`);
} else {
log().warn(`change wasm to ${name} but failed`);
}
};
export const isModuleExist = (name: string) => {
return modulesList.map(item => item.name).includes(name);
};
|
Baoyuantop/wasmed
|
contract/index.ts
|
import { getWasmExport } from "../storage";
import { log } from "../utils/log";
const contractList: any[] = [];
export const getContract = async (moduleName: string, ptr: number, length: number) => {
const wasm_exports = getWasmExport(moduleName);
const buffer = wasm_exports.memory.buffer.slice(ptr, ptr + length);
log().info(buffer, ptr, length, "from get contract");
const { instance } = await WebAssembly.instantiate(buffer, {});
contractList.push(instance);
return contractList.length - 1;
};
export const runContract = (id: number, ptr: number, length: number) => {
log().info(id, ptr, length, "begin run contract");
const contract = contractList[id];
log().info(contract, "the contract got when run contract");
// todo: add env from ptr & length
const result = contract.exports.main();
return result;
};
|
Baoyuantop/wasmed
|
rpc/handler.ts
|
<reponame>Baoyuantop/wasmed<gh_stars>0
import { IMessage } from "websocket";
import { isModuleExist, getWasmExport, isMethodExits, getCurMethod } from "../storage";
import { log } from "../utils/log";
import { setValueByBytes } from "../utils/index";
export let requestCache: RequestCache[] = [];
export const handler = (message: IMessage) => {
const requestData: any = JSON.parse(message.utf8Data);
log().info("receive a new message 📧", requestData.index);
const { index, type, module, name, args } = requestData;
if (!index || !type || !name || !args) {
return {
code: 32601,
message: "The sent json is not a valid request object",
index,
};
}
if (requestCache.length !== 0 && requestCache.includes(index)) {
return {
code: 32603,
message: "The requested index already exists",
index,
};
}
if (!isModuleExist(module)) {
return {
code: 32602,
message: "The module does not exist or is invalid",
index,
};
}
if (!isMethodExits(module, name)) {
return {
code: 32602,
message: "The method does not exist or is invalid",
index,
};
}
const wasm_exports = getWasmExport(module);
const curMethod = getCurMethod(module, name);
if (curMethod.arguments.length !== args.length) {
return {
code: 32602,
message: "The number of arguments does not match",
index,
};
}
const finalArgs = argsParse(module, index, args);
log().warn(finalArgs, "rpc final args");
wasm_exports[name](...finalArgs);
requestCache.push(index);
};
// Function parameter checksum processing
const argsParse = (moduleName: string, index: number, args: any[]): number[] => {
let argsHandled: number[] = [index];
if (args.length === 0) {
return argsHandled;
}
for (let i = 0; i < args.length; i++) {
const { type, value } = args[i];
if (type === "i32") {
argsHandled.push(value);
}
if (type === "bytes") {
const base64Decode = Buffer.from(value, "base64");
const { ptr, length } = setValueByBytes(moduleName, base64Decode);
argsHandled = argsHandled.concat([ptr, length]);
}
}
return argsHandled;
};
|
Baoyuantop/wasmed
|
rpc/parser.ts
|
<reponame>Baoyuantop/wasmed
import { promises as fs } from "fs";
import * as events from "events";
import { initModule } from "../index";
import { log } from "../utils/log";
export const event = new events.EventEmitter();
export const loadJson = async (folder: string) => {
try {
const filesName = await fs.readdir(folder);
if (filesName.length === 0) {
log().warn("empty folder");
return;
}
const result: any = {};
for (let i = 0; i < filesName.length; i++) {
const buffer = await fs.readFile(`target/abi/${filesName[i]}`);
const data: Method[] = JSON.parse(buffer.toString());
result[filesName[i].slice(0, -5)] = data;
}
return result;
} catch (error) {
log().error("folder not found");
return {};
}
};
export const wasmParser = async (modules: Modules) => {
const ordered = depsParser(modules);
event.on("next_wasm_init", async (index: number) => {
await initModule(ordered[index]);
});
await initModule(ordered[0]);
};
export const depsParser = (modules: Modules): Modules => {
const used = new Set;
const result: Modules = [];
let nameContainer: any[];
let moduleContainer: any[];
let length;
do {
length = modules.length;
nameContainer = [];
moduleContainer = [];
modules = modules.filter(item => {
if (!item.deps.every(Set.prototype.has, used)) {
return true;
}
nameContainer.push(item.name);
moduleContainer.push(item);
});
result.push(...moduleContainer);
nameContainer.forEach(Set.prototype.add, used);
} while (modules.length && modules.length !== length);
result.push(...modules);
return result;
};
|
Baoyuantop/wasmed
|
request/index.ts
|
<gh_stars>0
import axios from "axios";
import { getWasmExport } from "../storage";
import { getValue, setValue } from "../utils";
export const _request_callback = (moduleName: string) => {
return function _request_callback (ptr: number, path_length: number, fn: number, addr: number) {
const wasm_exports = getWasmExport();
const value = getValue(moduleName, ptr, path_length);
const arg = JSON.parse(value);
axios({...arg}).then(result => {
const { ptr, length } = setValue(moduleName, result.data);
wasm_exports.call_request_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
}).catch(error => {
const { ptr, length } = setValue(moduleName, error);
wasm_exports.call_request_callback_fn(ptr, length, fn, addr);
wasm_exports._wasm_free(ptr, length);
});
};
};
|
Baoyuantop/wasmed
|
storage/json.ts
|
<reponame>Baoyuantop/wasmed<filename>storage/json.ts
let methodsList: any = {};
export const initMethodsList = (list: any) => {
methodsList = list;
};
export const isMethodExits = (moduleName: string, methodName: string) => {
const curModule = methodsList[moduleName];
return curModule.map((item: any) => item.name).includes(methodName);
};
export const getModuleMethods = (moduleName: string) => {
return methodsList[moduleName];
};
export const getCurMethod = (moduleName: string, methodName: string) => {
if (isMethodExits(moduleName, methodName)) {
return methodsList[moduleName].find((item: any) => item.name === methodName);
}
};
|
Baoyuantop/wasmed
|
global.d.ts
|
<reponame>Baoyuantop/wasmed
type Modules = Module[];
type Module = {
name: string;
path: string;
deps: string[];
};
type Method = {
name: string;
module: string;
ty: "async" | "sync";
arguments: Arg[];
return: Return;
};
type Arg = {
name: string;
type: ValueType;
};
type Return = {
type: ValueType;
};
type ValueType = "u32" | "i32" | "u64" | "i64" | "isize" | "usize" | "bytes" | "null";
type ParseModuleList = ParseModule[];
type ParseModule = {
name: string;
instance: WebAssembly.Instance;
};
type ParseMethodList = Method[];
type RequestCache = number[];
type RPCRequest = {
jsonrpc: string;
module: string;
name: string;
index: number;
args: any[];
type: string;
};
type RPCResponse = {
jsonrpc: string;
index: number;
code: number;
result: any;
};
declare namespace WebAssembly {
export class Module {
static customSections(module: Module, sectionName: string): ArrayBuffer;
static exports(module: Module): object;
static imports(module: Module): object;
toString(): 'WebAssembly.Module';
}
export class Global {
value: any;
constructor(
descriptor: { value: 'i32' | 'i64' | 'f32' | 'f64'; mutable?: boolean },
value: any
);
toString(): 'WebAssembly.Global';
valueOf(): any;
}
export class Instance {
readonly exports: { [K: string]: Function };
constructor(module: Module, importObject?: object);
grow(pages: number): number;
}
export class Memory {
buffer: ArrayBuffer;
constructor(memoryDescriptor: { initial: number; maximum?: number });
}
export class Table {
length: number;
constructor(tableDescriptor: {
element: string;
initial: number;
maximum?: number;
});
get(index: number): Function;
grow(elements: number): number;
set(index: number, value: Function): void;
}
export class CompileError extends Error {}
export class LinkError extends Error {}
export class RuntimeError extends Error {}
export interface ResultObject {
module: Module;
instance: Instance;
}
export function instantiate(
source: Buffer,
importObject?: object
): Promise<ResultObject>;
}
|
Baoyuantop/wasmed
|
index.ts
|
<reponame>Baoyuantop/wasmed
import * as fs from "fs";
import { mw_rt } from "./notify/callback";
import { print } from "./debug";
import { _read_file_callback } from "./fs";
import { _request_callback } from "./request";
import { _sql_run_callback, _sql_query_callback, _sql_operate_callback } from "./sqlite";
import { _get_timestamp, _gen_rand32_callback, _load_callback, _load_run, _callback_number } from "./utils";
import { startServer, startTest } from "./rpc/server";
import { log } from "./utils/log";
import { getModuleMethods, getWasmExport, addModuleInstance, setIndex } from "./storage";
export let wasm_modules_amount: number;
const wstd = (moduleName: string) => {
return {
print: print(moduleName),
_read_file_callback,
_request_callback: _request_callback(moduleName),
_sql_run_callback: _sql_run_callback(moduleName),
_sql_query_callback: _sql_query_callback(moduleName),
_sql_operate_callback: _sql_operate_callback(moduleName),
_gen_rand32_callback,
_load_callback: _load_callback(moduleName),
_load_run: _load_run(),
_callback_number,
};
};
export const initModule = async (module: Module) => {
log().info(module.name, "module begin init");
const import_object = importGenerate(module);
try {
const wasm = fs.readFileSync(module.path);
const { instance } = await WebAssembly.instantiate(wasm, import_object);
addModuleInstance({
name: module.name,
instance: instance,
});
instance.exports._entry();
} catch (error) {
log().error("module init error", error);
}
};
const importGenerate = (module: Module) => {
const import_object: any = {
wstd: wstd(module.name),
mw_rt,
};
if (module.deps.length === 0) {
return import_object;
} else {
for (const dep of module.deps) {
import_object[dep] = {};
const moduleExpose = getModuleMethods(dep);
for (const expose of moduleExpose) {
let finalArgs: any[] = ["index"];
const argsDefined = expose.arguments;
if (argsDefined.length !== 0) {
for (const arg of argsDefined) {
if (arg.type === "i32") {
finalArgs.push("number");
}
if (arg.type === "bytes") {
finalArgs = finalArgs.concat(["ptr", "length"]);
}
}
}
const ptrIndex = finalArgs.findIndex(item => item === "ptr");
// from: module.name
// to: dep
import_object[dep][expose.name] = (...finalArgs: any) => {
const args = finalArgs;
const cb = args.pop();
const user_data = args.pop();
const index = cb + user_data;
args.unshift(index);
setIndex(index, { cb, user_data, moduleName: module.name, funcName: expose.name });
const from_exports = getWasmExport(dep);
const to_exports = getWasmExport(module.name);
const ptrValue = finalArgs[ptrIndex];
const lengthValue = finalArgs[ptrIndex + 1];
const memory = to_exports.memory.buffer.slice(ptrValue, ptrValue + lengthValue);
const typedArray = new Uint8Array(memory);
const ptr = from_exports._wasm_malloc(typedArray.length);
const Uint8Memory = new Uint8Array(from_exports.memory.buffer);
Uint8Memory.subarray(ptr, ptr + typedArray.length).set(typedArray);
finalArgs[ptrIndex] = ptr;
finalArgs[ptrIndex + 1] = typedArray.length;
from_exports[expose.name](...args);
};
}
}
return import_object;
}
};
export const test = async (modules: Module[]) => {
startTest(modules);
};
export const run = async (modules: Module[]) => {
wasm_modules_amount = modules.length;
startServer(modules);
};
|
Baoyuantop/wasmed
|
rpc/server.ts
|
import { server, connection } from "websocket";
import * as http from "http";
import { handler } from "./handler";
import { loadJson, wasmParser } from "./parser";
import { log } from "../utils/log";
import { initMethodsList } from "../storage";
export let socket: connection;
// For Make Test
export const startTest = async (modules: Modules) => {
try {
log().info("begin parser json");
const result = await loadJson("target/abi/");
initMethodsList(result);
log().success("json files parser success 🌟");
} catch (error) {
log().error("json parser fail", error);
return;
}
try {
await wasmParser(modules);
log().success("wasm files parser success 🦀️");
} catch (error) {
log().error("wasm parser fail", error);
return;
}
};
export const startServer = async (modules: Modules) => {
// load .json
try {
const result = await loadJson("target/abi/");
initMethodsList(result);
log().success("json files parser success 🌟");
} catch (error) {
log().error("json parser fail", error);
return;
}
// load .wasm
try {
await wasmParser(modules);
log().success("wasm files parser success 🦀️");
} catch (error) {
log().error("wasm parser fail", error);
return;
}
const httpServer = http.createServer();
const wsServer = new server({
httpServer: httpServer,
autoAcceptConnections: false,
});
wsServer.on("request", request => {
log().info("a new connect request 🔗");
const connect = request.accept("echo-protocol", request.origin);
socket = connect;
connect.on("message", async (message) => {
const error = handler(message);
if (error) {
const response: RPCResponse = {
jsonrpc: "2.0",
index: error.index,
code: error.code,
result: error.message,
};
connect.send(JSON.stringify(response));
}
});
connect.on("close", (reasonCode, description) => {
log().info("close", reasonCode, description);
});
});
httpServer.listen(3004, () => { log().success("server is running on 3003 🚀"); });
};
|
starsoft35/quark
|
src/util/device.ts
|
<gh_stars>0
// 是否为移动端设备
export const isMobileDevice = () => {
const r = window.matchMedia('(max-width: 768px)');
return r && r.matches;
};
|
starsoft35/quark
|
src/page/Welcome/constant.ts
|
<gh_stars>0
export const TAGS = [
'天擎',
'明月',
'鬼谋',
'魅影',
'星瞳',
'楼兰',
'妖狐',
'世界和平',
'汉江之虎',
'倾城',
'白发',
'独狼',
'卷毛',
'小楼一夜',
'黑衣',
'紫眸',
'斜眉',
'温良如玉',
'狂拽龙少',
'贵公子',
'铁血',
'天下有敌',
'杀手',
'光辉岁月',
'西南狼',
'不死鸟',
'女诸葛',
'书生',
'光芒万丈',
'相师',
'彩云',
'茶神',
'先知',
'青衣',
'烟雨',
'清风',
'蜘蛛侠',
'鹰隼',
'神算',
'花火',
'傲梅',
'猎人',
'暗月',
'花蝴蝶',
];
|
starsoft35/quark
|
src/store/list-demo/reducer.ts
|
<filename>src/store/list-demo/reducer.ts
import { combineReducers, Reducer } from 'redux';
import { getQuxListReducer } from '../base';
import { ID } from './constant';
import { IPageState } from './type';
const listReducer = getQuxListReducer(ID);
export default combineReducers({
listState: listReducer,
}) as Reducer<IPageState>;
|
starsoft35/quark
|
src/store/type.ts
|
<reponame>starsoft35/quark
import { IAppState, APP_CONSTANT } from './app';
import { IListDemoState, LIST_DEMO_CONSTANT } from './list-demo';
export interface IRootReducer {
[APP_CONSTANT.ID]: IAppState;
[LIST_DEMO_CONSTANT.ID]: IListDemoState;
}
export type GetStateFunc = () => IRootReducer;
|
starsoft35/quark
|
src/component/PageLoading.tsx
|
<reponame>starsoft35/quark
import React, { FC } from 'react';
import { Spin } from '@vdfor/react-component';
const Index: FC = () => <Spin />;
export default Index;
|
starsoft35/quark
|
src/store/app/type.ts
|
<reponame>starsoft35/quark
import { SectionStateEnum } from '@vdfor/util';
export interface IAppRouteState {
path: string;
id?: string; // 当前路由页面ID标识
uiStatus: SectionStateEnum;
}
export interface IAppState {
routeState: IAppRouteState;
}
|
starsoft35/quark
|
src/page/Welcome/index.tsx
|
<filename>src/page/Welcome/index.tsx
import React, { useState, useRef, useEffect, useCallback, FC } from 'react';
import { getRandomRound } from '@vdfor/util';
import { goPage } from '@/util';
import { TAGS } from './constant';
import styles from './index.less';
const getTagText = (): string => TAGS[getRandomRound(0, TAGS.length - 1)];
const goIndexPage = () => goPage('/home');
const Welcome: FC = () => {
const timer: any = useRef(null);
const [tagText, setTagText] = useState(getTagText());
const clearTimer = () => {
if (timer && timer.current) {
clearTimeout(timer.current);
}
};
const animate = useCallback(() => {
clearTimer();
timer.current = setTimeout(() => {
setTagText(getTagText());
animate();
}, Math.random() * 300 + 200);
}, []);
useEffect(() => {
animate();
return () => {
clearTimer();
};
}, [animate]);
return (
<div className={`v-styled-center ${styles.wrapper}`}>
<div className={`v-styled-center ${styles.tag}`}>{tagText}</div>
<div className={`v-styled-center ${styles.link}`} onClick={goIndexPage}>
ENTER
</div>
</div>
);
};
export default Welcome;
|
starsoft35/quark
|
src/store/app/index.ts
|
<reponame>starsoft35/quark
import * as APP_CONSTANT from './constant';
import * as appAction from './action';
export { default as appReducer } from './reducer';
export { IAppRouteState, IAppState } from './type';
export { APP_CONSTANT, appAction };
|
starsoft35/quark
|
src/util/index.ts
|
<reponame>starsoft35/quark
export * from './tool';
export * from './check';
export * from './request';
export * from './history';
export * from './device';
export { default as vconsoleInit } from './vconsole';
|
starsoft35/quark
|
src/page/Home/api.ts
|
import { request } from '@/util';
import { API_BASE_URL } from '@/constant';
export const loadUsersApi = () =>
request(`${API_BASE_URL}/user?role=1`, {
method: 'GET',
});
|
starsoft35/quark
|
config/env.ts
|
<reponame>starsoft35/quark
import pkg from '../package.json';
// 用于应用运行的环境变量
const APP_CONFIG = {
development: {
REACT_APP_API_BASE_URL: 'https://mock.vdfor.top/v0',
},
production: {
REACT_APP_API_BASE_URL: 'https://mock.vdfor.top/v0',
},
};
// 运行环境
const nodeEnv = process.env.NODE_ENV || 'production';
// 获取以 REACT_APP_ 开头的环境变量
const getReactAppEnvs = () => {
const builtConstants = {
REACT_APP_NAME: pkg.name,
REACT_APP_VERSION: pkg.version,
...APP_CONFIG[nodeEnv],
};
const initEnvs = { ...builtConstants, ...process.env };
const envs = {};
Object.keys(initEnvs).forEach(key => {
if (/^REACT_APP_/.test(key)) {
envs[`process.env.${key}`] = initEnvs[key];
}
});
return envs;
};
export default getReactAppEnvs;
|
starsoft35/quark
|
src/page/Home/index.tsx
|
import React, { FC, useEffect } from 'react';
import { Button } from 'antd-mobile';
import { loadUsersApi } from './api';
import styles from './index.less';
const Home: FC = () => {
useEffect(() => {
const loadUsers = async () => {
try {
await loadUsersApi();
} catch (error) {
//
}
};
loadUsers();
}, []);
return (
<div>
<h1>Hello, world</h1>
<div className={styles.text}>你好,世界</div>
<Button type="primary">按钮</Button>
</div>
);
};
export default Home;
|
starsoft35/quark
|
src/component/MobileWrapper.tsx
|
<gh_stars>0
import React, { PropsWithChildren } from 'react';
import { Spin } from '@vdfor/react-component';
import { SectionStateEnum } from '@vdfor/util';
import { SectionStateComponent } from '.';
interface IMobileWrapperProps extends PropsWithChildren<any> {
uiStatus?: SectionStateEnum;
}
export default ({ uiStatus = SectionStateEnum.LOADING, children }: IMobileWrapperProps) => (
<>
{(uiStatus === SectionStateEnum.LOADING && <Spin />) ||
(uiStatus === SectionStateEnum.ERROR ? (
<SectionStateComponent style={{ width: '100vw', height: '100vh' }} type="error" />
) : (
children
))}
</>
);
|
starsoft35/quark
|
src/store/store.ts
|
import { createStore, applyMiddleware, compose, Reducer } from 'redux';
import thunk from 'redux-thunk';
import { request } from '@/util';
import rootReducer from './rootReducer';
const composeEnhancers =
typeof window === 'object' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose;
const middlewares = [thunk.withExtraArgument({ request })];
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line
middlewares.push(require('redux-logger').createLogger());
}
const enhancer = composeEnhancers(applyMiddleware(...middlewares));
// configStore
const configStore = (reducer: Reducer<any, any>) => createStore(reducer, enhancer);
export default configStore(rootReducer);
|
starsoft35/quark
|
src/store/list-demo/index.ts
|
import * as LIST_DEMO_CONSTANT from './constant';
import * as listDemoAction from './action';
export { default as listDemoReducer } from './reducer';
export { listDemoAction, LIST_DEMO_CONSTANT };
export { IPageState as IListDemoState, IListDataItem as IListDemoListDataItem } from './type';
|
starsoft35/quark
|
config/config.ts
|
<filename>config/config.ts<gh_stars>0
import { defineConfig } from 'umi';
import fs from 'fs';
import path from 'path';
import lessParse from 'less-var-parse';
import pxToViewPort from 'postcss-px-to-viewport';
import getReactAppEnvs from './env';
import routes from './routes';
const nodeEnv = process.env.NODE_ENV || 'production';
// get antd and antd-mobile theme from src/assets/style/theme.less
const getTheme = () => {
const initTheme = lessParse(
fs.readFileSync(path.join(__dirname, '../src/asset/style/theme.less'), 'utf8'),
);
const theme = {};
Object.keys(initTheme).forEach(key => {
theme[key] = initTheme[key];
});
return theme;
};
// 是否开启SSR
// const isSSR = process.env.REACT_APP_SSR === '1';
export default defineConfig({
// chainWebpack(memo) {
// // 以 -icon.svg 结尾的处理成 react component
// memo.module
// .rule('svg')
// .test(/-icon\.svg(\?v=\d+\.\d+\.\d+)?$/)
// .use('babel-loader')
// .loader(require.resolve('@svgr/webpack'));
// },
define: { ...getReactAppEnvs() },
dva: false,
dynamicImport: { loading: '@/component/PageLoading' },
// @ts-ignore
extraBabelPlugins: [
[
'import',
{
libraryName: '@vdfor/react-component',
libraryDirectory: 'dist/lib',
camel2DashComponentName: false,
},
'@vdfor/react-component',
],
[
'import',
{ libraryName: 'lodash', libraryDirectory: '', camel2DashComponentName: false },
'lodash',
],
'macros',
],
extraPostCSSPlugins: [
pxToViewPort({
viewportWidth: 750,
propList: ['*'],
unitToConvert: 'px',
unitPrecision: 5,
viewportUnit: 'vw',
fontViewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false,
replace: true,
exclude: [/node_modules/],
}),
pxToViewPort({
// 作用于antd-mobile
viewportWidth: 375,
propList: ['*'],
unitToConvert: 'px',
unitPrecision: 5,
viewportUnit: 'vw',
fontViewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false,
replace: true,
exclude: [/![\\/]node_modules[\\/].*antd-mobile[\\/]/],
}),
],
hash: nodeEnv === 'production',
history: {
type: 'browser',
},
ignoreMomentLocale: true,
initialState: false,
manifest: {
basePath: '/',
},
publicPath: nodeEnv === 'production' ? './' : '/',
routes,
singular: true, // 单数模式
// ssr: isSSR,
theme: {
...getTheme(),
},
title: 'quark',
});
|
starsoft35/quark
|
src/store/base/list/type.ts
|
<gh_stars>0
import { SectionStateEnum } from '@vdfor/util';
export interface IListBasicState {
pageSize: number;
pageNum: number;
hasMore: boolean;
loadMoreLoading: boolean;
refreshLoading: boolean;
status: SectionStateEnum;
}
export interface IQuxListState extends IListBasicState {
data: any[];
}
|
starsoft35/quark
|
src/util/check.ts
|
// china mobile phone number regx
export const validPhoneRegx = /^1[0-9]{10}$/;
// email
// eslint-disable-next-line
export const validEmailRegx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// get file stuffix
export const fileSuffixMatchRegx = /\.[^.]+$/;
|
starsoft35/quark
|
src/constant/index.ts
|
export * from './httpCode';
export * from './env';
|
starsoft35/quark
|
src/util/history.ts
|
<filename>src/util/history.ts
import { history } from 'umi';
export const goPage = (url: string, replace = false) => {
if (replace) {
history.replace(url);
return;
}
history.push(url);
};
export const goBack = () => history.goBack();
export const jumpExternalUrl = (url: string, replace = false) => {
if (replace) {
window.location.replace(url);
return;
}
window.location.href = url;
};
|
starsoft35/quark
|
src/app.ts
|
/**
* 运行时配置
* https://umijs.org/zh/guide/runtime-config.html#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%9C%89%E8%BF%90%E8%A1%8C%E6%97%B6%E9%85%8D%E7%BD%AE%EF%BC%9F
*/
import React from 'react';
import { store, appAction } from '@/store';
import Index from './index';
export const onRouteChange = ({
location: { pathname = '/' } = {},
matchedRoutes: [{ route: { meta: { id = undefined } = {} } = {} } = {}],
}) => {
store.dispatch(appAction.setAppRouteState({ path: pathname, id })); // 当前路由信息同步到store
};
export const rootContainer = (container: any) => React.createElement(Index, null, container);
|
starsoft35/quark
|
src/component/ListWrapper.tsx
|
<reponame>starsoft35/quark<gh_stars>0
import React, { PropsWithChildren, CSSProperties } from 'react';
import { SkeletonList } from '@vdfor/react-component';
import styled from 'styled-components/macro';
import { SectionStateEnum, pxTransform } from '@vdfor/util';
import { StyledCenter, SectionStateComponent } from '.';
interface IListWrapperProps extends PropsWithChildren<any> {
uiStatus?: SectionStateEnum;
style?: CSSProperties;
}
const WrapperView = styled.div`
position: relative;
padding: ${pxTransform(16)};
`;
const SectionStateWrapper = styled(StyledCenter)`
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%, -50%, 0);
`;
export default ({
uiStatus = SectionStateEnum.LOADING,
style = {},
children,
}: IListWrapperProps) => (
<WrapperView style={style}>
{(uiStatus === SectionStateEnum.LOADING && <SkeletonList />) ||
(uiStatus === SectionStateEnum.CONTENT ? (
children
) : (
<SectionStateWrapper>
<SectionStateComponent type={uiStatus === SectionStateEnum.ERROR ? 'error' : 'empty'} />
</SectionStateWrapper>
))}
</WrapperView>
);
|
starsoft35/quark
|
src/store/base/list/action.ts
|
import { Dispatch } from 'redux';
import { SectionStateEnum, LoadActionEnum } from '@vdfor/util';
import { cancelHttpCode } from '@/constant';
import {
REFRESH_LIST_FAIL,
REFRESH_LIST_REQUEST,
REFRESH_LIST_SUCCESS,
RESET_LIST_FAIL,
RESET_LIST_REQUEST,
RESET_LIST_SUCCESS,
LOAD_MORE_LIST_SUCCESS,
LOAD_MORE_LIST_REQUEST,
LOAD_MORE_LIST_FAIL,
} from './constant';
import { IQuxListState } from './type';
import { IRootReducer } from '../../type';
interface IParams {
pageName: string;
pageReducerName: string;
listAlias: string;
isPagination: boolean; // 是否分页
loadRestDataFunc: (params: { pageSize: number; pageNum: number }) => Promise<any[]>;
}
interface IActionParams {
type: string;
payload?: any[];
isPagination?: boolean;
pagination?: {
hasMore: boolean;
pageNum: number;
};
}
export const getQuxListAction = ({
pageName,
pageReducerName,
listAlias = 'list',
loadRestDataFunc,
isPagination = true,
}: IParams) => (loadAction: LoadActionEnum) => async (
dispatch: Dispatch<IActionParams>,
getState: any,
) => {
const state = getState() as IRootReducer;
if (!(state[pageReducerName] && state[pageReducerName][listAlias])) {
return;
}
const { status, hasMore, pageNum: initPageNum, loadMoreLoading, refreshLoading } = state[
pageReducerName
][listAlias] as IQuxListState;
if (!hasMore && loadAction === LoadActionEnum.LOADMORE) {
return;
}
if (loadAction !== LoadActionEnum.RESET) {
// reset any
if (loadMoreLoading || refreshLoading || status === SectionStateEnum.LOADING) {
if (loadAction !== LoadActionEnum.LOADMORE) {
// showDurationLoading('正在加载中...');
}
return;
}
}
const selfCachePagination = {
// 缓存pageNum/hasMore - 用于加载失败时恢复
pageNum: initPageNum,
hasMore,
};
switch (
loadAction // request
) {
case LoadActionEnum.RESET:
dispatch({ type: `${pageName}${RESET_LIST_REQUEST}` });
break;
case LoadActionEnum.REFRESH:
dispatch({ type: `${pageName}${REFRESH_LIST_REQUEST}` });
break;
default:
// loadMore
dispatch({ type: `${pageName}${LOAD_MORE_LIST_REQUEST}` });
}
try {
const { pageSize, pageNum } = (getState() as IRootReducer)[pageReducerName][
listAlias
] as IQuxListState;
const payload = await loadRestDataFunc({ pageSize, pageNum });
switch (
loadAction // success
) {
case LoadActionEnum.RESET:
dispatch({ type: `${pageName}${RESET_LIST_SUCCESS}`, payload, isPagination });
break;
case LoadActionEnum.REFRESH:
dispatch({ type: `${pageName}${REFRESH_LIST_SUCCESS}`, payload, isPagination });
break;
default:
// loadMore
dispatch({ type: `${pageName}${LOAD_MORE_LIST_SUCCESS}`, payload });
}
} catch (error) {
if (error && error.status === cancelHttpCode) {
// error from request abort
return;
}
switch (
loadAction // fail
) {
case LoadActionEnum.RESET:
dispatch({ type: `${pageName}${RESET_LIST_FAIL}` });
// dispatch({ type: `${pageName}${RESET_LIST_FAIL}`, pagination: selfCachePagination });
break;
case LoadActionEnum.REFRESH:
dispatch({ type: `${pageName}${REFRESH_LIST_FAIL}`, pagination: selfCachePagination });
break;
default:
// loadMore
dispatch({ type: `${pageName}${LOAD_MORE_LIST_FAIL}`, pagination: selfCachePagination });
}
}
};
|
starsoft35/quark
|
src/store/list-demo/type.ts
|
import { IListBasicState } from '../base';
export interface IListDataItem {
id: string;
num: number;
title: string;
text: string;
imgUrl: string;
createAt: number;
}
export interface IListState extends IListBasicState {
data: IListDataItem[];
}
export interface IPageState {
listState: IListState;
}
|
starsoft35/quark
|
src/store/base/list/reducer.ts
|
<reponame>starsoft35/quark
import { produce } from 'immer';
import { AnyAction } from 'redux';
import { SectionStateEnum } from '@vdfor/util';
import {
REFRESH_LIST_FAIL,
REFRESH_LIST_REQUEST,
REFRESH_LIST_SUCCESS,
RESET_LIST_FAIL,
RESET_LIST_REQUEST,
RESET_LIST_SUCCESS,
LOAD_MORE_LIST_SUCCESS,
LOAD_MORE_LIST_REQUEST,
LOAD_MORE_LIST_FAIL,
} from './constant';
import { IQuxListState } from './type';
const INITIAL_STATE: IQuxListState = {
pageNum: 1,
pageSize: 15,
hasMore: true,
loadMoreLoading: false,
refreshLoading: false,
status: SectionStateEnum.CONTENT,
data: [],
};
export default (pageName: string) => (state: IQuxListState = INITIAL_STATE, action: AnyAction) =>
produce(state, draft => {
const { type, payload = [], isPagination, pagination = {} } = action;
switch (type) {
case `${pageName}${RESET_LIST_REQUEST}`:
Object.assign(draft, {
...INITIAL_STATE,
status: SectionStateEnum.LOADING,
});
break;
case `${pageName}${RESET_LIST_SUCCESS}`: {
const { data, pageSize, pageNum } = state;
const newData = [...data, ...payload];
const hasMore = isPagination ? payload.length >= pageSize : false;
Object.assign(draft, {
data: newData,
status:
!hasMore && newData.length === 0 ? SectionStateEnum.EMPTY : SectionStateEnum.CONTENT,
hasMore,
pageNum: pageNum + 1,
});
break;
}
case `${pageName}${RESET_LIST_FAIL}`:
Object.assign(draft, {
// ...pagination,
status: SectionStateEnum.ERROR,
});
break;
case `${pageName}${LOAD_MORE_LIST_REQUEST}`:
Object.assign(draft, { loadMoreLoading: true });
break;
case `${pageName}${LOAD_MORE_LIST_SUCCESS}`: {
const { data, pageSize, pageNum } = state;
Object.assign(draft, {
data: [...data, ...payload],
loadMoreLoading: false,
hasMore: payload.length >= pageSize,
pageNum: pageNum + 1,
});
break;
}
case `${pageName}${LOAD_MORE_LIST_FAIL}`:
Object.assign(draft, {
...pagination,
loadMoreLoading: false,
});
break;
case `${pageName}${REFRESH_LIST_REQUEST}`:
Object.assign(draft, {
refreshLoading: true,
pageNum: 1,
hasMore: true,
});
break;
case `${pageName}${REFRESH_LIST_SUCCESS}`: {
const { pageSize, pageNum } = state;
const newData = [...payload];
const hasMore = isPagination ? payload.length >= pageSize : false;
Object.assign(draft, {
data: newData,
status:
!hasMore && newData.length === 0 ? SectionStateEnum.EMPTY : SectionStateEnum.CONTENT,
hasMore,
pageNum: pageNum + 1,
refreshLoading: false,
});
break;
}
case `${pageName}${REFRESH_LIST_FAIL}`:
Object.assign(draft, {
...pagination,
refreshLoading: false,
status: SectionStateEnum.CONTENT,
});
break;
default:
Object.assign(draft, {});
}
});
|
starsoft35/quark
|
src/store/index.ts
|
export { default as store } from './store';
export * from './base';
export * from './app';
export * from './type';
/* business start */
export { listDemoAction, LIST_DEMO_CONSTANT, IListDemoListDataItem } from './list-demo';
|
starsoft35/quark
|
src/store/list-demo/api.ts
|
<filename>src/store/list-demo/api.ts
import { request } from '@/util';
import { API_BASE_URL } from '@/constant';
interface ILoadListApiData {
pageNum: number;
pageSize: number;
status: string;
}
export const loadListApi = (params: ILoadListApiData, requestTaskName: string): Promise<any> =>
request(`${API_BASE_URL}/quark-mobile/list`, {
method: 'GET',
params,
requestTaskName,
});
|
starsoft35/quark
|
src/util/tool.ts
|
import { pxTransform as pxTransformUtil } from '@vdfor/util';
/**
* copy from https://github.com/ant-design/ant-design-pro/blob/master/src/components/_utils/pathTools.js
*/
// /userinfo/2144/id => ['/userinfo','/useinfo/2144,'/userindo/2144/id']
export const urlToList = (url: string) => {
const urllist = url.split('/').filter(i => i);
return urllist.map((urlItem, index) => urlItem && `/${urllist.slice(0, index + 1).join('/')}`);
};
export const getBase64Str = (file: any) =>
new Promise(resolve => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
// eslint-disable-next-line
fileReader.onload = function() {
resolve(this.result as any);
};
});
export const pxTransform = (px: number) => pxTransformUtil(px, 32);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.