@xrystal/core 3.51.6 → 3.52.1

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 (121) hide show
  1. package/README.md +35 -1
  2. package/package.json +2 -1
  3. package/x/bin/commands/create.mjs +44 -0
  4. package/x/bin/commands/projects.mjs +53 -0
  5. package/x/bin/commands/sync.mjs +49 -1
  6. package/x/bin/commands/tmp.mjs +1 -1
  7. package/x/bin/helpers/.generated/.generated-from +2 -0
  8. package/x/bin/helpers/.generated/seed-from-tmp.mjs +25 -31
  9. package/x/bin/helpers/.generated/tmp-schema.mjs +156 -96
  10. package/x/bin/helpers/.generated/workspace.mjs +402 -0
  11. package/x/bin/helpers/.generated/xrystal-home-registry.mjs +310 -0
  12. package/x/bin/helpers/build-config.mjs +3 -2
  13. package/x/bin/helpers/cli-help.mjs +3 -1
  14. package/x/bin/helpers/project-artifacts.mjs +10 -0
  15. package/x/bin/helpers/tmp-config.mjs +13 -12
  16. package/x/bin/helpers/tmp-layout.mjs +28 -52
  17. package/x/bin/helpers/tmp-schema.mjs +9 -3
  18. package/x/bin/helpers/workspace-resolve.mjs +11 -0
  19. package/x/bin/helpers/workspace-scaffold.mjs +23 -0
  20. package/x/bin/helpers/xrystal-registry.mjs +13 -0
  21. package/x/bin/main-cli.js +2 -0
  22. package/x/dist/index.js +5 -1
  23. package/x/dist/loader/clients/index.js +22 -1
  24. package/x/dist/loader/configs/index.js +97 -1
  25. package/x/dist/loader/controller/index.js +267 -1
  26. package/x/dist/loader/dto/index.js +92 -1
  27. package/x/dist/loader/events/index.js +39 -1
  28. package/x/dist/loader/index.js +13 -1
  29. package/x/dist/loader/kafka/index.js +142 -1
  30. package/x/dist/loader/kafka/resolve-ssl.js +23 -1
  31. package/x/dist/loader/localizations/index.js +46 -1
  32. package/x/dist/loader/logger/index.js +229 -2
  33. package/x/dist/loader/mongo/index.js +52 -1
  34. package/x/dist/loader/mongo/resolve-connect.js +16 -1
  35. package/x/dist/loader/redis/index.js +57 -1
  36. package/x/dist/loader/redis/resolve-socket.js +31 -1
  37. package/x/dist/loader/registry/index.js +1 -1
  38. package/x/dist/loader/service/index.js +7 -1
  39. package/x/dist/loader/system/index.js +26 -1
  40. package/x/dist/project/index.js +51 -1
  41. package/x/dist/utils/constants/defaults.json +3 -1
  42. package/x/dist/utils/constants/index.d.ts +1 -0
  43. package/x/dist/utils/constants/index.js +42 -1
  44. package/x/dist/utils/constants/package-root.js +6 -1
  45. package/x/dist/utils/helpers/configs/index.js +1 -1
  46. package/x/dist/utils/helpers/context/controller-store.js +12 -1
  47. package/x/dist/utils/helpers/context/index.js +24 -1
  48. package/x/dist/utils/helpers/core/handlebars-resolve.js +15 -1
  49. package/x/dist/utils/helpers/core/index.js +46 -1
  50. package/x/dist/utils/helpers/core/paths.js +78 -1
  51. package/x/dist/utils/helpers/core/tmp-layout.d.ts +4 -4
  52. package/x/dist/utils/helpers/core/tmp-layout.js +229 -1
  53. package/x/dist/utils/helpers/date/index.js +48 -1
  54. package/x/dist/utils/helpers/dispatch/index.js +53 -1
  55. package/x/dist/utils/helpers/dto/index.js +10 -1
  56. package/x/dist/utils/helpers/filters/index.js +44 -1
  57. package/x/dist/utils/helpers/framework/index.js +18 -1
  58. package/x/dist/utils/helpers/handlers/adapters.js +41 -1
  59. package/x/dist/utils/helpers/handlers/execute.js +82 -1
  60. package/x/dist/utils/helpers/handlers/index.js +31 -1
  61. package/x/dist/utils/helpers/hash/crypto.js +22 -1
  62. package/x/dist/utils/helpers/id/index.js +24 -1
  63. package/x/dist/utils/helpers/index.d.ts +1 -0
  64. package/x/dist/utils/helpers/index.js +28 -1
  65. package/x/dist/utils/helpers/ip/index.js +21 -1
  66. package/x/dist/utils/helpers/is/index.js +35 -1
  67. package/x/dist/utils/helpers/kafka-loader-options/index.js +14 -1
  68. package/x/dist/utils/helpers/locales/index.js +82 -1
  69. package/x/dist/utils/helpers/logger-layer/index.js +33 -1
  70. package/x/dist/utils/helpers/math/index.js +14 -1
  71. package/x/dist/utils/helpers/middleware/index.js +36 -1
  72. package/x/dist/utils/helpers/node-env/index.js +20 -1
  73. package/x/dist/utils/helpers/objects/index.js +55 -1
  74. package/x/dist/utils/helpers/path/index.js +5 -1
  75. package/x/dist/utils/helpers/path/resolve-alias-path.d.ts +1 -1
  76. package/x/dist/utils/helpers/path/resolve-alias-path.js +62 -1
  77. package/x/dist/utils/helpers/protocol/index.d.ts +1 -1
  78. package/x/dist/utils/helpers/protocol/index.js +100 -1
  79. package/x/dist/utils/helpers/protocol/options.js +13 -1
  80. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +3 -1
  81. package/x/dist/utils/helpers/registry/index.js +103 -1
  82. package/x/dist/utils/helpers/runtime/dto-access.js +5 -1
  83. package/x/dist/utils/helpers/runtime/dto-types.js +1 -1
  84. package/x/dist/utils/helpers/runtime/index.js +2 -1
  85. package/x/dist/utils/helpers/runtime/shutdown.js +36 -1
  86. package/x/dist/utils/helpers/state/index.js +185 -1
  87. package/x/dist/utils/helpers/state/props-from-tmp.js +46 -1
  88. package/x/dist/utils/helpers/state/request-key-guard.js +43 -1
  89. package/x/dist/utils/helpers/state/scopes.js +69 -1
  90. package/x/dist/utils/helpers/string/index.js +9 -1
  91. package/x/dist/utils/helpers/timer/index.js +5 -1
  92. package/x/dist/utils/helpers/tmp/index.d.ts +2 -2
  93. package/x/dist/utils/helpers/tmp/index.js +8 -1
  94. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +14 -1
  95. package/x/dist/utils/helpers/tmp/path-normalize.js +27 -1
  96. package/x/dist/utils/helpers/tmp/runtime-tmp.js +42 -1
  97. package/x/dist/utils/helpers/tmp/seed-from-tmp.d.ts +2 -2
  98. package/x/dist/utils/helpers/tmp/seed-from-tmp.js +62 -1
  99. package/x/dist/utils/helpers/tmp/tmp-interpolate.js +22 -1
  100. package/x/dist/utils/helpers/tmp/tmp-loader.js +56 -1
  101. package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +35 -23
  102. package/x/dist/utils/helpers/tmp/tmp-schema.js +211 -1
  103. package/x/dist/utils/helpers/tmp/tmp-watch.js +23 -1
  104. package/x/dist/utils/helpers/tmp/toolchain-heal.js +157 -2
  105. package/x/dist/utils/helpers/validates/index.js +20 -1
  106. package/x/dist/utils/helpers/workspace/index.d.ts +42 -0
  107. package/x/dist/utils/helpers/workspace/index.js +222 -0
  108. package/x/dist/utils/helpers/xrystal-home/registry.d.ts +32 -0
  109. package/x/dist/utils/helpers/xrystal-home/registry.js +92 -0
  110. package/x/dist/utils/index.js +3 -1
  111. package/x/dist/utils/models/classes/class.clients.js +142 -1
  112. package/x/dist/utils/models/classes/class.interfaces.js +10 -1
  113. package/x/dist/utils/models/classes/class.service-locator.js +16 -1
  114. package/x/dist/utils/models/classes/class.tmp-file-loader.js +61 -1
  115. package/x/dist/utils/models/classes/class.x.js +181 -1
  116. package/x/dist/utils/models/enums/index.d.ts +9 -1
  117. package/x/dist/utils/models/enums/index.js +169 -1
  118. package/x/dist/utils/models/index.js +9 -1
  119. package/x/dist/utils/models/types/index.js +2 -1
  120. package/x/templates/api-service/tmp.yml +59 -0
  121. package/x/tmp.yml +7 -50
