Skip to content

Commit

Permalink
fix: update require
Browse files Browse the repository at this point in the history
  • Loading branch information
imfly committed Jul 26, 2024
1 parent ddbd1d0 commit 7c2d5ca
Show file tree
Hide file tree
Showing 21 changed files with 422 additions and 718 deletions.
10 changes: 10 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
registry=https://registry.npmjs.org/

# Prevent jsx namespace conflicts, because Vue global types will auto install.
# In the future, Vue 3 will fix this issue
# See https://github.com/vuejs/core/blob/main/CHANGELOG.md#features-1
auto-install-peers=false

# 在安装本地
# 或者 pnpm add web --filter docs --link-workspace-packages=true
link-workspace-packages = true
119 changes: 119 additions & 0 deletions examples/fun-tests/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* 系统启动入口
* wangxm 2018-12-25
*/
const packageFile = require('./package.json')

const command = require('commander')
const path = require('path')
const fs = require('fs')
const DdnCore = require('@ddn/core')
const DdnPeer = require('@ddn/peer').default
const constants = require('./constants')

/**
* 整理系统配置文件生成输入参数
*/
function genOptions () {
command
.version(packageFile.version)
.option('-p, --port <port>', 'Listening port number')
.option('-a, --address <ip>', 'Listening host name or ip')
.option('-b, --blockchain <path>', 'Blockchain db path')
.option('-g, --genesisblock <path>', 'Genesisblock path')
.option('-x, --peers [peers...]', 'Peers list')
.option('-l, --log <level>', 'Log level')
.option('-d, --daemon', 'Run ddn node as daemon')
.option('-e, --execute <path>', 'exe')
.option('-r, --reindex', 'verify or not when block loading')
.option('--dapps <dir>', 'DApps directory')
.option('--base <dir>', 'Base directory')
.parse(process.argv)

const baseDir = command.base || path.resolve(__dirname, './')

let genesisblockFile = path.join(baseDir, 'config', 'genesisBlock.json')
if (command.genesisblock) {
genesisblockFile = path.resolve(process.cwd(), command.genesisblock)
}
if (!fs.existsSync(genesisblockFile)) {
console.error('Failed: DDN genesisblock file does not exists.')
process.exit(1)
}

const genesisblockObject = JSON.parse(fs.readFileSync(genesisblockFile, 'utf8'))

const configObject = DdnCore.getUserConfig({ cwd: baseDir })

configObject.version = packageFile.version
configObject.basedir = baseDir
configObject.buildVersion = 'development'
configObject.net = process.env.NET || 'testnet'
configObject.publicDir = path.join(baseDir, 'public')
configObject.dappsDir = command.dapps || path.join(baseDir, 'dapps')
if (command.port) {
configObject.port = command.port
}

if (command.address) {
configObject.address = command.address
}

if (command.peers) {
if (typeof command.peers === 'string') {
configObject.peers.list = command.peers.split(',').map(peer => {
peer = peer.split(':')
return {
ip: peer.shift(),
port: peer.shift() || configObject.port
}
})
} else {
configObject.peers.list = command.peers
}
}

if (command.log) {
configObject.logLevel = command.log
}

if (command.reindex) {
configObject.loading.verifyOnLoading = true
}

return {
baseDir,
configObject,
constants,
genesisblockObject,
isDaemonMode: !!command.daemon
}
}

async function main () {
global._require_runtime_ = m => {
if (typeof global._require_native_ === 'function') {
return global._require_native_(m)
} else {
return require(m).default || require(m) // 兼容 ESM
}
}

let peer

try {
const options = genOptions()
peer = new DdnPeer()
await peer.run(options)
} catch (err) {
console.error(err)

if (peer) {
peer.destory()
}

process.exit(1)
}
}

