@lunora/codegen 1.0.0-alpha.187 → 1.0.0-alpha.189

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 CHANGED
@@ -65,8 +65,21 @@ interface RelationSnapshot {
65
65
  kind: "many" | "one";
66
66
  table: string;
67
67
  }
68
+ /** A table's declarative `.ttl(field, { after })` auto-expiry policy. */
69
+ interface TtlSnapshot {
70
+ /** Millisecond offset added to `field` to derive the expiry; absent ⇒ `field` IS the absolute expiry (an offset of zero). */
71
+ after?: number;
72
+ /** The epoch-millisecond expiry column the DO alarm sweep reads. */
73
+ field: string;
74
+ }
68
75
  /** Structural snapshot of one table. */
69
76
  interface TableSnapshot {
77
+ /**
78
+ * `.commitOrdered()` — every row carries a `_commitSeq`. Always written by a
79
+ * current snapshot, so its absence dates the baseline rather than describing
80
+ * the table; see {@link recordsTableModifiers}.
81
+ */
82
+ commitOrdered?: boolean;
70
83
  /**
71
84
  * Field name → {@link FieldSnapshot}, keys sorted by UTF-16 code unit (see
72
85
  * `sortKeys` below). Declaration order was tried and abandoned: the snapshot
@@ -76,14 +89,27 @@ interface TableSnapshot {
76
89
  fields: Record<string, FieldSnapshot>;
77
90
  /** Index name → {@link IndexSnapshot}. */
78
91
  indexes: Record<string, IndexSnapshot>;
92
+ /**
93
+ * `.memory()` — the table is emptied on every Durable Object cold start.
94
+ * Always written by a current snapshot; see {@link recordsTableModifiers}.
95
+ */
96
+ memory?: boolean;
79
97
  /** Relation accessor name → {@link RelationSnapshot}. */
80
98
  relations: Record<string, RelationSnapshot>;
81
99
  /**
82
- * `"root"` (default single-DO), `"global"` (D1-replicated), or
83
- * `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
100
+ * `"root"` (default single-DO), `"global:<backend>"` (`d1` or `hyperdrive`),
101
+ * or `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
84
102
  * stays a plain JSON-stable value.
103
+ *
104
+ * The backend is part of the MODE, not a detail beside it: a `.global()`
105
+ * table lives in D1 and a `.global({ backend: "hyperdrive" })` one in a
106
+ * Postgres/MySQL database reached through Hyperdrive — two different physical
107
+ * stores, and switching between them moves no rows. A snapshot written before
108
+ * that was encoded says bare `"global"`; see {@link shardModeChange}.
85
109
  */
86
110
  shardMode: string;
111
+ /** `.ttl(...)`, or absent when the table declares none. Only meaningful once {@link recordsTableModifiers} holds. */
112
+ ttl?: TtlSnapshot;
87
113
  }
88
114
  /** A deterministic structural view of the whole schema at one point in time. */
