@lunora/codegen 1.0.0-alpha.9 → 1.0.0-alpha.90

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 (76) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/index.d.mts +2722 -931
  3. package/dist/index.d.ts +2722 -931
  4. package/dist/index.mjs +1 -29
  5. package/dist/packem_shared/AGENTS_FILENAME-BesaDYkL.mjs +1 -0
  6. package/dist/packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs +1 -0
  7. package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
  9. package/dist/packem_shared/FLAGS_FILENAME-CHaH6obH.mjs +1 -0
  10. package/dist/packem_shared/GENERATED_HEADER-CUBdTCVk.mjs +1 -0
  11. package/dist/packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs +1 -0
  12. package/dist/packem_shared/MUTATORS_FILENAME-DY3rgWGl.mjs +1 -0
  13. package/dist/packem_shared/NOTIFY_FILENAME-CDvoTY3Y.mjs +1 -0
  14. package/dist/packem_shared/OPENRPC_VERSION-aq5eyIkd.mjs +3 -0
  15. package/dist/packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs +1 -0
  16. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ChA6rpGP.mjs +9 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs +2 -0
  18. package/dist/packem_shared/SHAPES_FILENAME-BdLj5-mD.mjs +1 -0
  19. package/dist/packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs +16 -0
  20. package/dist/packem_shared/WORKFLOWS_FILENAME-ClsYRKXp.mjs +1 -0
  21. package/dist/packem_shared/buildOpenApiDocument-Bw3MChvT.mjs +3 -0
  22. package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
  23. package/dist/packem_shared/discover-ast-CezKqEhE.mjs +1 -0
  24. package/dist/packem_shared/discover-queries-BmZeJ--u.mjs +1 -0
  25. package/dist/packem_shared/discoverAuthApiCalls-BgL6nj03.mjs +1 -0
  26. package/dist/packem_shared/discoverCrons-WJscxQFl.mjs +1 -0
  27. package/dist/packem_shared/discoverFunctions-BgGmxEqW.mjs +1 -0
  28. package/dist/packem_shared/discoverHttpRoutes-eW8RbVOr.mjs +1 -0
  29. package/dist/packem_shared/discoverInserts-BCz6zpI0.mjs +1 -0
  30. package/dist/packem_shared/discoverMaskProcedures-DLfQRsQc.mjs +1 -0
  31. package/dist/packem_shared/discoverMigrations-Cbc4W765.mjs +1 -0
  32. package/dist/packem_shared/discoverNondeterministicCalls-x9IhWxPP.mjs +1 -0
  33. package/dist/packem_shared/discoverQueries-Cf0LGoQG.mjs +1 -0
  34. package/dist/packem_shared/discoverR2sqlCalls--MSfSeDm.mjs +1 -0
  35. package/dist/packem_shared/discoverRlsMetadata-DTRS0ROc.mjs +1 -0
  36. package/dist/packem_shared/discoverSandboxUsage-BDyeyuYo.mjs +1 -0
  37. package/dist/packem_shared/discoverSchema-DSJSX4Ss.mjs +1 -0
  38. package/dist/packem_shared/discoverStorageRulesMetadata-Cic97L-2.mjs +1 -0
  39. package/dist/packem_shared/emit-DMvG162j.mjs +2310 -0
  40. package/dist/packem_shared/emitApp--dJ6EnFn.mjs +524 -0
  41. package/dist/packem_shared/formatAdvisories-BCEfzLT0.mjs +2 -0
  42. package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +1 -0
  43. package/dist/packem_shared/parse-validator-CkLxY-Mr.mjs +1 -0
  44. package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
  45. package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +1 -0
  46. package/dist/packem_shared/redact-6jD4lAhq.mjs +1 -0
  47. package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
  48. package/package.json +12 -7
  49. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  50. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  51. package/dist/packem_shared/GENERATED_HEADER-LceqJ_qp.mjs +0 -2688
  52. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  53. package/dist/packem_shared/OPENRPC_VERSION-s7lhywUr.mjs +0 -60
  54. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Ct0NDRLY.mjs +0 -937
  55. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DzLDbWk3.mjs +0 -233
  56. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  57. package/dist/packem_shared/buildOpenApiDocument-DSPTssJI.mjs +0 -183
  58. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  59. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  60. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  61. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  62. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  63. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  64. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  65. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  66. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  67. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  68. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  69. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  70. package/dist/packem_shared/discoverSchema-BF6L4mrU.mjs +0 -795
  71. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  72. package/dist/packem_shared/emitApp-CDg72pVv.mjs +0 -599
  73. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  74. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  75. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  76. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
