@lunora/codegen 1.0.0-alpha.401 → 1.0.0-alpha.403
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +87 -2
- package/dist/index.d.ts +87 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-Cli3X44r.mjs → AGENTS_FILENAME-D0Y0_UgB.mjs} +1 -1
- package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-D1SaOfnm.mjs → ALL_NOTIFY_CHANNELS-CtrsBtZX.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-BX1_ALLp.mjs → CONTAINERS_FILENAME-J-e3Vanb.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-CVYzxQ0y.mjs +1 -0
- package/dist/packem_shared/{FLAGS_FILENAME-DY3yo1u_.mjs → FLAGS_FILENAME-6RzszxVW.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Ck_l1lz7.mjs → MUTATORS_FILENAME-C3OImAxC.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-CCp_wKFT.mjs → OPENRPC_VERSION-UNYmA7Ty.mjs} +1 -1
- package/dist/packem_shared/{QUEUES_FILENAME-C5xotY-M.mjs → QUEUES_FILENAME-Ba-sK5Ek.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BIELlQsc.mjs → SCHEMA_SNAPSHOT_FILENAME-Cuhl5Xbr.mjs} +15 -13
- package/dist/packem_shared/{SHAPES_FILENAME-DCtGHMEm.mjs → SHAPES_FILENAME-CH0KrAdb.mjs} +1 -1
- package/dist/packem_shared/{WORKFLOWS_FILENAME-CyV1HQaP.mjs → WORKFLOWS_FILENAME-DfVfBum_.mjs} +1 -1
- package/dist/packem_shared/{attribution-DjweYNgJ.mjs → attribution-BhGR_h0Z.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-B1PEHSSc.mjs → buildOpenApiDocument-B8KEeeRr.mjs} +1 -1
- package/dist/packem_shared/{capabilitiesUsedBy-SSrieNZ1.mjs → capabilitiesUsedBy-BwhaHK08.mjs} +1 -1
- package/dist/packem_shared/chain-CXiqZFUk.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-BuF5PNwV.mjs → classify-procedure-call-BZ164dkJ.mjs} +1 -1
- package/dist/packem_shared/companionServiceBinding-BZjm486n.mjs +1 -0
- package/dist/packem_shared/{context-property-calls-BcUYQ6ph.mjs → context-property-calls-Ggrmu3UL.mjs} +1 -1
- package/dist/packem_shared/{context-root-2wag3akK.mjs → context-root-DnvrQxae.mjs} +1 -1
- package/dist/packem_shared/{createCodegenProject-C8N4Zm8h.mjs → createCodegenProject-Cfr1xHPC.mjs} +1 -1
- package/dist/packem_shared/{database-calls-B_85LJIk.mjs → database-calls-BRI5W-Mp.mjs} +1 -1
- package/dist/packem_shared/{discoverAuthApiCalls-f8_WRQEA.mjs → discoverAuthApiCalls-ENLGem4M.mjs} +1 -1
- package/dist/packem_shared/{discoverCrons-DTqSuSDh.mjs → discoverCrons-DWVXmktw.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-2gxHuLgt.mjs → discoverHttpRoutes-CAoEemno.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-CLh70kVu.mjs → discoverInserts-DmSa4WKU.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-e5_NQdf-.mjs → discoverMigrations-Duh6HVG3.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CrXAegUc.mjs → discoverNondeterministicCalls-BoF6ob-B.mjs} +1 -1
- package/dist/packem_shared/{discoverQueries-T8b_7ZZ-.mjs → discoverQueries-spxu-wHR.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-CnVvP2Ps.mjs → discoverRlsMetadata-Cc0zA-gZ.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-DttY0Jld.mjs → discoverRlsProcedures-mjiA0I4S.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-X0SECo-x.mjs → discoverSandboxUsage-Ccy9n7G1.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-ynieYB0n.mjs +1 -0
- package/dist/packem_shared/{discoverStorageRulesMetadata-t_oMSn0L.mjs → discoverStorageRulesMetadata-CtE5trUR.mjs} +1 -1
- package/dist/packem_shared/{emitApp-BrOgH7YU.mjs → emitApp-C3IUdkkt.mjs} +37 -28
- package/dist/packem_shared/{exported-procedure-chains-BaxQ8C-S.mjs → exported-procedure-chains-h8Y7xDjq.mjs} +1 -1
- package/dist/packem_shared/{fingerprintSchemaSources-PmhepCVj.mjs → fingerprintSchemaSources-C8H1wOcH.mjs} +1 -1
- package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-DpIVI5BM.mjs} +1 -1
- package/dist/packem_shared/index-jtzAVdUp.mjs +1 -0
- package/dist/packem_shared/{index-Dd6T5nSP.mjs → index-mFEIaT45.mjs} +1 -1
- package/dist/packem_shared/{ip-reads-WFubgB1G.mjs → ip-reads-BPDWkzEu.mjs} +1 -1
- package/dist/packem_shared/isTestPath-DRIdZaij.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-BXwH3_gn.mjs +1 -0
- package/dist/packem_shared/{modules-DE0ksIeR.mjs → modules-Qpm_zqz4.mjs} +1 -1
- package/dist/packem_shared/project-config-file-DR7xrrNB.mjs +1 -0
- package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-DUzluwPj.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/DEFAULT_TARGET-C-gcdslJ.mjs +0 -1
- package/dist/packem_shared/chain-DWwd9wXd.mjs +0 -1
- package/dist/packem_shared/companionServiceBinding-ChINWo8k.mjs +0 -1
- package/dist/packem_shared/discoverFunctions-D4GIaVIP.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-DaJLewG0.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-C0VcUGpb.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-CY0xmIWX.mjs +0 -1
- package/dist/packem_shared/discoverSchema-DDvMQheA.mjs +0 -1
- package/dist/packem_shared/index-fVYBrxkP.mjs +0 -1
- package/dist/packem_shared/isTestPath-ClgKgMYM.mjs +0 -1
- package/dist/packem_shared/loadProjectConfig-CtcJHHKS.mjs +0 -1
- package/dist/packem_shared/static-literal-BwDHHjEJ.mjs +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{APP_METHOD_CAPABILITIES as
|
|
1
|
+
import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as q}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-Cn7dMQ_u.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>q(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
|
|
2
2
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
|
|
3
3
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
4
4
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
5
5
|
|
|
6
6
|
return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
|
|
7
7
|
}
|
|
8
|
-
`:"",
|
|
8
|
+
`:"",P=e=>e?`
|
|
9
9
|
/**
|
|
10
10
|
* One bucket's \`Storage\`, signing under the name it is registered as.
|
|
11
11
|
*
|
|
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";impor
|
|
|
114
114
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
|
-
`:"",
|
|
117
|
+
`:"",G=e=>e?`
|
|
118
118
|
/**
|
|
119
119
|
* 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\`).
|
|
120
120
|
*
|
|
@@ -382,7 +382,7 @@ const buildGlobalCdcApplier =
|
|
|
382
382
|
|
|
383
383
|
return request.changes.length;
|
|
384
384
|
};
|
|
385
|
-
`:"",
|
|
385
|
+
`:"",_=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. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\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(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\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}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," 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>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],W=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
|
|
386
386
|
public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
|
|
387
387
|
this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
|
|
388
388
|
|
|
@@ -567,7 +567,7 @@ const buildGlobalCdcApplier =
|
|
|
567
567
|
: {}),`]:[],...l(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
|
|
568
568
|
${t.join(`
|
|
569
569
|
`)}
|
|
570
|
-
`:""},
|
|
570
|
+
`:""},U=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],F=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],z=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...F(r,t),...J(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...z(n),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...U(e.identity),...Y(e),...a||s?['import schema from "../schema.js";']:[],...K(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
|
|
571
571
|
// The schema's jurisdiction pins the auth object like every other DO.
|
|
572
572
|
jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",te=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,re=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
|
|
573
573
|
${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
|
|
@@ -583,7 +583,7 @@ ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`
|
|
|
583
583
|
|
|
584
584
|
if (adminRevocations) {
|
|
585
585
|
options.adminRevocations = adminRevocations;
|
|
586
|
-
}`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),
|
|
586
|
+
}`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ne=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
|
|
587
587
|
${S(e).join(`
|
|
588
588
|
`)}
|
|
589
589
|
], host)`:"host",ie=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],ce=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
@@ -855,13 +855,13 @@ ${S(e).join(`
|
|
|
855
855
|
}`]:[],...ie(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
856
856
|
${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
857
857
|
`)}
|
|
858
|
-
};`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"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>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...le(e),...
|
|
858
|
+
};`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"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>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...le(e),...se(e),...ne(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(r=>`(env as Record<string, unknown>)[${JSON.stringify(r)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],he=e=>e?`
|
|
859
859
|
/** The identity memo per \`env\` object, owned by one assembled worker. */
|
|
860
860
|
type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
|
|
861
|
-
`:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,n
|
|
861
|
+
`:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,n])=>[a,s,n]);return`
|
|
862
862
|
/** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
|
|
863
863
|
interface DeferredModules {
|
|
864
|
-
${t.map(([a,
|
|
864
|
+
${t.map(([a,s])=>` ${a}: ${s};`).join(`
|
|
865
865
|
`)}
|
|
866
866
|
}
|
|
867
867
|
|
|
@@ -871,17 +871,17 @@ let deferredModules: Promise<DeferredModules> | undefined;
|
|
|
871
871
|
const loadDeferredModules = (): Promise<DeferredModules> =>
|
|
872
872
|
(deferredModules ??= (async (): Promise<DeferredModules> => {
|
|
873
873
|
return {
|
|
874
|
-
${t.map(([a,,
|
|
874
|
+
${t.map(([a,,s])=>` ${a}: ${s},`).join(`
|
|
875
875
|
`)}
|
|
876
876
|
};
|
|
877
877
|
})());
|
|
878
878
|
`},pe=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
|
|
879
|
-
await ensureAuth(env);`:"",
|
|
880
|
-
await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:
|
|
881
|
-
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:
|
|
879
|
+
await ensureAuth(env);`:"",s=e?`
|
|
880
|
+
await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
|
|
881
|
+
const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
|
|
882
882
|
worker ??= ${t};`}},me=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
|
|
883
|
-
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},
|
|
884
|
-
`:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(
|
|
883
|
+
const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ke=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
|
|
884
|
+
`:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
|
|
885
885
|
`);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
|
|
886
886
|
${t(" ")}
|
|
887
887
|
]);
|
|
@@ -900,7 +900,14 @@ ${t(" ")}
|
|
|
900
900
|
return agentEmail(message, rawEnv, context);
|
|
901
901
|
};
|
|
902
902
|
|
|
903
|
-
`},ge=e=>
|
|
903
|
+
`},ge=e=>e.securityHeaders===void 0?"":`
|
|
904
|
+
/**
|
|
905
|
+
* \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
|
|
906
|
+
* the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
|
|
907
|
+
* \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
|
|
908
|
+
*/
|
|
909
|
+
const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
|
|
910
|
+
`,ve=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Se=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,s=_(t),n=ce(t),i=a?` let auth: LunoraAuth | null = null;
|
|
904
911
|
let authInit: Promise<void> | null = null;
|
|
905
912
|
// One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
|
|
906
913
|
// \`assemble()\` has its own auth closure and must not share.
|
|
@@ -983,15 +990,15 @@ type Selector<Env, T> = (env: Env) => T | undefined;
|
|
|
983
990
|
|
|
984
991
|
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
985
992
|
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
986
|
-
${he(a)}${ue(t)}${t.jurisdiction?`
|
|
993
|
+
${ge(t)}${he(a)}${ue(t)}${t.jurisdiction?`
|
|
987
994
|
// Module scope, so every isolate loading this script (the worker and each Durable
|
|
988
995
|
// Object class it exports) knows the schema's jurisdiction before a request runs.
|
|
989
996
|
// \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
|
|
990
997
|
declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
|
|
991
998
|
`:""}
|
|
992
|
-
${
|
|
999
|
+
${s.join(`
|
|
993
1000
|
|
|
994
|
-
`)}${
|
|
1001
|
+
`)}${s.length>0?`
|
|
995
1002
|
|
|
996
1003
|
`:""}/** The composed app: a Cloudflare module worker (\`fetch\` / \`scheduled\` / optional \`email\`) plus the \`ShardDO\` class binding. */
|
|
997
1004
|
interface ComposedApp extends LunoraWorker {
|
|
@@ -1008,7 +1015,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
1008
1015
|
* first request so per-isolate singletons are built once.
|
|
1009
1016
|
*/
|
|
1010
1017
|
class AppBuilder<Env extends object> {
|
|
1011
|
-
${
|
|
1018
|
+
${M(t).join(`
|
|
1012
1019
|
`)}
|
|
1013
1020
|
|
|
1014
1021
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -1072,7 +1079,7 @@ ${t.hasFramework?`
|
|
|
1072
1079
|
`:""}
|
|
1073
1080
|
return composed;
|
|
1074
1081
|
}
|
|
1075
|
-
${$(t)}${
|
|
1082
|
+
${$(t)}${P(t.hasStorage)}
|
|
1076
1083
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
1077
1084
|
private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
|
|
1078
1085
|
const options: WorkerOptions = {
|
|
@@ -1086,18 +1093,18 @@ ${de(t).join(`
|
|
|
1086
1093
|
options.adminToken = adminToken;
|
|
1087
1094
|
}
|
|
1088
1095
|
|
|
1089
|
-
${
|
|
1096
|
+
${n.join(`
|
|
1090
1097
|
|
|
1091
|
-
`)}${
|
|
1098
|
+
`)}${n.length>0?`
|
|
1092
1099
|
|
|
1093
1100
|
`:""} for (const fn of this.extendFns) {
|
|
1094
1101
|
Object.assign(options, fn(env, { ...options }));
|
|
1095
1102
|
}
|
|
1096
|
-
|
|
1103
|
+
${t.securityHeaders===void 0?"":"\n // `security.headers` from lunora.config, unless code set its own. After `.extend()`, whose shallow\n // assign would otherwise drop it when an extension sets only `security.cors`.\n if (options.security?.headers === undefined) {\n options.security = { ...options.security, headers: LUNORA_SECURITY_HEADERS };\n }\n"}
|
|
1097
1104
|
return options;
|
|
1098
1105
|
}
|
|
1099
1106
|
}
|
|
1100
|
-
${
|
|
1107
|
+
${G(t.hasGlobal)}
|
|
1101
1108
|
/**
|
|
1102
1109
|
* Shape of the project's root \`lunora.config.*\`.
|
|
1103
1110
|
*
|
|
@@ -1119,6 +1126,8 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
1119
1126
|
remote?: boolean;
|
|
1120
1127
|
/** Sibling Workers the app calls through service bindings — key → its folder and, for RPC, the exported \`WorkerEntrypoint\` class (\`rpc: false\` binds that class but calls it with plain \`fetch\`, without importing the service's sources). Becomes \`ctx.services.<key>\` in actions, a wrangler \`services[]\` entry, one \`lunora dev\` session and a services-first \`lunora deploy\`. Literals, for the same reason as \`target\`. */
|
|
1121
1128
|
services?: Record<string, { dir: string; entrypoint?: string; rpc?: false }>;
|
|
1129
|
+
/** Baseline security headers for the Worker AND the static assets' generated \`_headers\` (\`crossOriginOpenerPolicy\`, \`frameAncestors\`, \`csp\`, …; \`false\` omits a header, \`headers: false\` all of them). A \`security.headers\` set in code wins. Literals, for the same reason as \`target\`. */
|
|
1130
|
+
security?: { headers?: SecurityOptions["headers"] };
|
|
1122
1131
|
/** Studio settings. \`companion: true\` emits the companion Worker that serves the advisor procedure list to a hosted Studio, bound to the app as \`ADVISOR_COMPANION\`. A literal, for the same reason as \`target\`. */
|
|
1123
1132
|
studio?: { companion?: boolean };
|
|
1124
1133
|
/** Deploy target id — \`lunora deploy\`/\`verify\` read it when no \`--target\` is passed. Must be a literal: \`runCodegen\` resolves it synchronously by PARSING this file, so a computed value is not seen — \`lunora verify\` reports \`platform_unreadable_target\` rather than defaulting in silence. */
|
|
@@ -1137,6 +1146,6 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
1137
1146
|
*/
|
|
1138
1147
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
1139
1148
|
|
|
1140
|
-
export { AppBuilder, defineApp };
|
|
1141
|
-
export type { ${
|
|
1142
|
-
`};export{
|
|
1149
|
+
export { AppBuilder, defineApp${t.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
|
|
1150
|
+
export type { ${ve(t)} };
|
|
1151
|
+
`};export{Se as emitApp,ke as emitAuthModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-
|
|
1
|
+
import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-BZ164dkJ.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-
|
|
1
|
+
import{createHash as i}from"node:crypto";import{existsSync as s,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{listLunoraSourceFiles as h}from"./isTestPath-DRIdZaij.mjs";const S=t=>{if(!s(t))return"unreadable";const e=h(t,{includeSkipped:!0}),o=u(t,"schema.ts");s(o)&&e.push(o);const r=i("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(c(a))}catch{}return r.digest("hex")};export{S as default};
|
package/dist/packem_shared/{handler-reference-D2EE2q-4.mjs → handler-reference-DpIVI5BM.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-
|
|
1
|
+
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./isTestPath-DRIdZaij.mjs";import{r as v,h}from"./attribution-BhGR_h0Z.mjs";const b=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:b(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=h(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{Node as s,SyntaxKind as B}from"ts-morph";import{d as z}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as h,bindingKeyName as H,listLunoraSourceFiles as M,lunoraRelativePath as W}from"./isTestPath-DRIdZaij.mjs";import{e as K,i as O}from"./attribution-BhGR_h0Z.mjs";import{u as R,p as q,r as Y,c as w,a as G}from"./unwrap-handler-return-DUzluwPj.mjs";import{m as J}from"./ip-reads-BPDWkzEu.mjs";import{b as L,s as X,c as Q}from"./classify-procedure-call-BZ164dkJ.mjs";import{r as D,p as C,a as Z}from"./parse-validator-BisfC8bR.mjs";import{N as ee,l as te}from"./project-config-file-DR7xrrNB.mjs";import{s as ie}from"./dispatch-namespace-DwTjD7BU.mjs";const I=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,ne=e=>{const i=e.getArguments()[0],t=I(i);if(t!==void 0)return t;if(i===void 0||!s.isObjectLiteralExpression(i))return;const n=h(i,"handler");return n!==void 0&&s.isPropertyAssignment(n)?I(n.getInitializer()):void 0},re=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const t=h(i,"handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const n=t.getInitializer();return!n||!(s.isArrowFunction(n)||s.isFunctionExpression(n))?"unknown":R(n)},oe=e=>{const i=e.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":R(i)},se=e=>{let i={};for(const t of L(e)){if(t.name!=="input")continue;const n=t.call.getArguments()[0],o=n!==void 0&&s.isExpression(n)?D(n):void 0;o!==void 0&&(i={...C(o),...i})}return i},ae=e=>{const i=L(e).find(n=>n.name==="output");if(!i)return;const t=i.call.getArguments()[0];return t&&s.isExpression(t)?q(i.call,()=>Z(t)):void 0},E=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isStringLiteral(n)?n.getLiteralValue():void 0},k=(e,i)=>{const t=h(e,i);if(t===void 0||!s.isPropertyAssignment(t))return;const n=t.getInitializer();return n!==void 0&&s.isNumericLiteral(n)?n.getLiteralValue():void 0},ce=e=>{const i=h(e,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const t=i.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const n=E(t,"scope"),o=k(t,"maxAge"),r=k(t,"staleWhileRevalidate"),a=E(t,"tag"),c=E(t,"vary"),l={...o===void 0?{}:{maxAge:o},...n==="private"||n==="public"?{scope:n}:{},...r===void 0?{}:{staleWhileRevalidate:r},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},le=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const i=ce(e),t=h(e,"rest");return t!==void 0&&s.isPropertyAssignment(t)?{...i===void 0?{}:{cache:i},rest:t.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},ue=e=>{const i=L(e).find(t=>t.name==="expose");return i?le(i.call.getArguments()[0]):void 0},de=e=>{const i=L(e).find(r=>r.name==="x402");if(!i)return;const t=i.call.getArguments()[0];if(t===void 0||!s.isObjectLiteralExpression(t))return{};const n=h(t,"price");if(n===void 0||!s.isPropertyAssignment(n))return{};const o=n.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},ge=e=>{const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const t=h(i,"args");if(!t||!s.isPropertyAssignment(t))return{};const n=t.getInitializer(),o=n===void 0?void 0:D(n);return o===void 0?{}:C(o)},f=(e,i)=>{throw new g("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${e.getSourceFile().getFilePath()}:${String(e.getStartLineNumber())}`)},S=(e,i,t)=>{if(!e||!s.isObjectLiteralExpression(e))return f(i,"metadata objects");const n=new Set;for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))return f(o,"metadata fields without spreads, getters, or shorthand");const r=o.getNameNode(),a=s.isStringLiteral(r)?r.getLiteralValue():r.getText();if(!s.isIdentifier(r)&&!s.isStringLiteral(r)||!t.includes(a)||n.has(a))return f(o,"supported, unique metadata fields");n.add(a)}return e},y=(e,i)=>{const t=e.getProperty(i);return t&&s.isPropertyAssignment(t)?t.getInitializer():void 0},pe=e=>{const i=S(e,e,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),t={};for(const r of["maxAge","staleWhileRevalidate"]){const a=y(i,r);if(!(a===void 0&&r!=="maxAge")){if(!a||!s.isNumericLiteral(a))return f(e,`cache.${r}`);t[r]=a.getLiteralValue()}}const n=y(i,"scope");if(!n||!s.isStringLiteral(n)||!["private","public"].includes(n.getLiteralValue()))return f(e,"cache.scope");t.scope=n.getLiteralValue();for(const r of["tag","vary"]){const a=y(i,r);if(a!==void 0){if(!s.isStringLiteral(a))return f(a,`cache.${r}`);t[r]=a.getLiteralValue()}}const o=y(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return f(o,"cache.credentialHeaders");t.credentialHeaders=o.getElements().map(r=>s.isStringLiteral(r)?r.getLiteralValue():f(r,"cache.credentialHeaders string entries"))}return t},fe=e=>{const i=S(e.getArguments()[0],e,["rest","cache"]),t=y(i,"rest"),n=y(i,"cache");return t!==void 0&&!s.isTrueLiteral(t)&&!s.isFalseLiteral(t)?f(t,".expose({ rest })"):{...t?{rest:s.isTrueLiteral(t)}:{},...n?{cache:pe(n)}:{}}},me=e=>{const i=S(e.getArguments()[0],e,["price"]),t=y(i,"price");return!t||!s.isStringLiteral(t)&&!s.isNumericLiteral(t)?f(e,"`.x402({ price })` value"):{price:t.getLiteralValue()}},he=e=>{const i=e.map(o=>{const r=o.getArguments()[0];return r===void 0?ee:te(r)}),t=i.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)),n=i.reduce((o,r)=>({...r,...o}),{});return t?n:"unloaded"},ye=e=>{const{factory:i,steps:t}=X(e);if(!i)return f(e,"metadata from a resolvable Lunora factory root");const n={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:r,name:a}of t){if(!["expose","input","meta","output","use","x402"].includes(a))return f(r,`known builder modifiers, got .${a}()`);a==="expose"&&n.expose===void 0&&(n.expose=fe(r)),a==="x402"&&n.x402===void 0&&(n.x402=me(r))}const o=t.filter(r=>r.name==="meta").map(r=>r.call);return o.length===0?n:{...n,meta:he(o)}},ve=new Set(["action","mutation","query","stream"]),N=(e,i,t)=>{const n=e.getProperty(i)?.getTypeAtLocation(t);if(n===void 0)return;const o=n.isUnion()?n.getUnionTypes().filter(a=>!a.isUndefined()):[n],r=o.length===1?o[0]?.getLiteralValue():void 0;return typeof r=="string"?r:void 0},U=(e,i)=>{const t=N(e,"kind",i);return t!==void 0&&ve.has(t)&&e.getProperty("handler")!==void 0?t:void 0},be=e=>{const i=e.getParent();if(s.isPropertyAccessExpression(i)&&i.getExpression()===e)return i.getName()==="functions";if(s.isElementAccessExpression(i)&&i.getExpression()===e){const n=i.getArgumentExpression();return n!==void 0&&s.isStringLiteral(n)&&n.getLiteralValue()==="functions"}const t=s.isVariableDeclaration(i)&&i.getNameNode()!==e?i.getNameNode():void 0;return t!==void 0&&s.isObjectBindingPattern(t)&&t.getElements().some(n=>(n.getPropertyNameNode()?.getText()??n.getName())==="functions")},it=(e,i)=>{for(const t of e)for(const n of t.getVariableDeclarations()){const o=n.getNameNode();if(!n.isExported()||!s.isIdentifier(o))continue;const a=(n.getType().getProperty("functions")?.getTypeAtLocation(n)?.getProperties()??[]).filter(u=>U(u.getTypeAtLocation(n),n)!==void 0);if(a.length===0||o.findReferencesAsNodes().some(u=>be(u)))continue;const l=n.getName(),d=a.map(u=>u.getName()).join(", ");console.warn(`@lunora/codegen: ${i(t)}:${l} ships functions (${d}) that nothing re-exports, so none is in the generated api. Add \`export const { ${d} } = ${l}.functions;\` (or export your own wrappers of them).`)}},Ne=new Set(["connect","disconnect","init","reactor","whisper"]),Le={ArrayBuffer:"bytes",GeoPoint:"geoPoint"},Ae=8,P=(e,i)=>{const t=e.getText(i);return t===""?{kind:"from"}:{kind:"from",tsType:t}},Ee=new Set(["false","true"]),Pe=[[e=>e.isAny()||e.isUnknown(),"any"],[e=>e.isString(),"string"],[e=>e.isNumber(),"number"],[e=>e.isBoolean(),"boolean"],[e=>e.isNull(),"null"],[e=>e.isBigInt(),"bigint"]],Te=(e,i,t)=>{if(!e.isObject()||e.isIntersection()||e.getCallSignatures().length>0||e.isClass())return;const n=e.getProperties();if(n.some(r=>r.getTypeAtLocation(i).getCallSignatures().length>0))return;const o=e.getStringIndexType();if(o!==void 0&&n.length===0)return{keyType:{kind:"string"},kind:"record",valueType:b(o,i,t+1)};if(!(o!==void 0||n.length===0))return{kind:"object",shape:Object.fromEntries(n.map(r=>[r.getName(),$(r.getTypeAtLocation(i),r.isOptional(),i,t+1)]))}},b=(e,i,t)=>{if(t>Ae)return P(e,i);const n=Pe.find(([a])=>a(e));if(n!==void 0)return{kind:n[1]};const o=Le[(e.getSymbol()??e.getAliasSymbol())?.getName()??""];if(o!==void 0)return{kind:o};if(e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isBigIntLiteral())return{kind:"literal",literalValue:e.getText(i),sensitive:!0};const r=e.isIntersection()?N(e,"__table",i):void 0;if(r!==void 0)return{kind:"id",tableName:r};if(e.isUnion())return F(e.getUnionTypes(),i,t);if(e.isArray()){const a=e.getArrayElementType();return a===void 0?P(e,i):{inner:b(a,i,t+1),kind:"array"}}return Te(e,i,t)??P(e,i)},F=(e,i,t)=>{const o=new Set(e.filter(l=>l.isBooleanLiteral()).map(l=>l.getText(i))).size===Ee.size,r=e.filter(l=>!(o&&l.isBooleanLiteral())).map(l=>b(l,i,t+1)),a=o?[...r,{kind:"boolean"}]:r,[c]=a;return a.length===1&&c!==void 0?c:{kind:"union",members:a}},$=(e,i,t,n)=>{const o=e.isUnion()?e.getUnionTypes():[e],r=o.filter(l=>!l.isUndefined());if(!i&&r.length===o.length)return b(e,t,n);if(r.length===0)return{inner:{kind:"any"},kind:"optional"};const[a]=r;return{inner:r.length===1&&a!==void 0?b(a,t,n):F(r,t,n),kind:"optional"}},xe=(e,i)=>{const t=e.getProperty("__type")?.getTypeAtLocation(i);if(t===void 0)return{kind:"from"};const n=(e.getSymbol()??e.getAliasSymbol())?.getName();return n==="TimestampColumnValidator"?{kind:"timestamp"}:n==="ObjectColumnValidator"&&t.getProperties().length===0?{kind:"object",shape:{}}:$(t,!1,i,0)},Se=new Set(["AsyncGenerator","AsyncIterable","AsyncIterableIterator"]),Oe=(e,i)=>{const t=e.getProperty("handler")?.getTypeAtLocation(i).getCallSignatures()[0]?.getReturnType();if(t===void 0)return[];if(Se.has((t.getSymbol()??t.getAliasSymbol())?.getName()??"")){const[n]=t.getTypeArguments();return n===void 0?[]:[n]}return(t.isUnion()?t.getUnionTypes():[t]).map(n=>n.getSymbol()?.getName()==="Promise"?n.getTypeArguments()[0]??n:n)},we=(e,i)=>{const t=[...new Set(e.map(n=>Y(n,i)))];return t.length===0||t.includes("unknown")?"unknown":t.join(" | ")},Ie=(e,i,t,n)=>{const o=e.getType(),r=U(o,e);if(r===void 0)return;const a={...n?{description:n}:{},exportName:i,filePath:t,kind:r};if(o.getProperty("channel")?.isOptional()===!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a room from a published package; its name is not in the declared type, so codegen cannot route it. Declare the room with \`defineRoom\` in this file instead.`);const c=N(o,"lifecycle",e),l=o.getProperty("lifecycle");if(c===void 0&&l!==void 0&&!l.isOptional())throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a lifecycle hook from a published package whose type does not say which moment it runs at. Declare it with its moment, e.g. \`RegisteredLifecycleHook & { readonly lifecycle: "disconnect" }\` (what \`onDisconnect\` returns).`);if(c!==void 0){if(!Ne.has(c))throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a "${c}" lifecycle hook from a published package; only a locally declared hook can carry its route. Declare it in this file instead.`);return{...a,args:{},lifecycle:c,returnType:"void",visibility:"internal"}}const d=N(o,"visibility",e);if(d!=="internal"&&d!=="public")throw new g("PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",`${t}:${i} re-exports a function from a published package whose type does not say whether it is internal or public. Declare it in that package as \`RegisteredQuery\` / \`RegisteredMutation\` / \`RegisteredAction\` (public) or their \`RegisteredInternal*\` counterparts, not the bare \`RegisteredFunction\`, so codegen does not list an internal function in the client \`api\`.`);if(d==="internal"&&o.getProperty("visibility")?.isOptional()!==!1)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports an internal function from a published package whose type makes \`visibility\` optional, so the value may not carry it. Declare it with a \`RegisteredInternal*\` type, which requires \`visibility: "internal"\`.`);const u=o.getProperty("args")?.getTypeAtLocation(e);if(u===void 0||u.isAny()||u.isUnknown()||u.getStringIndexType()!==void 0||u.getNumberIndexType()!==void 0)throw new g("PUBLISHED_FUNCTION_UNSUPPORTED",`${t}:${i} re-exports a function from a published package whose type does not list its arguments. Declare its validator map with one key per argument (an empty \`{}\` for none) so codegen can type the client call.`);const m=Object.fromEntries(u.getProperties().map(p=>[p.getName(),xe(p.getTypeAtLocation(e),e)]));return{...a,args:m,...r==="query"?{readsIp:!0}:{},returnType:we(Oe(o,e),e),typeDerivedArgs:!0,visibility:d}},ke=8,A=(e,i=0)=>{if(i>ke)return;if(s.isCallExpression(e))return{call:e};if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return A(e.getExpression(),i+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const t=e.getSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0},T=(e,i)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const t=e.getInitializer();return t?A(t,i):{deadEnd:e}}if(s.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol()?.getValueDeclaration();return t?T(t,i+1):void 0}if(s.isBindingElement(e)){const t=H(e),r=e.getFirstAncestorByKind(B.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return r?T(r,i+1):void 0}return{deadEnd:e}},x=e=>{const i=A(e);return i!==void 0&&"call"in i?i.call:void 0},_=e=>{const i=A(e);return i!==void 0&&"deadEnd"in i&&i.deadEnd.getSourceFile().isDeclarationFile()},_e=(e,i=()=>!0)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const r=[];for(const a of t.getElements().filter(c=>i(c.getName()))){const c=x(a.getNameNode());c&&r.push([a.getName(),c])}return r}if(!i(e.getName()))return[];const n=e.getInitializer(),o=n&&(s.isCallExpression(n)?n:x(n));return o?[[e.getName(),o]]:[]},Re=(e,i)=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t))return t.getElements().filter(o=>i(o.getName())&&_(o.getNameNode())).map(o=>[o.getName(),o.getNameNode()]);const n=e.getInitializer();return i(e.getName())&&n!==void 0&&_(n)?[[e.getName(),t]]:[]},De=e=>{const i=e.getArguments()[0],t=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return n.getLiteralValue()},Ce=e=>e.startsWith("/")&&new URL(e,"https://lunora.invalid").pathname===e&&e!=="/_lunora"&&!e.startsWith("/_lunora/"),Ue=e=>{const i=e.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new g("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const t=i.getProperty("path"),n=s.isPropertyAssignment(t)?t.getInitializer():void 0;if(!n||!s.isStringLiteral(n))throw new g("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=n.getLiteralValue();if(!Ce(o))throw new g("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(l=>s.isSpreadAssignment(l)||s.isPropertyAssignment(l)&&s.isComputedPropertyName(l.getNameNode())))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const c=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(c===void 0||!(s.isTrueLiteral(c)||s.isFalseLiteral(c)))throw new g("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(c),path:o}},Fe=(e,i,t,n)=>{const o=n?ye(i):void 0,r=n?o?.expose:ue(i),a=n?o?.x402:de(i),c=w(()=>ae(i)),l=w(()=>oe(e)),d=z({kind:t.kind,output:c.value});return G(d?c.erased:l.erased),{args:se(i),...r?{expose:r}:{},...a?{x402:a}:{},...o?.meta===void 0?{}:{meta:o.meta},...t.adminOnly?{adminOnly:!0}:{},kind:t.kind,...c.value?{output:c.value}:{},returnType:l.value,visibility:o?.visibility==="internal"||t.visibility==="internal"?"internal":"public"}},$e=(e,i)=>{const t=Q(e,i);if(!t)return;if(t.channel)return{args:{},channel:{kind:t.channel,name:De(e)},kind:t.kind,returnType:"void",visibility:t.visibility};const{receiver:n}=t;return n?Fe(e,n,t,i):t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",...t.lifecycle==="socket"?{socket:{...Ue(e),origin:`${e.getSourceFile().getFilePath()}@${String(e.getStart())}`}}:{},visibility:t.visibility}:{args:ge(e),kind:t.kind,returnType:re(e),visibility:t.visibility}},V=e=>{const i=e?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},Ve=e=>V(e.getFirstAncestor(i=>s.isVariableStatement(i))),je=e=>{const i=new Map;for(const t of e.getVariableStatements())if(t.isExported())for(const n of t.getDeclarations())i.has(n.getName())||i.set(n.getName(),t);return t=>V(i.get(t))},j=(e,i,t,n,o)=>{const r=$e(e,n);if(!r)return;const a=o??Ve(e);return{args:r.args,...a?{description:a}:{},exportName:i,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},...r.meta===void 0?{}:{meta:r.meta},visibility:r.visibility,...r.adminOnly?{adminOnly:!0}:{},...r.kind==="query"&&(ne(e)===void 0||J(e))?{readsIp:!0}:{},...r.expose?{expose:r.expose}:{},...r.x402?{x402:r.x402}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{},...r.channel?{channel:r.channel}:{},...r.socket?{socket:r.socket}:{}}},Be=(e,i,t)=>{const n=[];for(const o of e.getExportAssignments()){if(o.isExportEquals())continue;const r=x(o.getExpression()),a=r?j(r,"default",i,t):void 0;r&&a&&n.push({call:r,entry:a})}return n},ze=(e,i,t)=>{const n=K(e),o=je(e),r=new Map,a=(d,u)=>{if(d?.channel?.kind!=="room")return;const m=r.get(d.channel.name);if(m!==void 0&&m!==u)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${d.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);r.set(d.channel.name,u)},c=e.getVariableStatements().flatMap(d=>d.getDeclarations()).flatMap(d=>_e(d,u=>n.has(u))).flatMap(([d,u])=>(n.get(d)??[]).filter(m=>O(m)).flatMap(m=>{const p=j(u,m,i,t,o(m));return a(p,u),p?[p]:[]})),l=new Set(c.map(d=>d.exportName));for(const d of e.getVariableStatements().flatMap(u=>u.getDeclarations()))for(const[u,m]of Re(d,p=>n.has(p)))for(const p of(n.get(u)??[]).filter(v=>O(v)&&!l.has(v))){const v=Ie(m,p,i,o(p));v&&(c.push(v),l.add(p))}for(const{call:d,entry:u}of Be(e,i,t))l.has(u.exportName)||(a(u,d),c.push(u));return c},He=e=>{const i=new Map;for(const t of e){if(t.channel?.kind!=="room")continue;const n=i.get(t.channel.name);if(n!==void 0&&n.file!==t.filePath)throw new g("DUPLICATE_ROOM_NAME",`Duplicate room name "${t.channel.name}": defined in ${n.origin} and ${t.filePath}:${t.exportName}. Room names must be unique across the project.`);n===void 0&&i.set(t.channel.name,{file:t.filePath,origin:`${t.filePath}:${t.exportName}`})}},Me=e=>{const i=new Map;for(const t of e){const n=ie(t.filePath),o=i.get(n);if(o&&o!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${t.filePath}" both resolve to "${n}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,t.filePath],status:500});i.set(n,t.filePath)}},nt=(e,i,t={})=>{const n=M(i),o=[];for(const r of n){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=W(i,r);o.push(...ze(a,c,t.lazyFunctions===!0))}return o.sort((r,a)=>`${r.filePath}:${r.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),Me(o),He(o),o};export{nt as d,I as i,ne as p,it as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-
|
|
1
|
+
import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-DRIdZaij.mjs";import{j as m,h as p}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-BRI5W-Mp.mjs";import{w as g,c as h}from"./classify-procedure-call-BZ164dkJ.mjs";import{a as k}from"./property-name-7cBlgK_O.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-
|
|
1
|
+
import{Node as s,SyntaxKind as i}from"ts-morph";import{i as n}from"./context-root-DnvrQxae.mjs";const o=/rate|limit|\bip\b|geo|throttle/iu,a=/^run[A-Z]/u,l=t=>s.isIdentifier(t)?(t.getSymbol()?.getDeclarations()??[]).some(r=>r.getFirstAncestorByKind(i.ImportDeclaration)?.getModuleSpecifierValue().startsWith("@lunora/")===!0):!1,c=t=>{const e=s.isCallExpression(t)?t.getExpression():t;let r;return s.isIdentifier(e)?r=e:s.isPropertyAccessExpression(e)&&(r=e.getNameNode()),r!==void 0&&l(s.isPropertyAccessExpression(e)?e.getExpression():r)&&!o.test(r.getText())},p=t=>{const e=s.isCallExpression(t)?t.getExpression():void 0;if(s.isElementAccessExpression(e)){const r=e.getArgumentExpression();return(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))&&r.getLiteralText()==="use"}return s.isPropertyAccessExpression(e)&&e.getName()==="use"},g=t=>{const e=t.getParent();return s.isPropertyAccessExpression(e)&&e.getExpression()===t?!a.test(e.getName()):s.isElementAccessExpression(e)&&e.getExpression()===t?s.isStringLiteral(e.getArgumentExpression())||s.isNoSubstitutionTemplateLiteral(e.getArgumentExpression()):s.isVariableDeclaration(e)&&e.getInitializer()?.getText()===t.getText()},u=t=>{if(s.isPropertyAccessExpression(t))return t.getName()==="ip";if(s.isElementAccessExpression(t)){const e=t.getArgumentExpression();return(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))&&e.getLiteralText()==="ip"}return s.isBindingElement(t)?t.getDotDotDotToken()!==void 0||(t.getPropertyNameNode()?.getText()??t.getName())==="ip":s.isShorthandPropertyAssignment(t)&&t.getName()==="ip"},A=t=>{for(const e of t.getDescendants()){if(u(e)||p(e)&&!c(e.getArguments()[0]))return!0;if(s.isIdentifier(e)&&n(e)&&!g(e)){const r=e.getParent();if(!(s.isParameterDeclaration(r)||s.isBindingElement(r)||s.isVariableDeclaration(r)))return!0}}return!1};export{A as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as A,readdirSync as P,realpathSync as D,lstatSync as I}from"node:fs";import{dirname as w,join as x,relative as F,sep as N,extname as O,basename as k}from"node:path";import{matcher as z}from"@visulima/fs";import{SyntaxKind as p,Node as s,VariableDeclarationKind as j}from"ts-morph";import{diagnosticAt as M}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{r as K}from"./project-config-file-DR7xrrNB.mjs";import{findProjectConfigFile as $,findCodegenConfigFile as V}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";import{p as B,a as U}from"./property-name-7cBlgK_O.mjs";const W=/\.ts$/u,g=(e,t)=>F(e,t).split(N).join("/").replace(W,""),H=new Set(["_generated","node_modules"]),L=new Set(["__fixtures__","__mocks__","__snapshots__","__tests__"]),_=/\.(?:bench|e2e|e2e-spec|spec|spec-d|test|test-d)(?:\.tsx?)?$/u,ve=e=>{const t=e.split("/");return _.test(t.at(-1)??"")||t.slice(0,-1).some(i=>L.has(i))},d=(e,t,i)=>t?H.has(e)||!i&&L.has(e):!i&&_.test(e),v=new Map,E=()=>!1;let f;const X=e=>{const t=V(e),i=t===void 0?void 0:A(t,{throwIfNoEntry:!1});if(t===void 0||i===void 0)return E;const n=`${String(i.mtimeMs)}:${String(i.size)}`,r=v.get(t);if(r?.key===n)return r.isExcluded;const{codegen:o}=K(w(t));o?.unreadable&&console.warn("@lunora/codegen: `codegen.exclude` in lunora.config is not an array of string literals without `!` negations — ignoring it.");const c=o?.exclude?.length?z(o.exclude):E;return v.set(t,{isExcluded:c,key:n}),c},G=(e,t,i)=>e==="schema.ts"&&t===i,Y=e=>{try{return A(e)}catch{console.warn(`@lunora/codegen: skipping ${e} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},R=(e,t,i,n,r)=>{let o,c;try{o=P(e),c=D(e)}catch{return t}if(n.has(c))return t;n.add(c);for(const l of o){const u=x(e,l),a=Y(u);a===void 0||r(l,F(i,u).split(N).join("/"),a.isDirectory())||(a.isDirectory()?R(u,t,i,n,r):a.isFile()&&O(l)===".ts"&&!G(l,e,i)&&t.push(u))}return t},C=(e,t={})=>{const i=t.includeSkipped??!1,n=`${String(i)}\0${e}`,r=f?.get(n);if(r!==void 0)return[...r];const o=i?E:X(e),c=R(e,[],e,new Set,(l,u,a)=>d(l,a,i)||o(u));return f?.set(n,c),[...c]},he=e=>{if(f!==void 0)return e();f=new Map;try{return e()}finally{f=void 0}},q=["src/server","src/index.ts","src/worker.ts"],Q=new Set([".ts",".tsx"]),T=(e,t=[])=>{let i;try{i=I(e)}catch{return t}if(i.isFile())return Q.has(O(e))&&!d(k(e),!1,!1)&&t.push(e),t;if(!i.isDirectory())return t;for(const n of P(e))d(n,!0,!1)||T(x(e,n),t);return t},J=e=>{const t=w(e),i=C(e).map(o=>({displayPath:g(e,o),filePath:o})),n=new Set(i.map(o=>o.filePath)),r=$(t);for(const o of[...q.flatMap(c=>T(x(t,c))),...r===void 0?[]:[r]])n.has(o)||(n.add(o),i.push({displayPath:g(t,o),filePath:o}));return i},Z=e=>Array.isArray(e),h=new WeakMap,ee=(e,t)=>{let i=h.get(e.compilerNode);i===void 0&&(i=new Map,h.set(e.compilerNode,i));let n=i.get(t);return n===void 0&&(n=e.getDescendantsOfKind(t),i.set(t,n)),n},b=(e,t,i,n)=>{const r=[];for(const{displayPath:o,filePath:c}of t){const l=e.getSourceFile(c)??e.addSourceFileAtPath(c);for(const u of ee(l,i)){const a=n(u,o);Z(a)?r.push(...a):a!==void 0&&r.push(a)}}return r},te=e=>C(e).map(t=>({displayPath:g(e,t),filePath:t})),ie=(e,t,i,n)=>b(e,te(t),i,n),ye=(e,t,i)=>ie(e,t,p.CallExpression,i),Ae=(e,t,i)=>b(e,J(t),p.CallExpression,i),Pe=e=>B(e.getPropertyNameNode()??e.getNameNode()),S=(e,t)=>e?.getProperties().find(i=>!s.isSpreadAssignment(i)&&U(i)===t),we=(e,t)=>{if(t){const o=e.getArguments()[0];return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0}const i=e.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=S(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const r=n.getInitializer();return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0},Fe=(e,t)=>{if(!e||!s.isObjectLiteralExpression(e))return;const i=S(e,t);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},se=e=>{const t=e?.getParent();return s.isVariableDeclaration(e)&&s.isVariableDeclarationList(t)&&t.getDeclarationKind()===j.Const},ne=e=>{let t=e,i=t.getParent();for(;i!==void 0&&(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isTypeAssertion(i)||s.isNonNullExpression(i));)t=i,i=t.getParent();return t},y=e=>{const t=ne(e),i=t.getParent();if(i===void 0)return!1;if(s.isBinaryExpression(i)){const r=i.getOperatorToken().getKind();return i.getLeft()===t&&r>=p.FirstAssignment&&r<=p.LastAssignment}if(s.isPrefixUnaryExpression(i)||s.isPostfixUnaryExpression(i)){const r=i.getOperatorToken();return r===p.PlusPlusToken||r===p.MinusMinusToken}return s.isDeleteExpression(i)?!0:s.isForOfStatement(i)||s.isForInStatement(i)?i.getInitializer()===t:s.isPropertyAssignment(i)?i.getInitializer()===t&&y(i):(s.isShorthandPropertyAssignment(i)||s.isSpreadAssignment(i)||s.isSpreadElement(i)||s.isObjectLiteralExpression(i)||s.isArrayLiteralExpression(i))&&y(i)},re=e=>{const t=e?.getDeclarations().find(n=>s.isVariableDeclaration(n));if(!se(t))return;const i=t.getParent().getParent();return s.isVariableStatement(i)&&s.isSourceFile(i.getParent())?t.getInitializer():void 0},oe=e=>re(e.getSymbol()),Ne=e=>{if(!e)return;if(s.isObjectLiteralExpression(e))return e;if(!s.isIdentifier(e))return;const t=oe(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},m=e=>{let t=e;for(;t&&(s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isParenthesizedExpression(t)||s.isNonNullExpression(t));)t=t.getExpression();return t},ce=(e,t)=>{let i=m(e);for(;s.isAwaitExpression(i)||s.isPropertyAccessExpression(i)||s.isElementAccessExpression(i)||s.isCallExpression(i);){const n=s.isCallExpression(i)?t?.(i):void 0;if(n!==void 0)return{verdict:n};i=m(i.getExpression())}return{root:i}},Oe=e=>ce(e).root,Le=e=>s.isArrowFunction(e)||s.isConstructorDeclaration(e)||s.isFunctionDeclaration(e)||s.isFunctionExpression(e)||s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)||s.isSetAccessorDeclaration(e),_e=(e,t)=>e?.compilerNode===t.compilerNode,Re=e=>{if(s.isPropertyAccessExpression(e))return{member:e.getName(),object:e.getExpression()};const t=s.isElementAccessExpression(e)?e.getArgumentExpression():void 0;return s.isElementAccessExpression(e)&&s.isStringLiteral(t)?{member:t.getLiteralValue(),object:e.getExpression()}:void 0},Ce=e=>{const t=e.getParent();return s.isReturnStatement(t)||s.isArrowFunction(t)&&t.getBody()===e?e.getFirstAncestor(n=>s.isFunctionLikeDeclaration(n)||s.isArrowFunction(n)):void 0},Te=e=>{const t=m(e);return t&&s.isCallExpression(t)?t:void 0},be=e=>{const t=e.getExportAssignment(r=>!r.isExportEquals());if(!t)return;const i=t.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},De=e=>{const t=e.getArguments()[1];return t&&s.isStringLiteral(t)?t.getLiteralValue():""},Ie=(e,t)=>{if(!s.isObjectLiteralExpression(e))return;const i=S(e,t);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},ae=e=>{const t=e.getStatements(),[i]=t;if(t.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},ke=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isParenthesizedExpression(e)){const t=e.getExpression();return s.isObjectLiteralExpression(t)?t:void 0}return s.isBlock(e)?ae(e):void 0},ze=e=>(t,i,n)=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t))return t.getLiteralValue();throw M(t,`${e} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},le=new Set(["api","internal"]),je=new Set(["run","runAction","runMutation","runQuery"]),ue=e=>{if(e===void 0||!s.isPropertyAccessExpression(e))return;const t=[];let i=e;for(;s.isPropertyAccessExpression(i);)t.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&le.has(i.getText())&&t.length>=2?t:void 0},Me=e=>{const t=ue(e);return t===void 0?void 0:`${t.slice(0,-1).join("_")}:${String(t.at(-1))}`};export{je as RUN_METHODS,W as TS_EXTENSION_RE,Pe as bindingKeyName,Oe as chainRootOf,ye as collectCallRows,ie as collectNodeRows,Ae as collectSecurityCallRows,be as defaultExportExpression,ee as descendantsOfKind,S as findObjectProperty,Me as functionKeyOf,ue as functionReferenceSegments,we as handlerOf,se as isConstDeclaration,Le as isFunctionLike,_e as isSameNode,ve as isTestPath,y as isWriteTarget,De as limitNameOf,C as listLunoraSourceFiles,J as listSecurityScanFiles,g as lunoraRelativePath,Re as memberAccessOf,ke as objectLiteralFromCallbackBody,Ne as optionsObjectLiteral,ne as outermostValueWrapper,Fe as propertyInitializer,U as propertyKeyName,B as propertyNameText,Ce as returningFunctionOf,ze as stringPropertyFor,Ie as stringPropertyOf,re as symbolConstInitializer,m as unwrapExpression,Te as unwrapToCallExpression,ce as walkChain,he as withSourceListMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a,p as t,e as i,r as s,c,d,a as n}from"./project-config-file-DR7xrrNB.mjs";import"./property-name-7cBlgK_O.mjs";import{PROJECT_CONFIG_FILENAMES as P,findProjectConfigFile as f}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";export{P as PROJECT_CONFIG_FILENAMES,f as findProjectConfigFile,a as loadProjectConfig,t as projectConfigProblems,i as readMergeDurableObjects,s as readProjectConfigLiterals,c as readProjectLazyFunctions,d as readProjectSecurityHeaders,n as readProjectStudioCompanion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-
|
|
1
|
+
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./isTestPath-DRIdZaij.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as B,readFileSync as se}from"node:fs";import{basename as j}from"node:path";import{createJiti as ie}from"jiti";import{Node as s,SyntaxKind as p,VariableDeclarationKind as J,Project as oe}from"ts-morph";import{s as ae,a as h}from"./property-name-7cBlgK_O.mjs";import{findProjectConfigFile as W,findCodegenConfigFile as w}from"./PROJECT_CONFIG_FILENAMES-CLfsyvjA.mjs";const q=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},ce=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,Q=e=>[...e].every(t=>t===" "||t>=" "&&t!==""&&t<="ÿ"),le=["same-origin","same-origin-allow-popups","unsafe-none"],ue=["DENY","SAMEORIGIN"],$=["includeSubDomains","maxAge","preload"],X=["csp","permissionsPolicy","referrerPolicy"],I=[...X,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],M=e=>e.map(t=>JSON.stringify(t)).join(", "),de=(e,t)=>{if(typeof e=="boolean")return e;if(!q(e)){t.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const o of Object.keys(e).filter(a=>!$.includes(a)))t.push(`security.headers.hsts.${o} is not an option (expected ${M($)})`);const{includeSubDomains:r,maxAge:n,preload:i}=e;n!==void 0&&!(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&t.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(n)})`);for(const[o,a]of[["includeSubDomains",r],["preload",i]])a!==void 0&&typeof a!="boolean"&&t.push(`security.headers.hsts.${o} must be a boolean`);return{...r===void 0?{}:{includeSubDomains:r},...n===void 0?{}:{maxAge:n},...i===void 0?{}:{preload:i}}},V=(e,t,r,n)=>{if(t===void 0||t===!1||r.includes(t))return t;n.push(`security.headers.${e} must be one of ${M(r)} or false (got ${JSON.stringify(t)})`)},fe=(e,t)=>{if(e!==void 0){if(!Array.isArray(e)){t.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const r of e)(typeof r!="string"||!ce.test(r)||!Q(r))&&t.push(`security.headers.frameAncestors entry ${JSON.stringify(r)} is not an origin like "https://partner.example"`);return[...e]}},pe=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!q(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const t=Object.keys(e).filter(n=>!I.includes(n)).map(n=>`security.headers.${n} is not an option (expected ${M(I)})`),r={};for(const n of X){const i=e[n];i===void 0||i===!1?r[n]=i:typeof i!="string"?t.push(`security.headers.${n} must be a string or false`):Q(i)?r[n]=i:t.push(`security.headers.${n} contains a line break or control character`)}return r.crossOriginOpenerPolicy=V("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,le,t),r.frameOptions=V("frameOptions",e.frameOptions,ue,t),r.frameAncestors=fe(e.frameAncestors,t),r.hsts=e.hsts===void 0?void 0:de(e.hsts,t),r.frameAncestors!==void 0&&typeof r.csp=="string"&&t.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),r.frameAncestors!==void 0&&r.frameOptions==="DENY"&&t.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),r.frameAncestors!==void 0&&r.csp===!1&&t.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),t.length>0?{ok:!1,problems:t}:{ok:!0,value:Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}},ge=(e,t)=>{const r=Array.from({length:t.length+1},(n,i)=>i);for(let n=1;n<=e.length;n+=1){let i=r[0]??0;r[0]=n;for(let o=1;o<=t.length;o+=1){const a=r[o]??0,l=e[n-1]===t[o-1]?0:1;r[o]=Math.min((r[o-1]??0)+1,a+1,i+l),i=a}}return r[t.length]??0},me=(e,t)=>{let r,n=Number.POSITIVE_INFINITY;for(const o of t){const a=ge(e,o);a<n&&(n=a,r=o)}const i=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&n<=i?r:void 0},g=Symbol("not-literal"),C=e=>Number(e.getText().replaceAll("_","")),b=e=>s.isTrueLiteral(e)||s.isFalseLiteral(e)?e.getLiteralValue():s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.ExclamationToken&&s.isNumericLiteral(e.getOperand())?C(e.getOperand())===0:void 0,be=e=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();if(s.isNumericLiteral(e))return C(e);if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken&&s.isNumericLiteral(e.getOperand()))return-C(e.getOperand());const t=b(e);return t!==void 0?t:s.isBinaryExpression(e)?ve(e):s.isNullLiteral(e)?null:g},ye={[p.AsteriskAsteriskToken]:(e,t)=>e**t,[p.AsteriskToken]:(e,t)=>e*t,[p.MinusToken]:(e,t)=>e-t,[p.PercentToken]:(e,t)=>e%t,[p.PlusToken]:(e,t)=>e+t,[p.SlashToken]:(e,t)=>e/t},ve=e=>{const t=ye[e.getOperatorToken().getKind()],[r,n]=[S(e.getLeft()),S(e.getRight())];return t!==void 0&&typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)?t(r,n):g},S=e=>{if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e))return S(e.getExpression());if(s.isArrayLiteralExpression(e)){const t=e.getElements().map(r=>S(r));return t.includes(g)?g:t}return s.isObjectLiteralExpression(e)?he(e):be(e)},he=e=>{const t=[];for(const r of e.getProperties()){const n=s.isPropertyAssignment(r)?r.getNameNode():void 0,i=s.isPropertyAssignment(r)?r.getInitializer():void 0,o=i===void 0?g:S(i);if(n===void 0||o===g||!(s.isIdentifier(n)||s.isStringLiteral(n)))return g;const a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(a==="__proto__")return g;t.push([a,o])}return Object.fromEntries(t)},N={accepts:["boolean"],expected:"a boolean"},xe={accepts:["function"],expected:"a function"},Oe={accepts:["number"],expected:"a number"},E={accepts:["string"],expected:"a string"},D={accepts:["array"],expected:"an array of strings",items:E},L={accepts:["boolean","string"],expected:"a string or `false`",literal:!1},v=(e,t)=>({accepts:["object"],expected:"an object",keys:e,...t===void 0?{}:{required:t}}),Ee={crossOriginOpenerPolicy:L,csp:L,frameAncestors:D,frameOptions:L,hsts:{accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries($.map(e=>[e,e==="maxAge"?Oe:N]))},permissionsPolicy:L,referrerPolicy:L},Se={accepts:["boolean","object"],expected:"a boolean or an object",keys:Object.fromEntries(I.toSorted((e,t)=>e.localeCompare(t)).map(e=>[e,Ee[e]]))},u=e=>{let t=e;for(;t!==void 0&&(s.isSatisfiesExpression(t)||s.isAsExpression(t)||s.isParenthesizedExpression(t));)t=t.getExpression();return t},Le=(e,t)=>e.getDescendants().some(r=>{if(s.isBinaryExpression(r)){const n=r.getOperatorToken().getKind(),i=r.getLeft();return n>=p.FirstAssignment&&n<=p.LastAssignment&&s.isIdentifier(i)&&i.getText()===t}return(s.isPrefixUnaryExpression(r)||s.isPostfixUnaryExpression(r))&&(r.getOperatorToken()===p.PlusPlusToken||r.getOperatorToken()===p.MinusMinusToken)&&r.getOperand().getText()===t}),T=(e,t)=>{const r=e.getVariableDeclaration(t);return r===void 0?void 0:r.getVariableStatement()?.getDeclarationKind()===J.Const||!Le(e,t)?r.getInitializer():void 0},Z=(e,t)=>{const r=u(e);return r!==void 0&&s.isIdentifier(r)?u(T(t,r.getText())):r},Ae=e=>{if(e!==void 0)return s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isTemplateExpression(e)?"string":b(e)!==void 0?"boolean":s.isBigIntLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isBigIntLiteral(e.getOperand())?"bigint":s.isNumericLiteral(e)||s.isPrefixUnaryExpression(e)&&s.isNumericLiteral(e.getOperand())?"number":s.isNullLiteral(e)?"null":s.isObjectLiteralExpression(e)?"object":s.isArrayLiteralExpression(e)?"array":s.isArrowFunction(e)||s.isFunctionExpression(e)||s.isMethodDeclaration(e)?"function":void 0},Ne={array:"an array",bigint:"a bigint",boolean:"a boolean",function:"a function",null:"null",number:"a number",object:"an object",string:"a string"},_=e=>s.isPropertyAssignment(e)?e.getInitializer():s.isShorthandPropertyAssignment(e)?e.getNameNode():s.isMethodDeclaration(e)?e:void 0,je=(e,t,r)=>{const n=l=>t===""?l:`${t}.${l}`,i=me(e,r),o=i===void 0?"":` Did you mean \`${n(i)}\`?`,a=t===""?"":` of \`${t}\``;return`unknown key \`${n(e)}\`.${o} Valid keys${a}: ${r.join(", ")}.`},ee=(e,t,r,n)=>{const i=Z(e,n),o=Ae(i);if(i===void 0||o===void 0)return[];const a=i.getText(),l=a.length>40?`${a.slice(0,37)}...`:a;if(!t.accepts.includes(o))return[`\`${r}\` must be ${t.expected}, got ${Ne[o]} (${l}).`];if(t.literal!==void 0&&o==="boolean"&&b(i)!==t.literal)return[`\`${r}\` must be ${t.expected}, got \`${a}\`.${t.hint===void 0?"":` ${t.hint}`}`];if(t.items!==void 0&&s.isArrayLiteralExpression(i)){const{items:c}=t,d=i.getElements(),f=d.findIndex(O=>s.isSpreadElement(O));return(f===-1?d:d.slice(0,f)).flatMap((O,ne)=>ee(O,c,`${r}[${String(ne)}]`,n))}return s.isObjectLiteralExpression(i)&&(t.keys!==void 0||t.entries!==void 0)?R(i,t,r,n):[]},Pe=(e,t,r)=>{const n=(e.required??[]).filter(i=>!t.has(i));return n.length===0?[]:[`\`${r}\` is missing ${n.map(i=>`\`${i}\``).join(", ")}.`]},R=(e,t,r,n,i=!1)=>{const o=e.getProperties(),a=f=>s.isSpreadAssignment(f)?void 0:ae(f.getNameNode()),l=!i&&o.every(f=>a(f)!==void 0),c=[],d=new Map(o.map(f=>[a(f),f]));for(const f of o){const y=a(f);if(y===void 0)continue;const O=t.entries??(t.keys!==void 0&&Object.hasOwn(t.keys,y)?t.keys[y]:void 0);O===void 0?c.push(je(y,r,Object.keys(t.keys??{}))):c.push(...Te(f,O,r===""?y:`${r}.${y}`,n,l&&d.get(y)===f))}return l?[...c,...Pe(t,d,r)]:c},Te=(e,t,r,n,i)=>{if(s.isGetAccessorDeclaration(e)||s.isSetAccessorDeclaration(e))return[];if(i)return ee(_(e),t,r,n);const o=Z(_(e),n);return o!==void 0&&s.isObjectLiteralExpression(o)&&(t.keys!==void 0||t.entries!==void 0)?R(o,t,r,n,!0):[]},ke=e=>s.isInterfaceDeclaration(e)||s.isTypeAliasDeclaration(e)||s.isExportSpecifier(e)&&(e.isTypeOnly()||e.getExportDeclaration().isTypeOnly()),$e=e=>e.getExportSymbols().filter(t=>{const r=t.getDeclarations();return r.length===0||!r.every(n=>ke(n))}).map(t=>t.getName()),Ie=(e,t,r)=>{if(t.getExportSymbols().some(c=>c.getName()==="default"))return;const n=$e(t),i=t.getExportDeclarations().filter(c=>c.isNamespaceExport()&&c.getNamespaceExport()===void 0&&!c.isTypeOnly()).map(c=>c.getModuleSpecifierValue()).filter(c=>c!==void 0);if(n.length===0&&i.length===0)return;if(n.length===0)return`${e} has no default export, so none of its settings are read (it only re-exports ${i.map(c=>`\`${c}\``).join(", ")} with \`export *\`, which never forwards a default). Lunora reads only the default export, and codegen reads its settings from this file without loading the modules it imports: move them here as \`export default { … } satisfies LunoraConfig\`.`;const o=n.filter(c=>r.has(c)),a=n.filter(c=>{const d=u(T(t,c));return!r.has(c)&&d!==void 0&&s.isObjectLiteralExpression(d)});let l="`export default { … } satisfies LunoraConfig`";return o.length>0?l=`\`export default { ${o.join(", ")} } satisfies LunoraConfig\``:a.length===1&&(l=`\`export default ${String(a[0])};\` in place of the named export`),`${e} has no default export, so none of its settings are read (it exports ${n.map(c=>`\`${c}\``).join(", ")}). Lunora reads only the default export: ${l}.`},te=e=>{const t=e.getExportAssignments().find(i=>!i.isExportEquals()),r=e.getExportDeclarations().filter(i=>!i.hasModuleSpecifier()&&!i.isTypeOnly()).flatMap(i=>i.getNamedExports()).find(i=>(i.getAliasNode()?.getText()??i.getName())==="default"),n=t===void 0&&r!==void 0?r.getNameNode():u(t?.getExpression());return n!==void 0&&s.isIdentifier(n)?u(T(e,n.getText())):n},Ce=e=>{const t=te(e);return t!==void 0&&s.isObjectLiteralExpression(t)?t:void 0},De=e=>{const t=te(e);if(t!==void 0)return s.isArrayLiteralExpression(t)?"an array":s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isTemplateExpression(t)?"a string":s.isNumericLiteral(t)?"a number":b(t)!==void 0?"a boolean":s.isNullLiteral(t)?"null":void 0},m=(e,t)=>s.isPropertyAssignment(e)?e.getInitializer():T(t,h(e)),x=(e,t,r)=>{const n=u(e);if(n===void 0||!s.isObjectLiteralExpression(n))return{unreadable:!0};const i=n.getProperties(),o=i.filter(c=>s.isPropertyAssignment(c)&&!s.isComputedPropertyName(c.getNameNode())||s.isShorthandPropertyAssignment(c));if(o.length!==i.length)return{unreadable:!0};const a=o.findLast(c=>h(c)===r);if(a===void 0)return{absent:!0};const l=m(a,t);return l===void 0?{unreadable:!0}:{literal:l}},z=["exportName","file","reason","rule"],ze=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return;const r={};for(const l of t.getProperties()){if(!s.isPropertyAssignment(l)||s.isComputedPropertyName(l.getNameNode()))return;const c=h(l),d=u(l.getInitializer());if(!z.includes(c)||d===void 0||!s.isStringLiteral(d)&&!s.isNoSubstitutionTemplateLiteral(d))return;r[c]=d.getLiteralValue()}const{exportName:n,file:i,reason:o,rule:a}=r;return n?.trim()&&i?.trim()&&o?.trim()&&a?.trim()?{exportName:n,file:i,reason:o,rule:a}:void 0},we=(e,t)=>{const r=x(e,t,"accept");if("absent"in r)return{};const n="literal"in r?u(r.literal):void 0;if(n===void 0||!s.isArrayLiteralExpression(n))return{acceptUnreadable:!0};const i=[];for(const o of n.getElements()){const a=ze(o);if(a===void 0)return{acceptUnreadable:!0};i.push(a)}return{accept:i}},Me=(e,t)=>{const r=x(e,t,"minSeverity"),n=we(e,t);return"absent"in r?{advisor:n}:"literal"in r&&s.isStringLiteral(r.literal)?{advisor:{...n,minSeverity:r.literal.getLiteralValue()}}:{advisor:{...n,unreadable:!0}}},Re=(e,t)=>{const r=x(e,t,"exclude");if("absent"in r)return{};if(!("literal"in r)||!s.isArrayLiteralExpression(r.literal))return{unreadable:!0};const n=[];for(const i of r.literal.getElements()){if(!s.isStringLiteral(i)&&!s.isNoSubstitutionTemplateLiteral(i)||i.getLiteralValue().startsWith("!"))return{unreadable:!0};n.push(i.getLiteralValue())}return{exclude:n}},Ve=(e,t,r)=>{const n=x(e,t,"lazyFunctions");if("absent"in n)return{};if("unreadable"in n)return e!==void 0&&(s.isIdentifier(e)||e.getText().includes("lazyFunctions")||r&&!s.isObjectLiteralExpression(e))?{lazyFunctionsUnreadable:!0}:{};const i="literal"in n?u(n.literal):void 0,o=i===void 0?void 0:b(i);return o===void 0?{lazyFunctionsUnreadable:!0}:{lazyFunctions:o}},_e=(e,t)=>{const r=u(e),n=r!==void 0&&s.isIdentifier(r),i=r!==void 0&&s.isIdentifier(r)?t.getVariableDeclaration(r.getText()):void 0,o=i?.getVariableStatement()?.getDeclarationKind()===J.Const,a=i?.getNameNode(),c=i!==void 0&&o&&a!==void 0&&s.isIdentifier(a)&&a.findReferencesAsNodes().length===1?u(i.getInitializer())??r:r;return{codegen:{...Re(c,t),...Ve(c,t,n)}}},Ue=(e,t)=>{const r=x(e,t,"merge");if("absent"in r)return{durableObjects:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{durableObjects:{unreadable:!0}}:{durableObjects:{merge:n}}},Fe=(e,t)=>{const r=x(e,t,"companion");if("absent"in r)return{studio:{}};const n="literal"in r?b(r.literal):void 0;return n===void 0?{studio:{unreadable:!0}}:{studio:{companion:n}}},Ke=(e,t)=>{const r=x(e,t,"headers");if("absent"in r)return{security:{}};const n="literal"in r?S(r.literal):g;return n===g?{security:{unreadable:!0}}:{security:{headers:n}}},re=(e,t)=>{const r=e.getProperty(t);if(r!==void 0)return(s.isPropertyAssignment(r)?r.getInitializer():void 0)??"unreadable"},U=(e,t)=>{const r=re(e,t);if(r!==void 0)return r!=="unreadable"&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():!1},Ye=e=>{const t=re(e,"rpc");if(t!==void 0)return t!=="unreadable"&&b(t)===!1?!1:"unreadable"},He=e=>{const t=u(e);if(t===void 0||!s.isObjectLiteralExpression(t))return{services:{unreadable:!0}};const r={};for(const n of t.getProperties()){if(!s.isPropertyAssignment(n)||s.isComputedPropertyName(n.getNameNode()))return{services:{unreadable:!0}};const i=u(n.getInitializer());if(i===void 0||!s.isObjectLiteralExpression(i)||i.getProperties().some(c=>!s.isPropertyAssignment(c)))return{services:{unreadable:!0}};const o=U(i,"dir"),a=U(i,"entrypoint"),l=Ye(i);if(typeof o!="string"||a===!1||l==="unreadable")return{services:{unreadable:!0}};r[h(n)]={dir:o,...a===void 0?{}:{entrypoint:a},...l===void 0?{}:{rpc:l}}}return{services:{declared:r}}},Ge=(e,t)=>s.isShorthandPropertyAssignment(e)?e.getNameNode():m(e,t),Be=(e,t)=>{const r=m(e,t);return r!==void 0&&s.isStringLiteral(r)?{target:r.getLiteralValue()}:{unreadable:!0}},Je=(e,t)=>{const r=u(m(e,t)),n=r===void 0?void 0:b(r);return n!==void 0?{remote:n}:r!==void 0&&s.isNullLiteral(r)?{}:r!==void 0&&s.isObjectLiteralExpression(r)?{remote:!0}:{unreadable:!0}},A=new Map([["advisor",{read:(e,t)=>Me(m(e,t),t),shape:v({accept:{...D,expected:"an array of objects",items:v(Object.fromEntries(z.map(e=>[e,E])),z)},minSeverity:E}),unreadable:{advisor:{unreadable:!0}}}],["app",{read:()=>({}),shape:xe,unreadable:{}}],["codegen",{read:(e,t)=>_e(Ge(e,t),t),shape:v({exclude:D,lazyFunctions:N}),unreadable:{codegen:{lazyFunctionsUnreadable:!0,unreadable:!0}}}],["durableObjects",{read:(e,t)=>Ue(m(e,t),t),shape:v({merge:N}),unreadable:{durableObjects:{unreadable:!0}}}],["remote",{read:Je,shape:{accepts:["boolean","null","object"],expected:"a boolean"},unreadable:{unreadable:!0}}],["security",{read:(e,t)=>Ke(m(e,t),t),shape:v({headers:Se}),unreadable:{security:{unreadable:!0}}}],["services",{read:(e,t)=>He(m(e,t)),shape:{accepts:["object"],entries:v({dir:E,entrypoint:E,rpc:{accepts:["boolean"],expected:"`false`",hint:"Leave it out for an RPC binding.",literal:!1}},["dir"]),expected:"an object"},unreadable:{services:{unreadable:!0}}}],["studio",{read:(e,t)=>Fe(m(e,t),t),shape:v({companion:N}),unreadable:{studio:{unreadable:!0}}}],["target",{read:Be,shape:E,unreadable:{unreadable:!0}}]]),We=(e,t)=>s.isGetAccessorDeclaration(e)||s.isMethodDeclaration(e)?A.get(h(e))?.unreadable??{}:!s.isPropertyAssignment(e)&&!s.isShorthandPropertyAssignment(e)?{}:A.get(h(e))?.read(e,t)??{},qe=(e,t)=>new oe({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(j(e),t,{overwrite:!0}),Qe=(e,t)=>{if(e.getProperties().some(n=>s.isSpreadAssignment(n))){const n=o=>e.getProperties().some(a=>!s.isSpreadAssignment(a)&&h(a)===o);let i={unreadable:!0};for(const[o,a]of A)n(o)&&(i={...i,...a.unreadable});return i}let r={};for(const n of e.getProperties())r={...r,...We(n,t)};return r},Xe=(e,t)=>{const r=qe(e,t),n=Ce(r);if(n===void 0){const o=De(r),a=o===void 0?Ie(j(e),r,A):`${j(e)} exports ${o} as its default, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`;return{literals:{unreadable:!0},...o===void 0?{namedOnly:a}:{notObject:a},problems:a===void 0?[]:[a]}}const i=v(Object.fromEntries([...A].map(([o,a])=>[o,a.shape])));return{literals:Qe(n,r),problems:R(n,i,"",r)}},F=new Map,P=e=>{let t;try{t=se(e,"utf8")}catch{return{literals:{unreadable:!0},problems:[]}}const r=F.get(e);if(r?.source===t)return r.value;const n=Xe(e,t);return F.set(e,{source:t,value:n}),n},K=new Map,at=async e=>{const t=W(e);if(t===void 0)return{};let r;try{const o=B(t);r=`${String(o.mtimeMs)}:${String(o.size)}`}catch{return{}}const n=K.get(t);if(n?.key===r)return n.value;const i=(async()=>{try{const a=(await ie(t,{interopDefault:!1,moduleCache:!1}).import(t))?.default,l=a===void 0?P(t).namedOnly:void 0;return l!==void 0?{error:l}:a!==void 0&&(a===null||typeof a!="object"||Array.isArray(a))?{error:P(t).notObject??`${j(t)}'s default export is not an object, so none of its settings are read. Lunora reads an object: \`export default { … } satisfies LunoraConfig\`.`}:{config:a}}catch(o){return{error:o instanceof Error?o.message:String(o)}}})();return K.set(t,{key:r,value:i}),i},k=e=>P(e).literals,ct=e=>P(e).problems,Ze=e=>{const t=W(e);return t===void 0?{}:k(t)},lt=e=>{const{durableObjects:t}=Ze(e);return t?.unreadable&&console.warn("@lunora/codegen: `durableObjects.merge` in lunora.config is not a boolean literal — the Durable Object classes stay separate."),t?.merge===!0};let Y;const ut=e=>{const t=w(e),{codegen:r}=t===void 0?{}:k(t);if(r?.lazyFunctionsUnreadable){const n=t===void 0?void 0:B(t,{throwIfNoEntry:!1}),i=t===void 0||n===void 0?"":`${t}:${String(n.mtimeMs)}:${String(n.size)}`;i!==Y&&(Y=i,console.warn("@lunora/codegen: `codegen.lazyFunctions` in lunora.config is not a boolean literal, so the config does not turn the function registry lazy."))}return r?.lazyFunctions===!0},H=new Set,dt=e=>{const t=w(e),{studio:r}=t===void 0?{}:k(t);return r?.unreadable&&t!==void 0&&!H.has(t)&&(H.add(t),console.warn("@lunora/codegen: `studio.companion` in lunora.config is not a boolean literal, so the companion Worker is not generated.")),r?.companion===!0},G=new Set,et=(e,t,r)=>{let n;r!==void 0?{problems:n}=r:t.unreadable&&t.security===void 0?n=["is not an object literal codegen can read, so `security.headers` cannot be read either"]:n=["`security.headers` is not built from literals"];const i=`${e??""}:${n.join(";")}`;return G.has(i)||(G.add(i),console.warn(`@lunora/codegen: lunora.config ${n.join("; ")}, so the default security headers apply.`)),!0},ft=e=>{const t=w(e),r=t===void 0?{}:k(t),{security:n}=r,o=n?.unreadable===!0||r.unreadable===!0&&n===void 0?void 0:pe(n?.headers);return o?.ok?o.value:et(t,r,o)};export{g as N,dt as a,at as b,ut as c,ft as d,lt as e,S as l,ct as p,Ze as r};
|
package/dist/packem_shared/{unwrap-handler-return-BpigsVD6.mjs → unwrap-handler-return-DUzluwPj.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-ClgKgMYM.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
|
|
1
|
+
import{posix as w,dirname as h,join as F}from"node:path";import{Node as l,SyntaxKind as g,DiagnosticCategory as K}from"ts-morph";import{lunoraRelativePath as B}from"./isTestPath-DRIdZaij.mjs";let S,v;const Oe=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Ue=e=>{S?.push(...e)},V=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},y=(e,t)=>{S?.push({exportName:V(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Pe=e=>{v!==void 0&&y(v,e)},Le=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},W=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},Fe=(e,t)=>{const n=new Map;for(const r of e){const s=W(r,B(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},q=/\bany\b(?!\s*(?:\?\s*)?:)/u,G=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,X=e=>q.test(e.replaceAll(G,"")),H="/_generated/",J=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},Y=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,x=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=Y.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},M=new WeakMap,z=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=M.get(n.compilerSymbol);return r===void 0&&(r=new Map,M.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},C=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),Q=(e,t,n)=>e.getModuleSpecifierValue()===t&&C(e,n)?n:void 0,Z=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},ee=(e,t,n)=>{if(!C(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:z(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},te=/^\.\.?(?:$|\/)/u,ne=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),re=(e,t)=>{const n=t.getModuleSpecifierValue();if(!te.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:ne.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${w.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=w.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},se=(e,t,n)=>{const r=x(t);for(const s of e.getImportDeclarations()){const i=r===void 0?Z(s,t)??ee(s,t,n):Q(s,r,n);if(i!==void 0)return{exportName:i,specifier:re(e,s)??s.getModuleSpecifierValue()}}},oe=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),f={kind:"verbatim"},p={kind:"expand"},ie=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),ae=e=>x(e)!==void 0||l.isExportable(e)&&e.isExported(),ce=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),O=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&x(e)===void 0||!ie.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(H))return f;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const c=se(t.getSourceFile(),o,o.getName());return c===void 0?ae(o)||!ce(r(),o.getName())?f:p:oe(c.specifier,t)?p:{kind:"qualify",qualified:c}},ue=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),_=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},le=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},ge=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=le(s);return i===void 0||!_(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>ue.has(s.getKind()))&&!_(r)&&t().startsWith("typeof ")},U=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,c;const a=()=>(c??=e.getText(t),c);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=O(u,t,n,a);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||ge(e,a)?p:f},de=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const c of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const a=O(c,t,n,()=>i.getText());if(a.kind==="qualify")return a;s||=a.kind!=="verbatim"}}return s?p:f},fe=/^[A-Za-z_$][\w$]*$/u,me=e=>fe.test(e)?e:JSON.stringify(e),P=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},A=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),T=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),U(e,t,n).kind!=="verbatim"||P(e).some(s=>T(s,t,n,r))?!0:A(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>de(i,t,n).kind!=="verbatim")?!0:T(s.getTypeAtLocation(t),t,n,r)):!1),pe=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},L=(e,t)=>e!==void 0&&(A(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,Se=32,ve=8,ye=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),c=o?i(o,t,n,r,s):void 0;if(c!==void 0)return`${L(o,c)}[]`},Ee=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getUnionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(a)}return[...new Set(o)].join(" | ")},be=(e,t,n,r,s,i)=>{const o=[];for(const c of e.getIntersectionTypes()){const a=i(c,t,n,r,s);if(a===void 0)return;o.push(L(c,a))}return o.join(" & ")},Te=(e,t,n,r,s,i)=>{if(!A(e))return;const o=[];for(const c of e.getProperties()){const a=c.getTypeAtLocation(t),u=pe(c,a),d=u&&a.isUnion()?a.getUnionTypes().filter(N=>!N.isUndefined()):[a],D=[];for(const N of d){const I=i(N,t,n,r+1,s);if(I===void 0)return;D.push(I)}o.push(`${me(c.getName())}${u?"?":""}: ${D.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},Ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},Ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),E=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Se)return!0;const i=new Set(r).add(e);if(P(e).some(u=>E(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return E(o,t,n+1,i,s);if(J(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const a=A(e)&&e.getProperties().some(u=>E(u.getTypeAtLocation(t),t,n+1,i,s));return a||s.add(e),a},xe=(e,t,n,r,s,i,o)=>{const c=[];for(const a of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(a,n,r,s+1,i);if(u===void 0)return;c.push(u)}return`import("${e.specifier}").${e.exportName}${c.length>0?`<${c.join(", ")}>`:""}`},De=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>ve||s.has(e))return;const i=U(e,t,n);if(i.kind==="verbatim"&&!T(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!Ne(e)){if(e.isEnumLiteral())return Ae(e);if(i.kind==="qualify"&&!De(e)){const c=xe(i.qualified,e,t,n,r,o,m);if(c!==void 0)return c}return e.isArray()?ye(e,t,n,r,o,m):e.isUnion()?Ee(e,t,n,r,o,m):e.isIntersection()?be(e,t,n,r,o,m):Te(e,t,n,r,o,m)}},R=new WeakMap,Ie=e=>{const t=R.get(e.compilerNode);if(t)return t;const n=e.getPreEmitDiagnostics().filter(r=>r.getCategory()===K.Error);return R.set(e.compilerNode,n),n},b=e=>{const t=e.getMessageText();return typeof t=="string"?t:t.getMessageText()},we=/is of type 'unknown'|on type '\{\}'/,he=e=>we.test(e),Me=/has no exported member '([^']+)'/,_e=(e,t,n,r)=>{const s=e.getSourceFile();for(const i of e.getDescendantsOfKind(g.Identifier))for(const o of i.getSymbol()?.getDeclarations()??[]){const c=o.getStart();if(o.getSourceFile()!==s||c>=n&&c<=r)continue;const a=t.find(u=>{const d=u.getStart();return d!==void 0&&d>=o.getStart()&&d<=o.getEnd()});if(a!==void 0)return b(a)}},$=e=>{const t=e.getStart(),n=e.getEnd(),r=Ie(e.getSourceFile()),s=r.find(a=>{const u=a.getStart();return u!==void 0&&u>=t&&u<=n});if(s===void 0){const a=_e(e,r,t,n);return a===void 0?void 0:{derivative:!0,message:a}}const i=b(s);if(!he(i))return{derivative:!1,message:i};const o=new Set(e.getDescendantsOfKind(g.Identifier).map(a=>a.getText())),c=r.find(a=>{const u=Me.exec(b(a))?.[1];return u!==void 0&&o.has(u)});return{derivative:!0,message:c?`${i}; caused by: ${b(c)}`:i}},Re=e=>{const t=e.getProject().getFileSystem();let n=h(e.getFilePath());for(;;){const r=F(n,"package.json");if(t.fileExistsSync(r)){let i;try{i=JSON.parse(t.readFileSync(r))}catch{return}const o=typeof i=="object"&&i!==null?i.name:void 0;return typeof o=="string"?o:void 0}const s=h(n);if(s===n)return;n=s}},k=e=>{const t=e.getSymbol()??e.getAliasSymbol(),n=t?.getName()==="SseEvent"?t.getDeclarations()[0]:void 0;return n!==void 0&&Re(n.getSourceFile())==="@lunora/server"},$e=e=>{const t=e.isUnion()?e.getUnionTypes():[e];if(t.some(n=>k(n)))return t.flatMap(n=>{const r=k(n)?n.getTypeArguments()[0]??n:n;return r.isUnion()?r.getUnionTypes():[r]})},j=(e,t)=>{const n=e.getText(t);if(!n||n==="any"||n==="never"||n==="unknown"){const s=$(t);return s!==void 0&&(n!=="unknown"||s.derivative)&&y(t,`${n||"any"} (${s.message})`),"unknown"}if(X(n)){const s=$(t);return s!==void 0&&y(t,`${n} (${s.message})`),"unknown"}if(E(e,t,0,new Set))return"unknown";const r=t.getSourceFile().getFilePath();if(T(e,t,r)){const s=m(e,t,r,0,new Set);return s===void 0&&y(t,n),s??"unknown"}return n},Ke=(e,t=!1)=>{const n=e.getType().getCallSignatures()[0];if(!n)return"unknown";let r=n.getReturnType();const i=(r.getSymbol()??r.getAliasSymbol())?.getName();if(i==="Promise"||i==="AsyncIterable"||i==="AsyncIterableIterator"||i==="AsyncGenerator"){const a=r.getTypeArguments()[0];a&&(r=a)}const o=t?$e(r):void 0;if(o===void 0)return j(r,e);const c=o.map(a=>j(a,e));return c.includes("unknown")?"unknown":[...new Set(c)].join(" | ")};export{Ue as a,T as b,Oe as c,Pe as d,m as e,Fe as f,X as i,Le as p,j as r,Ke as u};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as g,CLOUDFLARE_CAPABILITIES as b,CELLD_CAPABILITIES as y}from"@lunora/platform";import{readProjectConfigLiterals as f}from"./loadProjectConfig-CtcJHHKS.mjs";const m="cloudflare",S=t=>{const{target:e}=f(t);return e!==void 0&&e.length>0?e:void 0},I=(t,e)=>e??S(t)??m,z=(t,e)=>{if(e!==void 0)return[];const{target:r,unreadable:a}=f(t);return a!==!0||r!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${m}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${m}" }\`), or pass \`--target\`.`,target:m}]},_={max:1536,min:32},E=(t,e)=>{if(t!=="cloudflare")return[];const{max:r,min:a}=_,i=`${String(a)}-${String(r)}`;return e.filter(({dimensions:o})=>o!==void 0&&(!Number.isInteger(o)||o<a||o>r)).map(({dimensions:o,name:s})=>({level:"warn",message:`Vector index "${s}" declares ${String(o)} dimensions; Cloudflare Vectorize accepts ${i}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${s}", use ${i} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:y,cloudflare:b,node:g},O=(t,e)=>{const r=u[t];if(r===void 0)return!0;const a=r.features[e]?.level;return a==="native"||a==="emulated"},D=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),k={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","deliveryAuthorization","durableStreams","globalTables","liveStreams","queues","relationGraph","secrets","secretValues","services","topics","typedWebSockets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],h={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",deliveryAuthorization:"delivery authorization (`.deliveryAuthorization(...)` on the app builder)",cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",liveContext:"the live publisher (`ctx.live`)",liveStreams:"live topic streams (`defineLiveStream`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",secretValues:"human-supplied secret values (`requestSecretTool`, held for one agent step)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",typedWebSockets:"typed WebSocket routes and rooms (`defineWebSocket` / `defineRoom`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},T=(t,e,r)=>({level:"error",message:`${e.name} does not support ${h[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:r}),x=(t,e)=>({level:"error",message:`${t.name} withholds live streams, so ctx.live is not available on the "${e}" target, but this app reads ctx.live.`,name:"platform_unsupported_feature",remediation:'Remove the ctx.live usage, or deploy to a target whose capability matrix marks "liveStreams" as native or emulated.',target:e}),P=t=>({level:"error",message:"This app declares defineLiveStream topics and enables delivery authorization. With delivery authorization on, the shard answers every /_lunora/live/* request with 501, so the live streams cannot be served.",name:"platform_live_stream_delivery_authorization",remediation:"Remove the defineLiveStream declarations, or remove the .deliveryAuthorization(...) call. Live streams and delivery authorization cannot be combined.",target:t}),W=t=>({level:"error",message:"This app declares defineWebSocket routes and enables delivery authorization. With delivery authorization on, the shard answers every route upgrade with 501, so the routes cannot be served.",name:"platform_socket_delivery_authorization",remediation:"Remove the defineWebSocket declarations, or remove the .deliveryAuthorization(...) call. Socket routes and delivery authorization cannot be combined.",target:t}),A=(t,e,r)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${h[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:r}),$=t=>{const{diagnostics:e,gatedSignals:r,matrix:a,reported:i,signals:o,target:s}=t;for(const n of w){if(o[n]!==!0)continue;const d=a.features[n]?.level;d!=="unsupported"&&d!==void 0||(r[n]=!1,!i.has(n)&&e.push(d==="unsupported"?T(n,a,s):A(n,a,s)))}},R=(t,e,r,a={})=>{const i={...t},o={...a},s=[],n=new Set;for(const[l,c]of Object.entries(k)){if(c===null||!t[l])continue;const v=e.features[c]?.level;v==="unsupported"?(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name} does not support "${l}" (ctx.${l}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${l} usage, or deploy to a target whose capability matrix marks "${c}" as native or emulated.`,target:r})):v===void 0&&(i[l]=!1,n.add(c),s.push({feature:l,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${l}" (ctx.${l}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${c}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:r}))}$({diagnostics:s,gatedSignals:o,matrix:e,reported:n,signals:a,target:r});const d=e.features.liveStreams?.level,p=d===void 0||d==="unsupported";return a.liveContext===!0&&p&&s.push(x(e,r)),{diagnostics:s,liveStreamsWithheld:p,signals:o,usage:i}},F=(t,e,r={})=>{const a=u[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],liveStreamsWithheld:!1,signals:{...r},usage:{...t}}:R(t,a,e,r)},j=t=>{const e=u[t];if(e===void 0)return{supported:!0};const r=e.features.adminTokenRevocation?.level;return r!==void 0&&r!=="unsupported"?{supported:!0}:{diagnostic:{level:"warn",message:`${e.name} ${r===void 0?"does not declare a support level for":"does not support"} named admin tokens, so codegen omits the admin revocation store (\`_generated/adminRevocations.ts\` and the builder's \`.adminRevocations()\`). The root LUNORA_ADMIN_TOKEN is the only admin credential here.`,name:r===void 0?"platform_undeclared_feature":"platform_unsupported_feature",remediation:'Use the root admin token, or deploy to a target whose capability matrix marks "adminTokenRevocation" as native or emulated.',target:t},supported:!1}},N=t=>{const e=u[t];if(e===void 0)return;const r=Object.entries(e.features).filter(([,a])=>a.level==="unsupported").map(([a])=>a).toSorted((a,i)=>a.localeCompare(i));return{id:e.id,name:e.name,unsupported:r}};export{k as CAPABILITY_TO_FEATURE,m as DEFAULT_TARGET,j as gateAdminTokenRevocation,R as gateAgainstMatrix,F as gatePlatformFeatures,P as liveStreamsDeliveryAuthorizationDiagnostic,O as platformFeatureAvailable,D as platformMatrixIds,S as readProjectTarget,z as readTargetDiagnostics,I as resolveCodegenTarget,W as socketRoutesDeliveryAuthorizationDiagnostic,N as studioPlatformFor,E as vectorizeDimensionDiagnostics};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{w as a}from"./classify-procedure-call-BuF5PNwV.mjs";const l=s=>a(s,"use","rls");export{l as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as u,readFileSync as w}from"node:fs";import{join as d,isAbsolute as h,resolve as g}from"node:path";import{ts as E}from"ts-morph";import{companionDirectory as b,COMPANION_SERVICE_NAME as $,COMPANION_BINDING as p,companionName as S}from"./COMPANION_BINDING-Da_v9XpC.mjs";import{readProjectStudioCompanion as y,readProjectConfigLiterals as C}from"./loadProjectConfig-CtcJHHKS.mjs";const v=/^[A-Za-z_$][\w$]*$/u,N=["wrangler.jsonc","wrangler.json"],I=i=>`SERVICE_${i.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,_=(i,e)=>{const r=N.map(n=>d(e,n)).find(n=>u(n));if(r===void 0){const n=u(d(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${i}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=E.parseConfigFileTextToJson(r,w(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${i}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},f=(i,e)=>{const r=i.route??e.route,o=i.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(i.workers_dev??e.workers_dev)!==!1},O=(i,e,r)=>{if(!v.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!v.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=h(r.dir)?r.dir:g(i,r.dir),{config:n,path:t}=_(e,o),{main:s,name:m}=n;if(typeof m!="string"||m==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no Worker "name"`);if(typeof s!="string"||s==="")throw new Error(`@lunora/codegen: service "${e}": ${t} declares no "main" entry module`);const l=Object.entries(n.env??{}).map(([c,a])=>[c,a??{}]);return{binding:I(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(l.flatMap(([c,a])=>typeof a.name=="string"&&a.name!==""?[[c,a.name]]:[])),main:g(o,s),name:e,publicScopes:[...f(n,n)?[""]:[],...l.filter(([,c])=>f(c,n)).map(([c])=>c)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:m,wranglerPath:t}},j=i=>{const{services:e}=C(i);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>O(i,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const t=r.slice(o+1).find(s=>s.binding===n.binding);if(t!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${t.name}" both map to the binding ${n.binding} — rename one`)}return r},A=i=>{try{return{services:j(i)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}},B=(i,e="lunora")=>{if(!y(d(i,e)))return;const r=b(i,e);return{binding:p,envWorkers:{},main:d(r,"src","worker.ts"),name:$,publicScopes:[],worker:S(i),wranglerPath:d(r,"wrangler.jsonc")}},P=(i,e="lunora")=>{const{error:r,services:o}=A(i);try{const n=B(i,e);if(n===void 0)return{...r===void 0?{}:{error:r},services:o};const t=o.find(s=>s.worker===n.worker);return t!==void 0?{error:`lunora.config services.${t.name} deploys as "${t.worker}", the name the studio.companion Worker is given; rename that Worker or turn studio.companion off`,services:o}:{...r===void 0?{}:{error:r},services:[...o,n]}}catch(n){return{error:r??(n instanceof Error?n.message:String(n)),services:o}}},D=(i,e="lunora")=>{const r=P(i,e);return{...r,services:r.services.filter(o=>o.binding!==p||u(o.wranglerPath))}};export{B as companionServiceBinding,P as readBoundServiceBindings,D as readDevServiceBindings,A as readServiceBindings,j as resolveServiceBindings};
|