89
115
  interface SchemaSnapshot {
@@ -156,7 +182,7 @@ interface DriftChange {
156
182
  /** The table this change belongs to. Always set when `scope` is `"table"`. */
157
183
  table?: string;
158
184
  /** A machine-readable change discriminator. */
159
- type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
185
+ type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedCommitOrdering" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedMemoryMode" | "changedShardMode" | "changedTtlPolicy" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
160
186
  }
161
187
  /** The result of diffing two snapshots: every classified change. */
162
188
  interface SchemaDrift {
package/dist/index.d.ts CHANGED
@@ -65,8 +65,21 @@ interface RelationSnapshot {
65
65
  kind: "many" | "one";
66
66
  table: string;
67
67
  }
68
+ /** A table's declarative `.ttl(field, { after })` auto-expiry policy. */
69
+ interface TtlSnapshot {
70
+ /** Millisecond offset added to `field` to derive the expiry; absent ⇒ `field` IS the absolute expiry (an offset of zero). */
71
+ after?: number;
72
+ /** The epoch-millisecond expiry column the DO alarm sweep reads. */
73
+ field: string;
74
+ }
68
75
  /** Structural snapshot of one table. */
69
76
  interface TableSnapshot {
77
+ /**
78
+ * `.commitOrdered()` — every row carries a `_commitSeq`. Always written by a
79
+ * current snapshot, so its absence dates the baseline rather than describing
80
+ * the table; see {@link recordsTableModifiers}.
81
+ */
82
+ commitOrdered?: boolean;
70
83
  /**
71
84
  * Field name → {@link FieldSnapshot}, keys sorted by UTF-16 code unit (see
72
85
  * `sortKeys` below). Declaration order was tried and abandoned: the snapshot
@@ -76,14 +89,27 @@ interface TableSnapshot {
76
89
  fields: Record<string, FieldSnapshot>;
77
90
  /** Index name → {@link IndexSnapshot}. */
78
91
  indexes: Record<string, IndexSnapshot>;
92
+ /**
93
+ * `.memory()` — the table is emptied on every Durable Object cold start.
94
+ * Always written by a current snapshot; see {@link recordsTableModifiers}.
95
+ */
96
+ memory?: boolean;
79
97
  /** Relation accessor name → {@link RelationSnapshot}. */
80
98
  relations: Record<string, RelationSnapshot>;
81
99
  /**
82
- * `"root"` (default single-DO), `"global"` (D1-replicated), or
83
- * `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
100
+ * `"root"` (default single-DO), `"global:<backend>"` (`d1` or `hyperdrive`),
101
+ * or `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
84
102
  * stays a plain JSON-stable value.
103
+ *
104
+ * The backend is part of the MODE, not a detail beside it: a `.global()`
105
+ * table lives in D1 and a `.global({ backend: "hyperdrive" })` one in a
106
+ * Postgres/MySQL database reached through Hyperdrive — two different physical
107
+ * stores, and switching between them moves no rows. A snapshot written before
108
+ * that was encoded says bare `"global"`; see {@link shardModeChange}.
85
109
  */
86
110
  shardMode: string;
111
+ /** `.ttl(...)`, or absent when the table declares none. Only meaningful once {@link recordsTableModifiers} holds. */
112
+ ttl?: TtlSnapshot;
87
113
  }
88
114
  /** A deterministic structural view of the whole schema at one point in time. */
89
115
  interface SchemaSnapshot {
@@ -156,7 +182,7 @@ interface DriftChange {
156
182
  /** The table this change belongs to. Always set when `scope` is `"table"`. */
157
183
  table?: string;
158
184
  /** A machine-readable change discriminator. */
159
- type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
185
+ type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedCommitOrdering" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedMemoryMode" | "changedShardMode" | "changedTtlPolicy" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
160
186
  }
161
187
  /** The result of diffing two snapshots: every classified change. */
162
188
  interface SchemaDrift {
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as W}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-wC8dZkgS.mjs";import{emitApp as We}from"./packem_shared/emitApp-BpcEHPGo.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-BaDsKuhs.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-BPs1hq5Q.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-DtzlGawL.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-ILNsdYyt.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-D_n90pDd.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as W}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-CKAvO86n.mjs";import{emitApp as We}from"./packem_shared/emitApp-C8lGewoh.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-BLfOB6n9.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-y4g2x3Rk.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-DtzlGawL.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BOlAD295.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-wC8dZkgS.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,p as emitCrons,c as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,C as emitScheduler,h as emitSeed,D as emitServer,f as emitShard,G as emitVectors,R as emitWorkflows,_ as emitWranglerCronTriggers};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-CKAvO86n.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,p as emitCrons,c as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,C as emitScheduler,h as emitSeed,D as emitServer,f as emitShard,G as emitVectors,R as emitWorkflows,_ as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{G as c}from"./emit-wC8dZkgS.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
1
+ import{G as c}from"./emit-CKAvO86n.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
2
2
  `,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
@@ -1,4 +1,4 @@
1
- import{existsSync as b,mkdirSync as Ps,readFileSync as _t,writeFileSync as Is,rmSync as ws}from"node:fs";import{join as E,dirname as se}from"node:path";import{performance as ye}from"node:perf_hooks";import{runAdvisor as Ts}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Cs}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{toAdvisorContext as Fs}from"./formatAdvisories-CkEu1eye.mjs";import{s as Os}from"./paths-C-9fwEgQ.mjs";import{C as ne,o as Kt,j as Rs,f as Ls,k as Ds,b as ks,c as Ms,m as _s,e as Ks,p as zs,d as $s,i as Us,l as qs,g as Bs,q as Vs,n as Ws,a as js,h as Hs}from"./emit-wC8dZkgS.mjs";import{isD1GlobalTable as zt,isHyperdriveGlobalTable as $t}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Gs}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as Ys}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Qs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as le}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ue}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Oe,objectLiteralFromCallbackBody as Ut,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as w,collectSecurityCallRows as Xs,limitNameOf as qt,isContextIdentifier as Pe,handlerOf as Zs,isDatabaseAccessor as D,readTargetOf as Bt,enclosingExportName as Js}from"./listLunoraSourceFiles-D4xthUf-.mjs";import en from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as tn}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as sn}from"./discoverSandboxUsage-DskdDbkM.mjs";import nn from"./discoverStorageRulesMetadata-xhxu-mkS.mjs";import{a as S,c as k,d as Vt,e as rn}from"./classify-procedure-call-C8jbo0IJ.mjs";import{discoverWorkflows as on}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as an,resolveCodegenTarget as cn,readTargetDiagnostics as ln}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as R,a as K,e as v,r as un,b as dn,s as de,c as fn,f as gn,d as pn}from"./queries-CPlxXagL.mjs";import{r as fe,s as mn}from"./parse-validator-tdRHHDzh.mjs";import hn from"./discoverAuthApiCalls-DoblmzUW.mjs";import lt from"./discoverFunctions-DB9G_XrW.mjs";import{i as xn,r as vn,e as En}from"./unwrap-handler-return-CmIWbykC.mjs";import ut from"./discoverHttpRoutes-S81Iv_iB.mjs";import Sn from"./discoverHyperdriveCalls-DgAYcZRD.mjs";import yn from"./discoverInserts-COk-Sm_n.mjs";import{m as Re,a as oe,s as Wt,d as An}from"./index-D_Z8rX-f.mjs";import{e as jt}from"./exported-procedure-chains-C9FHwphy.mjs";import Nn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as bn,isDefineMutatorCallee as Pn,discoverMutators as dt}from"./MUTATORS_FILENAME-CTHlZ1j6.mjs";import In from"./discoverNondeterministicCalls-DkVVHe3U.mjs";import{discoverNotifyConfig as wn,discoverNotifyCalls as Tn}from"./NOTIFY_FILENAME-CZh4jN4q.mjs";import Cn from"./discoverR2sqlCalls-6u0OKy2N.mjs";import Fn from"./discoverRlsProcedures-vJZq3yhb.mjs";import On from"./discoverRlsMetadata-CwWRPb8N.mjs";import Rn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as Ln,redact as Dn,isHeuristicSecretKind as kn,isSecretishName as Mn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as _n}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as Kn}from"./emitApp-BpcEHPGo.mjs";import{buildOpenApiDocument as zn,emitOpenApiModule as $n}from"./buildOpenApiDocument-BaDsKuhs.mjs";import{buildOpenRpcDocument as Un,emitOpenRpcModule as qn}from"./OPENRPC_VERSION-BPs1hq5Q.mjs";import{buildSchemaSnapshot as Bn}from"./SchemaSnapshotParseError-D_n90pDd.mjs";const ft=(e,t="api")=>{const s=new Map;for(const n of e){const o=Os(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Vn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>zt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>$t(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ne)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Wn=(e,t,s={})=>{if(t===void 0)return;const n=Vn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
1
+ import{existsSync as b,mkdirSync as Ps,readFileSync as _t,writeFileSync as Is,rmSync as ws}from"node:fs";import{join as E,dirname as se}from"node:path";import{performance as ye}from"node:perf_hooks";import{runAdvisor as Ts}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Cs}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Fs}from"./formatAdvisories-CkEu1eye.mjs";import{s as Os}from"./paths-C-9fwEgQ.mjs";import{C as ne,o as Kt,j as Rs,f as Ls,k as Ds,b as ks,c as Ms,m as _s,e as Ks,p as zs,d as $s,i as Us,l as qs,g as Bs,q as Vs,n as Ws,a as js,h as Hs}from"./emit-CKAvO86n.mjs";import{isD1GlobalTable as zt,isHyperdriveGlobalTable as $t}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Gs}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as Ys}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Qs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as le}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ue}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Oe,objectLiteralFromCallbackBody as Ut,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as w,collectSecurityCallRows as Xs,limitNameOf as qt,isContextIdentifier as Pe,handlerOf as Zs,isDatabaseAccessor as D,readTargetOf as Bt,enclosingExportName as Js}from"./listLunoraSourceFiles-D4xthUf-.mjs";import en from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as tn}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as sn}from"./discoverSandboxUsage-DskdDbkM.mjs";import nn from"./discoverStorageRulesMetadata-xhxu-mkS.mjs";import{a as S,c as k,d as Vt,e as rn}from"./classify-procedure-call-C8jbo0IJ.mjs";import{discoverWorkflows as on}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as an,resolveCodegenTarget as cn,readTargetDiagnostics as ln}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as R,a as K,e as v,r as un,b as dn,s as de,c as fn,f as gn,d as pn}from"./queries-CPlxXagL.mjs";import{r as fe,s as mn}from"./parse-validator-tdRHHDzh.mjs";import hn from"./discoverAuthApiCalls-DoblmzUW.mjs";import lt from"./discoverFunctions-DB9G_XrW.mjs";import{i as xn,r as vn,e as En}from"./unwrap-handler-return-CmIWbykC.mjs";import ut from"./discoverHttpRoutes-S81Iv_iB.mjs";import Sn from"./discoverHyperdriveCalls-DgAYcZRD.mjs";import yn from"./discoverInserts-COk-Sm_n.mjs";import{m as Re,a as oe,s as Wt,d as An}from"./index-D_Z8rX-f.mjs";import{e as jt}from"./exported-procedure-chains-C9FHwphy.mjs";import Nn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as bn,isDefineMutatorCallee as Pn,discoverMutators as dt}from"./MUTATORS_FILENAME-CTHlZ1j6.mjs";import In from"./discoverNondeterministicCalls-DkVVHe3U.mjs";import{discoverNotifyConfig as wn,discoverNotifyCalls as Tn}from"./NOTIFY_FILENAME-CZh4jN4q.mjs";import Cn from"./discoverR2sqlCalls-6u0OKy2N.mjs";import Fn from"./discoverRlsProcedures-vJZq3yhb.mjs";import On from"./discoverRlsMetadata-CwWRPb8N.mjs";import Rn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as Ln,redact as Dn,isHeuristicSecretKind as kn,isSecretishName as Mn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as _n}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as Kn}from"./emitApp-C8lGewoh.mjs";import{buildOpenApiDocument as zn,emitOpenApiModule as $n}from"./buildOpenApiDocument-BLfOB6n9.mjs";import{buildOpenRpcDocument as Un,emitOpenRpcModule as qn}from"./OPENRPC_VERSION-y4g2x3Rk.mjs";import{buildSchemaSnapshot as Bn}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft=(e,t="api")=>{const s=new Map;for(const n of e){const o=Os(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Vn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>zt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>$t(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ne)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Wn=(e,t,s={})=>{if(t===void 0)return;const n=Vn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
2
  `);throw new L("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${o}
4
4
 
@@ -0,0 +1,2 @@
1
+ const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
2
+ `,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};
@@ -0,0 +1,18 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as v,sortKeys as f,diffSchemaSnapshots as I,parseSnapshotJson as A}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{serializeSchemaSnapshot as K}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as L}from"./isD1GlobalTable-udvHAAzD.mjs";const O=e=>{const t=e.shardMode;return t==="global"?`global:${L(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},_=(e,t)=>{const n=JSON.stringify(e),s=JSON.stringify(t);return n===s?0:n<s?-1:1},l=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,s=n??e,r={kind:t?n?.kind??"unknown":e.kind,nullable:s.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:s.column?.unique===!0||e.column?.unique===!0,...j[s.kind]?.(s)};return(s.hasRefinement===!0||e.hasRefinement===!0)&&(r.refined=!0),r},N=e=>{const t={};for(const[n,s]of Object.entries(e))t[n]=l(s);return f(t)},j={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:N(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(_)}:{}},D=e=>{const t={};for(const[o,a]of Object.entries(e.shape))t[o]=l(a);const n={};for(const o of e.indexes)n[o.name]={fields:[...o.fields],unique:o.unique??!1};const s={};for(const o of e.relations)s[o.name]={field:o.field,kind:o.kind,table:o.table};const r={commitOrdered:e.commitOrdered===!0,fields:f(t),indexes:f(n),memory:e.memory===!0,relations:f(s),shardMode:O(e)};return e.ttl&&(r.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),r},C=(e,t)=>{const n={};for(const r of e.tables)n[r.name]=D(r);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:f(n),version:v}};class R extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const z=e=>{const t=A(e);if(t.status==="invalid")throw new R(t.error);return t.status==="ok"?t.snapshot:void 0},M={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",x=e=>{const t=e===void 0?void 0:M[e];if(e===void 0||t===void 0)return`${y}
2
+ ${k}
3
+ `;const n=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
4
+ ${n}
5
+ `},p=e=>e.map(t=>` - ${t.summary}`).join(`
6
+ `),w=e=>e.remediation==="backfill"&&e.table!==void 0,B=/^[A-Za-z_]\w*$/u,F=e=>` lunora migrate create backfill_${e} --table ${e}`,P=(e,t,n)=>{const s=[...new Set(e.filter(o=>w(o)).map(o=>o.table))],r=[];if(s.length>0){r.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const o=s.filter(a=>B.test(a));o.length>0&&r.push(`
7
+ Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
8
+ ${o.map(a=>F(a)).join(`
9
+ `)}
10
+
11
+ `)}return t.length>0&&r.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
12
+ `),r.push(x(n)),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,p(e),"",`To fix:
13
+ ${r.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
14
+ `)},J=e=>{const{allowDrift:t=!1,baseline:n,command:s,current:r,migrations:o}=e,a=I(n,r),u=a.changes.filter(i=>i.severity==="breaking"),b=r.migrationIds.filter(i=>!(n?.migrationIds??[]).includes(i)),m=o.filter(i=>b.includes(i.id)),c=(i,h)=>({blocked:i,changes:a.changes,newMigrationIds:b,reason:h}),T=new Set(m.filter(i=>i.table!=="").map(i=>i.table)),$=m.filter(i=>i.table==="").map(i=>i.id);if(a.changes.length===0||n===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
15
+ ${p(a.changes)}`);const g=u.filter(i=>!w(i)||!T.has(i.table));if(g.length===0){const i=new Set(u.map(d=>d.table)),h=m.filter(d=>i.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
16
+ ${p(u)}`)}const S=P(g,$,s);return t?c(!1,`${S}
17
+
18
+ (overridden by --allow-schema-drift)`):c(!0,S)};export{v as SCHEMA_SNAPSHOT_VERSION,R as SchemaSnapshotParseError,C as buildSchemaSnapshot,I as diffSchemaSnapshots,J as evaluateSchemaDrift,z as parseSchemaSnapshot,K as serializeSchemaSnapshot};
@@ -1,3 +1,3 @@
1
- import{G as S}from"./emit-wC8dZkgS.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
1
+ import{G as S}from"./emit-CKAvO86n.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
2
  `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -1,4 +1,4 @@
1
- import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
1
+ import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
2
2
  /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
3
3
  readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:{field:`
4
4
  /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
@@ -15,41 +15,41 @@ import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as
15
15
  /**
16
16
  * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
17
17
  */
18
- readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],In=mt,Cn=new Map(In.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),co=mt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),gt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Dn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ft=e=>e.column!==void 0,Ln=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
18
+ readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],In=mt,Cn=new Map(In.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),ca=mt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),gt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Dn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ft=e=>e.column!==void 0,Ln=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
19
19
  `;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
20
20
  `;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
21
21
  `;case"null":return`if (${t} !== null) return DEFER;
22
22
  `;default:return`if (typeof ${t} !== "string") return DEFER;
23
23
  `}},En=(e,t)=>e.stringMaxLength===void 0?"":`if (${t}.length > ${String(e.stringMaxLength)}) return DEFER;
24
24
  `,_n=(e,t)=>{const n=e.literalValue?.trim();if(!(n===void 0||!gt.test(n)))return{out:t,pre:`if (${t} !== ${n}) return DEFER;
25
- `}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Dn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Ln(e.kind,t)+En(e,t)};switch(e.kind){case"array":return Pn(e,t,n);case"literal":return _n(e,t);case"object":return Bn(e,t,n);default:return}}},Pn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const o=n.next(),a=`__arr${String(o)}`,i=`__i${String(o)}`,s=`__e${String(o)}`,c=Ge(r,s,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
26
- const ${a} = new Array(${t}.length);
25
+ `}},Ge=(e,t,n)=>{if(!ft(e)&&!(e.unmodelledRefinement||e.sourceText!==void 0)){if(Dn.has(e.kind))return e.kind==="any"?{out:t,pre:""}:{out:t,pre:Ln(e.kind,t)+En(e,t)};switch(e.kind){case"array":return Pn(e,t,n);case"literal":return _n(e,t);case"object":return Bn(e,t,n);default:return}}},Pn=(e,t,n)=>{const{inner:r}=e;if(!r)return;const a=n.next(),o=`__arr${String(a)}`,i=`__i${String(a)}`,s=`__e${String(a)}`,c=Ge(r,s,n);if(!c)return;const d=`if (!Array.isArray(${t})) return DEFER;
26
+ const ${o} = new Array(${t}.length);
27
27
  for (let ${i} = 0; ${i} < ${t}.length; ${i}++) {
28
28
  const ${s} = ${t}[${i}];
29
- ${c.pre}${a}[${i}] = ${c.out};
29
+ ${c.pre}${o}[${i}] = ${c.out};
30
30
  }
31
- `;return{out:a,pre:d}},Mn=(e,t,n,r)=>{const o=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ft(t))return;const{inner:i}=t;if(!i)return;const s=Ge(i,n,r);if(!s)return;const c=r.next(),d=`__has${String(c)}`,h=`__val${String(c)}`,g=`let ${d} = false;
31
+ `;return{out:o,pre:d}},Mn=(e,t,n,r)=>{const a=JSON.stringify(e);if(t.kind==="optional"){if(t.hasRefinement||t.sourceText!==void 0||ft(t))return;const{inner:i}=t;if(!i)return;const s=Ge(i,n,r);if(!s)return;const c=r.next(),d=`__has${String(c)}`,h=`__val${String(c)}`,g=`let ${d} = false;
32
32
  let ${h};
33
33
  if (${n} !== undefined) {
34
34
  ${s.pre}${h} = ${s.out};
35
35
  ${d} = true;
36
36
  }
37
- `;return{entry:`...(${d} ? { ${o}: ${h} } : {})`,pre:g}}const a=Ge(t,n,r);if(a)return{entry:`${o}: ${a.out}`,pre:a.pre}},Fn=new Set(Object.getOwnPropertyNames(Object.prototype)),bt=(e,t,n)=>{let r="";const o=[];for(const a of Object.keys(e)){const i=e[a];if(!i)return;const s=JSON.stringify(a);let c=`${t}[${s}]`;if(Fn.has(a)){const h=`__f${String(n.next())}`;r+=`const ${h} = Object.hasOwn(${t}, ${s}) ? ${t}[${s}] : undefined;
38
- `,c=h}const d=Mn(a,i,c,n);if(!d)return;r+=d.pre,o.push(d.entry)}return{entries:o.join(", "),pre:r}},yt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
39
- `},Bn=(e,t,n)=>{const r=e.shape??{},o=bt(r,t,n);if(!o)return;const a=n.next(),i=`__obj${String(a)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
40
- ${yt(t)}${o.pre}const ${i} = { ${o.entries} };
37
+ `;return{entry:`...(${d} ? { ${a}: ${h} } : {})`,pre:g}}const o=Ge(t,n,r);if(o)return{entry:`${a}: ${o.out}`,pre:o.pre}},Fn=new Set(Object.getOwnPropertyNames(Object.prototype)),bt=(e,t,n)=>{let r="";const a=[];for(const o of Object.keys(e)){const i=e[o];if(!i)return;const s=JSON.stringify(o);let c=`${t}[${s}]`;if(Fn.has(o)){const h=`__f${String(n.next())}`;r+=`const ${h} = Object.hasOwn(${t}, ${s}) ? ${t}[${s}] : undefined;
38
+ `,c=h}const d=Mn(o,i,c,n);if(!d)return;r+=d.pre,a.push(d.entry)}return{entries:a.join(", "),pre:r}},yt=e=>{const t=`Object.getPrototypeOf(${e})`;return`if (${t} !== Object.prototype && ${t} !== null) return DEFER;
39
+ `},Bn=(e,t,n)=>{const r=e.shape??{},a=bt(r,t,n);if(!a)return;const o=n.next(),i=`__obj${String(o)}`,s=`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) return DEFER;
40
+ ${yt(t)}${a.pre}const ${i} = { ${a.entries} };
41
41
  `;return{out:i,pre:s}},qn=e=>{let t=0;const r=bt(e,"source",{next:()=>(t+=1,t)});if(r)return`(source) => {
42
42
  if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
43
43
  ${yt("source")}${r.pre}return { ${r.entries} };
44
44
  }`},S=`// GENERATED by @lunora/codegen — do not edit.
45
45
  // Run \`lunora codegen\` to regenerate.
46
46
 
47
- `,ae=(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"},wt=/^[A-Za-z_$][\w$]*$/u,jn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Wn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Un=e=>{if(e===void 0)return"unknown";if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},T=e=>{const t=Wn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?T(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Un(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,o])=>kt(r,o)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?T(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?T(e.keyType):"string",r=e.valueType?T(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>T(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?T(t.inner):"unknown";return`${n}?: ${r}`}return On(t)?`${n}?: ${T(t)}`:`${n}: ${T(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Kn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,o])=>{const a=se(o),i=T(a),s=q(r);return xt(o)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
47
+ `,oe=(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"},wt=/^[A-Za-z_$][\w$]*$/u,jn=/^[\w./-]+$/u,f=(e,t)=>{if(!wt.test(e))throw new X("INTERNAL",`@lunora/codegen: ${t} is not a valid JS identifier: ${JSON.stringify(e)}`)},Ve=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>wt.test(e)?e:JSON.stringify(e),Y=e=>e==="__proto__"?`[${JSON.stringify(e)}]`:q(e),Wn={any:"unknown",bigint:"bigint",boolean:"boolean",bytes:"ArrayBuffer",date:"number",geoPoint:"{ lat: number; lng: number }",null:"null",number:"number",storage:"string",string:"string",timestamp:"number"},Un=e=>{if(e===void 0)return"unknown";if(!gt.test(e))throw new X("INTERNAL",`@lunora/codegen: v.literal() argument is not a parseable string/number/boolean/null literal: ${JSON.stringify(e)}`);return e},T=e=>{const t=Wn[e.kind];if(t!==void 0)return t;switch(e.kind){case"array":return`Array<${e.inner?T(e.inner):"unknown"}>`;case"from":return e.tsType??"unknown";case"id":{const n=e.tableName??"_unknown_";return f(n,"v.id() table name"),`Id<"${n}">`}case"literal":return Un(e.literalValue);case"object":return e.shape?`{ ${Object.entries(e.shape).map(([r,a])=>kt(r,a)).join("; ")} }`:"Record<string, unknown>";case"optional":return`${e.inner?T(e.inner):"unknown"} | undefined`;case"record":{const n=e.keyType?T(e.keyType):"string",r=e.valueType?T(e.valueType):"unknown";return`Record<${n}, ${r}>`}case"union":return e.members&&e.members.length>0?e.members.map(n=>T(n)).join(" | "):"never";default:return"unknown"}},kt=(e,t)=>{const n=q(e);if(t.kind==="optional"){const r=t.inner?T(t.inner):"unknown";return`${n}?: ${r}`}return On(t)?`${n}?: ${T(t)}`:`${n}: ${T(t)}`},xe=e=>{const t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>kt(n,r)).join("; ")} }`},xt=e=>e.kind==="optional"||!!e.column?.hasDefault,se=e=>e.kind==="optional"&&e.inner?e.inner:e,Kn=e=>{f(e.name,"table name");const t=Object.entries(e.shape).map(([r,a])=>{const o=se(a),i=T(o),s=q(r);return xt(a)?` ${s}?: ${i};`:` ${s}: ${i};`}).join(`
48
48
  `),n=t?`
49
49
  ${t}
50
50
  `:"";return`export interface Insert_${e.name} {
51
51
  _id?: Id<"${e.name}">;
52
- _creationTime?: number;${n}}`},Je="schema",uo=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const A=v.inner?T(v.inner):"unknown";return` ${$}?: ${A};`}return` ${$}: ${T(v)};`}).join(`
52
+ _creationTime?: number;${n}}`},Je="schema",da=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const A=v.inner?T(v.inner):"unknown";return` ${$}?: ${A};`}return` ${$}: ${T(v)};`}).join(`
53
53
  `),b=l?`
54
54
  ${l}
55
55
  `:"",R=u.commitOrdered===!0?`
@@ -57,8 +57,8 @@ ${l}
57
57
  _id: Id<"${u.name}">;
58
58
  _creationTime: number;${R}${b}}`}).join(`
59
59
 
60
- `),o=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
61
- `),a=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
60
+ `),a=e.tables.map(u=>` ${u.name}: Doc_${u.name};`).join(`
61
+ `),o=e.tables.map(u=>{const l=u.indexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
62
62
  `),i=e.tables.map(u=>{const l=u.searchIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
63
63
  `),s=e.tables.map(u=>{const l=u.rankIndexes.map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
64
64
  `),c=e.tables.map(u=>{const l=u.shardMode==="global"?"":(u.geoIndexes??[]).map(b=>JSON.stringify(b.name)).join(" | ");return` ${u.name}: ${l||"never"};`}).join(`
@@ -93,7 +93,7 @@ export type Id<TName extends string> = string & { readonly __table: TName };
93
93
  ${r}
94
94
 
95
95
  export interface DataModel {
96
- ${o}
96
+ ${a}
97
97
  }
98
98
 
99
99
  export type Doc<T extends keyof DataModel> = DataModel[T];
@@ -103,7 +103,7 @@ export type Doc<T extends keyof DataModel> = DataModel[T];
103
103
  * Used by \`TableReader.withIndex()\` to constrain callers to declared names.
104
104
  */
105
105
  export interface IndexNamesByTable {
106
- ${a}
106
+ ${o}
107
107
  }
108
108
 
109
109
  export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
@@ -161,9 +161,9 @@ export interface Relations {
161
161
  ${y}
162
162
  }
163
163
 
164
- `,Je)},Qn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Hn=e=>e.replaceAll(Qn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Gn=/^@types\//u,Jn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const o=n.slice(r+dt.length);return o===""||Gn.test(o)?t:`import("${o}")`}),zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Yn=/^(?:\.\.?\/)+/u,Xn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Zn=(e,t)=>e.replaceAll(zn,(n,r)=>{if(vt.test(r.replace(Yn,"")))return n;const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Xn(`${o}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Hn(Zn(Jn(e),t)),er=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],tr=new RegExp(String.raw`import\("@lunora/(?<pkg>${er.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),nr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(tr,(n,r,o)=>{const a=nr[r];return o&&a&&!a.has(o)?n:`import("lunorash/${r}${o??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:T(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const o=r.toSorted((a,i)=>a.exportName.localeCompare(i.exportName)).map(a=>{const i=L(xe(a.args),a.filePath),s=L($t(a),a.filePath);return` ${a.exportName}: FunctionReference<"${a.kind}", ${i}, ${s}>;`}).join(`
164
+ `,Je)},Qn=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,vt=/^(?:\.\.?\/)*_generated\//u,St=/\.[A-Za-z]\w*$/u,Hn=e=>e.replaceAll(Qn,(t,n)=>{const r=n.replace(vt,"./");return`import("${St.test(r)?r:`${r}.js`}")`}),Vn=/import\("(?<spec>[^"]+)"\)/gu,dt="node_modules/",Gn=/^@types\//u,Jn=e=>e.replaceAll(Vn,(t,n)=>{const r=n.lastIndexOf(dt);if(r===-1||r>0&&n[r-1]!=="/")return t;const a=n.slice(r+dt.length);return a===""||Gn.test(a)?t:`import("${a}")`}),zn=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,Yn=/^(?:\.\.?\/)+/u,Xn=e=>{const t=[];for(const n of e.split("/"))if(!(n===""||n===".")){if(n===".."&&t.length>0&&t.at(-1)!==".."){t.pop();continue}t.push(n)}return t.join("/")},Zn=(e,t)=>e.replaceAll(zn,(n,r)=>{if(vt.test(r.replace(Yn,"")))return n;const a=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=`../${Xn(`${a}/${r}`)}`;return`import("${St.test(i)?i:`${i}.js`}")`}),L=(e,t)=>Hn(Zn(Jn(e),t)),er=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],tr=new RegExp(String.raw`import\("@lunora/(?<pkg>${er.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),nr={flags:new Set(["/web"]),platform:new Set},Rt=(e,t)=>t?e.replaceAll(tr,(n,r,a)=>{const o=nr[r];return a&&o&&!o.has(a)?n:`import("lunorash/${r}${a??""}")`}):e,ze=e=>["Doc","Id"].filter(t=>new RegExp(String.raw`(?<![.$\w])${t}<`,"u").test(e)),$t=e=>e.output===void 0||e.output.kind==="any"||e.kind==="stream"?e.returnType:T(e.output),Ye=e=>{const t=new Map;for(const n of e){const r=t.get(n.filePath)??[];r.push(n),t.set(n.filePath,r)}return[...t.entries()].toSorted(([n],[r])=>n.localeCompare(r))},ut=e=>{const t=([n,r])=>{const a=r.toSorted((o,i)=>o.exportName.localeCompare(i.exportName)).map(o=>{const i=L(xe(o.args),o.filePath),s=L($t(o),o.filePath);return` ${o.exportName}: FunctionReference<"${o.kind}", ${i}, ${s}>;`}).join(`
165
165
  `);return` ${q(N(n))}: {
166
- ${o}
166
+ ${a}
167
167
  };`};return Ye(e).map(n=>t(n)).join(`
168
168
  `)},rr=(e,t)=>{if(e.length===0&&t.length===0)return{block:"",importLine:""};const n=[];let r="";if(e.length>0&&(r+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),r+=`
169
169
  /** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
@@ -173,31 +173,31 @@ export interface WorkflowReference<Params = Record<string, unknown>> {
173
173
  readonly binding: string;
174
174
  readonly name: string;
175
175
  }
176
- `,e.length>0){const o=[...e].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),a=o.map(s=>` ${s.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${s.exportName}>>;`).join(`
177
- `),i=o.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.exportName)} },`).join(`
176
+ `,e.length>0){const a=[...e].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${s.exportName}>>;`).join(`
177
+ `),i=a.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.exportName)} },`).join(`
178
178
  `);r+=`
179
179
  /** This project's durable workflows, addressable as typed references (e.g. \`crons.daily("digest", …, workflows.digestPipeline, params)\`). */
180
180
  export interface WorkflowsRef {
181
- ${a}
181
+ ${o}
182
182
  }
183
183
 
184
184
  export const workflows: WorkflowsRef = {
185
185
  ${i}
186
186
  };
187
187
  `,n.push(`import type * as lunoraWorkflowDefinitions from "../workflows.js";
188
- `)}if(t.length>0){const o=[...t].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),a=o.map(s=>` ${s.exportName}: WorkflowReference<AgentRunInput>;`).join(`
189
- `),i=o.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.name)} },`).join(`
188
+ `)}if(t.length>0){const a=[...t].toSorted((s,c)=>s.exportName.localeCompare(c.exportName)),o=a.map(s=>` ${s.exportName}: WorkflowReference<AgentRunInput>;`).join(`
189
+ `),i=a.map(s=>` ${Y(s.exportName)}: { isLunoraWorkflow: true, binding: ${JSON.stringify(s.bindingName)}, name: ${JSON.stringify(s.name)} },`).join(`
190
190
  `);r+=`
191
191
  /** This project's durable agents, addressable as typed references for \`cronJobs()\` — each fire starts a fresh agent run (e.g. \`crons.daily("sweep", …, agents.support, { input, threadKey })\`). */
192
192
  export interface AgentsRef {
193
- ${a}
193
+ ${o}
194
194
  }
195
195
 
196
196
  export const agents: AgentsRef = {
197
197
  ${i}
198
198
  };
199
199
  `,n.push(`import type { AgentRunInput } from "@lunora/agent";
200
- `)}return{block:r,importLine:n.join("")}},or=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),ar=()=>new Set(Object.entries(pt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),sr=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Tt(t),o=ar(),a=t.find(s=>N(s.filePath)==="agents"&&o.has(s.exportName));if(a)throw new X("INTERNAL",`@lunora/codegen: "agents:${a.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${a.exportName}" export in ${a.filePath}`);const i=or().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
200
+ `)}return{block:r,importLine:n.join("")}},ar=()=>Object.keys(pt().functions).toSorted((e,t)=>e.localeCompare(t)),Tt=e=>new Set(e.filter(t=>N(t.filePath)==="agents").map(t=>t.exportName)),or=()=>new Set(Object.entries(pt().functions).filter(([,e])=>e.visibility==="internal").map(([e])=>e)),sr=(e,t)=>{const n={importLine:"",lines:"",prelude:""};if(e.length===0)return n;const r=Tt(t),a=or(),o=t.find(s=>N(s.filePath)==="agents"&&a.has(s.exportName));if(o)throw new X("INTERNAL",`@lunora/codegen: "agents:${o.exportName}" is reserved for the durable agent loop's internal dispatch — rename the "${o.exportName}" export in ${o.filePath}`);const i=ar().filter(s=>!r.has(s));return i.length===0?n:{importLine:`import { agentComponent } from "@lunora/agent/component";
201
201
  `,lines:i.map(s=>` "agents:${s}": lunoraAgentRuntimeFunctions.${s} as unknown as RegisteredLunoraFunction,`).join(`
202
202
  `),prelude:`
203
203
  /**
@@ -207,11 +207,11 @@ ${i}
207
207
  */
208
208
  const lunoraAgentRuntimeFunctions = agentComponent().functions;
209
209
  `}},ir=(e,t)=>{if(!e)return{importLine:"",lines:"",prelude:""};const n=t.find(r=>N(r.filePath)==="sandbox"&&r.exportName==="invoke");if(n)throw new X("INTERNAL",`@lunora/codegen: "sandbox:invoke" is reserved for the batteries-included sandbox tool dispatcher (browserTool/containerTool) — rename the "invoke" export in ${n.filePath}`);return{importLine:`import { sandboxComponent } from "@lunora/agent/component";
210
- `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},lr=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const o of e)o.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${o.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(o=>!n.has(o.exportName))},cr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},dr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=L(d.chunkType??"unknown",d.filePath),g=L(xe(d.searchParams),d.filePath),y=L(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
210
+ `,lines:' "sandbox:invoke": lunoraSandbox.invoke as unknown as RegisteredLunoraFunction,',prelude:"\n/**\n * The `@lunora/agent` sandbox dispatcher — auto-registered because `lunora/`\n * imports a sandbox tool (`browserTool`/`containerTool`). The batteries-included\n * tools dispatch to this internal action, which runs on an action ctx carrying\n * `ctx.browser` + `ctx.containers` (the durable tool step itself has neither).\n */\nconst lunoraSandbox = sandboxComponent();\n"}},lr=(e,t)=>{if(e.length===0)return[];const n=Tt(t),r=[{args:{key:{kind:"string"},limit:{inner:{kind:"number"},kind:"optional"}},exportName:"agentMessages",filePath:"agents",kind:"query",returnType:"Record<string, unknown>[]"},{args:{decision:{kind:"union",members:[{kind:"literal",literalValue:'"approve"'},{kind:"literal",literalValue:'"reject"'}]},instanceId:{kind:"string"},note:{inner:{kind:"string"},kind:"optional"},threadKey:{kind:"string"},toolCallId:{kind:"string"}},exportName:"agentResolveApproval",filePath:"agents",kind:"mutation",returnType:"{ resolved: boolean }"},{args:{agent:{kind:"string"},input:{kind:"string"},threadKey:{kind:"string"},title:{inner:{kind:"string"},kind:"optional"}},exportName:"agentRun",filePath:"agents",kind:"mutation",returnType:"{ id: string; threadKey: string }"},{args:{key:{kind:"string"}},exportName:"agentState",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"},{args:{key:{kind:"string"}},exportName:"agentThread",filePath:"agents",kind:"query",returnType:"Record<string, unknown> | undefined"}];for(const a of e)a.voice&&r.push({args:{threadKey:{kind:"string"}},exportName:`${a.exportName}Voice`,filePath:"agents",kind:"stream",returnType:"Record<string, unknown>"});return r.filter(a=>!n.has(a.exportName))},cr=(e,t)=>{if(e.length===0)return[];const n=new Set(t.filter(r=>N(r.filePath)==="mutators").map(r=>r.exportName));return e.filter(r=>!n.has(r.exportName)).map(r=>({args:r.args,exportName:r.exportName,filePath:r.filePath,kind:"mutation",returnType:r.returnType}))},dr=e=>{const t=e.filter(i=>i.stream);if(t.length===0)return{block:"",body:""};const n=Ye(t),r=n.map(([i,s])=>{const c=s.map(d=>{const h=L(d.chunkType??"unknown",d.filePath),g=L(xe(d.searchParams),d.filePath),y=L(xe(d.params),d.filePath);return` ${q(d.exportName)}: HttpStreamRef<${h}, ${g}, ${y}>;`}).join(`
211
211
  `);return` ${q(N(i))}: {
212
212
  ${c}
213
213
  };`}).join(`
214
- `),o=n.map(([i,s])=>{const c=s.map(d=>` ${Y(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
214
+ `),a=n.map(([i,s])=>{const c=s.map(d=>` ${Y(d.exportName)}: { method: ${JSON.stringify(d.method)}, path: ${JSON.stringify(d.path)} },`).join(`
215
215
  `);return` ${Y(N(i))}: {
216
216
  ${c}
217
217
  },`}).join(`
@@ -222,9 +222,9 @@ ${r}
222
222
  }
223
223
 
224
224
  export const httpStreams: HttpStreamsRef = {
225
- ${o}
225
+ ${a}
226
226
  };
227
- `,body:r}},ho=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:o=[],useUmbrella:a=!1,workflows:i=[]}=e,s=ae(a),c=[...n.filter(O=>O.visibility!=="internal"),...lr(t,n),...cr(o,n)],d=n.filter(O=>O.visibility==="internal"),h=ut(c),g=ut(d),y=dr(r),u=`${h}
227
+ `,body:r}},ua=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=oe(o),c=[...n.filter(O=>O.visibility!=="internal"),...lr(t,n),...cr(a,n)],d=n.filter(O=>O.visibility==="internal"),h=ut(c),g=ut(d),y=dr(r),u=`${h}
228
228
  ${g}
229
229
  ${y.body}`,l=ze(u),b=l.length>0?`
230
230
  import type { ${l.join(", ")} } from "./dataModel.js";
@@ -243,7 +243,7 @@ export const internal = anyApi as unknown as InternalApiTypes;
243
243
  ${v.block}${y.block}`,A=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=A.length>0?`import type { ${A.join(", ")} } from "${s.client}";
244
244
  `:"";return Rt(`${S}import { anyApi } from "${s.client}";
245
245
  ${H}${v.importLine}${b}
246
- ${$}`,a)},po=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
246
+ ${$}`,o)},ha=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
247
247
  import type { SeedClient, SeedClientOptions } from "@lunora/seed";
248
248
 
249
249
  import schema from "../schema.js";
@@ -260,7 +260,7 @@ import type { InsertModel } from "./dataModel.js";
260
260
  * const { posts } = await seed.posts((x) => x([10, 20]));
261
261
  */
262
262
  export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
263
- `:"",mo=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=ae(n),o=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,a=e.map(c=>{f(c.exportName,"shape export name");const d=o(c),h=L(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,u=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
263
+ `:"",pa=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),a=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,o=e.map(c=>{f(c.exportName,"shape export name");const d=a(c),h=L(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,u=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
264
264
  export interface ${Ve(l)} {
265
265
  ${y}
266
266
  /**
@@ -306,14 +306,14 @@ export const ${c.exportName}Collection = (
306
306
  return { checkpoints, collection: createCollection(config), scope };
307
307
  };`}).join(`
308
308
 
309
- `),i=ze(a),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
309
+ `),i=ze(o),s=i.length>0?`import type { ${i.join(", ")} } from "./dataModel.js";
310
310
  `:"";return`${S}import type { LunoraClient, SubscriptionError } from "${r.client}";
311
311
  import { lunoraCollectionOptions } from "@lunora/db/collections";
312
312
  import type { CheckpointRegistry, LunoraCollectionOptions, Row } from "@lunora/db";
313
313
  import type { Collection } from "@tanstack/db";
314
314
  import { createCollection } from "@tanstack/db";
315
315
  ${s}
316
- ${a}
316
+ ${o}
317
317
  `},ur=(e,t)=>`lunora_${N(e)}_${String(t)}`,hr=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
318
318
  const registered = LUNORA_FUNCTIONS[functionPath];
319
319
 
@@ -343,13 +343,13 @@ ${a}
343
343
  }
344
344
 
345
345
  return (await registered.handler(context, args ?? {})) as R;
346
- };`,pr=(e,t,n=[],r=[])=>{const o=new Map,a=l=>{o.has(l)||o.set(l,ur(l,o.size))};for(const l of e)a(l.filePath);for(const l of t)a(l.filePath);for(const l of n)a(l.filePath);for(const l of r)a(l.filePath);const i=[...o.entries()].map(([l,b])=>{if(!jn.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
347
- `),s=e.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
348
- `),c=t.map(l=>` ${JSON.stringify(l.id)}: ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
349
- `),d=n.map(l=>` "${N(l.filePath)}:${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
350
- `),h=r.map(l=>` "${l.exportName}": ${o.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
346
+ };`,pr=(e,t,n=[],r=[])=>{const a=new Map,o=l=>{a.has(l)||a.set(l,ur(l,a.size))};for(const l of e)o(l.filePath);for(const l of t)o(l.filePath);for(const l of n)o(l.filePath);for(const l of r)o(l.filePath);const i=[...a.entries()].map(([l,b])=>{if(!jn.test(l))throw new X("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(l)}`);return`import * as ${b} from "../${l}.js";`}).join(`
347
+ `),s=e.map(l=>` "${N(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
348
+ `),c=t.map(l=>` ${JSON.stringify(l.id)}: ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredDataMigration,`).join(`
349
+ `),d=n.map(l=>` "${N(l.filePath)}:${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredLunoraFunction,`).join(`
350
+ `),h=r.map(l=>` "${l.exportName}": ${a.get(l.filePath)??""}.${l.exportName} as unknown as RegisteredShape,`).join(`
351
351
  `),g=n.map(l=>`${N(l.filePath)}:${l.exportName}`),y=[s,d].filter(l=>l.length>0).join(`
352
- `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=qn(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${o.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
352
+ `),u=e.map(l=>{if(l.lifecycle||Object.keys(l.args).length===0)return;const b=qn(l.args);return b===void 0?void 0:`installCompiledValidatorMap(${a.get(l.filePath)??""}.${l.exportName}.args, ${b});`}).filter(l=>l!==void 0).join(`
353
353
  `);return{dispatchBody:y.length>0?`
354
354
  ${y}
355
355
  `:"",importBlock:i.length>0?`${i}
@@ -358,16 +358,16 @@ ${y}
358
358
  ${c}
359
359
  `:"",mutatorPaths:g,shapeBody:h.length>0?`
360
360
  ${h}
361
- `:""}},mr=e=>{const t=Ye(e),n=t.map(([o,a])=>{const i=a.map(s=>{const c=L(xe(s.args),s.filePath),d=c==="{}"?"?":"",h=L($t(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
362
- `);return` ${q(N(o))}: {
361
+ `:""}},mr=e=>{const t=Ye(e),n=t.map(([a,o])=>{const i=o.map(s=>{const c=L(xe(s.args),s.filePath),d=c==="{}"?"?":"",h=L($t(s),s.filePath);return s.kind==="stream"?` ${s.exportName}: (args${d}: ${c}) => Promise<AsyncIterable<${h}>>;`:` ${s.exportName}: (args${d}: ${c}) => Promise<${h}>;`}).join(`
362
+ `);return` ${q(N(a))}: {
363
363
  ${i}
364
364
  };`}).join(`
365
- `);return{implementation:t.map(([o,a])=>{const i=N(o),s=a.map(c=>` ${Y(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
365
+ `);return{implementation:t.map(([a,o])=>{const i=N(a),s=o.map(c=>` ${Y(c.exportName)}: (args) => callRegistered(context, "${i}:${c.exportName}", args),`).join(`
366
366
  `);return` ${Y(i)}: {
367
367
  ${s}
368
368
  },`}).join(`
369
- `),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const o of Object.values(r.shape)){const a=se(o);a.kind==="storage"&&typeof a.bucket=="string"&&a.bucket!==""&&n.add(a.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,o)=>r.localeCompare(o))]},go=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:o=!1,hasAnalytics:a=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:A=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=ae(H),w=gr($??{tables:[]},A).map(p=>JSON.stringify(p)).join(" | "),P=o?`import type { LunoraAi } from "@lunora/ai";
370
- `:"",M=o?`
369
+ `),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ma=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:A=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),w=gr($??{tables:[]},A).map(p=>JSON.stringify(p)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
370
+ `:"",M=a?`
371
371
  readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
372
372
  `:"",le=u?`
373
373
  readonly payments: LunoraPayment;`:"",Z=R?`import type { X402Pay } from "@lunora/x402/pay";
@@ -376,7 +376,7 @@ ${s}
376
376
  `:"",ee=t.length>0?`
377
377
  readonly containers: {${t.map(p=>`
378
378
  readonly ${p.exportName}: ContainerAccessor;`).join("")}
379
- };`:"",k=[...o?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(p=>(f(p.bindingName,`container binding "${p.bindingName}"`),` /** Durable Object namespace for the \`${p.exportName}\` container. */
379
+ };`:"",k=[...a?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...t.map(p=>(f(p.bindingName,`container binding "${p.bindingName}"`),` /** Durable Object namespace for the \`${p.exportName}\` container. */
380
380
  readonly ${p.bindingName}?: unknown;`)),...O.map(p=>(f(p.bindingName,`workflow binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` workflow. */
381
381
  readonly ${p.bindingName}?: unknown;`)),...v.map(p=>(f(p.bindingName,`queue binding "${p.bindingName}"`),` /** Queue producer binding for the \`${p.exportName}\` queue. */
382
382
  readonly ${p.bindingName}?: unknown;`)),...e.map(p=>(f(p.bindingName,`agent binding "${p.bindingName}"`),` /** Workflow binding for the \`${p.exportName}\` agent. */
@@ -399,7 +399,7 @@ ${k}`:""}
399
399
  }
400
400
 
401
401
  /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
402
- export type Env = CloudflareBindings;`,F=(p,We,Te)=>{const re=Cn.get(p);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${p}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",a,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",h,"action"),ue=F("pipelines",l,"action"),G=F("r2sql",b,"action"),_=s&&($?.vectorIndexes.length??0)>0,J=_?' | "vectors"':"",te=_?`
402
+ export type Env = CloudflareBindings;`,F=(p,We,Te)=>{const re=Cn.get(p);if(re!==void 0&&re.tier!==Te)throw new X("INTERNAL",`@lunora/codegen: capability "${p}" declares tier "${re.tier}" in SERVER_CTX_FIELDS but is emitted onto the "${Te}" context — update whichever is wrong.`);return We?re?.field??"":""},ce=F("kv",g,"every"),de=F("analytics",o,"every"),Oe=F("hyperdrive",d,"action"),Ie=F("browser",i,"action"),Ce=F("images",h,"action"),ue=F("pipelines",l,"action"),G=F("r2sql",b,"action"),_=s&&($?.vectorIndexes.length??0)>0,J=_?' | "vectors"':"",te=_?`
403
403
  readonly vectors: VectorSearch<VectorIndexName>;`:"",he=_?`
404
404
  readonly vectors: VectorSearchReader<VectorIndexName>;`:"",z=_?`import type { VectorSearch, VectorSearchReader } from "${C.server}";
405
405
  import type { VectorIndexName } from "./dataModel.js";
@@ -730,13 +730,13 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
730
730
  export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
731
731
  id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
732
732
  };
733
- `},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${N(n.filePath)}:${n.exportName}`);return t},fo=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:o=[],shapes:a=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=ae(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,o,a),R=sr(t,n),x=ir(s,n),v=[R.lines,x.lines].filter(k=>k.length>0).join(`
733
+ `},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${N(n.filePath)}:${n.exportName}`);return t},ga=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,a,o),R=sr(t,n),x=ir(s,n),v=[R.lines,x.lines].filter(k=>k.length>0).join(`
734
734
  `);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
735
735
  ${v}
736
736
  `:`
737
737
  ${v}
738
- `);const A=fr(n),H=a.length>0?`import type { RegisteredShape } from "${d.server}";
739
- `:"",O=a.length>0?`
738
+ `);const A=fr(n),H=o.length>0?`import type { RegisteredShape } from "${d.server}";
739
+ `:"",O=o.length>0?`
740
740
  /**
741
741
  * Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
742
742
  * The generated ShardDO's \`resolveShape\` override looks a shape up by name and
@@ -887,7 +887,7 @@ export interface RegisteredDataMigration {
887
887
  * shard DO's admin RPC and the CLI resolve migrations to run through this map.
888
888
  */
889
889
  export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${u}};
890
- `,i)},br=e=>{const t={};for(const n of e.tables){const r={};for(const[o,a]of Object.entries(n.shape)){const i=se(a);i.kind==="id"&&i.tableName!==void 0&&(r[o]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},yr=e=>{const t={};for(const n of e.tables){const r=[];for(const[o,a]of Object.entries(n.shape))se(a).kind==="storage"&&r.push(o);r.length>0&&(t[n.name]=r)}return t},wr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(o=>({fields:[...o.fields],name:o.name,type:"index",...o.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(o=>({fields:[o.field,...o.filterFields??[]],name:o.name,type:"search"})),...(n.geoIndexes??[]).map(o=>({fields:[o.field],name:o.name,type:"geo"})),...n.rankIndexes.map(o=>({fields:o.sortBy.map(a=>a.field),name:o.name,type:"rank"})),...n.vectorIndexes.map(o=>({fields:o.field===void 0?[]:[o.field],name:o.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},kr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},xr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},vr=(e,t,n)=>{const r=se(t),o={name:e,optional:xt(t),type:r.kind};if(r.kind==="id"&&r.tableName!==void 0){o.ref=r.tableName;const i=n.get(e);i!==void 0&&(o.onDelete=i)}r.kind==="storage"&&(o.isStorage=!0,r.bucket!==void 0&&(o.bucket=r.bucket));const a=xr(r);return a!==void 0&&(o.enumValues=a),r.column?.notNull===!1&&(o.nullable=!0),o},Sr=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...n.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],o=new Map(n.relations.filter(a=>a.kind==="one").map(a=>[a.field,a.onDelete]));for(const[a,i]of Object.entries(n.shape))r.push(vr(a,i,o));t[n.name]=r}return t},Rr=e=>e?{importFragment:"serveRelationFanout, ",override:`
890
+ `,i)},br=e=>{const t={};for(const n of e.tables){const r={};for(const[a,o]of Object.entries(n.shape)){const i=se(o);i.kind==="id"&&i.tableName!==void 0&&(r[a]=i.tableName)}Object.keys(r).length>0&&(t[n.name]=r)}return t},yr=e=>{const t={};for(const n of e.tables){const r=[];for(const[a,o]of Object.entries(n.shape))se(o).kind==="storage"&&r.push(a);r.length>0&&(t[n.name]=r)}return t},wr=e=>{const t={};for(const n of e.tables){const r=[...n.indexes.map(a=>({fields:[...a.fields],name:a.name,type:"index",...a.unique===!0?{unique:!0}:{}})),...n.searchIndexes.map(a=>({fields:[a.field,...a.filterFields??[]],name:a.name,type:"search"})),...(n.geoIndexes??[]).map(a=>({fields:[a.field],name:a.name,type:"geo"})),...n.rankIndexes.map(a=>({fields:a.sortBy.map(o=>o.field),name:a.name,type:"rank"})),...n.vectorIndexes.map(a=>({fields:a.field===void 0?[]:[a.field],name:a.name,type:"vector"}))];r.length>0&&(t[n.name]=r)}return t},kr=e=>{const t=[];for(const n of e.tables)!n.ttl||n.shardMode==="global"||t.push({...n.ttl.after===void 0?{}:{after:n.ttl.after},field:n.ttl.field,...n.softDelete?{softDeleteField:n.softDelete.field}:{},table:n.name});return t},xr=e=>{if(e.kind!=="union"||e.members===void 0||e.members.length===0)return;const t=[];for(const n of e.members){if(n.kind!=="literal"||n.literalValue===void 0)return;try{const r=JSON.parse(n.literalValue);if(typeof r!="string")return;t.push(r)}catch{return}}return t},vr=(e,t,n)=>{const r=se(t),a={name:e,optional:xt(t),type:r.kind};if(r.kind==="id"&&r.tableName!==void 0){a.ref=r.tableName;const i=n.get(e);i!==void 0&&(a.onDelete=i)}r.kind==="storage"&&(a.isStorage=!0,r.bucket!==void 0&&(a.bucket=r.bucket));const o=xr(r);return o!==void 0&&(a.enumValues=o),r.column?.notNull===!1&&(a.nullable=!0),a},Sr=e=>{const t={};for(const n of e.tables){const r=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...n.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],a=new Map(n.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,i]of Object.entries(n.shape))r.push(vr(o,i,a));t[n.name]=r}return t},Rr=e=>e?{importFragment:"serveRelationFanout, ",override:`
891
891
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
892
892
  this.ensureMigrated();
893
893
 
@@ -926,12 +926,12 @@ const aiStub: LunoraAi = {
926
926
  ${t}
927
927
  }) as unknown as LunoraAi["workersai"],
928
928
  };
929
- `}},I=(e,t,n,{cast:r="",sync:o=[]}={})=>{const a=n.map(i=>` ${i}: ${o.includes(i)?"":"async "}() => {
929
+ `}},I=(e,t,n,{cast:r="",sync:a=[]}={})=>{const o=n.map(i=>` ${i}: ${a.includes(i)?"":"async "}() => {
930
930
  ${t}
931
931
  },`).join(`
932
932
  `);return`
933
933
  const ${e} = {
934
- ${a}
934
+ ${o}
935
935
  }${r};
936
936
  `},E={build:"",configField:"",contextField:"",importLines:[],stub:""},Tr=e=>e?{build:`
937
937
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
@@ -969,10 +969,10 @@ ${a}
969
969
  const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
970
970
  provider: () => config.flags?.(env),
971
971
  targetingKey: ${s},
972
- });`,o=`
972
+ });`,a=`
973
973
  /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
974
974
  const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }> = ${JSON.stringify(e,void 0,4)};
975
- `,a=`
975
+ `,o=`
976
976
  protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
977
977
  const evalContext = context as import("${n}").EvaluationContext | undefined;
978
978
  const evaluations: FlagsResult["flags"] = [];
@@ -1026,7 +1026,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
1026
1026
 
1027
1027
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
1028
1028
  }
1029
- `;return{constant:o,evaluateOverride:a,subscriptionOverride:i}},Dr=e=>e?{build:`
1029
+ `;return{constant:a,evaluateOverride:o,subscriptionOverride:i}},Dr=e=>e?{build:`
1030
1030
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
1031
1031
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
1032
1032
  `,configField:`
@@ -1059,14 +1059,14 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
1059
1059
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
1060
1060
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
1061
1061
  `,configField:`
1062
- pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,bo=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(a=>(f(a.exportName,`container export "${a.exportName}"`),f(a.className,`container class "${a.className}"`),`/** Container DO for the \`${a.exportName}\` definition (binding \`${a.bindingName}\`). */
1063
- export class ${a.className} extends LunoraContainer {
1062
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,fa=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(f(o.exportName,`container export "${o.exportName}"`),f(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
1063
+ export class ${o.className} extends LunoraContainer {
1064
1064
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
1065
- super(ctx, env, ${a.exportName}, "${a.exportName}"${n});
1065
+ super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
1066
1066
  }
1067
1067
  }
1068
1068
  `)).join(`
1069
- `),o=e.map(a=>a.exportName).join(", ");return`${S}/**
1069
+ `),a=e.map(o=>o.exportName).join(", ");return`${S}/**
1070
1070
  * Container-enabled Durable Object classes for the containers declared in
1071
1071
  * \`lunora/containers.ts\`. Re-export them from your worker entry — wrangler
1072
1072
  * requires each \`containers[].class_name\` to be exported by the worker:
@@ -1080,11 +1080,11 @@ export class ${a.className} extends LunoraContainer {
1080
1080
  */
1081
1081
  import { LunoraContainer } from "@lunora/container/do";
1082
1082
 
1083
- import { ${o} } from "../containers.js";
1083
+ import { ${a} } from "../containers.js";
1084
1084
 
1085
1085
  export { ContainerProxy } from "@lunora/container/do";
1086
1086
 
1087
- ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)f(r.exportName,`container export "${r.exportName}"`),f(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
1087
+ ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)f(r.exportName,`container export "${r.exportName}"`),f(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const a=r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${a} },`}).join(`
1088
1088
  `);return{build:`
1089
1089
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent());
1090
1090
  `,contextField:`
@@ -1093,7 +1093,7 @@ ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
1093
1093
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
1094
1094
  ${n}
1095
1095
  ];