@@ -0,0 +1,524 @@
1
+ import{n as S,S as D}from"./emit-DMvG162j.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),a&&g.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},j=e=>[...e.hasStorage?[`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
2
+ interface StorageDeclaration<Env> {
3
+ /** The default R2 bucket binding (the bare \`ctx.storage\`). */
4
+ bucket: Selector<Env, R2BucketLike>;
5
+ /** Extra named buckets, reached via \`ctx.storage.bucket("name")\` and the studio's bucket picker. */
6
+ buckets?: Record<string, Selector<Env, R2BucketLike>>;
7
+ /** Public base URL signed/public object URLs resolve against. */
8
+ publicBaseUrl?: Selector<Env, string>;
9
+ /** HMAC secret for signed URLs. */
10
+ signingSecret?: Selector<Env, string>;
11
+ }`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. */\n namespace?: Selector<Env, ShardNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],q=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],I=e=>v.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
12
+ public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
13
+ this.shardExtras.${r} = factory;
14
+
15
+ return this;
16
+ }`),N=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — verifies the `Cf-Access-Jwt-Assertion` JWT and feeds the identity into `ctx.auth` / RLS via `resolveIdentity`. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when its JWT is present; everyone else falls through to the app session). */\n public access(selector: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector;\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
17
+ public admin(selector: Selector<Env, string>): this {
18
+ this.adminToken = selector;
19
+
20
+ return this;
21
+ }`,...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
22
+ public global(declaration: GlobalDeclaration<Env>): this {
23
+ this.globalDeclaration = declaration;
24
+
25
+ return this;
26
+ }`]:[],...e.hasHyperdriveGlobal?[` /** Back \`.global({ backend: "hyperdrive" })\` tables with a Postgres/MySQL database via Hyperdrive — wires reactive \`ctx.db\` routing through the shared store core. */
27
+ public hyperdriveGlobal(declaration: HyperdriveGlobalDeclaration<Env>): this {
28
+ this.hyperdriveGlobalDeclaration = declaration;
29
+
30
+ return this;
31
+ }`]:[],` /** Cloudflare Email Routing entry — exposes the top-level \`email\` handler. */
32
+ public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>): this {
33
+ this.emailHandler = handler;
34
+
35
+ return this;
36
+ }`," /** Mount a whole HTTP app (`httpRouter()` from `@lunora/server`, or anything with a `fetch`) ahead of Lunora's own routes. Use this for a multi-endpoint hono app with its own CORS + error handling; `.route()` is for one-off endpoints. */\n public httpRouter(app: HttpRouterLike): this {\n this.httpRouterApp = app;\n\n return this;\n }",` /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is \`"METHOD path"\`, \`"path"\`, or a path prefix matched by the runtime. */
37
+ public route(key: string, handler: Route): this {
38
+ this.routeMap[key] = handler;
39
+
40
+ return this;
41
+ }`,...e.hasScheduler?[` /** Wire the \`SchedulerDO\` — backs \`ctx.scheduler\` and the studio's scheduled-jobs view. */
42
+ public scheduler(declaration: SchedulerDeclaration<Env>): this {
43
+ this.schedulerDeclaration = declaration;
44
+
45
+ return this;
46
+ }`]:[],` /** The shard Durable Object namespace (typically \`env.SHARD\`) — required: every app routes RPC + WebSocket traffic through it. */
47
+ public shard(selector: Selector<Env, ShardNamespaceLike>): this {
48
+ this.shardSelector = selector;
49
+
50
+ return this;
51
+ }`,...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
52
+ public storage(declaration: StorageDeclaration<Env>): this {
53
+ this.storageDeclaration = declaration;
54
+
55
+ return this;
56
+ }`]:[],...I(e)],G=e=>{const t=[...e.hasGlobal?[` ...(this.globalDeclaration
57
+ ? {
58
+ d1: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
59
+ const env = rawEnv as Env;
60
+ const database = this.globalDeclaration?.d1(env);
61
+
62
+ if (!database) {
63
+ return undefined;
64
+ }
65
+
66
+ const origin = this.globalDeclaration?.origin?.(env);
67
+ const crossShard = origin
68
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
69
+ : undefined;
70
+
71
+ return createD1CtxDb({
72
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
73
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
74
+ exec: buildExec(database),
75
+ schema: schema as unknown as D1CtxDbOptions["schema"],
76
+ });
77
+ },
78
+ }
79
+ : {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
80
+ ? {
81
+ hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
82
+ const env = rawEnv as Env;
83
+ const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
84
+
85
+ if (!exec) {
86
+ return undefined;
87
+ }
88
+
89
+ const origin = this.hyperdriveGlobalDeclaration?.origin?.(env);
90
+ const crossShard = origin
91
+ ? createCrossShardRelationCapabilities({ identity: request?.identity, origin, userId: request?.userId ?? undefined })
92
+ : undefined;
93
+
94
+ return createHyperdriveGlobalCtxDb({
95
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),
96
+ auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
97
+ engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
98
+ exec,
99
+ schema: schema as unknown as SqlCtxDbOptions["schema"],
100
+ });
101
+ },
102
+ }
103
+ : {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
104
+ ? {
105
+ scheduler: (rawEnv: Record<string, unknown>) => {
106
+ const env = rawEnv as Env;
107
+ const namespace = this.schedulerDeclaration?.namespace(env);
108
+ const origin = this.schedulerDeclaration?.origin?.(env);
109
+
110
+ return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
111
+ },
112
+ }
113
+ : {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
114
+ ${t.join(`
115
+ `)}
116
+ `:""},W=e=>[...e.hasScheduler?[` if (this.schedulerDeclaration) {
117
+ options.schedulerDO = this.schedulerDeclaration.namespace(env);
118
+ }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
119
+ const source = workflowEnv as Record<string, unknown>;
120
+ const accountId = source["CLOUDFLARE_ACCOUNT_ID"];
121
+ const apiToken = source["CLOUDFLARE_API_TOKEN"];
122
+
123
+ return typeof accountId === "string" && accountId !== "" && typeof apiToken === "string" && apiToken !== ""
124
+ ? createWorkflowsRestClient({ accountId, apiToken })
125
+ : undefined;
126
+ };`]:[],...e.hasGlobal?[` if (this.globalDeclaration) {
127
+ const database = this.globalDeclaration.d1(env);
128
+
129
+ if (database) {
130
+ options.d1 = database;
131
+ options.globalIntrospector = buildGlobalIntrospector(database);
132
+ // \`resolveTableSharding\`/\`importGlobals\` wire the admin bulk-import
133
+ // endpoint: without the former, EVERY row (including a \`.global()\`
134
+ // table's) routes to the default shard, so a global table is never
135
+ // recognised as global and the latter is never reached — the
136
+ // endpoint answers 200 with \`inserted: {}\` for a write that never
137
+ // happened. Both are mechanical over the schema this file already
138
+ // imports, so there is nothing project-specific to configure.
139
+ options.resolveTableSharding = buildTableShardingResolver();
140
+ options.importGlobals = buildGlobalImporter(database);
141
+ }
142
+ }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
143
+ Object.assign(options, this.buildStorageAdmin(env));
144
+ options.storage = (rawEnv: unknown) => this.resolveStorage(rawEnv as Env);
145
+ }`]:[],...e.hasKv?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env as Record<string, unknown>) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` // Captured before the branch so the narrowing survives — reading
146
+ // \`this.authDeclaration.namespace\` again below would be optional all over again.
147
+ const authDeclaration = this.authDeclaration;
148
+ const authNamespace = authDeclaration?.namespace;
149
+ const authD1 = authDeclaration?.d1;
150
+
151
+ if (authDeclaration && authNamespace) {
152
+ // DO-backed mode. The auth tables live inside the object and DO storage is
153
+ // unreachable from here, so better-auth runs in there and this worker talks
154
+ // to it. \`createDoAuthWiring\` is a tested function in \`@lunora/auth\` rather
155
+ // than more emitted code: request-path logic in generated output can only be
156
+ // typechecked, never unit-tested.
157
+ const authWiring = createDoAuthWiring({
158
+ internalSecret: authDeclaration.internalSecret?.(env),
159
+ namespace: authNamespace(env),
160
+ objectName: authDeclaration.objectName?.(env),
161
+ });
162
+
163
+ options.authHandler = authWiring.authHandler;
164
+ options.resolveIdentity = authWiring.resolveIdentity;
165
+ // The audit log lives in the object like every other auth table, so the feed
166
+ // reads through it rather than querying D1.
167
+ options.authAuditReader = authWiring.auditReader;
168
+ // \`authAdmin\` stays D1-only: its ~30 methods read the auth tables directly
169
+ // from the worker, which DO storage does not allow. The studio's auth pages
170
+ // therefore report "not configured" in this mode rather than silently
171
+ // returning empty data.
172
+ } else if (authDeclaration && authD1) {
173
+ options.authHandler = (request) => {
174
+ const auth = getAuth();
175
+
176
+ return auth ? handleAuthRequest(auth, request) : Promise.resolve(undefined);
177
+ };
178
+ options.resolveIdentity = async (request) => {
179
+ const auth = getAuth();
180
+
181
+ if (!auth) {
182
+ return null;
183
+ }
184
+
185
+ const session = await auth.api.getSession({ headers: (request as Request).headers });
186
+
187
+ return session?.user?.id ? { userId: session.user.id } : null;
188
+ };
189
+ const authInstance = getAuth();
190
+
191
+ options.authAdmin = authInstance ? createAuthAdmin(authInstance) : undefined;
192
+ options.authAuditReader = createAuthAuditReader(d1Executor(authD1(env) as never));
193
+ }`]:[],...e.hasAccess?[e.hasAuth?` if (this.accessSelector) {
194
+ const accessResolver = createAccessResolver(this.accessSelector(env));
195
+ const fallback = options.resolveIdentity;
196
+
197
+ options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
198
+ }`:` if (this.accessSelector) {
199
+ options.resolveIdentity = createAccessResolver(this.accessSelector(env));
200
+ }`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
201
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
202
+ `)}
203
+ };`]:[]],$=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],B=e=>e?`
204
+ /** Resolve the storage capability (single or multi-bucket) for the DO side. */
205
+ private resolveStorage(env: Env): Storage | undefined {
206
+ const declaration = this.storageDeclaration;
207
+
208
+ if (!declaration) {
209
+ return undefined;
210
+ }
211
+
212
+ const defaultBucket = declaration.bucket(env);
213
+
214
+ if (!defaultBucket) {
215
+ return undefined;
216
+ }
217
+
218
+ const make = (bucket: R2BucketLike): Storage =>
219
+ createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
220
+ const extraEntries = Object.entries(declaration.buckets ?? {})
221
+ .map(([name, selector]) => [name, selector(env)] as const)
222
+ .filter((entry): entry is [string, R2BucketLike] => Boolean(entry[1]));
223
+
224
+ if (extraEntries.length === 0) {
225
+ return make(defaultBucket);
226
+ }
227
+
228
+ const map: Record<string, Storage> = { default: make(defaultBucket) };
229
+
230
+ for (const [name, bucket] of extraEntries) {
231
+ map[name] = make(bucket);
232
+ }
233
+
234
+ return createBucketStorage(map, { default: "default" });
235
+ }
236
+
237
+ /** Derive the studio file-browser admin functions from the same buckets \`.storage()\` declared. */
238
+ private buildStorageAdmin(env: Env): Partial<WorkerOptions> {
239
+ const declaration = this.storageDeclaration;
240
+
241
+ if (!declaration) {
242
+ return {};
243
+ }
244
+
245
+ const defaultBucket = declaration.bucket(env);
246
+
247
+ if (!defaultBucket) {
248
+ return {};
249
+ }
250
+
251
+ const make = (bucket: R2BucketLike): Storage =>
252
+ createStorage({ bucket, publicBaseUrl: declaration.publicBaseUrl?.(env), signingSecret: declaration.signingSecret?.(env) });
253
+ // Held separately from the map so \`pick\`'s fallback is a plain binding:
254
+ // under \`noUncheckedIndexedAccess\` a \`Record<string, Storage>\` lookup —
255
+ // including \`buckets.default\` — widens to \`Storage | undefined\`, which
256
+ // would not satisfy \`pick\`'s declared \`Storage\` return.
257
+ const fallbackStorage = make(defaultBucket);
258
+ const buckets: Record<string, Storage> = { default: fallbackStorage };
259
+
260
+ for (const [name, selector] of Object.entries(declaration.buckets ?? {})) {
261
+ const bucket = selector(env);
262
+
263
+ if (bucket) {
264
+ buckets[name] = make(bucket);
265
+ }
266
+ }
267
+
268
+ const pick = (name?: string): Storage => buckets[name !== undefined && name !== "" ? name : "default"] ?? fallbackStorage;
269
+ const hasSigning = Boolean(declaration.publicBaseUrl?.(env) && declaration.signingSecret?.(env));
270
+
271
+ return {
272
+ storageBuckets: Object.keys(buckets),
273
+ storageDelete: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).delete(key),
274
+ storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
275
+ storageSignedUrl: hasSigning
276
+ ? (key: string, opts?: { bucket?: string; expiresInSeconds?: number }) => pick(opts?.bucket).getSignedUrl(key, { expiresInSeconds: opts?.expiresInSeconds })
277
+ : undefined,
278
+ storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string }) => pick(opts?.bucket).upload(key, body, opts),
279
+ };
280
+ }
281
+ `:"",H=e=>e?`
282
+ /** Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`). */
283
+ const buildExec = (database: D1DatabaseLike): D1Exec => {
284
+ const batchFn = database.batch;
285
+
286
+ return {
287
+ all: async (sql, parameters) => {
288
+ const result = await database
289
+ .prepare(sql)
290
+ .bind(...parameters)
291
+ .all<Record<string, unknown>>();
292
+
293
+ return result.results;
294
+ },
295
+ // D1's own \`batch\` runs the whole array as one atomic SQLite
296
+ // transaction. Guarded because \`D1DatabaseLike.batch\` is optional in
297
+ // the structural type (test doubles may omit it) — real D1 always has
298
+ // it; a double without it still works through the store's sequential
299
+ // fallback. Invoked via \`.call(database, ...)\` rather than
300
+ // \`database.batch(...)\` directly so TS can narrow the captured
301
+ // \`batchFn\` across the closure boundary (a property-access narrowing
302
+ // like \`hasBatch = typeof database.batch === "function"\` does not
303
+ // survive into a nested arrow function); \`.call\` still binds \`this\`
304
+ // to \`database\`, so the real workerd \`D1Database\` doesn't throw
305
+ // \`TypeError: Illegal invocation\` the way a detached
306
+ // \`const fn = database.batch; fn(...)\` capture would.
307
+ batch: batchFn
308
+ ? async (statements) => {
309
+ await batchFn.call(
310
+ database,
311
+ statements.map(({ params, sql }) => database.prepare(sql).bind(...params)),
312
+ );
313
+ }
314
+ : undefined,
315
+ run: async (sql, parameters) => {
316
+ await database
317
+ .prepare(sql)
318
+ .bind(...parameters)
319
+ .run();
320
+ },
321
+ };
322
+ };
323
+
324
+ /** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
325
+ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
326
+ const exec = buildExec(database);
327
+
328
+ return {
329
+ facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
330
+ listTables: () => listGlobalTables(exec, schema as never),
331
+ readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
332
+ };
333
+ };
334
+
335
+ /**
336
+ * \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
337
+ * table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
338
+ * already record exactly this shape on the table) — mechanical, nothing to
339
+ * configure per project. \`undefined\` for a table the schema doesn't declare, so
340
+ * the import endpoint's own unknown-table handling still applies.
341
+ */
342
+ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
343
+ const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
344
+
345
+ return declared?.shardMode ? { mode: declared.shardMode } : undefined;
346
+ };
347
+
348
+ /**
349
+ * \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
350
+ * through the same D1 writer \`.global()\` reads/writes already use, via
351
+ * \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
352
+ * twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
353
+ * shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
354
+ *
355
+ * Passes each row's own \`line\` through rather than dropping it: the caller
356
+ * (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
357
+ * physical source line, and global rows are typically interspersed with
358
+ * shard-local ones it filtered out before calling here — a single
359
+ * \`startLine\` plus positional counting would mis-attribute every row after
360
+ * the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
361
+ * falls back to the position-derived count otherwise.
362
+ */
363
+ const buildGlobalImporter =
364
+ (database: D1DatabaseLike) =>
365
+ (request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
366
+ const exec = buildExec(database);
367
+ const writer = createD1CtxDb({ exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
368
+
369
+ return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
370
+ exec,
371
+ rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
372
+ startLine: request.startLine,
373
+ });
374
+ };
375
+ `:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=j(e),a=W(e),n=t?` let auth: LunoraAuth | null = null;
376
+ `:"",o=t?`
377
+ const ensureAuth = async (env: Env): Promise<void> => {
378
+ if (!this.authDeclaration || auth) {
379
+ return;
380
+ }
381
+
382
+ const d1 = this.authDeclaration.d1;
383
+
384
+ // DO-backed mode builds no instance here: better-auth runs inside the
385
+ // object, which materialises its own schema (the Kysely migrator below is
386
+ // dialect-bound and cannot target DO storage).
387
+ if (!d1) {
388
+ return;
389
+ }
390
+
391
+ auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
392
+ // Apply the better-auth schema lazily on first request (raw-D1 Kysely
393
+ // migrator). For production run the migrate command ahead of deploy.
394
+ await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
395
+ };
396
+ `:"",c=t?`
397
+ await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",u=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
398
+ host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,h=e.hasFramework?"host?: FrameworkHostHandler":"",l=e.emailAgents??[],p=l.length>0?` composed.email = dispatchAgentEmail([
399
+ ${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
400
+ `)}
401
+ ]);
402
+
403
+ `:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
404
+ public build(): ComposedApp {
405
+ return this.assemble();
406
+ }${e.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${D}${T(e).join(`
407
+ `)}
408
+
409
+ /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
410
+ type Selector<Env, T> = (env: Env) => T | undefined;
411
+ ${m(e)?"\n/** The generated `createShardDO` config — the long-tail `.ai()` / `.kv()` / … methods pass straight through to it. */\ntype ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;\n":""}
412
+ ${r.join(`
413
+
414
+ `)}${r.length>0?`
415
+
416
+ `:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
417
+ interface ComposedApp extends LunoraWorker {
418
+ /** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
419
+ email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
420
+ /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
421
+ ShardDO: ReturnType<typeof createShardDO>;
422
+ }
423
+
424
+ /**
425
+ * Fluent worker-composition builder. Records each capability declaration, then
426
+ * \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
427
+ * worker-side \`createWorker\` options — constructing the worker lazily on the
428
+ * first request so per-isolate singletons are built once.
429
+ */
430
+ class AppBuilder<Env extends object> {
431
+ ${q(e).join(`
432
+ `)}
433
+
434
+ private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
435
+
436
+ ${N(e).join(`
437
+
438
+ `)}
439
+
440
+ ${b}
441
+
442
+ /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
443
+ private assemble(${h}): ComposedApp {
444
+ const ShardDO = createShardDO({${G(e)}});
445
+
446
+ // Per-isolate singletons: the worker (and auth instance) are expensive to
447
+ // build, so the first request constructs them and every later request on
448
+ // the same isolate reuses them.
449
+ let worker: LunoraWorker | null = null;
450
+ ${n}${o}
451
+ ${u}
452
+
453
+ const composed: ComposedApp = {
454
+ ShardDO,
455
+ fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
456
+ const env = rawEnv as Env;${c}
457
+ worker ??= buildWorker(env);
458
+
459
+ return worker.fetch(request, rawEnv, context);
460
+ },
461
+ scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
462
+ worker ??= buildWorker(rawEnv as Env);
463
+
464
+ return worker.scheduled(controller, rawEnv, context);
465
+ },
466
+ serverQuery: (request, rawEnv, reference, args, options) => {
467
+ worker ??= buildWorker(rawEnv as Env);
468
+
469
+ return worker.serverQuery(request, rawEnv, reference, args, options);
470
+ },${e.hasQueue?`
471
+ queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
472
+ worker ??= buildWorker(rawEnv as Env);
473
+
474
+ return worker.queue?.(batch, rawEnv, context);
475
+ },`:""}
476
+ };
477
+
478
+ ${p} if (this.emailHandler) {
479
+ const handler = this.emailHandler;
480
+
481
+ composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
482
+ }
483
+
484
+ return composed;
485
+ }
486
+ ${B(e.hasStorage)}
487
+ /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
488
+ private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
489
+ const options: WorkerOptions = {
490
+ ${$(e).join(`
491
+ `)}
492
+ };
493
+
494
+ if (this.adminToken) {
495
+ options.adminToken = this.adminToken(env);
496
+ }
497
+
498
+ ${a.join(`
499
+
500
+ `)}${a.length>0?`
501
+
502
+ `:""} for (const fn of this.extendFns) {
503
+ Object.assign(options, fn(env, { ...options }));
504
+ }
505
+
506
+ return options;
507
+ }
508
+ }
509
+ ${H(e.hasGlobal)}
510
+ /**
511
+ * Start composing the app. Chain the capability methods, then \`.build()\`.
512
+ *
513
+ * \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
514
+ * — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
515
+ * what any app with its own bindings declares — is NOT assignable to an index
516
+ * signature, so the stricter bound forced every real app to write
517
+ * \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
518
+ * through the selectors you pass it, so the looser bound costs nothing.
519
+ */
520
+ const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
521
+
522
+ export { AppBuilder, defineApp };
523
+ export type { ${U(e)} };
524
+ `};export{F as emitApp};
@@ -0,0 +1,2 @@
1
+ import{runAdvisor as i}from"@lunora/advisor";const n=e=>[...e.indexes.map(s=>({fields:s.fields,kind:"index",name:s.name,unique:s.unique})),...e.searchIndexes.map(s=>({fields:[s.field,...s.filterFields??[]],kind:"search",name:s.name})),...e.rankIndexes.map(s=>({fields:[...s.sortBy.map(a=>a.field),...s.partitionBy??[]],kind:"rank",name:s.name})),...e.vectorIndexes.filter(s=>s.field!==void 0).map(s=>({fields:[s.field],kind:"vector",name:s.name})),...(e.geoIndexes??[]).map(s=>({fields:[s.field],kind:"geo",name:s.name}))],r=e=>{const s={};for(const[a,t]of Object.entries(e.shape))s[a]=t.kind==="optional"?t.inner?.kind??"optional":t.kind;return s},o=e=>({rlsMode:e.rlsMode,tables:e.tables.map(s=>({externallyManaged:s.externallyManaged??!1,externalSource:s.externalSource?{hasReconcile:s.externalSource.hasReconcile??!1,hasSoftDelete:s.externalSource.hasSoftDelete??!1,hasTenantBy:s.externalSource.hasTenantBy,mode:s.externalSource.mode,unanalyzable:s.externalSource.unanalyzable}:void 0,columnKinds:r(s),fields:Object.keys(s.shape),indexes:n(s),isPublic:s.isPublic??!1,name:s.name,relations:s.relations.map(a=>({field:a.field,kind:a.kind,name:a.name,onDelete:a.onDelete,references:a.references,table:a.table})),shardKind:typeof s.shardMode=="string"?s.shardMode:"shardBy",softDelete:s.softDelete,ttl:s.ttl}))}),l=e=>e.map(s=>({exportName:s.exportName,file:`lunora/${s.filePath}.ts`,table:s.table})),c=e=>({adminRoutes:e.adminRoutes,aiRawRuns:e.aiRawRuns,aiToolSideEffects:e.aiToolSideEffects,argumentDerivedFetches:e.argumentDerivedFetches,argValidators:e.argumentValidators,authApiCalls:e.authApiCalls,authConfigs:e.authConfigs,browserUrlAccesses:e.browserUrlAccesses,configCalls:e.configCalls,containerKeyAccesses:e.containerKeyAccesses,containerOverrides:e.containerOverrides,containers:e.containers,exportSinks:e.exportSinks,failOpenGuards:e.failOpenGuards,flagSecurityDefaults:e.flagSecurityDefaults,geoIndexUsages:e.geoIndexUsages,httpActionGuards:e.httpActionGuards,httpHeaderWrites:e.httpHeaderWrites,identityClaimReads:e.identityClaimReads,imageDeliveryUrlAccesses:e.imageDeliveryUrlAccesses,inserts:e.inserts,kvKeyAccesses:e.kvKeyAccesses,mailRecipientAccesses:e.mailRecipientAccesses,maskProcedures:e.maskProcedures,maskStrategies:e.maskStrategies,mutatorWrites:e.mutatorWrites,nondeterministicCalls:e.nondeterministicCalls,normalizeIdAuthorizations:e.normalizeIdAuthorizations,notifyCalls:e.notifyCalls,notifyConfig:e.notifyConfig,ownerFieldWrites:e.ownerFieldWrites,paymentWebhooks:e.paymentWebhooks,privilegedDispatches:e.privilegedDispatches,procedureProtections:e.procedureProtections,queries:e.queries??[],queues:e.queues,r2sqlCalls:e.r2sqlCalls,ratelimitKeySelectors:e.ratelimitKeySelectors,rawRowReturns:e.rawRowReturns,relationLoads:e.relationLoads,rlsProcedures:e.rlsProcedures,schema:o(e.schema),secretLiterals:e.secretLiterals,shapes:e.shapes===void 0?void 0:l(e.shapes),softDeleteReads:e.softDeleteReads,sqlInterpolations:e.sqlInterpolations,storageKeyAccesses:e.storageKeyAccesses,storageUploads:e.storageUploads,unrestrictedWhereBranches:e.unrestrictedWhereBranches,vectorNamespaceAccesses:e.vectorNamespaceAccesses,workflowCalls:e.workflowCalls,workflows:e.workflows,wranglerVariables:e.wranglerVariables}),m=e=>i(c(e),{source:"static"}),u=e=>{if(e.length===0)return"";const s=`@lunora/codegen: ${String(e.length)} schema advisor finding${e.length===1?"":"s"}`,a=e.map(t=>` [${t.level}] ${t.name}: ${t.detail}`);return[s,...a].join(`
2
+ `)};export{u as formatAdvisories,m as lintSchema,c as toAdvisorContext};
@@ -0,0 +1 @@
1
+ const s=/(?:^|\/)_generated\/server(?:\.js)?$/u,r=new Set(["@lunora/server","lunorash/server"]),n=e=>r.has(e),t=e=>s.test(e),o=e=>n(e)||t(e),a=new Set(["@lunora/scheduler",...r]),u=e=>a.has(e);export{u as E,n as o,o as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{Node as i}from"ts-morph";let c;const A=e=>{c=e},p=/^[A-Za-z_$][\w$]*$/u,g=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),k=(e,n)=>{const t={notNull:!0,...e.column};switch(n){case"$defaultFn":case"default":case"defaultNow":{t.hasDefault=!0;break}case"$onUpdateFn":{t.hasOnUpdate=!0;break}case"$type":break;case"nullable":{t.notNull=!1;break}case"unique":{t.unique=!0;break}}return{...e,column:t}},m=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),y=new Set(["check","meta"]),d=new Set,x=e=>{const n=e.getSymbol(),t=(n?.getAliasedSymbol()??n)?.getValueDeclaration();if(!(t===void 0||!i.isVariableDeclaration(t)))return t.getInitializer()},b="v",N=e=>{if(i.isIdentifier(e))return!0;let n=e;for(;i.isCallExpression(n);){const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return!1;n=t.getExpression()}return i.isIdentifier(n)&&n.getText()===b},o=e=>{if(i.isIdentifier(e)&&!d.has(e)){const n=x(e);if(n!==void 0&&N(n)){d.add(e);try{return o(n)}finally{d.delete(e)}}}return i.isCallExpression(e)?w(e):{kind:"any",sourceText:e.getText()}},E=e=>{const n={};for(const t of e.getProperties()){const a=i.isShorthandPropertyAssignment(t);if(!a&&!i.isPropertyAssignment(t))continue;const r=t.getNameNode();if(i.isComputedPropertyName(r))continue;const s=a?t.getNameNode():t.getInitializer();if(!s)continue;const l=t.getName();if(!p.test(l))throw new f("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(l)}`);n[l]=o(s)}return n},u=(e,n)=>e&&i.isExpression(e)?o(e):n,h=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),S=e=>{const n=e&&c?c(e):void 0;return n===void 0?{kind:"from"}:{kind:"from",tsType:n}},T=(e,n)=>{if(m.has(e))return{kind:e};const[t,a]=n;switch(e){case"array":return{inner:u(t,{kind:"any"}),kind:"array"};case"from":return S(t);case"id":return{kind:"id",tableName:t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:h(t)};case"object":return t&&i.isObjectLiteralExpression(t)?{kind:"object",shape:E(t)}:{kind:"object",shape:{}};case"optional":return{inner:u(t,{kind:"any"}),kind:"optional"};case"record":return{keyType:u(t,{kind:"string"}),kind:"record",valueType:u(a,{kind:"any"})};case"storage":return t&&i.isStringLiteral(t)?{bucket:t.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:n.filter(r=>i.isExpression(r)).map(r=>o(r))};default:throw new f("INTERNAL",`Unsupported validator kind: ${e}`)}},w=e=>{const n=e.getExpression();if(!i.isPropertyAccessExpression(n))return{kind:"any",sourceText:e.getText()};const t=n.getName(),a=e.getArguments();if(g.has(t)){const r=n.getExpression(),s=i.isExpression(r)?o(r):{kind:"any"};return k(s,t)}if(y.has(t)){const r=n.getExpression(),s=i.isExpression(r)?o(r):{kind:"any"};return t==="check"?{...s,hasRefinement:!0}:s}return T(t,a)};export{E as f,A as g,o as s};
@@ -0,0 +1 @@
1
+ const a=/\/index$/u,l=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(l,"_");export{c as n};
@@ -0,0 +1 @@
1
+ import{existsSync as i,readFileSync as f}from"node:fs";import{join as p}from"node:path";const l=t=>{const n=p(t,"package.json");if(i(n))try{const c=JSON.parse(f(n,"utf8")),o=new Set;for(const r of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=c[r];if(e!==null&&typeof e=="object")for(const s of Object.keys(e))o.add(s)}return o}catch{return}};export{l as default};
@@ -0,0 +1 @@
1
+ const s=/[\w+/=-]{40,}/u,a=/[a-z]/u,i=/[A-Z]/u,r=/\d/u,n=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,d=e=>{const t=s.exec(e)?.[0];return t===void 0?!1:a.test(t)&&i.test(t)&&r.test(t)},k=e=>n.test(e),c=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,o=/\bAKIA[\dA-Z]{16}\b/u,u=/\bgh[posru]_[\dA-Za-z]{36,}/u,h=/\bsk-[\dA-Za-z]{32,}/u,_=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,p=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,l=[{kind:"stripe_live_key",test:e=>c.test(e)},{kind:"aws_access_key",test:e=>o.test(e)},{kind:"github_token",test:e=>u.test(e)},{kind:"openai_key",test:e=>h.test(e)},{kind:"slack_token",test:e=>_.test(e)},{kind:"private_key",test:e=>p.test(e)},{kind:"high_entropy",test:d},{kind:"hex_secret",test:k}],A=new Set(["hex_secret","high_entropy"]),b=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),g=/([a-z\d])([A-Z])/gu,y=/[^A-Za-z\d]+/u,Z=e=>e.replaceAll(g,"$1 $2").split(y).filter(Boolean).map(t=>t.toLowerCase()),S=e=>e!==void 0&&Z(e).some(t=>b.has(t)),z=e=>l.find(t=>t.test(e))?.kind,E=e=>A.has(e),v=e=>`${e.slice(0,4)}…(${String(e.length)} chars)`;export{l as SECRET_RULES,E as isHeuristicSecretKind,S as isSecretishName,v as redact,z as secretKindOf};
@@ -0,0 +1 @@
1
+ const n=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}},a=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=a(e.inner)),e.members!==void 0&&(t.members=e.members.map(r=>a(r))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([r,l])=>[r,a(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=n(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=a(e.keyType)),e.valueType!==void 0&&(t.valueValidator=a(e.valueType)),{_meta:t,kind:e.kind}},i=e=>({tables:Object.fromEntries(e.tables.map(t=>[t.name,{shape:Object.fromEntries(Object.entries(t.shape).map(([r,l])=>[r,a(l)]))}]))});export{i as schemaFromIr};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.9",
3
+ "version": "1.0.0-alpha.90",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -25,7 +25,7 @@
25
25
  "directory": "packages/codegen"
26
26
  },
27
27
  "files": [
28
- "dist",
28
+ "./dist",
29
29
  "__assets__",
30
30
  "README.md",
31
31
  "LICENSE.md"
@@ -46,11 +46,16 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.4",
50
- "@lunora/container": "1.0.0-alpha.1",
51
- "@lunora/scheduler": "1.0.0-alpha.1",
52
- "@lunora/values": "1.0.0-alpha.2",
53
- "@lunora/workflow": "1.0.0-alpha.2",
49
+ "@lunora/advisor": "1.0.0-alpha.67",
50
+ "@lunora/agent": "1.0.0-alpha.41",
51
+ "@lunora/container": "1.0.0-alpha.23",
52
+ "@lunora/errors": "1.0.0-alpha.14",
53
+ "@lunora/platform": "1.0.0-alpha.6",
54
+ "@lunora/queue": "1.0.0-alpha.18",
55
+ "@lunora/scheduler": "1.0.0-alpha.21",
56
+ "@lunora/values": "1.0.0-alpha.19",
57
+ "@lunora/workflow": "1.0.0-alpha.21",
58
+ "jsonc-parser": "^3.3.1",
54
59
  "ts-morph": "^28.0.0"
55
60
  },
56
61
  "engines": {