@xrystal/core 3.38.1 → 3.38.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 +251 -2146
- package/package.json +3 -3
- package/x/bin/helpers/.generated/tmp-schema.mjs +8 -1
- package/x/bin/helpers/build-config.mjs +2 -0
- package/x/bin/helpers/defaults.json +44 -0
- package/x/bin/helpers/package-defaults.mjs +21 -0
- package/x/bin/helpers/project-artifacts.mjs +14 -1
- package/x/bin/paths.mjs +1 -1
- package/x/bin/scripts/clean-dist-tests.mjs +50 -0
- package/x/bin/scripts/fix-dist-imports.mjs +11 -2
- package/x/bin/scripts/sync-cli-defaults.mjs +16 -0
- package/x/dist/loader/clients/index.js +1 -1
- package/x/dist/loader/configs/index.js +1 -1
- package/x/dist/loader/controller/index.js +1 -1
- package/x/dist/loader/dto/index.js +1 -1
- package/x/dist/loader/events/index.js +1 -1
- package/x/dist/loader/index.js +1 -1
- package/x/dist/loader/kafka/index.js +1 -1
- package/x/dist/loader/localizations/index.js +1 -1
- package/x/dist/loader/logger/index.js +1 -1
- package/x/dist/loader/system/index.js +1 -1
- package/x/dist/project/index.js +1 -1
- package/x/dist/utils/constants/index.js +1 -1
- package/x/dist/utils/helpers/context/index.js +1 -1
- package/x/dist/utils/helpers/core/index.js +1 -1
- package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
- package/x/dist/utils/helpers/date/index.js +1 -1
- package/x/dist/utils/helpers/dispatch/index.js +1 -1
- package/x/dist/utils/helpers/framework/index.js +1 -1
- package/x/dist/utils/helpers/handlers/adapters.js +1 -1
- package/x/dist/utils/helpers/handlers/execute.js +1 -1
- package/x/dist/utils/helpers/handlers/index.js +1 -1
- package/x/dist/utils/helpers/index.js +1 -1
- package/x/dist/utils/helpers/middleware/index.js +1 -1
- package/x/dist/utils/helpers/protocol/index.js +1 -1
- package/x/dist/utils/helpers/protocol/options.js +1 -1
- package/x/dist/utils/helpers/runtime/dto-access.js +1 -1
- package/x/dist/utils/helpers/runtime/index.js +1 -1
- package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
- package/x/dist/utils/helpers/state/index.js +1 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
- package/x/dist/utils/helpers/state/scopes.js +1 -1
- package/x/dist/utils/helpers/tmp/index.js +1 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
- package/x/dist/utils/index.js +1 -1
- package/x/dist/utils/models/classes/class.clients.js +1 -1
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
- package/x/dist/utils/models/index.js +1 -1
- package/x/dist/utils/helpers/tests/tmp-schema.test.d.ts +0 -1
- package/x/dist/utils/helpers/tests/tmp-schema.test.js +0 -1
- package/x/dist/utils/helpers/tests/tmp-watch.test.d.ts +0 -1
- package/x/dist/utils/helpers/tests/tmp-watch.test.js +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"author": "Yusuf Yasir KAYGUSUZ",
|
|
3
3
|
"name": "@xrystal/core",
|
|
4
|
-
"version": "3.38.
|
|
4
|
+
"version": "3.38.3",
|
|
5
5
|
"description": "Project core for xrystal",
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"access": "public",
|
|
@@ -57,10 +57,10 @@
|
|
|
57
57
|
"scripts": {
|
|
58
58
|
"dev": "node x/bin/main-cli.js dev",
|
|
59
59
|
"build": "node x/bin/main-cli.js build",
|
|
60
|
-
"test": "bun test x/tests",
|
|
60
|
+
"test": "bun test x/tests source/utils/helpers/tests",
|
|
61
61
|
"lint": "eslint source",
|
|
62
62
|
"prepublishOnly": "bun run release:prepare && node x/bin/scripts/verify-publish-config.mjs",
|
|
63
|
-
"release:prepare": "bun run lint && bun run build && bun test x/tests",
|
|
63
|
+
"release:prepare": "bun run lint && bun run build && bun test x/tests source/utils/helpers/tests",
|
|
64
64
|
"build:prod": "bun run release:prepare && node x/bin/scripts/clean-source-types.mjs",
|
|
65
65
|
"build:dev": "node x/bin/main-cli.js dev",
|
|
66
66
|
"start": "node x/bin/main-cli.js start",
|
|
@@ -56,7 +56,14 @@ var defaults_default = {
|
|
|
56
56
|
// source/utils/constants/index.ts
|
|
57
57
|
var packageDefaults = Object.freeze({
|
|
58
58
|
...defaults_default,
|
|
59
|
-
layoutPaths: Object.freeze({ ...defaults_default.layoutPaths })
|
|
59
|
+
layoutPaths: Object.freeze({ ...defaults_default.layoutPaths }),
|
|
60
|
+
buildDefaults: Object.freeze({ ...defaults_default.buildDefaults }),
|
|
61
|
+
tsconfigDefaults: Object.freeze({
|
|
62
|
+
...defaults_default.tsconfigDefaults,
|
|
63
|
+
compilerOptions: Object.freeze({ ...defaults_default.tsconfigDefaults.compilerOptions })
|
|
64
|
+
}),
|
|
65
|
+
eslintDefaults: Object.freeze({ ...defaults_default.eslintDefaults }),
|
|
66
|
+
tmpWatchDefaults: Object.freeze({ ...defaults_default.tmpWatchDefaults })
|
|
60
67
|
});
|
|
61
68
|
var tmpFileName = `${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;
|
|
62
69
|
|
|
@@ -278,6 +278,7 @@ export function resolveEffectiveBuildOptions(root, layout, buildConfig = {}) {
|
|
|
278
278
|
export function resolveCoreBuildSteps(root, distRel, buildConfig = {}) {
|
|
279
279
|
const tsconfigRel = resolveTsconfigRel(root, buildConfig) ?? 'tsconfig.json'
|
|
280
280
|
const steps = [
|
|
281
|
+
'node x/bin/scripts/sync-cli-defaults.mjs',
|
|
281
282
|
`rm -rf ${distRel}`,
|
|
282
283
|
`bun run tsc --project ${tsconfigRel}`,
|
|
283
284
|
`bunx tsc-alias -p ${tsconfigRel}`,
|
|
@@ -286,6 +287,7 @@ export function resolveCoreBuildSteps(root, distRel, buildConfig = {}) {
|
|
|
286
287
|
steps.push('node x/bin/scripts/minify-dist.mjs')
|
|
287
288
|
}
|
|
288
289
|
steps.push('node x/bin/scripts/fix-dist-imports.mjs')
|
|
290
|
+
steps.push('node x/bin/scripts/clean-dist-tests.mjs')
|
|
289
291
|
steps.push('node x/bin/scripts/clean-source-types.mjs')
|
|
290
292
|
return steps
|
|
291
293
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"packageName": "@xrystal/core",
|
|
3
|
+
"packageRootFolder": "x",
|
|
4
|
+
"tmpBaseName": "tmp",
|
|
5
|
+
"tmpExtension": ".yml",
|
|
6
|
+
"mainSourceFolder": "./source",
|
|
7
|
+
"layoutPaths": {
|
|
8
|
+
"tests": "tests",
|
|
9
|
+
"environments": "environments",
|
|
10
|
+
"dist": "dist"
|
|
11
|
+
},
|
|
12
|
+
"buildDefaults": {
|
|
13
|
+
"tsconfig": "tsconfig.json",
|
|
14
|
+
"typecheck": false,
|
|
15
|
+
"tscLenient": false,
|
|
16
|
+
"declarations": false,
|
|
17
|
+
"sourcemap": false,
|
|
18
|
+
"minify": false
|
|
19
|
+
},
|
|
20
|
+
"tsconfigDefaults": {
|
|
21
|
+
"pathAliasKey": "@/*",
|
|
22
|
+
"compilerOptions": {
|
|
23
|
+
"noEmit": false,
|
|
24
|
+
"noEmitOnError": false,
|
|
25
|
+
"declaration": true,
|
|
26
|
+
"emitDeclarationOnly": false,
|
|
27
|
+
"sourceMap": false,
|
|
28
|
+
"declarationMap": false,
|
|
29
|
+
"strict": true,
|
|
30
|
+
"noImplicitAny": true
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"eslintDefaults": {
|
|
34
|
+
"restrictedImportDepth": 2
|
|
35
|
+
},
|
|
36
|
+
"tmpWatchDefaults": {
|
|
37
|
+
"intervalMs": 500,
|
|
38
|
+
"minIntervalMs": 100,
|
|
39
|
+
"maxIntervalMs": 10000
|
|
40
|
+
},
|
|
41
|
+
"publicFolderName": "public",
|
|
42
|
+
"kafkaLogsTopic": "log",
|
|
43
|
+
"templateRepoUri": "https://github.com/xdloper/api-gpt-svc"
|
|
44
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
6
|
+
const defaults = JSON.parse(readFileSync(path.join(here, 'defaults.json'), 'utf8'))
|
|
7
|
+
|
|
8
|
+
export const packageDefaults = Object.freeze({
|
|
9
|
+
...defaults,
|
|
10
|
+
layoutPaths: Object.freeze({ ...defaults.layoutPaths }),
|
|
11
|
+
buildDefaults: Object.freeze({ ...defaults.buildDefaults }),
|
|
12
|
+
tsconfigDefaults: Object.freeze({
|
|
13
|
+
...defaults.tsconfigDefaults,
|
|
14
|
+
compilerOptions: Object.freeze({ ...defaults.tsconfigDefaults.compilerOptions }),
|
|
15
|
+
}),
|
|
16
|
+
eslintDefaults: Object.freeze({ ...defaults.eslintDefaults }),
|
|
17
|
+
tmpWatchDefaults: Object.freeze({ ...defaults.tmpWatchDefaults }),
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
export const coreVersionPattern = /^\d{2}\.\d{2}\.\d{2}-v\d+$/
|
|
21
|
+
export const semverVersionPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/
|
|
@@ -73,6 +73,18 @@ function stablePackageShape(pkg) {
|
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
+
|
|
77
|
+
export function syncCliDefaults(root = process.cwd()) {
|
|
78
|
+
const src = path.join(root, 'source/utils/constants/defaults.json')
|
|
79
|
+
const dest = path.join(root, 'x/bin/helpers/defaults.json')
|
|
80
|
+
if (!fs.existsSync(src)) return { synced: false, reason: 'missing source' }
|
|
81
|
+
const needs = !fs.existsSync(dest) || fs.statSync(src).mtimeMs > fs.statSync(dest).mtimeMs
|
|
82
|
+
if (!needs) return { synced: false, reason: 'up-to-date', dest }
|
|
83
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
84
|
+
fs.copyFileSync(src, dest)
|
|
85
|
+
return { synced: true, dest }
|
|
86
|
+
}
|
|
87
|
+
|
|
76
88
|
export function syncCliTmpSchema(root = process.cwd(), { force = false } = {}) {
|
|
77
89
|
const srcAbs = path.join(root, CLI_SCHEMA_SOURCE)
|
|
78
90
|
if (!fs.existsSync(srcAbs)) {
|
|
@@ -130,6 +142,7 @@ export function ensureProjectArtifacts(root = process.cwd(), options = {}) {
|
|
|
130
142
|
} = options
|
|
131
143
|
|
|
132
144
|
const schema = syncCliTmpSchema(root, { force: forceSchema })
|
|
145
|
+
const defaults = syncCliDefaults(root)
|
|
133
146
|
const toolchain = syncProjectToolchain(root, { write: writeToolchain })
|
|
134
147
|
let manifest = { synced: false, reason: 'skipped' }
|
|
135
148
|
|
|
@@ -138,5 +151,5 @@ export function ensureProjectArtifacts(root = process.cwd(), options = {}) {
|
|
|
138
151
|
manifest = syncPackageManifest(root, { write: true })
|
|
139
152
|
}
|
|
140
153
|
|
|
141
|
-
return { schema, toolchain, manifest }
|
|
154
|
+
return { schema, defaults, toolchain, manifest }
|
|
142
155
|
}
|
package/x/bin/paths.mjs
CHANGED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
const distRoot = path.join(process.cwd(), 'x', 'dist')
|
|
5
|
+
const TEST_FILE_RE = /\.test\.(js|d\.ts)$/
|
|
6
|
+
|
|
7
|
+
export function cleanDistTests(distDir = distRoot) {
|
|
8
|
+
if (!fs.existsSync(distDir)) {
|
|
9
|
+
return { removed: 0 }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let removed = 0
|
|
13
|
+
|
|
14
|
+
function walk(dir) {
|
|
15
|
+
for (const name of fs.readdirSync(dir)) {
|
|
16
|
+
const abs = path.join(dir, name)
|
|
17
|
+
const stat = fs.statSync(abs)
|
|
18
|
+
if (stat.isDirectory()) {
|
|
19
|
+
walk(abs)
|
|
20
|
+
continue
|
|
21
|
+
}
|
|
22
|
+
if (!TEST_FILE_RE.test(name)) continue
|
|
23
|
+
fs.unlinkSync(abs)
|
|
24
|
+
removed++
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
walk(distDir)
|
|
29
|
+
|
|
30
|
+
function pruneEmptyDirs(dir) {
|
|
31
|
+
for (const name of fs.readdirSync(dir)) {
|
|
32
|
+
const abs = path.join(dir, name)
|
|
33
|
+
if (fs.statSync(abs).isDirectory()) pruneEmptyDirs(abs)
|
|
34
|
+
}
|
|
35
|
+
if (dir !== distDir && fs.readdirSync(dir).length === 0) {
|
|
36
|
+
fs.rmdirSync(dir)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
pruneEmptyDirs(distDir)
|
|
41
|
+
return { removed }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const invoked = process.argv[1] ? path.resolve(process.argv[1]) : ''
|
|
45
|
+
const isMain = invoked.endsWith(`${path.sep}clean-dist-tests.mjs`)
|
|
46
|
+
|
|
47
|
+
if (isMain) {
|
|
48
|
+
const result = cleanDistTests()
|
|
49
|
+
console.log(`clean-dist-tests: removed ${result.removed} file(s)`)
|
|
50
|
+
}
|
|
@@ -46,10 +46,19 @@ function fixJsonImportAttributes(source) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export function fixImportSpecifiersInSource(source, fileDir) {
|
|
49
|
-
|
|
49
|
+
let next = source.replace(/from\s*(['"])(\.\.?\/[^'"]+?)\2/g, (match, quote, spec) => {
|
|
50
50
|
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
51
|
-
return fixed === spec ? match :
|
|
51
|
+
return fixed === spec ? match : `from ${quote}${fixed}${quote}`
|
|
52
52
|
})
|
|
53
|
+
next = next.replace(/import\s*(['"])(\.\.?\/[^'"]+?)\1/g, (match, quote, spec) => {
|
|
54
|
+
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
55
|
+
return fixed === spec ? match : `import ${quote}${fixed}${quote}`
|
|
56
|
+
})
|
|
57
|
+
next = next.replace(/import\s*\(\s*(['"])(\.\.?\/[^'"]+?)\1\s*\)/g, (match, quote, spec) => {
|
|
58
|
+
const fixed = fixRelativeSpecifier(fileDir, spec)
|
|
59
|
+
return fixed === spec ? match : `import(${quote}${fixed}${quote})`
|
|
60
|
+
})
|
|
61
|
+
return next
|
|
53
62
|
}
|
|
54
63
|
|
|
55
64
|
export function fixDistImports(distDir = distRoot) {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
const root = process.cwd()
|
|
6
|
+
const src = path.join(root, 'source/utils/constants/defaults.json')
|
|
7
|
+
const dest = path.join(root, 'x/bin/helpers/defaults.json')
|
|
8
|
+
|
|
9
|
+
if (!fs.existsSync(src)) {
|
|
10
|
+
console.error('sync-cli-defaults: source defaults.json missing')
|
|
11
|
+
process.exit(1)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
15
|
+
fs.copyFileSync(src, dest)
|
|
16
|
+
console.log('sync-cli-defaults: copied → x/bin/helpers/defaults.json')
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BaseApiClient as t,CoreClientsEnum as s}from"../../utils
|
|
1
|
+
import{BaseApiClient as t,CoreClientsEnum as s}from"../../utils";import{bindLoaderTmpSync as i}from"../../utils";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 +1 @@
|
|
|
1
|
-
import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils
|
|
1
|
+
import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils";import{Constants as a}from"../../utils";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}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import y from"qs";import C from"../../loader/logger
|
|
1
|
+
import y from"qs";import C from"../../loader/logger";import S from"../../loader/system";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";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)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from"../../utils
|
|
1
|
+
import{DTO as u}from"@xrystal/dto/dto";import{bindLoaderTmpSync as m}from"../../utils";import{FrameworkEnum as c,parseFramework as f}from"../../utils";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)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LoggerLayerEnum as a,registerGracefulShutdown as s}from"../../utils
|
|
1
|
+
import{LoggerLayerEnum as a,registerGracefulShutdown as s}from"../../utils";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()}}
|
package/x/dist/loader/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import System from"./system
|
|
1
|
+
import System from"./system";import Configs from"./configs";import KafkaForCore from"./kafka";import Logger from"./logger";import Events from"./events";import Localizations from"./localizations";import DtoRuntime from"./dto";import Controller from"./controller";import Service from"./service";import Clients from"./clients";export{System,Configs,Logger,Events,Localizations,DtoRuntime,Controller,Service,Clients,KafkaForCore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils
|
|
1
|
+
import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils";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 +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
|
|
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";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}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import l,{format as o}from"winston";import p from"winston-transport";import"winston-daily-rotate-file";import d from"node:path";import{Partitioners as y}from"kafkajs";import{LoggerLayerEnum as r}from"../../utils
|
|
1
|
+
import l,{format as o}from"winston";import p from"winston-transport";import"winston-daily-rotate-file";import d from"node:path";import{Partitioners as y}from"kafkajs";import{LoggerLayerEnum as r}from"../../utils";import{LogDTO as k}from"../../utils";import{bindLoaderTmpSync as u}from"../../utils";import{getRequestId as f}from"../../utils";class h extends p{service;constructor(e,t){super(e);this.service=t}log(e,t){setImmediate(()=>this.emit("logged",e));this.service.logToKafka(e).finally(()=>t())}}const v={critical:r.CRITICAL,error:r.ERROR,warn:r.WARN,info:r.INFO,http:r.HTTP,debug:r.DEBUG},w={critical:"red",error:"magenta",warn:"yellow",info:"green",http:"cyan",debug:"blue"};export default class Logger{serviceName="";isKafkaReady=!1;kafkaProducer=null;kafkaLogsTopic="";winston;#t;#e;#s;constructor({system:e,configs:t,kafkaForCore:a}){this.#t=e;this.#e=t;this.#s=a}onDispose=async()=>{await this.teardownLogger()};onInit=async()=>{await this.syncFromTmp();u(this)};syncFromTmp=async()=>{await this.teardownLogger();this.serviceName=this.#t?.tmp?.configs?.service?.name??"";this.kafkaLogsTopic=this.#e?.all?.kafkaLogsTopic;l.addColors(w);const e=this.#t?.tmp?.configs?.service?.loaders?.loggers,{kafkaBrokers:t,isKafkaPassive:a}=this.#e.all,i=t?String(t).split(",").map((m)=>m.trim()):[];if(a===!1&&i.length>0&&this.#s.instance){this.kafkaProducer=this.#s.instance.producer({createPartitioner:y.DefaultPartitioner,retry:{initialRetryTime:500,retries:5}});try{await this.kafkaProducer?.connect();this.isKafkaReady=!0}catch{this.isKafkaReady=!1}}const c=e?.loadPath||"logs",s=e?.logLevel||e?.loggerLevel||"info";this.winstonLoader({loadPath:d.join(this.#e.all.rootFolderPath,c),loggerLevel:s})};teardownLogger=async()=>{if(this.kafkaProducer){try{await this.kafkaProducer.disconnect()}catch{}this.kafkaProducer=null}this.isKafkaReady=!1;if(this.winston){this.winston.clear();this.winston.close()}};winstonLoader=({loadPath:e,loggerLevel:t})=>{const{combine:a,timestamp:i,json:n,errors:c}=o,s=this.getTracingFormat(),m=a(s,i({format:"YYYY-MM-DD HH:mm:ss"}),c({stack:!0}),n({replacer:this.safeReplacer})),g=[new l.transports.Console({format:this.getConsoleFormat()}),new l.transports.DailyRotateFile({filename:d.resolve(e,"error","%DATE%_error.log"),level:"error",format:m,maxSize:"2mb",maxFiles:"7d"}),new l.transports.DailyRotateFile({filename:d.resolve(e,"critical","%DATE%_critical.log"),level:"critical",format:m,maxSize:"2mb",maxFiles:"14d"})];if(this.isKafkaReady&&this.kafkaProducer)g.push(new h({level:t},this));this.winston=l.createLogger({level:t,levels:v,format:s,transports:g});return this.winston};safeReplacer=(e,t)=>{if(t instanceof Headers)return Object.fromEntries(t.entries());if(t instanceof Error)return{message:t.message,stack:t.stack};return t};getTracingFormat=o((e)=>{if(e.id)return e;const t=f();if(t)e.id=t;return e});getConsoleFormat(){return o.combine(this.getTracingFormat(),o.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),o.colorize({all:!0}),o.printf((e)=>{const t=typeof e.message==="object"?JSON.stringify(e.message,this.safeReplacer):e.message,a=e.id?` : id: ${e.id}`:"",i=e.payload?`
|
|
2
2
|
Payload: ${JSON.stringify(e.payload,this.safeReplacer)}`:"",n=e.code?` [Code: ${e.code}]`:"";return`${e.timestamp} [${this.serviceName}] ${e.level}${n}: ${t}${a}${i}`}))}normalizeLevel(e){return typeof e==="string"?e.toLowerCase():r[e].toLowerCase()}normalizeMessage(e){if(e===void 0||e===null)return;return typeof e==="string"?e:JSON.stringify(e,this.safeReplacer)}buildLogBody(e){return k.schema({level:this.normalizeLevel(e.level),service:this.serviceName,message:this.normalizeMessage(e.message),payload:e.payload,code:e.code,timestamp:e.timestamp??new Date().toISOString(),id:e.id??f()??void 0,env:this.#e.all.env}).build()}async logToKafka(e){if(!this.kafkaProducer||!this.isKafkaReady)return;try{const t=this.buildLogBody({level:e.level,message:e.message,payload:e.payload,code:e.code,id:e.id,timestamp:e.timestamp});await this.kafkaProducer.send({topic:this.kafkaLogsTopic,messages:[{value:JSON.stringify(t,this.safeReplacer)}],acks:1})}catch(t){this.isKafkaReady=!1}}log(e,t,a,i){const c=typeof e==="object"&&e!==null&&"level"in e?e:{level:e,message:t,payload:a,code:i},s=this.buildLogBody(c);this.winston.log(s.level,s.message,{id:s.id,payload:s.payload,code:s.code,service:s.service,timestamp:s.timestamp,env:s.env})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils
|
|
1
|
+
import{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils";import{normalizeTmpDocument as x}from"../../utils/helpers/tmp/tmp-schema";export default class System{_core={};_tmp={};cwd=process.cwd();g=k;onInit=async({core:j})=>{this._core=j;await this.applyTmp(this._core._);v((b)=>void this.applyTmp(b))};async applyTmp(j){this._tmp=x(j);const b=this._tmp.configs;w(b);this.g.configureFromTmp(this._tmp);await q(b)}get core(){return this._core}get tmp(){return this._tmp}}
|
package/x/dist/project/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __dirname="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/project";import w from"path";import{System as G,Configs as I,Logger as J,Events as N,Localizations as O,DtoRuntime as Q,Clients as U,Controller as V,KafkaForCore as W}from"../loader
|
|
1
|
+
var __dirname="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/project";import w from"path";import{System as G,Configs as I,Logger as J,Events as N,Localizations as O,DtoRuntime as Q,Clients as U,Controller as V,KafkaForCore as W}from"../loader";import{Constants as X,getCore as Y,x as Z}from"../utils";import{ensureCoreTmpEntry as _,isCorePackageRoot as $}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as v}from"../utils/helpers/tmp/tmp-loader";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader";export const core=Y(),coreInit=async(q)=>{const{locales:b}=q;if(b)globalThis.__LOCAL_MESSAGES__=b};let A=!1;const x=async(q={})=>{if(A)return core;const b=process.cwd();if($(b))_(b);v();try{await(await Z.load([w.join(__dirname,"..","loader","**/*.{ts,js}")],{exclude:[w.join(__dirname,"..","utils","**/class.x.{ts,js}")]})).initialize([{service:G,props:{core}},{service:I,props:{}},{service:W,props:{}},{service:J,props:{}},{service:N,props:{}},{service:O,props:{}},{service:Q,props:{}},{service:V,props:{}},{service:U,props:{}}]);A=!0;return core}catch(j){const B=j instanceof Error?j.message:String(j);console.error(`[${X.packageName} core failure]: ${B}`);throw j}};export default x;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"node:path";import{packageRootDir as a}from"../../utils/package-root";import t from"./defaults.json" with { type: 'json' };export const packageDefaults=Object.freeze({...t,layoutPaths:Object.freeze({...t.layoutPaths}),buildDefaults:Object.freeze({...t.buildDefaults}),tsconfigDefaults:Object.freeze({...t.tsconfigDefaults,compilerOptions:Object.freeze({...t.tsconfigDefaults.compilerOptions})}),eslintDefaults:Object.freeze({...t.eslintDefaults}),tmpWatchDefaults:Object.freeze({...t.tmpWatchDefaults})}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const o=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static mainSourceFolder=packageDefaults.mainSourceFolder;static layoutPaths=packageDefaults.layoutPaths;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static bundledCoreTmpPath=e.join(a,packageDefaults.packageRootFolder,o)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as w}from"node:async_hooks";export const runContextStorage=new w;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(m,j){return runContextStorage.run(m,j)}export function runWithRequestId(m,j,v="http"){return runWithContext({requestId:m,kind:v},j)}export function runWithTrace(m,j,v){return runWithContext({requestId:m,kind:"job",label:v},j)}export function patchRunContext(m){const j=getRunContext();if(!j)return;Object.assign(j,m)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from"../../../utils/helpers/context/controller-store
|
|
1
|
+
import{AsyncLocalStorage as w}from"node:async_hooks";export const runContextStorage=new w;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(m,j){return runContextStorage.run(m,j)}export function runWithRequestId(m,j,v="http"){return runWithContext({requestId:m,kind:v},j)}export function runWithTrace(m,j,v){return runWithContext({requestId:m,kind:"job",label:v},j)}export function patchRunContext(m){const j=getRunContext();if(!j)return;Object.assign(j,m)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from"../../../utils/helpers/context/controller-store";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import M from"handlebars";import{Constants as I,ProtocolEnum as J,TmpFileLoader as Q}from"../../../utils/index.js";import{controllerContextStorage as U}from"../../../utils/helpers/context/controller-store
|
|
1
|
+
import M from"handlebars";import{Constants as I,ProtocolEnum as J,TmpFileLoader as Q}from"../../../utils/index.js";import{controllerContextStorage as U}from"../../../utils/helpers/context/controller-store";import{getTmpSnapshot as V}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as X}from"../../../utils/helpers/core/paths";import{parseProtocol as Y}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export const getCore=()=>({_:V()}),getTmpConfig=({root:q=process.cwd(),tmpFileName:z=I.tmpBaseName,ext:B=I.tmpExtension}={})=>{const D=X(q,z,B);if(!D)throw Error(`${z}${B.startsWith(".")?B:`.${B}`} file not found`);return new Q({filePath:D}).getResolvedTmpFile()};export function resolveObjWithHandlebars(q,z){if(typeof q==="string")return M.compile(q)(z);else if(typeof q==="object"&&q!==null)for(const B in q)q[B]=resolveObjWithHandlebars(q[B],z);return q}export const withProtocol=async(q,z=J.HTTP)=>{const B=Y(z),D=U.getStore();if(D)D.protocol=B;return await q()},protocol=async(q,z=J.HTTP)=>withProtocol(q,z),argvsConverter=(q)=>{const z=q?.slice(2),B={};z.forEach((D)=>{if(D.startsWith("--")){console.log(D);const[G,K]=D.split("=");B[G.replace("--","")]=K||""}});return B},findExt=(q)=>{const z=q.split(".");return z[z.length-1]},changeExtensions=(q,z)=>{return q.replace(findExt(q),z)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import U from"node:fs";import I from"node:path";import z from"yaml";import{Constants as J}from"../../../utils/constants
|
|
1
|
+
import U from"node:fs";import I from"node:path";import z from"yaml";import{Constants as J}from"../../../utils/constants";import{findAllFilesRecursively as L,findFileRecursively as A}from"../../../utils/helpers/core/paths";import{normalizeTmpDocument as D,readTmpServiceBlock as B,normalizeRootFolder as b,normalizeSourceFolder as x,resolveServiceLayoutPaths as k}from"../../../utils/helpers/tmp/tmp-schema";function M(E,q){return`${E}${q.startsWith(".")?q:`.${q}`}`}export function coreCanonicalTmpPath(E=process.cwd()){return I.join(I.resolve(E),J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension))}export function assertCoreTmpGuard(E,q){if(!isCorePackageRoot(E))return;const H=coreCanonicalTmpPath(E);if(I.resolve(q)!==I.resolve(H))throw Error(`@xrystal/core: tmp.yml must stay at ${J.packageRootFolder}/tmp.yml (expected ${H}, got ${q})`)}function N(E,q){const H=I.resolve(E),K=I.resolve(q);return L(H,J.tmpBaseName,J.tmpExtension).filter((Q)=>I.resolve(Q)!==K)}export function ensureCoreTmpEntry(E=process.cwd(),q={}){const H=I.resolve(E);if(!isCorePackageRoot(H))throw Error("ensureCoreTmpEntry is only for @xrystal/core package root");const K=coreCanonicalTmpPath(H),Q=N(H,K);if(Q.length>0){const X=Q.map((W)=>I.relative(H,W)).join(", ");throw Error(`@xrystal/core: tmp.yml must only exist under ${J.packageRootFolder}/. Remove extra copies: ${X}`)}if(U.existsSync(K)){assertCoreTmpGuard(H,K);return{tmpFilePath:K,created:!1,layout:buildTmpLayout(H,_(K),K)}}return ensureTmpFile(H,{...q,patchServiceName:!1})}function S(E,q,H){const K=I.resolve(E);if(isCorePackageRoot(K)){const Q=coreCanonicalTmpPath(K);return U.existsSync(Q)?Q:null}return A(K,q,H)}function _(E){return z.parse(U.readFileSync(E,"utf8"))}export function isCorePackageRoot(E){const q=I.join(I.resolve(E),"package.json");if(!U.existsSync(q))return!1;try{return JSON.parse(U.readFileSync(q,"utf8")).name===J.packageName}catch{return!1}}export function resolveRootFolderPath(E,q,H){const K=D(E).configs,Q=B(K);if(Q.paths?.root?.trim())return b(Q.paths.root);const X=E.project;if(typeof X?.name==="string"&&X.name.trim())return X.name.trim();const W=I.relative(I.resolve(H),I.dirname(I.resolve(q)));if(W&&W!==".")return W;return J.packageRootFolder}export function resolveLayoutPaths(E){const q=B(E);return k(q)}export function resolveMainFolderPath(E){const q=B(E);if(q.paths?.source?.trim())return x(q.paths.source);return J.mainSourceFolder}export function buildTmpLayout(E,q,H){const K=I.resolve(E),Q=q?D(q).configs:void 0,X=q&&H&&!isCorePackageRoot(K)?resolveRootFolderPath(q,H,K):J.packageRootFolder,W=I.join(K,X),Y=resolveLayoutPaths(Q),V=resolveMainFolderPath(Q),Z={tests:I.join(W,Y.tests),environments:I.join(W,Y.environments),dist:I.join(W,Y.dist)};return{projectRoot:K,rootFolderPath:X,rootFolderAbs:W,tmpFilePath:H,mainFolderPath:V,paths:Y,pathsAbs:Z}}export function resolveTmpLayout(E=process.cwd(),q={}){const H=q.tmpFileName??J.tmpBaseName,K=q.ext??J.tmpExtension,Q=S(E,H,K);if(!Q)throw Error(`${M(H,K)} not found under ${I.resolve(E)}`);if(isCorePackageRoot(I.resolve(E)))assertCoreTmpGuard(E,Q);return buildTmpLayout(E,_(Q),Q)}export function resolveTmpLayoutOrDefaults(E=process.cwd()){const q=S(E,J.tmpBaseName,J.tmpExtension);if(!q)return buildTmpLayout(E,null,null);return buildTmpLayout(E,_(q),q)}export function resolveBundledCoreTmpPath(E=process.cwd()){if(U.existsSync(J.bundledCoreTmpPath))return J.bundledCoreTmpPath;let q=I.resolve(E);while(q!==I.dirname(q)){const H=I.join(q,"node_modules","@xrystal","core",J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension));if(U.existsSync(H))return H;const K=I.join(q,"package.json");if(U.existsSync(K)){if(JSON.parse(U.readFileSync(K,"utf8")).name===J.packageName){const X=I.join(q,J.packageRootFolder,M(J.tmpBaseName,J.tmpExtension));if(U.existsSync(X))return X}}q=I.dirname(q)}throw Error("@xrystal/core bundled x/tmp.yml not found")}export function ownerTmpFilePath(E=process.cwd(),q){const H=q??resolveTmpLayoutOrDefaults(E);return I.join(H.rootFolderAbs,M(J.tmpBaseName,J.tmpExtension))}export function ensureTmpFile(E=process.cwd(),q={}){const H=I.resolve(E),K=q.patchServiceName??!0;if(isCorePackageRoot(H)){const V=coreCanonicalTmpPath(H),Z=N(H,V);if(Z.length>0){const $=Z.map((w)=>I.relative(H,w)).join(", ");throw Error(`@xrystal/core: tmp.yml must only exist under ${J.packageRootFolder}/. Remove extra copies: ${$}`)}if(U.existsSync(V)){assertCoreTmpGuard(H,V);return{tmpFilePath:V,created:!1,layout:buildTmpLayout(H,_(V),V)}}}else{const V=A(H,J.tmpBaseName,J.tmpExtension);if(V)return{tmpFilePath:V,created:!1,layout:buildTmpLayout(H,_(V),V)}}const Q=q.templatePath??resolveBundledCoreTmpPath(H);if(!U.existsSync(Q))throw Error("@xrystal/core bundled x/tmp.yml not found");const X=buildTmpLayout(H,null,null);U.mkdirSync(X.rootFolderAbs,{recursive:!0});const W=ownerTmpFilePath(H,X);let Y=U.readFileSync(Q,"utf8");if(K)try{const V=I.join(H,"package.json");if(U.existsSync(V)){const Z=JSON.parse(U.readFileSync(V,"utf8")),$=typeof Z.name==="string"?Z.name.replace(/^@/,"").replace(/\//g,"-"):null;if($){const w=z.parse(Y),G=w.configs??{},O=G.service;if(typeof O==="object"&&O!==null&&!Array.isArray(O))O.name=$;else G.service={name:$};w.configs=G;Y=z.stringify(w)}}}catch{}U.writeFileSync(W,Y);return{tmpFilePath:W,created:!0,layout:buildTmpLayout(H,_(W),W)}}export function resolveTmpLayoutEnsured(E=process.cwd()){return ensureTmpFile(E).layout}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PolarityTypeEnum as $}from"../../../utils/models
|
|
1
|
+
import{PolarityTypeEnum as $}from"../../../utils/models";export function dateZoneConverter({polarity:e,date:o,zone:n,factor:r=1000}){let s=null;if(e===$.NEGATIVE)s=o.getTime()-r*n;else s=o.getTime()+r*n;return new Date(s).toISOString()}export function convertDate(e,o="/",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function convertTime(e,o=":",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function getDateAndTime({getDate:e=!0,getTime:o=!0,dateCharacter:n="-",timeCharacter:r=":",separatorCharacter:s="&"}){const t=new Date;let u="";if(!e&&!o)throw Error("Invalid options! Required one true value");if(e){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0");u=`${t.getFullYear()}${n}${a}${n}${i}`}if(o){const i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0"),S=t.getSeconds().toString().padStart(2,"0");u=`${i}${r}${a}${r}${S}`}if(e&&o){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0"),S=t.getFullYear(),c=t.getHours().toString().padStart(2,"0"),g=t.getMinutes().toString().padStart(2,"0"),p=t.getSeconds().toString().padStart(2,"0");u=`${S}${n}${a}${n}${i}${s}${c}${r}${g}${r}${p}`}return u}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expressSink as J}from"@xrystal/dto/express";import{nodeSink as K}from"@xrystal/dto/node";import{fetchSink as L}from"@xrystal/dto/fetch";import{elysiaSink as M}from"@xrystal/dto/elysia";import{websocketSink as N}from"@xrystal/dto/websocket";import{socketIoSink as Q}from"@xrystal/dto/socketio";import{FrameworkEnum as z,ProtocolEnum as C}from"../../../utils/models
|
|
1
|
+
import{expressSink as J}from"@xrystal/dto/express";import{nodeSink as K}from"@xrystal/dto/node";import{fetchSink as L}from"@xrystal/dto/fetch";import{elysiaSink as M}from"@xrystal/dto/elysia";import{websocketSink as N}from"@xrystal/dto/websocket";import{socketIoSink as Q}from"@xrystal/dto/socketio";import{FrameworkEnum as z,ProtocolEnum as C}from"../../../utils/models";import{getFramework as T}from"../../../utils/helpers/framework";import{getDtoRuntime as U}from"../../../utils/helpers/runtime";export{expressSink}from"@xrystal/dto/express";export{nodeSink}from"@xrystal/dto/node";export{fetchSink}from"@xrystal/dto/fetch";export{elysiaSink}from"@xrystal/dto/elysia";export{websocketSink}from"@xrystal/dto/websocket";export{socketIoSink}from"@xrystal/dto/socketio";export{dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";const V=(j)=>!!j&&typeof j==="object"&&("body"in j)&&("statusCode"in j),W=(j)=>j instanceof Response||j instanceof Blob||j instanceof Uint8Array||j instanceof ArrayBuffer,G=(j)=>j.socket??j.ctx?.ws??j.ctx,X=()=>U().config.socket?.event??"response";export function dispatchResult(j,q,B){if(j===void 0||j===null)return;if(W(j))return j;if(!V(j))return j;if(q.protocol===C.SOCKETIO||q.framework===z.SOCKETIO){Q(G(q),X()).dispatch(j);return}if(q.protocol===C.WEBSOCKET||q.framework===z.WEBSOCKET){N(G(q)).dispatch(j);return}const H=q.framework??T(),A=B;switch(H){case z.EXPRESS:if(A&&!A.headersSent)J(B).dispatch(j);return;case z.NODE:if(A&&!A.headersSent)K(B).dispatch(j);return;case z.FETCH:return L.dispatch(j);case z.ELYSIA:default:return M(q.ctx?.set??{}).dispatch(j)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRuntimeTmpConfigs as q}from"../../../utils/helpers/tmp/runtime-tmp
|
|
1
|
+
import{getRuntimeTmpConfigs as q}from"../../../utils/helpers/tmp/runtime-tmp";import{FrameworkEnum as j}from"../../../utils/models";const x=new Set(Object.values(j));export function parseFramework(b){const c=b?String(b).toLowerCase():void 0;return c&&x.has(c)?c:j.ELYSIA}export function getFramework(b){if(b)return b;try{return parseFramework(q()?.service?.framework)}catch{return j.ELYSIA}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol";import{getFramework as M}from"../../../utils/helpers/framework";import{runAction as I}from"../../../utils/helpers/handlers/execute";export function toRealtimeHandler(z,D){const B=(b)=>{const J=L(b,D);return I({socket:b,ctx:{ws:b},protocol:J},z)},j=(b)=>B(b);j.with=(b)=>()=>B(b);return j}export const toHandler=(z,D)=>{const B=D??M();switch(B){case G.ELYSIA:return(j)=>I({framework:B,ctx:j},z);case G.FETCH:return(j,b)=>I({framework:B,ctx:{request:j,...b}},z);case G.NODE:return(j,b)=>I({framework:B,req:j,res:b},z,b);case G.EXPRESS:return(j,b,J)=>{I({framework:B,req:j,res:b,metadata:{locals:b.locals||{}}},z,b).catch(J)};case G.WEBSOCKET:case G.SOCKETIO:throw Error('[xrystal] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })');default:return(j)=>I({framework:G.ELYSIA,ctx:j},z)}},toWebSocket=(z,D)=>toRealtimeHandler(D,K.WEBSOCKET)(z),toSocketIo=(z,D)=>toRealtimeHandler(D,K.SOCKETIO)(z);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models
|
|
1
|
+
import{randomUUID as Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models";import{runControllerStore as Y}from"../../../utils/helpers/context";import{runWithRequestId as Z}from"../../../utils/helpers/context";import{dispatchResult as _}from"../../../utils/helpers/dispatch";import{getFramework as $}from"../../../utils/helpers/framework";import{attachSocketTransport as x,isRealtimeProtocol as H}from"../../../utils/helpers/protocol";import{getDtoRuntime as J}from"../../../utils/helpers/runtime";export const runController=Y;const B=(b)=>({framework:b.framework??(H(b.protocol)?void 0:$()),protocol:b.protocol??X.HTTP,...b,metadata:{locals:{},...b.metadata}}),M=(b,z)=>{if(!b)return;if(b instanceof Headers)return b.get(z)??b.get(z.toLowerCase());if(typeof b.get==="function"){const j=b.get;return j(z)??j(z.toLowerCase())}const A=b;return A[z]??A[z.toLowerCase()]},K=(b)=>{const z=b.ctx??{},A=b.req??{},j=A.headers??z.request?.headers;return b.requestId??z.requestId??A.ctx?.requestId??M(j,"x-request-id")??M(j,"x-correlation-id")??""},T=(b)=>{const z=String(K(b)||Q());b.requestId=z;b.ctx={...b.ctx,requestId:z};if(b.req)b.req.ctx={...b.req.ctx,requestId:z};return z},W=(b)=>{if(b.framework!==V.FETCH||b.ctx?.builder)return;const z=b.ctx?.request??b.req;if(!(z instanceof Request))return;b.ctx={...b.ctx,...J().forRequest(z)};if(b.ctx.requestId)b.requestId=String(b.ctx.requestId)},v=async(b,z,A)=>{const j=_(b,z,A),G=A;if(j instanceof Response&&G?.send){G.status?.(j.status);j.headers.forEach((N,O)=>G.setHeader?.(O,N));const L=j.headers.get("content-type")||"";if(L.includes("json")||L.includes("text/"))return G.send(await j.text());return G.send(Buffer.from(await j.arrayBuffer()))}return j},y=(b)=>H(b.protocol)?"ws":"http";export async function runAction(b,z,A){const j=B(b);if(H(j.protocol)&&j.socket&&!j.socket.builder)x(j.socket,j.protocol,J());W(j);const G=T(j);return Z(G,()=>runController(j,async()=>v(await z(),j,A)),y(j))}export function configureDto(b,z){return J().configure(b,z)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as A}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as A}from"../../../utils/models";import{createDtoMiddleware as q}from"../../../utils/helpers/middleware";import{attachSocketTransport as B,detectSocketProtocol as C,resolveRealtimeMiddlewareProtocol as D}from"../../../utils/helpers/protocol";import{getDtoRuntime as j}from"../../../utils/helpers/runtime";export{runAction,runController,configureDto}from"../../../utils/helpers/handlers/execute";export{toHandler,toRealtimeHandler,toWebSocket,toSocketIo}from"../../../utils/helpers/handlers/adapters";export{getFramework}from"../../../utils/helpers/framework";export{dispatchResult}from"../../../utils/helpers/dispatch";export{getRequestId,getRunContext,runWithContext,runWithRequestId,runWithTrace}from"../../../utils/helpers/context";export{G,propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey,GStoreScopeEnum}from"../../../utils/helpers/state";export{bindLoaderTmpSync,getRuntimeTmpConfigs,setRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,getTmpSnapshot,onTmpReload}from"../../../utils/helpers/tmp";export{normalizeFrameworkKind,createDtoMiddleware,resolveDtoAdapter}from"../../../utils/helpers/middleware";export{resolveCtrOptions}from"../../../utils/helpers/protocol/options";export{parseProtocol,getConfiguredProtocols,getConfiguredRealtimeProtocols,defaultRealtimeProtocolFromConfig,getDefaultRealtimeProtocol,resolveRealtimeMiddlewareProtocol,detectSocketProtocol,isRealtimeProtocol,isHttpProtocol,resolveProtocolsFromConfig,REALTIME_MIDDLEWARE_HINT}from"../../../utils/helpers/protocol";export{getDtoRuntime}from"../../../utils/helpers/runtime";export const dtoMiddleware=(b)=>q(j(),b);export function realtimeMiddleware(b){const z=D(b);return(u,y)=>{try{const h=C(u,z);B(u,h,j());y?.()}catch(h){y?.(h instanceof Error?h:Error(String(h)))}}}export const websocketMiddleware=(b)=>b?q(j(),b):realtimeMiddleware("ws"),socketIoMiddleware=(b)=>b?q(j(),b??A.SOCKETIO):realtimeMiddleware("socketio");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{default as pic}from"picocolors";export*from"../../utils/helpers/core
|
|
1
|
+
export{default as pic}from"picocolors";export*from"../../utils/helpers/core";export*from"../../utils/helpers/path";export*from"../../utils/helpers/is";export*from"../../utils/helpers/id";export*from"../../utils/helpers/validates";export*from"../../utils/helpers/ip";export*from"../../utils/helpers/hash/crypto";export*from"../../utils/helpers/string";export*from"../../utils/helpers/objects";export*from"../../utils/helpers/locales";export*from"../../utils/helpers/timer";export*from"../../utils/helpers/date";export*from"../../utils/helpers/math";export*from"../../utils/helpers/regex/checkSpecialRegexControl";export*from"../../utils/helpers/filters";export*from"../../utils/helpers/framework";export*from"../../utils/helpers/protocol";export*from"../../utils/helpers/dto";export*from"../../utils/helpers/dispatch";export*from"../../utils/helpers/middleware";export*from"../../utils/helpers/context";export*from"../../utils/helpers/tmp";export*from"../../utils/helpers/state";export*from"../../utils/helpers/handlers";export*from"../../utils/helpers/runtime";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as j}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as j}from"../../../utils/models";import{getFramework as x,parseFramework as C}from"../../../utils/helpers/framework";const G={express:j.EXPRESS,elysia:j.ELYSIA,node:j.NODE,fetch:j.FETCH,websocket:j.WEBSOCKET,ws:j.WEBSOCKET,socketio:j.SOCKETIO};export function normalizeFrameworkKind(b){if(b===void 0)return x();const q=typeof b==="object"&&b!==null&&"framework"in b?b.framework:b;if(!q)return x();const B=String(q).toLowerCase().replace(/[-_\s]/g,"");return G[B]??C(q)}export function resolveDtoAdapter(b,q){switch(q){case j.ELYSIA:return b.elysia();case j.NODE:return b.node();case j.SOCKETIO:return b.socketIo();case j.WEBSOCKET:return b.websocket();case j.FETCH:return null;case j.EXPRESS:return b.express();default:return b.elysia()}}export function createDtoMiddleware(b,q){return resolveDtoAdapter(b,normalizeFrameworkKind(q))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ProtocolEnum as h}from"../../../utils/models/enums
|
|
1
|
+
import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as J}from"../../../utils/helpers/tmp/runtime-tmp";const G={http:h.HTTP,https:h.HTTPS,ws:h.WEBSOCKET,websocket:h.WEBSOCKET,socketio:h.SOCKETIO,socket:h.SOCKETIO},REALTIME_MIDDLEWARE_HINT='[xrystal] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")';export function parseProtocol(b){if(!b)return h.HTTP;const j=String(b).toLowerCase().replace(/[-_\s.]/g,"");if(G[j])return G[j];return Object.values(h).includes(String(b))?b:h.HTTP}export function isRealtimeProtocol(b){return b===h.WEBSOCKET||b===h.SOCKETIO}export function isHttpProtocol(b){return!b||b===h.HTTP||b===h.HTTPS}function B(){return J()?.service}export function resolveProtocolsFromConfig(b){const j=b?.protocols;if(!j)return[h.HTTP];return(Array.isArray(j)?j:[j]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(B())}catch{return[h.HTTP,h.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(b){return resolveProtocolsFromConfig(b).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(b){const j=getConfiguredRealtimeProtocols(b);if(j.length===1)return j[0];if(j.length>1)return;return h.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(B())}catch{return h.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(b,j){if(b!==void 0&&b!==null&&b!=="")return parseProtocol(b);let q=j;if(!q)try{q=B()}catch{return h.WEBSOCKET}const z=getConfiguredRealtimeProtocols(q);if(z.length===1)return z[0];if(z.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return h.WEBSOCKET}export function detectSocketProtocol(b,j){if(j)return j;const q=b;if(q?.__xrystalProtocol)return q.__xrystalProtocol;return h.WEBSOCKET}export function attachSocketTransport(b,j,q){const z=b;if(j===h.SOCKETIO)q.attachSocketIo(b);else q.attachWebSocket(b);z.__xrystalProtocol=j}export{REALTIME_MIDDLEWARE_HINT};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as e,ProtocolEnum as o}from"../../../utils/models
|
|
1
|
+
import{FrameworkEnum as e,ProtocolEnum as o}from"../../../utils/models";import{parseProtocol as t}from"../../../utils/helpers/protocol";export function resolveCtrOptions(r){if(r===void 0)return{protocol:o.HTTP};if(typeof r==="string"){if(Object.values(e).includes(r))return{framework:r,protocol:o.HTTP};return{protocol:t(r)}}return{protocol:o.HTTP,...r}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as t}from"../../../utils/models
|
|
1
|
+
import{x as t}from"../../../utils/models";export const DTO_RUNTIME_KEY="dtoRuntime";export function getDtoRuntime(){return t.get(DTO_RUNTIME_KEY)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{getDtoRuntime,DTO_RUNTIME_KEY}from"../../../utils/helpers/runtime/dto-access
|
|
1
|
+
export{getDtoRuntime,DTO_RUNTIME_KEY}from"../../../utils/helpers/runtime/dto-access";export{gracefulShutdown,isShuttingDown,registerGracefulShutdown}from"../../../utils/helpers/runtime/shutdown";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader
|
|
1
|
+
import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader";import{clearRuntimeTmpConfigs as z}from"../../../utils/helpers/tmp/runtime-tmp";import A from"../../../utils/models/classes/class.x";let k=!1,q=!1;export function isShuttingDown(){return k}export async function gracefulShutdown(b=0){if(k){process.exit(b);return}k=!0;try{await A.shutdown()}catch{}y();z();await new Promise((j)=>setImmediate(j));process.exit(b)}export function registerGracefulShutdown(){if(q)return;q=!0;const b=(j)=>{gracefulShutdown(j==="SIGINT"?130:j==="SIGTERM"?143:0)};process.on("SIGINT",b);process.on("SIGTERM",b)}
|