@lunora/codegen 1.0.0-alpha.26 → 1.0.0-alpha.261

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.
Files changed (118) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +3851 -1254
  4. package/dist/index.d.ts +3851 -1254
  5. package/dist/index.mjs +1 -34
  6. package/dist/packem_shared/AGENTS_FILENAME-UhIaG4BZ.mjs +1 -0
  7. package/dist/packem_shared/CAPABILITY_PROBES-DFsutD7g.mjs +25 -0
  8. package/dist/packem_shared/CONTAINERS_FILENAME-DhUL5rDc.mjs +1 -0
  9. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_TARGET-7sHexLjO.mjs +1 -0
  11. package/dist/packem_shared/FLAGS_FILENAME-BINQ51Zq.mjs +1 -0
  12. package/dist/packem_shared/GENERATED_HEADER-dFyrHgQ0.mjs +1 -0
  13. package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
  14. package/dist/packem_shared/MUTATORS_FILENAME-D1Q6EUII.mjs +1 -0
  15. package/dist/packem_shared/NOTIFY_FILENAME-bbHHFQ_t.mjs +1 -0
  16. package/dist/packem_shared/OPENRPC_VERSION-CGu1_YK7.mjs +3 -0
  17. package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
  18. package/dist/packem_shared/QUEUES_FILENAME-CSLmXUQA.mjs +1 -0
  19. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BVhRHIbS.mjs +11 -0
  20. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
  21. package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
  22. package/dist/packem_shared/SHAPES_FILENAME-DuR5hLW1.mjs +1 -0
  23. package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
  24. package/dist/packem_shared/WORKFLOWS_FILENAME-IqUyMQgM.mjs +1 -0
  25. package/dist/packem_shared/attribution-sW_DHmLO.mjs +1 -0
  26. package/dist/packem_shared/buildOpenApiDocument-DOsv1HEF.mjs +3 -0
  27. package/dist/packem_shared/capabilitiesUsedBy-CzqyN9dX.mjs +1 -0
  28. package/dist/packem_shared/chain-BTbLDrrU.mjs +1 -0
  29. package/dist/packem_shared/classify-procedure-call-OnJoKgqu.mjs +1 -0
  30. package/dist/packem_shared/context-property-calls-BEBjylgc.mjs +1 -0
  31. package/dist/packem_shared/context-root-KWXRWlv6.mjs +1 -0
  32. package/dist/packem_shared/database-calls-rLPCL3-U.mjs +1 -0
  33. package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
  34. package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
  35. package/dist/packem_shared/discoverAuthApiCalls-CNj9-Jch.mjs +1 -0
  36. package/dist/packem_shared/discoverCrons-BqTY53L5.mjs +1 -0
  37. package/dist/packem_shared/discoverFunctions-DPH4drkg.mjs +1 -0
  38. package/dist/packem_shared/discoverHttpRoutes-MRFziTCb.mjs +1 -0
  39. package/dist/packem_shared/discoverHyperdriveCalls-BcVkR6nw.mjs +1 -0
  40. package/dist/packem_shared/discoverInserts-Duz40u-s.mjs +1 -0
  41. package/dist/packem_shared/discoverMaskProcedures-DYJhbHF3.mjs +1 -0
  42. package/dist/packem_shared/discoverMigrations-D2P2n7JE.mjs +1 -0
  43. package/dist/packem_shared/discoverNondeterministicCalls-Cxf6T2Oi.mjs +1 -0
  44. package/dist/packem_shared/discoverQueries-CWmNPVHm.mjs +1 -0
  45. package/dist/packem_shared/discoverR2sqlCalls-DnKwop5c.mjs +1 -0
  46. package/dist/packem_shared/discoverRlsMetadata-BXXEFXjf.mjs +1 -0
  47. package/dist/packem_shared/discoverRlsProcedures-Des596JU.mjs +1 -0
  48. package/dist/packem_shared/discoverSandboxUsage-Bjl8A_hj.mjs +1 -0
  49. package/dist/packem_shared/discoverSchema-Cd3iH6q5.mjs +1 -0
  50. package/dist/packem_shared/discoverStorageRulesMetadata-DGFonj0I.mjs +1 -0
  51. package/dist/packem_shared/emitAgents-Dotqck8w.mjs +1 -0
  52. package/dist/packem_shared/emitApi-xDIHPRPH.mjs +154 -0
  53. package/dist/packem_shared/emitApp-RNU41dtm.mjs +860 -0
  54. package/dist/packem_shared/emitCrons-DsXsg1uG.mjs +83 -0
  55. package/dist/packem_shared/emitDataModel-DSk9AkJe.mjs +113 -0
  56. package/dist/packem_shared/emitDrizzleSchema-DohtnI8c.mjs +15 -0
  57. package/dist/packem_shared/emitFunctions-evl8Mx1a.mjs +249 -0
  58. package/dist/packem_shared/emitServer-DymRagL2.mjs +368 -0
  59. package/dist/packem_shared/emitShard-DHMYSP4m.mjs +1 -0
  60. package/dist/packem_shared/exported-procedure-chains-58yS9zc8.mjs +1 -0
  61. package/dist/packem_shared/fingerprintSchemaSources-BzFVnBfa.mjs +1 -0
  62. package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
  63. package/dist/packem_shared/handler-reference-C1oBljnl.mjs +1 -0
  64. package/dist/packem_shared/index-BusOvbeQ.mjs +1 -0
  65. package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
  66. package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
  67. package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
  68. package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
  69. package/dist/packem_shared/listLunoraSourceFiles-DRes9d5p.mjs +1 -0
  70. package/dist/packem_shared/loadProjectConfig-CuGQsqYS.mjs +1 -0
  71. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  72. package/dist/packem_shared/modules-CsA-QVJ6.mjs +1 -0
  73. package/dist/packem_shared/parse-validator-B4mFs19C.mjs +1 -0
  74. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  75. package/dist/packem_shared/qualifiers-Cw8dEDbh.mjs +1 -0
  76. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  77. package/dist/packem_shared/readServiceBindings-CnvEGOir.mjs +1 -0
  78. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  79. package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
  80. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  81. package/dist/packem_shared/shard-WXSIZRpD.mjs +1438 -0
  82. package/dist/packem_shared/shard-runtime-B1nU9CRa.mjs +321 -0
  83. package/dist/packem_shared/shared-BXUKWh7t.mjs +9 -0
  84. package/dist/packem_shared/unwrap-handler-return-D7E2TKkS.mjs +1 -0
  85. package/package.json +16 -7
  86. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  87. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  88. package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
  89. package/dist/packem_shared/GENERATED_HEADER-CYaSI_qY.mjs +0 -3268
  90. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  91. package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
  92. package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
  93. package/dist/packem_shared/OPENRPC_VERSION-CRe5l79E.mjs +0 -60
  94. package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
  95. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-cgOjZTVY.mjs +0 -1137
  96. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
  97. package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
  98. package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
  99. package/dist/packem_shared/buildOpenApiDocument-BlpXQe2K.mjs +0 -183
  100. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  101. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  102. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  103. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  104. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  105. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  106. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  107. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  108. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  109. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  110. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  111. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  112. package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
  113. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  114. package/dist/packem_shared/emitApp-C38fHt_1.mjs +0 -675
  115. package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
  116. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  117. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  118. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,368 @@
