@lunora/codegen 1.0.0-alpha.124 → 1.0.0-alpha.126
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-BTQa3OFD.mjs → GENERATED_HEADER-NWWDWOX4.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DRHMcH-x.mjs → OPENRPC_VERSION-6XrIwoNr.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME--CCXsODJ.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-DvTuBr8Z.mjs → buildOpenApiDocument-DDvSUMD9.mjs} +1 -1
- package/dist/packem_shared/{emit-C_sJaMGR.mjs → emit-GW3Jf9w0.mjs} +315 -214
- package/dist/packem_shared/{emitApp-BuPtPsJ1.mjs → emitApp-D-mz_p6P.mjs} +141 -45
- package/package.json +10 -10
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bb_4PKpT.mjs +0 -9
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-
|
|
1
|
+
import{A as S,G as D}from"./emit-GW3Jf9w0.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";']:[],C=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,O=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],T=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],L=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:h,hasWorkflow:u,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"),r&&g.push("FrameworkHostHandler");const w=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } 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";']:[],...h?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...u?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...O(e),`import type { ${[...g].toSorted((f,y)=>f.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${w} } from "${i}";`,"",...A(e.identity),...T(e),...n||o?['import schema from "../schema.js";']:[],...C(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";']},q=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
2
|
interface StorageDeclaration<Env> {
|
|
3
3
|
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
4
|
bucket: Selector<Env, R2BucketLike>;
|
|
@@ -8,17 +8,17 @@ interface StorageDeclaration<Env> {
|
|
|
8
8
|
publicBaseUrl?: Selector<Env, string>;
|
|
9
9
|
/** HMAC secret for signed URLs. */
|
|
10
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. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],
|
|
12
|
-
public ${t}(factory: NonNullable<ShardConfig["${
|
|
13
|
-
this.shardExtras.${
|
|
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. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],I=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," 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>;"]:[]],G=e=>v.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
12
|
+
public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
|
|
13
|
+
this.shardExtras.${a} = factory;
|
|
14
14
|
|
|
15
15
|
return this;
|
|
16
|
-
}`),
|
|
16
|
+
}`),N=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
17
17
|
public admin(selector: Selector<Env, string>): this {
|
|
18
18
|
this.adminToken = selector;
|
|
19
19
|
|
|
20
20
|
return this;
|
|
21
|
-
}
|
|
21
|
+
}`," /**\n * Opt into change-data-capture: every write records a post-image to `__cdc_log` — on this shard AND, when the app has `.global()` tables, on the global backend. Backs streaming export, replay-PITR, and the `.global()` half of `defineShape` replication (whose poll tick asks the global changelog which tables moved). Off by default: it costs a changelog row per write, which an app using none of the above should not pay.\n *\n * REQUIRED for a shard-local `defineShape`: those replicate out of `__cdc_log`, and a `shape_subscribe` is refused with `SHAPE_REQUIRES_CDC` without it.\n *\n * It also changes how fresh a `.global()` shape is against writes made OUTSIDE `ctx.db` — an admin import, a PITR replay, an external ETL job, or a predicate over wall clock. With CDC off the poll re-reads every shape every 2s. With it on the poll asks the global changelog which tables moved and skips the rest, so a change the changelog never saw waits for the 30s unconditional resync instead. Writes through `ctx.db` are unaffected: they append, so the poll sees them on the next tick either way.\n */\n public cdc(enabled = true): this {\n this.cdcEnabled = enabled;\n\n return this;\n }",...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
22
|
public global(declaration: GlobalDeclaration<Env>): this {
|
|
23
23
|
this.globalDeclaration = declaration;
|
|
24
24
|
|
|
@@ -53,9 +53,10 @@ interface StorageDeclaration<Env> {
|
|
|
53
53
|
this.storageDeclaration = declaration;
|
|
54
54
|
|
|
55
55
|
return this;
|
|
56
|
-
}`]:[],...
|
|
56
|
+
}`]:[],...G(e)],j=e=>{const t=r=>e.hasScheduler?`
|
|
57
|
+
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
57
58
|
? {
|
|
58
|
-
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
59
|
+
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
59
60
|
const env = rawEnv as Env;
|
|
60
61
|
const database = this.globalDeclaration?.d1(env);
|
|
61
62
|
|
|
@@ -69,8 +70,14 @@ interface StorageDeclaration<Env> {
|
|
|
69
70
|
: undefined;
|
|
70
71
|
|
|
71
72
|
return createD1CtxDb({
|
|
72
|
-
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {})
|
|
73
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
|
|
74
|
+
...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
|
|
73
75
|
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
76
|
+
// Forwarded from the shard's own \`cdc\` config, so ONE
|
|
77
|
+
// switch governs both changelogs. Built without it, the
|
|
78
|
+
// global \`__cdc_log\` is never written and the shape
|
|
79
|
+
// poll's changed-tables fast path is unreachable.
|
|
80
|
+
cdc: request?.cdc ?? false,
|
|
74
81
|
exec: buildExec(database, request?.bookmark, request?.onBookmark),
|
|
75
82
|
schema: schema as unknown as D1CtxDbOptions["schema"],
|
|
76
83
|
});
|
|
@@ -78,7 +85,7 @@ interface StorageDeclaration<Env> {
|
|
|
78
85
|
}
|
|
79
86
|
: {}),`]:[],...e.hasHyperdriveGlobal?[` ...(this.hyperdriveGlobalDeclaration
|
|
80
87
|
? {
|
|
81
|
-
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
88
|
+
hyperdriveGlobal: (rawEnv: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string | null }) => {
|
|
82
89
|
const env = rawEnv as Env;
|
|
83
90
|
const exec = this.hyperdriveGlobalDeclaration?.exec(env) as SqlExec | undefined;
|
|
84
91
|
|
|
@@ -92,8 +99,11 @@ interface StorageDeclaration<Env> {
|
|
|
92
99
|
: undefined;
|
|
93
100
|
|
|
94
101
|
return createHyperdriveGlobalCtxDb({
|
|
95
|
-
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {})
|
|
102
|
+
...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
|
|
103
|
+
...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
|
|
96
104
|
auth: { identity: request?.identity ?? null, userId: request?.userId ?? null },
|
|
105
|
+
// See the D1 twin: one \`cdc\` switch, both changelogs.
|
|
106
|
+
cdc: request?.cdc ?? false,
|
|
97
107
|
engine: this.hyperdriveGlobalDeclaration?.engine as HyperdriveEngine,
|
|
98
108
|
exec,
|
|
99
109
|
schema: schema as unknown as SqlCtxDbOptions["schema"],
|
|
@@ -102,18 +112,12 @@ interface StorageDeclaration<Env> {
|
|
|
102
112
|
}
|
|
103
113
|
: {}),`]:[],...e.hasScheduler?[` ...(this.schedulerDeclaration
|
|
104
114
|
? {
|
|
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
|
-
},
|
|
115
|
+
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
112
116
|
}
|
|
113
|
-
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...
|
|
114
|
-
${
|
|
117
|
+
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
118
|
+
${a.join(`
|
|
115
119
|
`)}
|
|
116
|
-
`:""},
|
|
120
|
+
`:""},B=e=>[...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
117
121
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
118
122
|
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
119
123
|
const source = workflowEnv as Record<string, unknown>;
|
|
@@ -137,7 +141,18 @@ ${t.join(`
|
|
|
137
141
|
// happened. Both are mechanical over the schema this file already
|
|
138
142
|
// imports, so there is nothing project-specific to configure.
|
|
139
143
|
options.resolveTableSharding = buildTableShardingResolver();
|
|
140
|
-
options.importGlobals = buildGlobalImporter(database);
|
|
144
|
+
options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
|
|
145
|
+
// The read/replay half of the same admin plane. Each one is the
|
|
146
|
+
// only reason its endpoint can see the global storage plane at
|
|
147
|
+
// all, and every one of them fails SILENTLY when unset — export
|
|
148
|
+
// and \`lunora backup create\` answer 200 having written only
|
|
149
|
+
// shard-local rows (an export→import round trip then restores
|
|
150
|
+
// cleanly minus every global row), CDC sync answers with only
|
|
151
|
+
// shard changes, and point-in-time apply reports
|
|
152
|
+
// \`globalApplied: 0\`. Nothing here is project-specific either.
|
|
153
|
+
options.exportGlobals = buildGlobalExporter(database);
|
|
154
|
+
options.syncGlobals = buildGlobalCdcSync(database);
|
|
155
|
+
options.applyGlobals = buildGlobalCdcApplier(database, this.cdcEnabled);
|
|
141
156
|
}
|
|
142
157
|
}`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
|
|
143
158
|
Object.assign(options, this.buildStorageAdmin(env));
|
|
@@ -200,7 +215,15 @@ ${t.join(`
|
|
|
200
215
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
201
216
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
202
217
|
`)}
|
|
203
|
-
};`]:[]],
|
|
218
|
+
};`]:[]],W=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),"],$=e=>e.hasScheduler?`
|
|
219
|
+
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until both the namespace and origin are wired. */
|
|
220
|
+
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
221
|
+
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
222
|
+
const origin = this.schedulerDeclaration?.origin?.(env);
|
|
223
|
+
|
|
224
|
+
return namespace && origin ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace, originUrl: origin }) : undefined;
|
|
225
|
+
}
|
|
226
|
+
`:"",P=e=>e?`
|
|
204
227
|
/** Resolve the storage capability (single or multi-bucket) for the DO side. */
|
|
205
228
|
private resolveStorage(env: Env): Storage | undefined {
|
|
206
229
|
const declaration = this.storageDeclaration;
|
|
@@ -387,10 +410,12 @@ const buildTableShardingResolver = (): AdminTableResolver => (table) => {
|
|
|
387
410
|
* falls back to the position-derived count otherwise.
|
|
388
411
|
*/
|
|
389
412
|
const buildGlobalImporter =
|
|
390
|
-
(database: D1DatabaseLike) =>
|
|
413
|
+
(database: D1DatabaseLike, cdc: boolean) =>
|
|
391
414
|
(request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
|
|
392
415
|
const exec = buildExec(database);
|
|
393
|
-
|
|
416
|
+
// Same reason the PITR applier carries it: a bulk import that skips the
|
|
417
|
+
// changelog restores rows no downstream consumer is ever told about.
|
|
418
|
+
const writer = createD1CtxDb({ cdc, exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
394
419
|
|
|
395
420
|
return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
|
|
396
421
|
exec,
|
|
@@ -398,7 +423,78 @@ const buildGlobalImporter =
|
|
|
398
423
|
startLine: request.startLine,
|
|
399
424
|
});
|
|
400
425
|
};
|
|
401
|
-
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* \`exportGlobals\` for the admin export endpoint (and the scheduled R2 backup,
|
|
429
|
+
* which drains the same stream): the read twin of {@link buildGlobalImporter},
|
|
430
|
+
* over the same D1 handle. \`@lunora/d1\`'s \`exportGlobalRows\` keyset-paginates
|
|
431
|
+
* each table and provisions the schema's global tables first, so a table that
|
|
432
|
+
* was never written exports as empty instead of throwing \`no such table\`.
|
|
433
|
+
*
|
|
434
|
+
* \`tables\` is forwarded as-is: the runtime passes an empty array for "every
|
|
435
|
+
* table" (its \`tables === undefined\` case), which is exactly what
|
|
436
|
+
* \`selectGlobalTables\` reads an empty allowlist as.
|
|
437
|
+
*/
|
|
438
|
+
const buildGlobalExporter =
|
|
439
|
+
(database: D1DatabaseLike) =>
|
|
440
|
+
(request: { tables: ReadonlyArray<string> }) =>
|
|
441
|
+
exportGlobalRows(buildExec(database), schema as unknown as D1CtxDbOptions["schema"], { tables: request.tables });
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* \`syncGlobals\` for the admin CDC sync + warehouse-connector endpoints: pages
|
|
445
|
+
* the global \`__cdc_log\` past \`sinceSeq\`, the global-plane twin of the shard's
|
|
446
|
+
* \`runShardCdcSync\`.
|
|
447
|
+
*
|
|
448
|
+
* Probes \`sqlite_master\` first, exactly as the shard twin does. The changelog
|
|
449
|
+
* table is only created when the global writer runs with CDC enabled, so on
|
|
450
|
+
* every other app a straight read would throw \`no such table: __cdc_log\` and
|
|
451
|
+
* turn "nothing has changed yet" into a 500. Absent log ⇒ an empty page that
|
|
452
|
+
* leaves the caller's cursor where it was.
|
|
453
|
+
*/
|
|
454
|
+
const buildGlobalCdcSync =
|
|
455
|
+
(database: D1DatabaseLike) =>
|
|
456
|
+
async (request: { limit?: number; sinceSeq: number }): Promise<{ changes: ReadonlyArray<Record<string, unknown>>; cursor: number }> => {
|
|
457
|
+
const exec = buildExec(database);
|
|
458
|
+
const present = await exec.all(\`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\`, ["__cdc_log"]);
|
|
459
|
+
|
|
460
|
+
if (present.length === 0) {
|
|
461
|
+
return { changes: [], cursor: request.sinceSeq };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const page = await readD1CdcChanges(exec, { limit: request.limit, sinceSeq: request.sinceSeq });
|
|
465
|
+
|
|
466
|
+
// \`as unknown as\`, because \`CdcChange\` is an interface and interfaces carry
|
|
467
|
+
// no implicit index signature — the shapes are otherwise identical.
|
|
468
|
+
return { changes: page.changes as unknown as ReadonlyArray<Record<string, unknown>>, cursor: page.cursor };
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* \`applyGlobals\` for the admin point-in-time-recovery apply endpoint: replays a
|
|
473
|
+
* batch of global CDC changes through the same D1 writer \`.global()\` writes go
|
|
474
|
+
* through, and reports how many were replayed.
|
|
475
|
+
*
|
|
476
|
+
* \`applyCdcChanges\` is order-sensitive and idempotent per row (insert, falling
|
|
477
|
+
* back to replace on conflict), so the batch is handed over untouched — the
|
|
478
|
+
* caller already emits it in commit order. The changes arrive as plain parsed
|
|
479
|
+
* JSON off the wire, hence the cast to the replayer's own change shape.
|
|
480
|
+
*
|
|
481
|
+
* The writer carries the app's own \`cdc\` setting, so a replay APPENDS to the
|
|
482
|
+
* global changelog like any other write. Built without it the restored rows
|
|
483
|
+
* reach the tables and nothing else: a warehouse connector's cursor walks past a
|
|
484
|
+
* range that has no entries and its mirror silently diverges from the database,
|
|
485
|
+
* with nothing on either side able to notice — and every live \`.global()\` shape
|
|
486
|
+
* misses the restore until the next unconditional resync.
|
|
487
|
+
*/
|
|
488
|
+
const buildGlobalCdcApplier =
|
|
489
|
+
(database: D1DatabaseLike, cdc: boolean) =>
|
|
490
|
+
async (request: { changes: ReadonlyArray<Record<string, unknown>> }): Promise<number> => {
|
|
491
|
+
const writer = createD1CtxDb({ cdc, exec: buildExec(database), schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
492
|
+
|
|
493
|
+
await applyCdcChanges(writer, request.changes as unknown as Parameters<typeof applyCdcChanges>[1]);
|
|
494
|
+
|
|
495
|
+
return request.changes.length;
|
|
496
|
+
};
|
|
497
|
+
`:"",_=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const{hasAuth:t}=e,a=q(e),r=B(e),n=t?` let auth: LunoraAuth | null = null;
|
|
402
498
|
`:"",o=t?`
|
|
403
499
|
const ensureAuth = async (env: Env): Promise<void> => {
|
|
404
500
|
if (!this.authDeclaration || auth) {
|
|
@@ -419,25 +515,25 @@ const buildGlobalImporter =
|
|
|
419
515
|
// migrator). For production run the migrate command ahead of deploy.
|
|
420
516
|
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
|
|
421
517
|
};
|
|
422
|
-
`:"",
|
|
423
|
-
await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",
|
|
424
|
-
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}));`,
|
|
425
|
-
${
|
|
518
|
+
`:"",c=t?`
|
|
519
|
+
await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",h=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
520
|
+
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}));`,u=e.hasFramework?"host?: FrameworkHostHandler":"",l=e.emailAgents??[],p=l.length>0?` composed.email = dispatchAgentEmail([
|
|
521
|
+
${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
|
|
426
522
|
`)}
|
|
427
523
|
]);
|
|
428
524
|
|
|
429
525
|
`:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
430
526
|
public build(): ComposedApp {
|
|
431
527
|
return this.assemble();
|
|
432
|
-
}${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}${
|
|
528
|
+
}${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}${L(e).join(`
|
|
433
529
|
`)}
|
|
434
530
|
|
|
435
531
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
436
532
|
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
437
|
-
${
|
|
438
|
-
${
|
|
533
|
+
${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":""}
|
|
534
|
+
${a.join(`
|
|
439
535
|
|
|
440
|
-
`)}${
|
|
536
|
+
`)}${a.length>0?`
|
|
441
537
|
|
|
442
538
|
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
443
539
|
interface ComposedApp extends LunoraWorker {
|
|
@@ -454,32 +550,32 @@ interface ComposedApp extends LunoraWorker {
|
|
|
454
550
|
* first request so per-isolate singletons are built once.
|
|
455
551
|
*/
|
|
456
552
|
class AppBuilder<Env extends object> {
|
|
457
|
-
${
|
|
553
|
+
${I(e).join(`
|
|
458
554
|
`)}
|
|
459
555
|
|
|
460
556
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
461
557
|
|
|
462
|
-
${
|
|
558
|
+
${N(e).join(`
|
|
463
559
|
|
|
464
560
|
`)}
|
|
465
561
|
|
|
466
562
|
${b}
|
|
467
563
|
|
|
468
564
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
469
|
-
private assemble(${
|
|
470
|
-
const ShardDO = createShardDO({${
|
|
565
|
+
private assemble(${u}): ComposedApp {
|
|
566
|
+
const ShardDO = createShardDO({${j(e)}});
|
|
471
567
|
|
|
472
568
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
473
569
|
// build, so the first request constructs them and every later request on
|
|
474
570
|
// the same isolate reuses them.
|
|
475
571
|
let worker: LunoraWorker | null = null;
|
|
476
572
|
${n}${o}
|
|
477
|
-
${
|
|
573
|
+
${h}
|
|
478
574
|
|
|
479
575
|
const composed: ComposedApp = {
|
|
480
576
|
ShardDO,
|
|
481
577
|
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
482
|
-
const env = rawEnv as Env;${
|
|
578
|
+
const env = rawEnv as Env;${c}
|
|
483
579
|
worker ??= buildWorker(env);
|
|
484
580
|
|
|
485
581
|
return worker.fetch(request, rawEnv, context);
|
|
@@ -509,11 +605,11 @@ ${p} if (this.emailHandler) {
|
|
|
509
605
|
|
|
510
606
|
return composed;
|
|
511
607
|
}
|
|
512
|
-
${$(e.hasStorage)}
|
|
608
|
+
${$(e)}${P(e.hasStorage)}
|
|
513
609
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
514
610
|
private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
|
|
515
611
|
const options: WorkerOptions = {
|
|
516
|
-
${
|
|
612
|
+
${W(e).join(`
|
|
517
613
|
`)}
|
|
518
614
|
};
|
|
519
615
|
|
|
@@ -521,9 +617,9 @@ ${G(e).join(`
|
|
|
521
617
|
options.adminToken = this.adminToken(env);
|
|
522
618
|
}
|
|
523
619
|
|
|
524
|
-
${
|
|
620
|
+
${r.join(`
|
|
525
621
|
|
|
526
|
-
`)}${
|
|
622
|
+
`)}${r.length>0?`
|
|
527
623
|
|
|
528
624
|
`:""} for (const fn of this.extendFns) {
|
|
529
625
|
Object.assign(options, fn(env, { ...options }));
|
|
@@ -546,5 +642,5 @@ ${H(e.hasGlobal)}
|
|
|
546
642
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
547
643
|
|
|
548
644
|
export { AppBuilder, defineApp };
|
|
549
|
-
export type { ${
|
|
645
|
+
export type { ${_(e)} };
|
|
550
646
|
`};export{F as emitApp};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.126",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
53
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.90",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.65",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.35",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.24",
|
|
53
|
+
"@lunora/platform": "1.0.0-alpha.18",
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.35",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.39",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.29",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.33",
|
|
58
58
|
"jsonc-parser": "^3.3.1",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|