added harmony-network and new bundler

@types
neeboo 6 years ago
parent b823f1a03c
commit cff1cda279
  1. 2
      examples/temp.html
  2. 28
      examples/testNode.js
  3. 9
      gulpfile.js
  4. 9091
      includes/elliptic/elliptic.js
  5. 5
      package.json
  6. 8
      packages/harmony-account/package.json
  7. 4
      packages/harmony-account/src/account.ts
  8. 1
      packages/harmony-account/src/wallet.ts
  9. 2
      packages/harmony-account/tsconfig.json
  10. 10
      packages/harmony-crypto/package.json
  11. 5
      packages/harmony-crypto/tsconfig.json
  12. 10
      packages/harmony-network/package.json
  13. 8
      packages/harmony-network/src/http.ts
  14. 3
      packages/harmony-network/src/index.ts
  15. 148
      packages/harmony-network/src/messenger.ts
  16. 34
      packages/harmony-network/src/responseMiddleware.ts
  17. 46
      packages/harmony-network/src/rpcBuilder.ts
  18. 15
      packages/harmony-network/src/util.ts
  19. 2
      packages/harmony-network/tsconfig.json
  20. 16
      packages/harmony-utils/package.json
  21. 1
      packages/harmony-utils/src/index.ts
  22. 67
      packages/harmony-utils/src/transformers.ts
  23. 92
      packages/harmony-utils/src/validators.ts
  24. 2
      packages/harmony-utils/tsconfig.json
  25. 103
      scripts/bundle.ts
  26. 91
      scripts/projects.ts
  27. 184
      scripts/rollup/bundleBrowser.js
  28. 2
      tsconfig.base.json
  29. 6
      webpack.config.js

@ -36,6 +36,8 @@
</div> </div>
<script src="../dist/HarmonyAccount.browser.js"></script> <script src="../dist/HarmonyAccount.browser.js"></script>
<script src="../dist/HarmonyCrypto.browser.js"></script> <script src="../dist/HarmonyCrypto.browser.js"></script>
<script src="../dist/HarmonyUtils.browser.js"></script>
<script src="../dist/HarmonyNetwork.browser.js"></script>
</body> </body>

@ -1,11 +1,20 @@
const { Account, Wallet } = require('../packages/harmony-account/lib/index.js'); const {
Account,
Wallet,
} = require('../packages/harmony-account/dist/index.js');
const { const {
getAddressFromPublicKey, getAddressFromPublicKey,
} = require('../packages/harmony-crypto/lib/index.js'); } = require('../packages/harmony-crypto/dist/index.js');
const { const {
isAddress, isAddress,
isPrivateKey, isPrivateKey,
} = require('../packages/harmony-utils/lib/index.js'); } = require('../packages/harmony-utils/dist/index.js');
const { numberToHex } = require('../packages/harmony-utils/dist/index.js');
const {
HttpProvider,
Messenger,
} = require('../packages/harmony-network/dist/index.js');
// const a = Account.new(); // const a = Account.new();
@ -58,3 +67,16 @@ testWallet();
// console.log(a); // console.log(a);
// }); // });
// }); // });
// const newProvider = new HttpProvider('https://dev-api.zilliqa.com');
// const msg = new Messenger(newProvider);
// const getBalance = async () => {
// const res = await msg.send(
// 'GetBalance',
// '9bfec715a6bd658fcb62b0f8cc9bfa2ade71434a',
// );
// console.log(res);
// };
// getBalance();