1
+ import{relative as ve,isAbsolute as ke,sep as we}from"node:path";import{LunoraError as V}from"@lunora/errors";import{CAPABILITIES as Ie}from"./CAPABILITY_PROBES-DFsutD7g.mjs";import{p as $e}from"./ir-DBSvhNa-.mjs";import{a as p,G as Be,u as Re,d as Oe}from"./shared-BXUKWh7t.mjs";const Ne=/\.([cm]?)tsx?$/u,Me=(d,l=[])=>{const r=new Set;for(const t of d.tables)for(const i of Object.values(t.shape)){const n=Re(i);n.kind==="storage"&&typeof n.bucket=="string"&&n.bucket!==""&&r.add(n.bucket)}for(const t of l)t!==""&&t!=="default"&&r.add(t);return["default",...[...r].toSorted((t,i)=>t.localeCompare(i))]},Qe=({agents:d=[],capabilities:l=new Set,containers:r=[],env:t,hasVectors:i=!0,hasFlags:n=!1,hasNotify:_=!1,identity:s,queues:R=[],schema:O,generatedDirectory:N="",services:y=[],storageRuleBuckets:H=[],topics:M=[],useUmbrella:z=!1,workflows:C=[]}={})=>{const o=Oe(z),U=Me(O??{tables:[]},H).map(e=>JSON.stringify(e)).join(" | "),D=e=>e.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",J=[...new Set(r.map(e=>D(e)))].toSorted((e,a)=>e.localeCompare(a)),K=r.length>0?`import type { ${J.join(", ")} } from "@lunora/container";
2
+ `:"",Y=r.length>0?`
3
+ readonly containers: {${r.map(e=>`
4
+ readonly ${e.exportName}: ${D(e)};`).join("")}
5
+ };`:"",A=[...l.has("ai")?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...r.map(e=>(p(e.bindingName,`container binding "${e.bindingName}"`),` /** Durable Object namespace for the \`${e.exportName}\` container. */
6
+ readonly ${e.bindingName}?: unknown;`)),...R.map(e=>(p(e.bindingName,`queue binding "${e.bindingName}"`),` /** Queue producer binding for the \`${e.exportName}\` queue. */
7
+ readonly ${e.bindingName}?: unknown;`))].join(`
8
+ `),X=`
9
+
10
+ /**
11
+ * This project's Cloudflare bindings, as far as codegen can discover them from
12
+ * \`lunora/\` source — the container/workflow Durable Object namespaces and the
13
+ * conventional Workers AI binding. Bindings the config layer reconciles from
14
+ * user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
15
+ * visible here, so the open index signature keeps them reachable (cast at the
16
+ * use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
17
+ * under this signature too — Lunora can't type a third-party worker's RPC
18
+ * surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
19
+ */
20
+ export interface CloudflareBindings {
21
+ readonly [binding: string]: unknown;${A?`
22
+ ${A}`:""}
23
+ }
24
+
25
+ /** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
26
+ export type Env = CloudflareBindings;`,S=e=>Ie.map(a=>a.tier!==void 0&&e.includes(a.tier)&&l.has(a.key)?a.serverCtxField:"").join(""),W=S(["every"]),Z=S(["every","action"]),c=i&&(O?.vectorIndexes.length??0)>0,m=c?' | "vectors"':"",F=c?`
27
+ readonly vectors: VectorSearch<VectorIndexName>;`:"",ee=c?`
28
+ readonly vectors: VectorSearchReader<VectorIndexName>;`:"",te=c?`import type { VectorSearch, VectorSearchReader } from "${o.server}";
29
+ import type { VectorIndexName } from "./dataModel.js";
30
+ `:"",h=n?`
31
+ /** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
32
+ readonly flags: import("${o.flags}").LunoraFlags;`:"",b=_?`
33
+ /** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
34
+ readonly notify: import("@lunora/notify").LunoraNotify;
35
+ /** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
36
+ readonly push: import("@lunora/notify").LunoraPush;`:"",u=C.length>0,ae=u?`import type { WorkflowHandle } from "@lunora/workflow";
37
+ import type * as lunoraWorkflowDefinitions from "../workflows.js";
38
+ `:"",re=u?`
39
+
40
+ /** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
41
+ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
42
+ ? unknown extends Params
43
+ ? Record<string, unknown>
44
+ : NonNullable<Params>
45
+ : Record<string, unknown>;
46
+
47
+ /** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
48
+ export interface LunoraWorkflows {
49
+ ${C.map(e=>` get(name: ${JSON.stringify(e.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${e.exportName}>>;`).join(`
50
+ `)}
51
+ }`:"",Q=u?' | "workflows"':"",j=u?`
52
+ readonly workflows: LunoraWorkflows;`:"",P=$e(R),f=P.length>0,x=M.length>0,g=[...f?["QueueProducer"]:[],...x?["TopicPublisher"]:[]],oe=g.length>0?`import type { ${g.join(", ")} } from "@lunora/queue";
53
+ import type * as lunoraQueueDefinitions from "../queues.js";
54
+ `:"",ne=g.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",se=f?`
55
+
56
+ /** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
57
+ export interface LunoraQueues {
58
+ ${P.map(e=>` readonly ${e.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
59
+ `)}
60
+ }`:"",ie=x?`
61
+
62
+ /** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
63
+ export interface LunoraTopics {
64
+ ${M.map(e=>` readonly ${e.exportName}: TopicPublisher<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
65
+ `)}
66
+ }`:"",de=`${ne}${se}${ie}`,E=f?`
67
+ readonly queues: LunoraQueues;`:"",q=x?`
68
+ readonly topics: LunoraTopics;`:"",T=y.length>0,le=e=>{if(N==="")throw new V("INTERNAL","@lunora/codegen: emitServer needs `generatedDirectory` to import an RPC service's types");const a=ve(N,e);if(ke(a))throw new V("INTERNAL",`@lunora/codegen: an RPC service's entry (${e}) must be on the same drive as the app`);const B=a.split(we).join("/").replace(Ne,".$1js");return B.startsWith(".")?B:`./${B}`},L=y.filter(e=>e.rpcEntrypoint!==void 0),ce=L.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",ue=T?`import type { ${ce} } from "${o.server}";
69
+ ${L.map(e=>`import type * as lunoraService_${e.name} from ${JSON.stringify(le(e.main))};
70
+ `).join("")}`:"",pe=T?`
71
+
72
+ /** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
73
+ export interface LunoraServices {
74
+ ${y.map(e=>{p(e.name,`service "${e.name}"`);const a=e.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${e.name}.${e.rpcEntrypoint}>`;return` readonly ${e.name}: ${a};`}).join(`
75
+ `)}
76
+ }`:"",ye=T?`
77
+ readonly services: LunoraServices;`:"",v=d.length>0,me=v?`import type { AgentHandle } from "@lunora/agent";
78
+ `:"",he=v?`
79
+
80
+ /** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
81
+ export interface LunoraAgents {
82
+ ${d.map(e=>(p(e.exportName,`agent export "${e.exportName}"`),` readonly ${e.exportName}: AgentHandle;`)).join(`
83
+ `)}
84
+ }`:"",G=v?`
85
+ readonly agents: LunoraAgents;`:"",be=s?`import type { InferIdentity } from "${o.server}";
86
+ import type * as lunoraIdentityContract from "../identity.js";
87
+ `:"",fe=s?`
88
+
89
+ /** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
90
+ export type Identity = InferIdentity<typeof lunoraIdentityContract.${s.exportName}>;
91
+
92
+ /** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
93
+ type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",k=s?' | "auth"':"",w=s?`
94
+ readonly auth: NarrowedAuth;`:"",xe=s?", Identity":"",ge=t?`import type * as lunoraEnvContract from "../env.js";
95
+ `:"",Te=t?`
96
+
97
+ /** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
98
+ export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${t.exportName}>;`:"",I=t?' | "env"':"",$=t?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${Be}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${o.server}";
99
+ import type {
100
+ ActionBuilder,
101
+ ActionCtx as ActionCtxBase,
102
+ ColumnValidator,
103
+ DatabaseReader,
104
+ DatabaseWriter,
105
+ EmptyArgs,
106
+ InternalActionBuilder,
107
+ InternalMutationBuilder,
108
+ InternalQueryBuilder,
109
+ MutationBuilder,
110
+ MutationCtx as MutationCtxBase,
111
+ MutationStorage,
112
+ MutatorDefinition,
113
+ QueryBuilder,
114
+ QueryCtx as QueryCtxBase,
115
+ ReadOnlyStorage,
116
+ RegisteredMutator,
117
+ Storage as StorageBase,
118
+ TableReader,
119
+ Validator,
120
+ } from "${o.server}";
121
+
122
+ import type {
123
+ DatabaseReaderFacade as DatabaseReaderFacadeOf,
124
+ DatabaseWriterFacade as DatabaseWriterFacadeOf,
125
+ LoadWith as LoadWithOf,
126
+ TableReaderFacade as TableReaderFacadeOf,
127
+ TableWriterFacade as TableWriterFacadeOf,
128
+ WithArg as WithArgOf,
129
+ } from "${o.serverDataModel}";
130
+
131
+ export type {
132
+ AggregateOp,
133
+ GroupByEntry,
134
+ OrderBy,
135
+ QueryArgs,
136
+ QueryPage,
137
+ RankPage,
138
+ RankResult,
139
+ RestrictableQueryOptions,
140
+ RestrictableQueryOptionsOf,
141
+ SearchFilterBuilder,
142
+ SearchReader,
143
+ TableAggregateOptions,
144
+ TableAggregateOptionsOf,
145
+ TableGroupByOptions,
146
+ TableGroupByOptionsOf,
147
+ TableRankOptions,
148
+ TableRankPageOptions,
149
+ Where,
150
+ WhereOf,
151
+ WhereOperators,
152
+ } from "${o.serverDataModel}";
153
+
154
+ import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
155
+ ${te}${K}${ae}${oe}${ue}${me}${be}${ge}
156
+ export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
157
+
158
+ /**
159
+ * The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
160
+ * over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
161
+ *
162
+ * They live here rather than in \`dataModel.ts\` because they are the half that
163
+ * needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
164
+ * package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
165
+ * types without installing a server dependency to do it.
166
+ */
167
+
168
+ /** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
169
+ export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
170
+
171
+ /** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
172
+ export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
173
+
174
+ /** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
175
+ export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
176
+
177
+ /** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
178
+ export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
179
+
180
+ /** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
181
+ export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
182
+
183
+ /** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
184
+ export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
185
+
186
+ /** Insert builder returned by \`ctx.orm.insert(table)\`. */
187
+ export interface OrmInsertBuilder<T extends keyof DataModel> {
188
+ values: (values: Insert<T>) => Promise<IdOfTable<T>>;
189
+ }
190
+
191
+ /** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
192
+ export interface OrmReplaceBuilder<T extends keyof DataModel> {
193
+ with: (values: Insert<T>) => Promise<void>;
194
+ }
195
+
196
+ /** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
197
+ export interface OrmUpdateBuilder<T extends keyof DataModel> {
198
+ set: (values: Partial<Insert<T>>) => Promise<void>;
199
+ }
200
+
201
+ /** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
202
+ export interface OrmReader {
203
+ query: DatabaseReaderFacade;
204
+ }
205
+
206
+ /** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
207
+ export interface OrmWriter extends OrmReader {
208
+ delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
209
+ insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
210
+ replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
211
+ update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
212
+ }
213
+
214
+ /** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
215
+ export type StorageBucketName = ${U};${X}${re}${de}${pe}${he}${fe}${Te}
216
+
217
+ /**
218
+ * Project-typed contexts. The base contexts from \`@lunora/server\` are
219
+ * untyped against the schema; here \`db\` is widened to the generated per-table
220
+ * facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
221
+ * \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
222
+ * \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
223
+ */
224
+ /**
225
+ * The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
226
+ * a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
227
+ * \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
228
+ * as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
229
+ * \`ctx.db.<table>\` stays available alongside it via the facade.
230
+ *
231
+ * Intersected with the wide \`(string) => TableReader\` signature so the bound
232
+ * \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
233
+ * call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
234
+ *
235
+ * The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
236
+ * error: each resolves to the table's declared names, or \`never\` when it
237
+ * declares none of that kind. Without them a renamed or dropped index left
238
+ * every call site typechecking, and the query either threw at runtime or
239
+ * degraded silently to a full table scan.
240
+ */
241
+ type TypedTableQuery = (<T extends TableName>(
242
+ table: T,
243
+ ) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
244
+ ((table: string) => TableReader);
245
+
246
+ /**
247
+ * The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
248
+ * carries its table name, so the resolved document is typed \`Doc<table>\` (or
249
+ * \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
250
+ */
251
+ type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
252
+
253
+ /**
254
+ * Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
255
+ * genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
256
+ * collapses to \`never\` so it fails to typecheck.
257
+ *
258
+ * The \`string extends T\` arm is what distinguishes "the caller passed a computed
259
+ * string" from "the caller passed a misspelled literal" — only the wide \`string\` type
260
+ * is a supertype of \`string\`.
261
+ */
262
+ type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
263
+
264
+ /**
265
+ * The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
266
+ * table literal is a compile error rather than a call that hands back a confidently-
267
+ * branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
268
+ * {@link TypedTableGet}.
269
+ *
270
+ * Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
271
+ * overload resolution would fall through to it for a bad literal, silently restoring
272
+ * the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
273
+ * computed table name working — and keeps \`ctx.db\` structurally assignable to
274
+ * schema-agnostic consumers — without accepting an invalid literal.
275
+ */
276
+ type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
277
+
278
+ export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${m}${k}${I}> {
279
+ readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
280
+ readonly orm: OrmReader;
281
+ readonly storage: ReadOnlyStorage<StorageBucketName>;${ee}${W}${h}${b}${$}${w}
282
+ }
283
+
284
+ export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${m}${Q}${k}${I}> {
285
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
286
+ readonly orm: OrmWriter;
287
+ readonly storage: MutationStorage<StorageBucketName>;${F}${W}${h}${b}${$}${j}${E}${q}${G}${w}
288
+ }
289
+
290
+ export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${m}${Q}${k}${I}> {
291
+ readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
292
+ readonly orm: OrmWriter;
293
+ readonly storage: StorageBase<StorageBucketName>;${F}${Z}${Y}${h}${b}${ye}${$}${j}${E}${q}${G}${w}
294
+ }
295
+
296
+ /**
297
+ * Procedure builders bound to this project's typed contexts. Chain
298
+ * \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
299
+ * masking (each middleware may refine \`ctx\`), then the terminal
300
+ * \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
301
+ * handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
302
+ */
303
+ const lunoraBuilders = initLunora.dataModel<DataModel>().create();
304
+
305
+ /** \`query\` builder bound to this project's typed {@link QueryCtx}. */
306
+ export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
307
+
308
+ /** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
309
+ export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
310
+
311
+ /** \`action\` builder bound to this project's typed {@link ActionCtx}. */
312
+ export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
313
+
314
+ /** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
315
+ export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
316
+
317
+ /** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
318
+ export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
319
+
320
+ /** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
321
+ export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
322
+
323
+ /**
324
+ * \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
325
+ * custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
326
+ * \`${o.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
327
+ * schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
328
+ * \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
329
+ * no \`as unknown as\` cast. Runtime-identical to the package export; only the
330
+ * context type narrows, so discovery finds a mutator authored either way.
331
+ * @example
332
+ * export const setText = defineMutator({
333
+ * args: { id: v.id("nodes"), text: v.string() },
334
+ * server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
335
+ * });
336
+ */
337
+ export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
338
+ definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
339
+ ) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
340
+
341
+ /**
342
+ * \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
343
+ * Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
344
+ * a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
345
+ * name and the \`when\` predicate type-checks against the table's columns **and**
346
+ * its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
347
+ * etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
348
+ * Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
349
+ * so the \`rls()\` chain discovers a policy authored either way the same.
350
+ */
351
+ export const definePolicy = createPolicyDsl<DataModel, Relations${xe}>();
352
+
353
+ /**
354
+ * The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
355
+ * table names — so the argument autocompletes and returns a precise
356
+ * \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
357
+ * difference is the tightened \`id\` type.
358
+ *
359
+ * Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
360
+ * to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
361
+ * file that defines the table names, so they aren't known yet there; pass the
362
+ * names as string literals and the generated \`Id<"table">\` types still catch a
363
+ * typo wherever the id is used.
364
+ */
365
+ export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
366
+ id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
367
+ };
368
+ `};export{Qe 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-WXSIZRpD.mjs";import"./shard-runtime-B1nU9CRa.mjs";import"./shared-BXUKWh7t.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-sW_DHmLO.mjs";import{c as n}from"./classify-procedure-call-OnJoKgqu.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 c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-DRes9d5p.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(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"./listLunoraSourceFiles-DRes9d5p.mjs";import{r as v,d as b}from"./attribution-sW_DHmLO.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 r}from"ts-morph";import{propertyKeyName as u,listLunoraSourceFiles as f,lunoraRelativePath as m}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{b as p,d}from"./attribution-sW_DHmLO.mjs";import{t as g}from"./database-calls-rLPCL3-U.mjs";import{w as h,c as k}from"./classify-procedure-call-OnJoKgqu.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return u(e)},v=e=>h(e,"use","mask"),O=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.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(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=k(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=g(e,C,M);return{exportName:d(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},D=(e,s)=>{const t=[];for(const i of f(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=m(s,i);for(const a of p(o)){const c=b(a,n);c&&t.push(c)}}return t};export{l as a,D as d,v as m,O 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,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{readdirSync as x,realpathSync as L,lstatSync as F,statSync as O}from"node:fs";import{dirname as N,join as d,relative as w,sep as R,extname as S}from"node:path";import{SyntaxKind as c,Node as r,VariableDeclarationKind as T}from"ts-morph";import{diagnosticAt as b}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const C=/\.ts$/u,g=(e,t)=>w(e,t).split(R).join("/").replace(C,""),z=new Set(["_generated","node_modules"]),j=(e,t,i)=>e==="schema.ts"&&t===i,D=e=>{try{return O(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},y=(e,t,i,s)=>{let n,o;try{n=x(e),o=L(e)}catch{return t}if(s.has(o))return t;s.add(o);for(const a of n){const l=d(e,a),u=D(l);u!==void 0&&(u.isDirectory()?z.has(a)||y(l,t,i,s):u.isFile()&&S(a)===".ts"&&!j(a,e,i)&&t.push(l))}return t},v=e=>y(e,[],e,new Set),k=["src/server","src/index.ts","src/worker.ts"],_=new Set([".ts",".tsx"]),P=(e,t=[])=>{let i;try{i=F(e)}catch{return t}if(i.isFile())return _.has(S(e))&&t.push(e),t;if(!i.isDirectory())return t;for(const s of x(e))s==="_generated"||s==="node_modules"||P(d(e,s),t);return t},V=e=>{const t=N(e),i=v(e).map(o=>({displayPath:g(e,o),filePath:o})),s=new Set(i.map(o=>o.filePath)),n=I(t);for(const o of[...k.flatMap(a=>P(d(t,a))),...n===void 0?[]:[n]])s.has(o)||(s.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},K=e=>Array.isArray(e),h=(e,t,i,s)=>{const n=[];for(const{displayPath:o,filePath:a}of t){const l=e.getSourceFile(a)??e.addSourceFileAtPath(a);for(const u of l.getDescendantsOfKind(i)){const p=s(u,o);K(p)?n.push(...p):p!==void 0&&n.push(p)}}return n},B=e=>v(e).map(t=>({displayPath:g(e,t),filePath:t})),M=(e,t,i,s)=>h(e,B(t),i,s),ie=(e,t,i)=>M(e,t,c.CallExpression,i),re=(e,t,i)=>h(e,V(t),c.CallExpression,i),A=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e)||r.isNumericLiteral(e))return e.getLiteralText();if(r.isComputedPropertyName(e)){const t=e.getExpression();if(r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t))return t.getLiteralText()}return e.getText()},$=e=>A(e.getNameNode()),se=e=>A(e.getPropertyNameNode()??e.getNameNode()),E=(e,t)=>e?.getProperties().find(i=>!r.isSpreadAssignment(i)&&$(i)===t),ne=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!r.isObjectLiteralExpression(i))return;const s=E(i,"handler");if(!s||!r.isPropertyAssignment(s))return;const n=s.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:void 0},oe=(e,t)=>{if(!e||!r.isObjectLiteralExpression(e))return;const i=E(e,t);return i&&r.isPropertyAssignment(i)?i.getInitializer():void 0},U=e=>{const t=e?.getParent();return r.isVariableDeclaration(e)&&r.isVariableDeclarationList(t)&&t.getDeclarationKind()===T.Const},W=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(r.isParenthesizedExpression(i)||r.isAsExpression(i)||r.isSatisfiesExpression(i)||r.isTypeAssertion(i)||r.isNonNullExpression(i));)t=i,i=t.getParent();return t},m=e=>{const t=W(e),i=t.getParent();if(i===void 0)return!1;if(r.isBinaryExpression(i)){const n=i.getOperatorToken().getKind();return i.getLeft()===t&&n>=c.FirstAssignment&&n<=c.LastAssignment}if(r.isPrefixUnaryExpression(i)||r.isPostfixUnaryExpression(i)){const n=i.getOperatorToken();return n===c.PlusPlusToken||n===c.MinusMinusToken}return r.isDeleteExpression(i)?!0:r.isForOfStatement(i)||r.isForInStatement(i)?i.getInitializer()===t:r.isPropertyAssignment(i)?i.getInitializer()===t&&m(i):(r.isShorthandPropertyAssignment(i)||r.isSpreadAssignment(i)||r.isSpreadElement(i)||r.isObjectLiteralExpression(i)||r.isArrayLiteralExpression(i))&&m(i)},X=e=>{const t=e?.getDeclarations().find(s=>r.isVariableDeclaration(s));if(!U(t))return;const i=t.getParent().getParent();return r.isVariableStatement(i)&&r.isSourceFile(i.getParent())?t.getInitializer():void 0},Y=e=>X(e.getSymbol()),ae=e=>{if(!e)return;if(r.isObjectLiteralExpression(e))return e;if(!r.isIdentifier(e))return;const t=Y(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},f=e=>{let t=e;for(;t&&(r.isAsExpression(t)||r.isSatisfiesExpression(t)||r.isParenthesizedExpression(t)||r.isNonNullExpression(t));)t=t.getExpression();return t},q=(e,t)=>{let i=f(e);for(;r.isAwaitExpression(i)||r.isPropertyAccessExpression(i)||r.isElementAccessExpression(i)||r.isCallExpression(i);){const s=r.isCallExpression(i)?t?.(i):void 0;if(s!==void 0)return{verdict:s};i=f(i.getExpression())}return{root:i}},ce=e=>q(e).root,le=(e,t)=>e?.compilerNode===t.compilerNode,ue=e=>{if(r.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=r.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return r.isElementAccessExpression(e)&&r.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},pe=e=>{const t=e.getParent();return r.isReturnStatement(t)||r.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(s=>r.isFunctionLikeDeclaration(s)||r.isArrowFunction(s)):void 0},ge=e=>{const t=f(e);return t&&r.isCallExpression(t)?t:void 0},fe=e=>{const t=e.getExportAssignment(n=>!n.isExportEquals());if(!t)return;const i=t.getExpression();if(!r.isIdentifier(i))return i;const s=i.getSymbol()?.getValueDeclaration();return s&&r.isVariableDeclaration(s)?s.getInitializer():i},de=e=>{const t=e.getArguments()[1];return t&&r.isStringLiteral(t)?t.getLiteralValue():""},Ee=(e,t)=>{if(!r.isObjectLiteralExpression(e))return;const i=E(e,t);if(!i||!r.isPropertyAssignment(i))return;const s=i.getInitializer();return s&&r.isStringLiteral(s)?s.getLiteralText():void 0},H=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!r.isReturnStatement(i))return;const s=i.getExpression();return s!==void 0&&r.isObjectLiteralExpression(s)?s:void 0},me=e=>{if(r.isObjectLiteralExpression(e))return e;if(r.isParenthesizedExpression(e)){const t=e.getExpression();return r.isObjectLiteralExpression(t)?t:void 0}return r.isBlock(e)?H(e):void 0},xe=e=>(t,i,s)=>{if(r.isStringLiteral(t)||r.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw b(t,`${e} "${i}": \`${s}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},Q=new Set(["api","internal"]),Se=new Set(["run","runAction","runMutation","runQuery"]),ye=e=>{if(e===void 0||!r.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;r.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return r.isIdentifier(i)&&Q.has(i.getText())&&t.length>=2?t:void 0};export{Se as RUN_METHODS,C as TS_EXTENSION_RE,se as bindingKeyName,ce as chainRootOf,ie as collectCallRows,M as collectNodeRows,re as collectSecurityCallRows,fe as defaultExportExpression,E as findObjectProperty,ye as functionReferenceSegments,ne as handlerOf,U as isConstDeclaration,le as isSameNode,m as isWriteTarget,de as limitNameOf,v as listLunoraSourceFiles,V as listSecurityScanFiles,g as lunoraRelativePath,ue as memberAccessOf,me as objectLiteralFromCallbackBody,ae as optionsObjectLiteral,W as outermostValueWrapper,oe as propertyInitializer,$ as propertyKeyName,A as propertyNameText,pe as returningFunctionOf,xe as stringPropertyFor,Ee as stringPropertyOf,X as symbolConstInitializer,f as unwrapExpression,ge as unwrapToCallExpression,q as walkChain};
@@ -0,0 +1 @@
1
+ import{statSync as E,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as x}from"jiti";import{Project as S,Node as t}from"ts-morph";import{propertyKeyName as l}from"./listLunoraSourceFiles-DRes9d5p.mjs";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as T}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const f=new Map,F=async i=>{const r=v(i);if(r===void 0)return{};let e;try{const n=E(r);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=f.get(r);if(s?.key===e)return s.value;const a=(async()=>{try{const u=(await x(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:u!==null&&typeof u=="object"?u:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return f.set(r,{key:e,value:a}),a},L=i=>{let e=i.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&t.isIdentifier(e))for(e=i.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e));)e=e.getExpression();return e!==void 0&&t.isObjectLiteralExpression(e)?e:void 0},c=(i,r)=>t.isPropertyAssignment(i)?i.getInitializer():r.getVariableDeclaration(l(i))?.getInitializer(),g=i=>{let r=i;for(;r!==void 0&&(t.isSatisfiesExpression(r)||t.isAsExpression(r)||t.isParenthesizedExpression(r));)r=r.getExpression();return r},h=(i,r)=>{const e=g(i);if(e===void 0||!t.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),a=s.filter(o=>t.isPropertyAssignment(o)&&!t.isComputedPropertyName(o.getNameNode())||t.isShorthandPropertyAssignment(o));if(a.length!==s.length)return{advisor:{unreadable:!0}};const n=a.find(o=>l(o)==="minSeverity");if(n===void 0)return{advisor:{}};const u=c(n,r);return u!==void 0&&t.isStringLiteral(u)?{advisor:{minSeverity:u.getLiteralValue()}}:{advisor:{unreadable:!0}}},A=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),b=(i,r)=>{const e=i.getProperty(r);if(e!==void 0)return(t.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},m=(i,r)=>{const e=b(i,r);if(e!==void 0)return e!=="unreadable"&&(t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},j=i=>{const r=b(i,"rpc");if(r!==void 0)return r!=="unreadable"&&t.isFalseLiteral(r)?!1:"unreadable"},N=i=>{const r=g(i);if(r===void 0||!t.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const s of r.getProperties()){if(!t.isPropertyAssignment(s)||t.isComputedPropertyName(s.getNameNode()))return{services:{unreadable:!0}};const a=g(s.getInitializer());if(a===void 0||!t.isObjectLiteralExpression(a)||a.getProperties().some(d=>!t.isPropertyAssignment(d)))return{services:{unreadable:!0}};const n=m(a,"dir"),u=m(a,"entrypoint"),o=j(a);if(typeof n!="string"||u===!1||o==="unreadable")return{services:{unreadable:!0}};e[l(s)]={dir:n,...u===void 0?{}:{entrypoint:u},...o===void 0?{}:{rpc:o}}}return{services:{declared:e}}},w=(i,r)=>{if(t.isGetAccessorDeclaration(i)||t.isMethodDeclaration(i))return A.get(l(i))??{};if(!t.isPropertyAssignment(i)&&!t.isShorthandPropertyAssignment(i))return{};const e=l(i);if(e==="advisor")return h(c(i,r),r);if(e==="services")return N(c(i,r));if(e!=="target"&&e!=="remote")return{};const s=c(i,r);return s===void 0?{unreadable:!0}:e==="target"?t.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:t.isTrueLiteral(s)||t.isFalseLiteral(s)?{remote:s.getLiteralValue()}:t.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},V=i=>{const r=v(i);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const a=new S({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(P(r),e,{overwrite:!0}),n=L(a);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(o=>t.isSpreadAssignment(o))){const o=d=>n.getProperties().some(p=>!t.isSpreadAssignment(p)&&l(p)===d);return{...o("advisor")?{advisor:{unreadable:!0}}:{},...o("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let u={};for(const o of n.getProperties())u={...u,...w(o,a)};return u};export{T as PROJECT_CONFIG_FILENAMES,v as findProjectConfigFile,F as loadProjectConfig,V 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{s as g}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./listLunoraSourceFiles-DRes9d5p.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 n,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as v}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as E}from"./listLunoraSourceFiles-DRes9d5p.mjs";let f;const j=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"]),L=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&&n.isShorthandPropertyAssignment(r)){const i=r.getValueSymbol();r=(i?.getAliasedSymbol()??i)?.getValueDeclaration()}if(!(r===void 0||!n.isVariableDeclaration(r)))return r.getInitializer()},T=e=>{const t=e.getParent();return!n.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return u(e.getExpression());if(n.isObjectLiteralExpression(e))return e;if(n.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),i=r!==void 0&&n.isPropertyAssignment(r)?r.getInitializer():void 0;return i===void 0?void 0:u(i)}if(!n.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!T(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(n.isIdentifier(e))return!0;let t=e;for(;n.isCallExpression(t);){const r=t.getExpression();if(!n.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return n.isIdentifier(t)&&t.getText()===w},c=e=>{if(n.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 n.isCallExpression(e)?P(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 b(t)}finally{g.delete(t)}},b=e=>{const t={};for(const r of e.getProperties()){if(n.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const i=n.isShorthandPropertyAssignment(r);if(!i&&!n.isPropertyAssignment(r))continue;const o=r.getNameNode();if(n.isComputedPropertyName(o))continue;const a=i?r.getNameNode():r.getInitializer();if(!a)continue;const s=E(r);if(!A.test(s))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(s)}`);t[s]=c(a)}return t},d=(e,t)=>e&&n.isExpression(e)?c(e):t,V=e=>e===void 0?"undefined":n.isStringLiteral(e)||n.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}},x=(e,t,r)=>{if(N.has(e))return{kind:e};const[i,o]=t;switch(e){case"array":return{inner:d(i,{kind:"any"}),kind:"array"};case"from":return O(i);case"id":{if(!i||!n.isStringLiteral(i))throw v(i??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${i?i.getText():"no argument"}.`);return{kind:"id",tableName:i.getLiteralText()}}case"literal":return{kind:"literal",literalValue:V(i)};case"object":return i&&n.isObjectLiteralExpression(i)?{kind:"object",shape:b(i)}:{kind:"object",shape:{}};case"optional":return{inner:d(i,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(i,{kind:"string"}),kind:"record",valueType:d(o,{kind:"any"})};case"storage":return i&&n.isStringLiteral(i)?{bucket:i.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>n.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},M=e=>{const[t]=e;if(e.length!==1||t===void 0||!n.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},P=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),i=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const o=t.getExpression(),a=n.isExpression(o)?c(o):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const s=r==="max"&&a.kind==="string"?M(i):void 0;return s!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??s,s)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return x(r,i,e)};export{c as a,b as p,u as r,j as s};
@@ -0,0 +1 @@
1
+ const a=/\/index$/u,s=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(s,"_");export{c as s};
@@ -0,0 +1 @@
1
+ import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-BXUKWh7t.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{M as a,v as b,U as c,O as r};
@@ -0,0 +1 @@
1
+ import{existsSync as r,readFileSync as a}from"node:fs";import{join as d}from"node:path";const m=o=>{const n=d(o,"package.json");if(r(n))try{const s=JSON.parse(a(n,"utf8")),t=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=s[c];if(e!==null&&typeof e=="object")for(const i of Object.keys(e))t.add(i)}return t}catch{return}};export{m as default};
@@ -0,0 +1 @@
1
+ import{existsSync as g,readFileSync as p}from"node:fs";import{isAbsolute as w,resolve as m,join as u}from"node:path";import{ts as h}from"ts-morph";import{readProjectConfigLiterals as E}from"./loadProjectConfig-CuGQsqYS.mjs";const f=/^[A-Za-z_$][\w$]*$/u,$=["wrangler.jsonc","wrangler.json"],b=t=>`SERVICE_${t.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,y=(t,e)=>{const r=$.map(n=>u(e,n)).find(n=>g(n));if(r===void 0){const n=g(u(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${t}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=h.parseConfigFileTextToJson(r,p(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${t}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},v=(t,e)=>{const r=t.route??e.route,o=t.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(t.workers_dev??e.workers_dev)!==!1},S=(t,e,r)=>{if(!f.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!f.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=w(r.dir)?r.dir:m(t,r.dir),{config:n,path:s}=y(e,o),{main:c,name:l}=n;if(typeof l!="string"||l==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no Worker "name"`);if(typeof c!="string"||c==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no "main" entry module`);const d=Object.entries(n.env??{}).map(([i,a])=>[i,a??{}]);return{binding:b(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(d.flatMap(([i,a])=>typeof a.name=="string"&&a.name!==""?[[i,a.name]]:[])),main:m(o,c),name:e,publicScopes:[...v(n,n)?[""]:[],...d.filter(([,i])=>v(i,n)).map(([i])=>i)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:l,wranglerPath:s}},j=t=>{const{services:e}=E(t);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>S(t,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const s=r.slice(o+1).find(c=>c.binding===n.binding);if(s!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${s.name}" both map to the binding ${n.binding} — rename one`)}return r},A=t=>{try{return{services:j(t)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}};export{A as readServiceBindings,j as resolveServiceBindings};
@@ -0,0 +1 @@
1
+ const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
@@ -0,0 +1 @@
1
+ const t=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),i=/^[$A-Z_a-z][\w$]*$/u,a=e=>i.test(e)&&!t.has(e);export{t as R,a as i};
@@ -0,0 +1 @@
1
+ const s=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=s(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{shape:Object.fromEntries(Object.entries(a.shape).map(([l,o])=>[l,n(o)]))}]))});export{m as schemaFromIr};