@xrystal/core 3.48.0 → 3.48.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 (44) hide show
  1. package/package.json +1 -1
  2. package/x/dist/loader/configs/index.js +1 -1
  3. package/x/dist/loader/kafka/index.js +1 -1
  4. package/x/dist/loader/system/index.js +1 -1
  5. package/x/dist/project/index.js +1 -1
  6. package/x/dist/utils/constants/index.js +1 -1
  7. package/x/dist/utils/constants/package-root.js +1 -1
  8. package/x/dist/utils/helpers/context/index.js +1 -1
  9. package/x/dist/utils/helpers/core/handlebars-resolve.js +1 -1
  10. package/x/dist/utils/helpers/core/index.js +1 -1
  11. package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
  12. package/x/dist/utils/helpers/date/index.js +1 -1
  13. package/x/dist/utils/helpers/dispatch/index.js +1 -1
  14. package/x/dist/utils/helpers/framework/index.js +1 -1
  15. package/x/dist/utils/helpers/handlers/adapters.js +1 -1
  16. package/x/dist/utils/helpers/handlers/execute.js +1 -1
  17. package/x/dist/utils/helpers/handlers/index.js +1 -1
  18. package/x/dist/utils/helpers/index.d.ts +2 -0
  19. package/x/dist/utils/helpers/index.js +1 -1
  20. package/x/dist/utils/helpers/kafka/index.js +1 -1
  21. package/x/dist/utils/helpers/middleware/index.js +1 -1
  22. package/x/dist/utils/helpers/mongo/index.d.ts +8 -0
  23. package/x/dist/utils/helpers/mongo/index.js +1 -0
  24. package/x/dist/utils/helpers/path/index.js +1 -1
  25. package/x/dist/utils/helpers/path/resolve-alias-path.js +1 -1
  26. package/x/dist/utils/helpers/protocol/index.js +1 -1
  27. package/x/dist/utils/helpers/redis/index.d.ts +10 -0
  28. package/x/dist/utils/helpers/redis/index.js +1 -0
  29. package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
  30. package/x/dist/utils/helpers/state/index.js +1 -1
  31. package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
  32. package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
  33. package/x/dist/utils/helpers/state/scopes.js +1 -1
  34. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
  35. package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -1
  36. package/x/dist/utils/helpers/tmp/seed-from-tmp.js +1 -1
  37. package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
  38. package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
  39. package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
  40. package/x/dist/utils/helpers/tmp/toolchain-heal.js +2 -2
  41. package/x/dist/utils/models/classes/class.clients.js +1 -1
  42. package/x/dist/utils/models/classes/class.service-locator.js +1 -1
  43. package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
  44. package/x/dist/utils/models/classes/class.x.js +1 -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.48.0",
4
+ "version": "3.48.1",
5
5
  "description": "microservice runtime library",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -1 +1 @@
