modelence 0.5.1-dev.1 → 0.5.1-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-NHKQ6ZAI.js → chunk-NYWVIXEW.js} +2 -2
- package/dist/{chunk-NHKQ6ZAI.js.map → chunk-NYWVIXEW.js.map} +1 -1
- package/dist/{package-K7OWX74D.js → package-YU7BTQ6Z.js} +3 -3
- package/dist/{package-K7OWX74D.js.map → package-YU7BTQ6Z.js.map} +1 -1
- package/dist/server.js +1 -1
- package/dist/telemetry.d.ts +1 -1
- package/dist/telemetry.js +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import P from'elastic-apm-node';import y from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import l from'process';var g={},u={},b=false;function p(t){return u[t]?.value}function U(){if(!b)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(u).filter(([t])=>g[t]?.isPublic))}function W(t){t.forEach(({key:e,type:n,value:o})=>{!e.toLowerCase().startsWith("_system.")&&!g[e]||(u[e]={key:e,type:n,value:o});}),b=true;}function R(t){Object.entries(t).forEach(([e,n])=>{let{type:o,isPublic:r}=n;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(o==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),g=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function x({elasticCloudId:t,elasticApiKey:e}){let n=l.stdout.write,o=l.stderr.write;l.stdout.write=function(r,...c){return L(r.toString(),i.stdout),n.call(l.stdout,r,...c)},l.stderr.write=function(r,...c){return L(r.toString(),i.stderr),o.call(l.stderr,r,...c)},S();}function L(t,e){if(t.length===0)return;let n=new Date;for(let o=0;o<t.length;o++){let r=e[e.length-1];r.timestamp||(r.timestamp=n,r.sequenceId=z++),t[o]===`
|
|
2
|
-
`?e.push({log:"",timestamp:null}):r.log+=t[o];}}async function B(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:n,timestamp:o,sequenceId:r})=>{m(n,{timestamp:o,source:"console",sequenceId:r});}),e.forEach(({log:n,timestamp:o,sequenceId:r})=>{d(n,{timestamp:o,source:"console",sequenceId:r});});}function S(){setTimeout(()=>{B(),S();},1e3);}var s=null;function J(){}function Q(t){s=Object.assign({},s,t);}function I(){return s?.deploymentId}function v(){return s?.appAlias}function T(){return s?.deploymentAlias}function K(){return s?.telemetry?.serviceName}function a(){return !!s?.telemetry?.isEnabled}var M=false,f=null,E=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,a()&&await N();};async function N(){let t=p("_system.elastic.apmEndpoint"),e=p("_system.elastic.cloudId"),n=p("_system.elastic.apiKey"),o=v()??"unknown",r=T()??"unknown",c=I()??"unknown",C=K();f=P.start({serviceName:C,apiKey:n,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:c,appAlias:o,deploymentAlias:r}});let h=new ElasticsearchTransport({apm:f,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:n},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});h.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),E=y.createLogger({level:"debug",defaultMeta:{serviceName:C},format:y.format.combine(y.format.json()),transports:[h]}),x({elasticCloudId:e,elasticApiKey:n});}function A(){if(!f)throw new Error("APM is not initialized");return f}function w(){if(!E)throw new Error("Logger is not initialized");return E}function m(t,e){a()&&w().info(t,e);}function d(t,e){a()&&w().error(t,e);}function O(t,e,n){if(!a())return {end:()=>{}};let o=A(),r=o.startTransaction(e,t);return n&&o.setCustomContext(n),r}function q(t){if(!a()){console.error(t);return}A().captureError(t);}export{p as a,U as b,W as c,R as d,J as e,Q as f,rt as g,m as h,d as i,O as j,q as k};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
`?e.push({log:"",timestamp:null}):r.log+=t[o];}}async function B(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:n,timestamp:o,sequenceId:r})=>{m(n,{timestamp:o,source:"console",sequenceId:r});}),e.forEach(({log:n,timestamp:o,sequenceId:r})=>{d(n,{timestamp:o,source:"console",sequenceId:r});});}function S(){setTimeout(()=>{B(),S();},1e3);}var s=null;function J(){}function Q(t){s=Object.assign({},s,t);}function I(){return s?.deploymentId}function v(){return s?.appAlias}function T(){return s?.deploymentAlias}function K(){return s?.telemetry?.serviceName}function a(){return !!s?.telemetry?.isEnabled}var M=false,f=null,E=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,a()&&await N();};async function N(){let t=p("_system.elastic.apmEndpoint"),e=p("_system.elastic.cloudId"),n=p("_system.elastic.apiKey"),o=v()??"unknown",r=T()??"unknown",c=I()??"unknown",C=K();f=P.start({serviceName:C,apiKey:n,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:c,appAlias:o,deploymentAlias:r}});let h=new ElasticsearchTransport({apm:f,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:n},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});h.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),E=y.createLogger({level:"debug",defaultMeta:{serviceName:C},format:y.format.combine(y.format.json()),transports:[h]}),x({elasticCloudId:e,elasticApiKey:n});}function A(){if(!f)throw new Error("APM is not initialized");return f}function w(){if(!E)throw new Error("Logger is not initialized");return E}function m(t,e){a()&&w().info(t,e);}function d(t,e){a()&&w().error(t,e);}function O(t,e,n){if(!a())return {end:()=>{}};let o=A(),r=o.startTransaction(e,t);return n&&o.setCustomContext(n),r}function q(t){if(!a()){console.error(t);return}A().captureError(t);}export{p as a,U as b,W as c,R as d,J as e,Q as f,rt as g,m as h,d as i,O as j,q as k};//# sourceMappingURL=chunk-NYWVIXEW.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-NYWVIXEW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","appStarted","metadata","markAppStarted","setMetadata","_metadata","getDeploymentId","getAppAlias","getDeploymentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","deploymentAlias","deploymentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAgB,CAAA,KAAA,CAEb,SAASC,CAAAA,CAAUC,CAAgB,CAAA,CACxC,OAAOH,CAAOG,CAAAA,CAAG,CAAG,EAAA,KACtB,CAEO,SAASC,CAAmB,EAAA,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAM,CAAA,0FAA0F,CAG5G,CAAA,OAAO,OAAO,WACZ,CAAA,MAAA,CAAO,OAAQD,CAAAA,CAAM,CAAE,CAAA,MAAA,CAAO,CAAC,CAACG,CAAG,CAAMJ,GAAAA,CAAAA,CAAaI,CAAG,CAAA,EAAG,QAAQ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C,CAEO,SAASW,CAAS2B,CAAAA,CAAAA,CAAiBtC,CAAc,CAAA,CAClDqB,CAAmB,EAAA,EACrBgB,CAAU,EAAA,CAAE,KAAMC,CAAAA,CAAAA,CAAStC,CAAI,EAEnC,CAEO,SAASuC,CAAAA,CAAiBrD,CAAyBsD,CAAAA,CAAAA,CAAcC,EAA+B,CACrG,GAAI,CAACpB,CAAAA,EACH,CAAA,OAAO,CACL,GAAK,CAAA,IAAM,EAGb,CAGF,CAAA,IAAMC,CAAMc,CAAAA,CAAAA,EACNM,CAAAA,CAAAA,CAAcpB,CAAI,CAAA,gBAAA,CAAiBkB,CAAMtD,CAAAA,CAAI,EACnD,OAAIuD,CAAAA,EACFnB,CAAI,CAAA,gBAAA,CAAiBmB,CAAO,CAAA,CAEvBC,CACT,CAEO,SAASC,CAAAA,CAAaT,CAAc,CAAA,CACzC,GAAI,CAACb,GAAsB,CAAA,CACzB,OAAQ,CAAA,KAAA,CAAMa,CAAK,CAAA,CACnB,MACF,CAEAE,CAAO,EAAA,CAAE,YAAaF,CAAAA,CAAK,EAC7B","file":"chunk-NHKQ6ZAI.js","sourcesContent":["import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","type AppMetadata = {\n deploymentId: string;\n appAlias: string;\n deploymentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getDeploymentId() {\n return metadata?.deploymentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getDeploymentAlias() {\n return metadata?.deploymentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport { getAppAlias, getDeploymentAlias, getDeploymentId, getTelemetryServiceName, isTelemetryEnabled } from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const deploymentAlias = getDeploymentAlias() ?? 'unknown';\n const deploymentId = getDeploymentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n deploymentId,\n appAlias,\n deploymentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false\n }\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\n\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\nexport function startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","appStarted","metadata","markAppStarted","setMetadata","_metadata","getDeploymentId","getAppAlias","getDeploymentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","deploymentAlias","deploymentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAgB,CAAA,KAAA,CAEb,SAASC,CAAAA,CAAUC,CAAgB,CAAA,CACxC,OAAOH,CAAOG,CAAAA,CAAG,CAAG,EAAA,KACtB,CAEO,SAASC,CAAmB,EAAA,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAM,CAAA,0FAA0F,CAG5G,CAAA,OAAO,OAAO,WACZ,CAAA,MAAA,CAAO,OAAQD,CAAAA,CAAM,CAAE,CAAA,MAAA,CAAO,CAAC,CAACG,CAAG,CAAMJ,GAAAA,CAAAA,CAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,CAAYC,CAAAA,CAAAA,CAAsB,CAChDA,CAAAA,CAAQ,QAAQ,CAAC,CAAE,GAAAH,CAAAA,CAAAA,CAAK,KAAAI,CAAM,CAAA,KAAA,CAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBL,CAAI,CAAA,WAAA,GAAc,UAAW,CAAA,UAAU,CAEvC,EAAA,CAACJ,CAAaI,CAAAA,CAAG,CAKxCH,GAAAA,CAAAA,CAAOG,CAAG,CAAI,CAAA,CACZ,GAAAA,CAAAA,CAAAA,CACA,IAAAI,CAAAA,CAAAA,CACA,KAAAC,CAAAA,CACF,GACF,CAAC,CAAA,CAEDP,CAAgB,CAAA,KAClB,CAEO,SAASQ,CAAUC,CAAAA,CAAAA,CAAsB,CAE9C,MAAO,CAAA,OAAA,CAAQA,CAAM,CAAA,CAAE,OAAQ,CAAA,CAAC,CAACP,CAAAA,CAAKK,CAAK,CAAM,GAAA,CAC/C,GAAM,CAAE,IAAAD,CAAAA,CAAAA,CAAM,QAAAI,CAAAA,CAAS,EAAIH,CAE3B,CAAA,GAAIL,CAAI,CAAA,WAAA,EAAc,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Key, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","type AppMetadata = {\n deploymentId: string;\n appAlias: string;\n deploymentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getDeploymentId() {\n return metadata?.deploymentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getDeploymentAlias() {\n return metadata?.deploymentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport { getAppAlias, getDeploymentAlias, getDeploymentId, getTelemetryServiceName, isTelemetryEnabled } from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const deploymentAlias = getDeploymentAlias() ?? 'unknown';\n const deploymentId = getDeploymentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n deploymentId,\n appAlias,\n deploymentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false\n }\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\n\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\nexport function startTransaction(type: 'method' | 'cron' | 'ai' | 'custom', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",n="0.5.1-dev.
|
|
2
|
-
export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-
|
|
3
|
-
//# sourceMappingURL=package-
|
|
1
|
+
var s="module",i="modelence",n="0.5.1-dev.2",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:m,repository:a,author:u,license:y,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-YU7BTQ6Z.js.map
|
|
3
|
+
//# sourceMappingURL=package-YU7BTQ6Z.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,aAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,CAAS,CACP,MACA,CAAA,UACF,EACAC,CAAO,CAAA,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,OACT,GAAO,CAAA,cAAA,CACP,eAAkB,eAClB,CAAA,IAAA,CAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CACAC,CAAAA,CAAAA,CAAc,CACZ,IAAQ,CAAA,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WACVC,CAAAA,CAAAA,CAAW,yBACXC,CAAQ,CAAA,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBACZC,CAAAA,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,SACnB,eAAiB,CAAA,QAAA,CACjB,iBAAkB,QAClB,CAAA,iBAAA,CAAmB,UACnB,aAAe,CAAA,SAAA,CACf,eAAgB,SAChB,CAAA,kBAAA,CAAoB,UACpB,kCAAoC,CAAA,SAAA,CACpC,4BAA6B,SAC7B,CAAA,KAAA,CAAS,UACT,WAAa,CAAA,SAAA,CACb,UAAc,CAAA,QAChB,EACAC,CAAgB,CAAA,CACd,gBAAiB,SACjB,CAAA,sBAAA,CAAwB,SACxB,QAAY,CAAA,QAAA,CACZ,OAAU,QACV,CAAA,SAAA,CAAa,UACb,MAAU,CAAA,SAAA,CACV,mBAAoB,QACpB,CAAA,OAAA,CAAW,UACX,UAAY,CAAA,SAAA,CACZ,IAAQ,CAAA,QAAA,CACR,QAAW,QACX,CAAA,IAAA,CAAQ,UACR,IAAQ,CAAA,QAAA,CACR,IAAO,SACP,CAAA,IAAA,CAAQ,SACR,oBAAsB,CAAA,QAAA,CACtB,QAAW,SACX,CAAA,uBAAA,CAAyB,UACzB,GAAO,CAAA,SAAA,CACP,QAAW,QACb,CAAA,CACAC,CAAoB,CAAA,CAClB,MAAS,UACT,CAAA,WAAA,CAAa,UACf,CA7EFC,CAAAA,CAAAA,CAAA,CACE,IAAAlB,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,OAAA,CAAAC,EACA,WAAAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAOA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAsBA,iBAAAC,CAIF","file":"package-
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,aAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,CAAS,CACP,MACA,CAAA,UACF,EACAC,CAAO,CAAA,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,OACT,GAAO,CAAA,cAAA,CACP,eAAkB,eAClB,CAAA,IAAA,CAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CACAC,CAAAA,CAAAA,CAAc,CACZ,IAAQ,CAAA,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WACVC,CAAAA,CAAAA,CAAW,yBACXC,CAAQ,CAAA,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBACZC,CAAAA,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,SACnB,eAAiB,CAAA,QAAA,CACjB,iBAAkB,QAClB,CAAA,iBAAA,CAAmB,UACnB,aAAe,CAAA,SAAA,CACf,eAAgB,SAChB,CAAA,kBAAA,CAAoB,UACpB,kCAAoC,CAAA,SAAA,CACpC,4BAA6B,SAC7B,CAAA,KAAA,CAAS,UACT,WAAa,CAAA,SAAA,CACb,UAAc,CAAA,QAChB,EACAC,CAAgB,CAAA,CACd,gBAAiB,SACjB,CAAA,sBAAA,CAAwB,SACxB,QAAY,CAAA,QAAA,CACZ,OAAU,QACV,CAAA,SAAA,CAAa,UACb,MAAU,CAAA,SAAA,CACV,mBAAoB,QACpB,CAAA,OAAA,CAAW,UACX,UAAY,CAAA,SAAA,CACZ,IAAQ,CAAA,QAAA,CACR,QAAW,QACX,CAAA,IAAA,CAAQ,UACR,IAAQ,CAAA,QAAA,CACR,IAAO,SACP,CAAA,IAAA,CAAQ,SACR,oBAAsB,CAAA,QAAA,CACtB,QAAW,SACX,CAAA,uBAAA,CAAyB,UACzB,GAAO,CAAA,SAAA,CACP,QAAW,QACb,CAAA,CACAC,CAAoB,CAAA,CAClB,MAAS,UACT,CAAA,WAAA,CAAa,UACf,CA7EFC,CAAAA,CAAAA,CAAA,CACE,IAAAlB,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,OAAA,CAAAC,EACA,WAAAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAOA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAsBA,iBAAAC,CAIF","file":"package-YU7BTQ6Z.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.1-dev.2\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g as g$1,a as a$2,h,j,k}from'./chunk-NHKQ6ZAI.js';export{a as getConfig}from'./chunk-NHKQ6ZAI.js';import Fe from'dotenv';import nt from'http';import q from'express';import y,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import st from'os';import lt from'bcrypt';import {createServer,defineConfig}from'vite';import wt from'@vitejs/plugin-react';import B from'path';import bt from'fs';function Le(){return typeof window!="object"}function w(){if(!Le())throw new Error("This function can only be called on the server")}var oe=new Map,C={authenticated:null,unauthenticated:null};function ne(t,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))oe.set(o,n);}function v(){return C.unauthenticated?[C.unauthenticated]:[]}function re(){return C.authenticated?[C.authenticated]:[]}function ie(t,e){let o=e.find(n=>!Be(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Be(t,e){for(let o of t){let n=oe.get(o);if(n&&n.permissions.includes(e))return true}return false}var N={};function U(t,e){return w(),le(t),I("query",t,e)}function se(t,e){return w(),le(t),I("mutation",t,e)}function ae(t,e){return w(),de(t),I("query",t,e)}function ce(t,e){return w(),de(t),I("mutation",t,e)}function le(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function de(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function I(t,e,o){if(w(),N[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];N[e]={type:t,name:e,handler:n,permissions:i};}async function ue(t,e,o){w();let n=N[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{ie(o.roles,n.permissions),c=await r(e,o);}catch(h){throw s.end("error"),h}return s.end(),c}var p=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var We=z$1.string.bind(z$1),Ke=z$1.number.bind(z$1),Ve=z$1.date.bind(z$1),He=z$1.boolean.bind(z$1),Ze=z$1.array.bind(z$1),Qe=z$1.object.bind(z$1),Ge=z$1.enum.bind(z$1),a={string:We,number:Ke,date:Ve,boolean:He,array:Ze,object:Qe,enum:Ge,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var S=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function pe(t){let e=t?await S.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Xe()}async function fe(t,e){await S.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await S.updateOne({authToken:t},{$set:{userId:null}});}async function Xe(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await S.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function et(t){let e=Date.now(),o=new Date(e+a$1.days(7));await S.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new p("_system.session",{stores:[S],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await et(e);}}});var u=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});async function ye(t){let e=await pe(t),o=e.userId?await u.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?re():v();return {user:n,session:e,roles:i}}function we(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4||n instanceof b$2?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var g=null;async function be(){if(g)return g;let t=D();if(!t)throw new Error("MongoDB URI is not set");g=new MongoClient(t,{maxPoolSize:20});try{return await g.connect(),await g.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),g}catch(e){throw console.error(e),g=null,e}}function D(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ce(){return g}function rt(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,we(c));});}}async function Se(t,{combinedModules:e}){let o=q();o.use(q.json()),o.use(q.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,h=await it(r);try{let d=await ue(c,r.body.args,h);s.json({data:d,typeMap:a$3(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let x=d.flatten(),M=Object.entries(x.fieldErrors).map(([k,P])=>`${k}: ${(P??[]).join(", ")}`).join("; "),A=x.formErrors.join("; "),j=[M,A].filter(Boolean).join("; ");s.status(400).send(j);}else s.status(500).send(d instanceof Error?d.message:String(d));}}),rt(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=nt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function it(t){let e=y.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!D()){let{session:r,user:s,roles:c}=await ye(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:v()}}async function xe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await z("/api/connect","POST",{hostname:st.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Me(){return await z("/api/configs","GET")}async function Ee(){return await z("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function z(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var F=false,at=a$1.seconds(10);function De(){setInterval(async()=>{if(!F){F=true;try{await Ee();}catch(t){console.error("Error syncing status",t);}try{await ct();}catch(t){console.error("Error syncing config",t);}F=false;}},at);}async function ct(){let{configs:t}=await Me();c(t);}async function Re(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await u.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(h=>h.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await lt.hash(n,10);return (await u.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function Ie(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),i=z$1.string().parse(t.password),r=await u.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await lt.compare(i,s))throw ve();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function _e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function ve(){return new Error("Incorrect email/password combination")}async function Ae(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await u.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var je=new p("_system.user",{stores:[u],queries:{getOwnProfile:Ae},mutations:{signupWithPassword:Re,loginWithPassword:Ie,logout:_e}});var _=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function ke(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await _.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await _.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Pe=new p("_system.migration",{stores:[_]});var ut=a$1.minutes(1),mt=a$1.seconds(10),b={},L,T=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ne(t,{description:e="",interval:o,timeout:n=ut,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(L)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function Ue(){if(L)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await T.findOne({...e,"lock.containerId":{$exists:true}});await T.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await pt(mt);let n=await T.fetch(e),i=Date.now();n.forEach(r=>{let s=b[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),L=setInterval(ft,a$1.seconds(1));}}function pt(t){return new Promise(e=>setTimeout(e,t))}async function ft(){let t=Date.now();Object.values(b).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await ht(e);});}async function ht(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{$e(i,o),r.end("success");}).catch(s=>{$e(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await T.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function $e(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Je(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qe=new p("_system.cron",{stores:[T]});var W=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await St()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[q.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function St(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>bt.existsSync(B.join(t,n))),o=[wt(),xt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:B.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":B.resolve(t,"src")}}}}function xt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var ze=new W;async function Mt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=ze,migrations:i=[]}){Fe.config(),Fe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";_t().then(()=>{}).catch(()=>{});let c$1=[je,ge,qe,Pe],h=[...c$1,...t];e(),Dt(c$1),Et(t),ne(e$1,o);let d$1=Rt(h);d(d$1??{});let R=Tt(h);if(s&&Ot(h),r){let{configs:M,deploymentId:A,appAlias:j,deploymentAlias:k,telemetry:P}=await xe({configSchema:d$1,cronJobsMetadata:s?Je():void 0,stores:R});c(M),f$1({deploymentId:A,appAlias:j,deploymentAlias:k,telemetry:P});}else c(It());let x=D();if(x&&(await be(),vt(R)),s&&await ke(i),x)for(let M of R)M.createIndexes();r&&(await g$1(),De()),s&&Ue().catch(console.error),await Se(n,{combinedModules:h});}function Et(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))U(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))se(`${e.name}.${o}`,n);}}function Dt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ae(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ce(`${e.name}.${o}`,n);}}function Tt(t){return t.flatMap(e=>e.stores)}function Rt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Ot(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ne(`${e.name}.${o}`,n);}function vt(t){let e=Ce();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function It(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function _t(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=await import('./package-K7OWX74D.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:o.default.version})});}}
|
|
1
|
+
import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g as g$1,a as a$2,h,j,k}from'./chunk-NYWVIXEW.js';export{a as getConfig}from'./chunk-NYWVIXEW.js';import Fe from'dotenv';import nt from'http';import q from'express';import y,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import st from'os';import lt from'bcrypt';import {createServer,defineConfig}from'vite';import wt from'@vitejs/plugin-react';import B from'path';import bt from'fs';function Le(){return typeof window!="object"}function w(){if(!Le())throw new Error("This function can only be called on the server")}var oe=new Map,C={authenticated:null,unauthenticated:null};function ne(t,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))oe.set(o,n);}function v(){return C.unauthenticated?[C.unauthenticated]:[]}function re(){return C.authenticated?[C.authenticated]:[]}function ie(t,e){let o=e.find(n=>!Be(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Be(t,e){for(let o of t){let n=oe.get(o);if(n&&n.permissions.includes(e))return true}return false}var N={};function U(t,e){return w(),le(t),I("query",t,e)}function se(t,e){return w(),le(t),I("mutation",t,e)}function ae(t,e){return w(),de(t),I("query",t,e)}function ce(t,e){return w(),de(t),I("mutation",t,e)}function le(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function de(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function I(t,e,o){if(w(),N[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];N[e]={type:t,name:e,handler:n,permissions:i};}async function ue(t,e,o){w();let n=N[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{ie(o.roles,n.permissions),c=await r(e,o);}catch(h){throw s.end("error"),h}return s.end(),c}var p=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var We=z$1.string.bind(z$1),Ke=z$1.number.bind(z$1),Ve=z$1.date.bind(z$1),He=z$1.boolean.bind(z$1),Ze=z$1.array.bind(z$1),Qe=z$1.object.bind(z$1),Ge=z$1.enum.bind(z$1),a={string:We,number:Ke,date:Ve,boolean:He,array:Ze,object:Qe,enum:Ge,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var S=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function pe(t){let e=t?await S.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Xe()}async function fe(t,e){await S.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await S.updateOne({authToken:t},{$set:{userId:null}});}async function Xe(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await S.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function et(t){let e=Date.now(),o=new Date(e+a$1.days(7));await S.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new p("_system.session",{stores:[S],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await et(e);}}});var u=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});async function ye(t){let e=await pe(t),o=e.userId?await u.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?re():v();return {user:n,session:e,roles:i}}function we(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4||n instanceof b$2?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var g=null;async function be(){if(g)return g;let t=D();if(!t)throw new Error("MongoDB URI is not set");g=new MongoClient(t,{maxPoolSize:20});try{return await g.connect(),await g.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),g}catch(e){throw console.error(e),g=null,e}}function D(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ce(){return g}function rt(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,we(c));});}}async function Se(t,{combinedModules:e}){let o=q();o.use(q.json()),o.use(q.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,h=await it(r);try{let d=await ue(c,r.body.args,h);s.json({data:d,typeMap:a$3(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let x=d.flatten(),M=Object.entries(x.fieldErrors).map(([k,P])=>`${k}: ${(P??[]).join(", ")}`).join("; "),A=x.formErrors.join("; "),j=[M,A].filter(Boolean).join("; ");s.status(400).send(j);}else s.status(500).send(d instanceof Error?d.message:String(d));}}),rt(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=nt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function it(t){let e=y.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!D()){let{session:r,user:s,roles:c}=await ye(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:v()}}async function xe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await z("/api/connect","POST",{hostname:st.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Me(){return await z("/api/configs","GET")}async function Ee(){return await z("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function z(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var F=false,at=a$1.seconds(10);function De(){setInterval(async()=>{if(!F){F=true;try{await Ee();}catch(t){console.error("Error syncing status",t);}try{await ct();}catch(t){console.error("Error syncing config",t);}F=false;}},at);}async function ct(){let{configs:t}=await Me();c(t);}async function Re(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await u.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(h=>h.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await lt.hash(n,10);return (await u.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function Ie(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),i=z$1.string().parse(t.password),r=await u.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await lt.compare(i,s))throw ve();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function _e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function ve(){return new Error("Incorrect email/password combination")}async function Ae(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await u.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var je=new p("_system.user",{stores:[u],queries:{getOwnProfile:Ae},mutations:{signupWithPassword:Re,loginWithPassword:Ie,logout:_e}});var _=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function ke(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await _.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await _.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Pe=new p("_system.migration",{stores:[_]});var ut=a$1.minutes(1),mt=a$1.seconds(10),b={},L,T=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ne(t,{description:e="",interval:o,timeout:n=ut,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(L)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function Ue(){if(L)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await T.findOne({...e,"lock.containerId":{$exists:true}});await T.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await pt(mt);let n=await T.fetch(e),i=Date.now();n.forEach(r=>{let s=b[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),L=setInterval(ft,a$1.seconds(1));}}function pt(t){return new Promise(e=>setTimeout(e,t))}async function ft(){let t=Date.now();Object.values(b).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await ht(e);});}async function ht(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{$e(i,o),r.end("success");}).catch(s=>{$e(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await T.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function $e(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Je(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qe=new p("_system.cron",{stores:[T]});var W=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await St()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[q.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function St(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>bt.existsSync(B.join(t,n))),o=[wt(),xt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:B.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":B.resolve(t,"src")}}}}function xt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var ze=new W;async function Mt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=ze,migrations:i=[]}){Fe.config(),Fe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";_t().then(()=>{}).catch(()=>{});let c$1=[je,ge,qe,Pe],h=[...c$1,...t];e(),Dt(c$1),Et(t),ne(e$1,o);let d$1=Rt(h);d(d$1??{});let R=Tt(h);if(s&&Ot(h),r){let{configs:M,deploymentId:A,appAlias:j,deploymentAlias:k,telemetry:P}=await xe({configSchema:d$1,cronJobsMetadata:s?Je():void 0,stores:R});c(M),f$1({deploymentId:A,appAlias:j,deploymentAlias:k,telemetry:P});}else c(It());let x=D();if(x&&(await be(),vt(R)),s&&await ke(i),x)for(let M of R)M.createIndexes();r&&(await g$1(),De()),s&&Ue().catch(console.error),await Se(n,{combinedModules:h});}function Et(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))U(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))se(`${e.name}.${o}`,n);}}function Dt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ae(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ce(`${e.name}.${o}`,n);}}function Tt(t){return t.flatMap(e=>e.stores)}function Rt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Ot(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ne(`${e.name}.${o}`,n);}function vt(t){let e=Ce();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function It(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function _t(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=await import('./package-YU7BTQ6Z.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:o.default.version})});}}
|
|
2
2
|
export{p as Module,f as Store,U as createQuery,u as dbUsers,a as schema,Mt as startApp};//# sourceMappingURL=server.js.map
|
|
3
3
|
//# sourceMappingURL=server.js.map
|
package/dist/telemetry.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as elastic_apm_node from 'elastic-apm-node';
|
|
|
2
2
|
|
|
3
3
|
declare function logInfo(message: string, args: object): void;
|
|
4
4
|
declare function logError(message: string, args: object): void;
|
|
5
|
-
declare function startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>): elastic_apm_node.Transaction | {
|
|
5
|
+
declare function startTransaction(type: 'method' | 'cron' | 'ai' | 'custom', name: string, context?: Record<string, any>): elastic_apm_node.Transaction | {
|
|
6
6
|
end: () => void;
|
|
7
7
|
};
|
|
8
8
|
declare function captureError(error: Error): void;
|
package/dist/telemetry.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{k as captureError,i as logError,h as logInfo,j as startTransaction}from'./chunk-
|
|
1
|
+
export{k as captureError,i as logError,h as logInfo,j as startTransaction}from'./chunk-NYWVIXEW.js';//# sourceMappingURL=telemetry.js.map
|
|
2
2
|
//# sourceMappingURL=telemetry.js.map
|