1096
- `}},yo=e=>{if(e.length===0)return"";const t=e.map(r=>(f(r.exportName,`workflow export "${r.exportName}"`),f(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1096
+ `}},ba=e=>{if(e.length===0)return"";const t=e.map(r=>(f(r.exportName,`workflow export "${r.exportName}"`),f(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
1097
1097
  export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
1098
1098
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1099
1099
  super(ctx, env, ${r.exportName}, "${r.exportName}");
@@ -1121,7 +1121,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
1121
1121
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
1122
1122
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
1123
1123
 
1124
- ${t}`},wo=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{f(s.exportName,`agent export "${s.exportName}"`),f(s.className,`agent class "${s.className}"`);const c=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent (binding \`${s.bindingName}\`). */
1124
+ ${t}`},ya=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{f(s.exportName,`agent export "${s.exportName}"`),f(s.className,`agent class "${s.className}"`);const c=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent (binding \`${s.bindingName}\`). */
1125
1125
  export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1126
1126
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1127
1127
  super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
@@ -1135,7 +1135,7 @@ export class ${d} extends VoiceSessionDO {
1135
1135
  }
1136
1136
  }
1137
1137
  `;return`${c}${g}`}).join(`
1138
- `),o=e.map(s=>s.exportName).join(", ");return`${S}/**
1138
+ `),a=e.map(s=>s.exportName).join(", ");return`${S}/**
1139
1139
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
1140
1140
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
1141
1141
  * Workflow. Re-export them from your worker entry — wrangler requires each
@@ -1147,9 +1147,9 @@ import LunoraWorkflow from "@lunora/workflow/do";
1147
1147
  ${n?'import { compileAgentWorkflow, VoiceSessionDO } from "@lunora/agent";':'import { compileAgentWorkflow } from "@lunora/agent";'}
1148
1148
  import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
1149
1149
 
1150
- import { ${o} } from "../agents.js";
1150
+ import { ${a} } from "../agents.js";
1151
1151
 
1152
- ${r}`},ko=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)f(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
1152
+ ${r}`},wa=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)f(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
1153
1153
  `);return`${S}/**
1154
1154
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
1155
1155
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -1191,8 +1191,8 @@ ${t}
1191
1191
  const LUNORA_AGENTS: ReadonlyArray<AgentBindingSpec> = [
1192
1192
  ${t}
1193
1193
  ];
1194
- `}},Nt=(e,t,n,r,o)=>({constant:`
1195
- ${o}
1194
+ `}},Nt=(e,t,n,r,a)=>({constant:`
1195
+ ${a}
1196
1196
  const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1197
1197
  `,override:`
1198
1198
  protected override ${n}(): ${t} {
@@ -1209,10 +1209,10 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
1209
1209
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
1210
1210
  : x402Stub;
1211
1211
  `,configField:`
1212
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],xo=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:o,flagKeys:a=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:A,mutators:H=[],queues:O=[],rlsMetadata:C,schema:w,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=ae(Z),ee=H.length>0,k=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1212
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],ka=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:A,mutators:H=[],queues:O=[],rlsMetadata:C,schema:w,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,k=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
1213
1213
  /** 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. */
1214
1214
  const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
1215
- `,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(a,h,D.flags),te=Ar(l),he=Or(o),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,w.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Br(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=jr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Kr(b),{build:p,configField:We,imports:Te,stub:re}=Qr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=A??{columns:[]},Dt=ie??{rules:[]},Lt=le??{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:_t}=Wr(V),{constant:Pt,override:Mt}=Ur(O),K=v&&w.vectorIndexes.length>0,tt=new Set(w.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&w.vectorIndexes.some(m=>tt.has(m.table)),we=w.tables.some(m=>m.shardMode==="global"),Ue=w.tables.some(m=>Nn(m)),nt=w.tables.some(m=>An(m)),oe=w.tables.some(m=>m.externalSource!==void 0),rt=w.tables.some(m=>m.memory===!0),Ke=w.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=w.tables.length>0,Ft=br(w),Bt=wr(w),qt=Sr(w),jt=yr(w),ot=kr(w),at=Hr(K,V.length>0,O.length>0,h,Ke);k&&at.push("WhereInput");const st=Rr(we),Wt=k?`
1215
+ `,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(o,h,D.flags),te=Ar(l),he=Or(a),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,w.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Br(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=jr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Kr(b),{build:p,configField:We,imports:Te,stub:re}=Qr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=A??{columns:[]},Dt=ie??{rules:[]},Lt=le??{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:_t}=Wr(V),{constant:Pt,override:Mt}=Ur(O),K=v&&w.vectorIndexes.length>0,tt=new Set(w.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&w.vectorIndexes.some(m=>tt.has(m.table)),we=w.tables.some(m=>m.shardMode==="global"),Ue=w.tables.some(m=>Nn(m)),nt=w.tables.some(m=>An(m)),ae=w.tables.some(m=>m.externalSource!==void 0),rt=w.tables.some(m=>m.memory===!0),Ke=w.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=w.tables.length>0,Ft=br(w),Bt=wr(w),qt=Sr(w),jt=yr(w),at=kr(w),ot=Hr(K,V.length>0,O.length>0,h,Ke);k&&ot.push("WhereInput");const st=Rr(we),Wt=k?`
1216
1216
  protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
1217
1217
  const shape = LUNORA_SHAPES[name];
1218
1218
 
@@ -1283,20 +1283,20 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as
1283
1283
  protected override isCustomMutator(functionPath: string): boolean {
1284
1284
  return LUNORA_MUTATOR_PATHS.has(functionPath);
1285
1285
  }
1286
- `:"",Kt=k?"assertShapeShardable, ":"",Qt=lt===""?"":"assertShapesDeclareReadPolicies, ",ke=[`import type { ${at.join(", ")} } from "${D.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${rt?"clearMemoryTables, ":""}${Kt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${oe?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${st.importFragment}ShardDO as ShardDOBase } from "${D.do}";`,...oe?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${D.do}";`]:[],k?`import { asBucketStorage, ${Qt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${D.server}";`),K&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...G.importLines,..._.importLines,...te.importLines,...he.importLines,...z.importLines,...j.importLines,...W.importLines,...U.importLines,...B.importLines,...ne.importLines,...Re,...$e,...Se,...fe,...ye,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ht=K?`
1286
+ `:"",Kt=k?"assertShapeShardable, ":"",Qt=lt===""?"":"assertShapesDeclareReadPolicies, ",ke=[`import type { ${ot.join(", ")} } from "${D.do}";`,`import { applyCdcChanges, ${Ke?"backfillSearchIndexes, ":""}buildReprojectionMigration, ${rt?"clearMemoryTables, ":""}${Kt}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${ae?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Ne?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${st.importFragment}ShardDO as ShardDOBase } from "${D.do}";`,...ae?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${D.do}";`]:[],k?`import { asBucketStorage, ${Qt}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${D.server}";`];Qe&&ke.push(`import { bindOrm, bindTableFacade } from "${D.server}";`),K&&ke.push('import type { SchemaLike as VectorSchemaLike, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectors, createVectorSyncHook } from "@lunora/bindings/vectors";'),s&&ke.push('import type { AiBindingLike, LunoraAi } from "@lunora/ai";','import { createAi } from "@lunora/ai";'),ke.push(...ue.importLines,...G.importLines,..._.importLines,...te.importLines,...he.importLines,...z.importLines,...j.importLines,...W.importLines,...U.importLines,...B.importLines,...ne.importLines,...Re,...$e,...Se,...fe,...ye,...Te,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...ee?["LUNORA_MUTATOR_PATHS"]:[],...k?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ht=K?`
1287
1287
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Vt=nt?`
1288
1288
  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=Ue?`
1289
- hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=oe?`
1289
+ hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=ae?`
1290
1290
  sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",zt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Yt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Xt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',en=we?I("globalDbStub: DatabaseWriterLike",zt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",tn=K?I("vectorsStub: VectorSearchLike",Yt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",nn=Ne?`
1291
1291
  const vectorShardKey = this.currentShardKey();
1292
- `:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",on=Ne?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}] }`:"",an=K?`
1292
+ `:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=Ne?`, { namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, shardedIndexNames: [${w.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}] }`:"",on=K?`
1293
1293
  let vectors: VectorSearchLike;
1294
1294
  let onWrite: WriteHook | undefined;
1295
1295
 
1296
1296
  if (config.vectors) {
1297
1297
  const lunora = createVectors({ indexes: config.vectors(env) });
1298
1298
  ${nn}
1299
- vectors = createContextVectors(lunora${on});
1299
+ vectors = createContextVectors(lunora${an});
1300
1300
  onWrite = createVectorSyncHook({ ${rn}schema: schema as unknown as VectorSchemaLike, vectors });
1301
1301
  } else {
1302
1302
  vectors = vectorsStub;
@@ -1341,7 +1341,14 @@ ${nn}
1341
1341
  // keeps its own "degrade a provable slice to a whole-table dep"
1342
1342
  // fallback rather than reporting into a no-op.
1343
1343
  onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${K?`
1344
- onWrite,`:""}
1344
+ // Vectorize is outside this shard's SQLite and cannot roll back, so
1345
+ // the sync is held until the mutation's transaction has COMMITTED
1346
+ // (\`deferAfterCommit\`) instead of running inline. Inline, a write
1347
+ // that later aborted left a vector pointing at a row that does not
1348
+ // exist — which a search then surfaces — and a rolled-back delete
1349
+ // left the row with its vector already purged. Outside a
1350
+ // transaction (an action) nothing is open and it runs at once.
1351
+ onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
1345
1352
  scheduler,
1346
1353
  schema: schema as unknown as SchemaLike,
1347
1354
  sql: this.sql as SqlExec,
@@ -1435,7 +1442,7 @@ ${nn}
1435
1442
 
1436
1443
  return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
1437
1444
  }
1438
- `:"",pn=oe?`
1445
+ `:"",pn=ae?`
1439
1446
  const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
1440
1447
  const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
1441
1448
  `:"",mn=`
@@ -1445,7 +1452,7 @@ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1445
1452
  `:""}
1446
1453
  await this.dispatchShardInit();
1447
1454
  }
1448
- `,gn=oe?`
1455
+ `,gn=ae?`
1449
1456
  protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
1450
1457
  const env = (this.env ?? {}) as Record<string, unknown>;
1451
1458
  const sourced = Object.entries((schema as unknown as SchemaLike).tables)
@@ -1585,7 +1592,7 @@ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1585
1592
 
1586
1593
  return nextDueAt;
1587
1594
  }
1588
- `:"",fn=ot.length>0,bn=`
1595
+ `:"",fn=at.length>0,bn=`
1589
1596
  public constructor(state: ShardDOState, env: unknown) {
1590
1597
  super(state, env, {
1591
1598
  // Every writer this file builds spreads the ctxDbTuning() slice —
@@ -1598,7 +1605,7 @@ ${rt?` clearMemoryTables(this.sql as SqlExec, schema as unknown as Sc
1598
1605
  ...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
1599
1606
  ...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
1600
1607
  });
1601
- ${oe?`
1608
+ ${ae?`
1602
1609
  const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
1603
1610
  const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
1604
1611
 
@@ -1687,7 +1694,7 @@ const LUNORA_TABLE_COLUMNS: Record<
1687
1694
  const LUNORA_STORAGE_COLUMNS: Record<string, string[]> = ${JSON.stringify(jt,void 0,4)};
1688
1695
 
1689
1696
  /** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
1690
- const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(ot,void 0,4)};
1697
+ const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = ${JSON.stringify(at,void 0,4)};
1691
1698
 
1692
1699
  /** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
1693
1700
  const LUNORA_ADVISORIES: AdvisoryFinding[] = ${JSON.stringify(Ot,void 0,4)};
@@ -2351,7 +2358,7 @@ ${Ke?`
2351
2358
  userId: this.getCurrentUserId(),
2352
2359
  };
2353
2360
  const { identity, ip, userId } = caller;
2354
- ${an}${de}${wn}${Le}${_e}${De}${Fe}
2361
+ ${on}${de}${wn}${Le}${_e}${De}${Fe}
2355
2362
  // Which dispatch this ctx belongs to. Drives the two deferral facades
2356
2363
  // below and the \`ctx.run*\` caller guard; a ctx built for an
2357
2364
  // admin/lifecycle path has no registered function, and so no kind.
@@ -2540,21 +2547,21 @@ ${Sn}${vn}
2540
2547
  return ctx;
2541
2548
  }
2542
2549
  };
2543
- `},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:T(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:T(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Vr=(e,t,n)=>{f(e,"drizzle column name");const r=Xe(t),o=r.mode?`, { mode: "${r.mode}" }`:"";let a=`${r.builder}("${e}"${o})`;r.typeAnnotation&&(a+=`.$type<${r.typeAnnotation}>()`);const i=At(t,n);return i!==void 0&&(a+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(a+=".notNull()"),a},Gr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${Y(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Jr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,a])=>` ${o}: ${Vr(o,a,t)},`)].join(`
2550
+ `},Xe=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:T(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:T(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?Xe(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},At=(e,t)=>{const n=se(e);return n.kind==="id"&&n.tableName!==void 0&&t.has(n.tableName)?n.tableName:void 0},Vr=(e,t,n)=>{f(e,"drizzle column name");const r=Xe(t),a=r.mode?`, { mode: "${r.mode}" }`:"";let o=`${r.builder}("${e}"${a})`;r.typeAnnotation&&(o+=`.$type<${r.typeAnnotation}>()`);const i=At(t,n);return i!==void 0&&(o+=`.references((): AnySQLiteColumn => ${i}._id)`),r.notNull&&(o+=".notNull()"),o},Gr=e=>{const t=e.unique?"uniqueIndex":"index",n=e.fields.map(r=>(f(r,"drizzle index field"),`t.${r}`)).join(", ");return` ${Y(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${n}),`},Jr=(e,t)=>{f(e.name,"table name");const n=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([a,o])=>` ${a}: ${Vr(a,o,t)},`)].join(`
2544
2551
  `),r=e.indexes.length>0?`, (t) => ({
2545
- ${e.indexes.map(o=>Gr(o)).join(`
2552
+ ${e.indexes.map(a=>Gr(a)).join(`
2546
2553
  `)}
2547
2554
  })`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
2548
2555
  ${n}
2549
- }${r});`},zr=e=>e.typeAnnotation?.includes('Id<"')??!1,Yr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let o=!1,a=!1;for(const i of e){for(const s of Object.values(i.shape)){const c=Xe(s);n.add(c.builder),a=a||zr(c),o=o||At(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:o,needsId:a}},ht=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2550
- `;const n=ae(t),r=new Set(e.map(g=>g.name)),{columns:o,indexes:a,needsAnyColumn:i,needsId:s}=Yr(e,r),c=[...a,...o].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>Jr(g,r)).join(`
2556
+ }${r});`},zr=e=>e.typeAnnotation?.includes('Id<"')??!1,Yr=(e,t)=>{const n=new Set(["integer","sqliteTable","text"]),r=new Set;let a=!1,o=!1;for(const i of e){for(const s of Object.values(i.shape)){const c=Xe(s);n.add(c.builder),o=o||zr(c),a=a||At(s,t)!==void 0}for(const s of i.indexes)r.add(s.unique?"uniqueIndex":"index")}return{columns:[...n].toSorted((i,s)=>i.localeCompare(s)),indexes:[...r].toSorted((i,s)=>i.localeCompare(s)),needsAnyColumn:a,needsId:o}},ht=(e,t=!1)=>{if(e.length===0)return`${S}export {};
2557
+ `;const n=oe(t),r=new Set(e.map(g=>g.name)),{columns:a,indexes:o,needsAnyColumn:i,needsId:s}=Yr(e,r),c=[...o,...a].toSorted((g,y)=>g.localeCompare(y)),d=e.map(g=>Jr(g,r)).join(`
2551
2558
 
2552
2559
  `),h=[i?`import type { AnySQLiteColumn } from "${n.serverDrizzle}";
2553
2560
  `:"",s?`import type { Id } from "./dataModel.js";
2554
2561
  `:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
2555
2562
  ${h}
2556
2563
  ${d}
2557
- `},vo=(e,t=!1)=>{const n=e.tables.filter(o=>o.shardMode==="global"),r=e.tables.filter(o=>o.shardMode!=="global");return{global:L(ht(n,t),Je),shard:L(ht(r,t),Je)}},So=e=>e?`${S}/**
2564
+ `},xa=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:L(ht(n,t),Je),shard:L(ht(r,t),Je)}},va=e=>e?`${S}/**
2558
2565
  * The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
2559
2566
  * forward it — wrangler binds only what the entry exports:
2560
2567
  *
@@ -2564,15 +2571,15 @@ ${d}
2564
2571
  * forwards this module for you whenever it exists.
2565
2572
  */
2566
2573
  export { SchedulerDO } from "@lunora/scheduler";
2567
- `:"",Ro=e=>{const t=new Map;for(const i of e){const s=t.get(i.cron);s?s.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2574
+ `:"",Sa=e=>{const t=new Map;for(const i of e){const s=t.get(i.cron);s?s.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
2568
2575
  `),r=n.length>0?`
2569
2576
  ${n}
2570
- `:"",o=[...t.entries()].map(([i,s])=>{const c=s.map(d=>{const h=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${h}, args: ${JSON.stringify(d.args)} },`}).join(`
2577
+ `:"",a=[...t.entries()].map(([i,s])=>{const c=s.map(d=>{const h=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${h}, args: ${JSON.stringify(d.args)} },`}).join(`
2571
2578
  `);return` ${JSON.stringify(i)}: [
2572
2579
  ${c}
2573
2580
  ],`}).join(`
2574
- `),a=o.length>0?`
2575
- ${o}
2581
+ `),o=a.length>0?`
2582
+ ${a}
2576
2583
  `:"";return`${S}/**
2577
2584
  * One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
2578
2585
  * the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
@@ -2597,8 +2604,8 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
2597
2604
  * Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
2598
2605
  * looks up \`event.cron\` here and dispatches every job in the list.
2599
2606
  */
2600
- export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${a}};
2601
- `},$o=e=>{const t=[...e].toSorted((r,o)=>r.name.localeCompare(o.name)).map(r=>{const o=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&o.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&o.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&o.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&o.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${o.join(", ")} },`}).join(`
2607
+ export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
2608
+ `},Ra=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
2602
2609
  `),n=t.length>0?`
2603
2610
  ${t}
2604
2611
  `:"";return`${S}/**
@@ -2622,4 +2629,4 @@ export interface LunoraVectorIndex {
2622
2629
  * \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
2623
2630
  */
2624
2631
  export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
2625
- `},To=e=>[...new Set(e.map(t=>t.cron))];export{co as A,In as C,S as G,er as U,ho as a,mo as b,bo as c,Ro as d,wo as e,uo as f,vo as g,fo as h,So as i,go as j,xo as k,$o as l,yo as m,To as n,yr as o,ko as p,po as q};
2632
+ `},$a=e=>[...new Set(e.map(t=>t.cron))];export{ca as A,In as C,S as G,er as U,ua as a,pa as b,fa as c,Sa as d,ya as e,da as f,xa as g,ga as h,va as i,ma as j,ka as k,Ra as l,ba as m,$a as n,yr as o,wa as p,ha as q};
@@ -1,4 +1,4 @@
1
- import{A as w,G as k}from"./emit-wC8dZkgS.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
1
+ import{A as w,G as k}from"./emit-CKAvO86n.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
2
2
  public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
3
3
  this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.187",
3
+ "version": "1.0.0-alpha.189",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.137",
50
- "@lunora/agent": "1.0.0-alpha.115",
51
- "@lunora/container": "1.0.0-alpha.51",
52
- "@lunora/errors": "1.0.0-alpha.38",
49
+ "@lunora/advisor": "1.0.0-alpha.138",
50
+ "@lunora/agent": "1.0.0-alpha.116",
51
+ "@lunora/container": "1.0.0-alpha.52",
52
+ "@lunora/errors": "1.0.0-alpha.39",
53
53
  "@lunora/platform": "1.0.0-alpha.32",
54
- "@lunora/queue": "1.0.0-alpha.58",
55
- "@lunora/scheduler": "1.0.0-alpha.75",
56
- "@lunora/values": "1.0.0-alpha.48",
57
- "@lunora/workflow": "1.0.0-alpha.54",
54
+ "@lunora/queue": "1.0.0-alpha.59",
55
+ "@lunora/scheduler": "1.0.0-alpha.76",
56
+ "@lunora/values": "1.0.0-alpha.49",
57
+ "@lunora/workflow": "1.0.0-alpha.55",
58
58
  "jiti": "^2.7.0",
59
59
  "quicktype-core": "^26.0.0",
60
60
  "ts-morph": "^28.0.0"
@@ -1,2 +0,0 @@
1
- const p=(e,i=2166136261)=>{let t=i;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},m=e=>`${p(e,2166136261)}${p(e,16777619)}`,I=1;function g(e){const i={},t=Object.keys(e);t.sort();for(const n of t)i[n]=e[n];return i}const v=e=>`${JSON.stringify(e,void 0,2)}
2
- `,E=e=>m(v(e)),a=e=>typeof e=="object"&&e!==null,$=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",_=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(n){return{error:`baseline is not valid JSON: ${n instanceof Error?n.message:String(n)}`,status:"invalid"}}if(!a(i)||i.version!==1||!a(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[n,o]of Object.entries(i.tables))if(!$(o))return{error:`baseline table "${n}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},b=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,n)=>t===i.fields[n]),f=e=>e.unique!==void 0,u=({nullable:e,optional:i,refined:t,unique:n,...o})=>JSON.stringify(g(o)),h=e=>({form:JSON.stringify([u(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),y=e=>e.kind==="union"&&e.members?e.members.map(i=>h(i)):[h({...e,nullable:!1,optional:!1})],S=(e,i)=>{if(i.kind!=="union")return!1;const t=y(i);return y(e).every(n=>t.some(o=>o.form===n.form&&(n.refined||!o.refined)))},d=e=>{switch(e.kind){case"array":return`array(${e.of?d(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?d(e.key):"?"}, ${e.of?d(e.of):"?"})`;case"union":return(e.members??[]).map(i=>d(i)).join(" | ");default:return e.kind}},c=(e,i,t)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:t,table:e,type:i}),l=(e,i,t)=>({remediation:"none",scope:"table",severity:"safe",summary:t,table:e,type:i}),k=(e,i,t,n,o)=>{if(!(t.kind===n.kind&&(!o||u(t)===u(n))))return o&&S(t,n)?l(e,"widenedFieldShape",`field ${e}.${i} widened: ${d(t)} → ${d(n)} — every stored value stays valid`):t.kind!==n.kind?c(e,"changedFieldKind",`field ${e}.${i} changed type: ${t.kind} → ${n.kind} — add a data migration to convert existing values`):c(e,"changedFieldShape",`field ${e}.${i} changed shape: ${d(t)} → ${d(n)} — stored values were written against the old shape; add a data migration to convert them`)},x=(e,i,t,n)=>{const o=[];return t.unique!==n.unique&&o.push(n.unique===!0?c(e,"addedFieldConstraint",`field ${e}.${i} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):l(e,"relaxedFieldConstraint",`field ${e}.${i} is no longer unique`)),t.nullable!==n.nullable&&o.push(n.nullable===!0?l(e,"relaxedFieldConstraint",`field ${e}.${i} became nullable`):c(e,"addedFieldConstraint",`field ${e}.${i} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),t.refined!==n.refined&&o.push(n.refined===!0?c(e,"addedFieldConstraint",`field ${e}.${i} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):l(e,"relaxedFieldConstraint",`field ${e}.${i} dropped its validation refinement`)),o},O=(e,i,t,n)=>{const o=[],s=f(t)&&f(n),r=k(e,i,t,n,s);return r&&o.push(r),s&&o.push(...x(e,i,t,n)),t.optional&&!n.optional?o.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&n.optional&&o.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},F=(e,i,t)=>t.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},j=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.fields)){const r=i.fields[o];r===void 0?n.push(F(e,o,s)):n.push(...O(e,o,r,s))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&n.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},w=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.indexes)){const r=i.indexes[o];if(r===void 0){n.push(s.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${o} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}b(r,s)||n.push({remediation:"code",severity:"breaking",summary:`index ${o} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const o of Object.keys(i.indexes))t.indexes[o]===void 0&&n.push({remediation:"code",severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},A=(e,i,t,n)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&n.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(i.relations))t.relations[o]===void 0&&n.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},q=(e,i,t,n)=>{i.shardMode!==t.shardMode&&n.push({remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}),j(e,i,t,n),w(e,i,t,n),A(e,i,t,n)},C=(e,i)=>{const t=[],n=e?.tables??{};for(const[o,s]of Object.entries(i.tables)){const r=n[o];if(r===void 0){t.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}q(o,r,s,t)}for(const o of Object.keys(n))i.tables[o]===void 0&&t.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${o} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",s=i.jurisdiction??"(none)";t.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${s} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{I as SCHEMA_SNAPSHOT_VERSION,d as describeShape,O as diffExistingField,C as diffSchemaSnapshots,E as hashSchemaSnapshot,$ as isValidTableSnapshot,_ as parseSnapshotJson,v as serializeSchemaSnapshot,g as sortKeys};
@@ -1,18 +0,0 @@
1
- import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as f,diffSchemaSnapshots as A,parseSnapshotJson as L}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{serializeSchemaSnapshot as V}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";const _=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,N=(e,t)=>{const s=JSON.stringify(e),i=JSON.stringify(t);return s===i?0:s<i?-1:1},l=e=>{const t=e.kind==="optional",s=t?e.inner:void 0,i=s??e,n={kind:t?s?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...v[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(n.refined=!0),n},j=e=>{const t={};for(const[s,i]of Object.entries(e))t[s]=l(i);return f(t)},v={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:j(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(N)}:{}},D=e=>{const t={};for(const[n,a]of Object.entries(e.shape))t[n]=l(a);const s={};for(const n of e.indexes)s[n.name]={fields:[...n.fields],unique:n.unique??!1};const i={};for(const n of e.relations)i[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:f(t),indexes:f(s),relations:f(i),shardMode:_(e.shardMode)}},U=(e,t)=>{const s={};for(const n of e.tables)s[n.name]=D(n);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:f(s),version:I}};class O extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const C=e=>{const t=L(e);if(t.status==="invalid")throw new O(t.error);return t.status==="ok"?t.snapshot:void 0},R={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",M=e=>{const t=e===void 0?void 0:R[e];if(e===void 0||t===void 0)return`${y}
2
- ${k}
3
- `;const s=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
4
- ${s}
5
- `},m=e=>e.map(t=>` - ${t.summary}`).join(`
6
- `),w=e=>e.remediation==="backfill"&&e.table!==void 0,x=/^[A-Za-z_]\w*$/u,B=e=>` lunora migrate create backfill_${e} --table ${e}`,F=(e,t,s)=>{const i=[...new Set(e.filter(a=>w(a)).map(a=>a.table))],n=[];if(i.length>0){n.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const a=i.filter(r=>x.test(r));a.length>0&&n.push(`
7
- Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
8
- ${a.map(r=>B(r)).join(`
9
- `)}
10
-
11
- `)}return t.length>0&&n.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
12
- `),n.push(M(s)),[`${s??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,m(e),"",`To fix:
13
- ${n.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
14
- `)},H=e=>{const{allowDrift:t=!1,baseline:s,command:i,current:n,migrations:a}=e,r=A(s,n),u=r.changes.filter(o=>o.severity==="breaking"),b=n.migrationIds.filter(o=>!(s?.migrationIds??[]).includes(o)),p=a.filter(o=>b.includes(o.id)),c=(o,h)=>({blocked:o,changes:r.changes,newMigrationIds:b,reason:h}),T=new Set(p.filter(o=>o.table!=="").map(o=>o.table)),$=p.filter(o=>o.table==="").map(o=>o.id);if(r.changes.length===0||s===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
15
- ${m(r.changes)}`);const g=u.filter(o=>!w(o)||!T.has(o.table));if(g.length===0){const o=new Set(u.map(d=>d.table)),h=p.filter(d=>o.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
16
- ${m(u)}`)}const S=F(g,$,i);return t?c(!1,`${S}
17
-
18
- (overridden by --allow-schema-drift)`):c(!0,S)};export{I as SCHEMA_SNAPSHOT_VERSION,O as SchemaSnapshotParseError,U as buildSchemaSnapshot,A as diffSchemaSnapshots,H as evaluateSchemaDrift,C as parseSchemaSnapshot,V as serializeSchemaSnapshot};