@xrystal/core 3.32.1 → 3.37.4

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.
Files changed (264) hide show
  1. package/README.md +676 -136
  2. package/package.json +27 -24
  3. package/tsconfig.base.json +15 -0
  4. package/x/bin/commands/create.mjs +34 -5
  5. package/x/bin/commands/doctor.mjs +115 -25
  6. package/x/bin/commands/hooks.mjs +55 -0
  7. package/x/bin/commands/project.mjs +75 -42
  8. package/x/bin/commands/release.mjs +8 -3
  9. package/x/bin/commands/sync-toolchain.mjs +43 -0
  10. package/x/bin/commands/tmp.mjs +13 -4
  11. package/x/bin/helpers/.generated/.generated-from +1 -0
  12. package/x/bin/helpers/.generated/tmp-schema.mjs +192 -0
  13. package/x/bin/helpers/banner.mjs +66 -12
  14. package/x/bin/helpers/build-config.mjs +342 -0
  15. package/x/bin/helpers/cli-help.mjs +164 -0
  16. package/x/bin/helpers/create-target.mjs +18 -2
  17. package/x/bin/helpers/project-artifacts.mjs +142 -0
  18. package/x/bin/helpers/runtime-info.mjs +172 -0
  19. package/x/bin/helpers/tmp-config.mjs +11 -10
  20. package/x/bin/helpers/tmp-layout.mjs +10 -16
  21. package/x/bin/helpers/tmp-schema.mjs +9 -0
  22. package/x/bin/helpers/toolchain-config.mjs +233 -0
  23. package/x/bin/main-cli.js +31 -3
  24. package/x/bin/scripts/clean-source-types.mjs +19 -0
  25. package/x/bin/scripts/fix-dist-imports.mjs +80 -0
  26. package/x/bin/scripts/install-git-hooks.mjs +86 -0
  27. package/x/bin/scripts/minify-dist.mjs +50 -0
  28. package/x/bin/scripts/prepare-npm-publish.mjs +39 -0
  29. package/x/bin/scripts/publish-guard.mjs +113 -0
  30. package/x/bin/scripts/verify-npm-pack.mjs +12 -0
  31. package/x/bin/scripts/verify-publish-config.mjs +10 -0
  32. package/x/bin/scripts/verify-version-bump.mjs +27 -0
  33. package/x/bin/scripts/version-check.mjs +173 -0
  34. package/x/dist/index.js +1 -0
  35. package/x/dist/loader/clients/index.js +1 -0
  36. package/x/dist/loader/configs/index.js +1 -0
  37. package/{source → x/dist}/loader/controller/index.d.ts +20 -17
  38. package/x/dist/loader/controller/index.js +1 -0
  39. package/x/dist/loader/dto/index.js +1 -0
  40. package/x/dist/loader/events/index.js +1 -0
  41. package/x/dist/loader/index.d.ts +11 -0
  42. package/x/dist/loader/index.js +1 -0
  43. package/{source → x/dist}/loader/kafka/index.d.ts +1 -0
  44. package/x/dist/loader/kafka/index.js +1 -0
  45. package/x/dist/loader/localizations/index.js +1 -0
  46. package/{source → x/dist}/loader/logger/index.d.ts +1 -0
  47. package/x/dist/loader/logger/index.js +2 -0
  48. package/x/dist/loader/service/index.js +1 -0
  49. package/x/dist/loader/system/index.js +1 -0
  50. package/x/dist/project/index.d.ts +12 -0
  51. package/x/dist/project/index.js +1 -0
  52. package/x/dist/utils/constants/defaults.json +44 -0
  53. package/x/dist/utils/constants/index.js +1 -0
  54. package/x/dist/utils/helpers/configs/index.js +1 -0
  55. package/x/dist/utils/helpers/context/controller-store.js +1 -0
  56. package/x/dist/utils/helpers/context/index.js +1 -0
  57. package/{source → x/dist}/utils/helpers/core/index.d.ts +1 -1
  58. package/x/dist/utils/helpers/core/index.js +1 -0
  59. package/x/dist/utils/helpers/core/paths.js +1 -0
  60. package/x/dist/utils/helpers/core/tmp-layout.js +1 -0
  61. package/x/dist/utils/helpers/date/index.js +1 -0
  62. package/x/dist/utils/helpers/dispatch/index.js +1 -0
  63. package/x/dist/utils/helpers/dto/index.js +1 -0
  64. package/x/dist/utils/helpers/filters/index.js +1 -0
  65. package/x/dist/utils/helpers/framework/index.js +1 -0
  66. package/x/dist/utils/helpers/handlers/adapters.js +1 -0
  67. package/x/dist/utils/helpers/handlers/execute.js +1 -0
  68. package/x/dist/utils/helpers/handlers/index.js +1 -0
  69. package/x/dist/utils/helpers/hash/crypto.js +1 -0
  70. package/x/dist/utils/helpers/id/index.js +1 -0
  71. package/x/dist/utils/helpers/index.js +1 -0
  72. package/x/dist/utils/helpers/ip/index.js +1 -0
  73. package/x/dist/utils/helpers/is/index.js +1 -0
  74. package/x/dist/utils/helpers/locales/index.js +1 -0
  75. package/x/dist/utils/helpers/math/index.js +1 -0
  76. package/{source → x/dist}/utils/helpers/middleware/index.d.ts +2 -2
  77. package/x/dist/utils/helpers/middleware/index.js +1 -0
  78. package/x/dist/utils/helpers/objects/index.js +1 -0
  79. package/x/dist/utils/helpers/path/index.js +1 -0
  80. package/{source → x/dist}/utils/helpers/protocol/index.d.ts +2 -10
  81. package/x/dist/utils/helpers/protocol/index.js +1 -0
  82. package/x/dist/utils/helpers/protocol/options.js +1 -0
  83. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +1 -0
  84. package/x/dist/utils/helpers/runtime/dto-access.js +1 -0
  85. package/x/dist/utils/helpers/runtime/dto-types.js +1 -0
  86. package/{source → x/dist}/utils/helpers/runtime/index.d.ts +1 -0
  87. package/x/dist/utils/helpers/runtime/index.js +1 -0
  88. package/x/dist/utils/helpers/runtime/shutdown.d.ts +3 -0
  89. package/x/dist/utils/helpers/runtime/shutdown.js +1 -0
  90. package/x/dist/utils/helpers/state/index.js +1 -0
  91. package/x/dist/utils/helpers/state/props-from-tmp.js +1 -0
  92. package/x/dist/utils/helpers/state/request-key-guard.js +1 -0
  93. package/x/dist/utils/helpers/state/scopes.js +1 -0
  94. package/x/dist/utils/helpers/string/index.js +1 -0
  95. package/x/dist/utils/helpers/tests/tmp-schema.test.js +1 -0
  96. package/x/dist/utils/helpers/tests/tmp-watch.test.d.ts +1 -0
  97. package/x/dist/utils/helpers/tests/tmp-watch.test.js +1 -0
  98. package/x/dist/utils/helpers/timer/index.js +1 -0
  99. package/x/dist/utils/helpers/tmp/index.d.ts +5 -0
  100. package/x/dist/utils/helpers/tmp/index.js +1 -0
  101. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -0
  102. package/{source → x/dist}/utils/helpers/tmp/runtime-tmp.d.ts +2 -6
  103. package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -0
  104. package/{source → x/dist}/utils/helpers/tmp/tmp-loader.d.ts +1 -0
  105. package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -0
  106. package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +47 -0
  107. package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -0
  108. package/x/dist/utils/helpers/tmp/tmp-watch.d.ts +1 -0
  109. package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -0
  110. package/x/dist/utils/helpers/validates/index.js +1 -0
  111. package/x/dist/utils/index.js +1 -0
  112. package/x/dist/utils/models/classes/class.clients.js +1 -0
  113. package/x/dist/utils/models/classes/class.interfaces.js +1 -0
  114. package/x/dist/utils/models/classes/class.service-locator.js +1 -0
  115. package/{source → x/dist}/utils/models/classes/class.tmp-file-loader.d.ts +3 -2
  116. package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -0
  117. package/x/dist/utils/models/classes/class.x.js +1 -0
  118. package/x/dist/utils/models/enums/index.js +1 -0
  119. package/x/dist/utils/models/index.js +1 -0
  120. package/x/dist/utils/models/types/index.js +1 -0
  121. package/x/dist/utils/package-root.js +1 -0
  122. package/x/tmp.yml +51 -42
  123. package/source/index.js +0 -11
  124. package/source/loader/clients/index.js +0 -22
  125. package/source/loader/configs/index.js +0 -88
  126. package/source/loader/controller/index.js +0 -236
  127. package/source/loader/dto/index.js +0 -92
  128. package/source/loader/events/index.js +0 -44
  129. package/source/loader/index.d.ts +0 -11
  130. package/source/loader/index.js +0 -11
  131. package/source/loader/kafka/index.js +0 -137
  132. package/source/loader/localizations/index.js +0 -46
  133. package/source/loader/logger/index.js +0 -217
  134. package/source/loader/service/index.js +0 -7
  135. package/source/loader/system/index.js +0 -25
  136. package/source/project/index.d.ts +0 -8
  137. package/source/project/index.js +0 -70
  138. package/source/utils/constants/defaults.json +0 -15
  139. package/source/utils/constants/defaults.mjs +0 -10
  140. package/source/utils/constants/index.js +0 -22
  141. package/source/utils/helpers/configs/index.js +0 -1
  142. package/source/utils/helpers/context/controller-store.js +0 -12
  143. package/source/utils/helpers/context/index.js +0 -24
  144. package/source/utils/helpers/core/index.js +0 -58
  145. package/source/utils/helpers/core/paths.js +0 -78
  146. package/source/utils/helpers/core/tmp-layout.js +0 -241
  147. package/source/utils/helpers/date/index.js +0 -48
  148. package/source/utils/helpers/dispatch/index.js +0 -53
  149. package/source/utils/helpers/dto/index.js +0 -10
  150. package/source/utils/helpers/filters/index.js +0 -44
  151. package/source/utils/helpers/framework/index.js +0 -17
  152. package/source/utils/helpers/handlers/adapters.js +0 -40
  153. package/source/utils/helpers/handlers/execute.js +0 -82
  154. package/source/utils/helpers/handlers/index.js +0 -31
  155. package/source/utils/helpers/hash/crypto.js +0 -22
  156. package/source/utils/helpers/id/index.js +0 -24
  157. package/source/utils/helpers/index.js +0 -26
  158. package/source/utils/helpers/ip/index.js +0 -21
  159. package/source/utils/helpers/is/index.js +0 -35
  160. package/source/utils/helpers/locales/index.js +0 -82
  161. package/source/utils/helpers/math/index.js +0 -14
  162. package/source/utils/helpers/middleware/index.js +0 -36
  163. package/source/utils/helpers/objects/index.js +0 -55
  164. package/source/utils/helpers/path/index.js +0 -4
  165. package/source/utils/helpers/protocol/index.js +0 -99
  166. package/source/utils/helpers/protocol/options.js +0 -13
  167. package/source/utils/helpers/regex/checkSpecialRegexControl.js +0 -3
  168. package/source/utils/helpers/runtime/dto-access.js +0 -5
  169. package/source/utils/helpers/runtime/index.js +0 -1
  170. package/source/utils/helpers/state/index.js +0 -185
  171. package/source/utils/helpers/state/props-from-tmp.js +0 -44
  172. package/source/utils/helpers/state/request-key-guard.js +0 -42
  173. package/source/utils/helpers/state/scopes.js +0 -69
  174. package/source/utils/helpers/string/index.js +0 -9
  175. package/source/utils/helpers/timer/index.js +0 -5
  176. package/source/utils/helpers/tmp/index.d.ts +0 -3
  177. package/source/utils/helpers/tmp/index.js +0 -3
  178. package/source/utils/helpers/tmp/loader-tmp-sync.js +0 -13
  179. package/source/utils/helpers/tmp/runtime-tmp.js +0 -30
  180. package/source/utils/helpers/tmp/tmp-loader.js +0 -48
  181. package/source/utils/helpers/validates/index.js +0 -20
  182. package/source/utils/index.js +0 -3
  183. package/source/utils/models/classes/class.clients.js +0 -142
  184. package/source/utils/models/classes/class.interfaces.js +0 -10
  185. package/source/utils/models/classes/class.service-locator.js +0 -16
  186. package/source/utils/models/classes/class.tmp-file-loader.js +0 -38
  187. package/source/utils/models/classes/class.x.js +0 -180
  188. package/source/utils/models/enums/index.js +0 -148
  189. package/source/utils/models/index.js +0 -9
  190. package/source/utils/models/types/index.js +0 -2
  191. package/source/utils/models/types/shims.d.ts +0 -123
  192. package/source/utils/package-root.js +0 -5
  193. package/x/tests/cli.test.ts +0 -85
  194. package/x/tests/context.test.ts +0 -25
  195. package/x/tests/dispatch.test.ts +0 -84
  196. package/x/tests/fixtures/locales/en/translation.json +0 -8
  197. package/x/tests/fixtures/locales/tr/translation.json +0 -8
  198. package/x/tests/frameworks.integration.test.ts +0 -185
  199. package/x/tests/helpers/i18n-setup.ts +0 -52
  200. package/x/tests/helpers/middleware.ts +0 -23
  201. package/x/tests/helpers/register-test-dto.ts +0 -52
  202. package/x/tests/i18n.integration.test.ts +0 -77
  203. package/x/tests/i18n.test.ts +0 -96
  204. package/x/tests/middleware.test.ts +0 -83
  205. package/x/tests/project-layout.test.ts +0 -65
  206. package/x/tests/protocol.test.ts +0 -75
  207. package/x/tests/realtime.examples.test.ts +0 -198
  208. package/x/tests/runtime-tmp.test.ts +0 -49
  209. package/x/tests/socket.integration.test.ts +0 -174
  210. package/x/tests/state.test.ts +0 -183
  211. package/x/tests/tmp-layout-guard.test.ts +0 -40
  212. /package/{source → x/dist}/index.d.ts +0 -0
  213. /package/{source → x/dist}/loader/clients/index.d.ts +0 -0
  214. /package/{source → x/dist}/loader/configs/index.d.ts +0 -0
  215. /package/{source → x/dist}/loader/dto/index.d.ts +0 -0
  216. /package/{source → x/dist}/loader/events/index.d.ts +0 -0
  217. /package/{source → x/dist}/loader/localizations/index.d.ts +0 -0
  218. /package/{source → x/dist}/loader/service/index.d.ts +0 -0
  219. /package/{source → x/dist}/loader/system/index.d.ts +0 -0
  220. /package/{source → x/dist}/utils/constants/index.d.ts +0 -0
  221. /package/{source → x/dist}/utils/helpers/configs/index.d.ts +0 -0
  222. /package/{source → x/dist}/utils/helpers/context/controller-store.d.ts +0 -0
  223. /package/{source → x/dist}/utils/helpers/context/index.d.ts +0 -0
  224. /package/{source → x/dist}/utils/helpers/core/paths.d.ts +0 -0
  225. /package/{source → x/dist}/utils/helpers/core/tmp-layout.d.ts +0 -0
  226. /package/{source → x/dist}/utils/helpers/date/index.d.ts +0 -0
  227. /package/{source → x/dist}/utils/helpers/dispatch/index.d.ts +0 -0
  228. /package/{source → x/dist}/utils/helpers/dto/index.d.ts +0 -0
  229. /package/{source → x/dist}/utils/helpers/filters/index.d.ts +0 -0
  230. /package/{source → x/dist}/utils/helpers/framework/index.d.ts +0 -0
  231. /package/{source → x/dist}/utils/helpers/handlers/adapters.d.ts +0 -0
  232. /package/{source → x/dist}/utils/helpers/handlers/execute.d.ts +0 -0
  233. /package/{source → x/dist}/utils/helpers/handlers/index.d.ts +0 -0
  234. /package/{source → x/dist}/utils/helpers/hash/crypto.d.ts +0 -0
  235. /package/{source → x/dist}/utils/helpers/id/index.d.ts +0 -0
  236. /package/{source → x/dist}/utils/helpers/index.d.ts +0 -0
  237. /package/{source → x/dist}/utils/helpers/ip/index.d.ts +0 -0
  238. /package/{source → x/dist}/utils/helpers/is/index.d.ts +0 -0
  239. /package/{source → x/dist}/utils/helpers/locales/index.d.ts +0 -0
  240. /package/{source → x/dist}/utils/helpers/math/index.d.ts +0 -0
  241. /package/{source → x/dist}/utils/helpers/objects/index.d.ts +0 -0
  242. /package/{source → x/dist}/utils/helpers/path/index.d.ts +0 -0
  243. /package/{source → x/dist}/utils/helpers/protocol/options.d.ts +0 -0
  244. /package/{source → x/dist}/utils/helpers/regex/checkSpecialRegexControl.d.ts +0 -0
  245. /package/{source → x/dist}/utils/helpers/runtime/dto-access.d.ts +0 -0
  246. /package/{source → x/dist}/utils/helpers/runtime/dto-types.d.ts +0 -0
  247. /package/{source → x/dist}/utils/helpers/state/index.d.ts +0 -0
  248. /package/{source → x/dist}/utils/helpers/state/props-from-tmp.d.ts +0 -0
  249. /package/{source → x/dist}/utils/helpers/state/request-key-guard.d.ts +0 -0
  250. /package/{source → x/dist}/utils/helpers/state/scopes.d.ts +0 -0
  251. /package/{source → x/dist}/utils/helpers/string/index.d.ts +0 -0
  252. /package/{source/utils/helpers/runtime/dto-types.js → x/dist/utils/helpers/tests/tmp-schema.test.d.ts} +0 -0
  253. /package/{source → x/dist}/utils/helpers/timer/index.d.ts +0 -0
  254. /package/{source → x/dist}/utils/helpers/tmp/loader-tmp-sync.d.ts +0 -0
  255. /package/{source → x/dist}/utils/helpers/validates/index.d.ts +0 -0
  256. /package/{source → x/dist}/utils/index.d.ts +0 -0
  257. /package/{source → x/dist}/utils/models/classes/class.clients.d.ts +0 -0
  258. /package/{source → x/dist}/utils/models/classes/class.interfaces.d.ts +0 -0
  259. /package/{source → x/dist}/utils/models/classes/class.service-locator.d.ts +0 -0
  260. /package/{source → x/dist}/utils/models/classes/class.x.d.ts +0 -0
  261. /package/{source → x/dist}/utils/models/enums/index.d.ts +0 -0
  262. /package/{source → x/dist}/utils/models/index.d.ts +0 -0
  263. /package/{source → x/dist}/utils/models/types/index.d.ts +0 -0
  264. /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,39 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { PublishGuardError, runPublishGuards } from './publish-guard.mjs'