main()
3 changes: 2 additions & 1 deletion examples/fun-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@
"build-localnet": "./node_modules/.bin/gulp linux-build-local"
},
"dependencies": {
"@ddn/asset-aob": "1.2.3",
"@ddn/asset-aob": "workspace:*",
"@ddn/asset-dao": "^1.2.2",
"@ddn/asset-dapp": "workspace:*",
"@ddn/asset-evidence": "workspace:*",
"@ddn/core": "workspace:*",
Expand Down
2 changes: 2 additions & 0 deletions examples/fun-tests/src/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const a = require('@ddn/asset-evidence/.ddnrc.js')
console.log('a', a)
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,5 @@
"engines": {
"node": ">=16.14",
"pnpm": "^9.6.0"
},
"packageManager": "pnpm@9.6.0"
}
}
6 changes: 4 additions & 2 deletions packages/asset-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
"name": "@ddn/asset-base",
"version": "2.4.3",
"description": "DDN资产基类相关信息",
"main": "./dist/index.js",

"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
"dist",
"compiled"
],
"repository": {
"type": "git",
Expand Down
18 changes: 14 additions & 4 deletions packages/asset-base/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const a = require('@ddn/asset-evidence/.ddnrc.js')

class AssetUtils {
static loadFromObject (assetPlugins) {
static async loadFromObject (assetPlugins) {
const assets = {
transConfigs: [],
transTypeValues: [],
Expand All @@ -8,15 +10,21 @@ class AssetUtils {

for (const p in assetPlugins) {
const currAsset = assetPlugins[p]
console.log('a', a)

console.log('currAsset.........: ', currAsset) // @ddn/asset-evidence/.ddnrc.js
// console.log("currAsset.........: ", require.resolve(currAsset)); // @ddn/asset-evidence/.ddnrc.js
if (currAsset) {
let assetConfig
try {
assetConfig = require(`${currAsset}/.ddnrc.js`)
} catch (error) {
// console.log(`The asset extends error: ${currAsset} has no configure .ddnrc.js.`)
throw new Error(`The asset extends error: ${currAsset} has no configure .ddnrc.js.`)
}

const assetTransactions = assetConfig.transactions
console.log('assetTransactions.........: ', assetTransactions)

if (assetTransactions && assetTransactions.length > 0) {
assetTransactions.forEach(currTrans => {
Expand Down Expand Up @@ -95,6 +103,7 @@ class AssetUtils {

for (const p in assetPluginsJson) {
const currAsset = assetPluginsJson[p]

if (currAsset) {
const assetTransactions = currAsset.transactions

Expand Down Expand Up @@ -129,9 +138,10 @@ class AssetUtils {
return this
}

static loadFromFile (file) {
const assetPlugins = require(file)
return this.loadFromObject(assetPlugins)
// fixme: 该方法未使用 imfly 2024.7.26
static async loadFromFile (file) {
const assetPlugins = await import(file)
return await this.loadFromObject(assetPlugins)
}

static getTypeValue (typeName) {
Expand Down
5 changes: 3 additions & 2 deletions packages/asset-dapp/src/utils/router.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const extend = require('extend')
import extend from 'extend'
import express from 'express'

function map (root, config) {
const router = this
Expand Down Expand Up @@ -29,7 +30,7 @@ function map (root, config) {
* @returns {*}
*/
const Router = function () {
const router = require('express').Router()
const router = express.Router()

// router.use(function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
Expand Down
12 changes: 6 additions & 6 deletions packages/asset-evidence/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
"name": "@ddn/asset-evidence",
"version": "2.4.3",
"description": "DDN evidence",
"main": "./dist/index.js",
"types": "dist/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/ddnlink/ddn.git",
Expand All @@ -13,16 +11,18 @@
"bugs": {
"url": "http://github.com/ddnlink/ddn/issues"
},
"files": [
"dist",
".ddnrc.js"
],
"author": "wangxm",
"license": "AGPL 3.0",
"scripts": {
"build": "father build",
"dev": "father dev"
},
"main": "./dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
".ddnrc.js"
],
"dependencies": {
"@ddn/asset-base": "workspace:*",
"@ddn/utils": "workspace:*",
Expand Down
14 changes: 4 additions & 10 deletions packages/core/src/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import signale from 'signale'
import marked from 'marked'
import TerminalRenderer from 'marked-terminal'
import { existsSync, writeFileSync } from 'fs'
// 支持内部框架扩展 error code map
import ERROR_CODE_MAP from '@umijs/error-code-map'
import osLocale from 'os-locale'

marked.setOptions({
renderer: new TerminalRenderer()
})

// 支持内部框架扩展 error code map
const ERROR_CODE_MAP = require(process.env.ERROR_CODE_MAP_PATH || '@umijs/error-code-map')

export class DdnError extends Error {
constructor (opts, ...params) {
const { message, code, context } = opts
Expand Down Expand Up @@ -53,7 +53,6 @@ export function printDdnError (e, opts = {}) {
console.error(`\n${chalk.bgRed.black(' ERROR ')} ${chalk.red(e.message || message)}`)
}

const osLocale = require('os-locale')
const lang = osLocale.sync()

if (lang === 'zh-CN') {
Expand All @@ -63,12 +62,7 @@ export function printDdnError (e, opts = {}) {
}

if (!detailsOnly && e.stack) {
console.error(
`${chalk.bgRed.black(' STACK ')}\n\n${e.stack
.split('\n')
.slice(1)
.join('\n')}`
)
console.error(`${chalk.bgRed.black(' STACK ')}\n\n${e.stack.split('\n').slice(1).join('\n')}`)
}

// 将错误信息输出到文件
Expand Down
20 changes: 10 additions & 10 deletions packages/core/src/getUserConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ function defaultOnError (e) {
console.error(e)
}

export function requireFile (f, opts = {}) {
export async function requireFile (f, opts = {}) {
if (!existsSync(f)) {
return {}
}

const { onError = defaultOnError } = opts
let ret = {}
try {
ret = require(f) || {} // eslint-disable-line
ret = (await import(f)) || {} // eslint-disable-line
} catch (e) {
onError(e, f)
}
Expand All @@ -50,7 +50,7 @@ export function mergeConfigs (...configs) {
return extend(true, ...configs)
}

export function getConfigByConfigFile (configFile, opts = {}) {
export async function getConfigByConfigFile (configFile, opts = {}) {
const ddnEnv = process.env.DDN_ENV
const isDev = process.env.NODE_ENV === 'development'
const { defaultConfig, onError } = opts
Expand All @@ -63,11 +63,11 @@ export function getConfigByConfigFile (configFile, opts = {}) {
*/
const configs = [
defaultConfig,
requireFile(configFile, requireOpts),
ddnEnv && requireFile(addAffix(configFile, ddnEnv), requireOpts),
isDev && requireFile(addAffix(configFile, 'testnet'), requireOpts),
isDev && requireFile(addAffix(configFile, 'local'), requireOpts),
!isDev && requireFile(addAffix(configFile, 'mainnet'), requireOpts)
await requireFile(configFile, requireOpts),
ddnEnv && (await requireFile(addAffix(configFile, ddnEnv), requireOpts)),
isDev && (await requireFile(addAffix(configFile, 'testnet'), requireOpts)),
isDev && (await requireFile(addAffix(configFile, 'local'), requireOpts)),
!isDev && (await requireFile(addAffix(configFile, 'mainnet'), requireOpts))
]

return mergeConfigs(...configs)
Expand Down Expand Up @@ -106,12 +106,12 @@ export function cleanConfigRequireCache (cwd) {
* 主配置文件而生效。
* @param opts {cwd: cwd, defaultConfig: config.default.js }
*/
export function getUserConfig (opts = {}) {
export async function getUserConfig (opts = {}) {
const { cwd, defaultConfig } = opts
const absConfigFile = getConfigFile(cwd)

if (absConfigFile) {
return getConfigByConfigFile(absConfigFile, {
return await getConfigByConfigFile(absConfigFile, {
defaultConfig
})
} else {
Expand Down
Loading

0 comments on commit 7c2d5ca

Please sign in to comment.