@lunora/codegen 1.0.0-alpha.10 → 1.0.0-alpha.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +6 -0
- package/dist/index.d.mts +2730 -947
- package/dist/index.d.ts +2730 -947
- package/dist/index.mjs +1 -29
- package/dist/packem_shared/AGENTS_FILENAME-Dk-k250h.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-C5Dapn_Y.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-DkNdVeNM.mjs +3 -0
- package/dist/packem_shared/QUEUES_FILENAME-QpMZsde0.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-hQUs7FJj.mjs +9 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs +2 -0
- package/dist/packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs +16 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DcpvOBMi.mjs +3 -0
- package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
- package/dist/packem_shared/discover-ast-7ABwvTVn.mjs +1 -0
- package/dist/packem_shared/discover-queries-i4Vd2si7.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs +1 -0
- package/dist/packem_shared/discoverCrons-RlATa0_t.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-4TNKUv7P.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-DQivLBqT.mjs +1 -0
- package/dist/packem_shared/discoverInserts-D6szWzrV.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-BBPqLXA5.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-rbjxflR8.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs +1 -0
- package/dist/packem_shared/discoverQueries-uFtLDmn_.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-B63ARnKG.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-DBM98vVh.mjs +1 -0
- package/dist/packem_shared/discoverSchema-BNr7PVcZ.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs +1 -0
- package/dist/packem_shared/emit-B8FxCABN.mjs +2054 -0
- package/dist/packem_shared/emitApp-Dg-jOuj6.mjs +526 -0
- package/dist/packem_shared/formatAdvisories-CQvIhQ04.mjs +2 -0
- package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +1 -0
- package/dist/packem_shared/parse-validator-CusS8QwU.mjs +1 -0
- package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +1 -0
- package/dist/packem_shared/redact-6jD4lAhq.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
- package/package.json +12 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/GENERATED_HEADER-BiFXNUvo.mjs +0 -2692
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/OPENRPC_VERSION-B4i9Qp3v.mjs +0 -60
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bvv7qa_u.mjs +0 -939
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
- package/dist/packem_shared/buildOpenApiDocument-Cu3mZl-8.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-BnWHHJ4T.mjs +0 -822
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-KfMaKXWe.mjs +0 -603
- package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
import{n as S,S as D}from"./emit-B8FxCABN.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:a,hasFramework:r,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"),r&&g.push("FrameworkHostHandler");const f=[...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 { 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. 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}']:[]],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>;"]:[]],N=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
|
+
|
|
15
|
+
return this;
|
|
16
|
+
}`),I=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
|
+
}`]:[],...N(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
|
+
storageDownload: (key: string, opts?: { bucket?: string }) => pick(opts?.bucket).download(key),
|
|
275
|
+
storageList: (prefix?: string, opts?: { bucket?: string; cursor?: string; limit?: number }) => pick(opts?.bucket).list(prefix, opts),
|
|
276
|
+
storageSignedUrl: hasSigning
|
|
277
|
+
? (key: string, opts?: { bucket?: string; contentType?: string; expiresInSeconds?: number; method?: "GET" | "PUT" }) =>
|
|
278
|
+
pick(opts?.bucket).getSignedUrl(key, { contentType: opts?.contentType, expiresInSeconds: opts?.expiresInSeconds, method: opts?.method })
|
|
279
|
+
: undefined,
|
|
280
|
+
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
`:"",H=e=>e?`
|
|
284
|
+
/** 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\`). */
|
|
285
|
+
const buildExec = (database: D1DatabaseLike): D1Exec => {
|
|
286
|
+
const batchFn = database.batch;
|
|
287
|
+
|
|
288
|
+
return {
|
|
289
|
+
all: async (sql, parameters) => {
|
|
290
|
+
const result = await database
|
|
291
|
+
.prepare(sql)
|
|
292
|
+
.bind(...parameters)
|
|
293
|
+
.all<Record<string, unknown>>();
|
|
294
|
+
|
|
295
|
+
return result.results;
|
|
296
|
+
},
|
|
297
|
+
// D1's own \`batch\` runs the whole array as one atomic SQLite
|
|
298
|
+
// transaction. Guarded because \`D1DatabaseLike.batch\` is optional in
|
|
299
|
+
// the structural type (test doubles may omit it) — real D1 always has
|
|
300
|
+
// it; a double without it still works through the store's sequential
|
|
301
|
+
// fallback. Invoked via \`.call(database, ...)\` rather than
|
|
302
|
+
// \`database.batch(...)\` directly so TS can narrow the captured
|
|
303
|
+
// \`batchFn\` across the closure boundary (a property-access narrowing
|
|
304
|
+
// like \`hasBatch = typeof database.batch === "function"\` does not
|
|
305
|
+
// survive into a nested arrow function); \`.call\` still binds \`this\`
|
|
306
|
+
// to \`database\`, so the real workerd \`D1Database\` doesn't throw
|
|
307
|
+
// \`TypeError: Illegal invocation\` the way a detached
|
|
308
|
+
// \`const fn = database.batch; fn(...)\` capture would.
|
|
309
|
+
batch: batchFn
|
|
310
|
+
? async (statements) => {
|
|
311
|
+
await batchFn.call(
|
|
312
|
+
database,
|
|
313
|
+
statements.map(({ params, sql }) => database.prepare(sql).bind(...params)),
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
: undefined,
|
|
317
|
+
run: async (sql, parameters) => {
|
|
318
|
+
await database
|
|
319
|
+
.prepare(sql)
|
|
320
|
+
.bind(...parameters)
|
|
321
|
+
.run();
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
/** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
|
|
327
|
+
const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
|
|
328
|
+
const exec = buildExec(database);
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
|
|
332
|
+
listTables: () => listGlobalTables(exec, schema as never),
|
|
333
|
+
readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
|
|
334
|
+
};
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
|
|
339
|
+
* table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
|
|
340
|
+
* already record exactly this shape on the table) — mechanical, nothing to
|
|
341
|
+
* configure per project. \`undefined\` for a table the schema doesn't declare, so
|
|
342
|
+
* the import endpoint's own unknown-table handling still applies.
|
|
343
|
+
*/
|
|
344
|
+
const buildTableShardingResolver = (): AdminTableResolver => (table) => {
|
|
345
|
+
const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
|
|
346
|
+
|
|
347
|
+
return declared?.shardMode ? { mode: declared.shardMode } : undefined;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
|
|
352
|
+
* through the same D1 writer \`.global()\` reads/writes already use, via
|
|
353
|
+
* \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
|
|
354
|
+
* twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
|
|
355
|
+
* shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
|
|
356
|
+
*
|
|
357
|
+
* Passes each row's own \`line\` through rather than dropping it: the caller
|
|
358
|
+
* (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
|
|
359
|
+
* physical source line, and global rows are typically interspersed with
|
|
360
|
+
* shard-local ones it filtered out before calling here — a single
|
|
361
|
+
* \`startLine\` plus positional counting would mis-attribute every row after
|
|
362
|
+
* the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
|
|
363
|
+
* falls back to the position-derived count otherwise.
|
|
364
|
+
*/
|
|
365
|
+
const buildGlobalImporter =
|
|
366
|
+
(database: D1DatabaseLike) =>
|
|
367
|
+
(request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
|
|
368
|
+
const exec = buildExec(database);
|
|
369
|
+
const writer = createD1CtxDb({ exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
370
|
+
|
|
371
|
+
return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
|
|
372
|
+
exec,
|
|
373
|
+
rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
|
|
374
|
+
startLine: request.startLine,
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
`:"",U=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=j(e),r=W(e),n=t?` let auth: LunoraAuth | null = null;
|
|
378
|
+
`:"",o=t?`
|
|
379
|
+
const ensureAuth = async (env: Env): Promise<void> => {
|
|
380
|
+
if (!this.authDeclaration || auth) {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const d1 = this.authDeclaration.d1;
|
|
385
|
+
|
|
386
|
+
// DO-backed mode builds no instance here: better-auth runs inside the
|
|
387
|
+
// object, which materialises its own schema (the Kysely migrator below is
|
|
388
|
+
// dialect-bound and cannot target DO storage).
|
|
389
|
+
if (!d1) {
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
|
|
394
|
+
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
395
|
+
// migrator). For production run the migrate command ahead of deploy.
|
|
396
|
+
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
|
|
397
|
+
};
|
|
398
|
+
`:"",c=t?`
|
|
399
|
+
await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",u=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
400
|
+
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([
|
|
401
|
+
${l.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
|
|
402
|
+
`)}
|
|
403
|
+
]);
|
|
404
|
+
|
|
405
|
+
`:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
406
|
+
public build(): ComposedApp {
|
|
407
|
+
return this.assemble();
|
|
408
|
+
}${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(`
|
|
409
|
+
`)}
|
|
410
|
+
|
|
411
|
+
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
412
|
+
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
413
|
+
${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":""}
|
|
414
|
+
${a.join(`
|
|
415
|
+
|
|
416
|
+
`)}${a.length>0?`
|
|
417
|
+
|
|
418
|
+
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
419
|
+
interface ComposedApp extends LunoraWorker {
|
|
420
|
+
/** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
|
|
421
|
+
email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
422
|
+
/** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
|
|
423
|
+
ShardDO: ReturnType<typeof createShardDO>;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Fluent worker-composition builder. Records each capability declaration, then
|
|
428
|
+
* \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
|
|
429
|
+
* worker-side \`createWorker\` options — constructing the worker lazily on the
|
|
430
|
+
* first request so per-isolate singletons are built once.
|
|
431
|
+
*/
|
|
432
|
+
class AppBuilder<Env extends object> {
|
|
433
|
+
${q(e).join(`
|
|
434
|
+
`)}
|
|
435
|
+
|
|
436
|
+
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
437
|
+
|
|
438
|
+
${I(e).join(`
|
|
439
|
+
|
|
440
|
+
`)}
|
|
441
|
+
|
|
442
|
+
${b}
|
|
443
|
+
|
|
444
|
+
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
445
|
+
private assemble(${h}): ComposedApp {
|
|
446
|
+
const ShardDO = createShardDO({${G(e)}});
|
|
447
|
+
|
|
448
|
+
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
449
|
+
// build, so the first request constructs them and every later request on
|
|
450
|
+
// the same isolate reuses them.
|
|
451
|
+
let worker: LunoraWorker | null = null;
|
|
452
|
+
${n}${o}
|
|
453
|
+
${u}
|
|
454
|
+
|
|
455
|
+
const composed: ComposedApp = {
|
|
456
|
+
ShardDO,
|
|
457
|
+
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
458
|
+
const env = rawEnv as Env;${c}
|
|
459
|
+
worker ??= buildWorker(env);
|
|
460
|
+
|
|
461
|
+
return worker.fetch(request, rawEnv, context);
|
|
462
|
+
},
|
|
463
|
+
scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
464
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
465
|
+
|
|
466
|
+
return worker.scheduled(controller, rawEnv, context);
|
|
467
|
+
},
|
|
468
|
+
serverQuery: (request, rawEnv, reference, args, options) => {
|
|
469
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
470
|
+
|
|
471
|
+
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
472
|
+
},${e.hasQueue?`
|
|
473
|
+
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
474
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
475
|
+
|
|
476
|
+
return worker.queue?.(batch, rawEnv, context);
|
|
477
|
+
},`:""}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
${p} if (this.emailHandler) {
|
|
481
|
+
const handler = this.emailHandler;
|
|
482
|
+
|
|
483
|
+
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return composed;
|
|
487
|
+
}
|
|
488
|
+
${B(e.hasStorage)}
|
|
489
|
+
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
490
|
+
private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
|
|
491
|
+
const options: WorkerOptions = {
|
|
492
|
+
${$(e).join(`
|
|
493
|
+
`)}
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
if (this.adminToken) {
|
|
497
|
+
options.adminToken = this.adminToken(env);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
${r.join(`
|
|
501
|
+
|
|
502
|
+
`)}${r.length>0?`
|
|
503
|
+
|
|
504
|
+
`:""} for (const fn of this.extendFns) {
|
|
505
|
+
Object.assign(options, fn(env, { ...options }));
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
return options;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
${H(e.hasGlobal)}
|
|
512
|
+
/**
|
|
513
|
+
* Start composing the app. Chain the capability methods, then \`.build()\`.
|
|
514
|
+
*
|
|
515
|
+
* \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
|
|
516
|
+
* — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
|
|
517
|
+
* what any app with its own bindings declares — is NOT assignable to an index
|
|
518
|
+
* signature, so the stricter bound forced every real app to write
|
|
519
|
+
* \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
|
|
520
|
+
* through the selectors you pass it, so the looser bound costs nothing.
|
|
521
|
+
*/
|
|
522
|
+
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
523
|
+
|
|
524
|
+
export { AppBuilder, defineApp };
|
|
525
|
+
export type { ${U(e)} };
|
|
526
|
+
`};export{F as emitApp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as i}from"@lunora/advisor";const o=a=>[...a.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...a.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...a.rankIndexes.map(e=>({fields:[...e.sortBy.map(n=>n.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...a.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(a.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],r=a=>{const e={};for(const[n,t]of Object.entries(a.shape))e[n]=t.kind==="optional"?t.inner?.kind??"optional":t.kind;return e},d=a=>({rlsMode:a.rlsMode,tables:a.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:r(e),fields:Object.keys(e.shape),indexes:o(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(n=>({field:n.field,kind:n.kind,name:n.name,onDelete:n.onDelete,references:n.references,table:n.table})),shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),m=a=>a.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),c=a=>{const{argumentValidators:e,queries:n,schema:t,shapes:s,...l}=a;return{...l,argValidators:e,queries:n??[],schema:d(t),shapes:s===void 0?void 0:m(s)}},u=a=>i(c(a),{source:"static"}),h=a=>{if(a.length===0)return"";const e=`@lunora/codegen: ${String(a.length)} schema advisor finding${a.length===1?"":"s"}`,n=a.map(t=>` [${t.level}] ${t.name}: ${t.detail}`);return[e,...n].join(`
|
|
2
|
+
`)};export{h as formatAdvisories,u 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 g}from"@lunora/errors";import{Node as r}from"ts-morph";let c;const v=e=>{c=e},p=/^[A-Za-z_$][\w$]*$/u,f=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,b=e=>{const n=e.getSymbol(),t=(n?.getAliasedSymbol()??n)?.getValueDeclaration();if(!(t===void 0||!r.isVariableDeclaration(t)))return t.getInitializer()},x="v",N=e=>{if(r.isIdentifier(e))return!0;let n=e;for(;r.isCallExpression(n);){const t=n.getExpression();if(!r.isPropertyAccessExpression(t))return!1;n=t.getExpression()}return r.isIdentifier(n)&&n.getText()===x},o=e=>{if(r.isIdentifier(e)&&!d.has(e)){const n=b(e);if(n!==void 0&&N(n)){d.add(e);try{return o(n)}finally{d.delete(e)}}}return r.isCallExpression(e)?w(e):{kind:"any",sourceText:e.getText()}},h=e=>{const n={};for(const t of e.getProperties()){const s=r.isShorthandPropertyAssignment(t);if(!s&&!r.isPropertyAssignment(t))continue;const i=t.getNameNode();if(r.isComputedPropertyName(i))continue;const a=s?t.getNameNode():t.getInitializer();if(!a)continue;const l=t.getName();if(!p.test(l))throw new g("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(l)}`);n[l]=o(a)}return n},u=(e,n)=>e&&r.isExpression(e)?o(e):n,E=e=>e===void 0?"undefined":r.isStringLiteral(e)||r.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,s]=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&&r.isStringLiteral(t)?t.getLiteralText():"_unknown_"};case"literal":return{kind:"literal",literalValue:E(t)};case"object":return t&&r.isObjectLiteralExpression(t)?{kind:"object",shape:h(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(s,{kind:"any"})};case"storage":return t&&r.isStringLiteral(t)?{bucket:t.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:n.filter(i=>r.isExpression(i)).map(i=>o(i))};default:throw new g("INTERNAL",`Unsupported validator kind: ${e}`)}},w=e=>{const n=e.getExpression();if(!r.isPropertyAccessExpression(n))return{kind:"any",sourceText:e.getText()};const t=n.getName(),s=e.getArguments();if(f.has(t)||y.has(t)){const i=n.getExpression(),a=r.isExpression(i)?o(i):{kind:"any"};return f.has(t)?k(a,t):t==="check"?{...a,hasRefinement:!0}:a}return T(t,s)};export{h as g,o as s,v as y};
|
|
@@ -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.
|
|
3
|
+
"version": "1.0.0-alpha.100",
|
|
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.
|
|
50
|
-
"@lunora/
|
|
51
|
-
"@lunora/
|
|
52
|
-
"@lunora/
|
|
53
|
-
"@lunora/
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.72",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.48",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.26",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.17",
|
|
53
|
+
"@lunora/platform": "1.0.0-alpha.8",
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.22",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.25",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.22",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.24",
|
|
58
|
+
"jsonc-parser": "^3.3.1",
|
|
54
59
|
"ts-morph": "^28.0.0"
|
|
55
60
|
},
|
|
56
61
|
"engines": {
|