@lunora/codegen 1.0.0-alpha.241 → 1.0.0-alpha.243
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 +108 -58
- package/dist/index.d.ts +108 -58
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/AGENTS_FILENAME-Bb2jxbOa.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-CGB4bqUr.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-wK6-Tado.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-BzOl92QK.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DX6sZtLG.mjs +9 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-DNaUHGS8.mjs +1 -0
- package/dist/packem_shared/{discoverCrons-MfKw7IFf.mjs → discoverCrons-0lNudk0S.mjs} +1 -1
- package/dist/packem_shared/emitAgents-C3ygr0M8.mjs +1 -0
- package/dist/packem_shared/{emitApi-CJ9ziZnP.mjs → emitApi-DdW9RyGG.mjs} +22 -22
- package/dist/packem_shared/{emitApp-CgXCWBms.mjs → emitApp-D_9NVcvv.mjs} +2 -2
- package/dist/packem_shared/{emitCrons-BP2xBXDJ.mjs → emitCrons-BRKXFGFu.mjs} +11 -11
- package/dist/packem_shared/{emitFunctions-BqAz1ssY.mjs → emitFunctions-BgNeOZt_.mjs} +1 -1
- package/dist/packem_shared/{emitServer-BEo_fCY8.mjs → emitServer-pF_fhA82.mjs} +54 -52
- package/dist/packem_shared/emitShard-DID_s1FK.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/{shard-BaHiawkc.mjs → shard-BVzXMtWg.mjs} +67 -67
- package/dist/packem_shared/{shard-runtime-B5SUfdZB.mjs → shard-runtime-oIXHEMU7.mjs} +53 -44
- package/package.json +10 -10
- package/dist/packem_shared/AGENTS_FILENAME-DoPI92Wu.mjs +0 -1
- package/dist/packem_shared/CONTAINERS_FILENAME-B6TFs82W.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TARGET-DCpDuuUM.mjs +0 -1
- package/dist/packem_shared/QUEUES_FILENAME-CxkPcMH1.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CtkD-vQu.mjs +0 -9
- package/dist/packem_shared/WORKFLOWS_FILENAME-B_ZJxRSx.mjs +0 -1
- package/dist/packem_shared/emitAgents-CoNw0AKK.mjs +0 -1
- package/dist/packem_shared/emitShard-DFgzghbs.mjs +0 -1
- package/dist/packem_shared/ir-BgM8A3XV.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as Ut}from"@lunora/errors";import{serializeSchemaSnapshot as Wt,hashSchemaSnapshot as jt}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Ht,isD1GlobalTable as Vt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as Kt,i as Gt}from"./ir-DBSvhNa-.mjs";import{r as l}from"./json-data-Chfs2Cz5.mjs";import{r as F,e as Qt,a as zt,b as Xt,c as Jt,d as Yt,f as Zt,g as er,h as tr,i as rr,j as ar,k as nr,l as sr,m as or,n as ir,o as dr,p as cr,q as lr,s as hr,t as ur,u as pr,v as mr,w as gr,x as br,y as fr,z as wr}from"./shard-runtime-oIXHEMU7.mjs";import{u as te,i as yr,G as vr,d as kr}from"./shared-DjUziztz.mjs";const Sr=` /**
|
|
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
|
|
@@ -30,7 +30,7 @@ import{LunoraError as Pt}from"@lunora/errors";import{serializeSchemaSnapshot as
|
|
|
30
30
|
schema: schema as unknown as SchemaLike,
|
|
31
31
|
sql: this.sql as SqlExec,
|
|
32
32
|
});
|
|
33
|
-
}`,m=(a="")=>` const writer = this.adminWriter(${a});`,
|
|
33
|
+
}`,m=(a="")=>` const writer = this.adminWriter(${a});`,Rr=`${Sr}
|
|
34
34
|
|
|
35
35
|
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
36
36
|
this.ensureMigrated();
|
|
@@ -225,11 +225,11 @@ ${m()}
|
|
|
225
225
|
await applyCdcChanges(writer, args.changes);
|
|
226
226
|
|
|
227
227
|
return { applied: args.changes.length };
|
|
228
|
-
}`,
|
|
228
|
+
}`,xr=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:g,everyContextField:b,facadeBlock:c,globalDatabaseLine:h,notifyBuild:f,ormContextField:O,paymentsBuild:N,paymentsContextField:B,queuesBuild:U,queuesContextField:T,topicsBuild:E,topicsContextField:W,vectorsBuild:L,vectorsContextField:j,workflowsBuild:H,workflowsContextField:w})=>{const C=r.length>0,i=C?`
|
|
229
229
|
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
230
230
|
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
231
231
|
if (isAction) {
|
|
232
|
-
${a}${r.map(
|
|
232
|
+
${a}${r.map(v=>` ctx.${v} = ${v};`).join(`
|
|
233
233
|
`)}
|
|
234
234
|
}
|
|
235
235
|
`:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
|
|
@@ -253,7 +253,7 @@ ${a}${r.map(i=>` ctx.${i} = ${i};`).join(`
|
|
|
253
253
|
userId: this.getCurrentUserId(),
|
|
254
254
|
};
|
|
255
255
|
const { identity, ip, userId } = caller;
|
|
256
|
-
${
|
|
256
|
+
${L}${g}${t}${H}${U}${E}${e}
|
|
257
257
|
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
258
258
|
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
259
259
|
// admin/lifecycle path has no registered function, and so no kind. An
|
|
@@ -368,7 +368,7 @@ ${h} // \`ctx.db\`, wrapped in automatic instrumentation: by default
|
|
|
368
368
|
// handler making hundreds of queries stays readable. See
|
|
369
369
|
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
370
370
|
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
|
|
371
|
-
${c}${
|
|
371
|
+
${c}${N}
|
|
372
372
|
|
|
373
373
|
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
374
374
|
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
@@ -419,14 +419,14 @@ ${f}
|
|
|
419
419
|
// to the handler so code that signs its own URLs (a copy-in
|
|
420
420
|
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
421
421
|
// query and for a deferred dispatch, for the reasons given there.
|
|
422
|
-
origin: requestOrigin,${
|
|
422
|
+
origin: requestOrigin,${O}
|
|
423
423
|
scheduler,
|
|
424
424
|
span,
|
|
425
425
|
storage: contextStorage,
|
|
426
|
-
trace,${
|
|
426
|
+
trace,${j}${b}${B}${o}${w}${T}${W}${n}
|
|
427
427
|
};
|
|
428
428
|
${C?` const isAction = contextKind === "action";
|
|
429
|
-
`:""}${
|
|
429
|
+
`:""}${i}
|
|
430
430
|
const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
|
|
431
431
|
target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
|
|
432
432
|
// The composed mutation runs under the SAME wrapper the top-level RPC
|
|
@@ -477,7 +477,7 @@ ${C?` const isAction = contextKind === "action";
|
|
|
477
477
|
|
|
478
478
|
if (queryView === undefined) {
|
|
479
479
|
const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
|
|
480
|
-
${r.map(
|
|
480
|
+
${r.map(v=>` delete descriptors.${v};
|
|
481
481
|
`).join("")} // Writable and configurable, like the plain fields they replace.
|
|
482
482
|
const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
|
|
483
483
|
|
|
@@ -496,7 +496,7 @@ ${r.map(i=>` delete descriptors.${i};
|
|
|
496
496
|
installRun(ctx, contextKind);
|
|
497
497
|
|
|
498
498
|
return ctx;
|
|
499
|
-
}`},
|
|
499
|
+
}`},Ar=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
500
500
|
// referencing call fails loudly with a clear error instead of overflowing the
|
|
501
501
|
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
502
502
|
// single-threaded), so the counter reflects true nesting depth.
|
|
@@ -562,7 +562,7 @@ const dispatchRun = async (
|
|
|
562
562
|
} finally {
|
|
563
563
|
runDepth -= 1;
|
|
564
564
|
}
|
|
565
|
-
};`,
|
|
565
|
+
};`,Dr=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
|
|
566
566
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
567
567
|
|
|
568
568
|
// Internal functions are reachable server-side only: via \`ctx.run*\`
|
|
@@ -739,7 +739,7 @@ const dispatchRun = async (
|
|
|
739
739
|
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
740
740
|
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
741
741
|
return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
742
|
-
}`,
|
|
742
|
+
}`,Or=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
743
743
|
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
744
744
|
|
|
745
745
|
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
@@ -778,7 +778,7 @@ const dispatchRun = async (
|
|
|
778
778
|
// \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
|
|
779
779
|
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
|
|
780
780
|
};
|
|
781
|
-
}`,
|
|
781
|
+
}`,Tr=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=te(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},Er=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))te(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},Lr=a=>{const r={};for(const e of a.tables){const n=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];n.length>0&&(r[e.name]=n)}return r},Cr=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},Ir=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},_r=(a,r,e)=>{const n=te(r),t={name:a,optional:yr(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=Ir(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},$r=a=>{const r={};for(const e of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))n.push(_r(o,d,t));r[e.name]=n}return r},Mr=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
|
|
782
782
|
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
783
783
|
const shape = LUNORA_SHAPES[name];
|
|
784
784
|
|
|
@@ -849,7 +849,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
|
|
|
849
849
|
protected override isCustomMutator(functionPath: string): boolean {
|
|
850
850
|
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
851
851
|
}
|
|
852
|
-
`:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},
|
|
852
|
+
`:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},Pr=(a,r)=>a?`
|
|
853
853
|
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
854
854
|
const env = this.env as Record<string, unknown>;
|
|
855
855
|
// A shape read performs no writes, so the widened request only needs
|
|
@@ -908,7 +908,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
|
|
|
908
908
|
|
|
909
909
|
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
910
910
|
}
|
|
911
|
-
`:"",
|
|
911
|
+
`:"",qr=a=>({externalSourceOverride:a?`
|
|
912
912
|
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
913
913
|
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
914
914
|
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
@@ -1061,7 +1061,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as
|
|
|
1061
1061
|
`:"",sourceClientCacheConst:a?`
|
|
1062
1062
|
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1063
1063
|
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1064
|
-
`:""}),
|
|
1064
|
+
`:""}),Fr=(a,r)=>{const e=r.length>0,t=a?F("vectorsStub: VectorSearchLike",'throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
|
|
1065
1065
|
`:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",b=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(f=>JSON.stringify(f)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
|
|
1066
1066
|
const vectorSync = this.vectorSync(env);
|
|
1067
1067
|
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
@@ -1105,14 +1105,14 @@ ${o} const vectors = createContextVectors(lunora${b});
|
|
|
1105
1105
|
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1106
1106
|
});
|
|
1107
1107
|
}
|
|
1108
|
-
`:"",vectorsBuild:c,vectorsStub:t}},
|
|
1108
|
+
`:"",vectorsBuild:c,vectorsStub:t}},Xr=({advisories:a=[],advisorProcedures:r=[],agents:e=[],containers:n=[],env:t,flagKeys:o=[],hasAccessFacade:d=!1,hasAi:g=!1,hasAnalytics:b=!1,hasBrowser:c=!1,hasFlags:h=!1,hasHyperdrive:f=!1,hasImages:O=!1,hasKv:N=!1,hasNotify:B=!1,hasPayments:U=!1,hasPipelines:T=!1,hasR2sql:E=!1,hasVectors:W=!0,hasX402:L=!1,maskMetadata:j,mutators:H=[],queues:w=[],rlsMetadata:C,schema:i,schemaSnapshot:y,shapes:v=[],storageRules:he,studioFeatures:ue,topics:pe=[],useUmbrella:me=!1,workflows:V=[]})=>{const u=kr(me),re=H.length>0,k=v.length>0,ge=y===void 0?"":Wt(y),be=y===void 0?"":`
|
|
1109
1109
|
/** 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. */
|
|
1110
|
-
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(
|
|
1111
|
-
`,
|
|
1112
|
-
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",
|
|
1113
|
-
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1114
|
-
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",
|
|
1115
|
-
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",
|
|
1110
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(jt(y))}, json: ${JSON.stringify(ge)} };
|
|
1111
|
+
`,fe=y===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:we,configField:ye}=Qt(g),K=fr(d),S=zt(N),R=Xt(h,u.flags),G=Jt(o,h,u.flags),Q=wr(B),z=Yt(t),x=Zt(b),I=er(O),_=tr(f),$=rr(c),M=ar(E),P=nr(T),{build:ve,contextField:ke,importLines:Se,specs:Re}=sr(Kt(w)),{build:xe,contextField:Ae,importLines:De,specs:Oe}=or(pe,w),{build:Te,contextField:Ee,importLines:Le,specs:Ce}=ir(n,i.jurisdiction),{build:Ie,contextField:_e,importLines:$e,specs:Me}=dr(V),{build:Pe,contextField:qe,importLines:Fe,specs:Ne}=cr(e),{build:Be,configField:Ue,contextField:We,imports:je,stub:He}=lr(U),{build:Ve,configField:Ke,imports:Ge,stub:Qe}=hr(L),ze=a,Xe=r,ae=C??{policies:[],roles:[]},Je=j??{columns:[]},Ye=he??{rules:[]},Ze=ue??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:et,override:tt}=ur(V),{constant:rt,override:at}=pr(w),p=W&&i.vectorIndexes.length>0,X=new Set(i.tables.filter(s=>Gt(s)).map(s=>s.name)),ne=p&&i.vectorIndexes.some(s=>X.has(s.table)),A=i.tables.some(s=>s.shardMode==="global"),J=mr(X),Y=i.tables.some(s=>Ht(s)),se=i.tables.some(s=>Vt(s)),q=i.tables.some(s=>s.externalSource!==void 0),oe=i.tables.some(s=>s.memory===!0),Z=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(se&&Y)throw new Ut("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const ee=i.tables.length>0,nt=Tr(i),st=Lr(i),ot=$r(i),it=Er(i),ie=Cr(i),de=gr(p,V.length>0,w.length>0,h,Z);k&&de.push("WhereInput");const ce=br(A),{customMutatorOverride:dt,shapeGuardImport:ct,shapeReadPolicyAssertion:lt,shapeReadPolicyImport:ht,shapeResolveOverride:ut}=Mr({hasMutators:re,hasShapes:k,rlsData:ae}),D=[`import type { ${de.join(", ")} } from "${u.do}";`,`import { applyCdcChanges, ${Z?"backfillSearchIndexes, ":""}${p?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${oe?"clearMemoryTables, ":""}${ct}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${q?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${ce.importFragment}ShardDO as ShardDOBase } from "${u.do}";`,...q?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${u.do}";`]:[],k?`import { asBucketStorage, ${ht}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${u.server}";`];ee&&D.push(`import { bindOrm, bindTableFacade } from "${u.server}";`),p&&D.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),g&&D.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),D.push(...K.importLines,...S.importLines,...R.importLines,...Q.importLines,...z.importLines,...x.importLines,...I.importLines,..._.importLines,...$.importLines,...M.importLines,...P.importLines,...Le,...$e,...Se,...De,...Fe,...je,...Ge,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...re?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const pt=p?`
|
|
1112
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",mt=se?`
|
|
1113
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",gt=Y?`
|
|
1114
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",bt=q?`
|
|
1115
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",ft='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',wt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',yt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',vt=A?F("globalDbStub: DatabaseWriterLike",ft,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:kt,vectorsBuild:St,vectorsStub:Rt}=Fr(p,ne?i.vectorIndexes.filter(s=>X.has(s.table)).map(s=>s.name):[]),xt=`{
|
|
1116
1116
|
...this.ctxDbTuning(),
|
|
1117
1117
|
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1118
1118
|
broadcast: (delta) => {
|
|
@@ -1162,24 +1162,24 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
|
|
|
1162
1162
|
scheduler,
|
|
1163
1163
|
schema: schema as unknown as SchemaLike,
|
|
1164
1164
|
sql: this.sql as SqlExec,
|
|
1165
|
-
storage,${
|
|
1165
|
+
storage,${A?`
|
|
1166
1166
|
globalDb,`:""}
|
|
1167
|
-
}`,
|
|
1168
|
-
vectors,`:"",
|
|
1169
|
-
orm: bindOrm(facade),`:"",
|
|
1170
|
-
const globalDb: DatabaseWriterLike = ${
|
|
1171
|
-
`:"",
|
|
1167
|
+
}`,At=p?`
|
|
1168
|
+
vectors,`:"",Dt=ee?`
|
|
1169
|
+
orm: bindOrm(facade),`:"",le=Y?"config.hyperdriveGlobal":"config.d1",Ot=A?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
|
|
1170
|
+
const globalDb: DatabaseWriterLike = ${le}?.(env, globalRequest) ?? globalDbStub;
|
|
1171
|
+
`:"",Tt=Pr(k&&A,le),{externalSourceOverride:Et,sourceBootstrap:Lt,sourceClientCacheConst:Ct}=qr(q),It=`
|
|
1172
1172
|
protected override async runShardInit(): Promise<void> {
|
|
1173
1173
|
this.ensureMigrated();
|
|
1174
|
-
${
|
|
1174
|
+
${oe?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1175
1175
|
`:""}
|
|
1176
1176
|
await this.dispatchShardInit();
|
|
1177
1177
|
}
|
|
1178
|
-
`,
|
|
1178
|
+
`,_t=ie.length>0?`
|
|
1179
1179
|
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1180
1180
|
void this.scheduleTtlSweep();
|
|
1181
1181
|
}
|
|
1182
|
-
`:""
|
|
1182
|
+
`:"",$t=`
|
|
1183
1183
|
public constructor(state: ShardDOState, env: unknown) {
|
|
1184
1184
|
super(state, env, {
|
|
1185
1185
|
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
@@ -1192,7 +1192,7 @@ ${se?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
|
|
|
1192
1192
|
...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
|
|
1193
1193
|
...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
|
|
1194
1194
|
});
|
|
1195
|
-
${
|
|
1195
|
+
${Lt}${_t} }
|
|
1196
1196
|
|
|
1197
1197
|
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1198
1198
|
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
@@ -1216,14 +1216,14 @@ ${At}${Tt} }
|
|
|
1216
1216
|
protected override isPaidFunction(functionPath: string): boolean {
|
|
1217
1217
|
return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
|
|
1218
1218
|
}
|
|
1219
|
-
`,
|
|
1219
|
+
`,Mt=ee?`
|
|
1220
1220
|
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1221
1221
|
${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
|
|
1222
1222
|
`)}
|
|
1223
|
-
`:"",
|
|
1223
|
+
`:"",Pt=`${K.build}${S.build}${R.build}${x.build}${z.build}
|
|
1224
1224
|
const secrets = createSecrets(env);
|
|
1225
|
-
`,
|
|
1226
|
-
secrets,`,
|
|
1225
|
+
`,qt=`${K.contextField}${S.contextField}${R.contextField}${Q.contextField}${x.contextField}${z.contextField}
|
|
1226
|
+
secrets,`,Ft=Q.build,Nt=[...g?["ai"]:[],...O?["images"]:[],...f?["sql"]:[],...c?["browser"]:[],...E?["r2sql"]:[],...T?["pipelines"]:[],...L?["x402"]:[]],Bt=`${we}${I.build}${_.build}${$.build}${M.build}${P.build}${Ve}`;return`${vr}${D.join(`
|
|
1227
1227
|
`)}
|
|
1228
1228
|
|
|
1229
1229
|
type FunctionKind = "action" | "mutation" | "query";
|
|
@@ -1233,13 +1233,13 @@ interface FunctionReference {
|
|
|
1233
1233
|
}
|
|
1234
1234
|
|
|
1235
1235
|
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1236
|
-
const LUNORA_TABLE_REFS = ${l(
|
|
1236
|
+
const LUNORA_TABLE_REFS = ${l(nt,"Record<string, Record<string, string>>")};
|
|
1237
1237
|
|
|
1238
1238
|
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1239
|
-
const LUNORA_TABLE_INDEXES = ${l(
|
|
1239
|
+
const LUNORA_TABLE_INDEXES = ${l(st,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1240
1240
|
|
|
1241
1241
|
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1242
|
-
const LUNORA_TABLE_COLUMNS = ${l(
|
|
1242
|
+
const LUNORA_TABLE_COLUMNS = ${l(ot,`Record<
|
|
1243
1243
|
string,
|
|
1244
1244
|
Array<{
|
|
1245
1245
|
bucket?: string;
|
|
@@ -1256,29 +1256,29 @@ const LUNORA_TABLE_COLUMNS = ${l(tt,`Record<
|
|
|
1256
1256
|
>`)};
|
|
1257
1257
|
|
|
1258
1258
|
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1259
|
-
const LUNORA_STORAGE_COLUMNS = ${l(
|
|
1259
|
+
const LUNORA_STORAGE_COLUMNS = ${l(it,"Record<string, string[]>")};
|
|
1260
1260
|
|
|
1261
1261
|
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1262
|
-
const LUNORA_TTL_SWEEPS = ${l(
|
|
1262
|
+
const LUNORA_TTL_SWEEPS = ${l(ie,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1263
1263
|
|
|
1264
1264
|
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1265
|
-
const LUNORA_ADVISORIES = ${l(
|
|
1265
|
+
const LUNORA_ADVISORIES = ${l(ze,"AdvisoryFinding[]")};
|
|
1266
1266
|
|
|
1267
1267
|
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1268
|
-
const LUNORA_ADVISOR_PROCEDURES = ${l(
|
|
1268
|
+
const LUNORA_ADVISOR_PROCEDURES = ${l(Xe,"AdvisorProcedure[]")};
|
|
1269
1269
|
|
|
1270
1270
|
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1271
|
-
const LUNORA_RLS_METADATA = ${l(
|
|
1272
|
-
${
|
|
1271
|
+
const LUNORA_RLS_METADATA = ${l(ae,"RlsPoliciesResult")};
|
|
1272
|
+
${lt}
|
|
1273
1273
|
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1274
|
-
const LUNORA_MASK_METADATA = ${l(
|
|
1274
|
+
const LUNORA_MASK_METADATA = ${l(Je,"MaskPoliciesResult")};
|
|
1275
1275
|
|
|
1276
1276
|
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1277
|
-
const LUNORA_STORAGE_RULES = ${l(
|
|
1277
|
+
const LUNORA_STORAGE_RULES = ${l(Ye,"StorageRulesResult")};
|
|
1278
1278
|
|
|
1279
1279
|
/** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
|
|
1280
|
-
const LUNORA_STUDIO_FEATURES = ${l(
|
|
1281
|
-
${
|
|
1280
|
+
const LUNORA_STUDIO_FEATURES = ${l(Ze,"StudioFeaturesResult")};
|
|
1281
|
+
${be}${J.constant}${G.constant}${et}${rt}${Ce}${Me}${Re}${Oe}${Ne}
|
|
1282
1282
|
export interface ShardDOConfig {
|
|
1283
1283
|
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1284
1284
|
cdc?: boolean;
|
|
@@ -1293,27 +1293,27 @@ export interface ShardDOConfig {
|
|
|
1293
1293
|
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1294
1294
|
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1295
1295
|
/** \`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. */
|
|
1296
|
-
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${
|
|
1296
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${pt}${ye}${S.configField}${R.configField}${x.configField}${I.configField}${_.configField}${$.configField}${M.configField}${P.configField}${Ue}${Ke}${mt}${gt}${bt}${J.configField}
|
|
1297
1297
|
}
|
|
1298
|
-
${
|
|
1299
|
-
${
|
|
1298
|
+
${F("schedulerStub",wt,["cancel","runAfter","runAt"])}${F("storageStub",yt,["delete","download","getMetadata","getSignedUrl","getUrl","head","list","upload"],{sync:["getUrl"]})}${vt}${Ct}${Rt}${S.stub}${R.stub}${x.stub}${I.stub}${_.stub}${$.stub}${M.stub}${P.stub}${He}${Qe}
|
|
1299
|
+
${Ar}
|
|
1300
1300
|
|
|
1301
1301
|
/**
|
|
1302
1302
|
* Build the project's shard Durable Object. Export the result as \`ShardDO\`
|
|
1303
1303
|
* from the worker entry so wrangler binds it by name.
|
|
1304
1304
|
*/
|
|
1305
1305
|
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1306
|
-
class extends ShardDOBase {${
|
|
1306
|
+
class extends ShardDOBase {${$t}
|
|
1307
1307
|
private migrated = false;
|
|
1308
1308
|
|
|
1309
|
-
${
|
|
1310
|
-
${
|
|
1311
|
-
${
|
|
1312
|
-
${
|
|
1309
|
+
${Dr}
|
|
1310
|
+
${ce.override}
|
|
1311
|
+
${Or}
|
|
1312
|
+
${dt}${ut}${Tt}${Et}
|
|
1313
1313
|
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1314
1314
|
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1315
1315
|
}
|
|
1316
|
-
${
|
|
1316
|
+
${J.override}${It}
|
|
1317
1317
|
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1318
1318
|
// socket-terminated half of the same reactivity — and differs only in who
|
|
1319
1319
|
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
@@ -1401,7 +1401,7 @@ ${z.override}${Ot}
|
|
|
1401
1401
|
protected override studioFeatures(): StudioFeaturesResult {
|
|
1402
1402
|
return LUNORA_STUDIO_FEATURES;
|
|
1403
1403
|
}
|
|
1404
|
-
${
|
|
1404
|
+
${G.evaluateOverride}${G.subscriptionOverride}${tt}${at}
|
|
1405
1405
|
protected override advisories(): AdvisoryFinding[] {
|
|
1406
1406
|
return LUNORA_ADVISORIES;
|
|
1407
1407
|
}
|
|
@@ -1410,17 +1410,17 @@ ${V.evaluateOverride}${V.subscriptionOverride}${Xe}${Ye}
|
|
|
1410
1410
|
return LUNORA_ADVISOR_PROCEDURES;
|
|
1411
1411
|
}
|
|
1412
1412
|
|
|
1413
|
-
${
|
|
1413
|
+
${Rr}
|
|
1414
1414
|
|
|
1415
1415
|
protected override ensureMigrated(): void {
|
|
1416
1416
|
if (this.migrated) {
|
|
1417
1417
|
return;
|
|
1418
1418
|
}
|
|
1419
1419
|
|
|
1420
|
-
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${
|
|
1420
|
+
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${fe} });
|
|
1421
1421
|
this.migrated = true;
|
|
1422
1422
|
}
|
|
1423
|
-
${
|
|
1423
|
+
${Z?`
|
|
1424
1424
|
protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
|
|
1425
1425
|
// Migrations create the fts5 companions; without them every backfill
|
|
1426
1426
|
// statement would raise "no such table" on a shard that has never
|
|
@@ -1429,7 +1429,7 @@ ${J?`
|
|
|
1429
1429
|
|
|
1430
1430
|
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1431
1431
|
}
|
|
1432
|
-
`:""}${
|
|
1433
|
-
${
|
|
1432
|
+
`:""}${kt}
|
|
1433
|
+
${xr({actionOnlyFields:Nt,agentsBuild:Pe,agentsContextField:qe,containersBuild:Te,containersContextField:Ee,databaseOptions:xt,everyContextBuild:Pt,everyContextField:qt,facadeBlock:Mt,globalDatabaseLine:Ot,notifyBuild:Ft,ormContextField:Dt,paymentsBuild:Be,paymentsContextField:We,queuesBuild:ve,queuesContextField:ke,topicsBuild:xe,topicsContextField:Ae,vectorsBuild:St,vectorsContextField:At,workflowsBuild:Ie,workflowsContextField:_e,actionOnlyBuild:Bt})}
|
|
1434
1434
|
};
|
|
1435
|
-
`};export{
|
|
1435
|
+
`};export{Er as b,Xr as e};
|