@ -1,7 +1,12 @@
const { task } = require('gulp'); const { task } = require('gulp');
const del = require('del'); const del = require('del');
const packages = ['harmony-crypto']; const packages = [
'harmony-crypto',
'harmony-account',
'harmony-network',
'harmony-utils',
];
task('cleanBrowser', async () => { task('cleanBrowser', async () => {
await packages.map((p) => { await packages.map((p) => {
@ -12,7 +17,7 @@ task('cleanBrowser', async () => {
task('cleanServer', async () => { task('cleanServer', async () => {
await packages.map((p) => { await packages.map((p) => {
const pathToLib = `packages/${p}/node`; const pathToLib = `packages/${p}/dist`;
return del.sync([pathToLib]); return del.sync([pathToLib]);
}); });
}); });

File diff suppressed because it is too large Load Diff

@ -6,8 +6,10 @@
], ],
"scripts": { "scripts": {
"packages:cleanBrowser": "gulp cleanBrowser", "packages:cleanBrowser": "gulp cleanBrowser",
"packages:cleanServer": "gulp cleanServer",
"packages:browser": "yarn packages:cleanBrowser && rollup --c scripts/rollup/bundleBrowser.js", "packages:browser": "yarn packages:cleanBrowser && rollup --c scripts/rollup/bundleBrowser.js",
"dist": "yarn packages:browser && rm -rf dist && cross-env NODE_ENV=production webpack --config webpack.config.js", "packages:bundler": "yarn packages:cleanServer && yarn build:ts && ts-node -P scripts/tsconfig.json scripts/bundle.ts",
"dist": "yarn packages:bundler && rm -rf dist && cross-env NODE_ENV=production webpack --config webpack.config.js",
"bootstrap": "lerna bootstrap && yarn build", "bootstrap": "lerna bootstrap && yarn build",
"build": "yarn build:proto && yarn build:ts", "build": "yarn build:proto && yarn build:ts",
"build:ts": "tsc -b tsconfig.json", "build:ts": "tsc -b tsconfig.json",
@ -88,6 +90,7 @@
"rollup-plugin-commonjs": "^9.2.0", "rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-json": "^3.1.0", "rollup-plugin-json": "^3.1.0",
"rollup-plugin-license": "^0.8.1", "rollup-plugin-license": "^0.8.1",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0", "rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^3.4.0", "rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-typescript2": "^0.17.1", "rollup-plugin-typescript2": "^0.17.1",

@ -2,8 +2,12 @@
"name": "@harmony/account", "name": "@harmony/account",
"version": "0.0.1", "version": "0.0.1",
"description": "account and wallet for harmony", "description": "account and wallet for harmony",
"main": "lib/index.js", "main": "dist/index.js",
"typings":"lib/index.d.ts", "node": "dist/index.js",
"browser": "dist/index.js",
"module": "dist/index.esm.js",
"jsnext:main": "dist/index.esm.js",
"typings":"dist/index.d.ts",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },

@ -9,7 +9,7 @@ import {
Keystore, Keystore,
} from '@harmony/crypto'; } from '@harmony/crypto';
import { isPrivateKey } from '@harmony/utils'; import { isPrivateKey, add0xToString } from '@harmony/utils';
import { Shards, ShardId } from './types'; import { Shards, ShardId } from './types';
class Account { class Account {
@ -145,7 +145,7 @@ class Account {
if (!isPrivateKey(key)) { if (!isPrivateKey(key)) {
throw new Error(`${key} is not PrivateKey`); throw new Error(`${key} is not PrivateKey`);
} }
this.privateKey = key; this.privateKey = add0xToString(key);
this.publicKey = getPubkeyFromPrivateKey(this.privateKey); this.publicKey = getPubkeyFromPrivateKey(this.privateKey);
this.address = getAddressFromPrivateKey(this.privateKey); this.address = getAddressFromPrivateKey(this.privateKey);
this.shards = new Map().set('default', ''); this.shards = new Map().set('default', '');

@ -36,6 +36,7 @@ class Wallet {
} }
const seed = bip39.mnemonicToSeed(phrase); const seed = bip39.mnemonicToSeed(phrase);
const hdKey = hdkey.fromMasterSeed(seed); const hdKey = hdkey.fromMasterSeed(seed);
//TODO:hdkey should apply to Harmony's settings
const childKey = hdKey.derive(`m/44'/313'/0'/0/${index}`); const childKey = hdKey.derive(`m/44'/313'/0'/0/${index}`);
const privateKey = childKey.privateKey.toString('hex'); const privateKey = childKey.privateKey.toString('hex');
return this.addByPrivateKey(privateKey); return this.addByPrivateKey(privateKey);

@ -3,7 +3,7 @@
"compilerOptions": { "compilerOptions": {
"baseUrl": ".", "baseUrl": ".",
"paths": { "*": ["types/*"] }, "paths": { "*": ["types/*"] },
"outDir": "lib", "outDir": "dist",
"rootDir": "src" "rootDir": "src"
}, },
"include": ["src", "../../typings/**/*.d.ts"], "include": ["src", "../../typings/**/*.d.ts"],

@ -2,12 +2,12 @@
"name": "@harmony/crypto", "name": "@harmony/crypto",
"version": "0.0.1", "version": "0.0.1",
"description": "crypto libraries for harmony", "description": "crypto libraries for harmony",
"main": "lib/index.js", "main": "dist/index.js",
"node": "lib/index.js", "node": "dist/index.js",
"browser": "dist/index.js", "browser": "dist/index.js",
"module": "dist/index.js", "module": "dist/index.esm.js",
"jsnext:main": "dist/index.js", "jsnext:main": "dist/index.esm.js",
"typings":"lib/index.d.ts", "typings":"dist/index.d.ts",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },

@ -1,8 +1,9 @@
{ {
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "lib", "outDir": "dist",
"rootDir": "src" "rootDir": "src"
}, },
"include": ["src", "../../typings/**/*.d.ts"] "include": ["src", "../../typings/**/*.d.ts"],
"references": [{ "path": "../harmony-utils" }]
} }

@ -2,12 +2,12 @@
"name": "@harmony/network", "name": "@harmony/network",
"version": "0.0.1", "version": "0.0.1",
"description": "network suites for harmony", "description": "network suites for harmony",
"main": "lib/index.js", "main": "dist/index.js",
"node": "lib/index.js", "node": "dist/index.js",
"browser": "dist/index.js", "browser": "dist/index.js",
"module": "dist/index.js", "module": "dist/index.esm.js",
"jsnext:main": "dist/index.js", "jsnext:main": "dist/index.esm.js",
"typings": "lib/index.d.ts", "typings": "dist/index.d.ts",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },

@ -45,7 +45,7 @@ class HttpProvider extends BaseProvider {
* @param {Function} callback - callback function * @param {Function} callback - callback function
* @return {any} - RPC Response * @return {any} - RPC Response
*/ */
send(payload: RPCRequestPayload<object>, callback: any): Promise<any> { send(payload: RPCRequestPayload<object>, callback?: any): Promise<any> {
return this.requestFunc({ payload, callback }); return this.requestFunc({ payload, callback });
} }
@ -121,10 +121,10 @@ class HttpProvider extends BaseProvider {
/** /**
* @function optionsHandler * @function optionsHandler
* @memberof HttpProvider.prototype * @memberof HttpProvider.prototype
* @param {Object} obj - options object * @param {object} obj - options object
* @return {Object} - assign a new option object * @return {object} - assign a new option object
*/ */
optionsHandler(obj: object) { optionsHandler(obj: object): object {
if (this.options.user && this.options.password) { if (this.options.user && this.options.password) {
const AUTH_TOKEN = `Basic ${Buffer.from( const AUTH_TOKEN = `Basic ${Buffer.from(
`${this.options.user}:${this.options.password}`, `${this.options.user}:${this.options.password}`,

@ -1,5 +1,8 @@
export * from './baseProvider'; export * from './baseProvider';
export * from './defaultFetcher'; export * from './defaultFetcher';
export * from './messenger';
export * from './rpcBuilder';
export * from './util';
export * from './http'; export * from './http';
export * from './net'; export * from './net';
export * from './rpc'; export * from './rpc';

@ -0,0 +1,148 @@
import { JsonRpc } from './rpcbuilder';
import { ResponseMiddleware } from './responseMiddleware';
import { HttpProvider } from './http';
import { getResultForData } from './util';
import { RPCMethod } from './rpc';
const defaultConfig = {
Default: {
CHAIN_ID: 0,
Network_ID: 'Default',
nodeProviderUrl: 'http://localhost:4200',
},
DevNet: {
CHAIN_ID: 333,
Network_ID: 'DevNet',
nodeProviderUrl: 'https://devnet.harmony.one',
},
TestNet: {
CHAIN_ID: 2,
Network_ID: 'TestNet',
nodeProviderUrl: 'https://devnet.harmony.one',
},
MainNet: {
CHAIN_ID: 1,
Network_ID: 'MainNet',
nodeProviderUrl: 'https://mainnet.harmony.one',
},
};
/**
* @class Messenger
* @description Messenger instance
* @param {HttpProvider} provider HttpProvider
* @param {Object} config config object
* @return {Messenger} Messenger instance
*/
class Messenger {
provider: HttpProvider;
config?: object;
// tslint:disable-next-line: variable-name
Network_ID: string = 'Default';
JsonRpc: JsonRpc;
constructor(provider: HttpProvider, config?: object) {
/**
* @var {Provider} provider
* @memberof Messenger.prototype
* @description Provider instance
*/
this.provider = provider;
/**
* @var {Object} config
* @memberof Messenger.prototype
* @description Messenger config
*/
this.config = config || defaultConfig;
/**
* @var {Number} Network_ID
* @memberof Messenger.prototype
* @description Network ID for current provider
*/
/**
* @var {JsonRpc} JsonRpc
* @memberof Messenger.prototype
* @description JsonRpc instance
*/
this.JsonRpc = new JsonRpc();
// set Network ID
this.setNetworkID(defaultConfig.Default.Network_ID);
}
/**
* @function send
* @memberof Messenger.prototype
* @param {String} method - RPC method
* @param {Object} params - RPC method params
* @return {Object} RPC result
*/
send = async (method: RPCMethod, params: any) => {
this.providerCheck();
try {
const payload = this.JsonRpc.toPayload(method, params);
this.setResMiddleware((data: any) => new ResponseMiddleware(data));
const result = await this.provider.send(payload);
return getResultForData(result); // getResultForData(result)
} catch (e) {
throw new Error(e);
}
};
/**
* @function setProvider
* @memberof Messenger
* @description provider setter
* @param {Provider} provider - provider instance
*/
setProvider(provider: HttpProvider) {
this.provider = provider;
}
/**
* @function providerCheck
* @memberof Messenger
* @description provider checker
* @return {Error|null} provider validator
*/
providerCheck() {
if (!this.provider) {
throw new Error('provider is not found');
}
}
/**
* @function setReqMiddleware
* @description set request middleware
* @memberof Messenger
* @param {any} middleware - middle ware for req
* @param {String} method - method name
*/
setReqMiddleware(middleware: any, method = '*') {
return this.provider.middlewares.request.use(middleware, method);
}
/**
* @function setResMiddleware
* @description set response middleware
* @memberof Messenger
* @param {any} middleware - middle ware for req
* @param {String} method - method name
*/
setResMiddleware(middleware: any, method = '*') {
return this.provider.middlewares.response.use(middleware, method);
}
/**
* @function setNetworkID
* @description set network id
* @memberof Messenger
* @param {String} id network id string
*/
setNetworkID(id: string) {
this.Network_ID = id;
}
}
export { Messenger };

@ -0,0 +1,34 @@
import { RPCResponseBody } from './types';
/**
* @class ResponseMiddleware
* @description Response middleware of RPC
* @param {Object} ResponseBody - response from rpc
* @return {ResponseMiddleware} response middleware instance
*/
class ResponseMiddleware {
result: any;
error: any;
raw: any;
constructor(ResponseBody: RPCResponseBody<any, any>) {
this.result = ResponseBody.result;
this.error = ResponseBody.error;
this.raw = ResponseBody;
}
get getResult() {
return typeof this.result === 'string'
? this.result
: { ...this.result, responseType: 'result' };
}
get getError() {
return typeof this.error === 'string'
? this.error
: { ...this.error, responseType: 'error' };
}
get getRaw() {
return { ...this.raw, responseType: 'raw' };
}
}
export { ResponseMiddleware };

@ -0,0 +1,46 @@
import { RPCRequestPayload } from './types';
import { RPCMethod } from './rpc';
/**
* @class JsonRpc
* @description json rpc instance
* @return {JsonRpc} Json RPC instance
*/
class JsonRpc {
messageId: number;
constructor() {
/**
* @var {Number} messageId
* @memberof JsonRpc.prototype
* @description message id, default 0
*/
this.messageId = 0;
}
/**
* @function toPayload
* @memberof JsonRpc.prototype
* @description convert method and params to payload object
* @param {String} method - RPC method
* @param {Array<object>} params - params that send to RPC
* @return {Object} payload object
*/
toPayload = (
method: RPCMethod,
params: string,
): RPCRequestPayload<object> => {
// FIXME: error to be done by shared/errors
if (!method) throw new Error('jsonrpc method should be specified!');
// advance message ID
this.messageId += 1;
return {
jsonrpc: '2.0',
id: this.messageId,
method,
params: params !== undefined ? [params] : [],
};
};
}
export { JsonRpc };

@ -0,0 +1,15 @@
/**
* @function getResultForData
* @description get result for data by default
* @param {any} data - object get from provider
* @return {any} data result or data
*/
export function getResultForData(data: any): any {
if (data.result) {
return data.getResult;
}
if (data.error) {
return data.getError;
}
return data.getRaw;
}

@ -1,7 +1,7 @@
{ {
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "lib", "outDir": "dist",
"rootDir": "src" "rootDir": "src"
}, },
"include": ["src", "../../typings/**/*.d.ts"] "include": ["src", "../../typings/**/*.d.ts"]

@ -2,15 +2,19 @@
"name": "@harmony/utils", "name": "@harmony/utils",
"version": "0.0.1", "version": "0.0.1",
"description": "utils for harmony", "description": "utils for harmony",
"main": "lib/index.js", "main": "dist/index.js",
"node": "lib/index.js", "node": "dist/index.js",
"browser": "dist/index.js", "browser": "dist/index.js",
"module": "dist/index.js", "module": "dist/index.esm.js",
"jsnext:main": "dist/index.js", "jsnext:main": "dist/index.esm.js",
"typings":"lib/index.d.ts", "typings": "dist/index.d.ts",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"author": "neeboo@firestack.one", "author": "neeboo@firestack.one",
"license": "ISC" "license": "ISC",
"dependencies": {
"@types/bn.js": "^4.11.3",
"bn.js": "^4.11.8"
}
} }

@ -1 +1,2 @@
export * from './validators'; export * from './validators';
export * from './transformers';

@ -0,0 +1,67 @@
import BN from 'bn.js';
import { isString, isNumber, isHex } from './validators';
export const enum Units {
wei = 'wei',
kwei = 'kwei',
Mwei = 'Mwei',
Gwei = 'Gwei',
szabo = 'szabo',
finney = 'finney',
ether = 'ether',
}
export const numberToString = (
obj: BN | number | string,
radix: number = 10,
): string => {
if (BN.isBN(obj)) {
return obj.toString(radix);
} else if (isNumber(obj)) {
return new BN(obj).toString(radix);
} else if (isString(obj) && isNumber(Number(obj))) {
return new BN(obj).toString(radix);
} else {
throw new Error(`cannot parse number:${obj} to string`);
}
};
export const add0xToString = (obj: string): string => {
if (isString(obj) && !obj.startsWith('-')) {
return '0x' + obj.replace('0x', '');
} else if (isString(obj) && obj.startsWith('-')) {
return '-0x' + obj.replace('-', '');
} else {
throw new Error(`${obj} is not String`);
}
};
export const strip0x = (obj: string): string => {
return obj.toLowerCase().replace('0x', '');
};
export const numberToHex = (obj: any): string => {
try {
return add0xToString(numberToString(obj, 16));
} catch (error) {
throw error;
}
};
export const hexToNumber = (hex: string): string => {
if (isHex(hex)) {
return new BN(strip0x(hex), 'hex').toString();
} else {
throw new Error(`${hex} is not hex number`);
}
};
export const toWei = (obj: any): string => {
return '';
};
export const fromWei = (obj: any): string => {
return '';
};
export class Unit {}

@ -13,3 +13,95 @@ export const isPrivateKey = (privateKey: string): boolean => {
export const isPublicKey = (publicKey: string): boolean => { export const isPublicKey = (publicKey: string): boolean => {
return isKeyString(publicKey, 66); return isKeyString(publicKey, 66);
}; };
/**
* [isNumber verify param is a Number]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isNumber = (obj: any): boolean => {
return obj === +obj;
};
/**
* [isNumber verify param is a Number]
* @param {any} obj [value]
* @return {boolean} [boolean]
*/
export const isInt = (obj: any): boolean => {
return isNumber(obj) && Number.isInteger(obj);
};
/**
* [isString verify param is a String]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isString = (obj: any): boolean => {
return obj === `${obj}`;
};
/**
* [isBoolean verify param is a Boolean]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isBoolean = (obj: any): boolean => {
return obj === !!obj;
};
/**
* [isArray verify param input is an Array]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isArray = (obj: any): boolean => {
return Array.isArray(obj);
};
/**
* [isJson verify param input is a Json]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isJsonString = (obj: any): boolean => {
try {
return !!JSON.parse(obj) && isObject(JSON.parse(obj));
} catch (e) {
return false;
}
};
/**
* [isObject verify param is an Object]
* @param {any} obj [value]
* @return {Boolean} [boolean]
*/
export const isObject = (obj: any): boolean => {
return obj !== null && !Array.isArray(obj) && typeof obj === 'object';
};
/**
* [isFunction verify param is a Function]
* @param {any} obj [value]
* @return {Boolean} [description]
*/
export const isFunction = (obj: any): boolean => {
return typeof obj === 'function';
};
export const isHex = (obj: string): boolean => {
if (!isString(obj)) {
throw new Error(`${obj} is not string`);
} else {
try {
return (
(obj.startsWith('0x') || obj.startsWith('-0x')) &&
isNumber(Number.parseInt(obj.toLowerCase().replace('0x', ''), 16))
);
} catch (error) {
throw error;
}
}
};

@ -1,7 +1,7 @@
{ {
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "lib", "outDir": "dist",
"rootDir": "src" "rootDir": "src"
}, },
"include": ["src", "../../typings/**/*.d.ts"] "include": ["src", "../../typings/**/*.d.ts"]

@ -0,0 +1,103 @@
import * as path from 'path';
// tslint:disable-next-line: no-implicit-dependencies
import * as rollup from 'rollup';
// tslint:disable-next-line: no-implicit-dependencies
import alias from 'rollup-plugin-alias';
// tslint:disable-next-line: no-implicit-dependencies
import builtins from 'rollup-plugin-node-builtins';
// tslint:disable-next-line: no-implicit-dependencies
import commonjs from 'rollup-plugin-commonjs';
// tslint:disable-next-line: no-implicit-dependencies
import license from 'rollup-plugin-license';
// tslint:disable-next-line: no-implicit-dependencies
import json from 'rollup-plugin-json';
// tslint:disable-next-line: no-implicit-dependencies
import globals from 'rollup-plugin-node-globals';
// tslint:disable-next-line: no-implicit-dependencies
import resolve from 'rollup-plugin-node-resolve';
// tslint:disable-next-line: no-implicit-dependencies
import typescript2 from 'rollup-plugin-typescript2';
// tslint:disable-next-line: no-implicit-dependencies
import ts from 'typescript';
import { projects, preProcessFunc, preProcessProjects } from './projects';
async function bundles() {
await preProcessFunc(preProcessProjects);
for (const pkg of projects) {
const base = {
input: path.join(pkg.src, 'index.ts'),
plugins: [
alias({
elliptic: path.resolve(
__dirname,
'../',
'includes/elliptic/elliptic.js',
),
}),
resolve({
browser: true,
jsnext: true,
preferBuiltins: true,
}),
// babel(browserConfig),
globals(),
builtins(),
commonjs(),
json(),
typescript2({
typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
tsconfig: path.join(pkg.path, 'tsconfig.json'),
tsconfigOverride: {
module: 'esnext',
stripInternal: true,
emitDeclarationOnly: false,
composite: false,
declaration: false,
declarationMap: false,
sourceMap: true,
},
}),
license({
banner: `Test Banner`,
}),
],
external: projects
.filter((p) => p.name !== pkg.name)
.map((p) => p.scopedName)
.concat(['cross-fetch']),
};
const pkgBundler = await rollup.rollup(base);
await pkgBundler.write({
file: pkg.esm,
name: pkg.globalName,
format: 'esm',
sourcemap: true,
});
await pkgBundler.write({
file: pkg.umd,
exports: 'named',
name: pkg.globalName,
globals: {
...projects.reduce((g, pkg) => {
g[pkg.scopedName] = pkg.globalName;
return g;
}, {}),
tslib: 'tslib',
},
format: 'umd',
sourcemap: true,
});
await pkgBundler.write({
file: pkg.cjs,
name: pkg.globalName,
format: 'cjs',
sourcemap: true,
});
}
}
bundles();

@ -0,0 +1,91 @@
import * as path from 'path';
import * as fs from 'fs';
// tslint:disable-next-line: no-implicit-dependencies
import webpack from 'webpack';
// tslint:disable-next-line: no-implicit-dependencies
import camelCase from 'camelcase';
export const rootPath = path.resolve(__dirname, '../');
export const includesPath = path.join(rootPath, 'includes');
export const packagesPath = path.join(rootPath, 'packages');
export const preProcessProjects = {
preprocess: [
{
name: 'elliptic',
path: path.resolve(__dirname, '../node_modules/elliptic'),
entry: 'lib/elliptic.js',
outDir: path.join(includesPath, 'elliptic'),
},
],
};
export function preProcessFunc(project) {
const modules = project.preprocess.map((mod) => {
return new Promise((resolve, reject) => {
const compiler = webpack({
entry: {
[mod.name]: path.join(mod.path, mod.entry),
},
output: {
filename: '[name].js',
library: mod.name,
libraryTarget: 'commonjs2',
path: mod.outDir,
},
mode: 'production',
optimization: {
minimize: false,
},
});
compiler.run((err, stats) => {
if (err) {
reject(err);
} else {
// logPreProcess(
// `Successfully preprocessed ${Object.keys(
// stats.compilation.assets,
// ).join(' ,')}`,
// );
resolve(stats);
}
});
});
});
return Promise.all(modules);
}
export const projects = fs
.readdirSync(packagesPath)
.filter((p) => fs.lstatSync(path.join(packagesPath, p)).isDirectory())
.map((p) => {
const pkgName = path.basename(p);
const pkgGlobalName = camelCase(pkgName);
const pkgPath = path.join(packagesPath, p);
const pkgSrc = path.join(pkgPath, 'src');
const pkgScopedName = `@harmony/${p.replace('harmony-', '')}`;
const pkgDist = path.join(pkgPath, 'dist');
const pkgUmd = path.join(pkgDist, 'index.umd.js');
const pkgEsm = path.join(pkgDist, 'index.esm.js');
const pkgSystem = path.join(pkgDist, 'index.system.js');
const pkgAmd = path.join(pkgDist, 'index.amd.js');
const pkgCjs = path.join(pkgDist, 'index.cjs.js');
const pkgIife = path.join(pkgDist, 'index.js');
return {
name: pkgName,
globalName: pkgGlobalName,
scopedName: pkgScopedName,
path: pkgPath,
src: pkgSrc,
dist: pkgDist,
umd: pkgUmd,
esm: pkgEsm,
cjs: pkgCjs,
amd: pkgAmd,
iife: pkgIife,
system: pkgSystem,
};
});

@ -1,5 +1,6 @@
import * as path from 'path'; import * as path from 'path';
import camelCase from 'camelcase'; import * as fs from 'fs';
import * as rollup from 'rollup';
import alias from 'rollup-plugin-alias'; import alias from 'rollup-plugin-alias';
import babel from 'rollup-plugin-babel'; import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs'; import commonjs from 'rollup-plugin-commonjs';
@ -8,75 +9,31 @@ import json from 'rollup-plugin-json';
import globals from 'rollup-plugin-node-globals'; import globals from 'rollup-plugin-node-globals';
import resolve from 'rollup-plugin-node-resolve'; import resolve from 'rollup-plugin-node-resolve';
import typescript2 from 'rollup-plugin-typescript2'; import typescript2 from 'rollup-plugin-typescript2';
import webpack from 'webpack'; import camelCase from 'camelcase';
import ts from 'typescript'; import ts from 'typescript';
import packages from '../packages'; import packages from '../packages';
import browserConfig from '../babel/babel.browser.config.js'; import browserConfig from '../babel/babel.browser.config.js';
import { getKeys } from './getDependencies'; import { getKeys } from './getDependencies';
import {
const rootPath = path.resolve(__dirname, '../..'); rootPath,
const includesPath = path.join(rootPath, 'includes'); includesPath,
const packagesPath = path.join(rootPath, 'packages'); packagesPath,
projects,
const project = { preProcessFunc,
preprocess: [ preProcessProjects,
{ } from '../projects';
name: 'elliptic',
path: path.resolve(__dirname, '../node_modules/elliptic'),
entry: 'lib/elliptic.js',
outDir: path.join(includesPath, 'elliptic'),
},
],
};
function preProcess(project) {
const modules = project.preprocess.map((mod) => {
return new Promise((resolve, reject) => {
const compiler = webpack({
entry: {
[mod.name]: path.join(mod.path, mod.entry),
},
output: {
filename: '[name].js',
library: mod.name,
libraryTarget: 'commonjs2',
path: mod.outDir,
},
mode: 'production',
optimization: {
minimize: false,
},
});
compiler.run((err, stats) => {
if (err) {
reject(err);
} else {
// logPreProcess(
// `Successfully preprocessed ${Object.keys(
// stats.compilation.assets,
// ).join(' ,')}`,
// );
resolve(stats);
}
});
});
});
return Promise.all(modules);
}
async function bundles() { async function bundles() {
await preProcess(project); await preProcessFunc(preProcessProjects);
return packages.map((p) => { for (const pkg of projects) {
const external = getKeys(p); const externals = projects
const externalSetting = getKeys(p).length > 0 ? { external } : {}; .filter((p) => p.name !== pkg.name)
const externalObject = external.reduce((g, pkg) => { .map((p) => p.scopedName);
g[`${pkg}`] = pkg.startsWith('@harmony') ? pkg : camelCase(pkg);
return g; const base = {
}, {}); input: path.join(pkg.src, 'index.ts'),
const normal = {
input: `packages/${p}/src/index.ts`,
plugins: [ plugins: [
alias({ alias({
elliptic: path.resolve( elliptic: path.resolve(
@ -90,12 +47,13 @@ async function bundles() {
jsnext: true, jsnext: true,
preferBuiltins: true, preferBuiltins: true,
}), }),
babel(browserConfig), // babel(browserConfig),
globals(), globals(),
commonjs(), commonjs(),
json(), json(),
typescript2({ typescript2({
typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
tsconfig: `${packagesPath}/${p.name}/tsconfig.json`,
tsconfigOverride: { tsconfigOverride: {
module: 'esnext', module: 'esnext',
stripInternal: true, stripInternal: true,
@ -110,21 +68,99 @@ async function bundles() {
banner: `Test Banner`, banner: `Test Banner`,
}), }),
], ],
output: { external: projects
file: `packages/${p}/dist/index.js`, .filter((p) => p.name !== pkg.name)
exports: 'named', .map((p) => p.scopedName)
format: 'umd', .concat(['cross-fetch']),
};
const pkgBundler = await rollup.rollup(base);
await pkgBundler.write({
file: pkg.esm,
name: pkg.globalName,
format: 'esm',
sourcemap: true, sourcemap: true,
name: camelCase(p), });
await bundle.write({
file: pkg.umd,
exports: 'named',
name: pkg.globalName,
globals: { globals: {
...externalObject, ...projects.reduce((g, pkg) => {
g[pkg.scopedName] = pkg.globalName;
return g;
}, {}),
tslib: 'tslib', tslib: 'tslib',
}, },
}, format: 'umd',
}; sourcemap: true,
// return normal;
return Object.assign(normal, externalSetting);
}); });
}
// return projects.map((p) => {
// const external = getKeys(p.name).filter(
// (pkg) => !pkg.startsWith('@harmony'),
// );
// const externalSetting = getKeys(p.name).length > 0 ? { external } : {};
// const externalObject = external.reduce((g, pkg) => {
// g[`${pkg}`] = !pkg.startsWith('@harmony')
// ? pkg
// : `@harmony/${p.name.replace('harmony-', '')}`;
// return g;
// }, {});
// const normal = {
// input: `packages/${p.name}/src/index.ts`,
// plugins: [
// alias({
// elliptic: path.resolve(
// __dirname,
// '../',
// 'includes/elliptic/elliptic.js',
// ),
// }),
// resolve({
// browser: true,
// jsnext: true,
// preferBuiltins: true,
// }),
// // babel(browserConfig),
// globals(),
// commonjs(),
// json(),
// typescript2({
// typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
// tsconfig: `${packagesPath}/${p.name}/tsconfig.json`,
// tsconfigOverride: {
// module: 'esnext',
// stripInternal: true,
// emitDeclarationOnly: false,
// composite: false,
// declaration: false,
// declarationMap: false,
// sourceMap: true,
// },
// }),
// license({
// banner: `Test Banner`,
// }),
// ],
// output: {
// file: `packages/${p.name}/dist/index.js`,
// exports: 'named',
// format: 'umd',
// sourcemap: true,
// name: camelCase(p.name),
// globals: {
// ...externalObject,
// tslib: 'tslib',
// },
// },
// };
// // return normal;
// return Object.assign(normal, externalSetting);
// });
} }
export default bundles(); export default bundles();

@ -23,4 +23,4 @@
"strict": true, "strict": true,
"target": "es5" "target": "es5"
} }
} }

@ -14,9 +14,9 @@ function createBatchConfig(list) {
rules: [ rules: [
{ {
test: /\.js$/, test: /\.js$/,
use: { // use: {
loader: 'babel-loader', // loader: 'babel-loader',
}, // },
}, },
], ],
}, },

Loading…
Cancel
Save