@lunora/codegen 1.0.0-alpha.12 → 1.0.0-alpha.121
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 +2986 -958
- package/dist/index.d.ts +2986 -958
- package/dist/index.mjs +1 -30
- package/dist/packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-Dtmu39TP.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-B_KsWp7_.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-B2-W8Bm3.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-IJXY4yHt.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-CX52iE6f.mjs +3 -0
- package/dist/packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DL1A739E.mjs +9 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-CFyux-74.mjs +371 -0
- package/dist/packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-BoHDfCO3.mjs +16 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-VeBRFs54.mjs +3 -0
- package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
- package/dist/packem_shared/discover-ast-D33zP-NZ.mjs +1 -0
- package/dist/packem_shared/discover-queries-Dfj_0WJG.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BUJO2ipU.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-006teuNG.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-BxF4FRZL.mjs +1 -0
- package/dist/packem_shared/discoverInserts-YX8AmrzL.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-BCl3fNrQ.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-4Jjf5DJE.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-BA91Z-vF.mjs +1 -0
- package/dist/packem_shared/discoverQueries-C5S9tFoD.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-M2ob41UX.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-Dwt2p8IK.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-L0lV17de.mjs +1 -0
- package/dist/packem_shared/discoverSchema-gJ93Xjpx.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-69Y8wZb2.mjs +1 -0
- package/dist/packem_shared/emit-CW4ceRjr.mjs +2167 -0
- package/dist/packem_shared/emitApp-BMm-xmNg.mjs +550 -0
- package/dist/packem_shared/formatAdvisories-CkEu1eye.mjs +2 -0
- package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/parse-validator-C5ycrhR3.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.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-BEA7oWGC.mjs +0 -2841
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/OPENRPC_VERSION-CQ3f8YQ-.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BXtduJFE.mjs +0 -954
- 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-699G4RP4.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-DiK0QSBn.mjs +0 -617
- 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,550 @@
|
|
|
1
|
+
import{A as S,G as D}from"./emit-CW4ceRjr.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]),g=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage, 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(l),...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 { ${[...m].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";']},I=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}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," 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>;"]:[],...g(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,r,a])=>` /** ${a} */
|
|
12
|
+
public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
|
|
13
|
+
this.shardExtras.${r} = factory;
|
|
14
|
+
|
|
15
|
+
return this;
|
|
16
|
+
}`),q=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
|
+
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)],B=e=>{const t=[...e.hasGlobal?[` ...(this.globalDeclaration
|
|
57
|
+
? {
|
|
58
|
+
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; 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, request?.bookmark, request?.onBookmark),
|
|
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) } : {}),"]:[],...g(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
|
+
};`]:[]],G=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?`
|
|
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
|
+
/**
|
|
285
|
+
* 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\`).
|
|
286
|
+
*
|
|
287
|
+
* Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
|
|
288
|
+
* last-known write, when supplied) so reads observe it — read-your-writes
|
|
289
|
+
* across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
|
|
290
|
+
* produced by each write so the caller (the generated DO) can record it via
|
|
291
|
+
* \`setOutboundBookmark\` and echo \`x-d1-bookmark\` on the response.
|
|
292
|
+
*
|
|
293
|
+
* Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
|
|
294
|
+
* (storage-object resets, isolate memory evictions, dropped connections) does
|
|
295
|
+
* not surface on every \`.global()\` read. Only statements that are provably
|
|
296
|
+
* read-only retry; writes — including the \`UPDATE … RETURNING\` the store's
|
|
297
|
+
* optimistic-concurrency check issues through \`all\` — pass straight through,
|
|
298
|
+
* because a transient error never says whether the write applied.
|
|
299
|
+
*/
|
|
300
|
+
const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bookmark: string | undefined) => void): D1Exec => {
|
|
301
|
+
// Real D1 always exposes \`withSession\`; guarded the same way as \`batch\`
|
|
302
|
+
// below so a hand-rolled test double that omits it keeps working via
|
|
303
|
+
// \`prepare()\` straight on the raw binding — today's behaviour. With no
|
|
304
|
+
// inbound bookmark, \`"first-unconstrained"\` is the documented no-op
|
|
305
|
+
// equivalent (lowest latency, may read any replica) — see \`D1Client.withSession\`.
|
|
306
|
+
const session = typeof database.withSession === "function" ? database.withSession(bookmark ?? "first-unconstrained") : undefined;
|
|
307
|
+
const target = session ?? database;
|
|
308
|
+
const batchFn = target.batch;
|
|
309
|
+
|
|
310
|
+
return retryingExec({
|
|
311
|
+
all: async (sql, parameters) => {
|
|
312
|
+
const result = await target
|
|
313
|
+
.prepare(sql)
|
|
314
|
+
.bind(...parameters)
|
|
315
|
+
.all<Record<string, unknown>>();
|
|
316
|
+
|
|
317
|
+
return result.results;
|
|
318
|
+
},
|
|
319
|
+
// D1's own \`batch\` runs the whole array as one atomic SQLite
|
|
320
|
+
// transaction. Guarded because \`batch\` is optional in the structural
|
|
321
|
+
// type (test doubles may omit it) — real D1 always has it; a double
|
|
322
|
+
// without it still works through the store's sequential fallback.
|
|
323
|
+
// Invoked via \`.call(target, ...)\` rather than \`target.batch(...)\`
|
|
324
|
+
// directly so TS can narrow the captured \`batchFn\` across the closure
|
|
325
|
+
// boundary (a property-access narrowing like
|
|
326
|
+
// \`hasBatch = typeof target.batch === "function"\` does not survive
|
|
327
|
+
// into a nested arrow function); \`.call\` still binds \`this\` to
|
|
328
|
+
// \`target\`, so the real workerd \`D1Database\`/session doesn't throw
|
|
329
|
+
// \`TypeError: Illegal invocation\` the way a detached
|
|
330
|
+
// \`const fn = target.batch; fn(...)\` capture would.
|
|
331
|
+
batch: batchFn
|
|
332
|
+
? async (statements) => {
|
|
333
|
+
await batchFn.call(
|
|
334
|
+
target,
|
|
335
|
+
statements.map(({ params, sql }) => target.prepare(sql).bind(...params)),
|
|
336
|
+
);
|
|
337
|
+
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
338
|
+
}
|
|
339
|
+
: undefined,
|
|
340
|
+
run: async (sql, parameters) => {
|
|
341
|
+
await target
|
|
342
|
+
.prepare(sql)
|
|
343
|
+
.bind(...parameters)
|
|
344
|
+
.run();
|
|
345
|
+
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
346
|
+
},
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
/** Introspect \`.global()\` (D1-backed) tables for the studio's global data browser. */
|
|
351
|
+
const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector => {
|
|
352
|
+
const exec = buildExec(database);
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
facetColumn: (options) => facetGlobalColumn(exec, schema as never, options),
|
|
356
|
+
listTables: () => listGlobalTables(exec, schema as never),
|
|
357
|
+
readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
|
|
358
|
+
};
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* \`resolveTableSharding\` for the admin bulk-import endpoint: a lookup over each
|
|
363
|
+
* table's declared \`shardMode\` (\`defineTable(...).global()\` / \`.shardBy(field)\`
|
|
364
|
+
* already record exactly this shape on the table) — mechanical, nothing to
|
|
365
|
+
* configure per project. \`undefined\` for a table the schema doesn't declare, so
|
|
366
|
+
* the import endpoint's own unknown-table handling still applies.
|
|
367
|
+
*/
|
|
368
|
+
const buildTableShardingResolver = (): AdminTableResolver => (table) => {
|
|
369
|
+
const declared = (schema as unknown as D1CtxDbOptions["schema"]).tables[table];
|
|
370
|
+
|
|
371
|
+
return declared?.shardMode ? { mode: declared.shardMode } : undefined;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* \`importGlobals\` for the admin bulk-import endpoint: routes \`.global()\` rows
|
|
376
|
+
* through the same D1 writer \`.global()\` reads/writes already use, via
|
|
377
|
+
* \`@lunora/d1\`'s \`importGlobalRows\`. Mirrors \`runShardImport\`'s shard-local
|
|
378
|
+
* twin (\`createShardCtxDb\` + \`importShardRows\`) — same \`{ rows, startLine }\`
|
|
379
|
+
* shape, same trusted-import \`allowExplicitId\` semantics, forwarded as-is.
|
|
380
|
+
*
|
|
381
|
+
* Passes each row's own \`line\` through rather than dropping it: the caller
|
|
382
|
+
* (\`@lunora/runtime\`'s NDJSON import stream) already carries the row's true
|
|
383
|
+
* physical source line, and global rows are typically interspersed with
|
|
384
|
+
* shard-local ones it filtered out before calling here — a single
|
|
385
|
+
* \`startLine\` plus positional counting would mis-attribute every row after
|
|
386
|
+
* the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
|
|
387
|
+
* falls back to the position-derived count otherwise.
|
|
388
|
+
*/
|
|
389
|
+
const buildGlobalImporter =
|
|
390
|
+
(database: D1DatabaseLike) =>
|
|
391
|
+
(request: { rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
|
|
392
|
+
const exec = buildExec(database);
|
|
393
|
+
const writer = createD1CtxDb({ exec, schema: schema as unknown as D1CtxDbOptions["schema"] });
|
|
394
|
+
|
|
395
|
+
return importGlobalRows(writer, schema as unknown as D1CtxDbOptions["schema"], {
|
|
396
|
+
exec,
|
|
397
|
+
rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
|
|
398
|
+
startLine: request.startLine,
|
|
399
|
+
});
|
|
400
|
+
};
|
|
401
|
+
`:"",P=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=I(e),a=W(e),n=t?` let auth: LunoraAuth | null = null;
|
|
402
|
+
`:"",o=t?`
|
|
403
|
+
const ensureAuth = async (env: Env): Promise<void> => {
|
|
404
|
+
if (!this.authDeclaration || auth) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const d1 = this.authDeclaration.d1;
|
|
409
|
+
|
|
410
|
+
// DO-backed mode builds no instance here: better-auth runs inside the
|
|
411
|
+
// object, which materialises its own schema (the Kysely migrator below is
|
|
412
|
+
// dialect-bound and cannot target DO storage).
|
|
413
|
+
if (!d1) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
auth = createAuth({ ...this.authDeclaration.options(env), database: lunoraD1Adapter(d1(env) as never) });
|
|
418
|
+
// Apply the better-auth schema lazily on first request (raw-D1 Kysely
|
|
419
|
+
// migrator). For production run the migrate command ahead of deploy.
|
|
420
|
+
await ensureMigrated(createAuth({ ...this.authDeclaration.options(env), database: d1(env) as never }));
|
|
421
|
+
};
|
|
422
|
+
`:"",l=t?`
|
|
423
|
+
await ensureAuth(env);`:"",s=t?"() => auth":"() => null",d=t?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",u=e.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
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}));`,h=e.hasFramework?"host?: FrameworkHostHandler":"",c=e.emailAgents??[],p=c.length>0?` composed.email = dispatchAgentEmail([
|
|
425
|
+
${c.map(i=>` { agent: lunoraAgentDefinitions.${i.exportName}, binding: ${JSON.stringify(i.bindingName)} },`).join(`
|
|
426
|
+
`)}
|
|
427
|
+
]);
|
|
428
|
+
|
|
429
|
+
`:"",b=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
430
|
+
public build(): ComposedApp {
|
|
431
|
+
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}${T(e).join(`
|
|
433
|
+
`)}
|
|
434
|
+
|
|
435
|
+
/** 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
|
+
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
437
|
+
${g(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":""}
|
|
438
|
+
${r.join(`
|
|
439
|
+
|
|
440
|
+
`)}${r.length>0?`
|
|
441
|
+
|
|
442
|
+
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
443
|
+
interface ComposedApp extends LunoraWorker {
|
|
444
|
+
/** Cloudflare Email Routing entry — present only when \`.onEmail(...)\` was configured. */
|
|
445
|
+
email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
446
|
+
/** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */
|
|
447
|
+
ShardDO: ReturnType<typeof createShardDO>;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Fluent worker-composition builder. Records each capability declaration, then
|
|
452
|
+
* \`.build()\` fans them into the DO-side \`createShardDO\` factory and the
|
|
453
|
+
* worker-side \`createWorker\` options — constructing the worker lazily on the
|
|
454
|
+
* first request so per-isolate singletons are built once.
|
|
455
|
+
*/
|
|
456
|
+
class AppBuilder<Env extends object> {
|
|
457
|
+
${j(e).join(`
|
|
458
|
+
`)}
|
|
459
|
+
|
|
460
|
+
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
461
|
+
|
|
462
|
+
${q(e).join(`
|
|
463
|
+
|
|
464
|
+
`)}
|
|
465
|
+
|
|
466
|
+
${b}
|
|
467
|
+
|
|
468
|
+
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
469
|
+
private assemble(${h}): ComposedApp {
|
|
470
|
+
const ShardDO = createShardDO({${B(e)}});
|
|
471
|
+
|
|
472
|
+
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
473
|
+
// build, so the first request constructs them and every later request on
|
|
474
|
+
// the same isolate reuses them.
|
|
475
|
+
let worker: LunoraWorker | null = null;
|
|
476
|
+
${n}${o}
|
|
477
|
+
${u}
|
|
478
|
+
|
|
479
|
+
const composed: ComposedApp = {
|
|
480
|
+
ShardDO,
|
|
481
|
+
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
482
|
+
const env = rawEnv as Env;${l}
|
|
483
|
+
worker ??= buildWorker(env);
|
|
484
|
+
|
|
485
|
+
return worker.fetch(request, rawEnv, context);
|
|
486
|
+
},
|
|
487
|
+
scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
488
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
489
|
+
|
|
490
|
+
return worker.scheduled(controller, rawEnv, context);
|
|
491
|
+
},
|
|
492
|
+
serverQuery: (request, rawEnv, reference, args, options) => {
|
|
493
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
494
|
+
|
|
495
|
+
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
496
|
+
},${e.hasQueue?`
|
|
497
|
+
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
498
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
499
|
+
|
|
500
|
+
return worker.queue?.(batch, rawEnv, context);
|
|
501
|
+
},`:""}
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
${p} if (this.emailHandler) {
|
|
505
|
+
const handler = this.emailHandler;
|
|
506
|
+
|
|
507
|
+
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
return composed;
|
|
511
|
+
}
|
|
512
|
+
${$(e.hasStorage)}
|
|
513
|
+
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
514
|
+
private buildWorkerOptions(env: Env, ${d}): WorkerOptions {
|
|
515
|
+
const options: WorkerOptions = {
|
|
516
|
+
${G(e).join(`
|
|
517
|
+
`)}
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
if (this.adminToken) {
|
|
521
|
+
options.adminToken = this.adminToken(env);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
${a.join(`
|
|
525
|
+
|
|
526
|
+
`)}${a.length>0?`
|
|
527
|
+
|
|
528
|
+
`:""} for (const fn of this.extendFns) {
|
|
529
|
+
Object.assign(options, fn(env, { ...options }));
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
return options;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
${H(e.hasGlobal)}
|
|
536
|
+
/**
|
|
537
|
+
* Start composing the app. Chain the capability methods, then \`.build()\`.
|
|
538
|
+
*
|
|
539
|
+
* \`Env\` is constrained to \`object\`, not \`Record<string, unknown>\`: an \`interface Env\`
|
|
540
|
+
* — which is what wrangler's generated \`worker-configuration.d.ts\` gives you, and
|
|
541
|
+
* what any app with its own bindings declares — is NOT assignable to an index
|
|
542
|
+
* signature, so the stricter bound forced every real app to write
|
|
543
|
+
* \`type AppEnv = Env & Record<string, unknown>\`. The builder only ever reads \`env\`
|
|
544
|
+
* through the selectors you pass it, so the looser bound costs nothing.
|
|
545
|
+
*/
|
|
546
|
+
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
547
|
+
|
|
548
|
+
export { AppBuilder, defineApp };
|
|
549
|
+
export type { ${P(e)} };
|
|
550
|
+
`};export{F as emitApp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as t}from"@lunora/advisor";const i=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],d=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},l=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:d(e),fields:Object.keys(e.shape),indexes:i(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),m=n=>{const{argumentValidators:e,queries:r,schema:s,shapes:a,...o}=n;return{...o,argValidators:e,queries:r??[],schema:l(s),shapes:a===void 0?void 0:c(a)}},f=n=>t(m(n),{source:"static"}),h=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
|
|
2
|
+
`)};export{h as formatAdvisories,f as lintSchema,m as toAdvisorContext};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const b=/[^a-zA-Z0-9]+/gu,M=/([a-z0-9])([A-Z])/gu,p=t=>t.split(b).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),L=t=>t.replaceAll(M,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),O=t=>t==="query"?"query":t==="action"?"action":"mutation",i=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>i(o,e+1));const r=t;if(r.type==="integer"&&r.format==="int64"||r.type==="string"&&r.contentEncoding==="base64")return!0;const{properties:n}=r;return n!==null&&typeof n=="object"&&Object.values(n).some(o=>i(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>i(r[o],e+1))},R=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),T=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),j=["$","{","'","$","'","}"].join(""),D=t=>T(t).split("$").join(j),_=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,h=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const r=t;return r.type==="null"||Array.isArray(r.type)&&r.type.includes("null")?!0:["anyOf","oneOf"].some(n=>{const o=r[n];return Array.isArray(o)&&o.some(s=>h(s,e+1))})},E=(t,e,r)=>e.length===0?r===0?[]:[t]:e.map(n=>({properties:{...t.properties,...n.properties},required:new Set([...t.required,...n.required])})),C=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const r=t.required;return[{properties:e,required:new Set(Array.isArray(r)?r.filter(n=>typeof n=="string"):[])}]},m=(t,e,r)=>{const n=t[e];return Array.isArray(n)?n.flatMap(o=>A(o,r+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[...C(r),...m(r,"allOf",e)],o={properties:Object.assign({},...n.map(a=>a.properties)),required:new Set(n.flatMap(a=>[...a.required]))},s=[...m(r,"anyOf",e),...m(r,"oneOf",e)];return E(o,s,n.length)},S=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[r];for(const o of["anyOf","oneOf","allOf"]){const s=r[o];if(Array.isArray(s))for(const a of s)n.push(...S(a,e+1))}return n},y=(t,e,r,n=0)=>{if(n>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,l)=>a.localeCompare(l));for(const a of s){const l=[...e,a],u=o.every(c=>c.required.has(a)),g=o.map(c=>c.properties[a]).filter(c=>c!==void 0);u?g.some(c=>h(c))&&r.nullable.push(l):r.optional.push(l);for(const c of g)y(c,l,r,n+1)}for(const a of S(t))for(const l of["additionalProperties","items"]){const u=a[l];u!==null&&typeof u=="object"&&y(u,[...e,"*"],r,n+1)}},N=(t,e)=>t.join("\0").localeCompare(e.join("\0")),k=t=>{const e={nullable:[],optional:[]};y(t,[],e);const r=n=>[...new Map(n.map(o=>[o.join("\0"),o])).values()].toSorted(N);return{nullable:r(e.nullable),optional:r(e.optional)}},w=t=>{const[e="",r=""]=t.name.split(":"),n=`${p(e)}${p(r)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:k(o),argsType:d(o)&&!i(o)?`${n}Args`:void 0,takesArgs:d(o),functionName:r,functionPath:t.name,namespace:e,resultType:d(s)&&!i(s)?`${n}Result`:void 0,summary:t.summary??t.name,verb:O(t["x-lunora-function-kind"])}},x=t=>{const e=new Map;for(const r of t.methods){const n=w(r),o=e.get(n.namespace);o===void 0?e.set(n.namespace,[n]):o.push(n)}return[...e.entries()].toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({methods:n.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:r}))},I=t=>t.methods.flatMap(e=>{const r=w(e);return[{name:r.argsType,schema:e.params?.[0]?.schema},{name:r.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,r)=>e.name.localeCompare(r.name)),P=/^[A-Za-z][A-Za-z0-9]*$/u,$=t=>P.test(t),q=t=>{const e=new Map;for(const r of t.methods){const n=p(r.functionName);if(!$(n))throw new Error(`sdk: function "${r.functionPath}" produces the invalid identifier "${n}" — rename the export so it starts with a letter.`);const o=r.verb==="query"?[n,`Subscribe${n}`,`Watch${n}`]:[n];for(const s of o){const a=e.get(s);if(a!==void 0){const l=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${r.functionPath}" both generate "${s}"${l} — rename one so the generated methods stay distinct.`)}e.set(s,r.functionPath)}}},z=t=>{const e=new Map;for(const r of t){const n=p(r.name);if(!$(n))throw new Error(`sdk: namespace "${r.name}" produces the invalid identifier "${n}" — rename the file so it starts with a letter.`);const o=e.get(n);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${r.name}" both generate "${n}" — rename one so the generated types stay distinct.`);e.set(n,r.name),q(r)}},v=t=>t.flatMap(e=>e.methods),H=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],U=(t,e)=>{const r=n=>n!==void 0&&new RegExp(String.raw`\b${n}\b`,"u").test(e)?n:void 0;return t.map(n=>({methods:n.methods.map(o=>({...o,argsType:r(o.argsType),resultType:r(o.resultType)})),name:n.name}))},W=t=>t.methods.filter(e=>i(e.params?.[0]?.schema)||i(e.result?.schema)).map(e=>e.name).toSorted((e,r)=>e.localeCompare(r)),Z=(t,e)=>[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!new RegExp(String.raw`\b${r}\b`,"u").test(e)))].toSorted((r,n)=>r.localeCompare(n)),F=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,r)=>e.localeCompare(r));export{v as allMethods,_ as argsChoice,z as assertGeneratable,R as commentText,H as generatedHeaderLines,i as hasUnrepresentableWireType,d as isTypedSchema,D as kotlinLiteral,I as modelSources,k as nullPathsOf,w as parseMethod,x as parseSpec,F as referencedModels,T as stringLiteral,p as toPascalCase,L as toSnakeCase,Z as undeclaredModels,W as unrepresentableFunctions,O as verbForKind,U as withDeclaredModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{t as a,o as b,E as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{Node as i}from"ts-morph";import{diagnosticAt as p}from"./CodegenDiagnosticError-BUXlG3P-.mjs";let d;const R=e=>{d=e},y=/^[A-Za-z_$][\w$]*$/u,f=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","unique"]),m=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},k=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),N=new Set(["check","meta"]),u=new Set,b=e=>{const t=e.getSymbol(),r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(!(r===void 0||!i.isVariableDeclaration(r)))return r.getInitializer()},E="v",S=e=>{if(i.isIdentifier(e))return!0;let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return i.isIdentifier(t)&&t.getText()===E},o=e=>{if(i.isIdentifier(e)&&!u.has(e)){const t=b(e);if(t!==void 0&&S(t)){u.add(e);try{return o(t)}finally{u.delete(e)}}}return i.isCallExpression(e)?L(e):{kind:"any",sourceText:e.getText()}},h=e=>{const t={};for(const r of e.getProperties()){const n=i.isShorthandPropertyAssignment(r);if(!n&&!i.isPropertyAssignment(r))continue;const s=r.getNameNode();if(i.isComputedPropertyName(s))continue;const a=n?r.getNameNode():r.getInitializer();if(!a)continue;const c=r.getName();if(!y.test(c))throw new g("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(c)}`);t[c]=o(a)}return t},l=(e,t)=>e&&i.isExpression(e)?o(e):t,A=e=>e===void 0?"undefined":i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),T=e=>{const t=e&&d?d(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},v=(e,t,r)=>{if(k.has(e))return{kind:e};const[n,s]=t;switch(e){case"array":return{inner:l(n,{kind:"any"}),kind:"array"};case"from":return T(n);case"id":{if(!n||!i.isStringLiteral(n))throw p(n??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${n?n.getText():"no argument"}.`);return{kind:"id",tableName:n.getLiteralText()}}case"literal":return{kind:"literal",literalValue:A(n)};case"object":return n&&i.isObjectLiteralExpression(n)?{kind:"object",shape:h(n)}:{kind:"object",shape:{}};case"optional":return{inner:l(n,{kind:"any"}),kind:"optional"};case"record":return{keyType:l(n,{kind:"string"}),kind:"record",valueType:l(s,{kind:"any"})};case"storage":return n&&i.isStringLiteral(n)?{bucket:n.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>i.isExpression(a)).map(a=>o(a))};default:throw new g("INTERNAL",`Unsupported validator kind: ${e}`)}},L=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),n=e.getArguments();if(f.has(r)||N.has(r)){const s=t.getExpression(),a=i.isExpression(s)?o(s):{kind:"any"};return f.has(r)?m(a,r):r==="check"?{...a,hasRefinement:!0}:a}return v(r,n,e)};export{h as a,o as p,R as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/\/index$/u,s=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(s,"_");export{c as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as r,readFileSync as a}from"node:fs";import{join as d}from"node:path";const m=o=>{const n=d(o,"package.json");if(r(n))try{const s=JSON.parse(a(n,"utf8")),t=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=s[c];if(e!==null&&typeof e=="object")for(const i of Object.keys(e))t.add(i)}return t}catch{return}};export{m as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=s(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{shape:Object.fromEntries(Object.entries(a.shape).map(([l,o])=>[l,n(o)]))}]))});export{m as schemaFromIr};
|