@xrystal/core 3.51.6 → 3.52.0

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 (120) hide show
  1. package/README.md +35 -1
  2. package/package.json +1 -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 +9 -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/tmp.yml +7 -50
@@ -1 +1,46 @@
1
- import{Constants as G,ProtocolEnum as H,TmpFileLoader as J}from"../../../utils/index.js";import{controllerContextStorage as K}from "../../../utils/helpers/context/controller-store.js";import{getTmpSnapshot as M}from "../../../utils/helpers/tmp/tmp-loader.js";import{findFileRecursively as O}from "../../../utils/helpers/core/paths.js";import{parseProtocol as Q}from"../../../utils/helpers/protocol/index.js";export*from "../../../utils/helpers/core/paths.js";export*from "../../../utils/helpers/core/tmp-layout.js";export{resolveObjWithHandlebars}from "../../../utils/helpers/core/handlebars-resolve.js";export const getCore=()=>({_:M()}),getTmpConfig=({root:q=process.cwd(),tmpFileName:j=G.tmpBaseName,ext:z=G.tmpExtension}={})=>{const B=O(q,j,z);if(!B)throw Error(`${j}${z.startsWith(".")?z:`.${z}`} file not found`);return new J({filePath:B}).getResolvedTmpFile()},withProtocol=async(q,j=H.HTTP)=>{const z=Q(j),B=K.getStore();if(B)B.protocol=z;return await q()},protocol=async(q,j=H.HTTP)=>withProtocol(q,j),argvsConverter=(q)=>{const j=q?.slice(2),z={};j.forEach((B)=>{if(B.startsWith("--")){console.log(B);const[D,I]=B.split("=");z[D.replace("--","")]=I||""}});return z},findExt=(q)=>{const j=q.split(".");return j[j.length-1]},changeExtensions=(q,j)=>{return q.replace(findExt(q),j)};
1
+ import { Constants, ProtocolEnum, TmpFileLoader } from '../../../utils/index.js';
2
+ import { controllerContextStorage } from '../../../utils/helpers/context/controller-store.js';
3
+ import { getTmpSnapshot } from '../../../utils/helpers/tmp/tmp-loader.js';
4
+ import { findFileRecursively } from '../../../utils/helpers/core/paths.js';
5
+ import { parseProtocol } from '../../../utils/helpers/protocol/index.js';
6
+ export * from '../../../utils/helpers/core/paths.js';
7
+ export * from '../../../utils/helpers/core/tmp-layout.js';
8
+ export { resolveObjWithHandlebars } from '../../../utils/helpers/core/handlebars-resolve.js';
9
+ export const getCore = () => ({
10
+ _: getTmpSnapshot(),
11
+ });
12
+ export const getTmpConfig = ({ root = process.cwd(), tmpFileName = Constants.tmpBaseName, ext = Constants.tmpExtension, } = {}) => {
13
+ const filePath = findFileRecursively(root, tmpFileName, ext);
14
+ if (!filePath) {
15
+ throw new Error(`${tmpFileName}${ext.startsWith('.') ? ext : `.${ext}`} file not found`);
16
+ }
17
+ const loader = new TmpFileLoader({ filePath });
18
+ return loader.getResolvedTmpFile();
19
+ };
20
+ export const withProtocol = async (callback, protocol = ProtocolEnum.HTTP) => {
21
+ const resolved = parseProtocol(protocol);
22
+ const store = controllerContextStorage.getStore();
23
+ if (store)
24
+ store.protocol = resolved;
25
+ return await callback();
26
+ };
27
+ export const protocol = async (callback, proto = ProtocolEnum.HTTP) => withProtocol(callback, proto);
28
+ export const argvsConverter = (argvs) => {
29
+ const reelArgvs = argvs?.slice(2);
30
+ const reelConvertedArgvs = {};
31
+ reelArgvs.forEach((argv) => {
32
+ if (argv.startsWith('--')) {
33
+ console.log(argv);
34
+ const [key, value] = argv.split('=');
35
+ reelConvertedArgvs[key.replace('--', '')] = value || '';
36
+ }
37
+ });
38
+ return reelConvertedArgvs;
39
+ };
40
+ export const findExt = (filename) => {
41
+ const split = filename.split('.');
42
+ return split[split.length - 1];
43
+ };
44
+ export const changeExtensions = (filename, repalceExt) => {
45
+ return filename.replace(findExt(filename), repalceExt);
46
+ };
@@ -1 +1,78 @@
1
- import s from"node:path";import l from"node:fs";export function findFileRecursively(o,c,n="",f=["node_modules",".git"]){if(typeof o!=="string"||!l.existsSync(o))return null;const y=c+(n.startsWith(".")?n:n?`.${n}`:"");try{const i=l.readdirSync(o,{withFileTypes:!0});for(const t of i){const r=s.join(o,t.name);if(t.isFile()){if(!n){const u=s.extname(t.name);if(s.basename(t.name,u)===c)return r}else if(t.name===y)return r}if(t.isDirectory()){if(t.name.startsWith(".")||f.includes(t.name))continue;const e=findFileRecursively(r,c,n,f);if(e)return e}}return null}catch(i){if(i&&typeof i==="object"&&"code"in i&&i.code==="EACCES")return null;return null}}export function findAllFilesRecursively(o,c,n="",f=["node_modules",".git"]){const y=c+(n.startsWith(".")?n:n?`.${n}`:""),i=[];function t(r){if(!l.existsSync(r))return;let u;try{u=l.readdirSync(r,{withFileTypes:!0})}catch{return}for(const e of u){const a=s.join(r,e.name);if(e.isFile()){if(!n){const d=s.extname(e.name);if(s.basename(e.name,d)===c)i.push(a)}else if(e.name===y)i.push(a);continue}if(e.isDirectory()){if(e.name.startsWith(".")||f.includes(e.name))continue;t(a)}}}t(s.resolve(o));return i}
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ export function findFileRecursively(startDir, baseName, extName = '', excludedDirs = ['node_modules', '.git']) {
4
+ if (typeof startDir !== 'string' || !fs.existsSync(startDir)) {
5
+ return null;
6
+ }
7
+ const targetName = baseName + (extName.startsWith('.') ? extName : (extName ? `.${extName}` : ''));
8
+ try {
9
+ const entries = fs.readdirSync(startDir, { withFileTypes: true });
10
+ for (const entry of entries) {
11
+ const fullPath = path.join(startDir, entry.name);
12
+ if (entry.isFile()) {
13
+ if (!extName) {
14
+ const entryExt = path.extname(entry.name);
15
+ const entryBase = path.basename(entry.name, entryExt);
16
+ if (entryBase === baseName) {
17
+ return fullPath;
18
+ }
19
+ }
20
+ else if (entry.name === targetName) {
21
+ return fullPath;
22
+ }
23
+ }
24
+ if (entry.isDirectory()) {
25
+ const isHiddenOrExcluded = entry.name.startsWith('.') || excludedDirs.includes(entry.name);
26
+ if (isHiddenOrExcluded)
27
+ continue;
28
+ const foundPath = findFileRecursively(fullPath, baseName, extName, excludedDirs);
29
+ if (foundPath)
30
+ return foundPath;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ catch (error) {
36
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'EACCES') {
37
+ return null;
38
+ }
39
+ return null;
40
+ }
41
+ }
42
+ export function findAllFilesRecursively(startDir, baseName, extName = '', excludedDirs = ['node_modules', '.git']) {
43
+ const targetName = baseName + (extName.startsWith('.') ? extName : extName ? `.${extName}` : '');
44
+ const found = [];
45
+ function walk(dir) {
46
+ if (!fs.existsSync(dir))
47
+ return;
48
+ let entries;
49
+ try {
50
+ entries = fs.readdirSync(dir, { withFileTypes: true });
51
+ }
52
+ catch {
53
+ return;
54
+ }
55
+ for (const entry of entries) {
56
+ const fullPath = path.join(dir, entry.name);
57
+ if (entry.isFile()) {
58
+ if (!extName) {
59
+ const entryExt = path.extname(entry.name);
60
+ const entryBase = path.basename(entry.name, entryExt);
61
+ if (entryBase === baseName)
62
+ found.push(fullPath);
63
+ }
64
+ else if (entry.name === targetName) {
65
+ found.push(fullPath);
66
+ }
67
+ continue;
68
+ }
69
+ if (entry.isDirectory()) {
70
+ if (entry.name.startsWith('.') || excludedDirs.includes(entry.name))
71
+ continue;
72
+ walk(fullPath);
73
+ }
74
+ }
75
+ }
76
+ walk(path.resolve(startDir));
77
+ return found;
78
+ }
@@ -15,7 +15,7 @@ export type TmpLayout = {
15
15
  export declare function coreCanonicalTmpPath(projectRoot?: string): string;
16
16
  export declare function assertCoreTmpGuard(projectRoot: string, tmpFilePath: string): void;
17
17
  export declare function ensureCoreTmpEntry(projectRoot?: string, options?: {
18
- patchServiceName?: boolean;
18
+ patchProjectName?: boolean;
19
19
  templatePath?: string;
20
20
  }): {
21
21
  tmpFilePath: string;
@@ -23,7 +23,7 @@ export declare function ensureCoreTmpEntry(projectRoot?: string, options?: {
23
23
  layout: TmpLayout;
24
24
  };
25
25
  export declare function isCorePackageRoot(projectRoot: string): boolean;
26
- export declare function resolveRootFolderPath(tmp: Record<string, unknown>, tmpFilePath: string, projectRoot: string): string;
26
+ export declare function resolveRootFolderPath(tmp: Record<string, unknown>, _tmpFilePath: string, _projectRoot: string): string;
27
27
  export declare function resolveLayoutPaths(configs?: Record<string, unknown>): TmpLayoutPaths;
28
28
  export declare function resolveMainFolderPath(configs?: Record<string, unknown>): string;
29
29
  export declare function buildTmpLayout(projectRoot: string, tmp: Record<string, unknown> | null, tmpFilePath: string | null): TmpLayout;
@@ -33,9 +33,9 @@ export declare function resolveTmpLayout(projectRoot?: string, options?: {
33
33
  }): TmpLayout;
34
34
  export declare function resolveTmpLayoutOrDefaults(projectRoot?: string): TmpLayout;
35
35
  export declare function resolveBundledCoreTmpPath(projectRoot?: string): string;
36
- export declare function ownerTmpFilePath(projectRoot?: string, layout?: TmpLayout): string;
36
+ export declare function ownerTmpFilePath(projectRoot?: string, _layout?: TmpLayout, configs?: Record<string, unknown>): string;
37
37
  export declare function ensureTmpFile(projectRoot?: string, options?: {
38
- patchServiceName?: boolean;
38
+ patchProjectName?: boolean;
39
39
  templatePath?: string;
40
40
  }): {
41
41
  tmpFilePath: string;
@@ -1 +1,229 @@
1
- import U from"node:fs";import J from"node:path";import z from"yaml";import{Constants as I}from "../../../utils/constants/index.js";import{findAllFilesRecursively as L,findFileRecursively as A}from "../../../utils/helpers/core/paths.js";import{normalizeTmpDocument as D,readTmpServiceBlock as B,normalizeRootFolder as b,normalizeSourceFolder as x,resolveServiceLayoutPaths as k}from "../../../utils/helpers/tmp/tmp-schema.js";function M(E,q){return`${E}${q.startsWith(".")?q:`.${q}`}`}export function coreCanonicalTmpPath(E=process.cwd()){return J.join(J.resolve(E),I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension))}export function assertCoreTmpGuard(E,q){if(!isCorePackageRoot(E))return;const H=coreCanonicalTmpPath(E);if(J.resolve(q)!==J.resolve(H))throw Error(`${I.packageName}: tmp.yml must stay at ${I.packageRootFolder}/tmp.yml (expected ${H}, got ${q})`)}function N(E,q){const H=J.resolve(E),K=J.resolve(q);return L(H,I.tmpBaseName,I.tmpExtension).filter((Q)=>J.resolve(Q)!==K)}export function ensureCoreTmpEntry(E=process.cwd(),q={}){const H=J.resolve(E);if(!isCorePackageRoot(H))throw Error(`ensureCoreTmpEntry is only for ${I.packageName} package root`);const K=coreCanonicalTmpPath(H),Q=N(H,K);if(Q.length>0){const X=Q.map((W)=>J.relative(H,W)).join(", ");throw Error(`${I.packageName}: tmp.yml must only exist under ${I.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=J.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=J.join(J.resolve(E),"package.json");if(!U.existsSync(q))return!1;try{return JSON.parse(U.readFileSync(q,"utf8")).name===I.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=J.relative(J.resolve(H),J.dirname(J.resolve(q)));if(W&&W!==".")return W;return I.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 I.mainSourceFolder}export function buildTmpLayout(E,q,H){const K=J.resolve(E),Q=q?D(q).configs:void 0,X=q&&H&&!isCorePackageRoot(K)?resolveRootFolderPath(q,H,K):I.packageRootFolder,W=J.join(K,X),Y=resolveLayoutPaths(Q),V=resolveMainFolderPath(Q),Z={tests:J.join(W,Y.tests),environments:J.join(W,Y.environments),dist:J.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??I.tmpBaseName,K=q.ext??I.tmpExtension,Q=S(E,H,K);if(!Q)throw Error(`${M(H,K)} not found under ${J.resolve(E)}`);if(isCorePackageRoot(J.resolve(E)))assertCoreTmpGuard(E,Q);return buildTmpLayout(E,_(Q),Q)}export function resolveTmpLayoutOrDefaults(E=process.cwd()){const q=S(E,I.tmpBaseName,I.tmpExtension);if(!q)return buildTmpLayout(E,null,null);return buildTmpLayout(E,_(q),q)}export function resolveBundledCoreTmpPath(E=process.cwd()){if(U.existsSync(I.bundledCoreTmpPath))return I.bundledCoreTmpPath;let q=J.resolve(E);while(q!==J.dirname(q)){const H=J.join(q,"node_modules","@xrystal","core",I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension));if(U.existsSync(H))return H;const K=J.join(q,"package.json");if(U.existsSync(K)){if(JSON.parse(U.readFileSync(K,"utf8")).name===I.packageName){const X=J.join(q,I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension));if(U.existsSync(X))return X}}q=J.dirname(q)}throw Error(`${I.packageName} bundled ${I.packageRootFolder}/tmp.yml not found`)}export function ownerTmpFilePath(E=process.cwd(),q){const H=q??resolveTmpLayoutOrDefaults(E);return J.join(H.rootFolderAbs,M(I.tmpBaseName,I.tmpExtension))}export function ensureTmpFile(E=process.cwd(),q={}){const H=J.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)=>J.relative(H,w)).join(", ");throw Error(`${I.packageName}: tmp.yml must only exist under ${I.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,I.tmpBaseName,I.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(`${I.packageName} bundled ${I.packageRootFolder}/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=J.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
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import yaml from 'yaml';
4
+ import { Constants } from '../../../utils/constants/index.js';
5
+ import { findAllFilesRecursively, findFileRecursively } from '../../../utils/helpers/core/paths.js';
6
+ import { normalizeTmpDocument, normalizeRootFolder, normalizeSourceFolder, resolveMergedPaths, resolveTmpAbsPath } from '../../../utils/helpers/tmp/tmp-schema.js';
7
+ function formatTmpTarget(name, ext) {
8
+ return `${name}${ext.startsWith('.') ? ext : `.${ext}`}`;
9
+ }
10
+ export function coreCanonicalTmpPath(projectRoot = process.cwd()) {
11
+ return path.join(path.resolve(projectRoot), Constants.packageRootFolder, formatTmpTarget(Constants.tmpBaseName, Constants.tmpExtension));
12
+ }
13
+ export function assertCoreTmpGuard(projectRoot, tmpFilePath) {
14
+ if (!isCorePackageRoot(projectRoot))
15
+ return;
16
+ const canonical = coreCanonicalTmpPath(projectRoot);
17
+ if (path.resolve(tmpFilePath) !== path.resolve(canonical)) {
18
+ throw new Error(`${Constants.packageName}: tmp.yml must stay at ${Constants.packageRootFolder}/tmp.yml (expected ${canonical}, got ${tmpFilePath})`);
19
+ }
20
+ }
21
+ function findStrayCoreTmpFiles(projectRoot, canonicalPath) {
22
+ const resolvedRoot = path.resolve(projectRoot);
23
+ const canonical = path.resolve(canonicalPath);
24
+ const templatesPrefix = `${Constants.packageRootFolder}/templates/`;
25
+ return findAllFilesRecursively(resolvedRoot, Constants.tmpBaseName, Constants.tmpExtension).filter((filePath) => {
26
+ if (path.resolve(filePath) === canonical)
27
+ return false;
28
+ const rel = path.relative(resolvedRoot, filePath).replace(/\\/g, '/');
29
+ return !rel.startsWith(templatesPrefix);
30
+ });
31
+ }
32
+ export function ensureCoreTmpEntry(projectRoot = process.cwd(), options = {}) {
33
+ const resolvedRoot = path.resolve(projectRoot);
34
+ if (!isCorePackageRoot(resolvedRoot)) {
35
+ throw new Error(`ensureCoreTmpEntry is only for ${Constants.packageName} package root`);
36
+ }
37
+ const canonical = coreCanonicalTmpPath(resolvedRoot);
38
+ const strays = findStrayCoreTmpFiles(resolvedRoot, canonical);
39
+ if (strays.length > 0) {
40
+ const rel = strays.map((p) => path.relative(resolvedRoot, p)).join(', ');
41
+ throw new Error(`${Constants.packageName}: tmp.yml must only exist under ${Constants.packageRootFolder}/. Remove extra copies: ${rel}`);
42
+ }
43
+ if (fs.existsSync(canonical)) {
44
+ assertCoreTmpGuard(resolvedRoot, canonical);
45
+ return {
46
+ tmpFilePath: canonical,
47
+ created: false,
48
+ layout: buildTmpLayout(resolvedRoot, readTmpFile(canonical), canonical),
49
+ };
50
+ }
51
+ return ensureTmpFile(resolvedRoot, { ...options, patchProjectName: false });
52
+ }
53
+ function resolveTmpFilePath(projectRoot, tmpFileName, ext) {
54
+ const resolvedRoot = path.resolve(projectRoot);
55
+ if (isCorePackageRoot(resolvedRoot)) {
56
+ const canonical = coreCanonicalTmpPath(resolvedRoot);
57
+ return fs.existsSync(canonical) ? canonical : null;
58
+ }
59
+ return findFileRecursively(resolvedRoot, tmpFileName, ext);
60
+ }
61
+ function readTmpFile(filePath) {
62
+ return yaml.parse(fs.readFileSync(filePath, 'utf8'));
63
+ }
64
+ export function isCorePackageRoot(projectRoot) {
65
+ const pkgPath = path.join(path.resolve(projectRoot), 'package.json');
66
+ if (!fs.existsSync(pkgPath))
67
+ return false;
68
+ try {
69
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
70
+ return pkg.name === Constants.packageName;
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
76
+ export function resolveRootFolderPath(tmp, _tmpFilePath, _projectRoot) {
77
+ const configs = normalizeTmpDocument(tmp).configs;
78
+ return normalizeRootFolder(resolveMergedPaths(configs).root);
79
+ }
80
+ export function resolveLayoutPaths(configs) {
81
+ return resolveMergedPaths(configs).special;
82
+ }
83
+ export function resolveMainFolderPath(configs) {
84
+ return normalizeSourceFolder(resolveMergedPaths(configs).source);
85
+ }
86
+ export function buildTmpLayout(projectRoot, tmp, tmpFilePath) {
87
+ const resolvedRoot = path.resolve(projectRoot);
88
+ const configs = tmp
89
+ ? normalizeTmpDocument(tmp).configs
90
+ : undefined;
91
+ const rootFolderPath = tmp && tmpFilePath && !isCorePackageRoot(resolvedRoot)
92
+ ? resolveRootFolderPath(tmp, tmpFilePath, resolvedRoot)
93
+ : Constants.packageRootFolder;
94
+ const rootFolderAbs = path.join(resolvedRoot, rootFolderPath);
95
+ const paths = resolveLayoutPaths(configs);
96
+ const mainFolderPath = resolveMainFolderPath(configs);
97
+ const pathsAbs = {
98
+ tests: path.join(rootFolderAbs, paths.tests),
99
+ environments: path.join(rootFolderAbs, paths.environments),
100
+ dist: path.join(rootFolderAbs, paths.dist),
101
+ };
102
+ return {
103
+ projectRoot: resolvedRoot,
104
+ rootFolderPath,
105
+ rootFolderAbs,
106
+ tmpFilePath,
107
+ mainFolderPath,
108
+ paths,
109
+ pathsAbs,
110
+ };
111
+ }
112
+ export function resolveTmpLayout(projectRoot = process.cwd(), options = {}) {
113
+ const tmpFileName = options.tmpFileName ?? Constants.tmpBaseName;
114
+ const ext = options.ext ?? Constants.tmpExtension;
115
+ const tmpFilePath = resolveTmpFilePath(projectRoot, tmpFileName, ext);
116
+ if (!tmpFilePath) {
117
+ throw new Error(`${formatTmpTarget(tmpFileName, ext)} not found under ${path.resolve(projectRoot)}`);
118
+ }
119
+ if (isCorePackageRoot(path.resolve(projectRoot))) {
120
+ assertCoreTmpGuard(projectRoot, tmpFilePath);
121
+ }
122
+ return buildTmpLayout(projectRoot, readTmpFile(tmpFilePath), tmpFilePath);
123
+ }
124
+ export function resolveTmpLayoutOrDefaults(projectRoot = process.cwd()) {
125
+ const tmpFilePath = resolveTmpFilePath(projectRoot, Constants.tmpBaseName, Constants.tmpExtension);
126
+ if (!tmpFilePath) {
127
+ return buildTmpLayout(projectRoot, null, null);
128
+ }
129
+ return buildTmpLayout(projectRoot, readTmpFile(tmpFilePath), tmpFilePath);
130
+ }
131
+ export function resolveBundledCoreTmpPath(projectRoot = process.cwd()) {
132
+ const apiTemplate = Constants.bundledApiServiceTmpPath;
133
+ if (apiTemplate && fs.existsSync(apiTemplate)) {
134
+ return apiTemplate;
135
+ }
136
+ if (fs.existsSync(Constants.bundledCoreTmpPath)) {
137
+ return Constants.bundledCoreTmpPath;
138
+ }
139
+ let dir = path.resolve(projectRoot);
140
+ while (dir !== path.dirname(dir)) {
141
+ const candidate = path.join(dir, 'node_modules', '@xrystal', 'core', Constants.packageRootFolder, formatTmpTarget(Constants.tmpBaseName, Constants.tmpExtension));
142
+ if (fs.existsSync(candidate))
143
+ return candidate;
144
+ const pkgPath = path.join(dir, 'package.json');
145
+ if (fs.existsSync(pkgPath)) {
146
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
147
+ if (pkg.name === Constants.packageName) {
148
+ const inCore = path.join(dir, Constants.packageRootFolder, formatTmpTarget(Constants.tmpBaseName, Constants.tmpExtension));
149
+ if (fs.existsSync(inCore))
150
+ return inCore;
151
+ }
152
+ }
153
+ dir = path.dirname(dir);
154
+ }
155
+ throw new Error(`${Constants.packageName} bundled ${Constants.packageRootFolder}/tmp.yml not found`);
156
+ }
157
+ export function ownerTmpFilePath(projectRoot = process.cwd(), _layout, configs) {
158
+ if (configs) {
159
+ return resolveTmpAbsPath(projectRoot, configs);
160
+ }
161
+ return coreCanonicalTmpPath(projectRoot);
162
+ }
163
+ export function ensureTmpFile(projectRoot = process.cwd(), options = {}) {
164
+ const resolvedRoot = path.resolve(projectRoot);
165
+ const patchProjectName = options.patchProjectName ?? true;
166
+ if (isCorePackageRoot(resolvedRoot)) {
167
+ const canonical = coreCanonicalTmpPath(resolvedRoot);
168
+ const strays = findStrayCoreTmpFiles(resolvedRoot, canonical);
169
+ if (strays.length > 0) {
170
+ const rel = strays.map((p) => path.relative(resolvedRoot, p)).join(', ');
171
+ throw new Error(`${Constants.packageName}: tmp.yml must only exist under ${Constants.packageRootFolder}/. Remove extra copies: ${rel}`);
172
+ }
173
+ if (fs.existsSync(canonical)) {
174
+ assertCoreTmpGuard(resolvedRoot, canonical);
175
+ return {
176
+ tmpFilePath: canonical,
177
+ created: false,
178
+ layout: buildTmpLayout(resolvedRoot, readTmpFile(canonical), canonical),
179
+ };
180
+ }
181
+ }
182
+ else {
183
+ const existing = findFileRecursively(resolvedRoot, Constants.tmpBaseName, Constants.tmpExtension);
184
+ if (existing) {
185
+ return {
186
+ tmpFilePath: existing,
187
+ created: false,
188
+ layout: buildTmpLayout(resolvedRoot, readTmpFile(existing), existing),
189
+ };
190
+ }
191
+ }
192
+ const resolvedTemplate = options.templatePath ?? resolveBundledCoreTmpPath(resolvedRoot);
193
+ if (!fs.existsSync(resolvedTemplate)) {
194
+ throw new Error(`${Constants.packageName} bundled ${Constants.packageRootFolder}/tmp.yml not found`);
195
+ }
196
+ let content = fs.readFileSync(resolvedTemplate, 'utf8');
197
+ const templateDoc = readTmpFile(resolvedTemplate);
198
+ const templateConfigs = templateDoc.configs ?? {};
199
+ const merged = resolveMergedPaths(templateConfigs);
200
+ const targetPath = ownerTmpFilePath(resolvedRoot, undefined, templateConfigs);
201
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
202
+ if (patchProjectName) {
203
+ try {
204
+ const pkgPath = path.join(resolvedRoot, 'package.json');
205
+ if (fs.existsSync(pkgPath)) {
206
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
207
+ const projectName = typeof pkg.name === 'string'
208
+ ? pkg.name.replace(/^@/, '').replace(/\//g, '-').replace(/-svc$/, '')
209
+ : null;
210
+ if (projectName) {
211
+ const tmp = yaml.parse(content);
212
+ tmp.project = { name: projectName };
213
+ content = yaml.stringify(tmp);
214
+ }
215
+ }
216
+ }
217
+ catch {
218
+ }
219
+ }
220
+ fs.writeFileSync(targetPath, content);
221
+ return {
222
+ tmpFilePath: targetPath,
223
+ created: true,
224
+ layout: buildTmpLayout(resolvedRoot, readTmpFile(targetPath), targetPath),
225
+ };
226
+ }
227
+ export function resolveTmpLayoutEnsured(projectRoot = process.cwd()) {
228
+ return ensureTmpFile(projectRoot).layout;
229
+ }
@@ -1 +1,48 @@
1
- import{PolarityTypeEnum as $}from "../../../utils/models/index.js";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
+ import { PolarityTypeEnum } from "../../../utils/models/index.js";
2
+ export function dateZoneConverter({ polarity, date, zone, factor = 1000 }) {
3
+ let convertedZoneTime = null;
4
+ if (polarity === PolarityTypeEnum.NEGATIVE) {
5
+ convertedZoneTime = date.getTime() - factor * zone;
6
+ }
7
+ else {
8
+ convertedZoneTime = date.getTime() + factor * zone;
9
+ }
10
+ return new Date(convertedZoneTime).toISOString();
11
+ }
12
+ export function convertDate(date, splitCharacter = '/', replaceCharacter = '-') {
13
+ const convertDate = date.split(splitCharacter).map((value, index) => index !== 2 ? replaceCharacter : value);
14
+ return convertDate;
15
+ }
16
+ export function convertTime(time, splitCharacter = ':', replaceCharacter = '-') {
17
+ const convertDate = time.split(splitCharacter).map((value, index) => index !== 2 ? replaceCharacter : value);
18
+ return convertDate;
19
+ }
20
+ export function getDateAndTime({ getDate = true, getTime = true, dateCharacter = '-', timeCharacter = ':', separatorCharacter = '&' }) {
21
+ const date = new Date();
22
+ let formattedDate = '';
23
+ if (!getDate && !getTime) {
24
+ throw new Error("Invalid options! Required one true value");
25
+ }
26
+ if (getDate) {
27
+ const day = date.getDate().toString().padStart(2, '0');
28
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
29
+ const year = date.getFullYear();
30
+ formattedDate = `${year}${dateCharacter}${month}${dateCharacter}${day}`;
31
+ }
32
+ if (getTime) {
33
+ const hours = date.getHours().toString().padStart(2, '0');
34
+ const minutes = date.getMinutes().toString().padStart(2, '0');
35
+ const seconds = date.getSeconds().toString().padStart(2, '0');
36
+ formattedDate = `${hours}${timeCharacter}${minutes}${timeCharacter}${seconds}`;
37
+ }
38
+ if (getDate && getTime) {
39
+ const day = date.getDate().toString().padStart(2, '0');
40
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
41
+ const year = date.getFullYear();
42
+ const hours = date.getHours().toString().padStart(2, '0');
43
+ const minutes = date.getMinutes().toString().padStart(2, '0');
44
+ const seconds = date.getSeconds().toString().padStart(2, '0');
45
+ formattedDate = `${year}${dateCharacter}${month}${dateCharacter}${day}${separatorCharacter}${hours}${timeCharacter}${minutes}${timeCharacter}${seconds}`;
46
+ }
47
+ return formattedDate;
48
+ }
@@ -1 +1,53 @@
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/index.js";import{getFramework as T}from "../../../utils/helpers/framework/index.js";import{getDtoRuntime as U}from "../../../utils/helpers/runtime/index.js";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
+ import { expressSink } from '@xrystal/dto/express';
2
+ import { nodeSink } from '@xrystal/dto/node';
3
+ import { fetchSink } from '@xrystal/dto/fetch';
4
+ import { elysiaSink } from '@xrystal/dto/elysia';
5
+ import { websocketSink } from '@xrystal/dto/websocket';
6
+ import { socketIoSink } from '@xrystal/dto/socketio';
7
+ import { FrameworkEnum, ProtocolEnum } from '../../../utils/models/index.js';
8
+ import { getFramework } from '../../../utils/helpers/framework/index.js';
9
+ import { getDtoRuntime } from '../../../utils/helpers/runtime/index.js';
10
+ export { expressSink } from '@xrystal/dto/express';
11
+ export { nodeSink } from '@xrystal/dto/node';
12
+ export { fetchSink } from '@xrystal/dto/fetch';
13
+ export { elysiaSink } from '@xrystal/dto/elysia';
14
+ export { websocketSink } from '@xrystal/dto/websocket';
15
+ export { socketIoSink } from '@xrystal/dto/socketio';
16
+ export { dispatchExpressResponse, dispatchNodeResponse, toFetchResponse, applyElysiaTransport, dispatchWebSocketMessage, dispatchSocketIoMessage, } from '@xrystal/dto/response';
17
+ const isFinalResult = (value) => !!value && typeof value === 'object' && 'body' in value && 'statusCode' in value;
18
+ const isRawResponse = (value) => value instanceof Response || value instanceof Blob || value instanceof Uint8Array || value instanceof ArrayBuffer;
19
+ const socketOf = (store) => store.socket ?? store.ctx?.ws ?? store.ctx;
20
+ const socketEvent = () => getDtoRuntime().config.socket?.event ?? 'response';
21
+ export function dispatchResult(result, store, res) {
22
+ if (result === undefined || result === null)
23
+ return;
24
+ if (isRawResponse(result))
25
+ return result;
26
+ if (!isFinalResult(result))
27
+ return result;
28
+ if (store.protocol === ProtocolEnum.SOCKETIO || store.framework === FrameworkEnum.SOCKETIO) {
29
+ socketIoSink(socketOf(store), socketEvent()).dispatch(result);
30
+ return;
31
+ }
32
+ if (store.protocol === ProtocolEnum.WEBSOCKET || store.framework === FrameworkEnum.WEBSOCKET) {
33
+ websocketSink(socketOf(store)).dispatch(result);
34
+ return;
35
+ }
36
+ const fw = store.framework ?? getFramework();
37
+ const response = res;
38
+ switch (fw) {
39
+ case FrameworkEnum.EXPRESS:
40
+ if (response && !response.headersSent)
41
+ expressSink(res).dispatch(result);
42
+ return;
43
+ case FrameworkEnum.NODE:
44
+ if (response && !response.headersSent)
45
+ nodeSink(res).dispatch(result);
46
+ return;
47
+ case FrameworkEnum.FETCH:
48
+ return fetchSink.dispatch(result);
49
+ case FrameworkEnum.ELYSIA:
50
+ default:
51
+ return elysiaSink(store.ctx?.set ?? {}).dispatch(result);
52
+ }
53
+ }
@@ -1 +1,10 @@
1
- export{DTO,createDTO}from"@xrystal/dto/dto";export{ResponseDTO,Builder,createBuilderProxy,ResponsePresets,assembleResponseBody,dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";export{expressSink,expressMiddleware,ExpressAdapter}from"@xrystal/dto/express";export{nodeSink,nodeMiddleware,NodeAdapter}from"@xrystal/dto/node";export{fetchSink,fetchDerive,FetchAdapter}from"@xrystal/dto/fetch";export{elysiaSink,ElysiaAdapter}from"@xrystal/dto/elysia";export{websocketSink,WebSocketAdapter}from"@xrystal/dto/websocket";export{socketIoSink,SocketIoAdapter}from"@xrystal/dto/socketio";export{LogDTO,assembleLogBody}from"@xrystal/dto/log";export{QueueDTO,assembleQueueMessage}from"@xrystal/dto/queue";
1
+ export { DTO, createDTO } from '@xrystal/dto/dto';
2
+ export { ResponseDTO, Builder, createBuilderProxy, ResponsePresets, assembleResponseBody, dispatchExpressResponse, dispatchNodeResponse, toFetchResponse, applyElysiaTransport, dispatchWebSocketMessage, dispatchSocketIoMessage, } from '@xrystal/dto/response';
3
+ export { expressSink, expressMiddleware, ExpressAdapter } from '@xrystal/dto/express';
4
+ export { nodeSink, nodeMiddleware, NodeAdapter } from '@xrystal/dto/node';
5
+ export { fetchSink, fetchDerive, FetchAdapter } from '@xrystal/dto/fetch';
6
+ export { elysiaSink, ElysiaAdapter } from '@xrystal/dto/elysia';
7
+ export { websocketSink, WebSocketAdapter } from '@xrystal/dto/websocket';
8
+ export { socketIoSink, SocketIoAdapter } from '@xrystal/dto/socketio';
9
+ export { LogDTO, assembleLogBody, } from '@xrystal/dto/log';
10
+ export { QueueDTO, assembleQueueMessage, } from '@xrystal/dto/queue';
@@ -1 +1,44 @@
1
- function mongoFilter(t,n,r){const e={};if(!r)throw Error("MongoFilter helper property is required.");e[r]=e[r]||{};if(t&&n){e[r].$gte=t;e[r].$lte=n}else if(t)e[r].$gte=t;else if(n)e[r].$lte=n;return e}function filterUniqueOnce({arr:t,key:n,uniqueOnceValues:r}){const e=new Set;return t.filter((f)=>{const i=f[n];if(r.includes(i)){if(e.has(i))return!1;e.add(i);return!0}return!0})}function filterSortByPropOrder({arr:t,key:n,desiredOrder:r}){const e=new Map;r.forEach((f,i)=>e.set(f,i));return[...t].sort((f,i)=>{const o=e.get(f[n])??1/0,u=e.get(i[n])??1/0;return o-u})}function filterRemoveItemsByProps({arr:t,key:n,valuesToRemove:r}){return t.filter((e)=>!r.includes(e[n]))}export{mongoFilter,filterUniqueOnce,filterSortByPropOrder,filterRemoveItemsByProps};
1
+ function mongoFilter(start, end, objPath) {
2
+ const filter = {};
3
+ if (!objPath) {
4
+ throw new Error('MongoFilter helper property is required.');
5
+ }
6
+ filter[objPath] = filter[objPath] || {};
7
+ if (start && end) {
8
+ filter[objPath].$gte = start;
9
+ filter[objPath].$lte = end;
10
+ }
11
+ else if (start) {
12
+ filter[objPath].$gte = start;
13
+ }
14
+ else if (end) {
15
+ filter[objPath].$lte = end;
16
+ }
17
+ return filter;
18
+ }
19
+ function filterUniqueOnce({ arr, key, uniqueOnceValues }) {
20
+ const seen = new Set();
21
+ return arr.filter(item => {
22
+ const val = item[key];
23
+ if (uniqueOnceValues.includes(val)) {
24
+ if (seen.has(val))
25
+ return false;
26
+ seen.add(val);
27
+ return true;
28
+ }
29
+ return true;
30
+ });
31
+ }
32
+ function filterSortByPropOrder({ arr, key, desiredOrder }) {
33
+ const orderMap = new Map();
34
+ desiredOrder.forEach((value, index) => orderMap.set(value, index));
35
+ return [...arr].sort((a, b) => {
36
+ const aIndex = orderMap.get(a[key]) ?? Infinity;
37
+ const bIndex = orderMap.get(b[key]) ?? Infinity;
38
+ return aIndex - bIndex;
39
+ });
40
+ }
41
+ function filterRemoveItemsByProps({ arr, key, valuesToRemove }) {
42
+ return arr.filter(item => !valuesToRemove.includes(item[key]));
43
+ }
44
+ export { mongoFilter, filterUniqueOnce, filterSortByPropOrder, filterRemoveItemsByProps };
@@ -1 +1,18 @@
1
- import{getRuntimeTmpConfigs as q}from "../../../utils/helpers/tmp/runtime-tmp.js";import{FrameworkEnum as j}from "../../../utils/models/index.js";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
+ import { getRuntimeTmpConfigs } from '../../../utils/helpers/tmp/runtime-tmp.js';
2
+ import { FrameworkEnum } from '../../../utils/models/index.js';
3
+ const values = new Set(Object.values(FrameworkEnum));
4
+ export function parseFramework(value) {
5
+ const key = value ? String(value).toLowerCase() : undefined;
6
+ return key && values.has(key) ? key : FrameworkEnum.ELYSIA;
7
+ }
8
+ export function getFramework(override) {
9
+ if (override)
10
+ return override;
11
+ try {
12
+ const configs = getRuntimeTmpConfigs();
13
+ return parseFramework(configs?.global?.framework);
14
+ }
15
+ catch {
16
+ return FrameworkEnum.ELYSIA;
17
+ }
18
+ }
@@ -1 +1,41 @@
1
- import{FrameworkEnum as G,ProtocolEnum as K}from "../../../utils/models/index.js";import{detectSocketProtocol as L}from "../../../utils/helpers/protocol/index.js";import{getFramework as M}from "../../../utils/helpers/framework/index.js";import{runAction as I}from "../../../utils/helpers/handlers/execute.js";import{Constants as N}from "../../../utils/constants/index.js";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(`[${N.packageName}] 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
+ import { FrameworkEnum, ProtocolEnum } from '../../../utils/models/index.js';
2
+ import { detectSocketProtocol } from '../../../utils/helpers/protocol/index.js';
3
+ import { getFramework } from '../../../utils/helpers/framework/index.js';
4
+ import { runAction } from '../../../utils/helpers/handlers/execute.js';
5
+ import { Constants } from '../../../utils/constants/index.js';
6
+ export function toRealtimeHandler(action, protocol) {
7
+ const runFor = (socket) => {
8
+ const resolved = detectSocketProtocol(socket, protocol);
9
+ return runAction({ socket: socket, ctx: { ws: socket }, protocol: resolved }, action);
10
+ };
11
+ const handler = (socket) => runFor(socket);
12
+ handler.with = (socket) => () => runFor(socket);
13
+ return handler;
14
+ }
15
+ export const toHandler = (action, framework) => {
16
+ const fw = framework ?? getFramework();
17
+ switch (fw) {
18
+ case FrameworkEnum.ELYSIA:
19
+ return (elysiaCtx) => runAction({ framework: fw, ctx: elysiaCtx }, action);
20
+ case FrameworkEnum.FETCH:
21
+ return (req, serverCtx) => runAction({ framework: fw, ctx: { request: req, ...serverCtx } }, action);
22
+ case FrameworkEnum.NODE:
23
+ return (req, res) => runAction({ framework: fw, req: req, res: res }, action, res);
24
+ case FrameworkEnum.EXPRESS:
25
+ return (req, res, next) => {
26
+ runAction({
27
+ framework: fw,
28
+ req: req,
29
+ res: res,
30
+ metadata: { locals: res.locals || {} },
31
+ }, action, res).catch(next);
32
+ };
33
+ case FrameworkEnum.WEBSOCKET:
34
+ case FrameworkEnum.SOCKETIO:
35
+ throw new Error(`[${Constants.packageName}] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })`);
36
+ default:
37
+ return (elysiaCtx) => runAction({ framework: FrameworkEnum.ELYSIA, ctx: elysiaCtx }, action);
38
+ }
39
+ };
40
+ export const toWebSocket = (socket, action) => toRealtimeHandler(action, ProtocolEnum.WEBSOCKET)(socket);
41
+ export const toSocketIo = (socket, action) => toRealtimeHandler(action, ProtocolEnum.SOCKETIO)(socket);