@xrystal/core 3.32.1 → 3.37.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +651 -136
- package/package.json +27 -24
- package/tsconfig.base.json +15 -0
- package/x/bin/commands/create.mjs +34 -5
- package/x/bin/commands/doctor.mjs +115 -25
- package/x/bin/commands/hooks.mjs +55 -0
- package/x/bin/commands/project.mjs +75 -42
- package/x/bin/commands/release.mjs +8 -3
- package/x/bin/commands/sync-toolchain.mjs +43 -0
- package/x/bin/commands/tmp.mjs +13 -4
- package/x/bin/helpers/.generated/.generated-from +1 -0
- package/x/bin/helpers/.generated/tmp-schema.mjs +192 -0
- package/x/bin/helpers/banner.mjs +66 -12
- package/x/bin/helpers/build-config.mjs +342 -0
- package/x/bin/helpers/cli-help.mjs +164 -0
- package/x/bin/helpers/create-target.mjs +18 -2
- package/x/bin/helpers/project-artifacts.mjs +140 -0
- package/x/bin/helpers/runtime-info.mjs +172 -0
- package/x/bin/helpers/tmp-config.mjs +11 -10
- package/x/bin/helpers/tmp-layout.mjs +10 -16
- package/x/bin/helpers/tmp-schema.mjs +9 -0
- package/x/bin/helpers/toolchain-config.mjs +233 -0
- package/x/bin/main-cli.js +31 -3
- package/x/bin/scripts/clean-source-types.mjs +19 -0
- package/x/bin/scripts/fix-dist-imports.mjs +80 -0
- package/x/bin/scripts/install-git-hooks.mjs +86 -0
- package/x/bin/scripts/minify-dist.mjs +50 -0
- package/x/bin/scripts/prepare-npm-publish.mjs +49 -0
- package/x/bin/scripts/unpublish-leaked-versions.mjs +62 -0
- package/x/bin/scripts/verify-npm-pack.mjs +45 -0
- package/x/bin/scripts/verify-version-bump.mjs +27 -0
- package/x/bin/scripts/version-check.mjs +173 -0
- package/x/dist/index.d.ts +3 -0
- package/x/dist/index.js +1 -0
- package/x/dist/loader/clients/index.js +1 -0
- package/x/dist/loader/configs/index.js +1 -0
- package/{source → x/dist}/loader/controller/index.d.ts +20 -17
- package/x/dist/loader/controller/index.js +1 -0
- package/x/dist/loader/dto/index.js +1 -0
- package/x/dist/loader/events/index.js +1 -0
- package/x/dist/loader/index.d.ts +11 -0
- package/x/dist/loader/index.js +1 -0
- package/{source → x/dist}/loader/kafka/index.d.ts +1 -0
- package/x/dist/loader/kafka/index.js +1 -0
- package/x/dist/loader/localizations/index.js +1 -0
- package/{source → x/dist}/loader/logger/index.d.ts +1 -0
- package/x/dist/loader/logger/index.js +2 -0
- package/x/dist/loader/service/index.js +1 -0
- package/x/dist/loader/system/index.js +1 -0
- package/x/dist/project/index.js +1 -0
- package/x/dist/utils/constants/defaults.json +44 -0
- package/x/dist/utils/constants/index.js +1 -0
- package/x/dist/utils/helpers/configs/index.js +1 -0
- package/x/dist/utils/helpers/context/controller-store.js +1 -0
- package/x/dist/utils/helpers/context/index.js +1 -0
- package/{source → x/dist}/utils/helpers/core/index.d.ts +1 -1
- package/x/dist/utils/helpers/core/index.js +1 -0
- package/x/dist/utils/helpers/core/paths.js +1 -0
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -0
- package/x/dist/utils/helpers/date/index.js +1 -0
- package/x/dist/utils/helpers/dispatch/index.js +1 -0
- package/x/dist/utils/helpers/dto/index.js +1 -0
- package/x/dist/utils/helpers/filters/index.js +1 -0
- package/x/dist/utils/helpers/framework/index.js +1 -0
- package/x/dist/utils/helpers/handlers/adapters.js +1 -0
- package/x/dist/utils/helpers/handlers/execute.js +1 -0
- package/x/dist/utils/helpers/handlers/index.js +1 -0
- package/x/dist/utils/helpers/hash/crypto.js +1 -0
- package/x/dist/utils/helpers/id/index.js +1 -0
- package/x/dist/utils/helpers/index.js +1 -0
- package/x/dist/utils/helpers/ip/index.js +1 -0
- package/x/dist/utils/helpers/is/index.js +1 -0
- package/x/dist/utils/helpers/locales/index.js +1 -0
- package/x/dist/utils/helpers/math/index.js +1 -0
- package/{source → x/dist}/utils/helpers/middleware/index.d.ts +2 -2
- package/x/dist/utils/helpers/middleware/index.js +1 -0
- package/x/dist/utils/helpers/objects/index.js +1 -0
- package/x/dist/utils/helpers/path/index.js +1 -0
- package/{source → x/dist}/utils/helpers/protocol/index.d.ts +2 -10
- package/x/dist/utils/helpers/protocol/index.js +1 -0
- package/x/dist/utils/helpers/protocol/options.js +1 -0
- package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +1 -0
- package/x/dist/utils/helpers/runtime/dto-access.js +1 -0
- package/x/dist/utils/helpers/runtime/dto-types.js +1 -0
- package/{source → x/dist}/utils/helpers/runtime/index.d.ts +1 -0
- package/x/dist/utils/helpers/runtime/index.js +1 -0
- package/x/dist/utils/helpers/runtime/shutdown.d.ts +3 -0
- package/x/dist/utils/helpers/runtime/shutdown.js +1 -0
- package/x/dist/utils/helpers/state/index.js +1 -0
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -0
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -0
- package/x/dist/utils/helpers/state/scopes.js +1 -0
- package/x/dist/utils/helpers/string/index.js +1 -0
- package/x/dist/utils/helpers/tests/tmp-schema.test.js +1 -0
- package/x/dist/utils/helpers/tests/tmp-watch.test.js +1 -0
- package/x/dist/utils/helpers/timer/index.js +1 -0
- package/x/dist/utils/helpers/tmp/index.d.ts +5 -0
- package/x/dist/utils/helpers/tmp/index.js +1 -0
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -0
- package/{source → x/dist}/utils/helpers/tmp/runtime-tmp.d.ts +2 -6
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -0
- package/{source → x/dist}/utils/helpers/tmp/tmp-loader.d.ts +1 -0
- package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +47 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-watch.d.ts +1 -0
- package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -0
- package/x/dist/utils/helpers/validates/index.js +1 -0
- package/x/dist/utils/index.js +1 -0
- package/x/dist/utils/models/classes/class.clients.js +1 -0
- package/x/dist/utils/models/classes/class.interfaces.js +1 -0
- package/x/dist/utils/models/classes/class.service-locator.js +1 -0
- package/{source → x/dist}/utils/models/classes/class.tmp-file-loader.d.ts +3 -2
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -0
- package/x/dist/utils/models/classes/class.x.js +1 -0
- package/x/dist/utils/models/enums/index.js +1 -0
- package/x/dist/utils/models/index.js +1 -0
- package/x/dist/utils/models/types/index.js +1 -0
- package/x/dist/utils/package-root.js +1 -0
- package/x/tmp.yml +51 -42
- package/source/index.js +0 -11
- package/source/loader/clients/index.js +0 -22
- package/source/loader/configs/index.js +0 -88
- package/source/loader/controller/index.js +0 -236
- package/source/loader/dto/index.js +0 -92
- package/source/loader/events/index.js +0 -44
- package/source/loader/index.d.ts +0 -11
- package/source/loader/index.js +0 -11
- package/source/loader/kafka/index.js +0 -137
- package/source/loader/localizations/index.js +0 -46
- package/source/loader/logger/index.js +0 -217
- package/source/loader/service/index.js +0 -7
- package/source/loader/system/index.js +0 -25
- package/source/project/index.js +0 -70
- package/source/utils/constants/defaults.json +0 -15
- package/source/utils/constants/defaults.mjs +0 -10
- package/source/utils/constants/index.js +0 -22
- package/source/utils/helpers/configs/index.js +0 -1
- package/source/utils/helpers/context/controller-store.js +0 -12
- package/source/utils/helpers/context/index.js +0 -24
- package/source/utils/helpers/core/index.js +0 -58
- package/source/utils/helpers/core/paths.js +0 -78
- package/source/utils/helpers/core/tmp-layout.js +0 -241
- package/source/utils/helpers/date/index.js +0 -48
- package/source/utils/helpers/dispatch/index.js +0 -53
- package/source/utils/helpers/dto/index.js +0 -10
- package/source/utils/helpers/filters/index.js +0 -44
- package/source/utils/helpers/framework/index.js +0 -17
- package/source/utils/helpers/handlers/adapters.js +0 -40
- package/source/utils/helpers/handlers/execute.js +0 -82
- package/source/utils/helpers/handlers/index.js +0 -31
- package/source/utils/helpers/hash/crypto.js +0 -22
- package/source/utils/helpers/id/index.js +0 -24
- package/source/utils/helpers/index.js +0 -26
- package/source/utils/helpers/ip/index.js +0 -21
- package/source/utils/helpers/is/index.js +0 -35
- package/source/utils/helpers/locales/index.js +0 -82
- package/source/utils/helpers/math/index.js +0 -14
- package/source/utils/helpers/middleware/index.js +0 -36
- package/source/utils/helpers/objects/index.js +0 -55
- package/source/utils/helpers/path/index.js +0 -4
- package/source/utils/helpers/protocol/index.js +0 -99
- package/source/utils/helpers/protocol/options.js +0 -13
- package/source/utils/helpers/regex/checkSpecialRegexControl.js +0 -3
- package/source/utils/helpers/runtime/dto-access.js +0 -5
- package/source/utils/helpers/runtime/index.js +0 -1
- package/source/utils/helpers/state/index.js +0 -185
- package/source/utils/helpers/state/props-from-tmp.js +0 -44
- package/source/utils/helpers/state/request-key-guard.js +0 -42
- package/source/utils/helpers/state/scopes.js +0 -69
- package/source/utils/helpers/string/index.js +0 -9
- package/source/utils/helpers/timer/index.js +0 -5
- package/source/utils/helpers/tmp/index.d.ts +0 -3
- package/source/utils/helpers/tmp/index.js +0 -3
- package/source/utils/helpers/tmp/loader-tmp-sync.js +0 -13
- package/source/utils/helpers/tmp/runtime-tmp.js +0 -30
- package/source/utils/helpers/tmp/tmp-loader.js +0 -48
- package/source/utils/helpers/validates/index.js +0 -20
- package/source/utils/index.js +0 -3
- package/source/utils/models/classes/class.clients.js +0 -142
- package/source/utils/models/classes/class.interfaces.js +0 -10
- package/source/utils/models/classes/class.service-locator.js +0 -16
- package/source/utils/models/classes/class.tmp-file-loader.js +0 -38
- package/source/utils/models/classes/class.x.js +0 -180
- package/source/utils/models/enums/index.js +0 -148
- package/source/utils/models/index.js +0 -9
- package/source/utils/models/types/index.js +0 -2
- package/source/utils/models/types/shims.d.ts +0 -123
- package/source/utils/package-root.js +0 -5
- package/x/tests/cli.test.ts +0 -85
- package/x/tests/context.test.ts +0 -25
- package/x/tests/dispatch.test.ts +0 -84
- package/x/tests/fixtures/locales/en/translation.json +0 -8
- package/x/tests/fixtures/locales/tr/translation.json +0 -8
- package/x/tests/frameworks.integration.test.ts +0 -185
- package/x/tests/helpers/i18n-setup.ts +0 -52
- package/x/tests/helpers/middleware.ts +0 -23
- package/x/tests/helpers/register-test-dto.ts +0 -52
- package/x/tests/i18n.integration.test.ts +0 -77
- package/x/tests/i18n.test.ts +0 -96
- package/x/tests/middleware.test.ts +0 -83
- package/x/tests/project-layout.test.ts +0 -65
- package/x/tests/protocol.test.ts +0 -75
- package/x/tests/realtime.examples.test.ts +0 -198
- package/x/tests/runtime-tmp.test.ts +0 -49
- package/x/tests/socket.integration.test.ts +0 -174
- package/x/tests/state.test.ts +0 -183
- package/x/tests/tmp-layout-guard.test.ts +0 -40
- /package/{source → x/dist}/loader/clients/index.d.ts +0 -0
- /package/{source → x/dist}/loader/configs/index.d.ts +0 -0
- /package/{source → x/dist}/loader/dto/index.d.ts +0 -0
- /package/{source → x/dist}/loader/events/index.d.ts +0 -0
- /package/{source → x/dist}/loader/localizations/index.d.ts +0 -0
- /package/{source → x/dist}/loader/service/index.d.ts +0 -0
- /package/{source → x/dist}/loader/system/index.d.ts +0 -0
- /package/{source → x/dist}/project/index.d.ts +0 -0
- /package/{source → x/dist}/utils/constants/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/configs/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/context/controller-store.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/context/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/core/paths.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/core/tmp-layout.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/date/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/dispatch/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/dto/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/filters/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/framework/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/adapters.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/execute.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/handlers/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/hash/crypto.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/id/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/ip/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/is/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/locales/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/math/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/objects/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/path/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/protocol/options.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/regex/checkSpecialRegexControl.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/runtime/dto-access.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/runtime/dto-types.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/props-from-tmp.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/request-key-guard.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/state/scopes.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/string/index.d.ts +0 -0
- /package/{source/index.d.ts → x/dist/utils/helpers/tests/tmp-schema.test.d.ts} +0 -0
- /package/{source/utils/helpers/runtime/dto-types.js → x/dist/utils/helpers/tests/tmp-watch.test.d.ts} +0 -0
- /package/{source → x/dist}/utils/helpers/timer/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/tmp/loader-tmp-sync.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/validates/index.d.ts +0 -0
- /package/{source → x/dist}/utils/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.clients.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.interfaces.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.service-locator.d.ts +0 -0
- /package/{source → x/dist}/utils/models/classes/class.x.d.ts +0 -0
- /package/{source → x/dist}/utils/models/enums/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/index.d.ts +0 -0
- /package/{source → x/dist}/utils/models/types/index.d.ts +0 -0
- /package/{source → x/dist}/utils/package-root.d.ts +0 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
|
|
6
|
+
import { resolveProjectRoot } from '../helpers/project-root.mjs'
|
|
7
|
+
|
|
8
|
+
const verifyScriptPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'verify-version-bump.mjs')
|
|
9
|
+
const HOOK_MARKER = '@xrystal/core version-bump pre-commit'
|
|
10
|
+
|
|
11
|
+
export function resolveVerifyScriptPath() {
|
|
12
|
+
return verifyScriptPath
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isGitHookInstalled(root = resolveProjectRoot()) {
|
|
16
|
+
const hookPath = path.join(root, '.git', 'hooks', 'pre-commit')
|
|
17
|
+
if (!fs.existsSync(hookPath)) return false
|
|
18
|
+
return fs.readFileSync(hookPath, 'utf8').includes(HOOK_MARKER)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Install pre-commit into .git/hooks (core repo + services). No .githooks folder. */
|
|
22
|
+
export function installGitHooks(root = resolveProjectRoot()) {
|
|
23
|
+
const gitDir = path.join(root, '.git')
|
|
24
|
+
if (!fs.existsSync(gitDir)) {
|
|
25
|
+
throw new Error('Not a git repository. Run git init first.')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
execSync('git config --unset core.hooksPath', { cwd: root, stdio: 'ignore' })
|
|
30
|
+
} catch {
|
|
31
|
+
// already unset
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const hooksDir = path.join(gitDir, 'hooks')
|
|
35
|
+
fs.mkdirSync(hooksDir, { recursive: true })
|
|
36
|
+
|
|
37
|
+
const hookPath = path.join(hooksDir, 'pre-commit')
|
|
38
|
+
const nodeBin = process.execPath
|
|
39
|
+
const scriptPath = resolveVerifyScriptPath()
|
|
40
|
+
|
|
41
|
+
const content = `#!/bin/sh
|
|
42
|
+
# ${HOOK_MARKER}
|
|
43
|
+
set -e
|
|
44
|
+
"${nodeBin}" "${scriptPath}" --staged
|
|
45
|
+
`
|
|
46
|
+
|
|
47
|
+
fs.writeFileSync(hookPath, content, { mode: 0o755 })
|
|
48
|
+
|
|
49
|
+
return { root, hookPath, scriptPath }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
export function ensureHooksInstallScript(projectRoot, cliName = 'xcore') {
|
|
54
|
+
const packageJsonPath = path.join(projectRoot, 'package.json')
|
|
55
|
+
if (!fs.existsSync(packageJsonPath)) return false
|
|
56
|
+
|
|
57
|
+
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
|
|
58
|
+
pkg.scripts = pkg.scripts ?? {}
|
|
59
|
+
const script = `${cliName} hooks install`
|
|
60
|
+
if (pkg.scripts['hooks:install'] === script) return false
|
|
61
|
+
|
|
62
|
+
pkg.scripts['hooks:install'] = script
|
|
63
|
+
fs.writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 4)}
|
|
64
|
+
`)
|
|
65
|
+
return true
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Install pre-commit hook + package.json hooks:install script (create + manual). */
|
|
69
|
+
export function setupProjectGitHooks(projectRoot, { cliName = 'xcore' } = {}) {
|
|
70
|
+
ensureHooksInstallScript(projectRoot, cliName)
|
|
71
|
+
const refreshed = isGitHookInstalled(projectRoot)
|
|
72
|
+
const result = installGitHooks(projectRoot)
|
|
73
|
+
return { ...result, refreshed }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
|
77
|
+
|
|
78
|
+
if (isMain) {
|
|
79
|
+
try {
|
|
80
|
+
const result = installGitHooks()
|
|
81
|
+
console.log(`✓ pre-commit hook installed → ${result.hookPath}`)
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.error(`✗ ${error.message}`)
|
|
84
|
+
process.exit(1)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const distRoot = path.join(process.cwd(), 'x', 'dist')
|
|
6
|
+
|
|
7
|
+
function walkJsFiles(dir, out = []) {
|
|
8
|
+
for (const name of fs.readdirSync(dir)) {
|
|
9
|
+
const abs = path.join(dir, name)
|
|
10
|
+
const stat = fs.statSync(abs)
|
|
11
|
+
if (stat.isDirectory()) {
|
|
12
|
+
walkJsFiles(abs, out)
|
|
13
|
+
continue
|
|
14
|
+
}
|
|
15
|
+
if (name.endsWith('.js')) out.push(abs)
|
|
16
|
+
}
|
|
17
|
+
return out
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function minifyDistFile(file) {
|
|
21
|
+
const result = spawnSync(
|
|
22
|
+
'bun',
|
|
23
|
+
['build', file, '--outfile', file, '--minify', '--no-bundle', '--external', '*'],
|
|
24
|
+
{ stdio: 'pipe', encoding: 'utf8' },
|
|
25
|
+
)
|
|
26
|
+
if (result.status !== 0) {
|
|
27
|
+
const detail = (result.stderr || result.stdout || '').trim()
|
|
28
|
+
throw new Error(`minify failed for ${file}: ${detail || `exit ${result.status}`}`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function minifyDist(distDir = distRoot) {
|
|
33
|
+
if (!fs.existsSync(distDir)) {
|
|
34
|
+
throw new Error(`dist directory not found: ${distDir}`)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const files = walkJsFiles(distDir)
|
|
38
|
+
for (const file of files) {
|
|
39
|
+
minifyDistFile(file)
|
|
40
|
+
}
|
|
41
|
+
return { jsFileCount: files.length }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const invoked = process.argv[1] ? path.resolve(process.argv[1]) : ''
|
|
45
|
+
const isMain = invoked.endsWith(`${path.sep}minify-dist.mjs`)
|
|
46
|
+
|
|
47
|
+
if (isMain) {
|
|
48
|
+
const result = minifyDist()
|
|
49
|
+
console.log(`minify-dist: minified ${result.jsFileCount} file(s)`)
|
|
50
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const root = process.cwd()
|
|
6
|
+
|
|
7
|
+
const pathsToRemove = [
|
|
8
|
+
'source',
|
|
9
|
+
'x/tests',
|
|
10
|
+
'.github',
|
|
11
|
+
'.vscode',
|
|
12
|
+
'x/logs',
|
|
13
|
+
'x/docker',
|
|
14
|
+
'tsconfig.json',
|
|
15
|
+
'eslint.config.js',
|
|
16
|
+
'.gitignore',
|
|
17
|
+
'.babelrc',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
for (const rel of pathsToRemove) {
|
|
21
|
+
const abs = path.join(root, rel)
|
|
22
|
+
if (!fs.existsSync(abs)) continue
|
|
23
|
+
fs.rmSync(abs, { recursive: true, force: true })
|
|
24
|
+
console.log(`prepare-npm-publish: removed ${rel}`)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const distJs = []
|
|
28
|
+
function countDistJs(dir) {
|
|
29
|
+
for (const name of fs.readdirSync(dir)) {
|
|
30
|
+
const abs = path.join(dir, name)
|
|
31
|
+
const stat = fs.statSync(abs)
|
|
32
|
+
if (stat.isDirectory()) countDistJs(abs)
|
|
33
|
+
else if (name.endsWith('.js')) distJs.push(abs)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const distDir = path.join(root, 'x', 'dist')
|
|
38
|
+
if (!fs.existsSync(distDir)) {
|
|
39
|
+
console.error('prepare-npm-publish: x/dist missing — run build first')
|
|
40
|
+
process.exit(1)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
countDistJs(distDir)
|
|
44
|
+
if (distJs.length < 10) {
|
|
45
|
+
console.error(`prepare-npm-publish: expected full dist tree, found ${distJs.length} .js file(s)`)
|
|
46
|
+
process.exit(1)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
console.log(`prepare-npm-publish: ready (${distJs.length} .js in x/dist, no source/)`)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ONE-TIME cleanup: remove npm versions that shipped source/ in the tarball.
|
|
4
|
+
* Remove this script + the workflow step after leaked versions are gone.
|
|
5
|
+
*/
|
|
6
|
+
import { execSync } from 'node:child_process'
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
|
|
10
|
+
const pkgName = '@xrystal/core'
|
|
11
|
+
const root = process.cwd()
|
|
12
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
|
|
13
|
+
const publishingVersion = pkg.version
|
|
14
|
+
|
|
15
|
+
function run(cmd) {
|
|
16
|
+
return execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function resolveVersionsToUnpublish() {
|
|
20
|
+
const fromEnv = process.env.UNPUBLISH_VERSIONS?.trim()
|
|
21
|
+
if (fromEnv) {
|
|
22
|
+
return fromEnv.split(',').map((v) => v.trim()).filter(Boolean)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let published = []
|
|
26
|
+
try {
|
|
27
|
+
const raw = run(`npm view ${pkgName} versions --json`)
|
|
28
|
+
published = JSON.parse(raw)
|
|
29
|
+
if (!Array.isArray(published)) published = [published]
|
|
30
|
+
} catch {
|
|
31
|
+
console.log('unpublish-leaked: no published versions found on registry')
|
|
32
|
+
return []
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return published
|
|
36
|
+
.filter((v) => v !== publishingVersion)
|
|
37
|
+
.slice(-3)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const versions = resolveVersionsToUnpublish()
|
|
41
|
+
if (versions.length === 0) {
|
|
42
|
+
console.log('unpublish-leaked: nothing to unpublish')
|
|
43
|
+
process.exit(0)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
console.log(`unpublish-leaked: targeting ${versions.join(', ')} (keeping ${publishingVersion} for publish)`)
|
|
47
|
+
|
|
48
|
+
for (const version of versions) {
|
|
49
|
+
try {
|
|
50
|
+
run(`npm unpublish ${pkgName}@${version} --force`)
|
|
51
|
+
console.log(`unpublish-leaked: ✓ removed ${pkgName}@${version}`)
|
|
52
|
+
} catch (error) {
|
|
53
|
+
const stderr = error.stderr?.toString?.() ?? String(error)
|
|
54
|
+
console.warn(`unpublish-leaked: ⚠ unpublish ${version} failed: ${stderr.split('\n')[0]}`)
|
|
55
|
+
try {
|
|
56
|
+
run(`npm deprecate ${pkgName}@${version} "Removed: shipped source by mistake. Upgrade to a newer release."`)
|
|
57
|
+
console.log(`unpublish-leaked: deprecated ${pkgName}@${version} as fallback`)
|
|
58
|
+
} catch {
|
|
59
|
+
console.warn(`unpublish-leaked: ⚠ deprecate also failed for ${version}`)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execSync } from 'node:child_process'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
|
|
6
|
+
const root = process.cwd()
|
|
7
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
|
|
8
|
+
|
|
9
|
+
function fail(message) {
|
|
10
|
+
console.error(`verify-npm-pack: ✗ ${message}`)
|
|
11
|
+
process.exit(1)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (fs.existsSync(path.join(root, 'source'))) {
|
|
15
|
+
fail('source/ still exists on disk — run prepare-npm-publish.mjs first')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const files = Array.isArray(pkg.files) ? pkg.files : []
|
|
19
|
+
if (files.some((entry) => {
|
|
20
|
+
const normalized = String(entry).replace(/^\.\//, '')
|
|
21
|
+
return normalized === 'source' || normalized.startsWith('source/')
|
|
22
|
+
})) {
|
|
23
|
+
fail('package.json files must not include source/')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (!files.some((entry) => String(entry).replace(/^\.\//, '').includes('dist'))) {
|
|
27
|
+
fail('package.json files must include x/dist')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const dryRun = execSync('npm pack --dry-run 2>&1', { cwd: root, encoding: 'utf8' })
|
|
31
|
+
|
|
32
|
+
if (/source\/.*\.ts/.test(dryRun) || /npm notice.*source\//.test(dryRun)) {
|
|
33
|
+
fail('npm pack tarball lists source/ — TypeScript source must not ship')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (!/x\/dist\/.*\.js/.test(dryRun)) {
|
|
37
|
+
fail('npm pack tarball must include x/dist/**/*.js')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!fs.existsSync(path.join(root, 'x/dist/index.js'))) {
|
|
41
|
+
fail('x/dist/index.js missing')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
console.log('verify-npm-pack: ✓ no source/ in package')
|
|
45
|
+
console.log('verify-npm-pack: ✓ x/dist runtime present')
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
assertVersionBumpForStagedCommit,
|
|
6
|
+
assertVersionBumpForTag,
|
|
7
|
+
getProjectRoot,
|
|
8
|
+
} from './version-check.mjs'
|
|
9
|
+
|
|
10
|
+
const mode = process.argv.includes('--staged') ? 'staged' : process.argv.includes('--tag') ? 'tag' : 'staged'
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const root = getProjectRoot()
|
|
14
|
+
if (mode === 'tag') {
|
|
15
|
+
assertVersionBumpForTag(root)
|
|
16
|
+
} else {
|
|
17
|
+
assertVersionBumpForStagedCommit(root)
|
|
18
|
+
}
|
|
19
|
+
} catch (error) {
|
|
20
|
+
console.error(`\n✗ ${error.message}\n`)
|
|
21
|
+
process.exit(1)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
|
25
|
+
if (isMain) {
|
|
26
|
+
// success is silent for hooks
|
|
27
|
+
}
|
|
@@ -66,6 +66,178 @@ export function getVersionState(ref = 'HEAD', root = getProjectRoot()) {
|
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
|
|
70
|
+
export function parseSemver(version) {
|
|
71
|
+
const match = String(version).trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?(?:\+[0-9A-Za-z-.]+)?$/)
|
|
72
|
+
if (!match) return null
|
|
73
|
+
return {
|
|
74
|
+
major: Number(match[1]),
|
|
75
|
+
minor: Number(match[2]),
|
|
76
|
+
patch: Number(match[3]),
|
|
77
|
+
prerelease: match[4] ?? null,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @returns {-1|0|1} */
|
|
82
|
+
export function compareSemver(a, b) {
|
|
83
|
+
const left = parseSemver(a)
|
|
84
|
+
const right = parseSemver(b)
|
|
85
|
+
if (!left || !right) {
|
|
86
|
+
throw new Error(`Cannot compare versions "${a}" and "${b}"`)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
for (const key of ['major', 'minor', 'patch']) {
|
|
90
|
+
if (left[key] > right[key]) return 1
|
|
91
|
+
if (left[key] < right[key]) return -1
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!left.prerelease && !right.prerelease) return 0
|
|
95
|
+
if (!left.prerelease && right.prerelease) return 1
|
|
96
|
+
if (left.prerelease && !right.prerelease) return -1
|
|
97
|
+
if (left.prerelease === right.prerelease) return 0
|
|
98
|
+
return left.prerelease > right.prerelease ? 1 : -1
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function readPackageJsonVersionAtRef(ref, root = getProjectRoot()) {
|
|
102
|
+
try {
|
|
103
|
+
return readCommittedPackageJson(ref, root).version
|
|
104
|
+
} catch {
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function getLatestTagVersion(root = getProjectRoot()) {
|
|
110
|
+
try {
|
|
111
|
+
const tags = run('git tag -l "v*" --sort=-v:refname', { root })
|
|
112
|
+
.split('\n')
|
|
113
|
+
.map((tag) => tag.trim())
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
return tags[0]?.replace(/^v/, '') ?? null
|
|
116
|
+
} catch {
|
|
117
|
+
return null
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function resolveVersionBaseline(root = getProjectRoot()) {
|
|
122
|
+
const latestTag = getLatestTagVersion(root)
|
|
123
|
+
const parentVersion = readPackageJsonVersionAtRef('HEAD~1', root)
|
|
124
|
+
const baselineVersion = latestTag ?? parentVersion
|
|
125
|
+
const baselineLabel = latestTag ? `latest tag v${latestTag}` : 'previous commit'
|
|
126
|
+
return { baselineVersion, baselineLabel, latestTag, parentVersion }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function resolveStagedVersionBaseline(root = getProjectRoot()) {
|
|
130
|
+
const headVersion = readPackageJsonVersionAtRef('HEAD', root)
|
|
131
|
+
const latestTag = getLatestTagVersion(root)
|
|
132
|
+
|
|
133
|
+
if (latestTag && headVersion) {
|
|
134
|
+
const preferTag = compareSemver(latestTag, headVersion) >= 0
|
|
135
|
+
return {
|
|
136
|
+
baselineVersion: preferTag ? latestTag : headVersion,
|
|
137
|
+
baselineLabel: preferTag ? `latest tag v${latestTag}` : 'current HEAD commit',
|
|
138
|
+
latestTag,
|
|
139
|
+
headVersion,
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (latestTag) {
|
|
144
|
+
return { baselineVersion: latestTag, baselineLabel: `latest tag v${latestTag}`, latestTag, headVersion }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
baselineVersion: headVersion,
|
|
149
|
+
baselineLabel: 'current HEAD commit',
|
|
150
|
+
latestTag: null,
|
|
151
|
+
headVersion,
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @returns {{ ok: boolean, baselineVersion: string|null, baselineLabel: string, status: string }} */
|
|
156
|
+
export function evaluateVersionBump(version, ref = 'HEAD', root = getProjectRoot()) {
|
|
157
|
+
const { baselineVersion, baselineLabel, latestTag } = resolveVersionBaseline(root)
|
|
158
|
+
if (!baselineVersion) {
|
|
159
|
+
return { ok: true, baselineVersion: null, baselineLabel: 'first release', status: 'first release' }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
assertVersionFormat(version)
|
|
163
|
+
const cmp = compareSemver(version, baselineVersion)
|
|
164
|
+
|
|
165
|
+
if (cmp > 0) {
|
|
166
|
+
return { ok: true, baselineVersion, baselineLabel, status: `>${baselineVersion}` }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (cmp < 0) {
|
|
170
|
+
return { ok: false, baselineVersion, baselineLabel, status: `<${baselineVersion}` }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (latestTag && version === latestTag) {
|
|
174
|
+
const tag = resolveTagState(version, ref, root)
|
|
175
|
+
if (!tag.pointsToHead) {
|
|
176
|
+
return {
|
|
177
|
+
ok: true,
|
|
178
|
+
baselineVersion,
|
|
179
|
+
baselineLabel,
|
|
180
|
+
status: `=${latestTag} (retag on new commit)`,
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
ok: true,
|
|
185
|
+
baselineVersion,
|
|
186
|
+
baselineLabel,
|
|
187
|
+
status: `=${latestTag} (tag on HEAD)`,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { ok: false, baselineVersion, baselineLabel, status: `=${baselineVersion}` }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function assertVersionIncreased(current, baseline, baselineLabel = 'previous version') {
|
|
195
|
+
assertVersionFormat(current)
|
|
196
|
+
if (!baseline) return
|
|
197
|
+
|
|
198
|
+
assertVersionFormat(baseline)
|
|
199
|
+
const cmp = compareSemver(current, baseline)
|
|
200
|
+
if (cmp <= 0) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`package.json version must be greater than ${baselineLabel} (${baseline}).\n current: ${current}\n required: > ${baseline}`,
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function assertVersionBumpForTag(root = getProjectRoot()) {
|
|
208
|
+
const version = readCommittedPackageJson('HEAD', root).version
|
|
209
|
+
const evaluation = evaluateVersionBump(version, 'HEAD', root)
|
|
210
|
+
if (!evaluation.ok) {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`package.json version must be greater than ${evaluation.baselineLabel} (${evaluation.baselineVersion}).\n current: ${version}\n required: > ${evaluation.baselineVersion}`,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function assertVersionBumpForStagedCommit(root = getProjectRoot()) {
|
|
218
|
+
const stagedDiff = run('git diff --cached --name-only -- package.json', { root })
|
|
219
|
+
if (!stagedDiff.trim()) return
|
|
220
|
+
|
|
221
|
+
let stagedVersion
|
|
222
|
+
try {
|
|
223
|
+
stagedVersion = JSON.parse(run('git show :package.json', { root })).version
|
|
224
|
+
} catch {
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const headVersion = readPackageJsonVersionAtRef('HEAD', root)
|
|
229
|
+
if (stagedVersion === headVersion) return
|
|
230
|
+
|
|
231
|
+
const { baselineVersion, baselineLabel } = resolveStagedVersionBaseline(root)
|
|
232
|
+
if (!baselineVersion) {
|
|
233
|
+
assertVersionFormat(stagedVersion)
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
assertVersionIncreased(stagedVersion, baselineVersion, baselineLabel)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
|
|
69
241
|
export function assertVersionFormat(version) {
|
|
70
242
|
if (!VERSION_PATTERN.test(version)) {
|
|
71
243
|
throw new Error(`Invalid version "${version}". Expected semver (e.g. 3.29.1 or 4.0.0-beta.1).`)
|
|
@@ -124,6 +296,7 @@ export function assertReadyToTag({ requireClean = false, root = getProjectRoot()
|
|
|
124
296
|
}
|
|
125
297
|
|
|
126
298
|
assertVersionFormat(version)
|
|
299
|
+
assertVersionBumpForTag(root)
|
|
127
300
|
|
|
128
301
|
const tag = resolveTagState(version, 'HEAD', root)
|
|
129
302
|
|
package/x/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import r from"./project/index.js";import{ensureCoreTmpEntry as e,isCorePackageRoot as t}from"./utils/helpers/core/tmp-layout.js";import{getTmpSnapshot as a}from"./utils/helpers/tmp/tmp-loader.js";await(async()=>{const o=process.cwd();if(t(o))e(o);a();await r({})})();export{default as coreLoader,core,coreInit}from"./project/index.js";export{ensureCoreTmpEntry,isCorePackageRoot}from"./utils/helpers/core/tmp-layout.js";export{getTmpSnapshot}from"./utils/helpers/tmp/tmp-loader.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BaseApiClient as t,CoreClientsEnum as s}from"../../utils/index.js";import{bindLoaderTmpSync as i}from"../../utils/index.js";export default class Clients{_instances={};#s;constructor({configs:n}){this.#s=n}async onInit(){await this.syncFromTmp();i(this)}syncFromTmp=async()=>{this._instances[s.BASE_API_CLIENT]=new t({clientName:s.BASE_API_CLIENT,baseURL:this.#s.all.baseApiUri||""})};get instances(){return this._instances}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils/index.js";import{Constants as a}from"../../utils/index.js";export default class Configs{publicFolderName=a.publicFolderName;kafkaLogsTopic=a.kafkaLogsTopic;#s;#e;constructor({system:s}){this.#s=s;return new Proxy(this,{get:(o,r)=>{return o[r]||o.config?.[r]}})}onInit=async()=>{await this.syncFromTmp();v(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,o=e.configs.service.loaders.configs.loadPath,r=o.startsWith("@/")?c.join(process.cwd(),o.slice(2)):c.resolve(e.configs.rootFolderPath,o),p=import(l(r).href);this.#e={worker:process.env.WORKER==="true"?!0:!1,mode:process.env.MODE,nodeEnv:"development",debug:process.env.SYSTEM_LOGGER_LAYER??"",https:process.env.HTTPS??"false",httpsfileEncoding:process.env.ENCODING||"utf8",httpsCertfile:process.env.HTTPS_CERT_FILE??"",httpsKeyfile:process.env.HTTPS_KEY_FILE??"",rootFolderPath:e.configs.rootFolderPath||"x",projectName:e.project.name,serviceName:e.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:c.resolve(e.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:e.configs.service.name??"",kafkaBrokers:process.env.KAFKA_BROKERS??"",kafkaUsername:process.env.KAFKA_USERNAME??"",kafkaPassword:process.env.KAFKA_PASSWORD??"",kafkaTopics:[],kafkaLogsTopic:this.kafkaLogsTopic,baseApiUri:process.env.HTTPS==="true"?process.env.SYSTEM_HTTPS_BASE_API_URI??"":process.env.SYSTEM_BASE_API_URI??"",port:Number(process.env.PORT),internalSecret:process.env.INTERNAL_SECRET??"",secret:process.env.SECRET??"",cwd:s,env:"development"};try{const t=await p,f=t?.default||t?.configs||t||{},m=i.mergeWith({},this.#e,f,(n,E)=>{if(i.isArray(n))return n.concat(E)});this.#e=Object.freeze(m)}catch{this.#e=Object.freeze(this.#e)}};setConfig(s){const e=Object.assign(this.#e,s);this.#e=Object.freeze(e)}_(s){return this.#e[s]}get all(){return this.#e}}
|
|
@@ -3,25 +3,28 @@ import Logger from '../../loader/logger';
|
|
|
3
3
|
import System from '../../loader/system';
|
|
4
4
|
import { FrameworkEnum, IProvide, ProtocolEnum, controllerContextStorage, getControllerCtx, type ControllerMetadata, type ControllerStoreContext, type CtrOptions } from '../../utils';
|
|
5
5
|
export type ControllerContext = ControllerStoreContext;
|
|
6
|
-
export
|
|
7
|
-
|
|
6
|
+
export type TranslateFn = (key: string, args?: unknown) => string;
|
|
7
|
+
export type RequestHeaders = Record<string, string | string[] | undefined>;
|
|
8
|
+
export interface CustomRequest<B = unknown, Q = Record<string, unknown>, P = Record<string, unknown>> {
|
|
9
|
+
headers: RequestHeaders;
|
|
8
10
|
method: string;
|
|
9
11
|
url: string;
|
|
10
12
|
body: B;
|
|
11
13
|
params: P;
|
|
12
14
|
query: Q;
|
|
13
|
-
cookies: Record<string,
|
|
15
|
+
cookies: Record<string, unknown>;
|
|
14
16
|
ip: string;
|
|
15
17
|
lang: string;
|
|
16
18
|
requestId: string;
|
|
17
19
|
startTime: number;
|
|
18
|
-
t:
|
|
20
|
+
t: TranslateFn;
|
|
21
|
+
accounts?: unknown;
|
|
19
22
|
}
|
|
20
23
|
export interface CustomResponse {
|
|
21
24
|
builder: Builder;
|
|
22
|
-
locals: Record<string,
|
|
25
|
+
locals: Record<string, unknown>;
|
|
23
26
|
}
|
|
24
|
-
export interface SchemaArgs<B =
|
|
27
|
+
export interface SchemaArgs<B = unknown, Q = Record<string, unknown>, P = Record<string, unknown>> {
|
|
25
28
|
req: CustomRequest<B, Q, P>;
|
|
26
29
|
res: CustomResponse;
|
|
27
30
|
builder: Builder;
|
|
@@ -29,9 +32,9 @@ export interface SchemaArgs<B = any, Q = any, P = any> {
|
|
|
29
32
|
query: Q;
|
|
30
33
|
queries: Q;
|
|
31
34
|
params: P;
|
|
32
|
-
cookies: Record<string,
|
|
33
|
-
locals: Record<string,
|
|
34
|
-
t:
|
|
35
|
+
cookies: Record<string, unknown>;
|
|
36
|
+
locals: Record<string, unknown>;
|
|
37
|
+
t: TranslateFn;
|
|
35
38
|
}
|
|
36
39
|
export { controllerContextStorage, getControllerCtx, type ControllerMetadata };
|
|
37
40
|
export declare const runController: <T>(context: ControllerStoreContext, action: () => T | Promise<T>) => T | Promise<T>;
|
|
@@ -46,21 +49,21 @@ export declare abstract class BaseController {
|
|
|
46
49
|
protected get res(): CustomResponse;
|
|
47
50
|
protected parseRequestBody(): Promise<void>;
|
|
48
51
|
}
|
|
49
|
-
export default abstract class Controller extends BaseController implements IProvide<
|
|
52
|
+
export default abstract class Controller extends BaseController implements IProvide<unknown> {
|
|
50
53
|
onInit(): Promise<void>;
|
|
51
54
|
syncFromTmp: () => void;
|
|
52
|
-
protected parseMessage(msg:
|
|
55
|
+
protected parseMessage(msg: unknown, t: TranslateFn, isError?: boolean): string;
|
|
53
56
|
private args;
|
|
54
57
|
private fail;
|
|
55
58
|
private ok;
|
|
56
|
-
schema<B =
|
|
57
|
-
checks?: (args: SchemaArgs<B, Q, P>) => Promise<
|
|
58
|
-
logic?: (args: SchemaArgs<B, Q, P>) => Promise<
|
|
59
|
+
schema<B = unknown, Q = Record<string, unknown>, P = Record<string, unknown>>({ checks, logic, response }: {
|
|
60
|
+
checks?: (args: SchemaArgs<B, Q, P>) => Promise<unknown>;
|
|
61
|
+
logic?: (args: SchemaArgs<B, Q, P>) => Promise<unknown>;
|
|
59
62
|
response?: (args: SchemaArgs<B, Q, P> & {
|
|
60
|
-
logicResult:
|
|
61
|
-
}) => Promise<
|
|
63
|
+
logicResult: unknown;
|
|
64
|
+
}) => Promise<unknown>;
|
|
62
65
|
}): Promise<ArrayBuffer | Uint8Array<ArrayBufferLike> | Response | Blob | FinalResult>;
|
|
63
|
-
protected ctr<B =
|
|
66
|
+
protected ctr<B = unknown, Q = Record<string, unknown>, P = Record<string, unknown>>(definition: Parameters<Controller['schema']>[0], opts?: FrameworkEnum | CtrOptions): ((req: Request, serverCtx?: Record<string, unknown>) => Promise<unknown>) | ((req: unknown, res: {
|
|
64
67
|
locals?: Record<string, unknown>;
|
|
65
68
|
}, next: (err?: unknown) => void) => void);
|
|
66
69
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import y from"qs";import C from"../../loader/logger/index.js";import S from"../../loader/system/index.js";import{bindLoaderTmpSync as T,getClientIp as E,getConfiguredProtocols as D,isRealtimeProtocol as h,LoggerLayerEnum as O,parseResponseMessage as j,ProtocolEnum as g,x as q,controllerContextStorage,getControllerCtx,runControllerStore as P,adapterBagFromRequest as B,isFetchRequest as I,toHandler as M,toRealtimeHandler as H,resolveCtrOptions as A}from"../../utils/index.js";export{controllerContextStorage,getControllerCtx};export const runController=P;function x(t){return t instanceof Response||t instanceof Blob||t instanceof Uint8Array||t instanceof ArrayBuffer}function l(t){if(!t||typeof t!=="object")return null;return t}function b(t,e){const r=l(e);if(!r)return;if(r.statusCode!==void 0)return void t.httpStatus(Number(r.statusCode));if(r.code!==void 0){const a=Number(r.code);if(a>=100)t.httpStatus(a);else t.code(a)}}function w(t){const e=l(t);if(!e)return{data:void 0,extraData:void 0,message:void 0};const r=l(e.payload);if(r)return{data:r.data!==void 0?r.data:r,extraData:r.extraData,message:e.message};if(e.data!==void 0||e.extraData!==void 0)return{data:e.data,extraData:e.extraData,message:e.message};if(!(e.status!==void 0||e.message!==void 0||e.code!==void 0||e.statusCode!==void 0)&&Object.keys(e).length>0)return{data:e,extraData:void 0,message:e.message};return{data:void 0,extraData:void 0,message:e.message}}function F(t){return t instanceof ReadableStream||typeof t==="object"&&t!==null&&typeof t.getReader==="function"}function R(t){if(Array.isArray(t))return t[0]??"";return t??""}export function resolveBuilder(t){const e=t.ctx?.builder??t.res?.builder??t.socket?.builder;if(e)return e;throw Error("[xrystal] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter")}export class BaseController{system=q.get(S);logger=q.get(C);supportedProtocols=[g.HTTP,g.WEBSOCKET];get store(){return getControllerCtx()}get protocol(){return this.store?.protocol||g.HTTP}get req(){const t=this.store,e=t?.ctx||{},r=t?.req||{},a=I(e.request)?e.request:void 0,o=B(e.request),n=e.headers??r.headers??a?.headers??o?.headers,s=n instanceof Headers?Object.fromEntries(n.entries()):n??{},i=a?.url??o?.url??r.url??e.url??"";let c=t?.metadata?.parsedQuery||e.query||r.query||o?.query||{};if(!Object.keys(c).length&&i.includes("?"))c=y.parse(i.split("?")[1]);let u=e.cookies||r.cookies||o?.cookies||{};const d=s.cookie;if(!Object.keys(u).length&&typeof d==="string")u=Object.fromEntries(d.split(";").map((f)=>{const[m,p]=f.trim().split("=");return[decodeURIComponent(m),decodeURIComponent(p||"")]}));return{url:i,method:(e.method||r.method||a?.method||o?.method||"").toUpperCase(),headers:s,body:t?.metadata?.parsedBody||e.body||r.body||o?.body||{},query:c,params:{...r.params,...e.params,...o?.params,...o?.routeParams},cookies:u,ip:E(r,e),lang:e.lang||r.lang||"en",requestId:t?.requestId??e.requestId??r.ctx?.requestId??String(s["x-request-id"]??s["x-correlation-id"]??""),startTime:e.startTime??r.ctx?.startTime??Date.now(),t:e.t||r.t||((f)=>f),accounts:e.accounts||r.accounts||e.user}}get res(){const t=this.store;if(!t)throw Error("[xrystal] controller context missing");const e=t.metadata?.locals??{};return{builder:resolveBuilder(t),locals:e}}async parseRequestBody(){const t=this.store;if(!t)return;const e=t.ctx?.request,r=t.req||e||t.ctx?.req,a=this.req,o=R(a.headers["content-type"]).toLowerCase(),n=parseInt(R(a.headers["content-length"])||"-1",10);let s=a.body;const i=(d)=>{if(!d)return{};if(o.includes("application/json"))try{return JSON.parse(d)}catch{return d}if(o.includes("application/x-www-form-urlencoded"))return y.parse(d);try{return JSON.parse(d)}catch{try{return y.parse(d)}catch{return d}}},c=F,u=s&&typeof s==="object"&&!c(s)&&Object.keys(s).length>0;if(!h(this.protocol)&&!["GET","HEAD","OPTIONS"].includes(a.method)&&!u){if(r instanceof Request&&(c(s)||n>0))try{s=i(await r.clone().text())}catch{if(typeof s==="string")s=i(s)}else if(r&&typeof r==="object"&&"on"in r&&typeof r.on==="function"&&n!==0){const d=r;s=await new Promise((f)=>{let m="";const p=setTimeout(()=>f({}),200);d.on("data",(k)=>{m+=String(k)});d.on("end",()=>{clearTimeout(p);f(i(m))});d.on("error",()=>{clearTimeout(p);f({})})})}else if(typeof s==="string"&&s.length)s=i(s)}if(typeof FormData<"u"&&s instanceof FormData)s=Object.fromEntries(s.entries());if(!t.metadata)t.metadata={locals:{}};t.metadata.parsedBody=s||{};t.metadata.parsedQuery=a.query}}export default class Controller extends BaseController{async onInit(){await this.syncFromTmp();T(this)}syncFromTmp=()=>{this.supportedProtocols=D()};parseMessage(t,e,r=!1){return j(t,e,r)}args(t){const e=this.req,r=this.store.metadata?.locals??{};return{req:e,res:{builder:t,locals:r},builder:t,body:e.body,query:e.query,queries:e.query,params:e.params,cookies:e.cookies,locals:r,t:e.t}}fail(t,e,r){b(t,e);const{data:a,extraData:o}=w(e),n=l(e),s=this.parseMessage(n?.message??e,r,!0),i=a!==void 0||o!==void 0?{data:a,extraData:o}:void 0;return(a!==void 0?t.as.fail(a,s,i):t.as.fail(s,i)).build()}ok(t,e,r,a){let o="success_process",n=e!==void 0?e:r;if(typeof e==="string"){o=e;n=r}const{data:s,extraData:i,message:c}=w(n);if(typeof c==="string")o=c;b(t,n);return t.as.ok(s,this.parseMessage(o,a,!1),i!==void 0?{extraData:i}:void 0).build()}async schema({checks:t,logic:e,response:r}){const a=resolveBuilder(this.store);try{await this.parseRequestBody();const n=this.args(a);if(t){const u=await t(n);if(u!==!0)return this.fail(a,u,n.req.t)}let s=e?await e(n):{};const i=l(s);if(i&&typeof i.response==="function")s=await i.response();if(x(s))return s;if(i?.status===!1)return this.fail(a,s,n.req.t);const c=r?await r({...n,logicResult:s}):s;if(x(c))return c;return this.ok(a,c,s,n.req.t)}catch(o){const n=o instanceof Error?o.message:String(o);this.logger?.log(O.ERROR,`Controller Error: ${n}`);return a.as.internalServerError(this.parseMessage(n,this.req.t,!0)).build()}}ctr(t,e){const{framework:r,protocol:a}=A(e),o=()=>this.schema(t);if(h(a))return H(o,a);return M(o,r)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from"../../utils/index.js";import{FrameworkEnum as c,parseFramework as f}from"../../utils/index.js";export const DEFAULT_DTO_CONFIG={withDefaultHeaders:!0};function r(t,e){return{...t,...e,codes:e.codes?{...t.codes,...e.codes}:t.codes,defaultHeaders:e.defaultHeaders?{...t.defaultHeaders,...e.defaultHeaders}:t.defaultHeaders,socket:e.socket?{...t.socket,...e.socket}:t.socket,hooks:e.hooks??t.hooks,plugins:e.plugins?[...t.plugins??[],...e.plugins]:t.plugins}}export default class DtoRuntime{_runtime;_system;_config={...DEFAULT_DTO_CONFIG};_framework=c.ELYSIA;_bootConfig={};constructor({system:t}){this._system=t}async onInit(t={}){this._bootConfig=t.config??{};await this.syncFromTmp();m(this)}syncFromTmp=async()=>{this._framework=f(this._system?.tmp?.configs?.service?.framework);this.applyConfig(DEFAULT_DTO_CONFIG,this._system?.tmp?.configs?.service?.loaders?.dto??{},this._bootConfig,{rebuild:!0})};get instance(){return this._runtime}get config(){return this._config}get framework(){return this._framework}configure(t={},e={}){this.applyConfig(this._config,t,e);return this}use(...t){this._runtime.use(...t);this._config=r(this._config,{plugins:t});return this}express(){return this._runtime.express()}elysia(){return this._runtime.elysia()}node(){return this._runtime.node()}websocket(){return this._runtime.websocket()}socketIo(){return this._runtime.socketIo()}attachWebSocket(t,e){return this._runtime.attachWebSocket(t,e)}attachSocketIo(t){return this._runtime.attachSocketIo(t)}fetch(){return this._runtime.fetch()}forRequest(t){return this._runtime.forRequest(t)}applyConfig(...t){const e=t[t.length-1],i=e&&"rebuild"in e?t.pop():{},o=t.reduce((s,n)=>r(s,n),{...DEFAULT_DTO_CONFIG});this._config=o;if(!this._runtime||i.rebuild!==!1)this._runtime=new u(this._config)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LoggerLayerEnum as a,registerGracefulShutdown as s}from"../../utils/index.js";export default class Events{#e;constructor({logger:e}){this.#e=e}onInit=({})=>{this._globalLoader();this._DILoader()};_globalLoader=()=>{process.on("uncaughtException",(e,o)=>{this.#e.log({level:a.CRITICAL,message:`Uncaught Exception: ${e.message}`,payload:{stack:e.stack,origin:o}})});process.on("unhandledRejection",(e,o)=>{const t=e instanceof Error?e:Error(String(e));this.#e.log({level:a.CRITICAL,message:`Unhandled Rejection: ${t.message}`,payload:{stack:t.stack}})})};_DILoader=()=>{s()};get global(){return this._globalLoader()}}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import System from "./system";
|
|
2
|
+
import Configs from "./configs";
|
|
3
|
+
import KafkaForCore from "./kafka";
|
|
4
|
+
import Logger from "./logger";
|
|
5
|
+
import Events from "./events";
|
|
6
|
+
import Localizations from "./localizations";
|
|
7
|
+
import DtoRuntime from "./dto";
|
|
8
|
+
import Controller from "./controller";
|
|
9
|
+
import Service from "./service";
|
|
10
|
+
import Clients from "./clients";
|
|
11
|
+
export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import System from"./system/index.js";import Configs from"./configs/index.js";import KafkaForCore from"./kafka/index.js";import Logger from"./logger/index.js";import Events from"./events/index.js";import Localizations from"./localizations/index.js";import DtoRuntime from"./dto/index.js";import Controller from"./controller/index.js";import Service from"./service/index.js";import Clients from"./clients/index.js";export{System,Configs,Logger,Events,Localizations,DtoRuntime,Controller,Service,Clients,KafkaForCore};
|