@@ -1 +1,62 @@
1
- import V from"node:fs";import G from"node:path";import H from"../../../utils/constants/defaults.json" with { type: 'json' };const W=[".ts",".js",".mjs"];function J(k){return String(k).replace(/^\.\//,"")}function Y(k){for(const y of W){const q=`${k}${y}`;if(V.existsSync(q))return q}for(const y of W){const q=G.join(k,`index${y}`);if(V.existsSync(q))return q}return null}export function resolveAliasModulePath(k,y={}){const q=y.cwd??process.cwd(),K=y.aliasPrefix??H.pathAliasKey.replace("*","");if(!k.startsWith(K))return G.isAbsolute(k)?k:G.resolve(q,k);const C=J(y.sourceFolder??"source");let z=k.slice(K.length).replace(/^\/+/,"");if(z===C||z.startsWith(`${C}/`))z=z===C?"":z.slice(C.length+1);const N=G.join(q,C,z),Q=Y(N);if(Q)return Q;const Z=J(y.rootFolder??H.packageRootFolder),$=J(y.distSegment??"dist"),j=G.join(q,Z,$,z),R=Y(j);if(R)return R;return N}export function resolveTmpLoadPath(k,y,q=process.cwd()){const K=H.pathAliasKey.replace("*",""),C=y.configs??{};if(!k.startsWith(K)){const Q=C.rootFolderPath??H.packageRootFolder;return G.resolve(q,Q,k)}const z=C.service?.paths??{},N=z.special??{};return resolveAliasModulePath(k,{cwd:q,sourceFolder:J(String(z.source??"source")),rootFolder:C.rootFolderPath??H.packageRootFolder,distSegment:J(String(N.dist??"dist"))})}
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import defaults from '../../../utils/constants/defaults.json' with { type: 'json' };
4
+ const MODULE_EXTS = ['.ts', '.js', '.mjs'];
5
+ function stripDotSlash(value) {
6
+ return String(value).replace(/^\.\//, '');
7
+ }
8
+ function findModuleFile(basePath) {
9
+ for (const ext of MODULE_EXTS) {
10
+ const asFile = `${basePath}${ext}`;
11
+ if (fs.existsSync(asFile))
12
+ return asFile;
13
+ }
14
+ for (const ext of MODULE_EXTS) {
15
+ const asIndex = path.join(basePath, `index${ext}`);
16
+ if (fs.existsSync(asIndex))
17
+ return asIndex;
18
+ }
19
+ return null;
20
+ }
21
+ /** Resolve `@/…` the same way as tsconfig paths (`@/*` → `{sourceFolder}/*`), with dist fallback for prod. */
22
+ export function resolveAliasModulePath(spec, options = {}) {
23
+ const cwd = options.cwd ?? process.cwd();
24
+ const aliasPrefix = options.aliasPrefix ?? defaults.pathAliasKey.replace('*', '');
25
+ if (!spec.startsWith(aliasPrefix)) {
26
+ return path.isAbsolute(spec) ? spec : path.resolve(cwd, spec);
27
+ }
28
+ const sourceFolder = stripDotSlash(options.sourceFolder ?? 'source');
29
+ let rest = spec.slice(aliasPrefix.length).replace(/^\/+/, '');
30
+ // Legacy tmp.yml: `@/source/foo` → same as `@/foo` (tsconfig `@/*` already maps to source/*).
31
+ if (rest === sourceFolder || rest.startsWith(`${sourceFolder}/`)) {
32
+ rest = rest === sourceFolder ? '' : rest.slice(sourceFolder.length + 1);
33
+ }
34
+ const sourceBase = path.join(cwd, sourceFolder, rest);
35
+ const fromSource = findModuleFile(sourceBase);
36
+ if (fromSource)
37
+ return fromSource;
38
+ const rootFolder = stripDotSlash(options.rootFolder ?? defaults.packageRootFolder);
39
+ const distSegment = stripDotSlash(options.distSegment ?? 'dist');
40
+ const distBase = path.join(cwd, rootFolder, distSegment, rest);
41
+ const fromDist = findModuleFile(distBase);
42
+ if (fromDist)
43
+ return fromDist;
44
+ return sourceBase;
45
+ }
46
+ /** Resolve tmp.yml loader `loadPath` — `@/` modules or paths relative to `paths.root`. */
47
+ export function resolveTmpLoadPath(spec, tmp, cwd = process.cwd()) {
48
+ const aliasPrefix = defaults.pathAliasKey.replace('*', '');
49
+ const configs = tmp.configs ?? {};
50
+ if (!spec.startsWith(aliasPrefix)) {
51
+ const root = configs.rootFolderPath ?? defaults.packageRootFolder;
52
+ return path.resolve(cwd, root, spec);
53
+ }
54
+ const paths = configs.global?.paths ?? {};
55
+ const special = paths.special ?? {};
56
+ return resolveAliasModulePath(spec, {
57
+ cwd,
58
+ sourceFolder: stripDotSlash(String(paths.source ?? 'source')),
59
+ rootFolder: configs.rootFolderPath ?? defaults.packageRootFolder,
60
+ distSegment: stripDotSlash(String(special.dist ?? 'dist')),
61
+ });
62
+ }
@@ -4,7 +4,7 @@ declare const REALTIME_MIDDLEWARE_HINT: string;
4
4
  export declare function parseProtocol(value: unknown): ProtocolEnum;
5
5
  export declare function isRealtimeProtocol(protocol?: ProtocolEnum): boolean;
6
6
  export declare function isHttpProtocol(protocol?: ProtocolEnum): boolean;
7
- export type TmpConfigs = NonNullable<ReturnType<typeof getRuntimeTmpConfigs>>['service'];
7
+ export type TmpConfigs = NonNullable<ReturnType<typeof getRuntimeTmpConfigs>>['depends'];
8
8
  export declare function resolveProtocolsFromConfig(configs?: TmpConfigs): ProtocolEnum[];
9
9
  export declare function getConfiguredProtocols(): ProtocolEnum[];
10
10
  export declare function getConfiguredRealtimeProtocols(configs?: TmpConfigs): ProtocolEnum[];
@@ -1 +1,100 @@
1
- import{Constants as J}from "../../../utils/constants/index.js";import{ProtocolEnum as h}from "../../../utils/models/enums/index.js";import{getRuntimeTmpConfigs as K}from "../../../utils/helpers/tmp/runtime-tmp.js";const G={http:h.HTTP,https:h.HTTPS,ws:h.WEBSOCKET,websocket:h.WEBSOCKET,socketio:h.SOCKETIO,socket:h.SOCKETIO},REALTIME_MIDDLEWARE_HINT=`[${J.packageName}] 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 K()?.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
+ import { Constants } from '../../../utils/constants/index.js';
2
+ import { ProtocolEnum } from '../../../utils/models/enums/index.js';
3
+ import { getRuntimeTmpConfigs } from '../../../utils/helpers/tmp/runtime-tmp.js';
4
+ const PROTOCOL_ALIASES = {
5
+ http: ProtocolEnum.HTTP,
6
+ https: ProtocolEnum.HTTPS,
7
+ ws: ProtocolEnum.WEBSOCKET,
8
+ websocket: ProtocolEnum.WEBSOCKET,
9
+ socketio: ProtocolEnum.SOCKETIO,
10
+ socket: ProtocolEnum.SOCKETIO,
11
+ };
12
+ const REALTIME_MIDDLEWARE_HINT = `[${Constants.packageName}] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")`;
13
+ export function parseProtocol(value) {
14
+ if (!value)
15
+ return ProtocolEnum.HTTP;
16
+ const key = String(value).toLowerCase().replace(/[-_\s.]/g, '');
17
+ if (PROTOCOL_ALIASES[key])
18
+ return PROTOCOL_ALIASES[key];
19
+ const values = Object.values(ProtocolEnum);
20
+ return values.includes(String(value)) ? value : ProtocolEnum.HTTP;
21
+ }
22
+ export function isRealtimeProtocol(protocol) {
23
+ return protocol === ProtocolEnum.WEBSOCKET || protocol === ProtocolEnum.SOCKETIO;
24
+ }
25
+ export function isHttpProtocol(protocol) {
26
+ return !protocol || protocol === ProtocolEnum.HTTP || protocol === ProtocolEnum.HTTPS;
27
+ }
28
+ function tmpConfigsFromRuntime() {
29
+ return getRuntimeTmpConfigs()?.depends;
30
+ }
31
+ export function resolveProtocolsFromConfig(configs) {
32
+ const raw = configs?.protocols;
33
+ if (!raw)
34
+ return [ProtocolEnum.HTTP];
35
+ return (Array.isArray(raw) ? raw : [raw]).map(parseProtocol);
36
+ }
37
+ export function getConfiguredProtocols() {
38
+ try {
39
+ return resolveProtocolsFromConfig(tmpConfigsFromRuntime());
40
+ }
41
+ catch {
42
+ return [ProtocolEnum.HTTP, ProtocolEnum.WEBSOCKET];
43
+ }
44
+ }
45
+ export function getConfiguredRealtimeProtocols(configs) {
46
+ return resolveProtocolsFromConfig(configs).filter(isRealtimeProtocol);
47
+ }
48
+ export function defaultRealtimeProtocolFromConfig(configs) {
49
+ const realtime = getConfiguredRealtimeProtocols(configs);
50
+ if (realtime.length === 1)
51
+ return realtime[0];
52
+ if (realtime.length > 1)
53
+ return undefined;
54
+ return ProtocolEnum.WEBSOCKET;
55
+ }
56
+ export function getDefaultRealtimeProtocol() {
57
+ try {
58
+ return defaultRealtimeProtocolFromConfig(tmpConfigsFromRuntime());
59
+ }
60
+ catch {
61
+ return ProtocolEnum.WEBSOCKET;
62
+ }
63
+ }
64
+ export function resolveRealtimeMiddlewareProtocol(protocol, configs) {
65
+ if (protocol !== undefined && protocol !== null && protocol !== '') {
66
+ return parseProtocol(protocol);
67
+ }
68
+ let cfg = configs;
69
+ if (!cfg) {
70
+ try {
71
+ cfg = tmpConfigsFromRuntime();
72
+ }
73
+ catch {
74
+ return ProtocolEnum.WEBSOCKET;
75
+ }
76
+ }
77
+ const realtime = getConfiguredRealtimeProtocols(cfg);
78
+ if (realtime.length === 1)
79
+ return realtime[0];
80
+ if (realtime.length > 1)
81
+ throw new Error(REALTIME_MIDDLEWARE_HINT);
82
+ return ProtocolEnum.WEBSOCKET;
83
+ }
84
+ export function detectSocketProtocol(socket, explicit) {
85
+ if (explicit)
86
+ return explicit;
87
+ const s = socket;
88
+ if (s?.__xrystalProtocol)
89
+ return s.__xrystalProtocol;
90
+ return ProtocolEnum.WEBSOCKET;
91
+ }
92
+ export function attachSocketTransport(socket, protocol, runtime) {
93
+ const s = socket;
94
+ if (protocol === ProtocolEnum.SOCKETIO)
95
+ runtime.attachSocketIo(socket);
96
+ else
97
+ runtime.attachWebSocket(socket);
98
+ s.__xrystalProtocol = protocol;
99
+ }
100
+ export { REALTIME_MIDDLEWARE_HINT };
@@ -1 +1,13 @@
1
- import{FrameworkEnum as e,ProtocolEnum as o}from "../../../utils/models/index.js";import{parseProtocol as t}from "../../../utils/helpers/protocol/index.js";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
+ import { FrameworkEnum, ProtocolEnum } from '../../../utils/models/index.js';
2
+ import { parseProtocol } from '../../../utils/helpers/protocol/index.js';
3
+ export function resolveCtrOptions(opts) {
4
+ if (opts === undefined)
5
+ return { protocol: ProtocolEnum.HTTP };
6
+ if (typeof opts === 'string') {
7
+ const fwValues = Object.values(FrameworkEnum);
8
+ if (fwValues.includes(opts))
9
+ return { framework: opts, protocol: ProtocolEnum.HTTP };
10
+ return { protocol: parseProtocol(opts) };
11
+ }
12
+ return { protocol: ProtocolEnum.HTTP, ...opts };
13
+ }
@@ -1 +1,3 @@
1
- export function checkSpecialRegexControl(e,t){return t.test(e)}
1
+ export function checkSpecialRegexControl(str, regex) {
2
+ return regex.test(str);
3
+ }
@@ -1 +1,103 @@
1
- export const REGISTRY_COLLECTION="registry",LEGACY_TARGET_KEY_TO_SERVICE={coreTargetUri:"core",rootTargetUri:"core",iamTargetUri:"iam",websocketTargetUri:"websocket",mqttTargetUri:"mqtt"},TARGET_SERVICE_ALIASES={root:"core"};export function buildInternalBaseUrl(b,j=3000){const q=String(b??"").trim();if(!q)return"";return`http://${q}-service:${j}`}export function registryRedisHashKey(b){return`${b}:registry`}export const REGISTRY_TARGET_PREFIX="&";export function normalizeRegistryServiceName(b){const j=String(b??"").trim();if(!j)return"";return TARGET_SERVICE_ALIASES[j]??j}export function isRegistryTargetRef(b){return String(b??"").trim().startsWith(REGISTRY_TARGET_PREFIX)}export function parseRegistryTargetRef(b){const j=String(b??"").trim();if(!j.startsWith(REGISTRY_TARGET_PREFIX))return normalizeRegistryServiceName(j);return normalizeRegistryServiceName(j.slice(REGISTRY_TARGET_PREFIX.length))}export function resolveRegistryTargetRef(b,j){if(!isRegistryTargetRef(b)||!j)return;return j(parseRegistryTargetRef(b))}export function isAbsoluteHttpUrl(b){return/^https?:\/\//i.test(String(b??"").trim())}export function looksLikeLegacyConfigTargetKey(b){return/TargetUri$/i.test(String(b??"").trim())}export function normalizeRegistryDoc(b){if(!b)return null;const j=String(b.name??"").trim(),q=String(b.internalBaseUrl??"").trim();if(!j||!q)return null;const{others:x,registeredAt:H,lastSeenAt:J}=b;return{...b._id?{_id:String(b._id)}:{},name:j,internalBaseUrl:q,...b.version?{version:String(b.version)}:{},others:{created:x?.created??H,updated:x?.updated??J}}}export function serializeRegistryEntry(b){const j=b.others??{};return JSON.stringify({...b._id?{_id:b._id}:{},name:b.name,internalBaseUrl:b.internalBaseUrl,...b.version?{version:b.version}:{},others:{created:j.created instanceof Date?j.created.toISOString():j.created,updated:j.updated instanceof Date?j.updated.toISOString():j.updated}})}export function parseRegistryEntry(b){if(!b)return null;try{return normalizeRegistryDoc(JSON.parse(b))}catch{return null}}export function snapshotFromHash(b){const j={};for(const[q,x]of Object.entries(b??{})){const H=parseRegistryEntry(x);if(H)j[q]=H}return j}
1
+ export const REGISTRY_COLLECTION = 'registry';
2
+ export const LEGACY_TARGET_KEY_TO_SERVICE = {
3
+ coreTargetUri: 'core',
4
+ rootTargetUri: 'core',
5
+ iamTargetUri: 'iam',
6
+ websocketTargetUri: 'websocket',
7
+ mqttTargetUri: 'mqtt',
8
+ };
9
+ export const TARGET_SERVICE_ALIASES = {
10
+ root: 'core',
11
+ };
12
+ export function buildInternalBaseUrl(serviceName, port = 3000) {
13
+ const slug = String(serviceName ?? '').trim();
14
+ if (!slug)
15
+ return '';
16
+ return `http://${slug}-service:${port}`;
17
+ }
18
+ export function registryRedisHashKey(nodeEnv) {
19
+ return `${nodeEnv}:registry`;
20
+ }
21
+ export const REGISTRY_TARGET_PREFIX = '&';
22
+ export function normalizeRegistryServiceName(name) {
23
+ const key = String(name ?? '').trim();
24
+ if (!key)
25
+ return '';
26
+ return TARGET_SERVICE_ALIASES[key] ?? key;
27
+ }
28
+ /** Gateway/mongo target ref — `&iam` means resolve internalBaseUrl from registry. */
29
+ export function isRegistryTargetRef(value) {
30
+ return String(value ?? '').trim().startsWith(REGISTRY_TARGET_PREFIX);
31
+ }
32
+ /** Strip leading `&` and normalize service name (`&root` → `core`). */
33
+ export function parseRegistryTargetRef(value) {
34
+ const raw = String(value ?? '').trim();
35
+ if (!raw.startsWith(REGISTRY_TARGET_PREFIX)) {
36
+ return normalizeRegistryServiceName(raw);
37
+ }
38
+ return normalizeRegistryServiceName(raw.slice(REGISTRY_TARGET_PREFIX.length));
39
+ }
40
+ export function resolveRegistryTargetRef(target, resolveService) {
41
+ if (!isRegistryTargetRef(target) || !resolveService)
42
+ return undefined;
43
+ return resolveService(parseRegistryTargetRef(target));
44
+ }
45
+ export function isAbsoluteHttpUrl(value) {
46
+ return /^https?:\/\//i.test(String(value ?? '').trim());
47
+ }
48
+ export function looksLikeLegacyConfigTargetKey(key) {
49
+ return /TargetUri$/i.test(String(key ?? '').trim());
50
+ }
51
+ export function normalizeRegistryDoc(doc) {
52
+ if (!doc)
53
+ return null;
54
+ const name = String(doc.name ?? '').trim();
55
+ const internalBaseUrl = String(doc.internalBaseUrl ?? '').trim();
56
+ if (!name || !internalBaseUrl)
57
+ return null;
58
+ const othersRaw = doc.others;
59
+ const legacyCreated = doc.registeredAt;
60
+ const legacyUpdated = doc.lastSeenAt;
61
+ return {
62
+ ...(doc._id ? { _id: String(doc._id) } : {}),
63
+ name,
64
+ internalBaseUrl,
65
+ ...(doc.version ? { version: String(doc.version) } : {}),
66
+ others: {
67
+ created: othersRaw?.created ?? legacyCreated,
68
+ updated: othersRaw?.updated ?? legacyUpdated,
69
+ },
70
+ };
71
+ }
72
+ export function serializeRegistryEntry(entry) {
73
+ const others = entry.others ?? {};
74
+ return JSON.stringify({
75
+ ...(entry._id ? { _id: entry._id } : {}),
76
+ name: entry.name,
77
+ internalBaseUrl: entry.internalBaseUrl,
78
+ ...(entry.version ? { version: entry.version } : {}),
79
+ others: {
80
+ created: others.created instanceof Date ? others.created.toISOString() : others.created,
81
+ updated: others.updated instanceof Date ? others.updated.toISOString() : others.updated,
82
+ },
83
+ });
84
+ }
85
+ export function parseRegistryEntry(raw) {
86
+ if (!raw)
87
+ return null;
88
+ try {
89
+ return normalizeRegistryDoc(JSON.parse(raw));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ export function snapshotFromHash(fields) {
96
+ const out = {};
97
+ for (const [name, raw] of Object.entries(fields ?? {})) {
98
+ const entry = parseRegistryEntry(raw);
99
+ if (entry)
100
+ out[name] = entry;
101
+ }
102
+ return out;
103
+ }
@@ -1 +1,5 @@
1
- import{x as t}from "../../../utils/models/index.js";export const DTO_RUNTIME_KEY="dtoRuntime";export function getDtoRuntime(){return t.get(DTO_RUNTIME_KEY)}
1
+ import { x } from '../../../utils/models/index.js';
2
+ export const DTO_RUNTIME_KEY = 'dtoRuntime';
3
+ export function getDtoRuntime() {
4
+ return x.get(DTO_RUNTIME_KEY);
5
+ }
@@ -1 +1 @@
1
- export{};
1
+ export {};
@@ -1 +1,2 @@
1
- export{getDtoRuntime,DTO_RUNTIME_KEY}from "../../../utils/helpers/runtime/dto-access.js";export{gracefulShutdown,isShuttingDown,registerGracefulShutdown}from "../../../utils/helpers/runtime/shutdown.js";
1
+ export { getDtoRuntime, DTO_RUNTIME_KEY } from '../../../utils/helpers/runtime/dto-access.js';
2
+ export { gracefulShutdown, isShuttingDown, registerGracefulShutdown } from '../../../utils/helpers/runtime/shutdown.js';
@@ -1 +1,36 @@
1
- import{stopTmpLoader as y}from "../../../utils/helpers/tmp/tmp-loader.js";import{clearRuntimeTmpConfigs as z}from "../../../utils/helpers/tmp/runtime-tmp.js";import A from "../../../utils/models/classes/class.x.js";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)}
1
+ import { stopTmpLoader } from '../../../utils/helpers/tmp/tmp-loader.js';
2
+ import { clearRuntimeTmpConfigs } from '../../../utils/helpers/tmp/runtime-tmp.js';
3
+ import x from '../../../utils/models/classes/class.x.js';
4
+ let shuttingDown = false;
5
+ let registered = false;
6
+ export function isShuttingDown() {
7
+ return shuttingDown;
8
+ }
9
+ export async function gracefulShutdown(exitCode = 0) {
10
+ if (shuttingDown) {
11
+ process.exit(exitCode);
12
+ return;
13
+ }
14
+ shuttingDown = true;
15
+ try {
16
+ await x.shutdown();
17
+ }
18
+ catch {
19
+ // best-effort teardown
20
+ }
21
+ stopTmpLoader();
22
+ clearRuntimeTmpConfigs();
23
+ await new Promise((resolve) => setImmediate(resolve));
24
+ process.exit(exitCode);
25
+ }
26
+ export function registerGracefulShutdown() {
27
+ if (registered)
28
+ return;
29
+ registered = true;
30
+ const handle = (signal) => {
31
+ const code = signal === 'SIGINT' ? 130 : signal === 'SIGTERM' ? 143 : 0;
32
+ void gracefulShutdown(code);
33
+ };
34
+ process.on('SIGINT', handle);
35
+ process.on('SIGTERM', handle);
36
+ }
@@ -1 +1,185 @@
1
- import{createStore as w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from "../../../utils/models/enums/index.js";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from "../../../utils/helpers/state/props-from-tmp.js";import{warnIfRequestScopedKey as Q,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from "../../../utils/helpers/state/request-key-guard.js";import{buildStoresSnapshot as U,patchControllerScope as Y,patchRunScope as q}from "../../../utils/helpers/state/scopes.js";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from "../../../utils/models/enums/index.js";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from "../../../utils/helpers/state/scopes.js";const V=(j)=>JSON.parse(JSON.stringify(j));function $(j,z){const H=new Set([...Object.keys(j),...Object.keys(z)]),M=[];for(const J of H)if(j[J]!==z[J])M.push({key:J,value:z[J],prev:j[J]});return M}class GStoreFacade{store;baseline={};allowedKeys=new Set;allowAutoCreateProps=!0;warnOnRequestKeys=!0;constructor(){this.store=w(I(()=>({})))}configureFromTmp(j={}){const z=resolveGStoreBoot(j);this.allowAutoCreateProps=z.allowAutoCreateProps;this.warnOnRequestKeys=z.warnOnRequestKeys;this.allowedKeys=new Set(Object.keys(z.vars));const H=V(z.bootstrap?z.vars:{});this.store.setState(H,!0);this.baseline=V(H);return this}allowsAutoCreateProps(){return this.allowAutoCreateProps}declaredKeys(){return[...this.allowedKeys]}guardRequestKey(j){Q(j,this.warnOnRequestKeys)}assertPropAllowed(j){if(this.allowAutoCreateProps)return;if(!this.allowedKeys.has(j))throw Error(`${G_PROP_NOT_ALLOWED}: ${j}`)}registerAllowedKeys(j){for(const z of j)this.allowedKeys.add(z)}getState(){return this.store.getState()}select(j){return j(this.getState())}get(j,z){const H=this.getState();if(!(j in H))return z;return H[j]}set(j,z){this.guardRequestKey(j);this.assertPropAllowed(j);const H=this.getState();if(H[j]===z)return this;this.store.setState({...H,[j]:z});return this}merge(j){for(const M of Object.keys(j)){this.guardRequestKey(M);this.assertPropAllowed(M)}const z=this.getState();if(!$(z,{...z,...j}).length)return this;this.store.setState({...z,...j});return this}has(j){return j in this.getState()}remove(...j){const H={...this.getState()};let M=!1;for(const J of j)if(J in H){delete H[J];M=!0}if(M)this.store.setState(H,!0);return this}keys(){return Object.keys(this.getState())}entries(){return Object.entries(this.getState())}snapshot(){return{...this.getState()}}subscribe(j){return this.store.subscribe((z,H)=>j(z,H,$(H,z)))}subscribeKey(j,z){return this.store.subscribe((H)=>H[j],(H,M)=>z(H,M,{key:j,value:H,prev:M}))}bootstrap(j){if(!this.allowAutoCreateProps)for(const z of Object.keys(j))this.assertPropAllowed(z);else this.registerAllowedKeys(Object.keys(j));this.merge(j);this.baseline=V(this.getState());return this}reset(){this.store.setState(V(this.baseline),!0)}stores(){return U(this.snapshot())}list(){return Object.values(this.stores())}scope(j){const H=this.stores()[j],M={name:j,active:H.active,keys:()=>H.keys,get(J,X){if(!H.values||!(J in H.values))return X;return H.values[J]}};if(j===Z.GLOBAL)return{...M,set:(J,X)=>{this.set(J,X);return!0},merge:(J)=>{this.merge(J);return!0}};if(j===Z.RUN)return{...M,patch:(J)=>q(J)};return{...M,patch:(J)=>Y(J)}}}export{GStoreFacade};export const G=new GStoreFacade;
1
+ import { createStore } from 'zustand/vanilla';
2
+ import { subscribeWithSelector } from 'zustand/middleware';
3
+ import { GStoreScopeEnum } from '../../../utils/models/enums/index.js';
4
+ import { propsFromTmp, resolveGStoreBoot, G_PROP_NOT_ALLOWED } from '../../../utils/helpers/state/props-from-tmp.js';
5
+ import { warnIfRequestScopedKey, G_REQUEST_KEY_WARN, looksLikeRequestScopedKey } from '../../../utils/helpers/state/request-key-guard.js';
6
+ import { buildStoresSnapshot, patchControllerScope, patchRunScope, } from '../../../utils/helpers/state/scopes.js';
7
+ export { propsFromTmp, resolveGStoreBoot, G_PROP_NOT_ALLOWED, G_REQUEST_KEY_WARN, looksLikeRequestScopedKey };
8
+ export { GStoreScopeEnum } from '../../../utils/models/enums/index.js';
9
+ export { buildStoresSnapshot, summarizeController, runContextValues, patchControllerScope, patchRunScope, } from '../../../utils/helpers/state/scopes.js';
10
+ const cloneState = (state) => JSON.parse(JSON.stringify(state));
11
+ function diffChanges(prev, next) {
12
+ const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
13
+ const changes = [];
14
+ for (const key of keys) {
15
+ if (prev[key] !== next[key]) {
16
+ changes.push({ key, value: next[key], prev: prev[key] });
17
+ }
18
+ }
19
+ return changes;
20
+ }
21
+ class GStoreFacade {
22
+ store;
23
+ baseline = {};
24
+ allowedKeys = new Set();
25
+ allowAutoCreateProps = true;
26
+ warnOnRequestKeys = true;
27
+ constructor() {
28
+ this.store = createStore(subscribeWithSelector(() => ({})));
29
+ }
30
+ configureFromTmp(tmp = {}) {
31
+ const boot = resolveGStoreBoot(tmp);
32
+ this.allowAutoCreateProps = boot.allowAutoCreateProps;
33
+ this.warnOnRequestKeys = boot.warnOnRequestKeys;
34
+ this.allowedKeys = new Set(Object.keys(boot.vars));
35
+ const next = cloneState(boot.bootstrap ? boot.vars : {});
36
+ this.store.setState(next, true);
37
+ this.baseline = cloneState(next);
38
+ return this;
39
+ }
40
+ allowsAutoCreateProps() {
41
+ return this.allowAutoCreateProps;
42
+ }
43
+ declaredKeys() {
44
+ return [...this.allowedKeys];
45
+ }
46
+ guardRequestKey(key) {
47
+ warnIfRequestScopedKey(key, this.warnOnRequestKeys);
48
+ }
49
+ assertPropAllowed(key) {
50
+ if (this.allowAutoCreateProps)
51
+ return;
52
+ if (!this.allowedKeys.has(key)) {
53
+ throw new Error(`${G_PROP_NOT_ALLOWED}: ${key}`);
54
+ }
55
+ }
56
+ registerAllowedKeys(keys) {
57
+ for (const key of keys)
58
+ this.allowedKeys.add(key);
59
+ }
60
+ getState() {
61
+ return this.store.getState();
62
+ }
63
+ select(selector) {
64
+ return selector(this.getState());
65
+ }
66
+ get(key, fallback) {
67
+ const state = this.getState();
68
+ if (!(key in state))
69
+ return fallback;
70
+ return state[key];
71
+ }
72
+ set(key, value) {
73
+ this.guardRequestKey(key);
74
+ this.assertPropAllowed(key);
75
+ const prev = this.getState();
76
+ if (prev[key] === value)
77
+ return this;
78
+ this.store.setState({ ...prev, [key]: value });
79
+ return this;
80
+ }
81
+ merge(record) {
82
+ for (const key of Object.keys(record)) {
83
+ this.guardRequestKey(key);
84
+ this.assertPropAllowed(key);
85
+ }
86
+ const prev = this.getState();
87
+ const changes = diffChanges(prev, { ...prev, ...record });
88
+ if (!changes.length)
89
+ return this;
90
+ this.store.setState({ ...prev, ...record });
91
+ return this;
92
+ }
93
+ has(key) {
94
+ return key in this.getState();
95
+ }
96
+ remove(...keys) {
97
+ const prev = this.getState();
98
+ const next = { ...prev };
99
+ let touched = false;
100
+ for (const key of keys) {
101
+ if (key in next) {
102
+ delete next[key];
103
+ touched = true;
104
+ }
105
+ }
106
+ if (touched)
107
+ this.store.setState(next, true);
108
+ return this;
109
+ }
110
+ keys() {
111
+ return Object.keys(this.getState());
112
+ }
113
+ entries() {
114
+ return Object.entries(this.getState());
115
+ }
116
+ snapshot() {
117
+ return { ...this.getState() };
118
+ }
119
+ subscribe(listener) {
120
+ return this.store.subscribe((state, prev) => listener(state, prev, diffChanges(prev, state)));
121
+ }
122
+ subscribeKey(key, listener) {
123
+ return this.store.subscribe((state) => state[key], (value, prev) => listener(value, prev, { key, value, prev }));
124
+ }
125
+ bootstrap(record) {
126
+ if (!this.allowAutoCreateProps) {
127
+ for (const key of Object.keys(record))
128
+ this.assertPropAllowed(key);
129
+ }
130
+ else {
131
+ this.registerAllowedKeys(Object.keys(record));
132
+ }
133
+ this.merge(record);
134
+ this.baseline = cloneState(this.getState());
135
+ return this;
136
+ }
137
+ reset() {
138
+ this.store.setState(cloneState(this.baseline), true);
139
+ }
140
+ stores() {
141
+ return buildStoresSnapshot(this.snapshot());
142
+ }
143
+ list() {
144
+ return Object.values(this.stores());
145
+ }
146
+ scope(name) {
147
+ const stores = this.stores();
148
+ const entry = stores[name];
149
+ const base = {
150
+ name,
151
+ active: entry.active,
152
+ keys: () => entry.keys,
153
+ get(key, fallback) {
154
+ if (!entry.values || !(key in entry.values))
155
+ return fallback;
156
+ return entry.values[key];
157
+ },
158
+ };
159
+ if (name === GStoreScopeEnum.GLOBAL) {
160
+ return {
161
+ ...base,
162
+ set: (key, value) => {
163
+ this.set(key, value);
164
+ return true;
165
+ },
166
+ merge: (record) => {
167
+ this.merge(record);
168
+ return true;
169
+ },
170
+ };
171
+ }
172
+ if (name === GStoreScopeEnum.RUN) {
173
+ return {
174
+ ...base,
175
+ patch: (record) => patchRunScope(record),
176
+ };
177
+ }
178
+ return {
179
+ ...base,
180
+ patch: (record) => patchControllerScope(record),
181
+ };
182
+ }
183
+ }
184
+ export { GStoreFacade };
185
+ export const G = new GStoreFacade();
@@ -1 +1,46 @@
1
- import{Constants as I}from "../../../utils/constants/index.js";import{readTmpServiceBlock as J}from "../../../utils/helpers/tmp/tmp-schema.js";export const G_PROP_NOT_ALLOWED=`[${I.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;const F=()=>({});function L(j){return J(j).loaders?.system?.gStore}function M(j){if(typeof j.bootstrap==="boolean")return j.bootstrap;return!0}function Q(j){if(typeof j.autoCreateProps==="boolean")return j.autoCreateProps;return!0}function U(j){if(typeof j.warnOnRequestKeys==="boolean")return j.warnOnRequestKeys;return!0}export function resolveGStoreBoot(j={}){const x=j.configs??j,z=L(x);if(!z)return{bootstrap:!0,allowAutoCreateProps:!0,warnOnRequestKeys:!0,vars:F()};const E=z.options??{},D=z.vars,H=D&&typeof D==="object"&&!Array.isArray(D)?{...D}:F();return{bootstrap:M(E),allowAutoCreateProps:Q(E),warnOnRequestKeys:U(E),vars:H}}export function propsFromTmp(j={}){const x=resolveGStoreBoot(j);return x.bootstrap?x.vars:F()}
1
+ import { Constants } from '../../../utils/constants/index.js';
2
+ import { readTmpDependsBlock } from '../../../utils/helpers/tmp/tmp-schema.js';
3
+ export const G_PROP_NOT_ALLOWED = `[${Constants.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;
4
+ const emptyVars = () => ({});
5
+ function readGStoreNode(configs) {
6
+ const loaders = readTmpDependsBlock(configs).loaders;
7
+ const fromSystem = loaders?.system;
8
+ return fromSystem?.gStore;
9
+ }
10
+ function readBootstrap(options) {
11
+ if (typeof options.bootstrap === 'boolean')
12
+ return options.bootstrap;
13
+ return true;
14
+ }
15
+ function readAllowAutoCreateProps(options) {
16
+ if (typeof options.autoCreateProps === 'boolean')
17
+ return options.autoCreateProps;
18
+ return true;
19
+ }
20
+ function readWarnOnRequestKeys(options) {
21
+ if (typeof options.warnOnRequestKeys === 'boolean')
22
+ return options.warnOnRequestKeys;
23
+ return true;
24
+ }
25
+ export function resolveGStoreBoot(tmp = {}) {
26
+ const configs = (tmp.configs ?? tmp);
27
+ const gStore = readGStoreNode(configs);
28
+ if (!gStore) {
29
+ return { bootstrap: true, allowAutoCreateProps: true, warnOnRequestKeys: true, vars: emptyVars() };
30
+ }
31
+ const options = (gStore.options ?? {});
32
+ const varsRaw = gStore.vars;
33
+ const vars = varsRaw && typeof varsRaw === 'object' && !Array.isArray(varsRaw)
34
+ ? { ...varsRaw }
35
+ : emptyVars();
36
+ return {
37
+ bootstrap: readBootstrap(options),
38
+ allowAutoCreateProps: readAllowAutoCreateProps(options),
39
+ warnOnRequestKeys: readWarnOnRequestKeys(options),
40
+ vars,
41
+ };
42
+ }
43
+ export function propsFromTmp(tmp = {}) {
44
+ const boot = resolveGStoreBoot(tmp);
45
+ return boot.bootstrap ? boot.vars : emptyVars();
46
+ }
@@ -1 +1,43 @@
1
- import{Constants as B}from "../../../utils/constants/index.js";import{getRunContext as D}from "../../../utils/helpers/context/index.js";import{getControllerCtx as F}from "../../../utils/helpers/context/controller-store.js";export const G_REQUEST_KEY_WARN=`[${B.packageName}] G: key looks request-scoped — use run/controller context, not global G`;const H=new Set(["requestid","reqid","correlationid","cookies","cookie","headers","header","body","query","queries","params","locals","session","sessionid"]);export function looksLikeRequestScopedKey(j){const z=j.trim();if(!z)return!1;const f=z.toLowerCase();if(H.has(f))return!0;if(f.endsWith("requestid")||f.endsWith("correlationid"))return!0;if(f==="req"||f==="res")return!0;return!1}export function warnIfRequestScopedKey(j,z){if(!z||!looksLikeRequestScopedKey(j))return;const f=D()?"run":F()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${j}, scope: ${f})`)}
1
+ import { Constants } from '../../../utils/constants/index.js';
2
+ import { getRunContext } from '../../../utils/helpers/context/index.js';
3
+ import { getControllerCtx } from '../../../utils/helpers/context/controller-store.js';
4
+ export const G_REQUEST_KEY_WARN = `[${Constants.packageName}] G: key looks request-scoped — use run/controller context, not global G`;
5
+ const EXACT = new Set([
6
+ 'requestid',
7
+ 'reqid',
8
+ 'correlationid',
9
+ 'cookies',
10
+ 'cookie',
11
+ 'headers',
12
+ 'header',
13
+ 'body',
14
+ 'query',
15
+ 'queries',
16
+ 'params',
17
+ 'locals',
18
+ 'session',
19
+ 'sessionid',
20
+ ]);
21
+ export function looksLikeRequestScopedKey(key) {
22
+ const trimmed = key.trim();
23
+ if (!trimmed)
24
+ return false;
25
+ const lower = trimmed.toLowerCase();
26
+ if (EXACT.has(lower))
27
+ return true;
28
+ if (lower.endsWith('requestid') || lower.endsWith('correlationid'))
29
+ return true;
30
+ if (lower === 'req' || lower === 'res')
31
+ return true;
32
+ return false;
33
+ }
34
+ export function warnIfRequestScopedKey(key, enabled) {
35
+ if (!enabled || !looksLikeRequestScopedKey(key))
36
+ return;
37
+ const activeScope = getRunContext()
38
+ ? 'run'
39
+ : getControllerCtx()
40
+ ? 'controller'
41
+ : 'outside-request';
42
+ console.warn(`${G_REQUEST_KEY_WARN} (key: ${key}, scope: ${activeScope})`);
43
+ }