@lunora/codegen 1.0.0-alpha.28 → 1.0.0-alpha.280
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/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +4046 -1242
- package/dist/index.d.ts +4046 -1242
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-Dntm1vDe.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-brcmKenl.mjs +25 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-D5xnZUl6.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-GPPgJNTn.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-C1RHlinh.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-Ck_WOHzE.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-YOl15Grm.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-B8Wb9kiq.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-DnYKkFP6.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-hTuq7XDL.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CqU4KTnp.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-BrqrIhBv.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-eLdktkM5.mjs +1 -0
- package/dist/packem_shared/attribution-DqqCSywo.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-D_8TtHK1.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-CmSX6ODG.mjs +1 -0
- package/dist/packem_shared/chain-DmRSLvAh.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-HrUyDQX0.mjs +1 -0
- package/dist/packem_shared/context-property-calls-0qzW2Joh.mjs +1 -0
- package/dist/packem_shared/context-root-DKsAPUmn.mjs +1 -0
- package/dist/packem_shared/database-calls-CBlsQTga.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CeFyWdQy.mjs +1 -0
- package/dist/packem_shared/discoverCrons-DBuEbNrB.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-BswBeUWK.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-6utMwfNf.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-HGl9zBnw.mjs +1 -0
- package/dist/packem_shared/discoverInserts-Ao36AnSp.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-B29pl7an.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-CM6L8k6b.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-C6iIjMHn.mjs +1 -0
- package/dist/packem_shared/discoverQueries-4lacKgx_.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-BDomQsRO.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-CTQN6hgU.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-DllbV6_E.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-ejLtE6Ky.mjs +1 -0
- package/dist/packem_shared/discoverSchema-C3WOG-xt.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-CyZ44b1b.mjs +1 -0
- package/dist/packem_shared/dispatch-namespace-DwTjD7BU.mjs +1 -0
- package/dist/packem_shared/emitAgents-BedQefBj.mjs +1 -0
- package/dist/packem_shared/emitApi-Zx6VPN-7.mjs +135 -0
- package/dist/packem_shared/emitApp-CBIXVzkw.mjs +864 -0
- package/dist/packem_shared/emitCrons-Gd8jD8jF.mjs +96 -0
- package/dist/packem_shared/emitDataModel-DdtjdNg3.mjs +113 -0
- package/dist/packem_shared/emitDrizzleSchema-CpOGYfyl.mjs +15 -0
- package/dist/packem_shared/emitFunctions-BeKgL3dl.mjs +241 -0
- package/dist/packem_shared/emitServer-DlOheWku.mjs +1 -0
- package/dist/packem_shared/emitShard-CngydZFL.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains--nYG8cid.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-C4PkhFFQ.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/handler-reference-CpEEELL0.mjs +1 -0
- package/dist/packem_shared/index-BfaSHMNi.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTestPath-CiIyKqhF.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-DGqGWOfa.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-Cuogms61.mjs +1 -0
- package/dist/packem_shared/parse-validator-DYdT7Hyf.mjs +1 -0
- package/dist/packem_shared/project-config-file-Bv2l-Kmm.mjs +1 -0
- package/dist/packem_shared/qualifiers-DEdXn5wP.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-RHhGiz0k.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-DuE9xlvV.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/server-DSUfd6Tc.mjs +368 -0
- package/dist/packem_shared/shard-BTfJuEeP.mjs +1438 -0
- package/dist/packem_shared/shard-runtime-CkaEBSdL.mjs +326 -0
- package/dist/packem_shared/shared-DnCokNcE.mjs +13 -0
- package/dist/packem_shared/unwrap-handler-return-BTKoWeJc.mjs +1 -0
- package/package.json +17 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-Bq7mlUUg.mjs +0 -3269
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CPz5aJ8A.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BSBSVXEv.mjs +0 -1153
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-DLAW4ldJ.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-YuSwauCv.mjs +0 -675
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import{i as m}from"./ir-DBSvhNa-.mjs";import{G as i,d as c}from"./shared-DnCokNcE.mjs";const u=r=>r?`${i}/**
|
|
2
|
+
* The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
|
|
3
|
+
* forward it — wrangler binds only what the entry exports:
|
|
4
|
+
*
|
|
5
|
+
* \`export * from "./lunora/_generated/scheduler.js";\`
|
|
6
|
+
*
|
|
7
|
+
* A Vite-first (class-A) app needs no such line: the generated worker entry
|
|
8
|
+
* forwards this module for you whenever it exists.
|
|
9
|
+
*/
|
|
10
|
+
export { SchedulerDO } from "@lunora/scheduler";
|
|
11
|
+
`:"",y=(r,t)=>r.some(o=>m(o))?`${i}/**
|
|
12
|
+
* The \`ShardRegistryDO\` Durable Object class — the live set of shard keys per
|
|
13
|
+
* \`.shardBy()\` table, which cross-shard export, CDC sync and migrations fan out
|
|
14
|
+
* to. Re-exported so a worker entry can forward it (wrangler binds only what the
|
|
15
|
+
* entry exports), next to \`.shardRegistry((env) => env.SHARD_REGISTRY)\`:
|
|
16
|
+
*
|
|
17
|
+
* \`export { ShardRegistryDO } from "./lunora/_generated/shardRegistry.js";\`
|
|
18
|
+
*
|
|
19
|
+
* Name the class in a hand-written entry: binding inference provisions
|
|
20
|
+
* \`SHARD_REGISTRY\` off the entry's named exports, and cannot see through an
|
|
21
|
+
* \`export *\`. A Vite-first (class-A) app needs neither line — its generated
|
|
22
|
+
* worker entry does both whenever this module exists.
|
|
23
|
+
*/
|
|
24
|
+
export { ShardRegistryDO } from "${c(t).do}";
|
|
25
|
+
`:"",w=r=>`${i}/**
|
|
26
|
+
* Host the shard, the scheduler and the shard registry in ONE Durable Object
|
|
27
|
+
* class, so the app spends one of the account's classes instead of three. A
|
|
28
|
+
* Vite-first (class-A) app needs nothing more: its generated worker entry builds
|
|
29
|
+
* \`LunoraDO\` from these. A hand-written entry does the same by hand:
|
|
30
|
+
*
|
|
31
|
+
* \`export const LunoraDO = mergeDurableObjects({ shard: app.ShardDO, scheduler: SchedulerDO, shardRegistry: ShardRegistryDO });\`
|
|
32
|
+
*
|
|
33
|
+
* and passes \`roleNamespace(env.SHARD, "scheduler")\` / \`roleNamespace(env.SHARD, "shardRegistry")\`
|
|
34
|
+
* to \`.scheduler()\` / \`.shardRegistry()\`. Merge before the first deploy only:
|
|
35
|
+
* data already in \`ShardDO\` does not move, and a deployed merge cannot be undone.
|
|
36
|
+
*/
|
|
37
|
+
export { mergeDurableObjects, roleNamespace } from "${c(r).do}";
|
|
38
|
+
`,O=r=>{const t=new Map;for(const n of r){const d=t.get(n.cron);d?d.push(n):t.set(n.cron,[n])}const o=[...t.keys()].map(n=>` ${JSON.stringify(n)},`).join(`
|
|
39
|
+
`),e=o.length>0?`
|
|
40
|
+
${o}
|
|
41
|
+
`:"",s=[...t.entries()].map(([n,d])=>{const l=d.map(a=>{const f=a.workflow?`workflow: ${JSON.stringify(a.workflow.className)}`:`functionPath: ${JSON.stringify(a.functionPath)}`;return` { name: ${JSON.stringify(a.name)}, ${f}, args: ${JSON.stringify(a.args)} },`}).join(`
|
|
42
|
+
`);return` ${JSON.stringify(n)}: [
|
|
43
|
+
${l}
|
|
44
|
+
],`}).join(`
|
|
45
|
+
`),h=s.length>0?`
|
|
46
|
+
${s}
|
|
47
|
+
`:"";return`${i}/**
|
|
48
|
+
* One scheduled cron invocation. Exactly one target is set: \`functionPath\` is
|
|
49
|
+
* the \`namespace:fn\` dispatch ref (matches \`__lunoraRef\`), invoked on the
|
|
50
|
+
* shard; \`workflow\` is a workflow class name (its \`ctx.exports\` key) whose durable workflow is
|
|
51
|
+
* started fresh per fire. \`args\` are forwarded verbatim (a workflow's become
|
|
52
|
+
* its \`params\`).
|
|
53
|
+
*/
|
|
54
|
+
export interface LunoraCronJob {
|
|
55
|
+
args: Record<string, unknown>;
|
|
56
|
+
functionPath?: string;
|
|
57
|
+
name: string;
|
|
58
|
+
workflow?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Deduplicated cron schedules — mirror of wrangler's \`triggers.crons\`. The
|
|
63
|
+
* Lunora vite plugin keeps \`wrangler.jsonc\` in sync with this array.
|
|
64
|
+
*/
|
|
65
|
+
export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${e}];
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Dispatcher map keyed by cron expression. The Worker's \`scheduled()\` handler
|
|
69
|
+
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
70
|
+
*/
|
|
71
|
+
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${h}};
|
|
72
|
+
`},S=r=>{const t=[...r].toSorted((e,s)=>e.name.localeCompare(s.name)).map(e=>{const s=[`name: ${JSON.stringify(e.name)}`,`table: ${JSON.stringify(e.table)}`];return e.field!==void 0&&s.push(`field: ${JSON.stringify(e.field)}`),e.dimensions!==void 0&&s.push(`dimensions: ${JSON.stringify(e.dimensions)}`),e.metric!==void 0&&s.push(`metric: ${JSON.stringify(e.metric)}`),e.metadata!==void 0&&s.push(`metadata: ${JSON.stringify(e.metadata)}`),` { ${s.join(", ")} },`}).join(`
|
|
73
|
+
`),o=t.length>0?`
|
|
74
|
+
${t}
|
|
75
|
+
`:"";return`${i}/**
|
|
76
|
+
* One vector index declared in \`schema.ts\` — an inline \`.vectorize()\` column
|
|
77
|
+
* or a standalone \`defineVectorIndex()\`. \`field\` is the source column (absent
|
|
78
|
+
* for a \`select\`-derived Shape B index); \`metadata\` lists the row fields
|
|
79
|
+
* mirrored into Vectorize for filtering.
|
|
80
|
+
*/
|
|
81
|
+
export interface LunoraVectorIndex {
|
|
82
|
+
dimensions?: number;
|
|
83
|
+
field?: string;
|
|
84
|
+
metadata?: ReadonlyArray<string>;
|
|
85
|
+
metric?: "cosine" | "dot-product" | "euclidean";
|
|
86
|
+
name: string;
|
|
87
|
+
table: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Static registry of every vector index in the schema, sorted by name.
|
|
92
|
+
* Vectorize cannot enumerate indexes at runtime, so the worker passes this to
|
|
93
|
+
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
94
|
+
*/
|
|
95
|
+
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${o}];
|
|
96
|
+
`},b=r=>[...new Set(r.map(t=>t.cron))];export{O as emitCrons,w as emitDurableObjects,u as emitScheduler,y as emitShardRegistry,S as emitVectors,b as emitWranglerCronTriggers};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import{r as k}from"./qualifiers-DEdXn5wP.mjs";import{a as s,e as i,v as d,f as v,G as M}from"./shared-DnCokNcE.mjs";const D="schema",w=a=>{for(const e of a.tables)s(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([h,r])=>{const o=i(h);if(r.kind==="optional"){const g=r.inner?d(r.inner):"unknown";return` ${o}?: ${g};`}return` ${o}: ${d(r)};`}).join(`
|
|
2
|
+
`),n=t?`
|
|
3
|
+
${t}
|
|
4
|
+
`:"",N=e.commitOrdered===!0?`
|
|
5
|
+
_commitSeq: number;`:"";return`export interface Doc_${e.name} {
|
|
6
|
+
_id: Id<"${e.name}">;
|
|
7
|
+
_creationTime: number;${N}${n}}`}).join(`
|
|
8
|
+
|
|
9
|
+
`),c=a.tables.map(e=>` ${e.name}: Doc_${e.name};`).join(`
|
|
10
|
+
`),y=a.tables.map(e=>{const t=e.indexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
11
|
+
`),x=a.tables.map(e=>{const t=e.searchIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
12
|
+
`),b=a.tables.map(e=>{const t=e.rankIndexes.map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
13
|
+
`),f=a.tables.map(e=>{const t=e.shardMode==="global"?"":(e.geoIndexes??[]).map(n=>JSON.stringify(n.name)).join(" | ");return` ${e.name}: ${t||"never"};`}).join(`
|
|
14
|
+
`),T=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",$=a.tables.map(e=>v(e)).join(`
|
|
15
|
+
|
|
16
|
+
`),u=a.tables.map(e=>` ${e.name}: Insert_${e.name};`).join(`
|
|
17
|
+
`),I=a.tables.map(e=>{const t=e.relations.map(n=>(s(n.table,"relation target table"),` ${i(n.name)}: ${n.kind==="one"?"OneRelation":"ManyRelation"}<"${n.table}">;`)).join(`
|
|
18
|
+
`);return t?` ${e.name}: {
|
|
19
|
+
${t}
|
|
20
|
+
};`:` ${e.name}: {};`}).join(`
|
|
21
|
+
`);return k(`${M}export type TableName = ${l};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The tables **this app declared** — every {@link TableName} except those an add-on
|
|
25
|
+
* contributed through \`defineSchema(...).extend(...)\`.
|
|
26
|
+
*
|
|
27
|
+
* An add-on's tables are real tables and stay in \`TableName\` (they are queryable,
|
|
28
|
+
* they appear in \`DataModel\`), but an app enumerating "my tables" should not have to
|
|
29
|
+
* know they exist: an account-deletion sweep, an export, a migration allowlist, or a
|
|
30
|
+
* helper generic over a table union is about the app's own data, and every add-on
|
|
31
|
+
* added or removed would otherwise silently change the correct answer.
|
|
32
|
+
*
|
|
33
|
+
* \`\`\`ts
|
|
34
|
+
* // Doesn't need to mention \`ratelimit_buckets\`, and won't drift when an add-on lands.
|
|
35
|
+
* const EXPORTED: readonly AppTableName[] = ["nodes", "tagColors"];
|
|
36
|
+
* \`\`\`
|
|
37
|
+
*/
|
|
38
|
+
export type AppTableName = ${m};
|
|
39
|
+
|
|
40
|
+
export type Id<TName extends string> = string & { readonly __table: TName };
|
|
41
|
+
|
|
42
|
+
${p}
|
|
43
|
+
|
|
44
|
+
export interface DataModel {
|
|
45
|
+
${c}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type Doc<T extends keyof DataModel> = DataModel[T];
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Per-table index name union. \`never\` for tables without secondary indexes.
|
|
52
|
+
* Used by \`TableReader.withIndex()\` to constrain callers to declared names.
|
|
53
|
+
*/
|
|
54
|
+
export interface IndexNamesByTable {
|
|
55
|
+
${y}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type IndexName<T extends keyof DataModel> = IndexNamesByTable[T];
|
|
59
|
+
|
|
60
|
+
/** Per-table search-index name union. \`never\` for tables without searchIndex. */
|
|
61
|
+
export interface SearchIndexNamesByTable {
|
|
62
|
+
${x}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type SearchIndexName<T extends keyof DataModel> = SearchIndexNamesByTable[T];
|
|
66
|
+
|
|
67
|
+
/** Per-table rank-index name union. \`never\` for tables without a rankIndex. */
|
|
68
|
+
export interface RankIndexNamesByTable {
|
|
69
|
+
${b}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type RankIndexName<T extends keyof DataModel> = RankIndexNamesByTable[T];
|
|
73
|
+
|
|
74
|
+
/** Per-table geo-index name union. \`never\` for tables without a geoIndex. */
|
|
75
|
+
export interface GeoIndexNamesByTable {
|
|
76
|
+
${f}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type GeoIndexName<T extends keyof DataModel> = GeoIndexNamesByTable[T];
|
|
80
|
+
|
|
81
|
+
/** Union of declared vector index names. \`never\` when none are declared. */
|
|
82
|
+
export type VectorIndexName = ${T};
|
|
83
|
+
|
|
84
|
+
${$}
|
|
85
|
+
|
|
86
|
+
/** Per-table insert shape, accepted by \`ctx.db.<table>.insert(...)\`. */
|
|
87
|
+
export interface InsertModel {
|
|
88
|
+
${u}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type Insert<T extends keyof DataModel> = InsertModel[T];
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Phantom relation descriptors. They carry the relation kind and target table
|
|
95
|
+
* as type parameters only — there is no runtime value — so the \`with\` argument
|
|
96
|
+
* and its return type can be inferred from {@link Relations}.
|
|
97
|
+
*/
|
|
98
|
+
export interface OneRelation<Target extends keyof DataModel> {
|
|
99
|
+
readonly __relationKind: "one";
|
|
100
|
+
readonly __target: Target;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ManyRelation<Target extends keyof DataModel> {
|
|
104
|
+
readonly __relationKind: "many";
|
|
105
|
+
readonly __target: Target;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Per-table relation map keyed by accessor name. \`{}\` for tables with none. */
|
|
109
|
+
export interface Relations {
|
|
110
|
+
${I}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
`,D)};export{D as SCHEMA_MODULE_PATH,w as emitDataModel};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-DdtjdNg3.mjs";import{r as m}from"./qualifiers-DEdXn5wP.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-DnCokNcE.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(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:f(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?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
|
|
2
|
+
`),n=e.indexes.length>0?`, (t) => ({
|
|
3
|
+
${e.indexes.map(o=>I(o)).join(`
|
|
4
|
+
`)}
|
|
5
|
+
})`:"";return`export const ${e.name} = sqliteTable("${e.name}", {
|
|
6
|
+
${r}
|
|
7
|
+
}${n});`},C=e=>e.typeAnnotation?.includes('Id<"')??!1,D=(e,t)=>{const r=new Set(["integer","sqliteTable","text"]),n=new Set;let o=!1,l=!1;for(const s of e){for(const i of Object.values(s.shape)){const a=d(i);r.add(a.builder),l=l||C(a),o=o||N(i,t)!==void 0}for(const i of s.indexes)n.add(i.unique?"uniqueIndex":"index")}return{columns:[...r].toSorted((s,i)=>s.localeCompare(i)),indexes:[...n].toSorted((s,i)=>s.localeCompare(i)),needsAnyColumn:o,needsId:l}},p=(e,t=!1)=>{if(e.length===0)return`${b}export {};
|
|
8
|
+
`;const r=T(t),n=new Set(e.map(u=>u.name)),{columns:o,indexes:l,needsAnyColumn:s,needsId:i}=D(e,n),a=[...l,...o].toSorted((u,g)=>u.localeCompare(g)),$=e.map(u=>S(u,n)).join(`
|
|
9
|
+
|
|
10
|
+
`),y=[s?`import type { AnySQLiteColumn } from "${r.serverDrizzle}";
|
|
11
|
+
`:"",i?`import type { Id } from "./dataModel.js";
|
|
12
|
+
`:""].join("");return`${b}import { ${a.join(", ")} } from "${r.serverDrizzle}";
|
|
13
|
+
${y}
|
|
14
|
+
${$}
|
|
15
|
+
`},v=(e,t=!1)=>{const r=e.tables.filter(o=>o.shardMode==="global"),n=e.tables.filter(o=>o.shardMode!=="global");return{global:m(p(r,t),c),shard:m(p(n,t),c)}};export{v as default};
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import{LunoraError as B}from"@lunora/errors";import{L as H,G as q,I as J,d as Q,b as S,r as G,c as z}from"./shared-DnCokNcE.mjs";import{renderAgentFunctionRegistry as V,renderSandboxFunctionRegistry as W}from"./emitApi-Zx6VPN-7.mjs";import{a as K,b as Y,r as O,c as X}from"./qualifiers-DEdXn5wP.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const Z=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),A=n=>n.column!==void 0,ee=(n,e)=>{switch(n){case"bigint":return`if (typeof ${e} !== "bigint") return DEFER;
|
|
2
|
+
`;case"boolean":return`if (typeof ${e} !== "boolean") return DEFER;
|
|
3
|
+
`;case"date":case"number":case"timestamp":return`if (typeof ${e} !== "number" || !Number.isFinite(${e})) return DEFER;
|
|
4
|
+
`;case"null":return`if (${e} !== null) return DEFER;
|
|
5
|
+
`;default:return`if (typeof ${e} !== "string") return DEFER;
|
|
6
|
+
`}},te=(n,e)=>n.stringMaxLength===void 0?"":`if (${e}.length > ${String(n.stringMaxLength)}) return DEFER;
|
|
7
|
+
`,ne=(n,e)=>{const r=n.literalValue?.trim();if(!(r===void 0||!H.test(r)))return{out:e,pre:`if (${e} !== ${r}) return DEFER;
|
|
8
|
+
`}},v=(n,e,r)=>{if(!A(n)&&!(n.unmodelledRefinement||n.sourceText!==void 0)){if(Z.has(n.kind))return n.kind==="any"?{out:e,pre:""}:{out:e,pre:ee(n.kind,e)+te(n,e)};switch(n.kind){case"array":return re(n,e,r);case"literal":return ne(n,e);case"object":return se(n,e,r);default:return}}},re=(n,e,r)=>{const{inner:o}=n;if(!o)return;const a=r.next(),s=`__arr${String(a)}`,i=`__i${String(a)}`,c=`__e${String(a)}`,l=v(o,c,r);if(!l)return;const u=`if (!Array.isArray(${e})) return DEFER;
|
|
9
|
+
const ${s} = new Array(${e}.length);
|
|
10
|
+
for (let ${i} = 0; ${i} < ${e}.length; ${i}++) {
|
|
11
|
+
const ${c} = ${e}[${i}];
|
|
12
|
+
${l.pre}${s}[${i}] = ${l.out};
|
|
13
|
+
}
|
|
14
|
+
`;return{out:s,pre:u}},oe=(n,e,r,o)=>{const a=JSON.stringify(n);if(e.kind==="optional"){if(e.hasRefinement||e.sourceText!==void 0||A(e))return;const{inner:i}=e;if(!i)return;const c=v(i,r,o);if(!c)return;const l=o.next(),u=`__has${String(l)}`,d=`__val${String(l)}`,f=`let ${u} = false;
|
|
15
|
+
let ${d};
|
|
16
|
+
if (${r} !== undefined) {
|
|
17
|
+
${c.pre}${d} = ${c.out};
|
|
18
|
+
${u} = true;
|
|
19
|
+
}
|
|
20
|
+
`;return{entry:`...(${u} ? { ${a}: ${d} } : {})`,pre:f}}const s=v(e,r,o);if(s)return{entry:`${a}: ${s.out}`,pre:s.pre}},ae=new Set(Object.getOwnPropertyNames(Object.prototype)),_=(n,e,r)=>{let o="";const a=[];for(const s of Object.keys(n)){const i=n[s];if(!i)return;const c=JSON.stringify(s);let l=`${e}[${c}]`;if(ae.has(s)){const d=`__f${String(r.next())}`;o+=`const ${d} = Object.hasOwn(${e}, ${c}) ? ${e}[${c}] : undefined;
|
|
21
|
+
`,l=d}const u=oe(s,i,l,r);if(!u)return;o+=u.pre,a.push(u.entry)}return{entries:a.join(", "),pre:o}},T=n=>{const e=`Object.getPrototypeOf(${n})`;return`if (${e} !== Object.prototype && ${e} !== null) return DEFER;
|
|
22
|
+
`},se=(n,e,r)=>{const o=n.shape??{},a=_(o,e,r);if(!a)return;const s=r.next(),i=`__obj${String(s)}`,c=`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) return DEFER;
|
|
23
|
+
${T(e)}${a.pre}const ${i} = { ${a.entries} };
|
|
24
|
+
`;return{out:i,pre:c}},ie=n=>{let e=0;const o=_(n,"source",{next:()=>(e+=1,e)});if(o)return`(source) => {
|
|
25
|
+
if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER;
|
|
26
|
+
${T("source")}${o.pre}return { ${o.entries} };
|
|
27
|
+
}`},ce=(n,e)=>`lunora_${g(n)}_${String(e)}`,le=`const callRegistered = async <R>(context: CallerCtx, functionPath: string, args: Record<string, unknown> | undefined): Promise<R> => {
|
|
28
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
29
|
+
|
|
30
|
+
if (!registered) {
|
|
31
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A mutation is routed through the caller's own \`ctx.runMutation\` rather than
|
|
35
|
+
// invoked directly, so \`createCaller(ctx).ns.someMutation()\` gets exactly what
|
|
36
|
+
// \`ctx.runMutation(api.ns.someMutation)\` gets: the BEGIN/COMMIT span (or the
|
|
37
|
+
// enclosing one, when the caller is already inside a transaction), the jobs it
|
|
38
|
+
// schedules held until that span commits, and the deferred object deletes
|
|
39
|
+
// flushed only once it has. Called straight, a mutation composed from an action
|
|
40
|
+
// or a stream had none of the three — its writes autocommitted one row at a
|
|
41
|
+
// time and its \`ctx.scheduler\` calls dispatched immediately, so a mid-handler
|
|
42
|
+
// throw left the earlier writes durable and the job already enqueued.
|
|
43
|
+
//
|
|
44
|
+
// The fallback covers a context that is not a shard dispatch (\`runMutation\` is
|
|
45
|
+
// installed by \`buildCtx\` on every kind but a query's TYPE omits it); there is
|
|
46
|
+
// no transaction to join in that case, so a direct call is all there is.
|
|
47
|
+
//
|
|
48
|
+
// A query is routed through \`ctx.runQuery\` for the same reason: that is what
|
|
49
|
+
// hands it a query view of a mutation's or action's ctx (no request origin,
|
|
50
|
+
// query-guarded \`run*\`) instead of the caller's own.
|
|
51
|
+
if (registered.kind === "mutation" || registered.kind === "query") {
|
|
52
|
+
const run = (context as { runMutation?: unknown; runQuery?: unknown })[registered.kind === "mutation" ? "runMutation" : "runQuery"];
|
|
53
|
+
|
|
54
|
+
if (typeof run === "function") {
|
|
55
|
+
return (await run.call(context, { __lunoraRef: functionPath }, args ?? {})) as R;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return (await registered.handler(context, args ?? {})) as R;
|
|
60
|
+
};`,ue=(n,e,r=[],o=[])=>{const a=new Map,s=t=>{a.has(t)||a.set(t,ce(t,a.size))};for(const t of n)s(t.filePath);for(const t of e)s(t.filePath);for(const t of r)s(t.filePath);for(const t of o)s(t.filePath);const i=[...a.entries()].map(([t,m])=>{if(!J.test(t))throw new B("INTERNAL",`@lunora/codegen: refusing to emit import for unsafe file path: ${JSON.stringify(t)}`);return`import * as ${m} from "../${t}.js";`}).join(`
|
|
61
|
+
`),c=n.map(t=>` "${g(t.filePath)}:${t.exportName}": ${a.get(t.filePath)??""}.${t.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
62
|
+
`),l=e.map(t=>` ${JSON.stringify(t.id)}: ${a.get(t.filePath)??""}.${t.exportName} as unknown as RegisteredDataMigration,`).join(`
|
|
63
|
+
`),u=r.map(t=>` "${g(t.filePath)}:${t.exportName}": ${a.get(t.filePath)??""}.${t.exportName} as unknown as RegisteredLunoraFunction,`).join(`
|
|
64
|
+
`),d=o.map(t=>` "${t.exportName}": ${a.get(t.filePath)??""}.${t.exportName} as unknown as RegisteredShape,`).join(`
|
|
65
|
+
`),f=r.map(t=>`${g(t.filePath)}:${t.exportName}`),p=[c,u].filter(t=>t.length>0).join(`
|
|
66
|
+
`),R=n.map(t=>{if(t.lifecycle||Object.keys(t.args).length===0)return;const m=ie(t.args);return m===void 0?void 0:`installCompiledValidatorMap(${a.get(t.filePath)??""}.${t.exportName}.args, ${m});`}).filter(t=>t!==void 0).join(`
|
|
67
|
+
`);return{dispatchBody:p.length>0?`
|
|
68
|
+
${p}
|
|
69
|
+
`:"",importBlock:i.length>0?`${i}
|
|
70
|
+
|
|
71
|
+
`:"",installBlock:R,migrationBody:l.length>0?`
|
|
72
|
+
${l}
|
|
73
|
+
`:"",mutatorPaths:f,shapeBody:d.length>0?`
|
|
74
|
+
${d}
|
|
75
|
+
`:""}},de=n=>{const e=S(n,o=>{const a=O(G(o.args),o.filePath),s=a==="{}"?"?":"",i=O(X(o),o.filePath);return o.kind==="stream"?`${o.exportName}: (args${s}: ${a}) => Promise<AsyncIterable<${i}>>;`:`${o.exportName}: (args${s}: ${a}) => Promise<${i}>;`},"type");return{implementation:S(n,o=>`${z(o.exportName)}: (args) => callRegistered(context, "${g(o.filePath)}:${o.exportName}", args),`,"value"),types:e}},he=n=>{const e={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const r of n)r.lifecycle&&e[r.lifecycle].push(`${g(r.filePath)}:${r.exportName}`);return e},$e=n=>{const{agents:e=[],functions:r,migrations:o=[],mutators:a=[],shapes:s=[],useUmbrella:i=!1,usesSandbox:c=!1}=n,l=r.length>0,u=Q(i),{dispatchBody:d,importBlock:f,installBlock:p,migrationBody:R,mutatorPaths:t,shapeBody:m}=ue(r,o,a,s),b=V(e,r),w=W(c,r),k=[b.lines,w.lines].filter(h=>h.length>0).join(`
|
|
76
|
+
`);let N=d;k.length>0&&(N=d.length>0?`${d.trimEnd()}
|
|
77
|
+
${k}
|
|
78
|
+
`:`
|
|
79
|
+
${k}
|
|
80
|
+
`);const y=he(r),P=s.length>0?`import type { RegisteredShape } from "${u.server}";
|
|
81
|
+
`:"",L=s.length>0?`
|
|
82
|
+
/**
|
|
83
|
+
* Replication-shape registry — one entry per \`defineShape\` in \`lunora/shapes.ts\`.
|
|
84
|
+
* The generated ShardDO's \`resolveShape\` override looks a shape up by name and
|
|
85
|
+
* evaluates its trusted \`compileWhere(ctx, args)\` to authorize + scope a
|
|
86
|
+
* \`shape_subscribe\` (reads-as-permissions).
|
|
87
|
+
*/
|
|
88
|
+
export const LUNORA_SHAPES: Record<string, RegisteredShape> = {${m}};
|
|
89
|
+
`:"",E=t.length>0?`
|
|
90
|
+
/**
|
|
91
|
+
* Custom-mutator function paths — the \`LUNORA_FUNCTIONS\` keys the generated
|
|
92
|
+
* ShardDO's \`isCustomMutator\` override routes through the client-watermark push
|
|
93
|
+
* protocol (\`x-lunora-client-id\`/\`x-lunora-client-seq\` ordering).
|
|
94
|
+
*/
|
|
95
|
+
export const LUNORA_MUTATOR_PATHS: ReadonlySet<string> = new Set([${t.map(h=>JSON.stringify(h)).join(", ")}]);
|
|
96
|
+
`:"",C=p.length>0?`import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "${u.values}";
|
|
97
|
+
`:"",j=p.length>0?`
|
|
98
|
+
/**
|
|
99
|
+
* AOT-compiled argument validators (Worker-safe, no \`eval\`). Each is installed
|
|
100
|
+
* onto its function's live \`.args\` object and consulted by the interpreted
|
|
101
|
+
* parser as a zero-allocation fast path; anything it can't model is deferred.
|
|
102
|
+
*/
|
|
103
|
+
${p}
|
|
104
|
+
`:"",$=de(r),F=$.types?`
|
|
105
|
+
${$.types}
|
|
106
|
+
`:"",M=$.implementation?`
|
|
107
|
+
${$.implementation}
|
|
108
|
+
`:"",x=K($.types),D=x.length>0?`import type { ${x.join(", ")} } from "./dataModel.js";
|
|
109
|
+
`:"",I=l?"context":"_context",U=l?`${le}
|
|
110
|
+
|
|
111
|
+
`:"";return Y(`${q}${f}${b.importLine}${w.importLine}${C}${P}import { LunoraError } from "${u.server}";
|
|
112
|
+
import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js";
|
|
113
|
+
${D}
|
|
114
|
+
/**
|
|
115
|
+
* Single registered function, narrowed to the shape \`handleRpc\` needs.
|
|
116
|
+
* The real argument validators / return types are checked elsewhere — at
|
|
117
|
+
* the dispatch site we erase to \`unknown\` so a single map can host every
|
|
118
|
+
* registered function.
|
|
119
|
+
*/
|
|
120
|
+
export interface RegisteredLunoraFunction {
|
|
121
|
+
kind: "action" | "mutation" | "query" | "stream";
|
|
122
|
+
args: Record<string, unknown>;
|
|
123
|
+
/**
|
|
124
|
+
* Present on a \`"stream"\` declared \`durable\`: its run is persisted and
|
|
125
|
+
* survives the socket that opened it. Absent on every other kind, and on an
|
|
126
|
+
* ephemeral stream.
|
|
127
|
+
*/
|
|
128
|
+
durable?: { ttlMs?: number };
|
|
129
|
+
/**
|
|
130
|
+
* For \`"action" | "mutation" | "query"\` the handler is awaited and its result returned.
|
|
131
|
+
* For \`"stream"\` the handler returns an \`AsyncIterable\` synchronously and takes an
|
|
132
|
+
* \`AbortSignal\` as a third argument — the runtime drives it frame-by-frame.
|
|
133
|
+
*/
|
|
134
|
+
handler: ((context: unknown, args: Record<string, unknown>) => Promise<unknown> | unknown) | ((context: unknown, args: Record<string, unknown>, signal?: AbortSignal) => AsyncIterable<unknown>);
|
|
135
|
+
/**
|
|
136
|
+
* The lifecycle moment a hook fires on, when this registration came from
|
|
137
|
+
* \`onConnect\`/\`onDisconnect\`/\`onShardInit\`/\`onQueryChange\`/\`onWhisper\`.
|
|
138
|
+
* Read at dispatch to decide whether the function runs system-trusted:
|
|
139
|
+
* \`init\` and \`reactor\` have no caller identity, so RLS has no user to scope
|
|
140
|
+
* to. \`whisper\` does have one — it runs under the asking socket's identity.
|
|
141
|
+
*/
|
|
142
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "whisper";
|
|
143
|
+
/**
|
|
144
|
+
* Hoisted by the builder when the \`.use()\` chain carries a step with a
|
|
145
|
+
* per-dispatch effect — \`rateLimit(...)\` consuming budget, a single-use
|
|
146
|
+
* captcha token being burned. Read by \`isCacheableQuery\`: the chain runs
|
|
147
|
+
* inside the dispatch callback, and a reactive-cache HIT skips that
|
|
148
|
+
* callback, so such a query must never be memoized.
|
|
149
|
+
*/
|
|
150
|
+
perDispatch?: boolean;
|
|
151
|
+
/** \`"internal"\` functions are rejected on the external RPC path; absence === public. */
|
|
152
|
+
visibility?: "internal" | "public";
|
|
153
|
+
/**
|
|
154
|
+
* \`.x402({ price })\` tag on a paid public procedure. The origin worker
|
|
155
|
+
* paywalls it; the shard refuses to subscribe it (\`isPaidFunction\`).
|
|
156
|
+
*/
|
|
157
|
+
x402?: { readonly price: number | string };
|
|
158
|
+
}
|
|
159
|
+
${b.prelude}${w.prelude}
|
|
160
|
+
/**
|
|
161
|
+
* Static dispatch table. The key matches the \`__lunoraRef\` the client
|
|
162
|
+
* emits (\`api[namespace][fn].__lunoraRef === "namespace:fn"\`).
|
|
163
|
+
*/
|
|
164
|
+
export const LUNORA_FUNCTIONS: Record<string, RegisteredLunoraFunction> = {${N}};
|
|
165
|
+
${j}${L}${E}
|
|
166
|
+
/**
|
|
167
|
+
* Lifecycle manifest: the function paths the generated ShardDO dispatches when a
|
|
168
|
+
* client's WebSocket connects (\`connect\`) or disconnects (\`disconnect\`), once
|
|
169
|
+
* per Durable Object instance before any handler runs (\`init\`), after a
|
|
170
|
+
* write flush when a watched read's result changed (\`reactor\`), and before a
|
|
171
|
+
* socket joins or broadcasts to a whisper topic (\`whisper\`). Each path also
|
|
172
|
+
* resolves through {@link LUNORA_FUNCTIONS}. The socket-scoped moments run under
|
|
173
|
+
* the socket's verified identity; \`init\` and \`reactor\` have no caller, so they
|
|
174
|
+
* run anonymous — all via system dispatch.
|
|
175
|
+
*/
|
|
176
|
+
export const LUNORA_LIFECYCLE_HOOKS: {
|
|
177
|
+
connect: readonly string[];
|
|
178
|
+
disconnect: readonly string[];
|
|
179
|
+
init: readonly string[];
|
|
180
|
+
reactor: readonly string[];
|
|
181
|
+
whisper: readonly string[];
|
|
182
|
+
} = {
|
|
183
|
+
connect: [${y.connect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
184
|
+
disconnect: [${y.disconnect.map(h=>JSON.stringify(h)).join(", ")}],
|
|
185
|
+
init: [${y.init.map(h=>JSON.stringify(h)).join(", ")}],
|
|
186
|
+
reactor: [${y.reactor.map(h=>JSON.stringify(h)).join(", ")}],
|
|
187
|
+
whisper: [${y.whisper.map(h=>JSON.stringify(h)).join(", ")}],
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Resolve and invoke a registered function from an external caller. Throws a
|
|
192
|
+
* LunoraError-shaped object (404) when the path is unknown — the runtime's
|
|
193
|
+
* structural error mapper turns that into the right HTTP status. Internal
|
|
194
|
+
* functions are treated as not-found so their existence never leaks to clients.
|
|
195
|
+
*/
|
|
196
|
+
export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record<string, unknown>): Promise<unknown> => {
|
|
197
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
198
|
+
|
|
199
|
+
if (!registered || registered.visibility === "internal") {
|
|
200
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return registered.handler(context, args);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* A handler context accepted by {@link createCaller}. The runtime context the
|
|
208
|
+
* shard DO builds is uniform across kinds, so any handler's \`ctx\` works here.
|
|
209
|
+
*/
|
|
210
|
+
export type CallerCtx = ActionCtx | MutationCtx | QueryCtx;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Typed, in-process server-to-server caller. Every registered function — public
|
|
214
|
+
* *and* internal — is reachable; each call dispatches against the same shard
|
|
215
|
+
* with the supplied \`context\`, exactly like \`ctx.runQuery\`/\`runMutation\`/
|
|
216
|
+
* \`runAction\` but without re-stating the function path.
|
|
217
|
+
*/
|
|
218
|
+
export interface Caller {${F}}
|
|
219
|
+
|
|
220
|
+
${U}/** Build a {@link Caller} bound to \`context\` (typically a handler's \`ctx\`). */
|
|
221
|
+
export const createCaller = (${I}: CallerCtx): Caller => ({${M}});
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Single registered data migration, narrowed to the shape the per-shard runner
|
|
225
|
+
* consumes. \`up\`/\`down\` are erased to a structural transform; the authoring
|
|
226
|
+
* validation lives in \`defineMigration\`.
|
|
227
|
+
*/
|
|
228
|
+
export interface RegisteredDataMigration {
|
|
229
|
+
batchSize?: number;
|
|
230
|
+
down?: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
231
|
+
id: string;
|
|
232
|
+
table: string;
|
|
233
|
+
up: (document: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Registry of online data migrations keyed by \`defineMigration\`'s \`id\`. The
|
|
238
|
+
* shard DO's admin RPC and the CLI resolve migrations to run through this map.
|
|
239
|
+
*/
|
|
240
|
+
export const LUNORA_MIGRATIONS: Record<string, RegisteredDataMigration> = {${R}};
|
|
241
|
+
`,i)};export{$e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./CAPABILITY_PROBES-brcmKenl.mjs";import"./ir-DBSvhNa-.mjs";import{e}from"./server-DSUfd6Tc.mjs";import"./shared-DnCokNcE.mjs";export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-BTfJuEeP.mjs";import"./shard-runtime-CkaEBSdL.mjs";import"./shared-DnCokNcE.mjs";export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s}from"ts-morph";import{b as t,d as c}from"./attribution-DqqCSywo.mjs";import{c as n}from"./classify-procedure-call-HrUyDQX0.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-CiIyKqhF.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as i}from"@lunora/advisor";const d=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],l=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},m=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:l(e),fields:Object.keys(e.shape),indexes:d(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),u=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),f=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:t,shapes:o,...a}=n;return{...a,argValidators:e,mutators:r===void 0?void 0:u(r),queries:s??[],schema:m(t),shapes:o===void 0?void 0:c(o)}},p=n=>i(f(n),{source:"static"}),v=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
|
|
2
|
+
`)};export{v as formatAdvisories,p as lintSchema,f as toAdvisorContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-CiIyKqhF.mjs";import{r as v,d as b}from"./attribution-DqqCSywo.mjs";const h=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:h(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=b(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-CiIyKqhF.mjs";import{b as m,d as p}from"./attribution-DqqCSywo.mjs";import{t as d}from"./database-calls-CBlsQTga.mjs";import{w as g,c as h}from"./classify-procedure-call-HrUyDQX0.mjs";import{a as k}from"./project-config-file-Bv2l-Kmm.mjs";const l=e=>{if(!(!i.isPropertyAssignment(e)&&!i.isShorthandPropertyAssignment(e)&&!i.isMethodDeclaration(e)&&!i.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=l(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=h(t);if(!r)return;const o=r.receiver?y(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},E=(e,s)=>{const t=[];for(const r of u(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=f(s,r);for(const a of m(o)){const c=b(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=s=>s.filter(o=>o.topic===void 0),e=(s,o)=>s.filter(i=>i.topic===o),a=s=>typeof s.shardMode=="object"&&s.shardMode.kind==="shardBy";export{a as i,t as p,e as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=l=>l.shardMode==="global"&&l.globalBackend!=="hyperdrive",o=l=>l.shardMode==="global"&&l.globalBackend==="hyperdrive";export{e as isD1GlobalTable,o as isHyperdriveGlobalTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as h,statSync as P,readdirSync as A,realpathSync as D,lstatSync as C}from"node:fs";import{dirname as f,join as g,relative as F,sep as w,resolve as k,extname as O,basename as j}from"node:path";import{findUpSync as z,FIND_UP_STOP as V,matcher as K}from"@visulima/fs";import{SyntaxKind as p,Node as i,VariableDeclarationKind as $}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{p as U,a as B,r as W}from"./project-config-file-Bv2l-Kmm.mjs";import{findProjectConfigFile as N}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const X=/\.ts$/u,d=(e,t)=>F(e,t).split(w).join("/").replace(X,""),G=new Set(["_generated","node_modules"]),_=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),L=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,Se=e=>{const t=e.split("/");return L.test(t.at(-1)??"")||t.slice(0,-1).some(s=>_.has(s))},E=(e,t,s)=>t?G.has(e)||!s&&_.has(e):!s&&L.test(e),v=new Map,m=()=>!1,H=e=>{const t=z(a=>N(a)??(h(g(a,"package.json"))||h(g(a,".git"))?V:void 0),{cwd:f(k(e))}),s=t===void 0?void 0:P(t,{throwIfNoEntry:!1});if(t===void 0||s===void 0)return m;const n=`${String(s.mtimeMs)}:${String(s.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=W(f(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?K(o.exclude):m;return v.set(t,{isExcluded:c,key:n}),c},Y=(e,t,s)=>e==="schema.ts"&&t===s,q=e=>{try{return P(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,s,n,r)=>{let o,c;try{o=A(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const a of o){const u=g(e,a),l=q(u);l===void 0||r(a,F(s,u).split(w).join("/"),l.isDirectory())||(l.isDirectory()?R(u,t,s,n,r):l.isFile()&&O(a)===".ts"&&!Y(a,e,s)&&t.push(u))}return t},T=(e,t={})=>{const s=t.includeSkipped??!1,n=s?m:H(e);return R(e,[],e,new Set,(r,o,c)=>E(r,c,s)||n(o))},Q=["src/server","src/index.ts","src/worker.ts"],J=new Set([".ts",".tsx"]),b=(e,t=[])=>{let s;try{s=C(e)}catch{return t}if(s.isFile())return J.has(O(e))&&!E(j(e),!1,!1)&&t.push(e),t;if(!s.isDirectory())return t;for(const n of A(e))E(n,!0,!1)||b(g(e,n),t);return t},Z=e=>{const t=f(e),s=T(e).map(o=>({displayPath:d(e,o),filePath:o})),n=new Set(s.map(o=>o.filePath)),r=N(t);for(const o of[...Q.flatMap(c=>b(g(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),s.push({displayPath:d(t,o),filePath:o}));return s},ee=e=>Array.isArray(e),I=(e,t,s,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const a=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of a.getDescendantsOfKind(s)){const l=n(u,o);ee(l)?r.push(...l):l!==void 0&&r.push(l)}}return r},te=e=>T(e).map(t=>({displayPath:d(e,t),filePath:t})),se=(e,t,s,n)=>I(e,te(t),s,n),he=(e,t,s)=>se(e,t,p.CallExpression,s),ve=(e,t,s)=>I(e,Z(t),p.CallExpression,s),ye=e=>U(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(s=>!i.isSpreadAssignment(s)&&B(s)===t),Pe=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:void 0}const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const n=S(s,"handler");if(!n||!i.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:void 0},Ae=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=S(e,t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},ie=e=>{const t=e?.getParent();return i.isVariableDeclaration(e)&&i.isVariableDeclarationList(t)&&t.getDeclarationKind()===$.Const},ne=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isParenthesizedExpression(s)||i.isAsExpression(s)||i.isSatisfiesExpression(s)||i.isTypeAssertion(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();return t},y=e=>{const t=ne(e),s=t.getParent();if(s===void 0)return!1;if(i.isBinaryExpression(s)){const r=s.getOperatorToken().getKind();return s.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s)){const r=s.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return i.isDeleteExpression(s)?!0:i.isForOfStatement(s)||i.isForInStatement(s)?s.getInitializer()===t:i.isPropertyAssignment(s)?s.getInitializer()===t&&y(s):(i.isShorthandPropertyAssignment(s)||i.isSpreadAssignment(s)||i.isSpreadElement(s)||i.isObjectLiteralExpression(s)||i.isArrayLiteralExpression(s))&&y(s)},re=e=>{const t=e?.getDeclarations().find(n=>i.isVariableDeclaration(n));if(!ie(t))return;const s=t.getParent().getParent();return i.isVariableStatement(s)&&i.isSourceFile(s.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Fe=e=>{if(!e)return;if(i.isObjectLiteralExpression(e))return e;if(!i.isIdentifier(e))return;const t=oe(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},x=e=>{let t=e;for(;t&&(i.isAsExpression(t)||i.isSatisfiesExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let s=x(e);for(;i.isAwaitExpression(s)||i.isPropertyAccessExpression(s)||i.isElementAccessExpression(s)||i.isCallExpression(s);){const n=i.isCallExpression(s)?t?.(s):void 0;if(n!==void 0)return{verdict:n};s=x(s.getExpression())}return{root:s}},we=e=>ce(e).root,Oe=e=>i.isArrowFunction(e)||i.isConstructorDeclaration(e)||i.isFunctionDeclaration(e)||i.isFunctionExpression(e)||i.isGetAccessorDeclaration(e)||i.isMethodDeclaration(e)||i.isSetAccessorDeclaration(e),Ne=(e,t)=>e?.compilerNode===t.compilerNode,_e=e=>{if(i.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=i.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return i.isElementAccessExpression(e)&&i.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Le=e=>{const t=e.getParent();return i.isReturnStatement(t)||i.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>i.isFunctionLikeDeclaration(n)||i.isArrowFunction(n)):void 0},Re=e=>{const t=x(e);return t&&i.isCallExpression(t)?t:void 0},Te=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const s=t.getExpression();if(!i.isIdentifier(s))return s;const n=s.getSymbol()?.getValueDeclaration();return n&&i.isVariableDeclaration(n)?n.getInitializer():s},be=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!i.isObjectLiteralExpression(e))return;const s=S(e,t);if(!s||!i.isPropertyAssignment(s))return;const n=s.getInitializer();return n&&i.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&i.isObjectLiteralExpression(n)?n:void 0},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?ae(e):void 0},Ce=e=>(t,s,n)=>{if(i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${s}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),ke=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();return i.isIdentifier(s)&&le.has(s.getText())&&t.length>=2?t:void 0},je=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{ke as RUN_METHODS,X as TS_EXTENSION_RE,ye as bindingKeyName,we as chainRootOf,he as collectCallRows,se as collectNodeRows,ve as collectSecurityCallRows,Te as defaultExportExpression,S as findObjectProperty,je as functionKeyOf,ue as functionReferenceSegments,Pe as handlerOf,ie as isConstDeclaration,Oe as isFunctionLike,Ne as isSameNode,Se as isTestPath,y as isWriteTarget,be as limitNameOf,T as listLunoraSourceFiles,Z as listSecurityScanFiles,d as lunoraRelativePath,_e as memberAccessOf,De as objectLiteralFromCallbackBody,Fe as optionsObjectLiteral,ne as outermostValueWrapper,Ae as propertyInitializer,B as propertyKeyName,U as propertyNameText,Le as returningFunctionOf,Ce as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,x as unwrapExpression,Re as unwrapToCallExpression,ce as walkChain};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const g=/[^a-zA-Z0-9]+/gu,T=/([a-z0-9])([A-Z])/gu,p=t=>t.split(g).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),R=t=>t.replaceAll(T,"$1_$2").replaceAll(g,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),j=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},I=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),E=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),C=["$","{","'","$","'","}"].join(""),x=t=>E(t).split("$").join(C),z=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,b=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>b(s,e+1))})},N=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),P=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>A(o,n+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...P(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return N(o,s,r.length)},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...w(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),h=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?h.some(i=>b(i))&&n.nullable.push(c):n.optional.push(c);for(const i of h)y(i,c,n,r+1)}for(const a of w(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},k=(t,e)=>t.join("\0").localeCompare(e.join("\0")),q=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(k);return{nullable:n(e.nullable),optional:n(e.optional)}},$=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:q(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:j(t["x-lunora-function-kind"])}},H=t=>{const e=new Map;for(const n of t.methods){const r=$(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},U=t=>t.methods.flatMap(e=>{const n=$(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),L=/^[A-Za-z][A-Za-z0-9]*$/u,S=t=>L.test(t),D=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!S(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},W=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!S(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),D(n)}},Z=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},M=t=>t.flatMap(e=>e.methods),F=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],_=/^\s*(?:#|\/\/|\/\*|\*)/u,v=t=>t.split(`
|
|
3
|
+
`).filter(e=>!_.test(e)).join(`
|
|
4
|
+
`),O=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),G=(t,e)=>{const n=v(e),r=o=>o!==void 0&&O(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},B=t=>t.methods.filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),V=(t,e)=>{const n=v(e);return[...new Set(M(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!O(n,r)))].toSorted((r,o)=>r.localeCompare(o))},K=t=>[...new Set(M(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{M as allMethods,z as argsChoice,Z as assertDistinctMembers,W as assertGeneratable,I as commentText,F as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,x as kotlinLiteral,U as modelSources,q as nullPathsOf,$ as parseMethod,H as parseSpec,K as referencedModels,E as stringLiteral,p as toPascalCase,R as toSnakeCase,V as undeclaredModels,B as unrepresentableFunctions,j as verbForKind,G as withDeclaredModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(r,s)=>`JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${s}`;export{a as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as o,b as a,r as t}from"./project-config-file-Bv2l-Kmm.mjs";import{PROJECT_CONFIG_FILENAMES as i,findProjectConfigFile as l}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";export{i as PROJECT_CONFIG_FILENAMES,l as findProjectConfigFile,o as loadProjectConfig,a as readMergeDurableObjects,t as readProjectConfigLiterals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{t as a,o as b,E as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-CiIyKqhF.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{Node as i,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as b}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as E}from"./project-config-file-Bv2l-Kmm.mjs";let f;const z=e=>{f=e},A=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),k=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},N=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),T=new Set(["strip"]),l=new Set,g=new Set,S=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&i.isShorthandPropertyAssignment(r)){const n=r.getValueSymbol();r=(n?.getAliasedSymbol()??n)?.getValueDeclaration()}if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},L=e=>{const t=e.getParent();return!i.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(i.isParenthesizedExpression(e)||i.isAsExpression(e)||i.isSatisfiesExpression(e))return u(e.getExpression());if(i.isObjectLiteralExpression(e))return e;if(i.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),n=r!==void 0&&i.isPropertyAssignment(r)?r.getInitializer():void 0;return n===void 0?void 0:u(n)}if(!i.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!L(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===w},c=e=>{if(i.isIdentifier(e)&&!l.has(e)){const t=S(e);if(t!==void 0&&D(t)){l.add(e);try{return c(t)}finally{l.delete(e)}}}return i.isCallExpression(e)?$(e):{kind:"any",sourceText:e.getText()}},R=e=>{const t=u(e.getExpression());if(t===void 0||g.has(t))return{};g.add(t);try{return v(t)}finally{g.delete(t)}},V=e=>{throw b(e,`computed property name ${e.getText()} must be a string literal — codegen resolves object keys statically.`)},v=e=>{const t={};for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const s=n?r.getNameNode():r.getInitializer();if(!s)continue;const a=r.getNameNode(),o=E(a)??V(a);if(!A.test(o))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(o)}`);t[o]=c(s)}return t},d=(e,t)=>e&&i.isExpression(e)?c(e):t,x=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),O=e=>{const t=e&&f?f(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},M=(e,t,r)=>{if(N.has(e))return{kind:e};const[n,s]=t;switch(e){case"array":return{inner:d(n,{kind:"any"}),kind:"array"};case"from":return O(n);case"id":{if(!n||!i.isStringLiteral(n))throw b(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:x(n)};case"object":return n&&i.isObjectLiteralExpression(n)?{kind:"object",shape:v(n)}:{kind:"object",shape:{}};case"optional":return{inner:d(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(n,{kind:"string"}),kind:"record",valueType:d(s,{kind:"any"})};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>i.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},P=e=>{const[t]=e;if(e.length!==1||t===void 0||!i.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},$=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||T.has(r)){const s=t.getExpression(),a=i.isExpression(s)?c(s):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const o=r==="max"&&a.kind==="string"?P(n):void 0;return o!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??o,o)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return M(r,n,e)};export{c as a,v as p,u as r,z as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as x,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as S}from"jiti";import{Node as i,Project as E}from"ts-morph";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const j=t=>{if(i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)||i.isNumericLiteral(t))return t.getLiteralText();if(i.isComputedPropertyName(t)){const r=t.getExpression();return i.isStringLiteral(r)||i.isNoSubstitutionTemplateLiteral(r)?r.getLiteralText():void 0}return t.getText()},h=t=>j(t)??t.getText(),d=t=>h(t.getNameNode()),m=new Map,J=async t=>{const r=v(t);if(r===void 0)return{};let e;try{const a=x(r);e=`${String(a.mtimeMs)}:${String(a.size)}`}catch{return{}}const s=m.get(r);if(s?.key===e)return s.value;const n=(async()=>{try{const l=(await S(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:l!==null&&typeof l=="object"?l:void 0}}catch(a){return{error:a instanceof Error?a.message:String(a)}}})();return m.set(r,{key:e,value:n}),n},O=t=>{let e=t.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&i.isIdentifier(e))for(e=t.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(i.isSatisfiesExpression(e)||i.isAsExpression(e));)e=e.getExpression();return e!==void 0&&i.isObjectLiteralExpression(e)?e:void 0},c=(t,r)=>i.isPropertyAssignment(t)?t.getInitializer():r.getVariableDeclaration(d(t))?.getInitializer(),g=t=>{let r=t;for(;r!==void 0&&(i.isSatisfiesExpression(r)||i.isAsExpression(r)||i.isParenthesizedExpression(r));)r=r.getExpression();return r},b=(t,r,e)=>{const s=g(t);if(s===void 0||!i.isObjectLiteralExpression(s))return{unreadable:!0};const n=s.getProperties(),a=n.filter(u=>i.isPropertyAssignment(u)&&!i.isComputedPropertyName(u.getNameNode())||i.isShorthandPropertyAssignment(u));if(a.length!==n.length)return{unreadable:!0};const l=a.find(u=>d(u)===e);if(l===void 0)return{absent:!0};const o=c(l,r);return o===void 0?{unreadable:!0}:{literal:o}},A=(t,r)=>{const e=b(t,r,"minSeverity");return"absent"in e?{advisor:{}}:"literal"in e&&i.isStringLiteral(e.literal)?{advisor:{minSeverity:e.literal.getLiteralValue()}}:{advisor:{unreadable:!0}}},N=(t,r)=>{const e=b(t,r,"exclude");if("absent"in e)return{codegen:{}};if(!("literal"in e)||!i.isArrayLiteralExpression(e.literal))return{codegen:{unreadable:!0}};const s=[];for(const n of e.literal.getElements()){if(!i.isStringLiteral(n)&&!i.isNoSubstitutionTemplateLiteral(n)||n.getLiteralValue().startsWith("!"))return{codegen:{unreadable:!0}};s.push(n.getLiteralValue())}return{codegen:{exclude:s}}},T=(t,r)=>{const e=b(t,r,"merge");return"absent"in e?{durableObjects:{}}:"literal"in e&&(i.isTrueLiteral(e.literal)||i.isFalseLiteral(e.literal))?{durableObjects:{merge:e.literal.getLiteralValue()}}:{durableObjects:{unreadable:!0}}},w=new Map([["advisor",{advisor:{unreadable:!0}}],["codegen",{codegen:{unreadable:!0}}],["durableObjects",{durableObjects:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),L=(t,r)=>{const e=t.getProperty(r);if(e!==void 0)return(i.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},p=(t,r)=>{const e=L(t,r);if(e!==void 0)return e!=="unreadable"&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},z=t=>{const r=L(t,"rpc");if(r!==void 0)return r!=="unreadable"&&i.isFalseLiteral(r)?!1:"unreadable"},C=t=>{const r=g(t);if(r===void 0||!i.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const s of r.getProperties()){if(!i.isPropertyAssignment(s)||i.isComputedPropertyName(s.getNameNode()))return{services:{unreadable:!0}};const n=g(s.getInitializer());if(n===void 0||!i.isObjectLiteralExpression(n)||n.getProperties().some(u=>!i.isPropertyAssignment(u)))return{services:{unreadable:!0}};const a=p(n,"dir"),l=p(n,"entrypoint"),o=z(n);if(typeof a!="string"||l===!1||o==="unreadable")return{services:{unreadable:!0}};e[d(s)]={dir:a,...l===void 0?{}:{entrypoint:l},...o===void 0?{}:{rpc:o}}}return{services:{declared:e}}},D=(t,r)=>{if(i.isGetAccessorDeclaration(t)||i.isMethodDeclaration(t))return w.get(d(t))??{};if(!i.isPropertyAssignment(t)&&!i.isShorthandPropertyAssignment(t))return{};const e=d(t);if(e==="advisor")return A(c(t,r),r);if(e==="services")return C(c(t,r));if(e==="codegen")return N(c(t,r),r);if(e==="durableObjects")return T(c(t,r),r);if(e!=="target"&&e!=="remote")return{};const s=c(t,r);return s===void 0?{unreadable:!0}:e==="target"?i.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:i.isTrueLiteral(s)||i.isFalseLiteral(s)?{remote:s.getLiteralValue()}:i.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},M=t=>{const r=v(t);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const n=new E({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(P(r),e,{overwrite:!0}),a=O(n);if(a===void 0)return{unreadable:!0};if(a.getProperties().some(o=>i.isSpreadAssignment(o))){const o=u=>a.getProperties().some(f=>!i.isSpreadAssignment(f)&&d(f)===u);return{...o("advisor")?{advisor:{unreadable:!0}}:{},...o("codegen")?{codegen:{unreadable:!0}}:{},...o("durableObjects")?{durableObjects:{unreadable:!0}}:{},...o("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let l={};for(const o of a.getProperties())l={...l,...D(o,n)};return l},$=t=>{const{durableObjects:r}=M(t);return r?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),r?.merge===!0};export{d as a,$ as b,J as l,h as p,M as r,j as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DnCokNcE.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{O as a,M as b,U as c,v as r};
|