@xrystal/core 3.28.3 → 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 +2331 -21
- package/package.json +66 -24
- package/tsconfig.base.json +15 -0
- package/x/bin/commands/create.mjs +136 -0
- package/x/bin/commands/doctor.mjs +149 -0
- package/x/bin/commands/hooks.mjs +55 -0
- package/x/bin/commands/project.mjs +126 -0
- package/x/bin/commands/release.mjs +66 -0
- package/x/bin/commands/sync-toolchain.mjs +43 -0
- package/x/bin/commands/tmp.mjs +57 -0
- package/x/bin/constants/index.mjs +6 -0
- 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 +80 -0
- package/x/bin/helpers/build-config.mjs +342 -0
- package/x/bin/helpers/cli-help.mjs +164 -0
- package/x/bin/helpers/cli-identity.mjs +17 -0
- package/x/bin/helpers/create-target.mjs +35 -0
- package/{bin → x/bin}/helpers/index.mjs +44 -1
- package/x/bin/helpers/project-artifacts.mjs +140 -0
- package/x/bin/helpers/project-root.mjs +70 -0
- package/x/bin/helpers/runtime-info.mjs +172 -0
- package/x/bin/helpers/tmp-config.mjs +67 -0
- package/x/bin/helpers/tmp-layout.mjs +281 -0
- package/x/bin/helpers/tmp-schema.mjs +9 -0
- package/x/bin/helpers/toolchain-config.mjs +233 -0
- package/x/bin/main-cli.js +80 -0
- package/x/bin/paths.mjs +14 -0
- 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/release-prepare.mjs +56 -0
- package/x/bin/scripts/tag.mjs +17 -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 +370 -0
- package/x/dist/index.d.ts +3 -0
- package/x/dist/index.js +1 -0
- package/{source → x/dist}/loader/clients/index.d.ts +2 -1
- package/x/dist/loader/clients/index.js +1 -0
- package/{source → x/dist}/loader/configs/index.d.ts +3 -2
- package/x/dist/loader/configs/index.js +1 -0
- package/x/dist/loader/controller/index.d.ts +69 -0
- package/x/dist/loader/controller/index.js +1 -0
- package/x/dist/loader/dto/index.d.ts +39 -0
- package/x/dist/loader/dto/index.js +1 -0
- package/{source → x/dist}/loader/events/index.d.ts +1 -1
- package/x/dist/loader/events/index.js +1 -0
- package/{source → x/dist}/loader/index.d.ts +2 -1
- package/x/dist/loader/index.js +1 -0
- package/{source → x/dist}/loader/kafka/index.d.ts +6 -3
- package/x/dist/loader/kafka/index.js +1 -0
- package/{source → x/dist}/loader/localizations/index.d.ts +4 -3
- package/x/dist/loader/localizations/index.js +1 -0
- package/{source → x/dist}/loader/logger/index.d.ts +10 -7
- package/x/dist/loader/logger/index.js +2 -0
- package/x/dist/loader/service/index.js +1 -0
- package/{source → x/dist}/loader/system/index.d.ts +4 -3
- package/x/dist/loader/system/index.js +1 -0
- package/{source → x/dist}/project/index.d.ts +2 -2
- package/x/dist/project/index.js +1 -0
- package/x/dist/utils/constants/defaults.json +44 -0
- package/x/dist/utils/constants/index.d.ts +27 -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.d.ts +51 -0
- package/x/dist/utils/helpers/context/controller-store.js +1 -0
- package/x/dist/utils/helpers/context/index.d.ts +18 -0
- package/x/dist/utils/helpers/context/index.js +1 -0
- package/{source → x/dist}/utils/helpers/core/index.d.ts +8 -6
- package/x/dist/utils/helpers/core/index.js +1 -0
- package/x/dist/utils/helpers/core/paths.d.ts +2 -0
- package/x/dist/utils/helpers/core/paths.js +1 -0
- package/x/dist/utils/helpers/core/tmp-layout.d.ts +45 -0
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -0
- package/{source → x/dist}/utils/helpers/date/index.d.ts +1 -1
- package/x/dist/utils/helpers/date/index.js +1 -0
- package/x/dist/utils/helpers/dispatch/index.d.ts +9 -0
- package/x/dist/utils/helpers/dispatch/index.js +1 -0
- package/x/dist/utils/helpers/dto/index.d.ts +10 -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.d.ts +3 -0
- package/x/dist/utils/helpers/framework/index.js +1 -0
- package/x/dist/utils/helpers/handlers/adapters.d.ts +10 -0
- package/x/dist/utils/helpers/handlers/adapters.js +1 -0
- package/x/dist/utils/helpers/handlers/execute.d.ts +5 -0
- package/x/dist/utils/helpers/handlers/execute.js +1 -0
- package/x/dist/utils/helpers/handlers/index.d.ts +18 -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.d.ts +26 -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/{source → x/dist}/utils/helpers/locales/index.d.ts +1 -0
- package/x/dist/utils/helpers/locales/index.js +1 -0
- package/x/dist/utils/helpers/math/index.js +1 -0
- package/x/dist/utils/helpers/middleware/index.d.ts +19 -0
- 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/x/dist/utils/helpers/protocol/index.d.ts +20 -0
- package/x/dist/utils/helpers/protocol/index.js +1 -0
- package/x/dist/utils/helpers/protocol/options.d.ts +6 -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.d.ts +3 -0
- package/x/dist/utils/helpers/runtime/dto-access.js +1 -0
- package/x/dist/utils/helpers/runtime/dto-types.d.ts +19 -0
- package/x/dist/utils/helpers/runtime/dto-types.js +1 -0
- package/x/dist/utils/helpers/runtime/index.d.ts +3 -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.d.ts +59 -0
- package/x/dist/utils/helpers/state/index.js +1 -0
- package/x/dist/utils/helpers/state/props-from-tmp.d.ts +9 -0
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -0
- package/x/dist/utils/helpers/state/request-key-guard.d.ts +3 -0
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -0
- package/x/dist/utils/helpers/state/scopes.d.ts +21 -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/{source/utils/models/types/index.js → x/dist/utils/helpers/tests/tmp-watch.test.d.ts} +0 -1
- 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.d.ts +4 -0
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -0
- package/x/dist/utils/helpers/tmp/runtime-tmp.d.ts +9 -0
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-loader.d.ts +7 -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.d.ts +3 -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/{source → x/dist}/utils/models/enums/index.d.ts +14 -1
- package/x/dist/utils/models/enums/index.js +1 -0
- package/x/dist/utils/models/index.d.ts +9 -0
- package/x/dist/utils/models/index.js +1 -0
- package/x/dist/utils/models/types/index.d.ts +5 -0
- package/x/dist/utils/models/types/index.js +1 -0
- package/x/dist/utils/package-root.d.ts +2 -0
- package/x/dist/utils/package-root.js +1 -0
- package/x/tmp.yml +48 -17
- package/bin/constants/index.mjs +0 -17
- package/bin/main-cli.js +0 -131
- package/source/index.js +0 -6
- package/source/loader/clients/index.js +0 -18
- package/source/loader/configs/index.js +0 -81
- package/source/loader/controller/index.d.ts +0 -129
- package/source/loader/controller/index.js +0 -327
- package/source/loader/events/index.js +0 -44
- package/source/loader/index.js +0 -10
- package/source/loader/kafka/index.js +0 -122
- package/source/loader/localizations/index.js +0 -40
- package/source/loader/logger/index.js +0 -183
- package/source/loader/service/index.js +0 -7
- package/source/loader/system/index.js +0 -19
- package/source/project/index.js +0 -66
- package/source/utils/constants/index.d.ts +0 -10
- package/source/utils/constants/index.js +0 -11
- package/source/utils/helpers/configs/index.js +0 -1
- package/source/utils/helpers/core/index.js +0 -105
- package/source/utils/helpers/date/index.js +0 -48
- package/source/utils/helpers/filters/index.js +0 -44
- package/source/utils/helpers/hash/crypto.js +0 -22
- package/source/utils/helpers/id/index.js +0 -24
- package/source/utils/helpers/index.d.ts +0 -17
- package/source/utils/helpers/index.js +0 -17
- 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 -63
- package/source/utils/helpers/math/index.js +0 -14
- package/source/utils/helpers/middlewares/index.d.ts +0 -1
- package/source/utils/helpers/middlewares/index.js +0 -26
- package/source/utils/helpers/objects/index.js +0 -55
- package/source/utils/helpers/path/index.js +0 -4
- package/source/utils/helpers/regex/checkSpecialRegexControl.js +0 -3
- package/source/utils/helpers/string/index.js +0 -9
- package/source/utils/helpers/timer/index.js +0 -5
- package/source/utils/helpers/validates/index.js +0 -20
- package/source/utils/index.d.ts +0 -3
- package/source/utils/index.js +0 -3
- package/source/utils/models/classes/class.clients.js +0 -142
- package/source/utils/models/classes/class.dtos.d.ts +0 -47
- package/source/utils/models/classes/class.dtos.js +0 -36
- package/source/utils/models/classes/class.interfaces.js +0 -10
- package/source/utils/models/classes/class.response.d.ts +0 -17
- package/source/utils/models/classes/class.response.js +0 -35
- 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 -179
- package/source/utils/models/enums/index.js +0 -133
- package/source/utils/models/index.d.ts +0 -11
- package/source/utils/models/index.js +0 -11
- package/source/utils/models/types/index.d.ts +0 -3
- /package/{source → x/dist}/loader/service/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/configs/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/filters/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/ip/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/is/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/regex/checkSpecialRegexControl.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 → x/dist}/utils/helpers/timer/index.d.ts +0 -0
- /package/{source → x/dist}/utils/helpers/validates/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
|
@@ -0,0 +1,370 @@
|
|
|
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
|
+
import { resolveProjectRoot } from '../helpers/project-root.mjs'
|
|
6
|
+
import { semverVersionPattern } from '../paths.mjs'
|
|
7
|
+
import { runReleasePrepare } from './release-prepare.mjs'
|
|
8
|
+
|
|
9
|
+
export const VERSION_PATTERN = semverVersionPattern
|
|
10
|
+
|
|
11
|
+
export function getProjectRoot(startDir = process.cwd()) {
|
|
12
|
+
return resolveProjectRoot(startDir)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function getPkgPath(root = getProjectRoot()) {
|
|
16
|
+
return path.join(root, 'package.json')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function run(cmd, opts = {}) {
|
|
20
|
+
const root = opts.root ?? getProjectRoot()
|
|
21
|
+
const { inherit = false } = opts
|
|
22
|
+
const result = execSync(cmd, {
|
|
23
|
+
cwd: root,
|
|
24
|
+
encoding: 'utf8',
|
|
25
|
+
stdio: inherit ? 'inherit' : 'pipe',
|
|
26
|
+
})
|
|
27
|
+
if (inherit) return ''
|
|
28
|
+
return String(result ?? '').trim()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function gitTagFromVersion(version) {
|
|
32
|
+
return version.startsWith('v') ? version : `v${version}`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readDiskPackageJson(root = getProjectRoot()) {
|
|
36
|
+
return JSON.parse(fs.readFileSync(getPkgPath(root), 'utf8'))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function readCommittedPackageJson(ref = 'HEAD', root = getProjectRoot()) {
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse(run(`git show ${ref}:package.json`, { root }))
|
|
42
|
+
} catch {
|
|
43
|
+
throw new Error('Could not read package.json from git. Ensure you are in a repo with at least one commit.')
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function getVersionState(ref = 'HEAD', root = getProjectRoot()) {
|
|
48
|
+
const disk = readDiskPackageJson(root)
|
|
49
|
+
const committed = readCommittedPackageJson(ref, root)
|
|
50
|
+
const dirty = run('git status --porcelain', { root })
|
|
51
|
+
const packageJsonDirty = run('git status --porcelain -- package.json', { root })
|
|
52
|
+
const branch = run('git rev-parse --abbrev-ref HEAD', { root })
|
|
53
|
+
const headCommit = run(`git rev-parse ${ref}`, { root })
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
root,
|
|
57
|
+
disk,
|
|
58
|
+
committed,
|
|
59
|
+
dirty,
|
|
60
|
+
packageJsonDirty,
|
|
61
|
+
branch,
|
|
62
|
+
headCommit,
|
|
63
|
+
versionMatch: disk.version === committed.version,
|
|
64
|
+
isClean: dirty.length === 0,
|
|
65
|
+
isPackageJsonClean: packageJsonDirty.length === 0,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
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
|
+
|
|
241
|
+
export function assertVersionFormat(version) {
|
|
242
|
+
if (!VERSION_PATTERN.test(version)) {
|
|
243
|
+
throw new Error(`Invalid version "${version}". Expected semver (e.g. 3.29.1 or 4.0.0-beta.1).`)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function resolveTagState(version, ref = 'HEAD', root = getProjectRoot()) {
|
|
248
|
+
const tagName = gitTagFromVersion(version)
|
|
249
|
+
const headCommit = run(`git rev-parse ${ref}`, { root })
|
|
250
|
+
let existsLocal = false
|
|
251
|
+
let localCommit = null
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
localCommit = run(`git rev-parse refs/tags/${tagName}^{commit}`, { root })
|
|
255
|
+
existsLocal = true
|
|
256
|
+
} catch {
|
|
257
|
+
existsLocal = false
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
let existsRemote = false
|
|
261
|
+
try {
|
|
262
|
+
existsRemote = run(`git ls-remote --tags origin refs/tags/${tagName}`, { root }).length > 0
|
|
263
|
+
} catch {
|
|
264
|
+
existsRemote = false
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
tagName,
|
|
269
|
+
version,
|
|
270
|
+
headCommit,
|
|
271
|
+
existsLocal,
|
|
272
|
+
existsRemote,
|
|
273
|
+
localCommit,
|
|
274
|
+
pointsToHead: existsLocal && localCommit === headCommit,
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function assertReadyToTag({ requireClean = false, root = getProjectRoot() } = {}) {
|
|
279
|
+
const state = getVersionState('HEAD', root)
|
|
280
|
+
const version = state.committed.version
|
|
281
|
+
|
|
282
|
+
if (requireClean && !state.isClean) {
|
|
283
|
+
throw new Error(`Working tree is not clean:\n${state.dirty}\nCommit or stash changes before tagging.`)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (!state.isPackageJsonClean) {
|
|
287
|
+
throw new Error(
|
|
288
|
+
`package.json has uncommitted changes:\n${state.packageJsonDirty}\n\nCommit the version bump first, then run tag again.`
|
|
289
|
+
)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (!state.versionMatch) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
`package.json version mismatch:\n HEAD commit: ${state.committed.version}\n Disk: ${state.disk.version}\n\nCommit package.json before tagging.`
|
|
295
|
+
)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
assertVersionFormat(version)
|
|
299
|
+
assertVersionBumpForTag(root)
|
|
300
|
+
|
|
301
|
+
const tag = resolveTagState(version, 'HEAD', root)
|
|
302
|
+
|
|
303
|
+
if (tag.existsLocal && !tag.pointsToHead) {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`Tag "${tag.tagName}" already exists on a different commit.\n tag → ${tag.localCommit?.slice(0, 7)}\n HEAD → ${tag.headCommit.slice(0, 7)}\n\nBump version in package.json and commit first.`
|
|
306
|
+
)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (tag.existsRemote && tag.pointsToHead) {
|
|
310
|
+
throw new Error(`Tag "${tag.tagName}" is already on origin for this commit. Nothing to do.`)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (tag.existsRemote && !tag.pointsToHead) {
|
|
314
|
+
throw new Error(`Tag "${tag.tagName}" already exists on origin. Bump version in package.json and commit first.`)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return { ...state, version, tag }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export async function runTagRelease({
|
|
321
|
+
dryRun = false,
|
|
322
|
+
requireClean = false,
|
|
323
|
+
skipPrepare = false,
|
|
324
|
+
root = getProjectRoot(),
|
|
325
|
+
} = {}) {
|
|
326
|
+
assertReadyToTag({ requireClean, root })
|
|
327
|
+
|
|
328
|
+
runReleasePrepare({ root, dryRun, skipPrepare })
|
|
329
|
+
|
|
330
|
+
const state = assertReadyToTag({ requireClean, root })
|
|
331
|
+
const { version, branch, headCommit, tag } = state
|
|
332
|
+
const shortCommit = headCommit.slice(0, 7)
|
|
333
|
+
|
|
334
|
+
console.log(`\nChecks passed:`)
|
|
335
|
+
console.log(` project root: ${root}`)
|
|
336
|
+
console.log(` HEAD commit: ${shortCommit}`)
|
|
337
|
+
console.log(` package.json: ${version}`)
|
|
338
|
+
console.log(` git tag: ${tag.tagName}`)
|
|
339
|
+
console.log(` branch: ${branch}`)
|
|
340
|
+
console.log(` tag on HEAD: ${tag.pointsToHead ? 'yes (push only)' : 'no (will create)'}`)
|
|
341
|
+
console.log('')
|
|
342
|
+
|
|
343
|
+
if (dryRun) {
|
|
344
|
+
if (!tag.pointsToHead) console.log('[dry-run] git tag', tag.tagName)
|
|
345
|
+
console.log('[dry-run] git push origin', branch)
|
|
346
|
+
console.log('[dry-run] git push origin', tag.tagName)
|
|
347
|
+
return state
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (!tag.pointsToHead) {
|
|
351
|
+
run(`git tag ${tag.tagName}`, { inherit: true, root })
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
run(`git push origin ${branch}`, { inherit: true, root })
|
|
355
|
+
run(`git push origin ${tag.tagName}`, { inherit: true, root })
|
|
356
|
+
|
|
357
|
+
return state
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
|
361
|
+
|
|
362
|
+
if (isMain) {
|
|
363
|
+
try {
|
|
364
|
+
const state = assertReadyToTag()
|
|
365
|
+
console.log(`✓ Version ${state.version} ready → tag ${state.tag.tagName} (branch: ${state.branch})`)
|
|
366
|
+
} catch (error) {
|
|
367
|
+
console.error(`✗ ${error.message}`)
|
|
368
|
+
process.exit(1)
|
|
369
|
+
}
|
|
370
|
+
}
|
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";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IProvide } from "../../utils";
|
|
2
|
-
import Configs from "
|
|
2
|
+
import Configs from "../../loader/configs";
|
|
3
3
|
export default class Clients implements IProvide<any> {
|
|
4
4
|
#private;
|
|
5
5
|
private _instances;
|
|
@@ -7,5 +7,6 @@ export default class Clients implements IProvide<any> {
|
|
|
7
7
|
configs: Configs;
|
|
8
8
|
});
|
|
9
9
|
onInit(): Promise<void>;
|
|
10
|
+
syncFromTmp: () => Promise<void>;
|
|
10
11
|
get instances(): Record<string, any>;
|
|
11
12
|
}
|
|
@@ -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}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import System from '
|
|
1
|
+
import System from '../../loader/system';
|
|
2
2
|
import { IProvide, ModeEnum } from '../../utils';
|
|
3
3
|
export interface IConfig {
|
|
4
4
|
worker: boolean;
|
|
@@ -40,7 +40,8 @@ export default class Configs implements IProvide<any> {
|
|
|
40
40
|
constructor({ system }: {
|
|
41
41
|
system: System;
|
|
42
42
|
});
|
|
43
|
-
onInit: (
|
|
43
|
+
onInit: () => Promise<void>;
|
|
44
|
+
syncFromTmp: () => Promise<void>;
|
|
44
45
|
setConfig(newConfigs: any): void;
|
|
45
46
|
_<K extends keyof IConfig>(key: K): IConfig[K];
|
|
46
47
|
get all(): IConfig;
|
|
@@ -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}}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type Builder, type FinalResult } from '@xrystal/dto/response';
|
|
2
|
+
import Logger from '../../loader/logger';
|
|
3
|
+
import System from '../../loader/system';
|
|
4
|
+
import { FrameworkEnum, IProvide, ProtocolEnum, controllerContextStorage, getControllerCtx, type ControllerMetadata, type ControllerStoreContext, type CtrOptions } from '../../utils';
|
|
5
|
+
export type ControllerContext = ControllerStoreContext;
|
|
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;
|
|
10
|
+
method: string;
|
|
11
|
+
url: string;
|
|
12
|
+
body: B;
|
|
13
|
+
params: P;
|
|
14
|
+
query: Q;
|
|
15
|
+
cookies: Record<string, unknown>;
|
|
16
|
+
ip: string;
|
|
17
|
+
lang: string;
|
|
18
|
+
requestId: string;
|
|
19
|
+
startTime: number;
|
|
20
|
+
t: TranslateFn;
|
|
21
|
+
accounts?: unknown;
|
|
22
|
+
}
|
|
23
|
+
export interface CustomResponse {
|
|
24
|
+
builder: Builder;
|
|
25
|
+
locals: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
export interface SchemaArgs<B = unknown, Q = Record<string, unknown>, P = Record<string, unknown>> {
|
|
28
|
+
req: CustomRequest<B, Q, P>;
|
|
29
|
+
res: CustomResponse;
|
|
30
|
+
builder: Builder;
|
|
31
|
+
body: B;
|
|
32
|
+
query: Q;
|
|
33
|
+
queries: Q;
|
|
34
|
+
params: P;
|
|
35
|
+
cookies: Record<string, unknown>;
|
|
36
|
+
locals: Record<string, unknown>;
|
|
37
|
+
t: TranslateFn;
|
|
38
|
+
}
|
|
39
|
+
export { controllerContextStorage, getControllerCtx, type ControllerMetadata };
|
|
40
|
+
export declare const runController: <T>(context: ControllerStoreContext, action: () => T | Promise<T>) => T | Promise<T>;
|
|
41
|
+
export declare function resolveBuilder(store: ControllerContext): Builder;
|
|
42
|
+
export declare abstract class BaseController {
|
|
43
|
+
protected system: System;
|
|
44
|
+
protected logger: Logger;
|
|
45
|
+
protected supportedProtocols: ProtocolEnum[];
|
|
46
|
+
protected get store(): ControllerStoreContext | undefined;
|
|
47
|
+
protected get protocol(): ProtocolEnum;
|
|
48
|
+
protected get req(): CustomRequest;
|
|
49
|
+
protected get res(): CustomResponse;
|
|
50
|
+
protected parseRequestBody(): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
export default abstract class Controller extends BaseController implements IProvide<unknown> {
|
|
53
|
+
onInit(): Promise<void>;
|
|
54
|
+
syncFromTmp: () => void;
|
|
55
|
+
protected parseMessage(msg: unknown, t: TranslateFn, isError?: boolean): string;
|
|
56
|
+
private args;
|
|
57
|
+
private fail;
|
|
58
|
+
private ok;
|
|
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>;
|
|
62
|
+
response?: (args: SchemaArgs<B, Q, P> & {
|
|
63
|
+
logicResult: unknown;
|
|
64
|
+
}) => Promise<unknown>;
|
|
65
|
+
}): Promise<ArrayBuffer | Uint8Array<ArrayBufferLike> | Response | Blob | FinalResult>;
|
|
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: {
|
|
67
|
+
locals?: Record<string, unknown>;
|
|
68
|
+
}, next: (err?: unknown) => void) => void);
|
|
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,39 @@
|
|
|
1
|
+
import { DTO, type DTOConfig } from '@xrystal/dto/dto';
|
|
2
|
+
import System from '../../loader/system';
|
|
3
|
+
import { FrameworkEnum, IProvide } from '../../utils';
|
|
4
|
+
import type { ElysiaPlugin, HttpMiddleware, SocketMiddleware } from '../../utils';
|
|
5
|
+
export declare const DEFAULT_DTO_CONFIG: DTOConfig;
|
|
6
|
+
export type DtoConfigureOptions = {
|
|
7
|
+
rebuild?: boolean;
|
|
8
|
+
};
|
|
9
|
+
export default class DtoRuntime implements IProvide<{
|
|
10
|
+
config?: Partial<DTOConfig>;
|
|
11
|
+
}> {
|
|
12
|
+
private _runtime;
|
|
13
|
+
private _system;
|
|
14
|
+
private _config;
|
|
15
|
+
private _framework;
|
|
16
|
+
private _bootConfig;
|
|
17
|
+
constructor({ system }: {
|
|
18
|
+
system: System;
|
|
19
|
+
});
|
|
20
|
+
onInit(props?: {
|
|
21
|
+
config?: Partial<DTOConfig>;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
syncFromTmp: () => Promise<void>;
|
|
24
|
+
get instance(): DTO;
|
|
25
|
+
get config(): Readonly<DTOConfig>;
|
|
26
|
+
get framework(): FrameworkEnum;
|
|
27
|
+
configure(config?: Partial<DTOConfig>, options?: DtoConfigureOptions): this;
|
|
28
|
+
use(...plugins: NonNullable<DTOConfig["plugins"]>): this;
|
|
29
|
+
express(): HttpMiddleware;
|
|
30
|
+
elysia(): ElysiaPlugin;
|
|
31
|
+
node(): HttpMiddleware;
|
|
32
|
+
websocket(): SocketMiddleware;
|
|
33
|
+
socketIo(): SocketMiddleware;
|
|
34
|
+
attachWebSocket(socket: any, requestId?: string): unknown;
|
|
35
|
+
attachSocketIo(socket: any): unknown;
|
|
36
|
+
fetch(): unknown;
|
|
37
|
+
forRequest(request: Request): Record<string, unknown>;
|
|
38
|
+
private applyConfig;
|
|
39
|
+
}
|
|
@@ -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()}}
|
|
@@ -4,7 +4,8 @@ import KafkaForCore from "./kafka";
|
|
|
4
4
|
import Logger from "./logger";
|
|
5
5
|
import Events from "./events";
|
|
6
6
|
import Localizations from "./localizations";
|
|
7
|
+
import DtoRuntime from "./dto";
|
|
7
8
|
import Controller from "./controller";
|
|
8
9
|
import Service from "./service";
|
|
9
10
|
import Clients from "./clients";
|
|
10
|
-
export { System, Configs, Logger, Events, Localizations, Controller, Service, Clients, KafkaForCore };
|
|
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};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import Configs from "
|
|
2
|
-
import System from "
|
|
1
|
+
import Configs from "../../loader/configs";
|
|
2
|
+
import System from "../../loader/system";
|
|
3
3
|
import { IProvide } from "../../utils";
|
|
4
4
|
type KafkaInstanceType = {
|
|
5
5
|
clientId: string;
|
|
@@ -19,7 +19,10 @@ export default class KafkaForCore implements IProvide<any> {
|
|
|
19
19
|
system: System;
|
|
20
20
|
configs: Configs;
|
|
21
21
|
});
|
|
22
|
-
|
|
22
|
+
onDispose: () => Promise<void>;
|
|
23
|
+
onInit: () => Promise<void>;
|
|
24
|
+
syncFromTmp: () => Promise<void>;
|
|
25
|
+
private teardownKafka;
|
|
23
26
|
kafkaLoader: ({ clientId, brokers, username, password }: KafkaInstanceType) => Promise<any>;
|
|
24
27
|
initializeKafkaInfrastructure: () => Promise<void>;
|
|
25
28
|
sendMessage: (topic: string, message: any) => Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils/index.js";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#q;#h;constructor({system:h,configs:q}){this.#q=h;this.#h=q}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();O(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#h.all?.kafkaClientId;this.brokers=this.#h.all?.kafkaBrokers;this.username=this.#h.all?.kafkaUsername;this.password=this.#h.all?.kafkaPassword;if(this.#h.all.isKafkaPassive)return;const h=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((q)=>q?.trim()).filter(Boolean);if(h.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:h,username:this.username,password:this.password});await this.initializeKafkaInfrastructure()};teardownKafka=async()=>{if(this._producer){try{await this._producer.disconnect()}catch{}this._producer=void 0}};kafkaLoader=async({clientId:h,brokers:q,username:F,password:E})=>{const D={clientId:h,brokers:q,sasl:F&&E?{mechanism:"plain",username:F,password:E}:void 0,ssl:!1,logLevel:N.ERROR,logCreator:()=>{return({level:z,log:G})=>{console.error(`Kafka ${G.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const z=new M(D);this._instance=z;this._producer=z.producer();await this.producer.connect();return z}catch(z){console.error(`Kafka ${z}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:h,kafkaTopics:q,isKafkaPassive:F}={isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaBrokers:process.env?.KAFKA_BROKERS,kafkaTopics:[...new Set([...this.#h.all.kafkaTopics])]};if(F===!0||!h)return;const E=Array.isArray(q)?q:[];if(E.length===0)return;const D=this._instance.admin();try{await D.connect();const z=await D.listTopics(),G=E.filter((J)=>!z.includes(J)).map((J)=>({topic:J,numPartitions:1,replicationFactor:1}));if(G.length>0)await D.createTopics({waitForLeaders:!0,topics:G})}catch(z){}finally{await D.disconnect()}};sendMessage=async(h,q)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:h,messages:[{value:JSON.stringify(q)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import Configs from "
|
|
2
|
-
import System from "
|
|
1
|
+
import Configs from "../../loader/configs";
|
|
2
|
+
import System from "../../loader/system";
|
|
3
3
|
import { IProvide } from "../../utils";
|
|
4
4
|
export default class Localizations implements IProvide<any> {
|
|
5
5
|
#private;
|
|
@@ -8,7 +8,8 @@ export default class Localizations implements IProvide<any> {
|
|
|
8
8
|
system: System;
|
|
9
9
|
configs: Configs;
|
|
10
10
|
});
|
|
11
|
-
onInit: (
|
|
11
|
+
onInit: () => Promise<void>;
|
|
12
|
+
syncFromTmp: () => Promise<void>;
|
|
12
13
|
i18next: ({ loadPath, fallbackLang, preloadLang, }: {
|
|
13
14
|
loadPath?: string;
|
|
14
15
|
fallbackLang?: string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import o from"path";import n from"i18next";import s from"i18next-fs-backend";import*as e from"i18next-http-middleware";import{bindLoaderTmpSync as r}from"../../utils/index.js";export default class Localizations{_instance=null;#t;#n;constructor({system:t,configs:a}){this.#t=t;this.#n=a}onInit=async()=>{await this.syncFromTmp();r(this)};syncFromTmp=async()=>{this._instance=null;const t=this.#t.tmp.configs.service.loaders.localization;this.i18next({loadPath:o.join(this.#t.tmp.configs.rootFolderPath,t.loadPath),fallbackLang:t.fallbackLang,preloadLang:t.preloadLangs})};i18next=({loadPath:t,fallbackLang:a,preloadLang:i})=>{if(this._instance)return this._instance;n.use(s).use(e.LanguageDetector).init({fallbackLng:a,preload:i,backend:{loadPath:`${t}/{{lng}}.json`}});if(n)this._instance=n;return n};get instance(){return this._instance}}
|