@lunora/codegen 1.0.0-alpha.400 → 1.0.0-alpha.402
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/index.d.mts +86 -1
- package/dist/index.d.ts +86 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-Cli3X44r.mjs → AGENTS_FILENAME-BiSJTXnu.mjs} +1 -1
- package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs → ALL_NOTIFY_CHANNELS-_xAn-jI3.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-BX1_ALLp.mjs → CONTAINERS_FILENAME-Bj3hFBa-.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-BfJ7upI0.mjs +1 -0
- package/dist/packem_shared/{FLAGS_FILENAME-DY3yo1u_.mjs → FLAGS_FILENAME-BW7MzS9C.mjs} +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-B-tYRlRG.mjs → GENERATED_HEADER-DgrhC3Iv.mjs} +1 -1
- package/dist/packem_shared/{LUNORA_ERROR_CODES-CjACC-MQ.mjs → LUNORA_ERROR_CODES-D7AVT7qF.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Ck_l1lz7.mjs → MUTATORS_FILENAME-tPpN_a00.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-Dr6Xjldk.mjs → OPENRPC_VERSION-DI_G2H0Q.mjs} +1 -1
- package/dist/packem_shared/{QUEUES_FILENAME-C5xotY-M.mjs → QUEUES_FILENAME-Cpp-0QI9.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CxmZ2igT.mjs → SCHEMA_SNAPSHOT_FILENAME-CoCuKo3b.mjs} +11 -11
- package/dist/packem_shared/{SHAPES_FILENAME-DCtGHMEm.mjs → SHAPES_FILENAME-cHL4n_Co.mjs} +1 -1
- package/dist/packem_shared/{WORKFLOWS_FILENAME-CyV1HQaP.mjs → WORKFLOWS_FILENAME-BXjKKAmj.mjs} +1 -1
- package/dist/packem_shared/{attribution-DjweYNgJ.mjs → attribution-C6VQNs-V.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-BTp9vkHw.mjs → buildOpenApiDocument-aAAsKnsY.mjs} +1 -1
- package/dist/packem_shared/{capabilitiesUsedBy-SSrieNZ1.mjs → capabilitiesUsedBy-t-UvdnZl.mjs} +1 -1
- package/dist/packem_shared/chain-BvRxehwv.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BuF5PNwV.mjs → classify-procedure-call-DwWrpCoX.mjs} +1 -1
- package/dist/packem_shared/companionServiceBinding-CnEUhH0Z.mjs +1 -0
- package/dist/packem_shared/{context-property-calls-BcUYQ6ph.mjs → context-property-calls-RsCkfFCU.mjs} +1 -1
- package/dist/packem_shared/{context-root-2wag3akK.mjs → context-root-CY5kkBER.mjs} +1 -1
- package/dist/packem_shared/{createCodegenProject-C8N4Zm8h.mjs → createCodegenProject-BC4GwdnG.mjs} +1 -1
- package/dist/packem_shared/{database-calls-B_85LJIk.mjs → database-calls-HP2mxQAR.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-f8_WRQEA.mjs → discoverAuthApiCalls-CHytF_NH.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-DTqSuSDh.mjs → discoverCrons-C6Y1u_kI.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-B-051l15.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-2gxHuLgt.mjs → discoverHttpRoutes-BccPlGZb.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DmUuhUoL.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-CLh70kVu.mjs → discoverInserts-z7jg8LD3.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-CrkT80jO.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-e5_NQdf-.mjs → discoverMigrations-B6u2Do9_.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CrXAegUc.mjs → discoverNondeterministicCalls-Dei7EUFX.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-T8b_7ZZ-.mjs → discoverQueries-D4mihML_.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-Ej8oRuVk.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CnVvP2Ps.mjs → discoverRlsMetadata-CNn4cdfy.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-DttY0Jld.mjs → discoverRlsProcedures-CsczAow2.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-X0SECo-x.mjs → discoverSandboxUsage-EKZOCCPU.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-BcyKCBIw.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-t_oMSn0L.mjs → discoverStorageRulesMetadata-yCB6MdrA.mjs} +1 -1
- package/dist/packem_shared/{emitAgents-ChXyTTzS.mjs → emitAgents-ec5ov78B.mjs} +1 -1
- package/dist/packem_shared/{emitApi-Cdc8MeNK.mjs → emitApi-lwadq5G7.mjs} +1 -1
- package/dist/packem_shared/{emitApp-xunr1-_c.mjs → emitApp-C3IUdkkt.mjs} +37 -28
- package/dist/packem_shared/{emitCrons-BQjDleCe.mjs → emitCrons-CCRKs482.mjs} +1 -1
- package/dist/packem_shared/{emitDataModel-MjAOi3KM.mjs → emitDataModel-BvCZS4Yq.mjs} +1 -1
- package/dist/packem_shared/{emitDrizzleSchema-Dszoyymv.mjs → emitDrizzleSchema-BzOChEYW.mjs} +1 -1
- package/dist/packem_shared/{emitFunctions-BIMKBLQ8.mjs → emitFunctions-ppMX7E3X.mjs} +1 -1
- package/dist/packem_shared/{emitServer-DNwuNiay.mjs → emitServer-DsSAaZaT.mjs} +1 -1
- package/dist/packem_shared/{emitShard-CueduzG1.mjs → emitShard-Dhy_F7iF.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-BaxQ8C-S.mjs → exported-procedure-chains-DiNvW1Wl.mjs} +1 -1
- package/dist/packem_shared/{fingerprintSchemaSources-PmhepCVj.mjs → fingerprintSchemaSources-Cpom_87X.mjs} +1 -1
- package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-BqSXtjJ6.mjs} +1 -1
- package/dist/packem_shared/index-BPg6e1oa.mjs +1 -0
- package/dist/packem_shared/{index-Dd6T5nSP.mjs → index-DgHhQfpm.mjs} +1 -1
- package/dist/packem_shared/{ip-reads-WFubgB1G.mjs → ip-reads-Bn9qvrMD.mjs} +1 -1
- package/dist/packem_shared/isTestPath-B357_sbh.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-D4_s2UFp.mjs +1 -0
- package/dist/packem_shared/{modules-DE0ksIeR.mjs → modules-BgublqiK.mjs} +1 -1
- package/dist/packem_shared/project-config-file-DBVmBpin.mjs +1 -0
- package/dist/packem_shared/{qualifiers-ClaCHu0X.mjs → qualifiers-qqH8fRTo.mjs} +1 -1
- package/dist/packem_shared/{server-C4h6-BZx.mjs → server-CRFaUMKQ.mjs} +1 -1
- package/dist/packem_shared/{shard-DNpjvEod.mjs → shard-Csztu3jG.mjs} +57 -45
- package/dist/packem_shared/{shard-runtime-knn-ER8x.mjs → shard-runtime-D0xuE0pX.mjs} +1 -1
- package/dist/packem_shared/{shared-DhqnD5R3.mjs → shared-Cn7dMQ_u.mjs} +1 -1
- package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-zNStZJ4K.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +0 -1
- package/dist/packem_shared/chain-DWwd9wXd.mjs +0 -1
- package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +0 -1
- package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +0 -1
- package/dist/packem_shared/index-fVYBrxkP.mjs +0 -1
- package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +0 -1
- package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +0 -1
- package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as fr,m as gr,n as br,o as yr,p as wr,q as vr,s as kr}from"./shard-runtime-
|
|
1
|
+
import{LunoraError as pe}from"@lunora/errors";import{serializeSchemaSnapshot as Zt,hashSchemaSnapshot as er}from"./SCHEMA_SNAPSHOT_VERSION-DTLoSaNn.mjs";import{isHyperdriveGlobalTable as tr,isD1GlobalTable as rr}from"./isD1GlobalTable-udvHAAzD.mjs";import{r as nr}from"./json-data-Chfs2Cz5.mjs";import{r as q,e as ar,a as sr,b as or,c as ir,d as dr,f as cr,g as lr,h as ur,i as hr,j as pr,k as mr,l as fr,m as gr,n as br,o as yr,p as wr,q as vr,s as kr}from"./shard-runtime-D0xuE0pX.mjs";import{u as U,h as Sr,s as Rr,a as xr,I as Ar,c as Or,G as Tr,d as _r}from"./shared-Cn7dMQ_u.mjs";import{p as Dr}from"./platform-8oj7iXQy.mjs";import{i as Ir}from"./schema-BgM8A3XV.mjs";const m=(r,t)=>`((): (() => ${t}) => { let cached: ${t} | undefined; return () => (cached ??= JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${t}); })()`,me=["categories","description","facing","level","remediation","title"],Er=r=>{const t={};return{advisoryRows:r.map(o=>{let n=t[o.name];return n||(n=Object.fromEntries(me.filter(a=>a in o).map(a=>[a,o[a]])),t[o.name]=n),Object.fromEntries(Object.entries(o).filter(([a,i])=>!me.includes(a)||JSON.stringify(i)!==JSON.stringify(n[a])))}),advisoryRules:t}},Cr=` /**
|
|
2
2
|
* The bare writer every admin/maintenance entry point writes through.
|
|
3
3
|
*
|
|
4
4
|
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
@@ -234,7 +234,7 @@ ${y()}
|
|
|
234
234
|
await applyCdcChanges(writer, args.changes);
|
|
235
235
|
|
|
236
236
|
return { applied: args.changes.length };
|
|
237
|
-
}`,Pr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:f,everyContextBuild:c,everyContextField:g,facadeBlock:A,globalDatabaseLine:w,hasSensitiveArgs:u=!1,lazyFunctions:l=!1,notifyBuild:O,ormContextField:v,paymentsBuild:F,paymentsContextField:
|
|
237
|
+
}`,Pr=({actionOnlyBuild:r,actionOnlyFields:t,agentsBuild:e,agentsContextField:o,agentsSchedulerSource:n,containersBuild:a,containersContextField:i,databaseOptions:f,everyContextBuild:c,everyContextField:g,facadeBlock:A,globalDatabaseLine:w,hasSensitiveArgs:u=!1,lazyFunctions:l=!1,notifyBuild:O,ormContextField:v,paymentsBuild:F,paymentsContextField:B,queuesBuild:R,queuesContextField:j,topicsBuild:d,topicsContextField:k,vectorsBuild:I,vectorsContextField:W,workflowsBuild:K,workflowsContextField:E})=>{const T=t.length>0,H=v===""?"{ db }":"{ db, orm: bindOrm(facade) }",V=v===""?"":`
|
|
238
238
|
orm: databaseContext.orm,`,C=v===""?"":`
|
|
239
239
|
orm: { configurable: true, enumerable: true, value: mutationDatabase.orm, writable: true },`,x=T?`
|
|
240
240
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
@@ -300,7 +300,7 @@ ${r.replaceAll(/^(?=.)/gmu," ")}${t.map(p=>` ctx.${p} = ${p};`
|
|
|
300
300
|
|
|
301
301
|
return caller.ip;
|
|
302
302
|
};
|
|
303
|
-
${I}${c}${a}${
|
|
303
|
+
${I}${c}${a}${K}${R}${d}${e}
|
|
304
304
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
305
305
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
306
306
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -415,7 +415,7 @@ ${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
415
415
|
// mutation must rebuild its DB and table/ORM views with its own queue.
|
|
416
416
|
const makeDatabaseContext = (scheduler: SchedulerLike) => {
|
|
417
417
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${f}), logFunctionPath, traceAnchor, observability, options.sensitive);
|
|
418
|
-
${A} return ${
|
|
418
|
+
${A} return ${H};
|
|
419
419
|
};
|
|
420
420
|
const databaseContext = makeDatabaseContext(scheduler);
|
|
421
421
|
const db = databaseContext.db;
|
|
@@ -505,11 +505,11 @@ ${O}
|
|
|
505
505
|
// to the handler so code that signs its own URLs (a copy-in
|
|
506
506
|
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
507
507
|
// query and for a deferred dispatch, for the reasons given there.
|
|
508
|
-
origin: requestOrigin,${
|
|
508
|
+
origin: requestOrigin,${V}
|
|
509
509
|
scheduler,
|
|
510
510
|
span,
|
|
511
511
|
storage: contextStorage,
|
|
512
|
-
trace,${
|
|
512
|
+
trace,${W}${g}${B}${i}${E}${j}${k}${o}${u?`
|
|
513
513
|
[Symbol.for("lunora.admitSensitiveArgs")]: (args: Record<string, unknown>, names: ReadonlySet<string>): void => this.admitSensitiveValues(options.sensitive, args, names),`:""}
|
|
514
514
|
};
|
|
515
515
|
${T?` const isAction = contextKind === "action";
|
|
@@ -932,7 +932,7 @@ __COMMITTED_CATCH__ } finally {
|
|
|
932
932
|
// parked it, and there is nothing to park — an app with no scheduler has no
|
|
933
933
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
934
934
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
935
|
-
__OUTBOX_SCHEDULER__ }`,
|
|
935
|
+
__OUTBOX_SCHEDULER__ }`,Mr=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ identityTracked?: boolean; ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
936
936
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
937
937
|
|
|
938
938
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -945,9 +945,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
945
945
|
// Identity is threaded EXPLICITLY from the (deferred/interleaved)
|
|
946
946
|
// subscription caller — never read from the shared per-request field
|
|
947
947
|
// here — so a concurrent RPC can't leak its identity into this re-run.
|
|
948
|
-
|
|
949
|
-
const result = await registered.handler(ctx, args);
|
|
950
|
-
|
|
948
|
+
__SUBSCRIPTION_RUN__
|
|
951
949
|
// Ranges come from THIS run's reads, never a shared field on the DO:
|
|
952
950
|
// a deferred re-run interleaves with unrelated dispatches.
|
|
953
951
|
const ranges = footprint.ranges();
|
|
@@ -980,7 +978,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
980
978
|
return this.windowStreamReads(headroom, (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, headroom, identity }), args, signal));
|
|
981
979
|
},
|
|
982
980
|
};
|
|
983
|
-
}`,
|
|
981
|
+
}`,qr=` } catch (error) {
|
|
984
982
|
// The write committed before this failed. Mark the error so the caller can tell
|
|
985
983
|
// a durable write from a rollback: the rethrow still reaches the caller unchanged.
|
|
986
984
|
if (typeof error === "object" && error !== null) {
|
|
@@ -988,7 +986,7 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
988
986
|
}
|
|
989
987
|
|
|
990
988
|
throw error;
|
|
991
|
-
`,
|
|
989
|
+
`,Ur=(r,t=!1,e=!1)=>{const o=t?` const registeredBeforeLoad = LUNORA_FUNCTIONS[functionPath];
|
|
992
990
|
|
|
993
991
|
if (registeredBeforeLoad?.visibility === "internal" && !this.isSystemDispatch()) {
|
|
994
992
|
throw new LunoraError("FUNCTION_NOT_FOUND", "function not registered: " + functionPath);
|
|
@@ -1008,7 +1006,21 @@ __PREPARE_FUNCTION__ this.ensureServable();
|
|
|
1008
1006
|
`:"",a=e?` const configured = config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1009
1007
|
return configured === undefined ? undefined : withAgentScheduleShard(configured, LUNORA_AGENTS, this.currentShardKey());
|
|
1010
1008
|
`:` return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
1011
|
-
`;return $r.replace("__COMMITTED_CATCH__",r?
|
|
1009
|
+
`;return $r.replace("__COMMITTED_CATCH__",r?qr:"").replace("__PREPARE_FUNCTION__",`${o}${n}`).replace("__OUTBOX_SCHEDULER__",a)},Fr=` const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
|
|
1010
|
+
const result = await registered.handler(ctx, args);
|
|
1011
|
+
`,Br=` const sensitive = this.openSensitiveScope(functionPath, args);
|
|
1012
|
+
let result: unknown;
|
|
1013
|
+
|
|
1014
|
+
try {
|
|
1015
|
+
const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(functionPath, identity), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange, sensitive });
|
|
1016
|
+
|
|
1017
|
+
result = await registered.handler(ctx, args);
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
throw this.maskSensitiveError(error, sensitive);
|
|
1020
|
+
} finally {
|
|
1021
|
+
sensitive.clear();
|
|
1022
|
+
}
|
|
1023
|
+
`,jr=r=>Mr.replace("__SUBSCRIPTION_RUN__",r?Br:Fr),Wr=r=>{const t={};for(const e of r.tables){const o={};for(const[n,a]of Object.entries(e.shape)){const i=U(a);i.kind==="id"&&i.tableName!==void 0&&(o[n]=i.tableName)}Object.keys(o).length>0&&(t[e.name]=o)}return t},Kr=r=>{const t={};for(const e of r.tables){const o=[];for(const[n,a]of Object.entries(e.shape))U(a).kind==="storage"&&o.push(n);o.length>0&&(t[e.name]=o)}return t},Hr=r=>{const t={};for(const e of r.tables){const o=[...e.indexes.map(n=>({fields:[...n.fields],name:n.name,type:"index",...n.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(n=>({fields:[n.field,...n.filterFields??[]],name:n.name,type:"search"})),...(e.geoIndexes??[]).map(n=>({fields:[n.field],name:n.name,type:"geo"})),...e.rankIndexes.map(n=>({fields:n.sortBy.map(a=>a.field),name:n.name,type:"rank"})),...e.vectorIndexes.map(n=>({fields:n.field===void 0?[]:[n.field],name:n.name,type:"vector"}))];o.length>0&&(t[e.name]=o)}return t},Vr=r=>{const t=[];for(const e of r.tables)!e.ttl||e.shardMode==="global"||t.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return t},Gr=r=>{if(r.kind!=="union"||r.members===void 0||r.members.length===0)return;const t=[];for(const e of r.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const o=JSON.parse(e.literalValue);if(typeof o!="string")return;t.push(o)}catch{return}}return t},Qr=new Set(["bigint","boolean","date","number","timestamp"]),zr=r=>{const[t,e]=r.kind==="union"?r.members??[]:[];if(t===void 0||e===void 0||r.members?.length!==2)return;const o=a=>a.kind==="null"||a.kind==="literal"&&a.literalValue==="null",n=U(o(e)?t:e);return o(t)!==o(e)&&Qr.has(n.kind)?n:void 0},Jr=(r,t,e)=>{const o=U(t),n=zr(o),a=n??o,i={name:r,optional:Sr(t),type:a.kind};if(a.kind==="id"&&a.tableName!==void 0){i.ref=a.tableName;const c=e.get(r);c!==void 0&&(i.onDelete=c)}a.kind==="storage"&&(i.isStorage=!0,a.bucket!==void 0&&(i.bucket=a.bucket));const f=Gr(a);return f!==void 0&&(i.enumValues=f),(a.column?.notNull===!1||n!==void 0)&&(i.nullable=!0),i},Yr=r=>{const t={};for(const e of r.tables){const o=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],n=new Map(e.relations.flatMap(a=>a.kind==="one"?[[a.field,a.onDelete]]:[]));for(const[a,i]of Object.entries(e.shape))o.push(Jr(a,i,n));t[e.name]=o}return t},Xr=({hasMutators:r,hasSensitiveShapes:t,hasShapes:e,rlsData:o})=>{const n="{ columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined",a=t?` protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): ${n} {
|
|
1012
1024
|
const sensitive = this.openSensitiveScope(\`__shape__:\${name}\`, args);
|
|
1013
1025
|
|
|
1014
1026
|
try {
|
|
@@ -1090,7 +1102,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as
|
|
|
1090
1102
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
1091
1103
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
1092
1104
|
}
|
|
1093
|
-
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:g,shapeReadPolicyImport:g===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:f}},
|
|
1105
|
+
`:"",shapeGuardImport:e?"assertShapeShardable, ":"",shapeReadPolicyAssertion:g,shapeReadPolicyImport:g===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:f}},Zr=(r,t)=>r?`
|
|
1094
1106
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
1095
1107
|
const env = this.env as Record<string, unknown>;
|
|
1096
1108
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -1156,7 +1168,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as
|
|
|
1156
1168
|
|
|
1157
1169
|
return globalDb.cdcChangedTables?.(sinceSeq, cursorOnly === undefined ? {} : { cursorOnly });
|
|
1158
1170
|
}
|
|
1159
|
-
`:"",
|
|
1171
|
+
`:"",en=r=>({externalSourceOverride:r?`
|
|
1160
1172
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
1161
1173
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
1162
1174
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1313,7 +1325,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(c)}, (schema as
|
|
|
1313
1325
|
`:"",sourceClientCacheConst:r?`
|
|
1314
1326
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1315
1327
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1316
|
-
`:""}),
|
|
1328
|
+
`:""}),tn=(r,t)=>{const e=t.length>0,n=r?q("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertMany","upsertNow"]):"",a=e?` const vectorShardKey = this.currentShardKey();
|
|
1317
1329
|
`:"",i=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",c=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${t.map(w=>JSON.stringify(w)).join(", ")}]`]:[]].join(", ")} }`,g=r?`
|
|
1318
1330
|
const vectorSync = this.vectorSync(env);
|
|
1319
1331
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
@@ -1357,14 +1369,14 @@ ${a} const vectors = createContextVectors(lunora${c});
|
|
|
1357
1369
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1358
1370
|
});
|
|
1359
1371
|
}
|
|
1360
|
-
`:"",vectorsBuild:g,vectorsStub:n}},
|
|
1372
|
+
`:"",vectorsBuild:g,vectorsStub:n}},vn=({advisories:r=[],agents:t=[],capabilities:e=new Set,containers:o=[],env:n,flagKeys:a=[],hasFlags:i=!1,hasNotify:f=!1,hasRooms:c=!1,hasSecretValues:g=!1,hasSensitiveArgs:A=!1,hasSockets:w=!1,lazyFunctions:u=!1,hasVectors:l=!0,liveStreamDeclarations:O=[],liveStreams:v=!1,maskMetadata:F,mutators:B=[],queues:R=[],rlsMetadata:j,schema:d,schemaSnapshot:k,shapes:I=[],storageRules:W,studioFeatures:K,hasIpReaders:E=!1,services:T=[],topics:H=[],useUmbrella:V=!1,workflowEvents:C=[],workflows:x=[]})=>{const h=_r(V),G=B.length>0,p=I.length>0,L=I.some(s=>Rr(s.args).length>0),P=A||L,ge=k===void 0?"":Zt(k),be=k===void 0?"":`
|
|
1361
1373
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1362
1374
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(er(k))}, json: ${JSON.stringify(ge)} };
|
|
1363
|
-
`,ye=k===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",S=ar(e),
|
|
1364
|
-
return { ${
|
|
1375
|
+
`,ye=k===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",S=ar(e),N=sr(i,h.flags),Q=or(a,i,h.flags),z=kr(f),J=ir(n),{build:we,contextField:ve,importLines:ke,specs:Se}=dr(Dr(R)),{build:Re,contextField:xe,importLines:Ae,specs:Oe}=cr(H,R),Y=lr(T,h.server),{build:Te,contextField:_e,importLines:De,specs:Ie}=ur(o,d.jurisdiction),{build:Ee,contextField:Ce,importLines:Le,specs:Pe}=hr(x),{build:Ne,contextField:$e,importLines:Me,schedulerSource:qe,specs:Ue,stampsOutbox:Fe}=pr(t,g&&t.length>0),{build:Be,configField:je,contextField:We,imports:Ke,stub:He}=mr(e.has("payments")),Ve=r,{advisoryRules:Ge,advisoryRows:Qe}=Er(Ve),ne=j??{policies:[],roles:[]},ze=F??{columns:[]},Je=W??{rules:[]},Ye=K??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Xe,override:Ze}=fr(x,C),{constant:et,override:tt}=gr(x,C),{constant:rt,override:nt}=br(R),b=l&&d.vectorIndexes.length>0,X=new Set(d.tables.filter(s=>Ir(s)).map(s=>s.name)),ae=b&&d.vectorIndexes.some(s=>X.has(s.table)),_=d.tables.some(s=>s.shardMode==="global"),Z=yr(X),ee=d.tables.some(s=>tr(s)),se=d.tables.some(s=>rr(s)),$=d.tables.some(s=>s.externalSource!==void 0),oe=d.tables.some(s=>s.memory===!0),te=d.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&ee)throw new pe("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const re=d.tables.length>0,at=Wr(d),st=Hr(d),ot=Yr(d),it=Kr(d),ie=Vr(d),de=wr(b,x.length>0,R.length>0,i,te);p&&de.push("WhereInput");const ce=vr(_),{customMutatorOverride:dt,shapeGuardImport:ct,shapeReadPolicyAssertion:lt,shapeReadPolicyImport:ut,shapeResolveOverride:ht}=Xr({hasMutators:G,hasSensitiveShapes:L,hasShapes:p,rlsData:ne}),D=v?O:[];for(const s of D)if(xr(s.exportName,"live stream export name"),!Ar.test(s.filePath))throw new pe("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe live stream file path: ${JSON.stringify(s.filePath)}`);const pt=u?[]:D.map(s=>`import { ${s.exportName} as liveStream_${s.exportName} } from "../${s.filePath}.js";`),mt=` protected override liveStreams() {
|
|
1376
|
+
return { ${D.map(s=>`${Or(s.id)}: liveStream_${s.exportName}`).join(", ")} };
|
|
1365
1377
|
}
|
|
1366
1378
|
`,ft=` private readonly liveStreamLoaders = new Map<string, () => Promise<{ validatePublish: (topic: string, payload: unknown) => unknown }>>([
|
|
1367
|
-
${
|
|
1379
|
+
${D.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}.js").then((module) => module.${s.exportName})],`).join(`
|
|
1368
1380
|
`)}
|
|
1369
1381
|
]);
|
|
1370
1382
|
|
|
@@ -1385,11 +1397,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1385
1397
|
protected override liveStreams() {
|
|
1386
1398
|
return Object.fromEntries(this.loadedLiveStreams);
|
|
1387
1399
|
}
|
|
1388
|
-
`;let le="";
|
|
1400
|
+
`;let le="";D.length>0&&(le=u?ft:mt);const M=[`import type { ${de.join(", ")} } from "${h.do}";`,`import { applyCdcChanges, createStableIdFactory, createStableRandomFactory, ${te?"backfillSearchIndexes, ":""}${b?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${ct}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${$?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ae?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${h.do}";`,...$?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${h.do}";`]:[],p?`import { asBucketStorage, ${ut}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${h.server}";`];re&&M.push(`import type { FacadeEntry } from "${h.server}";`,`import { bindOrm, defineLazyFacade } from "${h.server}";`),b&&M.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),M.push(...S.importLines,...N.importLines,...z.importLines,...J.importLines,...De,...Le,...ke,...Ae,...Y.importLines,...Me,...Ke,...P?[`import { sensitiveArgumentNames } from "${h.values}";`]:[],"",'import schema from "../schema.js";',...pt,`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...u?["getLoadedFunction","loadFunction"]:[],...G?["LUNORA_MUTATOR_PATHS"]:[],...E?["LUNORA_IP_READER_PATHS"]:[],...c?["LUNORA_ROOMS"]:[],...w?["LUNORA_SOCKETS"]:[],...p?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const gt=b?`
|
|
1389
1401
|
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",bt=se?`
|
|
1390
1402
|
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",yt=ee?`
|
|
1391
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",wt
|
|
1392
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",vt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",kt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",St="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Rt=
|
|
1403
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; userId?: string | undefined }) => DatabaseWriterLike | undefined;`:"",wt=$?`
|
|
1404
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",vt="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",kt="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",St="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Rt=_?q("globalDbStub: DatabaseWriterLike",vt,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:xt,vectorsBuild:At,vectorsStub:Ot}=tn(b,ae?d.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),Tt=`{
|
|
1393
1405
|
...this.ctxDbTuning(),
|
|
1394
1406
|
auth: {
|
|
1395
1407
|
get identity() {
|
|
@@ -1448,11 +1460,11 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1448
1460
|
scheduler,
|
|
1449
1461
|
schema: schema as unknown as SchemaLike,
|
|
1450
1462
|
sql: this.sql as SqlExec,
|
|
1451
|
-
storage,${
|
|
1463
|
+
storage,${_?`
|
|
1452
1464
|
globalDb,`:""}
|
|
1453
|
-
}`,
|
|
1454
|
-
vectors,`:"",
|
|
1455
|
-
orm: bindOrm(facade),`:"",ue=ee?"config.hyperdriveGlobal":"config.d1",It=
|
|
1465
|
+
}`,_t=b?`
|
|
1466
|
+
vectors,`:"",Dt=re?`
|
|
1467
|
+
orm: bindOrm(facade),`:"",ue=ee?"config.hyperdriveGlobal":"config.d1",It=_?` const bookmark = this.getInboundBookmark();
|
|
1456
1468
|
const globalRequest = {
|
|
1457
1469
|
...this.globalCdcOptions(config.cdc ?? false),
|
|
1458
1470
|
...(bookmark === undefined ? {} : { bookmark }),
|
|
@@ -1465,14 +1477,14 @@ ${_.map(s=>` [${JSON.stringify(s.id)}, () => import("../${s.filePath}
|
|
|
1465
1477
|
},
|
|
1466
1478
|
};
|
|
1467
1479
|
const globalDb: DatabaseWriterLike = ${ue}?.(env, globalRequest) ?? globalDbStub;
|
|
1468
|
-
`:"",Et=
|
|
1480
|
+
`:"",Et=Zr(p&&_,ue),Ct=c?` protected override roomHandlerPath(topic: string): string | undefined {
|
|
1469
1481
|
// Own properties only: a plain object would resolve \`toString\` and the like to inherited functions.
|
|
1470
1482
|
return Object.hasOwn(LUNORA_ROOMS, topic) ? LUNORA_ROOMS[topic] : undefined;
|
|
1471
1483
|
}
|
|
1472
1484
|
`:"",Lt=w?` protected override socketRoute(path: string): { auth: boolean; functionPath: string } | undefined {
|
|
1473
1485
|
return LUNORA_SOCKETS[path];
|
|
1474
1486
|
}
|
|
1475
|
-
`:"",{externalSourceOverride:Pt,sourceBootstrap:Nt,sourceClientCacheConst:$t}=
|
|
1487
|
+
`:"",{externalSourceOverride:Pt,sourceBootstrap:Nt,sourceClientCacheConst:$t}=en($),Mt=`
|
|
1476
1488
|
private shardInitDeferred = false;
|
|
1477
1489
|
private deferredShardInit?: Promise<void>;
|
|
1478
1490
|
|
|
@@ -1518,11 +1530,11 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1518
1530
|
|
|
1519
1531
|
await this.deferredShardInit;
|
|
1520
1532
|
}
|
|
1521
|
-
`,
|
|
1533
|
+
`,qt=ie.length>0?`
|
|
1522
1534
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1523
1535
|
void this.scheduleTtlSweep();
|
|
1524
1536
|
}
|
|
1525
|
-
`:"",
|
|
1537
|
+
`:"",Ut=`
|
|
1526
1538
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1527
1539
|
super(state, env, {
|
|
1528
1540
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1542,7 +1554,7 @@ ${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1542
1554
|
${E?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
1543
1555
|
this.ipKeyedFunctionPaths.add(path);
|
|
1544
1556
|
}
|
|
1545
|
-
`:""}${Nt}${
|
|
1557
|
+
`:""}${Nt}${qt} }
|
|
1546
1558
|
|
|
1547
1559
|
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1548
1560
|
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
@@ -1581,10 +1593,10 @@ ${E?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1581
1593
|
|
|
1582
1594
|
return this.holdShardWhileLoading(() => loadFunction(functionPath));
|
|
1583
1595
|
}
|
|
1584
|
-
`:"",
|
|
1596
|
+
`:"",Ft=he===""?`
|
|
1585
1597
|
|
|
1586
1598
|
`:`${he}
|
|
1587
|
-
`,Bt=
|
|
1599
|
+
`,Bt=P?`
|
|
1588
1600
|
protected override sensitiveArgNames(functionPath: string): ReadonlySet<string> {
|
|
1589
1601
|
const registered = LUNORA_FUNCTIONS[functionPath];${L?`
|
|
1590
1602
|
const shape = functionPath.startsWith("__shape__:") ? LUNORA_SHAPES[functionPath.slice("__shape__:".length)] : undefined;`:""}
|
|
@@ -1599,20 +1611,20 @@ ${E?` for (const path of LUNORA_IP_READER_PATHS) {
|
|
|
1599
1611
|
|
|
1600
1612
|
`:"",jt=Nr(u),Wt=u?` const preparation = this.prepareFunction(functionPath, "subscription");
|
|
1601
1613
|
if (preparation !== undefined) await preparation;
|
|
1602
|
-
`:"",Kt=
|
|
1614
|
+
`:"",Kt=jr(P).replace("__PREPARE_FUNCTION__",Wt),Ht=Ur(c,u,Fe),Vt=re?`
|
|
1603
1615
|
const facade = db as unknown as Record<string, FacadeEntry>;
|
|
1604
1616
|
${d.tables.map(s=>` defineLazyFacade(db, ${JSON.stringify(s.name)});`).join(`
|
|
1605
1617
|
`)}
|
|
1606
|
-
`:"",Gt=`${S.everyBuild}${
|
|
1618
|
+
`:"",Gt=`${S.everyBuild}${N.build}${J.build}
|
|
1607
1619
|
const secrets = createSecrets(env);
|
|
1608
|
-
`,Qt=`${S.everyFields}${
|
|
1620
|
+
`,Qt=`${S.everyFields}${N.contextField}${z.contextField}${J.contextField}
|
|
1609
1621
|
secrets,`,zt=z.build,Jt=v?`
|
|
1610
1622
|
const live = {
|
|
1611
1623
|
publish: async (ref: { __lunoraLive: string; topic: string }, payload: unknown, publishOptions?: { shardKey?: string }): Promise<void> => {
|
|
1612
1624
|
await this.publishLiveFromAction(ref.topic, payload, { ...publishOptions, stream: ref.__lunoraLive });
|
|
1613
1625
|
},
|
|
1614
1626
|
};
|
|
1615
|
-
`:"",Yt=[...S.actionFields,...T.length>0?["services"]:[],...v?["live"]:[]],Xt=`${S.actionBuild}${Y.build}${Jt}`;return`${Tr}${
|
|
1627
|
+
`:"",Yt=[...S.actionFields,...T.length>0?["services"]:[],...v?["live"]:[]],Xt=`${S.actionBuild}${Y.build}${Jt}`;return`${Tr}${M.join(`
|
|
1616
1628
|
`)}
|
|
1617
1629
|
|
|
1618
1630
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1675,7 +1687,7 @@ const LUNORA_STUDIO_FEATURES = ${m(Ye,"StudioFeaturesResult")};
|
|
|
1675
1687
|
|
|
1676
1688
|
/** How long a shard with a UNIQUE index blocked by duplicate rows serves the cached diagnostic before re-attempting the build. */
|
|
1677
1689
|
const BLOCKED_MIGRATION_RETRY_MS = 5000;
|
|
1678
|
-
${be}${Z.constant}${Q.constant}${Xe}${et}${rt}${Ie}${Pe}${Se}${Oe}${Y.specs}${
|
|
1690
|
+
${be}${Z.constant}${Q.constant}${Xe}${et}${rt}${Ie}${Pe}${Se}${Oe}${Y.specs}${Ue}
|
|
1679
1691
|
export interface ShardDOConfig {
|
|
1680
1692
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1681
1693
|
cdc?: boolean;
|
|
@@ -1692,7 +1704,7 @@ export interface ShardDOConfig {
|
|
|
1692
1704
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1693
1705
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1694
1706
|
/** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
|
|
1695
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${gt}${S.configFields}${
|
|
1707
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${gt}${S.configFields}${N.configField}${je}${bt}${yt}${wt}${Z.configField}
|
|
1696
1708
|
}
|
|
1697
1709
|
${q("schedulerStub",kt,["cancel","runAfter","runAt"])}${q("storageStub",St,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${Rt}${$t}${Ot}${S.stubs}${He}
|
|
1698
1710
|
// \`ctx.fetch\` is action-only. A query is re-run by every live subscription and a
|
|
@@ -1713,17 +1725,17 @@ ${jt}
|
|
|
1713
1725
|
* from the worker entry so wrangler binds it by name.
|
|
1714
1726
|
*/
|
|
1715
1727
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1716
|
-
class extends ShardDOBase {${
|
|
1728
|
+
class extends ShardDOBase {${Ut}
|
|
1717
1729
|
private blockedUniqueIndexes: readonly string[] = [];
|
|
1718
1730
|
private migrated = false;
|
|
1719
|
-
private migrationRetryAt = 0;${
|
|
1731
|
+
private migrationRetryAt = 0;${Ft}${Bt}${Ht}
|
|
1720
1732
|
${ce.override}
|
|
1721
1733
|
${Kt}
|
|
1722
1734
|
${dt}${ht}${Et}${Pt}
|
|
1723
1735
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1724
1736
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1725
1737
|
}
|
|
1726
|
-
${Ct}${Lt}${le}${Z.override}${
|
|
1738
|
+
${Ct}${Lt}${le}${Z.override}${Mt}
|
|
1727
1739
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1728
1740
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1729
1741
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1880,6 +1892,6 @@ ${te?`
|
|
|
1880
1892
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1881
1893
|
}
|
|
1882
1894
|
`:""}${xt}
|
|
1883
|
-
${Pr({hasSensitiveArgs:
|
|
1895
|
+
${Pr({hasSensitiveArgs:P,lazyFunctions:u,actionOnlyFields:Yt,agentsBuild:Ne,agentsContextField:$e,agentsSchedulerSource:qe,containersBuild:Te,containersContextField:_e,databaseOptions:Tt,everyContextBuild:Gt,everyContextField:Qt,facadeBlock:Vt,globalDatabaseLine:It,notifyBuild:zt,ormContextField:Dt,paymentsBuild:Be,paymentsContextField:We,queuesBuild:we,queuesContextField:ve,topicsBuild:Re,topicsContextField:xe,vectorsBuild:At,vectorsContextField:_t,workflowsBuild:Ee,workflowsContextField:Ce,actionOnlyBuild:Xt})}
|
|
1884
1896
|
};
|
|
1885
|
-
`};export{
|
|
1897
|
+
`};export{Kr as b,vn as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{r as $}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as S}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{a as l,G as f,I as w}from"./shared-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{r as $}from"./json-data-Chfs2Cz5.mjs";import{CAPABILITIES as S}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{a as l,G as f,I as w}from"./shared-Cn7dMQ_u.mjs";import{s as L}from"./platform-8oj7iXQy.mjs";const M=e=>e?{importFragment:"serveRelationFanout, ",override:`
|
|
2
2
|
protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
|
|
3
3
|
this.ensureServable();
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{v as _}from"./parse-validator-BisfC8bR.mjs";import{R as k}from"./reserved-words-CW1QFbTd.mjs";import{acceptsAbsentIr as I}from"./LUNORA_ERROR_CODES-
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{v as _}from"./parse-validator-BisfC8bR.mjs";import{R as k}from"./reserved-words-CW1QFbTd.mjs";import{acceptsAbsentIr as I}from"./LUNORA_ERROR_CODES-D7AVT7qF.mjs";import{n as E}from"./dispatch-namespace-DwTjD7BU.mjs";const R=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,O=e=>Object.keys(e).filter(n=>_(e[n])),B=e=>e.typeDerivedArgs===!0&&Object.keys(e.args).length>0||O(e.args).length>0,F=`// GENERATED by @lunora/codegen — do not edit.
|
|
2
2
|
// Run \`lunora codegen\` to regenerate.
|
|
3
3
|
|
|
4
4
|
`,G=(e=!1)=>e?{client:"lunorash/client",do:"lunorash/do",flags:"lunorash/flags",server:"lunorash/server",serverDataModel:"lunorash/server/data-model",serverDrizzle:"lunorash/server/drizzle",serverTypes:"lunorash/server/types",values:"lunorash/values"}:{client:"@lunora/client",do:"@lunora/do",flags:"@lunora/flags",server:"@lunora/server",serverDataModel:"@lunora/server/data-model",serverDrizzle:"@lunora/server/drizzle",serverTypes:"@lunora/server/types",values:"@lunora/values"},b=/^[A-Za-z_$][\w$]*$/u,U=/^[\w./-]+$/u,w=(e,n)=>{if(!b.test(e)||k.has(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},V=(e,n)=>{if(!b.test(e))throw new $("INTERNAL",`@lunora/codegen: ${n} is not a valid JS identifier: ${JSON.stringify(e)}`)},H=e=>e.charAt(0).toUpperCase()+e.slice(1),g=e=>b.test(e)?e:JSON.stringify(e),j=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:g(e),D=e=>{const n=new Map;for(const r of e){const t=n.get(r.filePath)??[];t.push(r),n.set(r.filePath,t)}return[...n.entries()].toSorted(([r],[t])=>r.localeCompare(t))},Y=(e,n,r)=>{const[t,l]=r==="type"?[g,";"]:[j,","],h={children:new Map};for(const[o,d]of D(e)){let a=h;for(const m of E(o)){let c=a.children.get(m);c===void 0&&(c={children:new Map},a.children.set(m,c)),a=c}a.file={entries:d,path:o}}const u=o=>o.file?.path??u(o.children.values().next().value),p=(o,d)=>{const a=" ".repeat(d),{entries:m=[],path:c=""}=o.file??{},y=m.find(s=>o.children.has(s.exportName));if(y!==void 0){const s=u(o.children.get(y.exportName));throw new $("NAMESPACE_COLLISION",`Namespace collision: the export "${y.exportName}" of "${c}" and "${s}" both resolve to api.${[...E(c),y.exportName].join(".")}. Rename the export or the folder.`)}const A=m.toSorted((s,f)=>s.exportName.localeCompare(f.exportName)).map(s=>`${a}${n(s)}`),S=[...o.children.entries()].toSorted(([s],[f])=>s.localeCompare(f)).map(([s,f])=>`${a}${t(s)}: {
|
package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-zNStZJ4K.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-ClgKgMYM.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
|
|
1
|
+
import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-B357_sbh.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as g,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as y}from"@lunora/platform";import{readProjectConfigLiterals as f}from"./loadProjectConfig-CtcJHHKS.mjs";const m="cloudflare",S=t=>{const{target:e}=f(t);return e!==void 0&&e.length>0?e:void 0},I=(t,e)=>e??S(t)??m,z=(t,e)=>{if(e!==void 0)return[];const{target:r,unreadable:a}=f(t);return a!==!0||r!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${m}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${m}" }\`), or pass \`--target\`.`,target:m}]},_={max:1536,min:32},E=(t,e)=>{if(t!=="cloudflare")return[];const{max:r,min:a}=_,i=`${String(a)}-${String(r)}`;return e.filter(({dimensions:o})=>o!==void 0&&(!Number.isInteger(o)||o<a||o>r)).map(({dimensions:o,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(o)} dimensions; Cloudflare Vectorize accepts ${i}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${i} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:y,cloudflare:b,node:g},O=(t,e)=>{const r=u[t];if(r===void 0)return!0;const a=r.features[e]?.level;return a==="native"||a==="emulated"},D=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),k={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","deliveryAuthorization","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","secretValues","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],h={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",deliveryAuthorization:"delivery authorization (`.deliveryAuthorization(...)` on the app builder)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",secretValues:"human-supplied secret values (`requestSecretTool`, held for one agent step)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},T=(t,e,r)=>({level:"error",message:`${e.name} does not support ${h[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:r}),x=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),P=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),W=t=>({level:"error",message:"This app declares defineWebSocket routes and enables delivery authorization. With delivery authorization on, the shard answers every route upgrade with 501, so the routes cannot be served.",name:"platform_socket_delivery_authorization",remediation:"Remove the defineWebSocket declarations, or remove the .deliveryAuthorization(...) call. Socket routes and delivery authorization cannot be combined.",target:t}),A=(t,e,r)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${h[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:r}),$=t=>{const{diagnostics:e,gatedSignals:r,matrix:a,reported:i,signals:o,target:s}=t;for(const n of w){if(o[n]!==!0)continue;const d=a.features[n]?.level;d!=="unsupported"&&d!==void 0||(r[n]=!1,!i.has(n)&&e.push(d==="unsupported"?T(n,a,s):A(n,a,s)))}},R=(t,e,r,a={})=>{const i={...t},o={...a},s=[],n=new Set;for(const[l,c]of Object.entries(k)){if(c===null||!t[l])continue;const v=e.features[c]?.level;v==="unsupported"?(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${c}" as native or emulated.`,target:r})):v===void 0&&(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${c}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:r}))}$({diagnostics:s,gatedSignals:o,matrix:e,reported:n,signals:a,target:r});const d=e.features.liveStreams?.level,p=d===void 0||d==="unsupported";return a.liveContext===!0&&p&&s.push(x(e,r)),{diagnostics:s,liveStreamsWithheld:p,signals:o,usage:i}},F=(t,e,r={})=>{const a=u[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...r},usage:{...t}}:R(t,a,e,r)},j=t=>{const e=u[t];if(e===void 0)return{supported:!0};const r=e.features.adminTokenRevocation?.level;return r!==void 0&&r!=="unsupported"?{supported:!0}:{diagnostic:{level:"warn",message:`${e.name} ${r===void 0?"does not declare a support level for":"does not support"} named admin tokens, so codegen omits the admin revocation store (\`_generated/adminRevocations.ts\` and the builder's \`.adminRevocations()\`). The root LUNORA_ADMIN_TOKEN is the only admin credential here.`,name:r===void 0?"platform_undeclared_feature":"platform_unsupported_feature",remediation:'Use the root admin token, or deploy to a target whose capability matrix marks "adminTokenRevocation" as native or emulated.',target:t},supported:!1}},N=t=>{const e=u[t];if(e===void 0)return;const r=Object.entries(e.features).filter(([,a])=>a.level==="unsupported").map(([a])=>a).toSorted((a,i)=>a.localeCompare(i));return{id:e.id,name:e.name,unsupported:r}};export{k as CAPABILITY_TO_FEATURE,m as DEFAULT_TARGET,j as gateAdminTokenRevocation,R as gateAgainstMatrix,F as gatePlatformFeatures,P as liveStreamsDeliveryAuthorizationDiagnostic,O as platformFeatureAvailable,D as platformMatrixIds,S as readProjectTarget,z as readTargetDiagnostics,I as resolveCodegenTarget,W as socketRoutesDeliveryAuthorizationDiagnostic,N as studioPlatformFor,E as vectorizeDimensionDiagnostics};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{w as a}from"./classify-procedure-call-BuF5PNwV.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as u,readFileSync as w}from"node:fs";import{join as d,isAbsolute as h,resolve as g}from"node:path";import{ts as E}from"ts-morph";import{companionDirectory as b,COMPANION_SERVICE_NAME as $,COMPANION_BINDING as p,companionName as S}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{readProjectStudioCompanion as y,readProjectConfigLiterals as C}from"./loadProjectConfig-CtcJHHKS.mjs";const v=/^[A-Za-z_$][\w$]*$/u,N=["wrangler.jsonc","wrangler.json"],I=i=>`SERVICE_${i.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,_=(i,e)=>{const r=N.map(n=>d(e,n)).find(n=>u(n));if(r===void 0){const n=u(d(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${i}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=E.parseConfigFileTextToJson(r,w(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${i}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},f=(i,e)=>{const r=i.route??e.route,o=i.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(i.workers_dev??e.workers_dev)!==!1},O=(i,e,r)=>{if(!v.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!v.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=h(r.dir)?r.dir:g(i,r.dir),{config:n,path:t}=_(e,o),{main:s,name:m}=n;if(typeof m!="string"||m==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no Worker "name"`);if(typeof s!="string"||s==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no "main" entry module`);const l=Object.entries(n.env??{}).map(([c,a])=>[c,a??{}]);return{binding:I(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(l.flatMap(([c,a])=>typeof a.name=="string"&&a.name!==""?[[c,a.name]]:[])),main:g(o,s),name:e,publicScopes:[...f(n,n)?[""]:[],...l.filter(([,c])=>f(c,n)).map(([c])=>c)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:m,wranglerPath:t}},j=i=>{const{services:e}=C(i);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>O(i,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const t=r.slice(o+1).find(s=>s.binding===n.binding);if(t!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${t.name}" both map to the binding ${n.binding} — rename one`)}return r},A=i=>{try{return{services:j(i)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}},B=(i,e="lunora")=>{if(!y(d(i,e)))return;const r=b(i,e);return{binding:p,envWorkers:{},main:d(r,"src","worker.ts"),name:$,publicScopes:[],worker:S(i),wranglerPath:d(r,"wrangler.jsonc")}},P=(i,e="lunora")=>{const{error:r,services:o}=A(i);try{const n=B(i,e);if(n===void 0)return{...r===void 0?{}:{error:r},services:o};const t=o.find(s=>s.worker===n.worker);return t!==void 0?{error:`lunora.config services.${t.name} deploys as "${t.worker}", the name the studio.companion Worker is given; rename that Worker or turn studio.companion off`,services:o}:{...r===void 0?{}:{error:r},services:[...o,n]}}catch(n){return{error:r??(n instanceof Error?n.message:String(n)),services:o}}},D=(i,e="lunora")=>{const r=P(i,e);return{...r,services:r.services.filter(o=>o.binding!==p||u(o.wranglerPath))}};export{B as companionServiceBinding,P as readBoundServiceBindings,D as readDevServiceBindings,A as readServiceBindings,j as resolveServiceBindings};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./declared-output-Iaar469J.mjs";import"./isTestPath-ClgKgMYM.mjs";import"./attribution-DjweYNgJ.mjs";import"./unwrap-handler-return-BpigsVD6.mjs";import"./ip-reads-WFubgB1G.mjs";import"./classify-procedure-call-BuF5PNwV.mjs";import{d as f}from"./index-fVYBrxkP.mjs";import"./dispatch-namespace-DwTjD7BU.mjs";export{f as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as o}from"./context-property-calls-BcUYQ6ph.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./isTestPath-ClgKgMYM.mjs";import"./attribution-DjweYNgJ.mjs";import"./database-calls-B_85LJIk.mjs";import"./classify-procedure-call-BuF5PNwV.mjs";import{d as a}from"./index-Dd6T5nSP.mjs";export{a as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as r}from"./context-property-calls-BcUYQ6ph.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as q}from"@lunora/errors";import{Node as a,SyntaxKind as J}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,descendantsOfKind as U}from"./isTestPath-ClgKgMYM.mjs";import{createRequire as W}from"node:module";import{join as N}from"node:path";import{fileURLToPath as K}from"node:url";import{createJiti as H}from"jiti";import{l as X,N as Z}from"./static-literal-BwDHHjEJ.mjs";import{r as G,p as Q}from"./parse-validator-BisfC8bR.mjs";import{R as Y}from"./reserved-words-CW1QFbTd.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const ee=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,te=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},ne=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),p=e=>{const t=e?._meta??{},n=e?.kind??"unknown",r={column:ne(t.column),kind:n,...t.sensitive===!0?{sensitive:!0}:{}};switch(n){case"array":case"optional":{r.inner=p(t.inner);break}case"from":break;case"id":{r.tableName=t.tableName;break}case"literal":{r.literalValue=te(t.value);break}case"object":{const i=t.shape??{};r.shape=Object.fromEntries(Object.entries(i).map(([o,l])=>[o,p(l)]));break}case"record":{r.valueType=p(t.valueValidator),t.keyValidator!==void 0&&(r.keyType=p(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(r.bucket=t.bucket);break}case"union":{const i=t.members??[];r.members=i.map(o=>p(o));break}}const s=t.constraints;return s!==void 0&&Object.keys(s).length>0&&(r.hasRefinement=!0,n==="string"&&typeof s.maxLength=="number"&&(r.stringMaxLength=s.maxLength)),r},re=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",se=e=>{const t=r=>typeof e[r]=="string"?e[r]:void 0,n=Array.isArray(e.columns)?e.columns.filter(r=>typeof r=="string"):void 0;return{binding:t("binding")??"",...n===void 0?{}:{columns:n},hasReconcile:e.reconcileEveryMs!==void 0,hasSoftDelete:e.softDeleteColumn!==void 0,hasTenantBy:e.tenantBy!==void 0,...t("idColumn")===void 0?{}:{idColumn:t("idColumn")},...t("mode")===void 0?{}:{mode:t("mode")},...t("query")===void 0?{}:{query:t("query")}}},ie=(e,t)=>{const n=e.shape??{},r=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}})),s=re(e.shardMode);return{...e.aggregateIndexes&&e.aggregateIndexes.length>0?{aggregateIndexed:!0}:{},...e.commitOrderedMode===!0?{commitOrdered:!0}:{},...e.isExternallyManaged?{externallyManaged:!0}:{},...e.externalSource?{externalSource:se(e.externalSource)}:{},...e.isPublic===!0?{isPublic:!0}:{},geoIndexes:(e.geoIndexes??[]).map(({field:i,name:o,precision:l})=>({field:i,name:o,...l===void 0?{}:{precision:l}})),...s==="global"?{globalBackend:e.shardMode?.backend==="hyperdrive"?"hyperdrive":"d1"}:{},indexes:r,...e.memoryMode===!0?{memory:!0}:{},name:t,rankIndexes:(e.rankIndexes??[]).map(({name:i,partitionBy:o,sortBy:l})=>({name:i,...o===void 0?{}:{partitionBy:o},sortBy:l.map(({direction:c,field:u})=>({direction:c,field:u}))})),relations:Object.entries(e.relationMap??{}).map(([i,o])=>o.through!==void 0?{kind:"many",name:i,table:o.table,through:{...o.through}}:{field:o.field,kind:o.kind,name:i,...o.onDelete===void 0?{}:{onDelete:o.onDelete},references:o.references,table:o.table}),searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,p(o)])),shardMode:s,...e.softDeleteMode?{softDelete:{field:e.softDeleteMode.field}}:{},...e.ttlPolicy?{ttl:{field:e.ttlPolicy.field,...e.ttlPolicy.after===void 0?{}:{after:e.ttlPolicy.after}}}:{},vectorIndexes:(e.vectorIndexes??[]).map(i=>({...i.dimensions===void 0?{}:{dimensions:i.dimensions},field:i.field,...i.metadata===void 0?{}:{metadata:i.metadata},...i.metric===void 0?{}:{metric:i.metric},name:i.name,table:t}))}},oe=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const r=Object.entries(n).map(([o,l])=>ie(l,o)),s=e.vectorIndexes??{},i=Object.entries(s??{}).map(([o,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:o,table:l.table??""}));return{bareTables:r,bareVectorIndexes:i,key:t}},ae=e=>{if(a.isIdentifier(e))return e.getText();if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t.getText():void 0}},le=e=>{const t=ae(e);if(t===void 0)return;const n=a.isPropertyAccessExpression(e)?e.getName():void 0,r=n===void 0?[]:[n];for(const s of e.getSourceFile().getImportDeclarations()){const i=s.getModuleSpecifierValue();for(const o of s.getNamedImports())if((o.getAliasNode()?.getText()??o.getName())===t)return{importedName:o.getName(),moduleSpecifier:i,propertyPath:r};if(s.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:i,propertyPath:r};if(s.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:i,propertyPath:[]}}},j=e=>a.isCallExpression(e)?e:a.isParenthesizedExpression(e)||a.isAsExpression(e)||a.isSatisfiesExpression(e)?j(e.getExpression()):void 0,ce=(e,t,n)=>{const r=n.getSymbol()?.compilerSymbol,s=i=>r!==void 0&&i?.getSymbol()?.compilerSymbol===r;return a.isPropertyAccessExpression(t)?s(e.getNamespaceImport())?t.getName():void 0:s(e.getDefaultImport())?"default":e.getNamedImports().find(i=>s(i.getAliasNode()??i.getNameNode()))?.getName()},de=e=>{if(!a.isPropertyAccessExpression(e)||!a.isIdentifier(e.getExpression()))return;const t=e.getExpression().getSymbol(),n=(t?.getAliasedSymbol()??t)?.getValueDeclaration(),r=a.isVariableDeclaration(n)?n.getInitializer():void 0,s=r===void 0?void 0:j(r),i=s?.getExpression(),o=i!==void 0&&a.isPropertyAccessExpression(i)?i.getExpression():i;if(s===void 0||i===void 0||o===void 0||!a.isIdentifier(o))return;const l=s.getArguments().map(u=>X(u)),c=s.getReturnType().getProperty(e.getName())?.getTypeAtLocation(s).getNonNullableType();if(!(l.includes(Z)||c?.getProperty("tables")===void 0))for(const u of s.getSourceFile().getImportDeclarations()){const h=u.getModuleSpecifierValue();if(h.startsWith("."))continue;const y=ce(u,i,o);if(y!==void 0)return{args:l,importedName:y,moduleSpecifier:h,propertyPath:[e.getName()]}}},$=(e,t)=>{let n=e;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},fe=(e,t)=>$(e[t.importedName],t.propertyPath),P=(e,t)=>{const n=H(N(t,"noop.js")).esmResolve(e);return W(N(t,"noop.cjs"))(n.startsWith("file:")?K(n):n)},ue=(e,t)=>{const n=le(e);if(n&&!n.moduleSpecifier.startsWith("."))return fe(P(n.moduleSpecifier,t),n);const r=de(e);if(!r)return;const s=P(r.moduleSpecifier,t)[r.importedName];return typeof s=="function"?$(s(...r.args),r.propertyPath):void 0},me=(e,t)=>{try{const n=ue(e,t);return typeof n!="object"||n===null?void 0:oe(n)}catch{return}},ge=new Set(["cosine","dot-product","euclidean"]),x=(e,t)=>{const n=m(e,t);if(n&&a.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=x(e,t);if(n&&a.isStringLiteral(n))return n.getLiteralText()},E=(e,t)=>{const n=x(e,t);if(n&&a.isNumericLiteral(n))return Number(n.getLiteralText())},D=(e,t)=>{const n=x(e,t);if(n&&(a.isTrueLiteral(n)||a.isFalseLiteral(n)))return n.getLiteralValue()},I=(e,t)=>{const n=x(e,t);if(n&&a.isArrayLiteralExpression(n))return n.getElements().filter(r=>a.isStringLiteral(r)).map(r=>r.getLiteralText())},z=e=>e&&ge.has(e)?e:void 0,S=e=>e&&a.isStringLiteral(e)?e.getLiteralText():"_unnamed_",pe=(e,t)=>{const n=I(e,t);return n!==void 0&&n.length>0?n:void 0},M=(e,t,n,r,s)=>{let i=e;for(;;){const o=i.getParent();if(!o||!a.isPropertyAccessExpression(o))break;const l=o.getParent();if(!l||!a.isCallExpression(l))break;if(o.getName()===t){const c=l.getArguments()[0];if(!c||!a.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${s})`);const u=c.getLiteralText();if(!r.has(u))throw d(c,`unknown ${n} ${JSON.stringify(u)} — expected ${s}`);return u}i=l}},he=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,be=/^(?:sqlite_|_cf_|__)/u,xe=/__(?:agg|rank|geo|fts)_/u,ye=e=>be.test(e)||xe.test(e),ve=new Set(["cascade","restrict","set null"]),Ee=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),R=/^[A-Za-z_$][\w$]*$/u,T=(e,t)=>{if(Ee.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(Y.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!R.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ye(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},Ie=e=>e&&ve.has(e)?e:void 0,Se=e=>{if(!a.isArrowFunction(e))return;let t=e.getBody();if(a.isParenthesizedExpression(t))t=t.getExpression();else if(a.isBlock(t)){const n=t.getStatements().find(r=>a.isReturnStatement(r));t=n&&a.isReturnStatement(n)?n.getExpression()??t:t}return a.isObjectLiteralExpression(t)?t:void 0},we=(e,t,n)=>{const r=a.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!a.isObjectLiteralExpression(r))throw d(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[s,i,o]=["table","from","to"].map(l=>f(r,l));if(s===void 0||i===void 0||o===void 0)throw d(r,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(i===o)throw d(r,`relation \`through\` has \`from\` and \`to\` both set to "${i}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:i,table:s,to:o}}},ke=(e,t,n,r)=>{const s=r&&a.isObjectLiteralExpression(r)?r:void 0,i=e==="many"?s?.getProperty("through"):void 0;return i?we(i,t,n):{field:(s&&f(s,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&s?Ie(f(s,"onDelete")):void 0,references:(s&&f(s,"references"))??"_id",table:n}},Te=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isPropertyAccessExpression(n))return;const r=n.getName();if(r!=="one"&&r!=="many")return;const[s,i]=t.getArguments();if(!s||!a.isStringLiteral(s))throw d(s??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${s?s.getText():"no argument"}.`);const o=s.getLiteralText();return ke(r,k(e),o,i)},Ae=e=>{const t=Se(e);if(!t)return[];const n=[];for(const r of t.getProperties()){const s=Te(r);s&&n.push(s)}return n},Oe=(e,t,n)=>{if(!t.includes("."))return;const[r="",...s]=t.split("."),i=`${r}${s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${i}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},Ne=e=>{if(!e||!a.isObjectLiteralExpression(e))return!1;const t=m(e,"unique");if(!t||!a.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!a.isTrueLiteral(n)&&!a.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return a.isTrueLiteral(n)},Pe=e=>{const[t,n,r]=e,s=Ne(r),i=S(t),o=n&&a.isArrayLiteralExpression(n)?n.getElements():[];for(const c of o)if(!a.isStringLiteral(c))throw d(c,`index "${i}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=o.filter(c=>a.isStringLiteral(c));for(const c of l)Oe(c,c.getLiteralText(),i);return{fields:l.map(c=>c.getLiteralText()),name:i,unique:s}},_e=e=>{const[t,n]=e;let r="_unknown_",s,i,o,l;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=I(n,"filterFields"),i=f(n,"language"),o=D(n,"staged"),l=f(n,"strategy")),{field:r,filterFields:s,language:i,name:S(t),staged:o,strategy:l}},Le=e=>{const[t,n]=e;let r="_unknown_",s;return n&&a.isObjectLiteralExpression(n)&&(r=f(n,"field")??r,s=E(n,"precision")),{field:r,name:S(t),precision:s}},je=e=>{const[t,n]=e,r=t&&a.isStringLiteral(t)?t.getLiteralText():"_unknown_";let s;return n&&a.isObjectLiteralExpression(n)&&(s=E(n,"after")),{after:s,field:r}},$e=e=>{if(!a.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},De=e=>{const[t,n]=e;let r=[],s;if(n&&a.isObjectLiteralExpression(n)){const i=m(n,"sortBy");if(i&&a.isPropertyAssignment(i)){const o=i.getInitializer();o&&a.isArrayLiteralExpression(o)&&(r=o.getElements().map(l=>$e(l)).filter(l=>l!==void 0))}s=I(n,"partitionBy")}return{name:S(t),partitionBy:s,sortBy:r}},ze=(e,t)=>{const[n,r]=e,s=n&&a.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!r||!a.isObjectLiteralExpression(r)))return{dimensions:E(r,"dimensions"),field:s,metadata:I(r,"metadata"),metric:z(f(r,"metric")),name:f(r,"index")??"_unnamed_",table:t}},Me=e=>{const t=e[0];return t&&a.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},_=(e,t)=>{if(e===void 0)return t;if(!a.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=m(e,"field");if(n===void 0)return t;const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(r&&a.isStringLiteral(r))return r.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Re=e=>{const t=e[0];return!t||!a.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:pe(t,"columns"),hasReconcile:m(t,"reconcileEveryMs")!==void 0,hasSoftDelete:m(t,"softDeleteColumn")!==void 0,hasTenantBy:m(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ce=(e,t,n,r)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(Le(n));break}case"global":{e.shardMode="global",e.globalBackend=Me(n);break}case"index":{e.indexes.unshift(Pe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(De(n));break}case"relations":{const s=n[0];s&&e.relations.push(...Ae(s));break}case"searchIndex":{e.searchIndexes.push(_e(n));break}case"shardBy":{const s=n[0];e.shardMode={field:s&&a.isStringLiteral(s)?s.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:_(n[0],"deletedAt")};break}case"source":{e.externalSource=Re(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(_(n[0],"updatedAt"));break}case"ttl":{e.ttl=je(n);break}case"vectorize":{const s=ze(n,r);s&&e.vectorIndexes.push(s);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Fe=(e,t,n)=>{const r=new Set(n.map(s=>s.name));for(const s of n)for(const i of L){const o=`${s.name}${i}`;if(!r.has(o))continue;const l=i==="__vocab"?`the \`fts5vocab\` companion for "${o}" is created \`IF NOT EXISTS\`, so it silently resolves to "${s.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${o}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${s.name}" and "${o}", whose generated FTS5 tables collide: "${s.name}" already owns "${t}__fts_${o}" as its "${i}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Be=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,he(t))},Ve=(e,t,n)=>{const{softDelete:r,timestampsFields:s}=n,i={};r&&!(r.field in t)&&(i[r.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[o]=s;if(o===void 0)return{...t,...i};if(s.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(o===r?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${o}"; give one of them another field.`);const l=t[o];if(l===void 0)i[o]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${o}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...i}},C=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let r={},s=e;for(;a.isCallExpression(s);){const i=s.getExpression(),o=s.getArguments();if(a.isPropertyAccessExpression(i))Ce(n,i.getName(),o,t),s=i.getExpression();else if(a.isIdentifier(i)&&i.getText()==="defineTable"){const l=o[0];if(l&&a.isObjectLiteralExpression(l))r=Q(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return r=Ve(e,r,n),Fe(e,t,n.searchIndexes),Be(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:r,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},F=(e,t=[],n=new Set,r=new Set)=>{r.add(e);for(const s of e.getProperties()){if(a.isSpreadAssignment(s)){const o=G(s.getExpression());o!==void 0&&!r.has(o)&&F(o,t,n,r);continue}if(!a.isPropertyAssignment(s))continue;const i=s.getInitializer();if(i){const o=k(s);if(T(o,s.getNameNode()),n.has(o))throw d(s.getNameNode(),`defineSchema({...}): table "${o}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(o),t.push(C(i,o))}}return t},qe=e=>{const t=m(e,"source");if(t&&a.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&a.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Je=e=>{if(!a.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!a.isCallExpression(t))return;const n=t.getExpression();if(!a.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const r=t.getArguments()[0];if(!r||!a.isObjectLiteralExpression(r))return;const s=e.getNameNode(),i=a.isStringLiteral(s)?s.getLiteralText():s.getText();return{dimensions:E(r,"dimensions"),metric:z(f(r,"metric")),name:i,table:qe(r)}},B=e=>{const t=[];for(const n of e.getProperties()){const r=Je(n);r&&t.push(r)}return t},A=(e,t)=>`${e}_${t}`,Ue=(e,t)=>{if(!R.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},b=(e,t,n)=>n.has(e)?A(t,e):e,v=(e,t)=>{const n=r=>r===void 0?void 0:v(r,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(r=>v(r,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([r,s])=>[r,v(s,t)]))}}},We=(e,t,n,r)=>{const s=A(t,e.name);return{...e,extensionKey:t,...r?{extensionFromPackage:!0}:{},name:s,shape:Object.fromEntries(Object.entries(e.shape).map(([i,o])=>[i,v(o,l=>b(l,t,n))])),relations:e.relations.map(i=>{const o=b(i.table,t,n);return i.through===void 0?{...i,table:o}:{...i,table:o,through:{...i.through,table:b(i.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:b(i.table,t,n)}))}},Ke=e=>{if(a.isVariableDeclaration(e)||a.isPropertyAssignment(e))return e.getInitializer();if(a.isShorthandPropertyAssignment(e))return e.getNameNode()},He=e=>{if(!a.isCallExpression(e))return!1;const t=e.getExpression();return a.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Xe=e=>{if(a.isIdentifier(e))return e;if(a.isPropertyAccessExpression(e)){const t=e.getExpression();return a.isIdentifier(t)?t:void 0}},Ze=e=>{if(a.isObjectLiteralExpression(e))return e;if(a.isCallExpression(e)){const t=e.getExpression();let n;if(a.isIdentifier(t)?n=t.getText():a.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const r=e.getArguments()[1];return r&&a.isObjectLiteralExpression(r)?r:void 0}}},Ge=(e,t)=>{const n=Ke(e);if(n){if(a.isPropertyAccessExpression(t)){const r=Ze(n);return r?x(r,t.getName()):void 0}return n}},Qe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,He(t))return t;const r=Xe(t),s=r&&a.isIdentifier(r)?r.getSymbol():void 0,o=(s?.getAliasedSymbol()?.getDeclarations()??s?.getDeclarations()??[])[0];if(!o)return;const l=o.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Ge(o,t)}},Ye=e=>{const[t,n]=e.getArguments();if(!(!t||!a.isStringLiteral(t))&&!(!n||!a.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},et=e=>{const t=m(e,"tables");if(!t||!a.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!a.isObjectLiteralExpression(n))return[];const r=[];for(const s of n.getProperties()){if(!a.isPropertyAssignment(s))continue;const i=s.getInitializer();if(!i)continue;const o=k(s);T(o,s.getNameNode()),r.push(C(i,o))}return r},tt=e=>{const t=m(e,"vectorIndexes");if(!t||!a.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!a.isObjectLiteralExpression(n)?[]:B(n)},V=(e,t,n,r,s)=>{Ue(e,r);const i=new Set(t.map(c=>c.name)),o=t.map(c=>We(c,e,i,s)),l=n.map(c=>({...c,name:A(e,c.name),table:b(c.table,e,i)}));return{tables:o,vectorIndexes:l}},nt=(e,t,n)=>V(e,et(n),tt(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),rt=(e,t)=>{const n=e.getArguments()[0];if(!n)return;let r=n;for(;a.isParenthesizedExpression(r)||a.isAsExpression(r)||a.isSatisfiesExpression(r);)r=r.getExpression();const s=Qe(r);if(!s){if(t!==void 0){const o=me(r,t);if(o){for(const l of o.bareTables)T(l.name,r);return V(o.key,o.bareTables,o.bareVectorIndexes,r,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${r.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types. If the receiver is a component built with options codegen cannot evaluate (a function, a variable), extend with the standalone extension the package exports instead (e.g. \`presenceExtension\`, \`actionCacheExtension\` or \`documentHistoryExtension\` from \`@lunora/server\`).`);return}const i=Ye(s);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return nt(i.key,i.keyNode,i.options)},st=e=>{const t=[];let n=e;for(;;){const r=n.getParent();if(!r||!a.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!a.isCallExpression(s))break;r.getName()==="extend"&&t.push(s),n=s}return t},it=(e,t,n)=>{const r=new Set(t.map(i=>i.name)),s=[];for(const i of st(e)){const o=rt(i,n);if(o){for(const l of o.tables){if(r.has(l.name))throw d(i,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);r.add(l.name),t.push(l)}s.push(...o.vectorIndexes)}}return s},ot=new Set(["eu","fedramp","us"]),at=e=>M(e,"jurisdiction","jurisdiction",ot,'"eu", "us", or "fedramp"'),lt=e=>{let t=e;for(;;){const n=t.getParent(),r=n?.getParent();if(!n||!a.isPropertyAccessExpression(n)||!r||!a.isCallExpression(r))return!1;if(n.getName()==="jurisdiction"){const s=r.getArguments()[1];return s!==void 0&&a.isObjectLiteralExpression(s)&&D(s,"pinAuth")===!0}t=r}},ct=new Set(["required"]),dt=e=>M(e,"rls","rls mode",ct,'"required"'),ft=e=>{if(!a.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const r=a.isPropertyAssignment(n)?n.getInitializer():void 0;if(!r||!a.isCallExpression(r))return;const s=r.getExpression(),i=r.getArguments()[1],o=i&&a.isObjectLiteralExpression(i)?f(i,"on"):void 0;if(!a.isIdentifier(s)||s.getText()!=="defineAggregateIndex"||o===void 0)return;t.add(o)}return t},ut=(e,t)=>{if(t===void 0)return;const n=ft(t);for(const r of e)(n===void 0||n.has(r.name))&&(r.aggregateIndexed=!0)},kt=(e,t,n)=>{const r=e.addSourceFileAtPath(t),s=U(r,J.CallExpression).find(g=>{const O=g.getExpression();return a.isIdentifier(O)&&O.getText()==="defineSchema"});if(!s)throw new q("INTERNAL",`defineSchema() not found in ${t}`);const i=s.getArguments()[0];if(!i||!a.isObjectLiteralExpression(i))throw d(s,"defineSchema() expects an object literal");const o=F(i),l=s.getArguments()[1],c=l&&a.isObjectLiteralExpression(l)?B(l):[],u=it(s,o,n);ut(o,s.getArguments()[2]);const h=[...o.flatMap(g=>g.vectorIndexes),...c,...u],y=new Set(o.filter(g=>g.shardMode==="global").map(g=>g.name)),w=h.find(g=>y.has(g.table));if(w)throw d(s,ee(w.table,w.name));return{jurisdiction:at(s),...lt(s)?{jurisdictionPinsAuth:!0}:{},rlsMode:dt(s),tables:o,vectorIndexes:h}};export{kt as default};
|