1
- import E from"node:path";import c from"lodash";import{pathToFileURL as l}from"node:url";import{Constants as i}from"../../utils/constants";import{resolveTmpLoadPath as v}from"../../utils/helpers/path/resolve-alias-path";import{bindLoaderTmpSync as h}from"../../utils/helpers/tmp/loader-tmp-sync";export default class Configs{publicFolderName=i.publicFolderName;kafkaLogsTopic=i.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();h(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,o=e.configs.service.loaders.configs.loadPath,r=v(o,e,s),a=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:E.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 a,p=t?.default||t?.configs||t||{},f=c.mergeWith({},this.#e,p,(n,m)=>{if(c.isArray(n))return n.concat(m)});this.#e=Object.freeze(f)}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
+ import Q from"node:path";import H from"lodash";import{pathToFileURL as W}from"node:url";import{Constants as I}from"../../utils/constants";import{resolveTmpLoadPath as X}from"../../utils/helpers/path/resolve-alias-path";import{bindLoaderTmpSync as Y}from"../../utils/helpers/tmp/loader-tmp-sync";export default class Configs{publicFolderName=I.publicFolderName;kafkaLogsTopic=I.kafkaLogsTopic;#z;#q;constructor({system:z}){this.#z=z;return new Proxy(this,{get:(A,B)=>{return A[B]||A.config?.[B]}})}onInit=async()=>{await this.syncFromTmp();Y(this)};syncFromTmp=async()=>{const z=process.cwd(),q=this.#z.tmp,A=q.configs.service.loaders.configs.loadPath,B=X(A,q,z),J=import(W(B).href);this.#q={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:q.configs.rootFolderPath||"x",projectName:q.project.name,serviceName:q.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:Q.resolve(q.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:q.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:z,env:"development"};try{const E=await J,K=E?.default||E?.configs||E||{},M=H.mergeWith({},this.#q,K,(G,N)=>{if(H.isArray(G))return G.concat(N)});this.#q=Object.freeze(M)}catch{this.#q=Object.freeze(this.#q)}};setConfig(z){const q=Object.assign(this.#q,z);this.#q=Object.freeze(q)}_(z){return this.#q[z]}get all(){return this.#q}}
@@ -1 +1 @@
1
- import{Kafka as c,logLevel as l}from"kafkajs";import{bindLoaderTmpSync as k,resolveKafkaJsSsl as f}from"../../utils";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#r;#a;constructor({system:r,configs:a}){this.#r=r;this.#a=a}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();k(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#a.all?.kafkaClientId;this.brokers=this.#a.all?.kafkaBrokers;this.username=this.#a.all?.kafkaUsername;this.password=this.#a.all?.kafkaPassword;if(this.#a.all.isKafkaPassive)return;const r=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((a)=>a?.trim()).filter(Boolean);if(r.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:r,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:r,brokers:a,username:i,password:t})=>{const e={clientId:r,brokers:a,sasl:i&&t?{mechanism:"plain",username:i,password:t}:void 0,ssl:f(a),logLevel:l.ERROR,logCreator:()=>{return({level:s,log:n})=>{console.error(`Kafka ${n.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const s=new c(e);this._instance=s;this._producer=s.producer();await this.producer.connect();return s}catch(s){console.error(`Kafka ${s}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:r,kafkaTopics:a,isKafkaPassive:i}={isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaBrokers:process.env?.KAFKA_BROKERS,kafkaTopics:[...new Set([...this.#a.all.kafkaTopics])]};if(i===!0||!r)return;const t=Array.isArray(a)?a:[];if(t.length===0)return;const e=this._instance.admin();try{await e.connect();const s=await e.listTopics(),n=t.filter((o)=>!s.includes(o)).map((o)=>({topic:o,numPartitions:1,replicationFactor:1}));if(n.length>0)await e.createTopics({waitForLeaders:!0,topics:n})}catch(s){}finally{await e.disconnect()}};sendMessage=async(r,a)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:r,messages:[{value:JSON.stringify(a)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
1
+ import{Kafka as N,logLevel as O}from"kafkajs";import{bindLoaderTmpSync as Q,resolveKafkaJsSsl as R}from"../../utils";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#q;#h;constructor({system:q,configs:h}){this.#q=q;this.#h=h}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();Q(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 q=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((h)=>h?.trim()).filter(Boolean);if(q.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:q,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:q,brokers:h,username:F,password:E})=>{const D={clientId:q,brokers:h,sasl:F&&E?{mechanism:"plain",username:F,password:E}:void 0,ssl:R(h),logLevel:O.ERROR,logCreator:()=>{return({level:z,log:G})=>{console.error(`Kafka ${G.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const z=new N(D);this._instance=z;this._producer=z.producer();await this.producer.connect();return z}catch(z){console.error(`Kafka ${z}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:q,kafkaTopics:h,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||!q)return;const E=Array.isArray(h)?h:[];if(E.length===0)return;const D=this._instance.admin();try{await D.connect();const z=await D.listTopics(),G=E.filter((M)=>!z.includes(M)).map((M)=>({topic:M,numPartitions:1,replicationFactor:1}));if(G.length>0)await D.createTopics({waitForLeaders:!0,topics:G})}catch(z){}finally{await D.disconnect()}};sendMessage=async(q,h)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:q,messages:[{value:JSON.stringify(h)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
@@ -1 +1 @@
1
- import{G as m,notifyRuntimeTmpChange as o,onTmpReload as p,setRuntimeTmpConfigs as s}from"../../utils";import{normalizeTmpDocument as e}from"../../utils/helpers/tmp/tmp-schema";export default class System{_core={};_tmp={};cwd=process.cwd();g=m;onInit=async({core:i})=>{this._core=i;await this.applyTmp(this._core._);p((t)=>void this.applyTmp(t))};async applyTmp(i){this._tmp=e(i);const t=this._tmp.configs;s(t);this.g.configureFromTmp(this._tmp);await o(t)}get core(){return this._core}get tmp(){return this._tmp}}
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}}
@@ -1 +1 @@
1
- import e from"path";import{fileURLToPath as p}from"node:url";import{System as c,Configs as n,Logger as l,Events as m,Localizations as f,DtoRuntime as u,Clients as g,Controller as d,KafkaForCore as C}from"../loader";import{Constants as v,getCore as x,x as h}from"../utils";import{ensureCoreTmpEntry as E,isCorePackageRoot as S}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as y}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=x(),coreInit=async(s)=>{const{locales:o}=s;if(o)globalThis.__LOCAL_MESSAGES__=o};let t=!1;const a=e.dirname(p(import.meta.url)),L=e.join(a,"..","loader","**/*.{ts,js}"),T=e.join(a,"..","utils","**/class.x.{ts,js}"),_=async(s={})=>{if(t)return core;const o=process.cwd();if(S(o))E(o);y();try{await(await h.load([L],{exclude:[T]})).initialize([{service:c,props:{core}},{service:n,props:{}},{service:C,props:{}},{service:l,props:{}},{service:m,props:{}},{service:f,props:{}},{service:u,props:{}},{service:d,props:{}},{service:g,props:{}}]);t=!0;return core}catch(r){const i=r instanceof Error?r.message:String(r);console.error(`[${v.packageName} core failure]: ${i}`);throw r}};export default _;
1
+ import A from"path";import{fileURLToPath as O}from"node:url";import{System as Q,Configs as V,Logger as W,Events as X,Localizations as Y,DtoRuntime as Z,Clients as _,Controller as $,KafkaForCore as v}from"../loader";import{Constants as z,getCore as F,x as K}from"../utils";import{ensureCoreTmpEntry as U,isCorePackageRoot as b}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as j}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=F(),coreInit=async(B)=>{const{locales:q}=B;if(q)globalThis.__LOCAL_MESSAGES__=q};let I=!1;const J=A.dirname(O(import.meta.url)),k=A.join(J,"..","loader","**/*.{ts,js}"),x=A.join(J,"..","utils","**/class.x.{ts,js}"),G=async(B={})=>{if(I)return core;const q=process.cwd();if(b(q))U(q);j();try{await(await K.load([k],{exclude:[x]})).initialize([{service:Q,props:{core}},{service:V,props:{}},{service:v,props:{}},{service:W,props:{}},{service:X,props:{}},{service:Y,props:{}},{service:Z,props:{}},{service:$,props:{}},{service:_,props:{}}]);I=!0;return core}catch(w){const N=w instanceof Error?w.message:String(w);console.error(`[${z.packageName} core failure]: ${N}`);throw w}};export default G;
@@ -1 +1 @@
1
- import r from"node:path";import{packageRootDir as i}from"../../utils/constants/package-root";import e from"./defaults.json" with { type: 'json' };import{seedFromTmp as t}from"../../utils/helpers/tmp/seed-from-tmp";export const packageDefaults=Object.freeze({...e,mainSourceFolder:t.sourceFolder,framework:t.framework,layoutPaths:Object.freeze({...t.layout}),brand:Object.freeze({...e.brand}),runtimes:Object.freeze(Object.fromEntries(Object.entries(e.runtimes).map(([a,o])=>[a,Object.freeze({...o})]))),bundlers:Object.freeze([...e.bundlers]),buildDefaults:Object.freeze({...e.buildDefaults}),tmpWatchDefaults:Object.freeze({...e.tmpWatchDefaults}),cliBinNames:Object.freeze([...e.cliBinNames??[e.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const c=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static cliName=packageDefaults.cliName;static cliBinNames=packageDefaults.cliBinNames;static pathAliasKey=packageDefaults.pathAliasKey;static brand=packageDefaults.brand;static mainSourceFolder=packageDefaults.mainSourceFolder;static framework=packageDefaults.framework;static layoutPaths=packageDefaults.layoutPaths;static cliBinFile=packageDefaults.cliBinFile;static logTag=packageDefaults.packageName;static bundledCoreTmpPath=r.join(i,packageDefaults.packageRootFolder,c)}export{seedFromTmp,loadSeedFromBundledTmp}from"../../utils/helpers/tmp/seed-from-tmp";
1
+ import w from"node:path";import{packageRootDir as x}from"../../utils/constants/package-root";import b from"./defaults.json" with { type: 'json' };import{seedFromTmp as j}from"../../utils/helpers/tmp/seed-from-tmp";export const packageDefaults=Object.freeze({...b,mainSourceFolder:j.sourceFolder,framework:j.framework,layoutPaths:Object.freeze({...j.layout}),brand:Object.freeze({...b.brand}),runtimes:Object.freeze(Object.fromEntries(Object.entries(b.runtimes).map(([n,q])=>[n,Object.freeze({...q})]))),bundlers:Object.freeze([...b.bundlers]),buildDefaults:Object.freeze({...b.buildDefaults}),tmpWatchDefaults:Object.freeze({...b.tmpWatchDefaults}),cliBinNames:Object.freeze([...b.cliBinNames??[b.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const z=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static cliName=packageDefaults.cliName;static cliBinNames=packageDefaults.cliBinNames;static pathAliasKey=packageDefaults.pathAliasKey;static brand=packageDefaults.brand;static mainSourceFolder=packageDefaults.mainSourceFolder;static framework=packageDefaults.framework;static layoutPaths=packageDefaults.layoutPaths;static cliBinFile=packageDefaults.cliBinFile;static logTag=packageDefaults.packageName;static bundledCoreTmpPath=w.join(x,packageDefaults.packageRootFolder,z)}export{seedFromTmp,loadSeedFromBundledTmp}from"../../utils/helpers/tmp/seed-from-tmp";
@@ -1 +1 @@
1
- import o from"node:path";import{fileURLToPath as t}from"node:url";const r=o.dirname(t(import.meta.url));export const sourceDir=o.resolve(r,"..",".."),packageRootDir=o.resolve(r,"..","..","..");
1
+ import b from"node:path";import{fileURLToPath as w}from"node:url";const q=b.dirname(w(import.meta.url));export const sourceDir=b.resolve(q,"..",".."),packageRootDir=b.resolve(q,"..","..","..");
@@ -1 +1 @@
1
- import{AsyncLocalStorage as n}from"node:async_hooks";export const runContextStorage=new n;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(e,t){return runContextStorage.run(e,t)}export function runWithRequestId(e,t,r="http"){return runWithContext({requestId:e,kind:r},t)}export function runWithTrace(e,t,r){return runWithContext({requestId:e,kind:"job",label:r},t)}export function patchRunContext(e){const t=getRunContext();if(!t)return;Object.assign(t,e)}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 i from"handlebars";export function resolveObjWithHandlebars(e,t){if(typeof e==="string")return i.compile(e)(t);if(typeof e==="object"&&e!==null){const r=e;for(const n in r)r[n]=resolveObjWithHandlebars(r[n],t)}return e}
1
+ import C from"handlebars";export function resolveObjWithHandlebars(q,A){if(typeof q==="string")return C.compile(q)(A);if(typeof q==="object"&&q!==null){const z=q;for(const B in z)z[B]=resolveObjWithHandlebars(z[B],A)}return q}
@@ -1 +1 @@
1
- import{Constants as n,ProtocolEnum as c,TmpFileLoader as l}from"../../../utils/index.js";import{controllerContextStorage as i}from"../../../utils/helpers/context/controller-store";import{getTmpSnapshot as a}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as m}from"../../../utils/helpers/core/paths";import{parseProtocol as f}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export{resolveObjWithHandlebars}from"../../../utils/helpers/core/handlebars-resolve";export const getCore=()=>({_:a()}),getTmpConfig=({root:t=process.cwd(),tmpFileName:o=n.tmpBaseName,ext:r=n.tmpExtension}={})=>{const e=m(t,o,r);if(!e)throw Error(`${o}${r.startsWith(".")?r:`.${r}`} file not found`);return new l({filePath:e}).getResolvedTmpFile()},withProtocol=async(t,o=c.HTTP)=>{const r=f(o),e=i.getStore();if(e)e.protocol=r;return await t()},protocol=async(t,o=c.HTTP)=>withProtocol(t,o),argvsConverter=(t)=>{const o=t?.slice(2),r={};o.forEach((e)=>{if(e.startsWith("--")){console.log(e);const[s,p]=e.split("=");r[s.replace("--","")]=p||""}});return r},findExt=(t)=>{const o=t.split(".");return o[o.length-1]},changeExtensions=(t,o)=>{return t.replace(findExt(t),o)};
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";import{getTmpSnapshot as M}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as O}from"../../../utils/helpers/core/paths";import{parseProtocol as Q}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export{resolveObjWithHandlebars}from"../../../utils/helpers/core/handlebars-resolve";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 +1 @@
1
- import c from"node:fs";import n from"node:path";import x from"yaml";import{Constants as r}from"../../../utils/constants";import{findAllFilesRecursively as P,findFileRecursively as k}from"../../../utils/helpers/core/paths";import{normalizeTmpDocument as S,readTmpServiceBlock as F,normalizeRootFolder as T,normalizeSourceFolder as E,resolveServiceLayoutPaths as R}from"../../../utils/helpers/tmp/tmp-schema";function v(t,e){return`${t}${e.startsWith(".")?e:`.${e}`}`}export function coreCanonicalTmpPath(t=process.cwd()){return n.join(n.resolve(t),r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension))}export function assertCoreTmpGuard(t,e){if(!isCorePackageRoot(t))return;const o=coreCanonicalTmpPath(t);if(n.resolve(e)!==n.resolve(o))throw Error(`${r.packageName}: tmp.yml must stay at ${r.packageRootFolder}/tmp.yml (expected ${o}, got ${e})`)}function w(t,e){const o=n.resolve(t),s=n.resolve(e);return P(o,r.tmpBaseName,r.tmpExtension).filter((a)=>n.resolve(a)!==s)}export function ensureCoreTmpEntry(t=process.cwd(),e={}){const o=n.resolve(t);if(!isCorePackageRoot(o))throw Error(`ensureCoreTmpEntry is only for ${r.packageName} package root`);const s=coreCanonicalTmpPath(o),a=w(o,s);if(a.length>0){const p=a.map((l)=>n.relative(o,l)).join(", ");throw Error(`${r.packageName}: tmp.yml must only exist under ${r.packageRootFolder}/. Remove extra copies: ${p}`)}if(c.existsSync(s)){assertCoreTmpGuard(o,s);return{tmpFilePath:s,created:!1,layout:buildTmpLayout(o,f(s),s)}}return ensureTmpFile(o,{...e,patchServiceName:!1})}function N(t,e,o){const s=n.resolve(t);if(isCorePackageRoot(s)){const a=coreCanonicalTmpPath(s);return c.existsSync(a)?a:null}return k(s,e,o)}function f(t){return x.parse(c.readFileSync(t,"utf8"))}export function isCorePackageRoot(t){const e=n.join(n.resolve(t),"package.json");if(!c.existsSync(e))return!1;try{return JSON.parse(c.readFileSync(e,"utf8")).name===r.packageName}catch{return!1}}export function resolveRootFolderPath(t,e,o){const s=S(t).configs,a=F(s);if(a.paths?.root?.trim())return T(a.paths.root);const p=t.project;if(typeof p?.name==="string"&&p.name.trim())return p.name.trim();const l=n.relative(n.resolve(o),n.dirname(n.resolve(e)));if(l&&l!==".")return l;return r.packageRootFolder}export function resolveLayoutPaths(t){const e=F(t);return R(e)}export function resolveMainFolderPath(t){const e=F(t);if(e.paths?.source?.trim())return E(e.paths.source);return r.mainSourceFolder}export function buildTmpLayout(t,e,o){const s=n.resolve(t),a=e?S(e).configs:void 0,p=e&&o&&!isCorePackageRoot(s)?resolveRootFolderPath(e,o,s):r.packageRootFolder,l=n.join(s,p),m=resolveLayoutPaths(a),i=resolveMainFolderPath(a),u={tests:n.join(l,m.tests),environments:n.join(l,m.environments),dist:n.join(l,m.dist)};return{projectRoot:s,rootFolderPath:p,rootFolderAbs:l,tmpFilePath:o,mainFolderPath:i,paths:m,pathsAbs:u}}export function resolveTmpLayout(t=process.cwd(),e={}){const o=e.tmpFileName??r.tmpBaseName,s=e.ext??r.tmpExtension,a=N(t,o,s);if(!a)throw Error(`${v(o,s)} not found under ${n.resolve(t)}`);if(isCorePackageRoot(n.resolve(t)))assertCoreTmpGuard(t,a);return buildTmpLayout(t,f(a),a)}export function resolveTmpLayoutOrDefaults(t=process.cwd()){const e=N(t,r.tmpBaseName,r.tmpExtension);if(!e)return buildTmpLayout(t,null,null);return buildTmpLayout(t,f(e),e)}export function resolveBundledCoreTmpPath(t=process.cwd()){if(c.existsSync(r.bundledCoreTmpPath))return r.bundledCoreTmpPath;let e=n.resolve(t);while(e!==n.dirname(e)){const o=n.join(e,"node_modules","@xrystal","core",r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension));if(c.existsSync(o))return o;const s=n.join(e,"package.json");if(c.existsSync(s)){if(JSON.parse(c.readFileSync(s,"utf8")).name===r.packageName){const p=n.join(e,r.packageRootFolder,v(r.tmpBaseName,r.tmpExtension));if(c.existsSync(p))return p}}e=n.dirname(e)}throw Error(`${r.packageName} bundled ${r.packageRootFolder}/tmp.yml not found`)}export function ownerTmpFilePath(t=process.cwd(),e){const o=e??resolveTmpLayoutOrDefaults(t);return n.join(o.rootFolderAbs,v(r.tmpBaseName,r.tmpExtension))}export function ensureTmpFile(t=process.cwd(),e={}){const o=n.resolve(t),s=e.patchServiceName??!0;if(isCorePackageRoot(o)){const i=coreCanonicalTmpPath(o),u=w(o,i);if(u.length>0){const d=u.map((y)=>n.relative(o,y)).join(", ");throw Error(`${r.packageName}: tmp.yml must only exist under ${r.packageRootFolder}/. Remove extra copies: ${d}`)}if(c.existsSync(i)){assertCoreTmpGuard(o,i);return{tmpFilePath:i,created:!1,layout:buildTmpLayout(o,f(i),i)}}}else{const i=k(o,r.tmpBaseName,r.tmpExtension);if(i)return{tmpFilePath:i,created:!1,layout:buildTmpLayout(o,f(i),i)}}const a=e.templatePath??resolveBundledCoreTmpPath(o);if(!c.existsSync(a))throw Error(`${r.packageName} bundled ${r.packageRootFolder}/tmp.yml not found`);const p=buildTmpLayout(o,null,null);c.mkdirSync(p.rootFolderAbs,{recursive:!0});const l=ownerTmpFilePath(o,p);let m=c.readFileSync(a,"utf8");if(s)try{const i=n.join(o,"package.json");if(c.existsSync(i)){const u=JSON.parse(c.readFileSync(i,"utf8")),d=typeof u.name==="string"?u.name.replace(/^@/,"").replace(/\//g,"-"):null;if(d){const y=x.parse(m),h=y.configs??{},g=h.service;if(typeof g==="object"&&g!==null&&!Array.isArray(g))g.name=d;else h.service={name:d};y.configs=h;m=x.stringify(y)}}}catch{}c.writeFileSync(l,m);return{tmpFilePath:l,created:!0,layout:buildTmpLayout(o,f(l),l)}}export function resolveTmpLayoutEnsured(t=process.cwd()){return ensureTmpFile(t).layout}
1
+ import U from"node:fs";import J from"node:path";import z from"yaml";import{Constants as I}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 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 +1 @@
1
- import{PolarityTypeEnum as d}from"../../../utils/models";export function dateZoneConverter({polarity:e,date:o,zone:n,factor:r=1000}){let s=null;if(e===d.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 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 p}from"@xrystal/dto/express";import{nodeSink as f}from"@xrystal/dto/node";import{fetchSink as a}from"@xrystal/dto/fetch";import{elysiaSink as m}from"@xrystal/dto/elysia";import{websocketSink as k}from"@xrystal/dto/websocket";import{socketIoSink as S}from"@xrystal/dto/socketio";import{FrameworkEnum as t,ProtocolEnum as r}from"../../../utils/models";import{getFramework as d}from"../../../utils/helpers/framework";import{getDtoRuntime as h}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 E=(o)=>!!o&&typeof o==="object"&&("body"in o)&&("statusCode"in o),x=(o)=>o instanceof Response||o instanceof Blob||o instanceof Uint8Array||o instanceof ArrayBuffer,s=(o)=>o.socket??o.ctx?.ws??o.ctx,w=()=>h().config.socket?.event??"response";export function dispatchResult(o,e,i){if(o===void 0||o===null)return;if(x(o))return o;if(!E(o))return o;if(e.protocol===r.SOCKETIO||e.framework===t.SOCKETIO){S(s(e),w()).dispatch(o);return}if(e.protocol===r.WEBSOCKET||e.framework===t.WEBSOCKET){k(s(e)).dispatch(o);return}const c=e.framework??d(),n=i;switch(c){case t.EXPRESS:if(n&&!n.headersSent)p(i).dispatch(o);return;case t.NODE:if(n&&!n.headersSent)f(i).dispatch(o);return;case t.FETCH:return a.dispatch(o);case t.ELYSIA:default:return m(e.ctx?.set??{}).dispatch(o)}}
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 n}from"../../../utils/helpers/tmp/runtime-tmp";import{FrameworkEnum as t}from"../../../utils/models";const o=new Set(Object.values(t));export function parseFramework(r){const e=r?String(r).toLowerCase():void 0;return e&&o.has(e)?e:t.ELYSIA}export function getFramework(r){if(r)return r;try{return parseFramework(n()?.service?.framework)}catch{return t.ELYSIA}}
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 a,ProtocolEnum as s}from"../../../utils/models";import{detectSocketProtocol as l}from"../../../utils/helpers/protocol";import{getFramework as E}from"../../../utils/helpers/framework";import{runAction as m}from"../../../utils/helpers/handlers/execute";import{Constants as u}from"../../../utils/constants";export function toRealtimeHandler(t,c){const e=(r)=>{const n=l(r,c);return m({socket:r,ctx:{ws:r},protocol:n},t)},o=(r)=>e(r);o.with=(r)=>()=>e(r);return o}export const toHandler=(t,c)=>{const e=c??E();switch(e){case a.ELYSIA:return(o)=>m({framework:e,ctx:o},t);case a.FETCH:return(o,r)=>m({framework:e,ctx:{request:o,...r}},t);case a.NODE:return(o,r)=>m({framework:e,req:o,res:r},t,r);case a.EXPRESS:return(o,r,n)=>{m({framework:e,req:o,res:r,metadata:{locals:r.locals||{}}},t,r).catch(n)};case a.WEBSOCKET:case a.SOCKETIO:throw Error(`[${u.packageName}] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })`);default:return(o)=>m({framework:a.ELYSIA,ctx:o},t)}},toWebSocket=(t,c)=>toRealtimeHandler(c,s.WEBSOCKET)(t),toSocketIo=(t,c)=>toRealtimeHandler(c,s.SOCKETIO)(t);
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";import{Constants as N}from"../../../utils/constants";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 +1 @@
1
- import{randomUUID as a}from"node:crypto";import{FrameworkEnum as m,ProtocolEnum as q}from"../../../utils/models";import{runControllerStore as x}from"../../../utils/helpers/context";import{runWithRequestId as p}from"../../../utils/helpers/context";import{dispatchResult as l}from"../../../utils/helpers/dispatch";import{getFramework as I}from"../../../utils/helpers/framework";import{attachSocketTransport as g,isRealtimeProtocol as c}from"../../../utils/helpers/protocol";import{getDtoRuntime as s}from"../../../utils/helpers/runtime";export const runController=x;const w=(t)=>({framework:t.framework??(c(t.protocol)?void 0:I()),protocol:t.protocol??q.HTTP,...t,metadata:{locals:{},...t.metadata}}),i=(t,r)=>{if(!t)return;if(t instanceof Headers)return t.get(r)??t.get(r.toLowerCase());if(typeof t.get==="function"){const e=t.get;return e(r)??e(r.toLowerCase())}const o=t;return o[r]??o[r.toLowerCase()]},k=(t)=>{const r=t.ctx??{},o=t.req??{},e=o.headers??r.request?.headers;return t.requestId??r.requestId??o.ctx?.requestId??i(e,"x-request-id")??i(e,"x-correlation-id")??""},R=(t)=>{const r=String(k(t)||a());t.requestId=r;t.ctx={...t.ctx,requestId:r};if(t.req)t.req.ctx={...t.req.ctx,requestId:r};return r},h=(t)=>{if(t.framework!==m.FETCH||t.ctx?.builder)return;const r=t.ctx?.request??t.req;if(!(r instanceof Request))return;t.ctx={...t.ctx,...s().forRequest(r)};if(t.ctx.requestId)t.requestId=String(t.ctx.requestId)},y=async(t,r,o)=>{const e=l(t,r,o),n=o;if(e instanceof Response&&n?.send){n.status?.(e.status);e.headers.forEach((f,d)=>n.setHeader?.(d,f));const u=e.headers.get("content-type")||"";if(u.includes("json")||u.includes("text/"))return n.send(await e.text());return n.send(Buffer.from(await e.arrayBuffer()))}return e},C=(t)=>c(t.protocol)?"ws":"http";export async function runAction(t,r,o){const e=w(t);if(c(e.protocol)&&e.socket&&!e.socket.builder)g(e.socket,e.protocol,s());h(e);const n=R(e);return p(n,()=>runController(e,async()=>y(await r(),e,o)),C(e))}export function configureDto(t,r){return s().configure(t,r)}
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 l}from"../../../utils/models";import{createDtoMiddleware as r}from"../../../utils/helpers/middleware";import{attachSocketTransport as a,detectSocketProtocol as c,resolveRealtimeMiddlewareProtocol as p}from"../../../utils/helpers/protocol";import{getDtoRuntime as t}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=(o)=>r(t(),o);export function realtimeMiddleware(o){const n=p(o);return(m,i)=>{try{const e=c(m,n);a(m,e,t());i?.()}catch(e){i?.(e instanceof Error?e:Error(String(e)))}}}export const websocketMiddleware=(o)=>o?r(t(),o):realtimeMiddleware("ws"),socketIoMiddleware=(o)=>o?r(t(),o??l.SOCKETIO):realtimeMiddleware("socketio");
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");
@@ -25,3 +25,5 @@ export * from '../../utils/helpers/state';
25
25
  export * from '../../utils/helpers/handlers';
26
26
  export * from '../../utils/helpers/runtime';
27
27
  export * from '../../utils/helpers/kafka';
28
+ export * from '../../utils/helpers/redis';
29
+ export * from '../../utils/helpers/mongo';
@@ -1 +1 @@
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";export*from"../../utils/helpers/kafka";
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";export*from"../../utils/helpers/kafka";export*from"../../utils/helpers/redis";export*from"../../utils/helpers/mongo";
@@ -1 +1 @@
1
- import t from"node:fs";export function resolveKafkaJsSsl(r=[]){const s=process.env.KAFKA_SSL==="true",c=r.some((n)=>/:9095\b/.test(n));if(!s&&!c)return!1;const e=process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(e&&t.existsSync(e))return{ca:[t.readFileSync(e,"utf-8")],rejectUnauthorized:!1}}catch{}return{rejectUnauthorized:!1}}
1
+ import q from"node:fs";export function resolveKafkaJsSsl(x=[]){const y=process.env.KAFKA_SSL==="true",z=x.some((B)=>/:9095\b/.test(B));if(!y&&!z)return!1;const j=process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(j&&q.existsSync(j))return{ca:[q.readFileSync(j,"utf-8")],rejectUnauthorized:!1}}catch{}return{rejectUnauthorized:!1}}
@@ -1 +1 @@
1
- import{FrameworkEnum as r}from"../../../utils/models";import{getFramework as o,parseFramework as a}from"../../../utils/helpers/framework";const n={express:r.EXPRESS,elysia:r.ELYSIA,node:r.NODE,fetch:r.FETCH,websocket:r.WEBSOCKET,ws:r.WEBSOCKET,socketio:r.SOCKETIO};export function normalizeFrameworkKind(e){if(e===void 0)return o();const t=typeof e==="object"&&e!==null&&"framework"in e?e.framework:e;if(!t)return o();const s=String(t).toLowerCase().replace(/[-_\s]/g,"");return n[s]??a(t)}export function resolveDtoAdapter(e,t){switch(t){case r.ELYSIA:return e.elysia();case r.NODE:return e.node();case r.SOCKETIO:return e.socketIo();case r.WEBSOCKET:return e.websocket();case r.FETCH:return null;case r.EXPRESS:return e.express();default:return e.elysia()}}export function createDtoMiddleware(e,t){return resolveDtoAdapter(e,normalizeFrameworkKind(t))}
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))}
@@ -0,0 +1,8 @@
1
+ export type MongoConnectOptions = {
2
+ tls?: boolean;
3
+ tlsCAFile?: string;
4
+ tlsCertificateKeyFile?: string;
5
+ tlsAllowInvalidHostnames?: boolean;
6
+ };
7
+ /** Private CA client TLS for bare-metal Mongo / bare-metal Mongo TLS */
8
+ export declare function resolveMongoConnectOptions(mongodbUri?: string | null): MongoConnectOptions;
@@ -0,0 +1 @@
1
+ export function resolveMongoConnectOptions(e){if(!((e?.trim()??"").includes("tls=true")||process.env.MONGODB_SSL==="true"))return{};return{tls:!0,tlsCAFile:process.env.MONGODB_SSL_CA||process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt",tlsCertificateKeyFile:process.env.MONGODB_SSL_PEM||"/etc/tls/infra/mongodb.pem",tlsAllowInvalidHostnames:!0}}
@@ -1 +1 @@
1
- import t from"path";import{fileURLToPath as r}from"url";export*from"../../../utils/helpers/path/resolve-alias-path";export const __filename=(o)=>r(o),__dirname=(o)=>t.dirname(r(o));
1
+ import d from"path";import{fileURLToPath as c}from"url";export*from"../../../utils/helpers/path/resolve-alias-path";export const __filename=(b)=>c(b),__dirname=(b)=>d.dirname(c(b));
@@ -1 +1 @@
1
- import u from"node:fs";import n from"node:path";import i from"../../../utils/constants/defaults.json" with { type: 'json' };const h=[".ts",".js",".mjs"];function c(t){return String(t).replace(/^\.\//,"")}function p(t){for(const e of h){const o=`${t}${e}`;if(u.existsSync(o))return o}for(const e of h){const o=n.join(t,`index${e}`);if(u.existsSync(o))return o}return null}export function resolveAliasModulePath(t,e={}){const o=e.cwd??process.cwd(),l=e.aliasPrefix??i.pathAliasKey.replace("*","");if(!t.startsWith(l))return n.isAbsolute(t)?t:n.resolve(o,t);const s=c(e.sourceFolder??"source");let r=t.slice(l.length).replace(/^\/+/,"");if(r===s||r.startsWith(`${s}/`))r=r===s?"":r.slice(s.length+1);const a=n.join(o,s,r),d=p(a);if(d)return d;const g=c(e.rootFolder??i.packageRootFolder),m=c(e.distSegment??"dist"),F=n.join(o,g,m,r),f=p(F);if(f)return f;return a}export function resolveTmpLoadPath(t,e,o=process.cwd()){const l=i.pathAliasKey.replace("*",""),s=e.configs??{};if(!t.startsWith(l)){const d=s.rootFolderPath??i.packageRootFolder;return n.resolve(o,d,t)}const r=s.service?.paths??{},a=r.special??{};return resolveAliasModulePath(t,{cwd:o,sourceFolder:c(String(r.source??"source")),rootFolder:s.rootFolderPath??i.packageRootFolder,distSegment:c(String(a.dist??"dist"))})}
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 +1 @@
1
- import{Constants as s}from"../../../utils/constants";import{ProtocolEnum as r}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as u}from"../../../utils/helpers/tmp/runtime-tmp";const c={http:r.HTTP,https:r.HTTPS,ws:r.WEBSOCKET,websocket:r.WEBSOCKET,socketio:r.SOCKETIO,socket:r.SOCKETIO},REALTIME_MIDDLEWARE_HINT=`[${s.packageName}] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")`;export function parseProtocol(t){if(!t)return r.HTTP;const e=String(t).toLowerCase().replace(/[-_\s.]/g,"");if(c[e])return c[e];return Object.values(r).includes(String(t))?t:r.HTTP}export function isRealtimeProtocol(t){return t===r.WEBSOCKET||t===r.SOCKETIO}export function isHttpProtocol(t){return!t||t===r.HTTP||t===r.HTTPS}function i(){return u()?.service}export function resolveProtocolsFromConfig(t){const e=t?.protocols;if(!e)return[r.HTTP];return(Array.isArray(e)?e:[e]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(i())}catch{return[r.HTTP,r.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(t){return resolveProtocolsFromConfig(t).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(t){const e=getConfiguredRealtimeProtocols(t);if(e.length===1)return e[0];if(e.length>1)return;return r.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(i())}catch{return r.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(t,e){if(t!==void 0&&t!==null&&t!=="")return parseProtocol(t);let o=e;if(!o)try{o=i()}catch{return r.WEBSOCKET}const n=getConfiguredRealtimeProtocols(o);if(n.length===1)return n[0];if(n.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return r.WEBSOCKET}export function detectSocketProtocol(t,e){if(e)return e;const o=t;if(o?.__xrystalProtocol)return o.__xrystalProtocol;return r.WEBSOCKET}export function attachSocketTransport(t,e,o){const n=t;if(e===r.SOCKETIO)o.attachSocketIo(t);else o.attachWebSocket(t);n.__xrystalProtocol=e}export{REALTIME_MIDDLEWARE_HINT};
1
+ import{Constants as J}from"../../../utils/constants";import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as K}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=`[${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};
@@ -0,0 +1,10 @@
1
+ export type RedisSocketOptions = {
2
+ connectTimeout?: number;
3
+ keepAlive?: boolean;
4
+ tls?: boolean | {
5
+ ca?: string[];
6
+ rejectUnauthorized?: boolean;
7
+ };
8
+ };
9
+ /** rediss:// + private CA from REDIS_SSL_CA / KAFKA_SSL_CA / infra-tls mount / ozel CA */
10
+ export declare function resolveRedisSocketOptions(redisUri?: string | null): RedisSocketOptions;
@@ -0,0 +1 @@
1
+ import q from"node:fs";export function resolveRedisSocketOptions(w){const j={connectTimeout:1e4,keepAlive:!0};if(!((w?.trim()??"").startsWith("rediss://")||process.env.REDIS_SSL==="true"))return j;const k=process.env.REDIS_SSL_CA||process.env.KAFKA_SSL_CA||"/etc/tls/infra/ca.crt";try{if(k&&q.existsSync(k))return{...j,tls:{ca:[q.readFileSync(k,"utf-8")],rejectUnauthorized:!1}}}catch{}return{...j,tls:{rejectUnauthorized:!1}}}
@@ -1 +1 @@
1
- import{stopTmpLoader as n}from"../../../utils/helpers/tmp/tmp-loader";import{clearRuntimeTmpConfigs as s}from"../../../utils/helpers/tmp/runtime-tmp";import i from"../../../utils/models/classes/class.x";let o=!1,r=!1;export function isShuttingDown(){return o}export async function gracefulShutdown(t=0){if(o){process.exit(t);return}o=!0;try{await i.shutdown()}catch{}n();s();await new Promise((e)=>setImmediate(e));process.exit(t)}export function registerGracefulShutdown(){if(r)return;r=!0;const t=(e)=>{gracefulShutdown(e==="SIGINT"?130:e==="SIGTERM"?143:0)};process.on("SIGINT",t);process.on("SIGTERM",t)}
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)}
@@ -1 +1 @@
1
- import{createStore as h}from"zustand/vanilla";import{subscribeWithSelector as l}from"zustand/middleware";import{GStoreScopeEnum as a}from"../../../utils/models/enums";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp";import{warnIfRequestScopedKey as c,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard";import{buildStoresSnapshot as p,patchControllerScope as S,patchRunScope as f}from"../../../utils/helpers/state/scopes";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes";const i=(t)=>JSON.parse(JSON.stringify(t));function u(t,e){const s=new Set([...Object.keys(t),...Object.keys(e)]),o=[];for(const r of s)if(t[r]!==e[r])o.push({key:r,value:e[r],prev:t[r]});return o}class GStoreFacade{store;baseline={};allowedKeys=new Set;allowAutoCreateProps=!0;warnOnRequestKeys=!0;constructor(){this.store=h(l(()=>({})))}configureFromTmp(t={}){const e=resolveGStoreBoot(t);this.allowAutoCreateProps=e.allowAutoCreateProps;this.warnOnRequestKeys=e.warnOnRequestKeys;this.allowedKeys=new Set(Object.keys(e.vars));const s=i(e.bootstrap?e.vars:{});this.store.setState(s,!0);this.baseline=i(s);return this}allowsAutoCreateProps(){return this.allowAutoCreateProps}declaredKeys(){return[...this.allowedKeys]}guardRequestKey(t){c(t,this.warnOnRequestKeys)}assertPropAllowed(t){if(this.allowAutoCreateProps)return;if(!this.allowedKeys.has(t))throw Error(`${G_PROP_NOT_ALLOWED}: ${t}`)}registerAllowedKeys(t){for(const e of t)this.allowedKeys.add(e)}getState(){return this.store.getState()}select(t){return t(this.getState())}get(t,e){const s=this.getState();if(!(t in s))return e;return s[t]}set(t,e){this.guardRequestKey(t);this.assertPropAllowed(t);const s=this.getState();if(s[t]===e)return this;this.store.setState({...s,[t]:e});return this}merge(t){for(const o of Object.keys(t)){this.guardRequestKey(o);this.assertPropAllowed(o)}const e=this.getState();if(!u(e,{...e,...t}).length)return this;this.store.setState({...e,...t});return this}has(t){return t in this.getState()}remove(...t){const s={...this.getState()};let o=!1;for(const r of t)if(r in s){delete s[r];o=!0}if(o)this.store.setState(s,!0);return this}keys(){return Object.keys(this.getState())}entries(){return Object.entries(this.getState())}snapshot(){return{...this.getState()}}subscribe(t){return this.store.subscribe((e,s)=>t(e,s,u(s,e)))}subscribeKey(t,e){return this.store.subscribe((s)=>s[t],(s,o)=>e(s,o,{key:t,value:s,prev:o}))}bootstrap(t){if(!this.allowAutoCreateProps)for(const e of Object.keys(t))this.assertPropAllowed(e);else this.registerAllowedKeys(Object.keys(t));this.merge(t);this.baseline=i(this.getState());return this}reset(){this.store.setState(i(this.baseline),!0)}stores(){return p(this.snapshot())}list(){return Object.values(this.stores())}scope(t){const s=this.stores()[t],o={name:t,active:s.active,keys:()=>s.keys,get(r,n){if(!s.values||!(r in s.values))return n;return s.values[r]}};if(t===a.GLOBAL)return{...o,set:(r,n)=>{this.set(r,n);return!0},merge:(r)=>{this.merge(r);return!0}};if(t===a.RUN)return{...o,patch:(r)=>f(r)};return{...o,patch:(r)=>S(r)}}}export{GStoreFacade};export const G=new GStoreFacade;
1
+ import{createStore as w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from"../../../utils/models/enums";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp";import{warnIfRequestScopedKey as Q,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard";import{buildStoresSnapshot as U,patchControllerScope as Y,patchRunScope as q}from"../../../utils/helpers/state/scopes";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes";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 +1 @@
1
- import{Constants as u}from"../../../utils/constants";import{readTmpServiceBlock as p}from"../../../utils/helpers/tmp/tmp-schema";export const G_PROP_NOT_ALLOWED=`[${u.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;const n=()=>({});function c(r){return p(r).loaders?.system?.gStore}function f(r){if(typeof r.bootstrap==="boolean")return r.bootstrap;return!0}function l(r){if(typeof r.autoCreateProps==="boolean")return r.autoCreateProps;return!0}function i(r){if(typeof r.warnOnRequestKeys==="boolean")return r.warnOnRequestKeys;return!0}export function resolveGStoreBoot(r={}){const t=r.configs??r,o=c(t);if(!o)return{bootstrap:!0,allowAutoCreateProps:!0,warnOnRequestKeys:!0,vars:n()};const s=o.options??{},e=o.vars,a=e&&typeof e==="object"&&!Array.isArray(e)?{...e}:n();return{bootstrap:f(s),allowAutoCreateProps:l(s),warnOnRequestKeys:i(s),vars:a}}export function propsFromTmp(r={}){const t=resolveGStoreBoot(r);return t.bootstrap?t.vars:n()}
1
+ import{Constants as I}from"../../../utils/constants";import{readTmpServiceBlock as J}from"../../../utils/helpers/tmp/tmp-schema";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 +1 @@
1
- import{Constants as t}from"../../../utils/constants";import{getRunContext as s}from"../../../utils/helpers/context";import{getControllerCtx as n}from"../../../utils/helpers/context/controller-store";export const G_REQUEST_KEY_WARN=`[${t.packageName}] G: key looks request-scoped — use run/controller context, not global G`;const i=new Set(["requestid","reqid","correlationid","cookies","cookie","headers","header","body","query","queries","params","locals","session","sessionid"]);export function looksLikeRequestScopedKey(o){const r=o.trim();if(!r)return!1;const e=r.toLowerCase();if(i.has(e))return!0;if(e.endsWith("requestid")||e.endsWith("correlationid"))return!0;if(e==="req"||e==="res")return!0;return!1}export function warnIfRequestScopedKey(o,r){if(!r||!looksLikeRequestScopedKey(o))return;const e=s()?"run":n()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${o}, scope: ${e})`)}
1
+ import{Constants as B}from"../../../utils/constants";import{getRunContext as D}from"../../../utils/helpers/context";import{getControllerCtx as F}from"../../../utils/helpers/context/controller-store";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 +1 @@
1
- import{GStoreScopeEnum as r}from"../../../utils/models/enums";import{getRunContext as a,patchRunContext as u}from"../../../utils/helpers/context";import{getControllerCtx as n}from"../../../utils/helpers/context/controller-store";export function summarizeController(e){if(!e)return null;return{protocol:e.protocol,framework:e.framework,requestId:e.requestId,metadata:e.metadata,hasReq:!!e.req,hasRes:!!e.res,hasSocket:!!e.socket}}export function runContextValues(e){if(!e)return null;return{...e}}export function buildStoresSnapshot(e){const t=a(),o=summarizeController(n());return{[r.GLOBAL]:{name:r.GLOBAL,active:!0,keys:Object.keys(e),values:{...e}},[r.RUN]:{name:r.RUN,active:!!t,keys:t?Object.keys(t):[],values:runContextValues(t)},[r.CONTROLLER]:{name:r.CONTROLLER,active:!!o,keys:o?Object.keys(o):[],values:o}}}export function patchControllerScope(e){const t=n();if(!t)return!1;if(e.requestId!==void 0)t.requestId=e.requestId;if(e.metadata)t.metadata={...t.metadata,...e.metadata,locals:{...t.metadata?.locals??{},...e.metadata.locals??{}}};return!0}export function patchRunScope(e){if(!a())return!1;u(e);return!0}
1
+ import{GStoreScopeEnum as j}from"../../../utils/models/enums";import{getRunContext as q,patchRunContext as w}from"../../../utils/helpers/context";import{getControllerCtx as v}from"../../../utils/helpers/context/controller-store";export function summarizeController(d){if(!d)return null;return{protocol:d.protocol,framework:d.framework,requestId:d.requestId,metadata:d.metadata,hasReq:!!d.req,hasRes:!!d.res,hasSocket:!!d.socket}}export function runContextValues(d){if(!d)return null;return{...d}}export function buildStoresSnapshot(d){const f=q(),k=summarizeController(v());return{[j.GLOBAL]:{name:j.GLOBAL,active:!0,keys:Object.keys(d),values:{...d}},[j.RUN]:{name:j.RUN,active:!!f,keys:f?Object.keys(f):[],values:runContextValues(f)},[j.CONTROLLER]:{name:j.CONTROLLER,active:!!k,keys:k?Object.keys(k):[],values:k}}}export function patchControllerScope(d){const f=v();if(!f)return!1;if(d.requestId!==void 0)f.requestId=d.requestId;if(d.metadata)f.metadata={...f.metadata,...d.metadata,locals:{...f.metadata?.locals??{},...d.metadata.locals??{}}};return!0}export function patchRunScope(d){if(!q())return!1;w(d);return!0}
@@ -1 +1 @@
1
- import{packageDefaults as e}from"../../../utils/constants";import{onRuntimeTmpChange as t}from"../../../utils/helpers/tmp/runtime-tmp";export function bindLoaderTmpSync(n){const o=n.constructor.name;t(async()=>{try{await n.syncFromTmp()}catch(a){const r=a instanceof Error?a.message:String(a);console.warn(`[${e.packageName}] ${o} tmp reload failed: ${r}`)}})}
1
+ import{packageDefaults as w}from"../../../utils/constants";import{onRuntimeTmpChange as x}from"../../../utils/helpers/tmp/runtime-tmp";export function bindLoaderTmpSync(j){const q=j.constructor.name;x(async()=>{try{await j.syncFromTmp()}catch(b){const v=b instanceof Error?b.message:String(b);console.warn(`[${w.packageName}] ${q} tmp reload failed: ${v}`)}})}
@@ -1 +1 @@
1
- import{packageDefaults as s}from"../../../utils/constants";import{healToolchainIfLayoutNeedsSync as a,resetToolchainHealState as c}from"../../../utils/helpers/tmp/toolchain-heal";let o;const i=[];export function setRuntimeTmpConfigs(n){o=n}export function getRuntimeTmpConfigs(){return o}export function onRuntimeTmpChange(n){i.push(n);return()=>{const e=i.indexOf(n);if(e>=0)i.splice(e,1)}}export async function notifyRuntimeTmpChange(n){if(n)o=n;const e=o;if(!e)return;if(e.rootFolderPath&&e.service?.paths)try{a(process.cwd(),e)}catch(t){const r=t instanceof Error?t.message:String(t);console.warn(`[${s.packageName}] toolchain auto-sync skipped: ${r}`)}for(const t of i)await t(e)}export function clearRuntimeTmpConfigs(){o=void 0;i.length=0;c()}
1
+ import{packageDefaults as A}from"../../../utils/constants";import{healToolchainIfLayoutNeedsSync as B,resetToolchainHealState as E}from"../../../utils/helpers/tmp/toolchain-heal";let v;const w=[];export function setRuntimeTmpConfigs(j){v=j}export function getRuntimeTmpConfigs(){return v}export function onRuntimeTmpChange(j){w.push(j);return()=>{const b=w.indexOf(j);if(b>=0)w.splice(b,1)}}export async function notifyRuntimeTmpChange(j){if(j)v=j;const b=v;if(!b)return;if(b.rootFolderPath&&b.service?.paths)try{B(process.cwd(),b)}catch(q){const z=q instanceof Error?q.message:String(q);console.warn(`[${A.packageName}] toolchain auto-sync skipped: ${z}`)}for(const q of w)await q(b)}export function clearRuntimeTmpConfigs(){v=void 0;w.length=0;E()}
@@ -1 +1 @@
1
- import a from"node:fs";import c from"node:path";import{fileURLToPath as d}from"node:url";import l from"yaml";import defaults from"../../../utils/constants/defaults.json" with { type: 'json' };import{normalizeRootFolder as u,normalizeSourceFolder as g}from"../../../utils/helpers/tmp/path-normalize";export{defaults as packageIdentityDefaults};const f=c.dirname(d(import.meta.url)),p=`${defaults.tmpBaseName}${defaults.tmpExtension}`;function i(e,o){if(typeof e!=="string"||!e.trim())throw Error(`${defaults.packageName}: bundled tmp.yml missing ${o}`);return e.trim()}function y(e){const o=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return{tests:i(o.tests,"configs.service.paths.special.tests"),environments:i(o.environments,"configs.service.paths.special.environments"),dist:i(o.dist,"configs.service.paths.special.dist")}}function h(){try{return process.cwd()}catch{return null}}function w(e){if(e){if(!a.existsSync(e))throw Error(`${defaults.packageName}: bundled tmp.yml missing at ${e}`);return e}const o=[f,h()].filter((t)=>Boolean(t));for(const t of o){let r=c.resolve(t);for(;;){const s=c.join(r,defaults.packageRootFolder,p);if(a.existsSync(s))return s;const n=c.dirname(r);if(n===r)break;r=n}}throw Error(`${defaults.packageName}: bundled ${defaults.packageRootFolder}/${p} not found from ${f}`)}export function loadSeedFromBundledTmp(e){const o=w(e),t=l.parse(a.readFileSync(o,"utf8")),r=t?.configs&&typeof t.configs==="object"?t.configs:{},s=r.service&&typeof r.service==="object"?r.service:{},n=s.paths&&typeof s.paths==="object"?s.paths:{},m=i(n.source,"configs.service.paths.source");return{rootFolder:u(n.root,defaults.packageRootFolder),sourceFolder:g(m,m),framework:i(s.framework,"configs.service.framework"),layout:y(n.special)}}export const seedFromTmp=loadSeedFromBundledTmp();
1
+ import K from"node:fs";import J from"node:path";import{fileURLToPath as V}from"node:url";import W from"yaml";import defaults from"../../../utils/constants/defaults.json" with { type: 'json' };import{normalizeRootFolder as X,normalizeSourceFolder as Y}from"../../../utils/helpers/tmp/path-normalize";export{defaults as packageIdentityDefaults};const O=J.dirname(V(import.meta.url)),Q=`${defaults.tmpBaseName}${defaults.tmpExtension}`;function I(j,A){if(typeof j!=="string"||!j.trim())throw Error(`${defaults.packageName}: bundled tmp.yml missing ${A}`);return j.trim()}function Z(j){const A=j&&typeof j==="object"&&!Array.isArray(j)?j:{};return{tests:I(A.tests,"configs.service.paths.special.tests"),environments:I(A.environments,"configs.service.paths.special.environments"),dist:I(A.dist,"configs.service.paths.special.dist")}}function _(){try{return process.cwd()}catch{return null}}function $(j){if(j){if(!K.existsSync(j))throw Error(`${defaults.packageName}: bundled tmp.yml missing at ${j}`);return j}const A=[O,_()].filter((E)=>Boolean(E));for(const E of A){let D=J.resolve(E);for(;;){const G=J.join(D,defaults.packageRootFolder,Q);if(K.existsSync(G))return G;const H=J.dirname(D);if(H===D)break;D=H}}throw Error(`${defaults.packageName}: bundled ${defaults.packageRootFolder}/${Q} not found from ${O}`)}export function loadSeedFromBundledTmp(j){const A=$(j),E=W.parse(K.readFileSync(A,"utf8")),D=E?.configs&&typeof E.configs==="object"?E.configs:{},G=D.service&&typeof D.service==="object"?D.service:{},H=G.paths&&typeof G.paths==="object"?G.paths:{},M=I(H.source,"configs.service.paths.source");return{rootFolder:X(H.root,defaults.packageRootFolder),sourceFolder:Y(M,M),framework:I(G.framework,"configs.service.framework"),layout:Z(H.special)}}export const seedFromTmp=loadSeedFromBundledTmp();
@@ -1 +1 @@
1
- import s from"node:fs";import m from"node:path";import{Constants as t}from"../../../utils/constants";import{assertCoreTmpGuard as f,coreCanonicalTmpPath as c,isCorePackageRoot as u}from"../../../utils/helpers/core/tmp-layout";import{findFileRecursively as d}from"../../../utils/helpers/core/paths";import{TmpFileLoader as T}from"../../../utils/models/classes/class.tmp-file-loader";import{registerGracefulShutdown as h}from"../../../utils/helpers/runtime/shutdown";let r=null,a=null;function g(i=process.cwd(),e=t.tmpBaseName,o=t.tmpExtension){const n=m.resolve(i);if(u(n)){const p=c(n);if(!s.existsSync(p))throw Error(`${t.packageRootFolder}/tmp.yml not found. Run ${t.cliName} tmp or ensureCoreTmpEntry() before starting ${t.packageName}`);f(n,p);return p}const l=d(n,e,o);if(!l)throw Error(`${e}${o.startsWith(".")?o:`.${o}`} file not found`);return l}export function getTmpLoaderPath(){if(!a)a=g();return a}export function getTmpLoader(){if(!r){r=new T({filePath:getTmpLoaderPath()});h()}return r}export function getTmpSnapshot(){return getTmpLoader().getResolvedTmpFile()}export function onTmpReload(i){const e=getTmpLoader(),o=()=>i(e.getResolvedTmpFile());e.on("reload",o);return()=>e.off("reload",o)}export function stopTmpLoader(){if(r){r.stop();r=null;a=null}}export function resetTmpLoaderForTests(){stopTmpLoader()}
1
+ import J from"node:fs";import K from"node:path";import{Constants as z}from"../../../utils/constants";import{assertCoreTmpGuard as M,coreCanonicalTmpPath as O,isCorePackageRoot as Q}from"../../../utils/helpers/core/tmp-layout";import{findFileRecursively as U}from"../../../utils/helpers/core/paths";import{TmpFileLoader as V}from"../../../utils/models/classes/class.tmp-file-loader";import{registerGracefulShutdown as W}from"../../../utils/helpers/runtime/shutdown";let q=null,B=null;function X(D=process.cwd(),j=z.tmpBaseName,b=z.tmpExtension){const A=K.resolve(D);if(Q(A)){const E=O(A);if(!J.existsSync(E))throw Error(`${z.packageRootFolder}/tmp.yml not found. Run ${z.cliName} tmp or ensureCoreTmpEntry() before starting ${z.packageName}`);M(A,E);return E}const H=U(A,j,b);if(!H)throw Error(`${j}${b.startsWith(".")?b:`.${b}`} file not found`);return H}export function getTmpLoaderPath(){if(!B)B=X();return B}export function getTmpLoader(){if(!q){q=new V({filePath:getTmpLoaderPath()});W()}return q}export function getTmpSnapshot(){return getTmpLoader().getResolvedTmpFile()}export function onTmpReload(D){const j=getTmpLoader(),b=()=>D(j.getResolvedTmpFile());j.on("reload",b);return()=>j.off("reload",b)}export function stopTmpLoader(){if(q){q.stop();q=null;B=null}}export function resetTmpLoaderForTests(){stopTmpLoader()}
@@ -1 +1 @@
1
- import l from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as n,RuntimeEnum as u}from"../../../utils/models/enums";import{seedFromTmp as c}from"../../../utils/helpers/tmp/seed-from-tmp";import{interpolateWithContext as d}from"../../../utils/helpers/tmp/tmp-interpolate";import{normalizeLayoutPaths as m,normalizeRootFolder as g,normalizeSourceFolder as b}from"../../../utils/helpers/tmp/path-normalize";function t(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function h(e){if(typeof e==="number"||typeof e==="string")return e;return}export function normalizeRuntime(e){const r=typeof e==="string"?e.trim().toLowerCase():"";if(r===u.NODE)return u.NODE;if(r===u.BUN)return u.BUN;if(!r)throw Error(`${l.packageName}: configs.global.runtime is required (${Object.values(u).join("|")})`);throw Error(`${l.packageName}: unknown configs.global.runtime "${String(e)}" (expected ${Object.values(u).join("|")})`)}export function normalizeBundler(e){const r=typeof e==="string"?e.trim().toLowerCase():"";if(!r)return n.AUTO;if(r===n.TSC)return n.TSC;if(r===n.ESBUILD)return n.ESBUILD;if(r===n.BUN)return n.BUN;if(r===n.AUTO)return n.AUTO;throw Error(`${l.packageName}: unknown build.bundler "${String(e)}" (expected ${Object.values(n).join("|")})`)}export function resolveEffectiveBundler(e,r){if(e!==n.AUTO)return e;return n.TSC}export function normalizeRootFolder(e){return g(e,l.packageRootFolder)}export function normalizeSourceFolder(e){return b(e,c.sourceFolder)}export function readTmpGlobalBlock(e){const r=t(e?.global)?e.global:{},o=t(r.vars)?r.vars:{};return{runtime:normalizeRuntime(r.runtime),vars:{...o}}}export function readTmpCoreBlock(e){const r=t(e?.core)?e.core:{},o=t(r.tmp)?r.tmp:{};return{tmp:{fileWatchIntervalMs:h(o.fileWatchIntervalMs)}}}export function readTmpServiceBlock(e){const r=t(e?.service)?e.service:{},o=t(r.paths)?r.paths:{},i=t(o.special)?o.special:{};let s=t(r.loaders)?{...r.loaders}:void 0,a=t(r.build)?r.build:void 0;if(s&&t(s.build)){const{build:f,...p}=s;s=p;if(!a&&t(f))a=f}return{name:typeof r.name==="string"?r.name:void 0,framework:typeof r.framework==="string"?r.framework:void 0,paths:{root:typeof o.root==="string"?o.root:void 0,source:typeof o.source==="string"?o.source:void 0,special:{tests:typeof i.tests==="string"?i.tests:void 0,environments:typeof i.environments==="string"?i.environments:void 0,dist:typeof i.dist==="string"?i.dist:void 0}},protocols:r.protocols,loaders:s,build:a}}export function resolveServiceLayoutPaths(e){return m(e.paths?.special,c.layout)}function y(e){const r=resolveServiceLayoutPaths(e);return{name:e.name,framework:e.framework??c.framework,paths:{root:e.paths?.root??l.packageRootFolder,source:e.paths?.source??c.sourceFolder,special:r},protocols:e.protocols,loaders:e.loaders,build:e.build}}function w(e){return{tmp:{fileWatchIntervalMs:e.tmp?.fileWatchIntervalMs}}}export function buildTmpVarContext(e){return{...e.vars,runtime:e.runtime,global:e}}export function applyTmpGlobalVars(e){const r=t(e.configs)?e.configs:{},o=readTmpGlobalBlock(r);return d(e,buildTmpVarContext(o))}export function resolveTmpRuntimeConfigs(e){const r=t(e?.configs)?e.configs:{},o=readTmpGlobalBlock(r),i=readTmpServiceBlock(r),s=readTmpCoreBlock(r),a=y(i);return{global:o,service:a,core:w(s),rootFolderPath:normalizeRootFolder(a.paths.root)}}export function normalizeTmpDocument(e){const r=applyTmpGlobalVars(e);return{...r,configs:resolveTmpRuntimeConfigs(r)}}
1
+ import Q from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as H,RuntimeEnum as O}from"../../../utils/models/enums";import{seedFromTmp as U}from"../../../utils/helpers/tmp/seed-from-tmp";import{interpolateWithContext as Z}from"../../../utils/helpers/tmp/tmp-interpolate";import{normalizeLayoutPaths as _,normalizeRootFolder as $,normalizeSourceFolder as I}from"../../../utils/helpers/tmp/path-normalize";function D(j){return typeof j==="object"&&j!==null&&!Array.isArray(j)}function x(j){if(typeof j==="number"||typeof j==="string")return j;return}export function normalizeRuntime(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(q===O.NODE)return O.NODE;if(q===O.BUN)return O.BUN;if(!q)throw Error(`${Q.packageName}: configs.global.runtime is required (${Object.values(O).join("|")})`);throw Error(`${Q.packageName}: unknown configs.global.runtime "${String(j)}" (expected ${Object.values(O).join("|")})`)}export function normalizeBundler(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(!q)return H.AUTO;if(q===H.TSC)return H.TSC;if(q===H.ESBUILD)return H.ESBUILD;if(q===H.BUN)return H.BUN;if(q===H.AUTO)return H.AUTO;throw Error(`${Q.packageName}: unknown build.bundler "${String(j)}" (expected ${Object.values(H).join("|")})`)}export function resolveEffectiveBundler(j,q){if(j!==H.AUTO)return j;return H.TSC}export function normalizeRootFolder(j){return $(j,Q.packageRootFolder)}export function normalizeSourceFolder(j){return I(j,U.sourceFolder)}export function readTmpGlobalBlock(j){const q=D(j?.global)?j.global:{},A=D(q.vars)?q.vars:{};return{runtime:normalizeRuntime(q.runtime),vars:{...A}}}export function readTmpCoreBlock(j){const q=D(j?.core)?j.core:{},A=D(q.tmp)?q.tmp:{};return{tmp:{fileWatchIntervalMs:x(A.fileWatchIntervalMs)}}}export function readTmpServiceBlock(j){const q=D(j?.service)?j.service:{},A=D(q.paths)?q.paths:{},J=D(A.special)?A.special:{};let K=D(q.loaders)?{...q.loaders}:void 0,M=D(q.build)?q.build:void 0;if(K&&D(K.build)){const{build:X,...Y}=K;K=Y;if(!M&&D(X))M=X}return{name:typeof q.name==="string"?q.name:void 0,framework:typeof q.framework==="string"?q.framework:void 0,paths:{root:typeof A.root==="string"?A.root:void 0,source:typeof A.source==="string"?A.source:void 0,special:{tests:typeof J.tests==="string"?J.tests:void 0,environments:typeof J.environments==="string"?J.environments:void 0,dist:typeof J.dist==="string"?J.dist:void 0}},protocols:q.protocols,loaders:K,build:M}}export function resolveServiceLayoutPaths(j){return _(j.paths?.special,U.layout)}function L(j){const q=resolveServiceLayoutPaths(j);return{name:j.name,framework:j.framework??U.framework,paths:{root:j.paths?.root??Q.packageRootFolder,source:j.paths?.source??U.sourceFolder,special:q},protocols:j.protocols,loaders:j.loaders,build:j.build}}function N(j){return{tmp:{fileWatchIntervalMs:j.tmp?.fileWatchIntervalMs}}}export function buildTmpVarContext(j){return{...j.vars,runtime:j.runtime,global:j}}export function applyTmpGlobalVars(j){const q=D(j.configs)?j.configs:{},A=readTmpGlobalBlock(q);return Z(j,buildTmpVarContext(A))}export function resolveTmpRuntimeConfigs(j){const q=D(j?.configs)?j.configs:{},A=readTmpGlobalBlock(q),J=readTmpServiceBlock(q),K=readTmpCoreBlock(q),M=L(J);return{global:A,service:M,core:N(K),rootFolderPath:normalizeRootFolder(M.paths.root)}}export function normalizeTmpDocument(j){const q=applyTmpGlobalVars(j);return{...q,configs:resolveTmpRuntimeConfigs(q)}}
@@ -1 +1 @@
1
- import{packageDefaults as o}from"../../../utils/constants";import{readTmpCoreBlock as u}from"../../../utils/helpers/tmp/tmp-schema";const f=o.tmpWatchDefaults;function e(n){const t=f?.[n];if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${o.packageName}: tmpWatchDefaults.${n} missing in defaults.json`);return t}export function resolveTmpWatchIntervalMs(n){const t=n?.configs,s=u(t),r=e("intervalMs"),c=s.tmp?.fileWatchIntervalMs??r,a=Number(c);if(!Number.isFinite(a))return r;const i=e("minIntervalMs"),m=e("maxIntervalMs");return Math.min(m,Math.max(i,Math.round(a)))}
1
+ import{packageDefaults as J}from"../../../utils/constants";import{readTmpCoreBlock as P}from"../../../utils/helpers/tmp/tmp-schema";const Q=J.tmpWatchDefaults;function z(y){const j=Q?.[y];if(typeof j!=="number"||!Number.isFinite(j))throw Error(`${J.packageName}: tmpWatchDefaults.${y} missing in defaults.json`);return j}export function resolveTmpWatchIntervalMs(y){const j=y?.configs,K=P(j),G=z("intervalMs"),M=K.tmp?.fileWatchIntervalMs??G,I=Number(M);if(!Number.isFinite(I))return G;const N=z("minIntervalMs"),O=z("maxIntervalMs");return Math.min(O,Math.max(N,Math.round(I)))}
@@ -1,2 +1,2 @@
1
- import c from"node:fs";import f from"node:path";import{packageDefaults as r}from"../../../utils/constants";import{normalizeSourceFolder as y}from"../../../utils/helpers/tmp/path-normalize";function d(t){return String(t).replace(/^\.\//,"")}function h(){const t=r.buildDefaults?.tsconfig;if(!t||!String(t).trim())throw Error(`${r.packageName}: buildDefaults.tsconfig missing in defaults.json`);return String(t)}export function layoutOptionsFromRuntimeConfigs(t){const e=t.service?.paths,o=e?.special;return{rootFolderPath:t.rootFolderPath||r.packageRootFolder,mainFolderPath:y(e?.source,r.mainSourceFolder),pathsDist:o?.dist||r.layoutPaths.dist,pathsTests:o?.tests||r.layoutPaths.tests}}export function layoutFingerprint(t){return[t.rootFolderPath,d(t.mainFolderPath),t.pathsDist,t.pathsTests].join("\x00")}export function resolveRecommendedTsconfig(t){const e=d(t.mainFolderPath),o=t.rootFolderPath,s=r.pathAliasKey;return{include:[e],exclude:[`${o}/${t.pathsTests}`],compilerOptions:{baseUrl:".",paths:{[s]:[`${e}/*`]},rootDir:`./${e}`,outDir:`./${o}/${t.pathsDist}`}}}function S(t){const e=f.join(t,"package.json");if(!c.existsSync(e))return`${r.packageName}/tsconfig.base.json`;try{if(JSON.parse(c.readFileSync(e,"utf8")).name===r.packageName)return"./tsconfig.base.json"}catch{}return`${r.packageName}/tsconfig.base.json`}function F(t,e,o){const s=e.compilerOptions??{};return{...e,extends:e.extends??o,include:t.include,exclude:t.exclude,compilerOptions:{...s,baseUrl:t.compilerOptions.baseUrl,paths:t.compilerOptions.paths,rootDir:t.compilerOptions.rootDir,outDir:t.compilerOptions.outDir}}}export function auditTsconfigAgainstLayout(t,e,o=h()){const s=f.join(t,o);if(!c.existsSync(s))return{ok:!1,missing:!0,notes:[`${o} missing`]};let i;try{i=JSON.parse(c.readFileSync(s,"utf8"))}catch{return{ok:!1,missing:!1,notes:[`${o} unreadable`]}}const n=resolveRecommendedTsconfig(e),a=[],u=i.compilerOptions??{},p=r.pathAliasKey;if(u.outDir!==n.compilerOptions.outDir)a.push("outDir drift");if(!(Array.isArray(i.include)?i.include.map(String):[]).some((m)=>d(m)===n.include[0]))a.push("include drift");const g=u.paths?.[p];if(JSON.stringify(g)!==JSON.stringify(n.compilerOptions.paths[p]))a.push(`paths ${p} drift`);return{ok:a.length===0,missing:!1,notes:a}}export function writeTsconfigFromLayout(t,e,o=h()){const s=f.join(t,o),i=!c.existsSync(s);let n={};if(!i)try{n=JSON.parse(c.readFileSync(s,"utf8"))}catch{n={}}const a=resolveRecommendedTsconfig(e),u=F(a,n,S(t));c.writeFileSync(s,`${JSON.stringify(u,null,2)}
2
- `,"utf8");return{wrote:!0,created:i,abs:s}}let l=null;export function resetToolchainHealState(){l=null}export function healToolchainIfLayoutNeedsSync(t,e,o={}){const s=layoutOptionsFromRuntimeConfigs(e),i=layoutFingerprint(s),n=h(),a=auditTsconfigAgainstLayout(t,s,n);if(l===null){l=i;if(a.ok)return{healed:!1,tsconfigRel:n,fingerprint:i};writeTsconfigFromLayout(t,s,n);if(!o.quiet)console.info(`[${r.packageName}] toolchain auto-synced (${n}) — bootstrap layout drift`);return{healed:!0,reason:"bootstrap",tsconfigRel:n,fingerprint:i}}if(i===l)return{healed:!1,tsconfigRel:n,fingerprint:i};l=i;writeTsconfigFromLayout(t,s,n);if(!o.quiet)console.info(`[${r.packageName}] toolchain auto-synced (${n}) — tmp layout paths changed`);return{healed:!0,reason:"layout-changed",tsconfigRel:n,fingerprint:i}}
1
+ import Q from"node:fs";import Y from"node:path";import{packageDefaults as M}from"../../../utils/constants";import{normalizeSourceFolder as C}from"../../../utils/helpers/tmp/path-normalize";function Z(j){return String(j).replace(/^\.\//,"")}function _(){const j=M.buildDefaults?.tsconfig;if(!j||!String(j).trim())throw Error(`${M.packageName}: buildDefaults.tsconfig missing in defaults.json`);return String(j)}export function layoutOptionsFromRuntimeConfigs(j){const B=j.service?.paths,G=B?.special;return{rootFolderPath:j.rootFolderPath||M.packageRootFolder,mainFolderPath:C(B?.source,M.mainSourceFolder),pathsDist:G?.dist||M.layoutPaths.dist,pathsTests:G?.tests||M.layoutPaths.tests}}export function layoutFingerprint(j){return[j.rootFolderPath,Z(j.mainFolderPath),j.pathsDist,j.pathsTests].join("\x00")}export function resolveRecommendedTsconfig(j){const B=Z(j.mainFolderPath),G=j.rootFolderPath,I=M.pathAliasKey;return{include:[B],exclude:[`${G}/${j.pathsTests}`],compilerOptions:{baseUrl:".",paths:{[I]:[`${B}/*`]},rootDir:`./${B}`,outDir:`./${G}/${j.pathsDist}`}}}function E(j){const B=Y.join(j,"package.json");if(!Q.existsSync(B))return`${M.packageName}/tsconfig.base.json`;try{if(JSON.parse(Q.readFileSync(B,"utf8")).name===M.packageName)return"./tsconfig.base.json"}catch{}return`${M.packageName}/tsconfig.base.json`}function W(j,B,G){const I=B.compilerOptions??{};return{...B,extends:B.extends??G,include:j.include,exclude:j.exclude,compilerOptions:{...I,baseUrl:j.compilerOptions.baseUrl,paths:j.compilerOptions.paths,rootDir:j.compilerOptions.rootDir,outDir:j.compilerOptions.outDir}}}export function auditTsconfigAgainstLayout(j,B,G=_()){const I=Y.join(j,G);if(!Q.existsSync(I))return{ok:!1,missing:!0,notes:[`${G} missing`]};let J;try{J=JSON.parse(Q.readFileSync(I,"utf8"))}catch{return{ok:!1,missing:!1,notes:[`${G} unreadable`]}}const H=resolveRecommendedTsconfig(B),N=[],V=J.compilerOptions??{},X=M.pathAliasKey;if(V.outDir!==H.compilerOptions.outDir)N.push("outDir drift");if(!(Array.isArray(J.include)?J.include.map(String):[]).some((A)=>Z(A)===H.include[0]))N.push("include drift");const $=V.paths?.[X];if(JSON.stringify($)!==JSON.stringify(H.compilerOptions.paths[X]))N.push(`paths ${X} drift`);return{ok:N.length===0,missing:!1,notes:N}}export function writeTsconfigFromLayout(j,B,G=_()){const I=Y.join(j,G),J=!Q.existsSync(I);let H={};if(!J)try{H=JSON.parse(Q.readFileSync(I,"utf8"))}catch{H={}}const N=resolveRecommendedTsconfig(B),V=W(N,H,E(j));Q.writeFileSync(I,`${JSON.stringify(V,null,2)}
2
+ `,"utf8");return{wrote:!0,created:J,abs:I}}let U=null;export function resetToolchainHealState(){U=null}export function healToolchainIfLayoutNeedsSync(j,B,G={}){const I=layoutOptionsFromRuntimeConfigs(B),J=layoutFingerprint(I),H=_(),N=auditTsconfigAgainstLayout(j,I,H);if(U===null){U=J;if(N.ok)return{healed:!1,tsconfigRel:H,fingerprint:J};writeTsconfigFromLayout(j,I,H);if(!G.quiet)console.info(`[${M.packageName}] toolchain auto-synced (${H}) — bootstrap layout drift`);return{healed:!0,reason:"bootstrap",tsconfigRel:H,fingerprint:J}}if(J===U)return{healed:!1,tsconfigRel:H,fingerprint:J};U=J;writeTsconfigFromLayout(j,I,H);if(!G.quiet)console.info(`[${M.packageName}] toolchain auto-synced (${H}) — tmp layout paths changed`);return{healed:!0,reason:"layout-changed",tsconfigRel:H,fingerprint:J}}
@@ -1 +1 @@
1
- import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader";import{LoggerLayerEnum as x,x as b}from"../../../utils";import{getRequestId as D}from"../../../utils/helpers/context";export class ClientStore{static _store={};static get(t){return this._store[t]||{}}static set(t,e){this._store[t]={...this._store[t],...e}}}export class Client{logger=b.get(N);configs=b.get(y);clientName;baseURL;version=null;timeout=15000;debug;authConfigs;breaker={failures:0,lastFailure:0,state:"CLOSED",threshold:5,cooldown:30000};constructor({clientName:t,baseURL:e,version:r,timeout:i,auth:s,debug:n}){this.clientName=t;this.baseURL=e;this.version=r||null;this.authConfigs=s;this.timeout=i||15000;const c=Number(this.configs.all.debug)>=x.DEBUG;this.debug=n??c;if(s?.token)ClientStore.set(t,{accessToken:s.token})}resolvePath(t,e){return e.split(".").reduce((r,i)=>r?r[i]:void 0,t)}static cryptoHashGenerate=({algorithm:t,input:e,digest:r="hex"})=>{return k(t).update(e).digest(r)}}export class BaseApiClient extends Client{constructor(t){super(t)}async request(t,e={}){if(this.breaker.state==="OPEN")if(Date.now()-this.breaker.lastFailure>this.breaker.cooldown)this.breaker.state="HALF_OPEN";else throw Error(`[CircuitBreaker] ${this.clientName} is OPEN`);const r=e.retries??3;let i=0;while(i<r)try{const s=await this._execute(t,{...e});if(s.ok||s.status===401){this.breaker.failures=0;this.breaker.state="CLOSED";return s}if([502,503,504].includes(s.status))throw Error(`Server Error: ${s.status}`);return s}catch(s){i++;this.breaker.failures++;this.breaker.lastFailure=Date.now();if(this.breaker.failures>=this.breaker.threshold)this.breaker.state="OPEN";if(i>=r)throw s;const n=Math.pow(2,i)*500;await new Promise((c)=>setTimeout(c,n))}throw Error(`${this.clientName} failed after ${r} attempts`)}async _execute(t,e){const r=this.baseURL.replace(/\/$/,""),i=e.version!==void 0?e.version:this.version,s=i?`/${i.replace(/^\//,"")}`:"",n=`${r}${s}${t}`,c=D(),l=new Headers(e.headers||{}),u=e.body instanceof URLSearchParams,d=e.body instanceof FormData;if(!u&&!d)l.set("Content-Type","application/json");if(c)l.set("x-correlation-id",c);const f=this.configs.all.internalSecret||process.env.INTERNAL_SECRET;if(f){const a=Date.now().toString(),w=E("sha256",f).update(a+this.clientName).digest("hex");l.set("x-internal-signature",w);l.set("x-internal-timestamp",a);l.set("x-internal-client",this.clientName)}const p=e.debug??this.debug,{version:L,retries:v,debug:C,...h}=e;let o=h.body;if(o&&typeof o==="object"&&!u&&!d)o=JSON.stringify(o);if(p){const a={method:h.method||"GET",url:n,body:o&&typeof o==="string"?JSON.parse(o):o};console.log(`[DEBUG] ${this.clientName}`,a);this.logger.winston.info(`${this.clientName} Request`,a)}const m=new AbortController,g=setTimeout(()=>m.abort(),this.timeout);try{const a=await fetch(n,{...h,body:o,headers:l,signal:m.signal});clearTimeout(g);return a}catch(a){clearTimeout(g);throw a}}}
1
+ import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader";import{LoggerLayerEnum as x,x as b}from"../../../utils";import{getRequestId as D}from"../../../utils/helpers/context";export class ClientStore{static _store={};static get(t){return this._store[t]||{}}static set(t,e){this._store[t]={...this._store[t],...e}}}export class Client{logger=b.get(N);configs=b.get(y);clientName;baseURL;version=null;timeout=15000;debug;authConfigs;breaker={failures:0,lastFailure:0,state:"CLOSED",threshold:5,cooldown:30000};constructor({clientName:t,baseURL:e,version:r,timeout:i,auth:s,debug:n}){this.clientName=t;this.baseURL=e;this.version=r||null;this.authConfigs=s;this.timeout=i||15000;const c=Number(this.configs.all.debug)>=x.DEBUG;this.debug=n??c;if(s?.token)ClientStore.set(t,{accessToken:s.token})}resolvePath(t,e){return e.split(".").reduce((r,i)=>r?r[i]:void 0,t)}static cryptoHashGenerate=({algorithm:t,input:e,digest:r="hex"})=>{return k(t).update(e).digest(r)}}export class BaseApiClient extends Client{constructor(t){super(t)}async request(t,e={}){if(this.breaker.state==="OPEN")if(Date.now()-this.breaker.lastFailure>this.breaker.cooldown)this.breaker.state="HALF_OPEN";else throw Error(`[CircuitBreaker] ${this.clientName} is OPEN`);const r=e.retries??3;let i=0;while(i<r)try{const s=await this._execute(t,{...e});if(s.ok||s.status===401){this.breaker.failures=0;this.breaker.state="CLOSED";return s}if([502,503,504].includes(s.status))throw Error(`Server Error: ${s.status}`);return s}catch(s){i++;this.breaker.failures++;this.breaker.lastFailure=Date.now();if(this.breaker.failures>=this.breaker.threshold)this.breaker.state="OPEN";if(i>=r)throw s;const n=Math.pow(2,i)*500;await new Promise((c)=>setTimeout(c,n))}throw Error(`${this.clientName} failed after ${r} attempts`)}async _execute(t,e){const r=this.baseURL.replace(/\/$/,""),i=e.version!==void 0?e.version:this.version,s=i?`/${i.replace(/^\//,"")}`:"",n=`${r}${s}${t}`,c=D(),l=new Headers(e.headers||{}),u=e.body instanceof URLSearchParams,d=e.body instanceof FormData;if(!u&&!d)l.set("Content-Type","application/json");if(c)l.set("x-correlation-id",c);const f=this.configs.all.internalSecret||process.env.INTERNAL_SECRET;if(f){const a=Date.now().toString(),w=E("sha256",f).update(a+this.clientName).digest("hex");l.set("x-internal-signature",w);l.set("x-internal-timestamp",a);l.set("x-internal-client",this.clientName)}const p=e.debug??this.debug,{version:L,retries:$,debug:v,...h}=e;let o=h.body;if(o&&typeof o==="object"&&!u&&!d)o=JSON.stringify(o);if(p){const a={method:h.method||"GET",url:n,body:o&&typeof o==="string"?JSON.parse(o):o};console.log(`[DEBUG] ${this.clientName}`,a);this.logger.winston.info(`${this.clientName} Request`,a)}const m=new AbortController,g=setTimeout(()=>m.abort(),this.timeout);try{const a=await fetch(n,{...h,body:o,headers:l,signal:m.signal});clearTimeout(g);return a}catch(a){clearTimeout(g);throw a}}}
@@ -1 +1 @@
1
- export class Locator{_context=new Map;constructor({}){}set=({service:t,reference:n,args:e})=>{this._context.set(t,new n(...e||[]))};get=(t)=>{if(!this._context.has(t))throw Error(`${t} not found in context.`);return this._context.get(t)}}export default new Locator({});
1
+ export class Locator{_context=new Map;constructor({}){}set=({service:t,reference:e,args:o})=>{this._context.set(t,new e(...o||[]))};get=(t)=>{if(!this._context.has(t))throw Error(`${t} not found in context.`);return this._context.get(t)}}export default new Locator({});
@@ -1 +1 @@
1
- import{EventEmitter as h}from"node:events";import{readFileSync as a,unwatchFile as r,watchFile as l}from"node:fs";import{resolve as n}from"node:path";import{parse as m}from"yaml";import{resolveObjWithHandlebars as c}from"../../../utils/helpers/core/handlebars-resolve";import{normalizeTmpDocument as p}from"../../../utils/helpers/tmp/tmp-schema";import{resolveTmpWatchIntervalMs as s}from"../../../utils/helpers/tmp/tmp-watch";export class TmpFileLoader extends h{#t={};#e;#i=s(null);#s=!1;constructor({filePath:t}){super();this.#e=n(t);this.#r();this.#o()}#r(){try{const t=a(this.#e,"utf8"),e=m(t),i=s(e),o=this.#s&&i!==this.#i;this.#t=e;this.#i=i;this.emit("reload",this.#t);if(o)this.#o()}catch(t){console.error(`[TmpFileLoader] Error: ${t}`)}}#o(){if(this.#s)r(this.#e);this.#i=s(this.#t);l(this.#e,{interval:this.#i},(t,e)=>{if(t.mtimeMs!==e.mtimeMs)this.#r()});this.#s=!0}stop(){if(this.#s){r(this.#e);this.#s=!1}this.removeAllListeners()}getResolvedTmpFile(){const t=Object.keys(this.#t).length>0?this.#t:(this.#r(),this.#t);return p(c(t,t))}}
1
+ import{EventEmitter as L}from"node:events";import{readFileSync as N,unwatchFile as G,watchFile as Q}from"node:fs";import{resolve as R}from"node:path";import{parse as U}from"yaml";import{resolveObjWithHandlebars as V}from"../../../utils/helpers/core/handlebars-resolve";import{normalizeTmpDocument as X}from"../../../utils/helpers/tmp/tmp-schema";import{resolveTmpWatchIntervalMs as A}from"../../../utils/helpers/tmp/tmp-watch";export class TmpFileLoader extends L{#k={};#q;#B=A(null);#A=!1;constructor({filePath:k}){super();this.#q=R(k);this.#G();this.#K()}#G(){try{const k=N(this.#q,"utf8"),q=U(k),B=A(q),K=this.#A&&B!==this.#B;this.#k=q;this.#B=B;this.emit("reload",this.#k);if(K)this.#K()}catch(k){console.error(`[TmpFileLoader] Error: ${k}`)}}#K(){if(this.#A)G(this.#q);this.#B=A(this.#k);Q(this.#q,{interval:this.#B},(k,q)=>{if(k.mtimeMs!==q.mtimeMs)this.#G()});this.#A=!0}stop(){if(this.#A){G(this.#q);this.#A=!1}this.removeAllListeners()}getResolvedTmpFile(){const k=Object.keys(this.#k).length>0?this.#k:(this.#G(),this.#k);return X(V(k,k))}}
@@ -1 +1 @@
1
- var __filename="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/utils/models/classes/class.x.js";import{createContainer as w,asClass as y,asValue as L,InjectionMode as z,listModules as C,Lifetime as h}from"awilix";import p from"node:path";import{pathToFileURL as A}from"node:url";import S from"../../../utils/constants/defaults.json" with { type: 'json' };export const xSymbol=Symbol.for(`${S.packageName}/di-container`);class I{checkRegistration(e,t){return!!e.registrations[t]}}class N extends I{container;initializedNames=new Set;loadedPaths=new Set;registeredClasses=new Set;isInitializing=!1;constructor(){super();this.container=w({injectionMode:z.PROXY,strict:!0})}getName(e){if(typeof e==="string")return e.charAt(0).toLowerCase()+e.slice(1);if(typeof e==="function"&&e.name)return e.name.charAt(0).toLowerCase()+e.name.slice(1);return""}async load(e,t={}){const{verbose:r=!1,exclude:m=[],lifetime:s=h.SINGLETON}=t,i=process.cwd(),n=(Array.isArray(e)?e:[e]).map((c)=>{return(p.isAbsolute(c)?c:p.resolve(i,c)).replace(/\\/g,"/").toLowerCase()});let a=[];try{a=C(n)}catch(c){return this}for(const c of a){const f=c.path.replace(/\\/g,"/").toLowerCase();if(this.loadedPaths.has(f))continue;if(f===__filename.replace(/\\/g,"/").toLowerCase()||f.endsWith(".d.ts"))continue;try{const g=await import(A(c.path).href);let o=g.default;if(!o)o=Object.values(g).find((l)=>typeof l==="function"&&!!l.prototype&&!!l.name);if(typeof o==="function"&&!!o.prototype&&!!o.name){if(this.registeredClasses.has(o))continue;const l=this.getName(o);if(l&&!this.checkRegistration(this.container,l)){this.container.register({[l]:y(o).setLifetime(s)});this.loadedPaths.add(f);this.registeredClasses.add(o)}}}catch(u){if(r)console.error("[DI] Load Error:",u.message)}}return this}register(e,t=h.SINGLETON){const r=this.getName(e);if(!r||this.registeredClasses.has(e))return this;if(this.checkRegistration(this.container,r))return this;this.container.register({[r]:y(e).setLifetime(t)});this.registeredClasses.add(e);return this}registerInstance(e,t){if(!e)return this;const r=this.getName(e);this.container.register({[r]:L(t)});return this}async initialize(e,t=!1){if(this.isInitializing)return this;this.isInitializing=!0;try{const r=e?Array.isArray(e)?e:[e]:[];for(const s of r){const i=this.getName(s.service);if(!i||this.initializedNames.has(i))continue;const n=this.container.registrations[i];if(!n||n.lifetime!==h.SINGLETON)continue;try{const a=this.container.cradle[i];if(a&&typeof a.onInit==="function")await a.onInit(s.props||{});this.initializedNames.add(i)}catch(a){if(t)console.error(`[DI] Priority onInit Failed (${i}):`,a.message)}}const m=Object.keys(this.container.registrations);for(const s of m){if(this.initializedNames.has(s))continue;if(this.container.registrations[s].lifetime!==h.SINGLETON)continue;try{const n=this.container.cradle[s];if(n&&typeof n.onInit==="function")await n.onInit({});this.initializedNames.add(s)}catch(n){if(t)console.error(`[DI] Auto onInit Failed (${s}):`,n.message)}}for(const s of this.initializedNames)try{const i=this.container.cradle[s];if(i&&typeof i.onAfterInit==="function")await i.onAfterInit()}catch(i){if(t)console.error(`[DI] onAfterInit Failed (${s}):`,i.message)}}finally{this.isInitializing=!1}return this}get(e){const t=this.getName(e);return this.container.resolve(t)}async shutdown(){for(const e of this.initializedNames)try{const t=this.container.cradle[e];if(t&&typeof t.onDispose==="function")await t.onDispose()}catch(t){console.error(`[DI] onDispose Failed (${e})`)}await this.container.dispose()}get cradle(){return this.container.cradle}}const d=globalThis;if(!d[xSymbol])d[xSymbol]=new N;export default d[xSymbol];
1
+ var __filename="/Volumes/MAC/Desktop/software/xrystal/-xrystal-core/x/dist/utils/models/classes/class.x.js";import{createContainer as V,asClass as K,asValue as j,InjectionMode as N,listModules as X,Lifetime as Z}from"awilix";import R from"node:path";import{pathToFileURL as x}from"node:url";import C from"../../../utils/constants/defaults.json" with { type: 'json' };export const xSymbol=Symbol.for(`${C.packageName}/di-container`);class T{checkRegistration(q,A){return!!q.registrations[A]}}class U extends T{container;initializedNames=new Set;loadedPaths=new Set;registeredClasses=new Set;isInitializing=!1;constructor(){super();this.container=V({injectionMode:N.PROXY,strict:!0})}getName(q){if(typeof q==="string")return q.charAt(0).toLowerCase()+q.slice(1);if(typeof q==="function"&&q.name)return q.name.charAt(0).toLowerCase()+q.name.slice(1);return""}async load(q,A={}){const{verbose:H=!1,exclude:$=[],lifetime:E=Z.SINGLETON}=A,B=process.cwd(),G=(Array.isArray(q)?q:[q]).map((Q)=>{return(R.isAbsolute(Q)?Q:R.resolve(B,Q)).replace(/\\/g,"/").toLowerCase()});let O=[];try{O=X(G)}catch(Q){return this}for(const Q of O){const Y=Q.path.replace(/\\/g,"/").toLowerCase();if(this.loadedPaths.has(Y))continue;if(Y===__filename.replace(/\\/g,"/").toLowerCase()||Y.endsWith(".d.ts"))continue;try{const F=await import(x(Q.path).href);let J=F.default;if(!J)J=Object.values(F).find((W)=>typeof W==="function"&&!!W.prototype&&!!W.name);if(typeof J==="function"&&!!J.prototype&&!!J.name){if(this.registeredClasses.has(J))continue;const W=this.getName(J);if(W&&!this.checkRegistration(this.container,W)){this.container.register({[W]:K(J).setLifetime(E)});this.loadedPaths.add(Y);this.registeredClasses.add(J)}}}catch(w){if(H)console.error("[DI] Load Error:",w.message)}}return this}register(q,A=Z.SINGLETON){const H=this.getName(q);if(!H||this.registeredClasses.has(q))return this;if(this.checkRegistration(this.container,H))return this;this.container.register({[H]:K(q).setLifetime(A)});this.registeredClasses.add(q);return this}registerInstance(q,A){if(!q)return this;const H=this.getName(q);this.container.register({[H]:j(A)});return this}async initialize(q,A=!1){if(this.isInitializing)return this;this.isInitializing=!0;try{const H=q?Array.isArray(q)?q:[q]:[];for(const E of H){const B=this.getName(E.service);if(!B||this.initializedNames.has(B))continue;const G=this.container.registrations[B];if(!G||G.lifetime!==Z.SINGLETON)continue;try{const O=this.container.cradle[B];if(O&&typeof O.onInit==="function")await O.onInit(E.props||{});this.initializedNames.add(B)}catch(O){if(A)console.error(`[DI] Priority onInit Failed (${B}):`,O.message)}}const $=Object.keys(this.container.registrations);for(const E of $){if(this.initializedNames.has(E))continue;if(this.container.registrations[E].lifetime!==Z.SINGLETON)continue;try{const G=this.container.cradle[E];if(G&&typeof G.onInit==="function")await G.onInit({});this.initializedNames.add(E)}catch(G){if(A)console.error(`[DI] Auto onInit Failed (${E}):`,G.message)}}for(const E of this.initializedNames)try{const B=this.container.cradle[E];if(B&&typeof B.onAfterInit==="function")await B.onAfterInit()}catch(B){if(A)console.error(`[DI] onAfterInit Failed (${E}):`,B.message)}}finally{this.isInitializing=!1}return this}get(q){const A=this.getName(q);return this.container.resolve(A)}async shutdown(){for(const q of this.initializedNames)try{const A=this.container.cradle[q];if(A&&typeof A.onDispose==="function")await A.onDispose()}catch(A){console.error(`[DI] onDispose Failed (${q})`)}await this.container.dispose()}get cradle(){return this.container.cradle}}const _=globalThis;if(!_[xSymbol])_[xSymbol]=new U;export default _[xSymbol];