5
+
6
+ const root = process.cwd()
7
+
8
+ const pathsToRemove = [
9
+ 'source',
10
+ 'x/tests',
11
+ '.github',
12
+ '.vscode',
13
+ 'x/logs',
14
+ 'x/docker',
15
+ 'tsconfig.json',
16
+ 'eslint.config.js',
17
+ '.gitignore',
18
+ '.babelrc',
19
+ ]
20
+
21
+ for (const rel of pathsToRemove) {
22
+ const abs = path.join(root, rel)
23
+ if (!fs.existsSync(abs)) continue
24
+ fs.rmSync(abs, { recursive: true, force: true })
25
+ console.log(`prepare-npm-publish: removed ${rel}`)
26
+ }
27
+
28
+ if (!fs.existsSync(path.join(root, 'x', 'dist'))) {
29
+ console.error('prepare-npm-publish: x/dist missing — run build first')
30
+ process.exit(1)
31
+ }
32
+
33
+ try {
34
+ const { jsCount } = runPublishGuards(root, { strictDisk: true })
35
+ console.log(`prepare-npm-publish: ready (${jsCount} .js in x/dist, verified)`)
36
+ } catch (error) {
37
+ console.error(`prepare-npm-publish: ✗ ${error instanceof PublishGuardError ? error.message : error.message}`)
38
+ process.exit(1)
39
+ }
@@ -0,0 +1,113 @@
1
+ import { execSync } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ export class PublishGuardError extends Error {
6
+ constructor(message) {
7
+ super(message)
8
+ this.name = 'PublishGuardError'
9
+ }
10
+ }
11
+
12
+ export function readPackage(root = process.cwd()) {
13
+ return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
14
+ }
15
+
16
+ export function assertFilesListNoSource(pkg) {
17
+ const files = Array.isArray(pkg.files) ? pkg.files : []
18
+ const bad = files.filter((entry) => {
19
+ const normalized = String(entry).replace(/^\.\//, '').replace(/\\/g, '/')
20
+ return normalized === 'source' || normalized.startsWith('source/')
21
+ })
22
+ if (bad.length > 0) {
23
+ throw new PublishGuardError(`package.json files must not include source/ (found: ${bad.join(', ')})`)
24
+ }
25
+ }
26
+
27
+ export function assertFilesListHasDist(pkg) {
28
+ const files = Array.isArray(pkg.files) ? pkg.files : []
29
+ if (!files.some((entry) => String(entry).replace(/^\.\//, '').includes('dist'))) {
30
+ throw new PublishGuardError('package.json files must include x/dist')
31
+ }
32
+ }
33
+
34
+ export function assertMainExportsPointToDist(pkg) {
35
+ const main = String(pkg.main ?? '')
36
+ if (!main.includes('/dist/')) {
37
+ throw new PublishGuardError(`package.json main must point to x/dist (got ${main || 'empty'})`)
38
+ }
39
+ const exports = pkg.exports ?? {}
40
+ for (const [key, value] of Object.entries(exports)) {
41
+ if (key === './tsconfig.base.json') continue
42
+ const target = typeof value === 'string' ? value : value?.default
43
+ if (target && !String(target).includes('/dist/')) {
44
+ throw new PublishGuardError(`exports[${key}] must point to x/dist (got ${target})`)
45
+ }
46
+ }
47
+ }
48
+
49
+ export function assertSourceAbsentOnDisk(root = process.cwd()) {
50
+ if (fs.existsSync(path.join(root, 'source'))) {
51
+ throw new PublishGuardError('source/ must not exist on disk at publish time')
52
+ }
53
+ }
54
+
55
+ export function countDistJs(root = process.cwd()) {
56
+ const distDir = path.join(root, 'x', 'dist')
57
+ if (!fs.existsSync(distDir)) return 0
58
+ let count = 0
59
+ const walk = (dir) => {
60
+ for (const name of fs.readdirSync(dir)) {
61
+ const abs = path.join(dir, name)
62
+ if (fs.statSync(abs).isDirectory()) walk(abs)
63
+ else if (name.endsWith('.js')) count += 1
64
+ }
65
+ }
66
+ walk(distDir)
67
+ return count
68
+ }
69
+
70
+ export function assertDistTree(root = process.cwd(), minJs = 10) {
71
+ const distIndex = path.join(root, 'x/dist/index.js')
72
+ if (!fs.existsSync(distIndex)) {
73
+ throw new PublishGuardError('x/dist/index.js missing — run build first')
74
+ }
75
+ const jsCount = countDistJs(root)
76
+ if (jsCount < minJs) {
77
+ throw new PublishGuardError(`x/dist incomplete (${jsCount} .js files, need >= ${minJs})`)
78
+ }
79
+ }
80
+
81
+ export function assertDistMinified(root = process.cwd()) {
82
+ const indexJs = fs.readFileSync(path.join(root, 'x/dist/index.js'), 'utf8')
83
+ const lines = indexJs.split('\n').filter((line) => line.trim().length > 0)
84
+ const looksReadable = lines.length > 3 && indexJs.includes("from './") && !indexJs.includes('from"')
85
+ if (looksReadable) {
86
+ throw new PublishGuardError('x/dist/index.js looks unminified — enable build.minify before publish')
87
+ }
88
+ }
89
+
90
+ export function assertNpmPackClean(root = process.cwd()) {
91
+ const dryRun = execSync('npm pack --dry-run 2>&1', { cwd: root, encoding: 'utf8' })
92
+ if (/source\/.*\.ts/.test(dryRun) || /npm notice.*source\//.test(dryRun)) {
93
+ throw new PublishGuardError('npm pack tarball lists source/ — TypeScript source must not ship')
94
+ }
95
+ if (!/x\/dist\/.*\.js/.test(dryRun)) {
96
+ throw new PublishGuardError('npm pack tarball must include x/dist/**/*.js')
97
+ }
98
+ return dryRun
99
+ }
100
+
101
+ export function runPublishGuards(root = process.cwd(), { strictDisk = false } = {}) {
102
+ const pkg = readPackage(root)
103
+ assertFilesListNoSource(pkg)
104
+ assertFilesListHasDist(pkg)
105
+ assertMainExportsPointToDist(pkg)
106
+ assertDistTree(root)
107
+ assertNpmPackClean(root)
108
+ if (strictDisk) {
109
+ assertSourceAbsentOnDisk(root)
110
+ assertDistMinified(root)
111
+ }
112
+ return { pkg, jsCount: countDistJs(root) }
113
+ }
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { PublishGuardError, runPublishGuards } from './publish-guard.mjs'
3
+
4
+ try {
5
+ const { jsCount } = runPublishGuards(process.cwd(), { strictDisk: true })
6
+ console.log('verify-npm-pack: ✓ package.json files — no source/')
7
+ console.log('verify-npm-pack: ✓ main/exports → x/dist')
8
+ console.log(`verify-npm-pack: ✓ npm pack clean (${jsCount} .js, minified)`)
9
+ } catch (error) {
10
+ console.error(`verify-npm-pack: ✗ ${error instanceof PublishGuardError ? error.message : error.message}`)
11
+ process.exit(1)
12
+ }
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { PublishGuardError, runPublishGuards } from './publish-guard.mjs'
3
+
4
+ try {
5
+ runPublishGuards(process.cwd(), { strictDisk: false })
6
+ console.log('verify-publish-config: ✓ npm pack would not ship source/')
7
+ } catch (error) {
8
+ console.error(`verify-publish-config: ✗ ${error instanceof PublishGuardError ? error.message : error.message}`)
9
+ process.exit(1)
10
+ }
@@ -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
 
@@ -0,0 +1 @@
1
+ import a from"./project/index.js";await(async()=>{await a({})})();
@@ -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 interface CustomRequest<B = any, Q = any, P = any> {
7
- headers: Record<string, any>;
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, any>;
15
+ cookies: Record<string, unknown>;
14
16
  ip: string;
15
17
  lang: string;
16
18
  requestId: string;
17
19
  startTime: number;
18
- t: (k: string, args?: any) => string;
20
+ t: TranslateFn;
21
+ accounts?: unknown;
19
22
  }
20
23
  export interface CustomResponse {
21
24
  builder: Builder;
22
- locals: Record<string, any>;
25
+ locals: Record<string, unknown>;
23
26
  }
24
- export interface SchemaArgs<B = any, Q = any, P = any> {
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, any>;
33
- locals: Record<string, any>;
34
- t: Function;
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<any> {
52
+ export default abstract class Controller extends BaseController implements IProvide<unknown> {
50
53
  onInit(): Promise<void>;
51
54
  syncFromTmp: () => void;
52
- protected parseMessage(msg: any, t: Function, isError?: boolean): string;
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 = any, Q = any, P = any>({ checks, logic, response }: {
57
- checks?: (args: SchemaArgs<B, Q, P>) => Promise<any>;
58
- logic?: (args: SchemaArgs<B, Q, P>) => Promise<any>;
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: any;
61
- }) => Promise<any>;
63
+ logicResult: unknown;
64
+ }) => Promise<unknown>;
62
65
  }): Promise<ArrayBuffer | Uint8Array<ArrayBufferLike> | Response | Blob | FinalResult>;
63
- protected ctr<B = any, Q = any, P = any>(definition: Parameters<Controller['schema']>[0], opts?: FrameworkEnum | CtrOptions): ((req: Request, serverCtx?: Record<string, unknown>) => Promise<unknown>) | ((req: unknown, res: {
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};