@palbase/backend 24.3.0 → 25.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/bin/palbase-backend.cjs +101 -60
  2. package/dist/bin/palbase-backend.cjs.map +1 -1
  3. package/dist/bin/palbase-backend.js +17 -13
  4. package/dist/bin/palbase-backend.js.map +1 -1
  5. package/dist/{chunk-EIXCY4SS.js → chunk-43A3KGWL.js} +80 -49
  6. package/dist/chunk-43A3KGWL.js.map +1 -0
  7. package/dist/{chunk-ERDL5VAE.js → chunk-5CMLOAEF.js} +2 -2
  8. package/dist/chunk-OEQBHE2Z.js +825 -0
  9. package/dist/chunk-OEQBHE2Z.js.map +1 -0
  10. package/dist/{chunk-7Z6MGMXQ.js → chunk-XJ2RSHEU.js} +11 -5
  11. package/dist/chunk-XJ2RSHEU.js.map +1 -0
  12. package/dist/{chunk-UWSYTUGM.js → chunk-ZQRWW37O.js} +44 -1
  13. package/dist/chunk-ZQRWW37O.js.map +1 -0
  14. package/dist/db/env.cjs.map +1 -1
  15. package/dist/db/env.d.cts +29 -13
  16. package/dist/db/env.d.ts +29 -13
  17. package/dist/db/index.cjs +212 -111
  18. package/dist/db/index.cjs.map +1 -1
  19. package/dist/db/index.d.cts +1 -1
  20. package/dist/db/index.d.ts +1 -1
  21. package/dist/db/index.js +11 -1
  22. package/dist/engine/index.cjs +87 -50
  23. package/dist/engine/index.cjs.map +1 -1
  24. package/dist/engine/index.d.cts +2 -2
  25. package/dist/engine/index.d.ts +2 -2
  26. package/dist/engine/index.js +3 -3
  27. package/dist/{index-DEneI8Mn.d.ts → index-BF1f0DfA.d.ts} +5 -2
  28. package/dist/{index-C-ALG22n.d.cts → index-CoaDN9dL.d.cts} +5 -2
  29. package/dist/{index-BTMYod_l.d.ts → index-Ct1iiB4N.d.ts} +203 -61
  30. package/dist/{index-BLAbr9ZH.d.cts → index-CwaWRhyc.d.cts} +203 -61
  31. package/dist/index.cjs +550 -297
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +122 -20
  34. package/dist/index.d.ts +122 -20
  35. package/dist/index.js +164 -217
  36. package/dist/index.js.map +1 -1
  37. package/dist/openapi/index.cjs +100 -36
  38. package/dist/openapi/index.cjs.map +1 -1
  39. package/dist/openapi/index.js +59 -2
  40. package/dist/openapi/index.js.map +1 -1
  41. package/docs/README.md +64 -31
  42. package/docs/endpoints.md +25 -28
  43. package/docs/llms-full.txt +399 -153
  44. package/docs/schema.md +272 -91
  45. package/docs/services.md +39 -4
  46. package/package.json +1 -1
  47. package/template/AGENTS.md +119 -314
  48. package/template/CLAUDE.md +13 -0
  49. package/template/controllers/notes.controller.ts +6 -13
  50. package/template/db/public.ts +38 -0
  51. package/template/models/notes/create.ts +38 -0
  52. package/template/package.json +6 -3
  53. package/template/services/note.service.test.ts +45 -0
  54. package/template/services/note.service.ts +2 -2
  55. package/dist/chunk-7Z6MGMXQ.js.map +0 -1
  56. package/dist/chunk-D5CQES25.js +0 -556
  57. package/dist/chunk-D5CQES25.js.map +0 -1
  58. package/dist/chunk-EIXCY4SS.js.map +0 -1
  59. package/dist/chunk-UWSYTUGM.js.map +0 -1
  60. package/template/db/schema.ts +0 -35
  61. /package/dist/{chunk-ERDL5VAE.js.map → chunk-5CMLOAEF.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/runtime.ts","../src/db/tx-plan.ts","../src/clients/http.ts","../src/clients/documents.ts","../src/clients/flags.ts","../src/clients/notifications.ts","../src/clients/realtime.ts","../src/clients/storage.ts","../src/clients/index.ts","../src/db/policy.ts","../src/db/schema.ts","../src/db/schema-json.ts","../src/channels.ts","../src/db/extensions.ts","../src/db/columns.ts","../src/db/raw.ts","../src/db/embedding.ts","../src/db/typed-db.ts","../src/db/env-gen.ts","../src/stack-gen.ts","../src/decorators/registry.ts","../src/decorators/controller.ts","../src/decorators/methods.ts","../src/decorators/webhook.ts","../src/decorators/hook.ts","../src/decorators/upload.ts","../src/decorators/sse.ts","../src/decorators/params.ts","../src/middleware.ts","../src/errors.ts","../src/error-registry.ts","../src/job.ts","../src/decorators/job.ts"],"sourcesContent":["export type {\n PBRequest,\n ClientInfo,\n RateLimitConfig,\n DBClient,\n DBOps,\n FileContext,\n Logger,\n CacheClient,\n SecretsService,\n PalbaseDocsClient,\n PalbaseCollectionRef,\n PalbaseDocumentRef,\n PalbaseDocumentSnapshot,\n PalbaseQuerySnapshot,\n PalbaseWhereOperator,\n PalbaseResult,\n Middleware,\n ErrorDef,\n ErrorMap,\n ErrorThrowers,\n} from \"./endpoint.js\";\nexport {\n Database,\n Documents,\n Storage,\n Cache,\n Secrets,\n Log,\n Notifications,\n Flags,\n Realtime,\n __setRuntime,\n __runWithRuntime,\n __requestALS,\n __getRuntime,\n // Where a long-lived resource lives: opened once as the app comes up, closed\n // when it goes away. `__runStartHooks` is the engine's door to them (it\n // CLAIMS the declarations, so a candidate release loaded beside the live one\n // never closes the live one's pool); `__resetLifecycleHooks` is for tests.\n onStart,\n onShutdown,\n __runStartHooks,\n __resetLifecycleHooks,\n} from \"./runtime.js\";\nexport type {\n RuntimeServices,\n RequestStore,\n LifecycleHook,\n ShutdownRunner,\n} from \"./runtime.js\";\n\n// The module clients and their composition root. The PROCESS calls\n// buildModuleClients once at boot and hands the result to createApp — which is\n// the whole reason this package now contains the implementations and not just\n// the interfaces they were being checked against by nobody.\nexport { buildModuleClients } from \"./clients/index.js\";\nexport type { ModuleClientsConfig } from \"./clients/index.js\";\nexport { makeHttpClient, PalbaseModuleError } from \"./clients/http.js\";\nexport type { ModuleTransport, RequestOptions, TransportConfig } from \"./clients/http.js\";\n\nexport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseInvokeOptions,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseFlagSource,\n PalbaseSetOverrideResult,\n PalbaseSetOverridesResult,\n PalbaseClearOverrideResult,\n PalbaseClearAllOverridesResult,\n PalbaseBatchOverrideOperation,\n PalbaseBatchSetOverridesResult,\n PalbaseNotificationsClient,\n PalbasePushClient,\n PalbaseEmailClient,\n PalbaseSmsClient,\n PalbaseInboxClient,\n PalbasePreferencesClient,\n PalbaseAnalyticsClient,\n PalbaseAnalyticsQueryNamespace,\n PalbaseAnalyticsManagementNamespace,\n PalbaseLinksClient,\n // Shared local types\n PalbaseUser,\n PalbaseSession,\n PalbaseDeviceInfo,\n PalbaseAttestAndroidParams,\n PalbaseAttestAndroidResult,\n PalbaseAttestiOSParams,\n PalbaseAttestiOSResult,\n PalbaseBindDeviceParams,\n PalbaseVerifyRequestSignatureParams,\n PalbaseFileObject,\n PalbaseSignedUrlResponse,\n PalbaseUploadOptions,\n PalbaseTransformOptions,\n PalbaseListOptions,\n PalbasePushSendParams,\n PalbasePushSendResponse,\n PalbaseEmailSendParams,\n PalbaseEmailSendResponse,\n PalbaseSmsSendParams,\n PalbaseSmsSendResponse,\n PalbaseInboxSendParams,\n PalbaseInboxSendResponse,\n PalbaseInboxMessage,\n PalbaseInboxListOptions,\n PalbaseInboxListResult,\n PalbasePreferences,\n PalbaseRegisterDeviceParams,\n PalbaseDeviceTokenView,\n PalbaseMultiChannelResponse,\n PalbaseAnalyticsProperties,\n PalbaseIdentifyTraits,\n PalbaseCountQueryInput,\n PalbaseCountResult,\n PalbaseEventsQueryInput,\n PalbaseEventsResult,\n PalbaseUsersQueryInput,\n PalbaseUsersResult,\n PalbaseFunnelQueryInput,\n PalbaseFunnelResult,\n PalbaseRetentionQueryInput,\n PalbaseRetentionResult,\n PalbaseCohortQueryInput,\n PalbaseCohortResult,\n PalbaseOverviewResult,\n PalbaseEventNamesResult,\n PalbaseUserDetailResult,\n PalbaseCreateLinkParams,\n PalbaseUpdateLinkParams,\n PalbaseLink,\n PalbaseLinkDetails,\n PalbaseLinkAnalytics,\n PalbaseQrCodeOptions,\n PalbaseMatchParams,\n PalbaseInitialLink,\n PalbaseListLinksOptions,\n PalbaseListLinksResult,\n} from \"./clients.js\";\nexport { defineSchema } from \"./db/schema.js\";\n// The declaration as DATA — what the deploy reads to build the database. The\n// bundler calls this; a project never has to.\nexport { toSchemaJSON } from \"./db/schema-json.js\";\nexport type { SchemaJSON, TableJSON, ColumnJSON, PolicyJSON } from \"./db/schema-json.js\";\nexport type { SchemaDef, TableDef, TableInput, ColumnMap, SchemaInput } from \"./db/schema.js\";\nexport { policy, PolicyBuilder } from \"./db/policy.js\";\nexport type { PolicyDef, PolicyCommand, PolicyMode } from \"./db/policy.js\";\n// The realtime twin of `policy`: which channels exist and who may join them.\n// Undeclared channels are denied by the server, so this declaration is the\n// whole surface — the runtime reads it back off globalThis at boot.\nexport { defineChannels, ownerOnly, publicChannel } from \"./channels.js\";\nexport type { ChannelsDef, ChannelEntry, ChannelsInput, ChannelGrant, ChannelAuthorizeCtx } from \"./channels.js\";\nexport { PALBASE_EXTENSIONS, EXTENSION_DEPENDENCIES, isPalbaseExtension } from \"./db/extensions.js\";\nexport type { PalbaseExtension } from \"./db/extensions.js\";\nexport { uuid, text, integer, bigint, numeric, boolean, timestamp, jsonb, enumType, vector } from \"./db/columns.js\";\nexport type { ColumnBuilder, ColumnDef, ColumnType, OnDeleteAction } from \"./db/columns.js\";\nexport { raw } from \"./db/raw.js\";\nexport type { RawConstraintDef } from \"./db/raw.js\";\nexport { openai } from \"./db/embedding.js\";\nexport type { EmbeddingModelRef } from \"./db/embedding.js\";\nexport { makeTypedDB } from \"./db/typed-db.js\";\nexport type {\n TypedDB,\n TypedTx,\n TypedTable,\n InsertShape,\n RowShape,\n EnvTypedDatabase,\n EnvServiceDatabase,\n EnvTypedTable,\n EnvTables,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\n// Transaction plans: the `tx.tables.*` operation surface, its handles, and the\n// expressions a plan may write. `Database.transaction()` is on `Database`.\nexport { inc, dec, now, TxRefError, TxPlanError } from \"./db/tx-plan.js\";\nexport type {\n Ref,\n TxRow,\n TxRows,\n TxTable,\n TxPlanHandle,\n Materialized,\n TxNow,\n TxColumnExpr,\n TxInsertValue,\n TxSetValue,\n TxInsertShape,\n TxSetShape,\n TxWhere,\n TxSelectOptions,\n TxPlanBody,\n TxPlanResponse,\n TxPlanOpResult,\n TxPlanRejection,\n TxWireOp,\n TxWireRef,\n TxWireExpr,\n TxWireGuard,\n TxWireValue,\n} from \"./db/tx-plan.js\";\nexport type { Tables, TableTypes } from \"./db/env.js\";\nexport { makeEnvDts } from \"./db/env-gen.js\";\n// `config/` IS GONE, and so is the purchases family. Both were author-facing\n// surfaces with nothing behind them.\n//\n// The five config declarations nobody applied — storage, flags, notifications,\n// egress, auth — stopped being applied when the server-side declaration applier\n// was retired (v2 S-005, \"settings have one door, and a second one is how the\n// two disagree\"); `contract_lock_test.go` keeps it retired, and its own comment\n// records that the applier produced that silent failure FIVE times. The two that\n// still worked travelled by CLI courier: `config/secrets.ts` gated the push and\n// `config/test-users.ts` was PUT at the stack. Both jobs are now done where the\n// setting lives — `palbase secret set`, `palbase test-user templates set` — and\n// what a controller may SPELL comes back as a type instead of a declaration.\n//\n// `purchases` never had a v2 backend at all: v2 contains no palstore, which\n// `clients/index.ts` recorded on 2026-08-15 while deliberately leaving the tree\n// in place. It is taken now.\n//\n// The rule that replaced all of it: `db/schema.ts` and behaviour-carrying code\n// live in the repo; everything else is CONFIGURATION and is set through the CLI\n// (later MCP) against the stack. Codegen exists so that code can be written\n// against it — a generated type is not a declaration, and it produces no file an\n// author edits.\nexport type { PalbaseSecretName, PalbaseFlagKey, PalbaseBucketName } from \"./stack.js\";\nexport { makeStackDts } from \"./stack-gen.js\";\nexport type { StackNames } from \"./stack-gen.js\";\n// Class-controller decorator model (replaces defineController/defineHandler/route).\n// `getRegisteredControllers` is what makes exporting a controller OPTIONAL:\n// importing the file registers it. `Controller` stays exported for authoring.\nexport { Controller, getRegisteredControllers, __resetRegisteredControllers } from \"./decorators/controller.js\";\n// The APPLICATION-level ring of the auth cascade (route → controller →\n// application → true). Declared once at module scope instead of repeating the\n// same `auth` on every @Controller — the repetition is what gets forgotten.\nexport { defineDefaultAuth, __resetDefaultAuth, assertZeroArgConstructor, resolveEffectiveAuth } from \"./decorators/controller.js\";\nexport type { ControllerOptions } from \"./decorators/controller.js\";\nexport { Get, Post, Put, Patch, Delete, Query } from \"./decorators/methods.js\";\nexport { Deny, getHookConfig, Hook } from \"./decorators/hook.js\";\nexport type { HookFn, ResolvedHookClass } from \"./decorators/hook.js\";\nexport { Upload } from \"./decorators/upload.js\";\nexport type { UploadConfig } from \"./decorators/upload.js\";\n// `UploadedObject` is exported from upload.js, where BOTH the `@UploadedObject()`\n// decorator value AND the `UploadedObject` type are declared. One module → one\n// export name carries both — authors write `@UploadedObject()` (value) and\n// `: UploadedObject` (type) with a single imported name.\nexport { UploadedObject } from \"./decorators/upload.js\";\n// `@Sse` + its two parameter companions. `SseWriter` is the writer `@SseOut()`\n// injects; `SseConfig` is the route marker's type. The pipeline keys off the\n// config's PRESENCE, not the HTTP verb — see decorators/sse.ts.\nexport { Sse, SseOut, Signal } from \"./decorators/sse.js\";\nexport type { SseConfig, SseWriter } from \"./decorators/sse.js\";\nexport {\n Body,\n QueryParams,\n Headers,\n Param,\n User,\n OptionalUser,\n Client,\n RequestId,\n TraceId,\n Req,\n} from \"./decorators/params.js\";\nexport type { RouteOptions, HttpMethodUpper, ThrowDescriptor, RouteMeta, ParamMeta, ParamKind } from \"./decorators/registry.js\";\n// recordThrows is the stager-injected carrier for inferred throw descriptors\n// (the recordReturn twin) — public so the injected IIFE in a deployed bundle\n// can call it via `require(\"@palbase/backend\").recordThrows(...)`.\nexport { recordThrows } from \"./decorators/registry.js\";\n// getRoutes reads a controller's RouteMeta[] straight from the registry — the\n// isolate runtime enumerates routes with it instead of the worker.js raw-Symbol\n// fallback (the ROUTES symbol stays, both fallbacks keep reading it).\nexport { getRoutes } from \"./decorators/registry.js\";\nexport { defineMiddleware } from \"./middleware.js\";\nexport type { MiddlewareContext, MiddlewareHandler } from \"./middleware.js\";\n// The authenticated-user TYPE is exported as `UserT` (not `User`) because the\n// value name `User` is the @User() parameter decorator (exported above). A\n// controller annotates `@User() user: UserT` — decorator for the value\n// position, `UserT` for the type. (NestJS-style: same name as the decorator\n// would collide in the value+type namespaces.)\nexport type { User as UserT, VerifiedDevice, HttpMethod, AuthConfig } from \"./types.js\";\nexport {\n HttpError,\n PalError,\n BadRequest,\n Unauthorized,\n Forbidden,\n NotFound,\n Conflict,\n TooManyRequests,\n // 23505, typed. The engine throws it; a caller branches on `.constraint`\n // instead of matching the driver's message string.\n UniqueViolation,\n} from \"./errors.js\";\n// Typed project errors — defineError returns an HttpError subclass and\n// self-registers {code, status, dataSchema} in the project-global error\n// registry (the OpenAPI spec twins join `RouteMeta.throws` against it).\nexport { defineError, getErrorRegistry } from \"./error-registry.js\";\nexport type { RegisteredError, DefinedError, DefinedErrorWithData } from \"./error-registry.js\";\nexport type { JobMeta } from \"./job.js\";\nexport type { WebhookProvider, WebhookMeta, WebhookRequest } from \"./webhook.js\";\n// Webhooks and jobs are classes: `@Webhook`/`@On` for inbound webhooks,\n// `@Job` for cron. Both take their name from their file — see decorators/*.\nexport { getWebhookConfig, On, Webhook } from \"./decorators/webhook.js\";\nexport type { ResolvedWebhook, SignatureSpec, WebhookEventHandler, WebhookOptions } from \"./decorators/webhook.js\";\nexport { getJobConfig, Job } from \"./decorators/job.js\";\nexport type { JobOptions, ResolvedJob } from \"./decorators/job.js\";\n// `Resource` is GONE, not deprecated. Its boot registry was never wired: nothing\n// in the runtime ever called `__runResourceBoot` (measured 2026-08-29 —\n// `grep -rn \"ResourceBoot\"` across v2/runtime and palsvc returned nothing), so\n// `init(env)` never ran, the declared secrets never arrived, and a project that\n// wrote one got an object whose fields sat at their initializers with no error\n// anywhere. That is the same silence the `auth`/`storage`/`documents` hook\n// helpers were removed for, one surface down.\n//\n// Nothing replaces it, because the thing it was ceremony around is already the\n// stack's: the VAULT holds what a backend may read, the runtime lists those names\n// off it and mirrors them into `process.env` at boot, and `Secrets.get()` reads a\n// value with the rotation the deploy generation already carries. A field frozen\n// once inside `init(env)` could not have that. `static secrets` was therefore a\n// third list of names, behind the vault and behind `config/secrets.ts` — which is\n// itself down to a hint rather than a constraint (v2/runtime/src/server.ts:517).\n// `config/egress.ts` fences the calls a resource would have made and\n// `openai.embedding(...)` in the schema puts the one vendor client the platform\n// actually runs where the platform runs it. `resources/` stays exactly what the\n// bundler already treats it as — a directory of plain modules a controller\n// imports.\n// Types only. A hook is declared with @Hook/@On in hooks/*.ts.\n//\n// The `auth`/`storage`/`documents` helpers that used to live here are gone, not\n// deprecated: they returned a record nothing in the runtime or the bundler ever\n// read, so a project that called one got a handler that never ran and no error\n// anywhere. api-surface.mjs asks for a deprecation bridge because a major locks\n// every tenant's deploy — a real cost, and the reason this shipped as a bridge\n// in 20.0.0. There are no production tenants to lock yet (owner's call,\n// 2026-08-22), so the bridge is spending a release to soften a break nobody can\n// feel, and the honest surface is the one with no dead names in it.\nexport type {\n HookMeta,\n AuthHookEvent,\n DocumentHookEvent,\n FileUploadedEvent,\n FileDeletedEvent,\n} from \"./hooks.js\";\nexport { z } from \"zod\";\n","/**\n * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, controller methods import PascalCase service singletons directly:\n *\n * import { Controller, Post, Body, Database } from \"@palbase/backend\";\n *\n * \\@Controller(\"/todos\")\n * export default class TodosController {\n * \\@Post(\"\") create(\\@Body(CreateTodoBody) body: CreateTodoBody): unknown {\n * return Database.insert(\"todos\", { title: body.title });\n * }\n * }\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport type { PalbaseFlagKey } from \"./stack.js\";\nimport type { Buckets, BucketTypes } from \"./db/env.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n DBOps,\n CacheClient,\n Logger,\n PalbaseDocsClient,\n SecretsService,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseSetOverrideResult,\n PalbaseRealtimeClient,\n} from \"./clients.js\";\nimport type { PalbaseResult } from \"./endpoint.js\";\nimport type {\n EnvTypedDatabase,\n EnvServiceDatabase,\n EnvTables,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\nimport type { Materialized } from \"./db/tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./db/tx-plan.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but\n * cannot hold a subscription socket — `subscribe()` lives on the client SDK).\n *\n * EXCLUDED on purpose: Functions, Links, Analytics, Auth. They are not\n * exposed as backend handler singletons (auth lives on the client SDK; the rest\n * are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Secrets: SecretsService;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n Realtime: PalbaseRealtimeClient;\n}\n\n/**\n * The per-request ALS box.\n *\n * `runtime` is the service bundle. `userId` is the request's authenticated user\n * id, written by the runtime immediately after it assembles the request object\n * (worker.js: `requestALS.getStore().userId = pbReq.user?.id || null`) and\n * `null` on an anonymous request. It was already being written there for the\n * Flags client's auto-bind; declaring it here makes the existing contract typed\n * instead of implicit, which is what lets `currentSubjectId()` read a\n * server-owned identity rather than trusting anything the caller sent.\n */\nexport interface RequestStore {\n runtime: RuntimeServices;\n userId?: string | null;\n /** This request's id (`req_…`), written by the runtime. Used as the spend\n * idempotency scope when the caller supplied no `Idempotency-Key`. */\n requestId?: string;\n /** The caller's `Idempotency-Key` header, or `null` when absent. What makes a\n * client's retry replay its first result instead of charging twice. */\n idempotencyKey?: string | null;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\nexport const __requestALS = new AsyncLocalStorage<RequestStore>();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return scoped.runtime;\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n// ─── lifecycle: where a long-lived resource lives (FR-013) ─────────────────\n//\n// `Resource` was removed in 23.0.0 and nothing replaced the LIFECYCLE half of\n// it. What that left behind is measurable: a connection pool (the driver in\n// `docs/resources.md`'s own example was Neo4j) had no documented place to be\n// opened and NO WAY AT ALL to be closed, so every deploy left the pool it\n// opened behind. These two hooks are that half — and only that half. The\n// secret-distribution half does not come back: a handler reads `Secrets.get`,\n// and a start hook, which runs before any request scope exists, reads the\n// `process.env` the runtime mirrors the vault into at boot.\n\n/** A lifecycle hook. Sync or async; the runtime awaits what it returns. */\nexport type LifecycleHook = () => void | Promise<void>;\n\n/** Runs one release's shutdown hooks. Handed back by {@link __runStartHooks}\n * and called by the engine's `app.shutdown()`. Idempotent. */\nexport type ShutdownRunner = () => Promise<void>;\n\ninterface DeclaredHook {\n name: string;\n run: LifecycleHook;\n}\n\ninterface DeclaredLifecycle {\n start: DeclaredHook[];\n shutdown: DeclaredHook[];\n}\n\n/**\n * What has been DECLARED and not yet claimed by an app.\n *\n * On globalThis under a well-known Symbol for the reason the controller\n * registry is (`decorators/controller.ts`): a deployed bundle inlines its own\n * copy of this package, and the engine that has to RUN these hooks holds the\n * other copy. Two module-local arrays would mean the engine reads the empty one\n * and every declared hook is silently never run — which is exactly how\n * `Resource`'s `init(env)` died.\n */\nconst LIFECYCLE: unique symbol = Symbol.for(\"palbase.backend.lifecycleHooks\") as never;\n\nfunction declaredLifecycle(): DeclaredLifecycle {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n return (g[LIFECYCLE] ??= { start: [], shutdown: [] });\n}\n\n/**\n * Run `hook` ONCE while the application comes up, before it serves anything.\n *\n * Call it at MODULE SCOPE in a file the application imports — the same rule\n * `defineDefaultAuth` and `@Controller` follow, and for the same reason: the\n * declaration is claimed when the app boots, which is after module loading and\n * before the first request. `name` is not decoration: a hook that throws is\n * reported by that name and the boot is REFUSED, so it is what tells an\n * operator which resource did not come up.\n *\n * There is no request scope yet, so the `Database`/`Secrets`/… singletons are\n * NOT available inside a start hook. A secret is read from `process.env` here\n * (the runtime mirrors the vault into it at boot).\n *\n * @example\n * // resources/graph.ts\n * import neo4j from \"neo4j-driver\";\n * import { onStart, onShutdown } from \"@palbase/backend\";\n *\n * export let graph: Driver;\n * onStart(\"graph\", () => {\n * graph = neo4j.driver(process.env.NEO4J_URL!, neo4j.auth.basic(\"neo4j\", process.env.NEO4J_PASSWORD!));\n * });\n * onShutdown(\"graph\", () => graph.close());\n */\nexport function onStart(name: string, hook: LifecycleHook): void {\n declaredLifecycle().start.push({ name, run: hook });\n}\n\n/**\n * Run `hook` while the application shuts down — the place a pool opened in\n * {@link onStart} is closed.\n *\n * Shutdown is BEST-EFFORT by design: a hook that throws is reported by name and\n * the rest still run. A drain that abandoned the remaining hooks on the first\n * failure would leak exactly what this exists to release, and the process is\n * leaving anyway.\n *\n * Hooks run in REVERSE declaration order, so a resource is released before what\n * it was built on.\n */\nexport function onShutdown(name: string, hook: LifecycleHook): void {\n declaredLifecycle().shutdown.push({ name, run: hook });\n}\n\nfunction reason(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Best-effort drain: every hook runs, a failure is reported, none is silent. */\nasync function drain(hooks: DeclaredHook[]): Promise<void> {\n for (const h of [...hooks].reverse()) {\n try {\n await h.run();\n } catch (err) {\n console.error(`[palbase] shutdown hook \"${h.name}\" failed: ${reason(err)}`, err);\n }\n }\n}\n\n/**\n * CLAIM what has been declared, run the start hooks, and hand back the runner\n * for this release's shutdown hooks. Called by the engine's `createApp`; the\n * `App.shutdown()` it builds calls what comes back. NOT part of the public\n * author-facing API.\n *\n * IT CLAIMS RATHER THAN READS, which is what makes it correct in this runtime:\n * a candidate release is loaded BESIDE the live one in one process\n * (`v2/runtime/src/registry-scope.ts`), and both bundles append to the one\n * shared slot above. If each app read the whole list, the live app's shutdown\n * would close the candidate's pool and the candidate's would close the live\n * app's. Taking the declarations leaves each app holding exactly its own.\n *\n * A start hook that throws REFUSES THE BOOT — with the hook's name in the\n * message — after releasing whatever the earlier hooks already opened. Serving\n * from a half-initialised app is the silence this whole surface replaces, and a\n * boot that dies holding an open pool is the leak it replaces.\n */\nexport async function __runStartHooks(): Promise<ShutdownRunner> {\n const slot = declaredLifecycle();\n const start = slot.start.splice(0);\n const shutdown = slot.shutdown.splice(0);\n\n for (const h of start) {\n try {\n await h.run();\n } catch (err) {\n await drain(shutdown);\n throw new Error(`[palbase] start hook \"${h.name}\" failed: ${reason(err)}`, { cause: err });\n }\n }\n\n let drained = false;\n return async () => {\n // SIGTERM racing a redeploy asks twice; a pool is closed once.\n if (drained) return;\n drained = true;\n await drain(shutdown);\n };\n}\n\n/** Drop every declaration. For tests, which declare repeatedly in one process.\n * NOT part of the public author-facing API. */\nexport function __resetLifecycleHooks(): void {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n delete g[LIFECYCLE];\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/**\n * Build the `.tables` accessor for the top-level `Database`. Each\n * `tables.<name>` access returns a small object that forwards the five CRUD ops\n * to the underlying client using `name` as the string table identifier. The\n * shapes are typed against the generated `palbase-env.d.ts` (`EnvTables`); at\n * runtime they are plain string-keyed calls, so no schema value is needed here.\n *\n * Returns `EnvTables` — TS cannot infer the mapped type through the Proxy, so\n * a single structural narrowing names the surface (the proxy returns a\n * correctly-shaped accessor for whatever string member is read).\n */\n/** T018 (C-8): similar/recommend'in string-keyed yüzü. DBOps'a (endpoint.ts)\n * BİLEREK eklenmedi — search-param imza üçlüsü (engine/db + typed-db +\n * endpoint) büyümesin: proxy dispatch runtime'da engine ops'una zaten ulaşır,\n * derleme güvenliğini typed yüzey (EnvTypedTable) verir. */\ninterface RecoOps {\n similar(table: string, id: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n recommend(table: string, params: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\nfunction makeTablesAccessor(ops: () => DBOps & RecoOps): EnvTables {\n const tablesProxy = new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n const name = prop;\n return {\n insert: (data: Record<string, unknown>) => ops().insert(name, data),\n update: (id: string, data: Record<string, unknown>) => ops().update(name, id, data),\n delete: (id: string) => ops().delete(name, id),\n findById: (id: string) => ops().findById(name, id),\n findMany: (query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n ops().findMany(name, query, opts),\n upsert: (data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n ops().upsert(name, data, opts),\n search: (params?: Record<string, unknown>) => ops().search(name, params),\n similar: (id: string, params?: Record<string, unknown>) => ops().similar(name, id, params),\n recommend: (params: Record<string, unknown>) => ops().recommend(name, params),\n facets: (params: { facets: string[] } & Record<string, unknown>) => ops().facets(name, params),\n supersede: (id: string, row: Record<string, unknown>) => ops().supersede(name, id, row),\n };\n },\n },\n );\n return tablesProxy as EnvTables;\n}\n\n/** The raw string-keyed `DBClient` for the current request scope. */\nconst rawDatabase: DBClient = makeServiceProxy(\"Database\");\n\n/**\n * Wrap a raw `DBClient` into the typed `{ ...ops, tables, transaction }`\n * surface. The five string ops forward straight through; `tables` is the\n * env-typed accessor; `transaction` yields typed tables. Reused for both the\n * default (RLS-enforced) `Database` and the `asService()` sibling — each is\n * fed its own raw client (the default proxy vs `rawDatabase.asService()`).\n *\n * The `satisfies` pins the op surface so a missing/renamed op is a compile\n * error; the assembled object carries `tables`/`transaction` alongside.\n */\nfunction makeTypedSurface(raw: Omit<DBClient, \"asService\">): EnvServiceDatabase {\n // Proxy dispatch her üyeyi taşır; RecoOps tipi DBClient'a eklenmediğinden\n // (yukarıdaki karar) similar/recommend erişimi bu daraltmadan geçer.\n const reco = raw as Omit<DBClient, \"asService\"> & RecoOps;\n const ops = {\n query: (sql: string, params?: unknown[]) => raw.query(sql, params),\n insert: (table: string, data: Record<string, unknown>) => raw.insert(table, data),\n update: (table: string, id: string, data: Record<string, unknown>) =>\n raw.update(table, id, data),\n delete: (table: string, id: string) => raw.delete(table, id),\n findById: (table: string, id: string) => raw.findById(table, id),\n findMany: (table: string, query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n raw.findMany(table, query, opts),\n upsert: (table: string, data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n raw.upsert(table, data, opts),\n updateMany: (table: string, where: Record<string, unknown>, set: Record<string, unknown>) =>\n raw.updateMany(table, where, set),\n deleteMany: (table: string, where: Record<string, unknown>) => raw.deleteMany(table, where),\n count: (table: string, where?: Record<string, unknown>) => raw.count(table, where),\n search: (table: string, params?: Record<string, unknown>) => raw.search(table, params),\n similar: (table: string, id: string, params?: Record<string, unknown>) =>\n reco.similar(table, id, params),\n recommend: (table: string, params: Record<string, unknown>) => reco.recommend(table, params),\n facets: (table: string, params: { facets: string[] } & Record<string, unknown>) => reco.facets(table, params),\n supersede: (table: string, id: string, row: Record<string, unknown>) =>\n raw.supersede(table, id, row),\n } satisfies DBOps & RecoOps;\n return Object.assign(ops, {\n // Both surfaces get it: a savepoint on the service transaction is as useful\n // as one on the request's, and each is bound to its own connection.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>) => raw.attempt(fn),\n tables: makeTablesAccessor(() => reco),\n transaction<T>(\n fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>> {\n // A FRESH builder per call: it holds this transaction's ops and its error\n // slot table, and the runtime serves concurrent requests on one event loop.\n // A shared builder would splice one request's writes into another's plan.\n const builder = new TxPlanBuilder();\n return runTxPlan(raw, makeTxTablesAccessor(builder), builder, fn) as Promise<\n Materialized<T>\n >;\n },\n });\n}\n\n/**\n * The transaction twin of {@link makeTablesAccessor}: `tables.<name>` yields the\n * table's PLAN operations, recorded into `builder` instead of sent one by one.\n *\n * Same Proxy shape and same reason for the single narrowing — TS cannot infer a\n * mapped type through a Proxy, so the cast names what the trap returns.\n */\nfunction makeTxTablesAccessor(builder: TxPlanBuilder): TxTables {\n const tablesProxy = new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return builder.table(prop);\n },\n },\n );\n return tablesProxy as TxTables;\n}\n\n/**\n * The project's own Postgres (pgx, schema `env_<envId>`).\n *\n * Typed by default: `Database.tables.<name>.insert({...})` is typed against\n * the project's generated `palbase-env.d.ts` with NO import and NO generic.\n * The raw string ops (`query`/`insert`/`update`/`delete`/`findById`/`findMany`)\n * are also available for dynamic table names and read-only SQL.\n *\n * RLS is enforced by default (the runtime runs each op as `authenticated` with\n * the verified user's claims). To bypass RLS, call `Database.asService()` —\n * explicit and greppable — which runs as the `service_role` (BYPASSRLS).\n *\n * @example\n * import { Database } from \"@palbase/backend\";\n *\n * const todo = await Database.tables.todos.insert({ title: req.input.title });\n * todo.id; // string ✓\n * const rows = await Database.query(\"SELECT id FROM todos WHERE done = $1\", [false]);\n * const all = await Database.asService().tables.todos.findMany({}); // RLS bypass\n */\nexport const Database: EnvTypedDatabase = Object.assign(makeTypedSurface(rawDatabase), {\n /**\n * Lazily resolve the runtime's service-role sibling on each call. We do NOT\n * cache it: `rawDatabase.asService()` reads the CURRENT request scope through\n * the runtime proxy, and the per-request runtime injects a service client\n * bound to that request's identity headers — caching would leak one request's\n * sibling into another concurrent request.\n */\n asService(): EnvServiceDatabase {\n return makeTypedSurface(rawDatabase.asService());\n },\n});\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/**\n * `buckets.<name>` — the storage twin of `Database.tables.<name>`, and the same\n * mechanism: `config/storage.ts` generates a `Buckets` augmentation into\n * `palbase-env.d.ts`, so a bucket name is a property with no import and no\n * generic, and a typo is a compile error.\n *\n * The intermediate `.buckets` is there for the reason `.tables` is: bucket\n * names must not share a namespace with the client's own methods, or the day\n * somebody declares a bucket called `bucket` the surface breaks.\n */\nexport type EnvBuckets = {\n [K in keyof Buckets]: TypedBucketClient<Buckets[K] extends BucketTypes ? Buckets[K] : BucketTypes>;\n};\n\n/** One bucket, with its declared variant names in the type. */\nexport interface TypedBucketClient<B extends BucketTypes> extends Omit<PalbaseBucketClient, \"getPublicUrl\"> {\n /** The public URL for the object, or for one of THIS bucket's declared\n * renditions. A name the bucket does not declare is a compile error. */\n getPublicUrl(path: string, options?: { variant?: B[\"variants\"] }): string;\n}\n\nfunction makeBucketsAccessor(storage: () => PalbaseStorageClient): EnvBuckets {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return storage().bucket(prop);\n },\n },\n ) as EnvBuckets;\n}\n\nconst rawStorage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/**\n * Object storage: buckets, objects, renditions and signed URLs.\n *\n * `Storage.buckets.posts.upload(...)` is the typed path. `Storage.bucket(name)`\n * remains for a name computed at runtime — rare, and it gives up the typing,\n * which is the honest trade rather than a second blessed way to do it.\n */\nexport const Storage: PalbaseStorageClient & { buckets: EnvBuckets } = Object.assign(\n {\n // FORWARDED explicitly, not assigned onto the service proxy.\n //\n // `Object.assign(rawStorage, {buckets})` writes onto the proxy's TARGET, and\n // the proxy's only trap is `get`, which forwards every read to the module\n // client — so the property landed somewhere nothing reads and\n // `Storage.buckets.docs` was `undefined` in a deployed handler. It\n // typechecked, every test passed, and the live call answered\n // \"TypeError: undefined is not an object\". `Database` never had the bug\n // because it builds a plain surface the same way this now does.\n bucket: (name: string) => rawStorage.bucket(name),\n },\n { buckets: makeBucketsAccessor(() => rawStorage) },\n);\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n\n/**\n * This tenant's secrets — API keys, provider credentials, signing material the\n * BACKEND owns.\n *\n * `await Secrets.get(\"STRIPE_KEY\")` in a handler. There is no `.env` to read\n * and no file to mount: a secret is written through the vault's authenticated\n * API (or the CLI/MCP that calls it), and this is how the deployed code reads\n * it back. A name this tenant has not set answers null — as does every name\n * the STACK holds, because no route returns a platform secret's value at all.\n */\nexport const Secrets: SecretsService = makeServiceProxy(\"Secrets\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n\n/**\n * The raw runtime Flags client for the current request scope. Carries the\n * default-surface reads + `setOverride` AND the runtime's `asService()` sibling\n * (the br-pod's `buildFlagsClient` returns both). The default `Flags` singleton\n * below forwards reads + `setOverride` through here; `Flags.asService()`\n * forwards to this client's own `asService()`.\n */\nconst rawFlags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Feature flags.\n *\n * Mirrors the `Database` / `Database.asService()` model. The default surface is\n * RLS-equivalent for flags: reads resolve against the CURRENT request user and\n * `Flags.setOverride(key, value)` writes an override for that same signed-in\n * user (no userId argument, no admin power). Cross-user admin writes\n * (`setOverrideForUser`, …) live behind `Flags.asService()` — explicit and\n * greppable, just like `Database.asService()`.\n *\n * @example\n * import { Flags } from \"@palbase/backend\";\n *\n * if (await Flags.isEnabled(\"new_checkout\")) { ... } // current user\n * await Flags.setOverride(\"new_checkout\", true); // current user\n * await Flags.asService().setOverrideForUser(\"u_9\", \"x\", true); // cross-user\n */\nexport const Flags: PalbaseFlagsClient = Object.assign(\n {\n isEnabled(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<boolean>> {\n return rawFlags.isEnabled(flagName, context);\n },\n getVariant(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagVariant>> {\n return rawFlags.getVariant(flagName, context);\n },\n getAll(context?: PalbaseFlagContext): Promise<PalbaseResult<PalbaseFlag[]>> {\n return rawFlags.getAll(context);\n },\n /**\n * Resolve a flag's value, with an optional fallback.\n *\n * FORWARDED as of 2026-08-15. This surface is written out by hand, method\n * by method, and `get` was missing from it — so the client implemented it,\n * thirty assertions covered it, and `Flags.get(\"x\")` was `undefined` in a\n * deployed handler. Exactly the shape of the `Storage.buckets` defect found\n * the same day: a hand-maintained forwarding list is a list somebody has to\n * remember to update.\n */\n get(\n flagName: PalbaseFlagKey,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n return rawFlags.get(flagName, defaultOrContext, maybeContext);\n },\n setOverride(\n key: PalbaseFlagKey,\n value: PalbaseFlagValue,\n ): Promise<PalbaseResult<PalbaseSetOverrideResult>> {\n return rawFlags.setOverride(key, value);\n },\n },\n {\n /**\n * Lazily resolve the runtime's cross-user sibling on each call. We do NOT\n * cache it: `rawFlags.asService()` reads the CURRENT request scope through\n * the runtime proxy, so caching would leak one request's sibling into\n * another concurrent request. Mirrors `Database.asService()`.\n */\n asService(): PalbaseFlagsServiceClient {\n return rawFlags.asService();\n },\n },\n);\n\n/**\n * The Realtime broadcast singleton for the current request scope. Backend-side\n * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —\n * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:\n * `broadcast` resolves once accepted (or with an `error`), never blocking the\n * handler on subscribers.\n *\n * @example\n * import { Realtime } from \"@palbase/backend\";\n *\n * await Realtime.broadcast(\"room:42\", \"message\", { text, from: user.id });\n */\nexport const Realtime: PalbaseRealtimeClient = makeServiceProxy(\"Realtime\");\n","/**\n * tx-plan.ts — `Database.transaction()` as a PLAN, not a pinned session.\n *\n * A transaction used to be a conversation: BEGIN, then one network round trip\n * per operation, then COMMIT. Each of those round trips cost ~4 ms and, because\n * the pooler runs in transaction mode, an open transaction pinned a Postgres\n * backend for the whole conversation. A 121-operation statement upload pinned\n * one backend for ~490 ms.\n *\n * So the callback no longer TALKS to the database. It DESCRIBES what should\n * happen; the description is serialised and sent once; the broker runs the whole\n * thing inside one transaction and answers once. Committing on return and\n * rolling back on throw is unchanged — that is the only property tenant code\n * actually asked for.\n *\n * The consequences, stated plainly, because they are the whole design:\n *\n * - The callback is SYNCHRONOUS. There is nothing to await: no statement has\n * run yet when it returns. `async` on the callback and `await` inside it are\n * both compile errors (see {@link TxPlan} and {@link NotAwaitable}).\n * - `insert()` does not hand back a row, it hands back {@link TxRows}. Reading\n * a field requires `.expectOne(err)` first, which makes \"what if the row\n * isn't there\" a question you cannot route around: it is the argument.\n * - A field read from a row is a {@link Ref} — a PROMISE OF A VALUE THE SERVER\n * WILL PRODUCE, not the value. It can be written into a later operation and\n * it can be returned from the callback (it is substituted for the real value\n * before `transaction()` resolves). It cannot be branched on. See the\n * \"Truthiness\" note below — this is the sharp edge of the whole design.\n * - Control flow that needs a real value must move OUT of the callback: read\n * before the transaction, or express the condition as a guard\n * (`updateWhere({ id, accepted_at: null }, …).expectOne(new Conflict(…))`)\n * which the server evaluates and which rolls the whole plan back.\n *\n * # Truthiness — the hole this file CANNOT close\n *\n * JavaScript does not let a Proxy trap truthiness. `if (ref)` takes the true\n * branch, always, for every Ref, and no `get` handler ever runs. `tsc` is silent\n * because a Ref is a perfectly good object. So:\n *\n * const pot = tx.tables.pots.select({ id }, { limit: 1 }).expectOne(e);\n * if (!pot.balance) { … } // ← ALWAYS false. Silently wrong data.\n *\n * What this file does close: coercion (`Symbol.toPrimitive`/`valueOf`/\n * `toString`), awaiting (`then` is a callable member with a non-thenable\n * signature, which is a *compile* error), serialisation (`toJSON`), and nesting\n * a Ref inside a literal value where the server would store it as data. What it\n * cannot close is a bare truthiness test. The real defence is the build-time\n * static analysis (`tx_analysis.js`, phase P4); until that ships, this hole is\n * open and this comment is the only warning.\n *\n * # Wire contract\n *\n * The JSON this file emits is consumed by\n * the plan executor in `engine/db.ts`. That executor rejects\n * unknown fields at every level, so an op carries EXACTLY the fields its kind\n * takes. Everything here that looks like a needless restriction is one of the\n * server's rules made visible early:\n *\n * - `$ref` only points BACKWARDS, and only at an op statically known to yield\n * at most one row (insert, or a `one`/`atMost 1` guard, or `select limit 1`).\n * `.expectOne()` is what this file uses to satisfy that, always.\n * - `$expr` is a closed set: `inc`/`dec` (update only — they read the column's\n * current value) and `now()`.\n * - `update`/`delete` require a `where`; `insert` refuses one.\n * - `insertMany` rows must all set the same columns.\n * - ≤1000 ops, ≤5000 rows per insertMany, ≤8 MiB of JSON.\n *\n * Column keys are emitted SORTED, so the same callback always produces byte-\n * identical JSON. That is what lets the Go decoder be locked to golden files\n * this SDK emits (`testdata/tx_plan_golden/`).\n */\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * A plan handle was used as if it were a value: awaited, coerced to a string or\n * number, serialised, or nested inside another value.\n *\n * Thrown while the callback is still BUILDING the plan, so nothing has been sent\n * and nothing has been written.\n */\nexport class TxRefError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxRefError\";\n }\n}\n\n/**\n * The plan the callback described cannot be sent: it breaks a rule the server\n * would reject, and rejecting it here names the line that wrote it instead of\n * returning a 400 about an op index.\n */\nexport class TxPlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxPlanError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Wire types — mirror the plan executor in `engine/db.ts` exactly.\n// ---------------------------------------------------------------------------\n\n/** A backwards reference to an earlier op's single-row result. */\nexport interface TxWireRef {\n $ref: { op: number; field: string };\n}\n\n/** A call from the server's closed function set. */\nexport interface TxWireExpr {\n $expr: { fn: \"inc\" | \"dec\"; by: number } | { fn: \"now\" };\n}\n\n/** One value in a `values`/`set`/`where` map: a literal, a `$ref` or a `$expr`. */\nexport type TxWireValue = TxWireRef | TxWireExpr | unknown;\n\n/** The tenant's declared expectation about an op's row count. `slot` indexes the\n * client-side error table — the error OBJECT never travels. */\nexport interface TxWireGuard {\n kind: \"one\" | \"none\" | \"atLeast\" | \"atMost\";\n n: number;\n slot: number;\n}\n\n/** One operation in the wire plan. Fields are omitted, never null: the decoder\n * rejects a field that does not belong to the op's kind. */\nexport interface TxWireOp {\n /** upsert and insertMany: the columns Postgres matches on. */\n onConflict?: readonly string[];\n /** insertMany only: what a collision does. Absent means no ON CONFLICT clause\n * at all, which is what every insertMany did before this option existed. */\n action?: \"ignore\" | \"update\";\n op: \"insert\" | \"insertMany\" | \"upsert\" | \"update\" | \"delete\" | \"select\";\n table: string;\n values?: Record<string, TxWireValue>;\n rows?: Record<string, TxWireValue>[];\n set?: Record<string, TxWireValue>;\n where?: Record<string, TxWireValue>;\n limit?: number;\n lock?: \"update\";\n guard?: TxWireGuard;\n}\n\n/** The plan the engine executes on the request's own transaction. */\nexport interface TxPlanBody {\n ops: TxWireOp[];\n}\n\n/** One op's outcome, positionally matched to the plan's ops. */\nexport interface TxPlanOpResult {\n rows: Record<string, unknown>[];\n rows_affected: number;\n}\n\n/** One result per op, in plan order. */\nexport interface TxPlanResponse {\n results: TxPlanOpResult[];\n}\n\n/**\n * The fields the runtime must copy from the broker's error envelope onto the\n * rejection it throws out of {@link DBClient.txPlan}.\n *\n * `slot` is the whole point: on a guard failure the server answers with the\n * INDEX of the expectation that did not hold, never with an error message of its\n * own, and this SDK maps that index back to the `Error` the callback handed to\n * `.expectOne(…)`. Without `slot` a guard failure degrades to a generic 409.\n */\nexport interface TxPlanRejection {\n status?: number;\n /** `tx_plan_invalid` | `tx_guard_failed` | `tx_ref_unresolved` | a pg class. */\n error_code?: string;\n /** Present only for `tx_guard_failed`: the client-side error table index. */\n slot?: number;\n /** Present on a database error: which op failed. */\n op?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Handle types\n// ---------------------------------------------------------------------------\n\ndeclare const refBrand: unique symbol;\ndeclare const rowBrand: unique symbol;\ndeclare const rowsBrand: unique symbol;\n\n/**\n * Makes a handle a compile error to `await`.\n *\n * `then` is declared as a CALLABLE member whose signature is not `PromiseLike`,\n * which is precisely the shape TypeScript rejects: `await handle` is TS1320 and\n * `async () => handle` is TS1058. A non-callable `then` would not do it — the\n * compiler simply ignores those.\n */\nexport interface NotAwaitable {\n /** Not a promise. Nothing here has run yet; there is nothing to await. */\n then(doNotAwaitAPlanHandle: \"a transaction plan is built synchronously\"): never;\n}\n\n/**\n * A value the SERVER will produce, standing in for a column of a row this plan\n * writes or reads.\n *\n * Legal uses: write it into a later operation's `values`/`set`/`where`, or\n * return it from the callback (it is replaced by the real value before\n * `transaction()` resolves).\n *\n * Illegal, and caught: `await`, `String(ref)`, `` `${ref}` ``, `ref + 1`,\n * `JSON.stringify(ref)`, burying it inside a jsonb object.\n *\n * Illegal, and NOT caught: `if (ref)`. See the truthiness note at the top.\n */\nexport interface Ref<T> extends NotAwaitable {\n readonly [refBrand]: T;\n}\n\n/** The brand carried by a single-row handle, and the seam `Materialized` reads\n * to turn `return st` into the whole row. */\nexport interface TxRowHandle<Row> extends NotAwaitable {\n readonly [rowBrand]: Row;\n}\n\n/**\n * A row this plan is known to produce exactly one of. Every property is a\n * {@link Ref}; returning the handle itself yields the whole row.\n *\n * Only `.expectOne(err)` produces one — which is the design: a row you can read\n * fields from is a row whose absence you have already answered for.\n */\nexport type TxRow<Row> = { readonly [K in keyof Row]: Ref<Row[K]> } & TxRowHandle<Row>;\n\n/**\n * The result of one operation, before any expectation is declared about it.\n *\n * Deliberately not a row and not a list: an operation's row count is not known\n * until the server runs it, so the only thing that can be said about it here is\n * an EXPECTATION. Declaring one is also the only way to get a readable row.\n *\n * At most one expectation per operation — the wire carries one guard per op, and\n * a second call throws rather than silently dropping the first.\n */\nexport interface TxRows<Row> extends NotAwaitable {\n readonly [rowsBrand]: Row;\n /**\n * Require exactly one row, and read it. On any other count the server rolls\n * the whole transaction back and this `error` is thrown to the caller.\n *\n * This is the only way to reach a row's fields, and the only shape a `$ref`\n * may point at.\n */\n expectOne(error: Error): TxRow<Row>;\n /** Require zero rows (e.g. \"this membership must not already exist\"). */\n expectNone(error: Error): void;\n /** Require at least `n` rows. */\n expectAtLeast(n: number, error: Error): void;\n /** Require at most `n` rows. */\n expectAtMost(n: number, error: Error): void;\n}\n\n/** `now()` — the server's clock, usable wherever a value is. */\nexport interface TxNow extends NotAwaitable {\n readonly $expr: { fn: \"now\" };\n}\n\n/** `inc(n)` / `dec(n)` — read the column's CURRENT value and write it back\n * changed. Only meaningful in an update's `set`, which is where the types allow\n * it and where the server allows it. */\nexport interface TxColumnExpr extends NotAwaitable {\n readonly $expr: { fn: \"inc\" | \"dec\"; by: number };\n}\n\n/**\n * Resolve a callback's return type against what actually comes back: every\n * {@link Ref} becomes its value, every {@link TxRow} becomes its row, and\n * anything else keeps its shape.\n *\n * A {@link TxRows} resolves to an explanatory string type rather than a row\n * list: it has no single answer to give, and saying so in the type is louder\n * than a runtime throw.\n */\nexport type Materialized<T> = T extends Ref<infer U>\n ? U\n : T extends TxRowHandle<infer R>\n ? R\n : T extends TxRows<unknown>\n ? \"a TxRows cannot leave the transaction callback — read a row with .expectOne(err) first\"\n : T extends Date\n ? T\n : T extends object\n ? { [K in keyof T]: Materialized<T[K]> }\n : T;\n\n// ---------------------------------------------------------------------------\n// Author-facing value types\n// ---------------------------------------------------------------------------\n\n/** A value written by an INSERT: a literal, an earlier row's field, or `now()`.\n * `inc`/`dec` are absent on purpose — they read a current value, and an inserted\n * row has none. */\nexport type TxInsertValue<V> = V | Ref<V> | TxNow;\n\n/** A value written by an UPDATE's `set`: everything an insert takes, plus the\n * read-modify-write expressions. */\nexport type TxSetValue<V> = V | Ref<V> | TxNow | TxColumnExpr;\n\n/** An insert payload: the table's insert shape, with refs and `now()` allowed. */\nexport type TxInsertShape<Insert> = { [K in keyof Insert]: TxInsertValue<Insert[K]> };\n\n/** An update's `set`: any subset of the insert shape, with expressions allowed. */\nexport type TxSetShape<Insert> = { [K in keyof Insert]?: TxSetValue<Insert[K]> };\n\n/**\n * A filter. Every entry is an equality test and they are AND-ed; a `null`\n * becomes `IS NULL`, which is what makes `{ accepted_at: null }` a usable\n * \"not yet accepted\" guard rather than a clause that matches nothing.\n */\nexport type TxWhere<Row> = { [K in keyof Row]?: Row[K] | Ref<Row[K]> };\n\n/** Options for a plan `select`. */\nexport interface TxSelectOptions {\n /** Cap the rows read. */\n limit?: number;\n /** Take a real `FOR UPDATE` row lock for the rest of the transaction. */\n lock?: \"update\";\n}\n\n/** One table, as the plan sees it. */\nexport interface TxTable<Row, Insert> {\n /** Insert one row. Returns a handle — call `.expectOne(err)` to read fields. */\n insert(values: TxInsertShape<Insert>): TxRows<Row>;\n /**\n * Insert many rows in ONE statement. Every row must set the same columns\n * (a row that omits one would silently take the column's default).\n *\n * An empty list writes nothing and sends nothing.\n */\n /**\n * Insert many rows in ONE statement, optionally choosing what a collision does.\n *\n * Without `opts` this is a plain multi-row INSERT and a collision aborts the\n * transaction — the behaviour every call had before the option existed.\n *\n * `action: \"ignore\"` emits `ON CONFLICT DO NOTHING`, which is how \"insert the\n * ones that are new\" becomes one round-trip instead of one per row with a\n * 23505 caught around each. **The returned rows are the ones actually\n * INSERTED**: a row that collided is skipped, so it is absent from the result\n * — Postgres does not return what it did not write.\n *\n * `action: \"update\"` emits `ON CONFLICT DO UPDATE`, setting every non-conflict\n * column from the incoming row, and every row comes back.\n */\n insertMany(\n rows: readonly TxInsertShape<Insert>[],\n opts?: {\n onConflict: readonly Extract<keyof Row, string>[];\n action?: \"ignore\" | \"update\";\n },\n ): TxRows<Row>;\n /**\n * Insert the row, or update it when it collides on `onConflict` — inside the\n * plan's savepoint, with the same meaning `tables.<t>.upsert()` has outside it.\n *\n * It is an operation because the alternative is not writable here: a failed\n * insert aborts the whole transaction, so \"try, then fall back\" cannot be two\n * plan steps.\n */\n upsert(\n values: TxInsertShape<Insert>,\n options: { onConflict: readonly Extract<keyof Row, string>[] },\n ): TxRows<Row>;\n /**\n * Update every row matching `where`. The filter comes first because it is the\n * dangerous half: an update whose `where` you got wrong rewrites rows you\n * never looked at. The server refuses an update with no `where` at all.\n */\n updateWhere(where: TxWhere<Row>, set: TxSetShape<Insert>): TxRows<Row>;\n /** Delete every row matching `where`. The server refuses an unfiltered delete. */\n deleteWhere(where: TxWhere<Row>): TxRows<Row>;\n /** Read rows, optionally locking them for the rest of the transaction. */\n select(where?: TxWhere<Row>, options?: TxSelectOptions): TxRows<Row>;\n}\n\n/**\n * The handle a transaction callback receives.\n *\n * It carries tables and nothing else: no `query`, no `findById`, no `asService`.\n * A read whose value the plan does not write belongs OUTSIDE the transaction,\n * where it costs one round trip and can be branched on like an ordinary value.\n */\nexport interface TxPlanHandle<TTables> {\n tables: TTables;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — expressions\n// ---------------------------------------------------------------------------\n\n/** Internal marker read by the serialiser. */\nconst EXPR = Symbol.for(\"palbase.tx.expr\");\nconst REF = Symbol.for(\"palbase.tx.ref\");\nconst ROW = Symbol.for(\"palbase.tx.row\");\nconst ROWS = Symbol.for(\"palbase.tx.rows\");\n\ninterface RefDescriptor {\n op: number;\n field: string;\n}\n\n/** Property reads that must not silently produce a value on a plan handle.\n * `then` is the one that matters for correctness (it makes `await` a compile\n * error AND stops a handle from being adopted by a promise); the rest turn a\n * silent wrong answer — `\"[object Object]\"`, `NaN`, `{}` — into a thrown one. */\nconst TRAPPED_PROPS: readonly (string | symbol)[] = [\n \"then\",\n \"valueOf\",\n \"toString\",\n \"toJSON\",\n Symbol.toPrimitive,\n];\n\nfunction trap(prop: string | symbol, what: string, hint: string): never {\n const name = typeof prop === \"symbol\" ? prop.description ?? String(prop) : prop;\n throw new TxRefError(\n `${what} was used as a value (via \\`${name}\\`). Nothing in a transaction ` +\n `callback has run yet, so there is no value to read. ${hint}`,\n );\n}\n\n/** The server's `now()`. */\nexport function now(): TxNow {\n return makeExpr({ fn: \"now\" }) as TxNow;\n}\n\n/** Add `by` to the column's current value. Only valid in an update's `set`. */\nexport function inc(by: number): TxColumnExpr {\n assertFiniteNumber(by, \"inc\");\n return makeExpr({ fn: \"inc\", by }) as TxColumnExpr;\n}\n\n/** Subtract `by` from the column's current value. Only valid in an update's `set`. */\nexport function dec(by: number): TxColumnExpr {\n assertFiniteNumber(by, \"dec\");\n return makeExpr({ fn: \"dec\", by }) as TxColumnExpr;\n}\n\nfunction assertFiniteNumber(by: number, fn: string): void {\n if (typeof by !== \"number\" || !Number.isFinite(by)) {\n // JSON has no NaN/Infinity: they would serialise to `null` and the server\n // would reject the plan with an unhelpful decode error.\n throw new TxPlanError(`${fn}() needs a finite number, got ${String(by)}`);\n }\n}\n\nfunction makeExpr(expr: TxWireExpr[\"$expr\"]): unknown {\n return new Proxy(\n { [EXPR]: expr } as Record<string | symbol, unknown>,\n {\n get(target, prop) {\n if (prop === EXPR) return target[EXPR];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(prop, \"A plan expression\", \"Write it into an operation instead.\");\n }\n return undefined;\n },\n },\n );\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — refs and row handles\n// ---------------------------------------------------------------------------\n\nfunction makeRef(op: number, field: string): unknown {\n const target: Record<string | symbol, unknown> = { [REF]: { op, field } satisfies RefDescriptor };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === REF) return t[REF];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n `\\`${field}\\` of a row this transaction has not written yet`,\n \"Pass it to another operation in the same plan, or return it from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n return undefined;\n },\n });\n}\n\nfunction makeRowHandle(op: number): unknown {\n const target: Record<string | symbol, unknown> = { [ROW]: op };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === ROW) return t[ROW];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n \"A row this transaction has not written yet\",\n \"Read one of its columns to reference it, or return the row from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n if (typeof prop === \"symbol\") return undefined;\n return makeRef(op, prop);\n },\n });\n}\n\nfunction refDescriptor(v: unknown): RefDescriptor | null {\n if (typeof v !== \"object\" || v === null) return null;\n const d = (v as Record<symbol, unknown>)[REF];\n return isRefDescriptor(d) ? d : null;\n}\n\nfunction isRefDescriptor(d: unknown): d is RefDescriptor {\n return (\n typeof d === \"object\" &&\n d !== null &&\n typeof (d as RefDescriptor).op === \"number\" &&\n typeof (d as RefDescriptor).field === \"string\"\n );\n}\n\nfunction rowOpIndex(v: unknown): number | null {\n if (typeof v !== \"object\" || v === null) return null;\n const op = (v as Record<symbol, unknown>)[ROW];\n return typeof op === \"number\" ? op : null;\n}\n\nfunction exprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n if (typeof v !== \"object\" || v === null) return null;\n const e = (v as Record<symbol, unknown>)[EXPR];\n return typeof e === \"object\" && e !== null ? (e as TxWireExpr[\"$expr\"]) : null;\n}\n\nfunction isRowsHandle(v: unknown): boolean {\n return typeof v === \"object\" && v !== null && (v as Record<symbol, unknown>)[ROWS] !== undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — value encoding\n// ---------------------------------------------------------------------------\n\n/**\n * Encode one value of a `values`/`set`/`where` map.\n *\n * The nesting check is not defensive tidiness. The server treats `$ref` as a\n * tagged value only at the TOP of a column's value; a ref buried inside a jsonb\n * payload is just data, and would be stored as the literal object\n * `{\"$ref\":{...}}` — a write that succeeds, commits, and is wrong. So a nested\n * handle is a hard error here, where the line that wrote it is still on the\n * stack.\n */\nfunction encodeValue(value: unknown, column: string, allowColumnExpr: boolean): TxWireValue {\n const ref = refDescriptor(value);\n if (ref) return { $ref: { op: ref.op, field: ref.field } } satisfies TxWireRef;\n\n const expr = exprOf(value);\n if (expr) {\n if (expr.fn !== \"now\" && !allowColumnExpr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() reads the column's current value, so it is ` +\n `only valid in updateWhere(where, set).`,\n );\n }\n return { $expr: expr } satisfies TxWireExpr;\n }\n\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant ` +\n `(e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n\n assertNoNestedHandles(value, column);\n return value;\n}\n\nfunction assertNoNestedHandles(value: unknown, column: string): void {\n if (typeof value !== \"object\" || value === null) return;\n if (value instanceof Date) return;\n if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: a plan handle is nested inside a value. The server would ` +\n `store it as literal JSON, not resolve it. Put the reference directly in ` +\n `the column.`,\n );\n }\n if (Array.isArray(value)) {\n for (const item of value) assertNoNestedHandles(item, column);\n return;\n }\n for (const item of Object.values(value as Record<string, unknown>)) {\n assertNoNestedHandles(item, column);\n }\n}\n\n/**\n * Encode a column map, dropping `undefined` and emitting keys SORTED.\n *\n * Sorting is what makes the same callback produce byte-identical JSON every\n * time, which is what lets the Go decoder be locked to goldens this SDK emits.\n * Dropping `undefined` mirrors what `JSON.stringify` would do anyway, but does\n * it where the resulting column list is still checkable.\n */\nfunction encodeMap(\n map: Record<string, unknown>,\n allowColumnExpr: boolean,\n): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n if (value === undefined) continue;\n out[key] = encodeValue(value, key, allowColumnExpr);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the builder\n// ---------------------------------------------------------------------------\n\n/** How many rows an op can produce, as far as the CLIENT can tell before it\n * runs. Only the empty `insertMany` is knowable, and knowing it is what lets a\n * doomed expectation fail on the line that declared it. */\nconst SKIPPED_OP = -1;\n\nclass TxRowsImpl<Row> implements TxRows<Row> {\n // Present so `isRowsHandle` recognises the object; never read for its value.\n readonly [ROWS] = true;\n // Phantom: the type brand that stops a bare object passing as a TxRows. Never\n // present at run time, which is what `declare` says.\n declare readonly [rowsBrand]: Row;\n private guarded = false;\n\n constructor(\n private readonly builder: TxPlanBuilder,\n private readonly opIndex: number,\n private readonly what: string,\n ) {}\n\n // The type-level `await` guard made real: TS rejects `await rows` at compile\n // time, and reaching this means someone called `.then(...)` by hand.\n then(): never {\n throw new TxRefError(\n `${this.what} cannot be awaited: a transaction callback builds a plan, it ` +\n `does not run statements. Remove the \\`await\\`.`,\n );\n }\n\n expectOne(error: Error): TxRow<Row> {\n this.declareGuard(\"one\", 1, error);\n if (this.opIndex === SKIPPED_OP) throw error;\n return makeRowHandle(this.opIndex) as TxRow<Row>;\n }\n\n expectNone(error: Error): void {\n this.declareGuard(\"none\", 0, error);\n }\n\n expectAtLeast(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtLeast\");\n this.declareGuard(\"atLeast\", n, error);\n if (this.opIndex === SKIPPED_OP && n > 0) throw error;\n }\n\n expectAtMost(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtMost\");\n this.declareGuard(\"atMost\", n, error);\n }\n\n private declareGuard(kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n if (!(error instanceof Error)) {\n // The error object is the ONLY thing that describes this failure to the\n // caller — the server sends back an index, never a message.\n throw new TxPlanError(\n `${this.what}: an expectation needs the Error to throw when it does not ` +\n `hold (e.g. \\`.expect…(new Conflict(\"already accepted\"))\\`).`,\n );\n }\n if (this.guarded) {\n throw new TxPlanError(\n `${this.what} already has an expectation. One operation carries one ` +\n `expectation; declare the second one on its own operation.`,\n );\n }\n this.guarded = true;\n if (this.opIndex === SKIPPED_OP) return;\n this.builder.attachGuard(this.opIndex, kind, n, error);\n }\n}\n\nfunction assertGuardCount(n: number, fn: string): void {\n if (!Number.isInteger(n) || n < 0) {\n throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);\n }\n}\n\n/** Bounds mirrored from the plan executor so an over-sized plan is named here rather\n * than rejected as an opaque 400 after it has crossed the network. */\nconst MAX_OPS = 1000;\nconst MAX_ROWS = 5000;\n\n/**\n * Accumulates ops and the client-side error table while the callback runs.\n *\n * Exported for the runtime and for tests that need the serialised plan without\n * a server; author code never sees it.\n */\nexport class TxPlanBuilder {\n private readonly ops: TxWireOp[] = [];\n /** Errors handed to expectations, indexed by the `slot` the server echoes. */\n private readonly slots: Error[] = [];\n\n /** The table surface handed to the callback. Untyped here; the public\n * `transaction()` signatures put the schema types on top. */\n table(name: string): TxTable<Record<string, unknown>, Record<string, unknown>> {\n return {\n insert: (values) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.insert() needs at least one column`);\n }\n return this.push({ op: \"insert\", table: name, values: encoded }, `${name}.insert()`);\n },\n\n upsert: (values, options) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.upsert() needs at least one column`);\n }\n if (options.onConflict.length === 0) {\n throw new TxPlanError(`${name}.upsert() needs at least one onConflict column`);\n }\n return this.push(\n { op: \"upsert\", table: name, values: encoded, onConflict: options.onConflict },\n `${name}.upsert()`,\n );\n },\n\n insertMany: (rows, opts) => {\n if (rows.length === 0) {\n // Nothing to write. Emitting an op would be a guaranteed 400 (the\n // server requires rows), and refusing outright would punish the\n // ordinary \"filtered every candidate out\" case.\n return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);\n }\n if (rows.length > MAX_ROWS) {\n throw new TxPlanError(\n `${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. ` +\n `Split the write across requests.`,\n );\n }\n const encoded = rows.map((row) => encodeMap(row as Record<string, unknown>, false));\n assertUniformRows(encoded, name);\n if (opts !== undefined && opts.onConflict.length === 0) {\n throw new TxPlanError(\n `${name}.insertMany() was given a conflict action with no onConflict ` +\n `columns. Postgres matches a collision on columns, so name them.`,\n );\n }\n return this.push(\n {\n op: \"insertMany\",\n table: name,\n rows: encoded,\n // Omitted entirely when no options were given, so the op a plain\n // insertMany produces is byte-identical to the one it produced\n // before this option existed.\n ...(opts !== undefined\n ? { onConflict: opts.onConflict, action: opts.action ?? \"ignore\" }\n : {}),\n },\n `${name}.insertMany()`,\n );\n },\n\n updateWhere: (where, set) => {\n const encodedWhere = encodeMap(where as Record<string, unknown>, false);\n const encodedSet = encodeMap(set as Record<string, unknown>, true);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.updateWhere() needs a filter. An update with no filter ` +\n `rewrites the whole table.`,\n );\n }\n if (Object.keys(encodedSet).length === 0) {\n throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);\n }\n return this.push(\n { op: \"update\", table: name, set: encodedSet, where: encodedWhere },\n `${name}.updateWhere()`,\n );\n },\n\n deleteWhere: (where) => {\n const encodedWhere = encodeMap(where as Record<string, unknown>, false);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.deleteWhere() needs a filter. A delete with no filter empties ` +\n `the table.`,\n );\n }\n return this.push(\n { op: \"delete\", table: name, where: encodedWhere },\n `${name}.deleteWhere()`,\n );\n },\n\n select: (where, options) => {\n const op: TxWireOp = { op: \"select\", table: name };\n const encodedWhere = encodeMap((where ?? {}) as Record<string, unknown>, false);\n if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;\n if (options?.limit !== undefined) {\n if (!Number.isInteger(options.limit) || options.limit < 0) {\n throw new TxPlanError(\n `${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`,\n );\n }\n op.limit = options.limit;\n }\n if (options?.lock !== undefined) op.lock = options.lock;\n return this.push(op, `${name}.select()`);\n },\n };\n }\n\n private push(op: TxWireOp, what: string): TxRows<Record<string, unknown>> {\n if (this.ops.length >= MAX_OPS) {\n throw new TxPlanError(\n `this transaction has ${MAX_OPS} operations, which is the limit. Use ` +\n `insertMany() for bulk writes, or split the work across requests.`,\n );\n }\n const index = this.ops.length;\n this.ops.push(op);\n return new TxRowsImpl(this, index, what);\n }\n\n /** Attach an expectation to an op and record its error in the slot table. */\n attachGuard(opIndex: number, kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n const op = this.ops[opIndex];\n // Unreachable: the index came from `push`. A loud failure beats a silently\n // unguarded write if that ever stops being true.\n if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);\n const slot = this.slots.length;\n this.slots.push(error);\n op.guard = { kind, n, slot };\n }\n\n /** The serialisable plan. Empty when the callback described no writes. */\n body(): TxPlanBody {\n return { ops: this.ops };\n }\n\n /** The error the server's `slot` selects, or `null` when it names one this\n * plan never declared (a server/client disagreement, not a tenant error). */\n errorForSlot(slot: number): Error | null {\n return this.slots[slot] ?? null;\n }\n}\n\nfunction assertUniformRows(rows: Record<string, TxWireValue>[], table: string): void {\n const first = rows[0];\n if (!first) return;\n const want = Object.keys(first);\n const wantKey = want.join(\",\");\n for (let i = 1; i < rows.length; i++) {\n const got = Object.keys(rows[i] as Record<string, TxWireValue>);\n if (got.join(\",\") !== wantKey) {\n // One statement, one column list. A ragged row would take the DB default\n // for the column it omitted — a write that succeeds and is wrong.\n throw new TxPlanError(\n `${table}.insertMany(): every row must set the same columns. Row 0 sets ` +\n `[${want.join(\", \")}] but row ${i} sets [${got.join(\", \")}]. ` +\n `(A property set to \\`undefined\\` counts as absent — use \\`null\\`.)`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — materialisation\n// ---------------------------------------------------------------------------\n\n/**\n * Replace every handle in the callback's return value with what the server\n * actually produced.\n *\n * Walks arrays and PLAIN objects only. Class instances (a Date, a Zod schema, a\n * domain object) are returned untouched — recursing into them would rebuild them\n * as bare objects, and nothing inside one can be a handle that this SDK created.\n */\nexport function materializeResult(value: unknown, results: TxPlanOpResult[]): unknown {\n const ref = refDescriptor(value);\n if (ref) {\n const row = rowOf(results, ref.op, `\\`${ref.field}\\``);\n if (!(ref.field in row)) {\n throw new TxPlanError(\n `the transaction's operation ${ref.op} returned no column \\`${ref.field}\\`.`,\n );\n }\n return row[ref.field];\n }\n\n const rowOp = rowOpIndex(value);\n if (rowOp !== null) return rowOf(results, rowOp, \"a row\");\n\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n \"an operation result cannot be returned from a transaction callback: its \" +\n \"row count is not known until the plan runs. Declare an expectation \" +\n \"(`.expectOne(err)`) and return the row, or a column of it.\",\n );\n }\n\n if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);\n return out;\n }\n\n return value;\n}\n\nfunction rowOf(results: TxPlanOpResult[], opIndex: number, what: string): Record<string, unknown> {\n const result = results[opIndex];\n if (!result) {\n throw new TxPlanError(\n `the transaction returned no result for operation ${opIndex}, so ${what} ` +\n `cannot be read.`,\n );\n }\n const row = result.rows[0];\n if (!row) {\n // Unreachable through the public API: a handle only exists behind an\n // `expectOne`, and the server rolls back rather than answering 200 with a\n // guard unmet. Loud, because the alternative is `undefined` in tenant data.\n throw new TxPlanError(\n `the transaction's operation ${opIndex} returned no row, so ${what} cannot ` +\n `be read.`,\n );\n }\n return row;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the driver\n// ---------------------------------------------------------------------------\n\n/** What {@link runTxPlan} needs from the runtime: one call, one transaction. */\nexport interface TxPlanTransport {\n txPlan(plan: TxPlanBody): Promise<TxPlanResponse>;\n}\n\n/**\n * Build the plan, send it, and resolve the callback's return value.\n *\n * A callback that throws never reaches the network: there is nothing to roll\n * back because nothing was sent. A callback that describes no writes also skips\n * the round trip entirely.\n *\n * The RETURN type is `unknown` here on purpose. `Materialized<T>` is a compile-\n * time rewrite of the callback's return type, and it belongs on the public\n * `transaction()` signatures where `T` is inferred from the author's callback;\n * threading it through this driver as well would mean inferring `T` twice, from\n * two different positions, and reconciling them. The public wrappers narrow\n * once, at the seam where the value types were erased anyway.\n */\nexport async function runTxPlan<TTables>(\n transport: TxPlanTransport,\n tables: TTables,\n builder: TxPlanBuilder,\n fn: (tx: TxPlanHandle<TTables>) => unknown,\n): Promise<unknown> {\n const returned = fn({ tables });\n const body = builder.body();\n if (body.ops.length === 0) {\n return materializeResult(returned, []);\n }\n\n let response: TxPlanResponse;\n try {\n response = await transport.txPlan(body);\n } catch (err) {\n throw translateRejection(err, builder);\n }\n return materializeResult(returned, response.results);\n}\n\n/**\n * Turn the broker's rejection back into the tenant's own error.\n *\n * The server never sees the `Error` an expectation was given — only its slot\n * index — so this is the only place the intended error can be produced. A\n * rejection this SDK does not recognise passes through untouched: inventing an\n * error for it would hide the real failure.\n */\nfunction translateRejection(err: unknown, builder: TxPlanBuilder): unknown {\n if (typeof err !== \"object\" || err === null) return err;\n const rejection = err as TxPlanRejection;\n if (rejection.error_code !== \"tx_guard_failed\" || typeof rejection.slot !== \"number\") {\n return err;\n }\n return builder.errorForSlot(rejection.slot) ?? err;\n}\n","/**\n * http.ts — the transport every module client speaks over.\n *\n * WHY IT IS HERE. This code, and the five clients built on it, spent their life\n * in `v2/runtime/internal/runtime/module-clients.js`: 1,768 lines of untyped\n * CommonJS that entered the SDK through an `@ts-expect-error` and left through\n * `unknown` casts. The interfaces those clients implement were always in this\n * package — only the implementations were outside it, where nothing checked one\n * against the other. Two defects came through that gap on 2026-08-15 (a type\n * that described a different server's columns; an accessor that was `undefined`\n * in a deployed handler), and both were green on each side alone.\n *\n * WHAT IT IS NOT. Nothing Bun-specific lives here. The transport is a `fetch`\n * the caller may supply, so this package stays runtime-agnostic and the process\n * that knows which runtime it is decides what to hand in.\n */\n\nimport type { PalbaseResult } from \"../endpoint.js\";\n\n/** Per-request options a module client may pass. */\nexport interface RequestOptions {\n /** JSON-serialised unless it is a string, a Uint8Array, a Blob or FormData. */\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/**\n * What a module client is given. An INTERFACE rather than a class, because the\n * clients depend on this shape and not on the thing that implements it — which\n * is what lets a test drive a whole client without a server.\n */\nexport interface ModuleTransport {\n /** The platform's base URL, for the rare client that must build a URL. */\n readonly baseUrl: string;\n request<T = unknown>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResult<T>>;\n}\n\nexport interface TransportConfig {\n baseUrl: string;\n apiKey: string;\n /**\n * The `fetch` to use. Omitted means the ambient one — resolved at CALL time,\n * never captured here: the egress fence replaces `globalThis.fetch` after the\n * clients are built, and a captured reference would keep calling the\n * un-fenced original.\n */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * A module call that failed.\n *\n * `code` is the platform's own error code (`forbidden`, `not_found`, …) so a\n * caller can branch on it without matching message text.\n */\nexport class PalbaseModuleError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details: Record<string, unknown>;\n\n constructor(code: string, message: string, status: number, details: Record<string, unknown> = {}) {\n super(message);\n this.name = \"PalbaseModuleError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n\nexport function makeHttpClient(cfg: TransportConfig): ModuleTransport {\n async function request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<PalbaseResult<T>> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(options.headers ?? {}),\n };\n if (cfg.apiKey) headers[\"apikey\"] = cfg.apiKey;\n\n const init: RequestInit = { method, headers };\n if (options.body !== undefined) {\n if (typeof options.body === \"string\" || options.body instanceof Uint8Array) {\n init.body = options.body as RequestInit[\"body\"];\n } else if (typeof FormData !== \"undefined\" && options.body instanceof FormData) {\n // The platform writes Content-Type itself, WITH the multipart boundary.\n // Setting it here omits the boundary, and the server then parses zero\n // parts from a request that looks perfectly well formed.\n delete headers[\"Content-Type\"];\n init.body = options.body;\n } else if (typeof Blob !== \"undefined\" && options.body instanceof Blob) {\n delete headers[\"Content-Type\"];\n init.body = options.body;\n } else {\n init.body = JSON.stringify(options.body);\n }\n }\n if (options.signal) init.signal = options.signal;\n\n // Resolved HERE, per call. See TransportConfig.fetchImpl.\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n\n let response: Response;\n try {\n response = await doFetch(`${cfg.baseUrl}${path}`, init);\n } catch (err) {\n // AN ENVELOPE, not an exception.\n //\n // This threw until 2026-08-15, and the throw made three separate claims\n // false at once:\n //\n // 1. The package's own rule — \"Response: { data, error }, no thrown API\n // errors\". Every client here is written to that contract.\n // 2. `Flags.get(key, default)`, whose documented behaviour is that the\n // default applies when the flag is absent AND when the service is\n // unreachable. It reads `resp.error !== null` to decide, and a throw\n // never reaches that branch: measured, `get(\"beta\", \"DEFAULT\")`\n // raised `connect ECONNREFUSED` instead of answering \"DEFAULT\". The\n // test that was supposed to cover it handed the client a hand-made\n // error envelope — a shape this code could not produce.\n // 3. Consistency with the Realtime client, which already envelopes a\n // network failure so a handler that wrote a row does not lose it\n // because pubsub was down.\n //\n // A caller destructuring { data, error } and checking `error` was being\n // defeated by an exception: the defensive code existed and did not help,\n // which is the worst kind of surprise to leave in a package.\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"Network request failed\",\n 0,\n ),\n status: 0,\n };\n }\n\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n let parsed: unknown = null;\n if (method !== \"HEAD\" && contentType.includes(\"json\")) {\n parsed = await response.json().catch(() => null);\n } else if (method !== \"HEAD\" && contentType.startsWith(\"image/\")) {\n // QR codes and the like: hand back bytes the caller can write or forward.\n parsed = new Uint8Array(await response.arrayBuffer());\n } else if (method !== \"HEAD\" && response.body) {\n // A non-JSON error still says something; \"request failed\" says nothing.\n parsed = await response.text().catch(() => null);\n }\n\n if (!response.ok) {\n const body = (parsed && typeof parsed === \"object\" ? parsed : {}) as Record<string, unknown>;\n const code = typeof body.error === \"string\" && body.error ? body.error : \"unknown_error\";\n const message =\n (typeof body.error_description === \"string\" && body.error_description) ||\n response.statusText ||\n \"request failed\";\n return {\n data: null,\n error: new PalbaseModuleError(code, message, response.status, body),\n status: response.status,\n };\n }\n\n return { data: parsed as T, error: null, status: response.status };\n }\n\n return { baseUrl: cfg.baseUrl, request };\n}\n","/**\n * documents.ts — the Documents client, Firestore-shaped.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:705-773` (plus\n * the `buildDocumentRef` / `buildCollectionRef` helpers above it) with its\n * behaviour intact: the same methods, the same paths, the same bodies. What\n * changed is that it now sits beside the interface it implements, so a drift\n * between the two is a compile error rather than a runtime surprise.\n */\n\nimport type {\n PalbaseCollectionRef,\n PalbaseDocsClient,\n PalbaseDocumentRef,\n PalbaseDocumentSnapshot,\n PalbaseQuerySnapshot,\n PalbaseResult,\n PalbaseWhereOperator,\n} from \"../endpoint.js\";\nimport { PalbaseModuleError, type ModuleTransport } from \"./http.js\";\n\n/**\n * A path segment the platform will accept.\n *\n * Validated HERE rather than at the server, because a rejected segment is a\n * programming mistake and the useful moment to hear about it is the call.\n */\nconst SEGMENT_RE = /^[A-Za-z0-9_-]+$/;\n\nfunction validateSegment(segment: string, label: string): void {\n if (!SEGMENT_RE.test(segment)) {\n throw new Error(`Invalid ${label}: \"${segment}\". Must match ${SEGMENT_RE.source}`);\n }\n}\n\ninterface WhereClause {\n field: string;\n op: PalbaseWhereOperator;\n value: unknown;\n}\ninterface OrderClause {\n field: string;\n direction: \"asc\" | \"desc\";\n}\ninterface ChainState {\n where: WhereClause[];\n orderBy: OrderClause[];\n limit?: number;\n}\n\ninterface RawDocument {\n id?: string;\n exists?: boolean;\n data?: Record<string, unknown>;\n}\n\nfunction buildDocumentRef<T extends Record<string, unknown>>(\n http: ModuleTransport,\n path: string,\n): PalbaseDocumentRef<T> {\n return {\n path,\n async set(data: T) {\n return http.request<void>(\"PUT\", `/v1/docs/${path}`, { body: data });\n },\n async get(): Promise<PalbaseResult<PalbaseDocumentSnapshot<T>>> {\n const response = await http.request<RawDocument>(\"GET\", `/v1/docs/${path}`);\n if (response.error) return { data: null, error: response.error, status: response.status };\n const raw = response.data ?? {};\n const exists = raw.exists !== undefined ? raw.exists : Boolean(raw.data || raw.id);\n const segments = path.split(\"/\");\n const id = raw.id || segments[segments.length - 1] || \"\";\n return {\n data: { id, exists, data: () => raw.data as T | undefined, ref: { path } },\n error: null,\n status: response.status,\n };\n },\n async update(data: Partial<T>) {\n return http.request<void>(\"PATCH\", `/v1/docs/${path}`, { body: data });\n },\n async delete() {\n return http.request<void>(\"DELETE\", `/v1/docs/${path}`);\n },\n collection<C extends Record<string, unknown>>(name: string): PalbaseCollectionRef<C> {\n validateSegment(name, \"subcollection name\");\n return buildCollectionRef<C>(http, `${path}/${name}`);\n },\n };\n}\n\nfunction buildCollectionRef<T extends Record<string, unknown>>(\n http: ModuleTransport,\n path: string,\n state: ChainState = { where: [], orderBy: [] },\n): PalbaseCollectionRef<T> {\n function snapshot(doc: { id: string; data: Record<string, unknown> }): PalbaseDocumentSnapshot<T> {\n return {\n id: doc.id,\n exists: true,\n data: () => doc.data as T,\n ref: { path: `${path}/${doc.id}` },\n };\n }\n\n function querySnapshot(docs: PalbaseDocumentSnapshot<T>[]): PalbaseQuerySnapshot<T> {\n return {\n docs,\n empty: docs.length === 0,\n size: docs.length,\n docChanges: () => docs.map((doc) => ({ type: \"added\" as const, doc })),\n };\n }\n\n return {\n path,\n\n doc(id: string) {\n validateSegment(id, \"document ID\");\n return buildDocumentRef<T>(http, `${path}/${id}`);\n },\n\n async add(data: T) {\n const resp = await http.request<{ id: string }>(\"POST\", `/v1/docs/${path}`, { body: data });\n if (resp.error || !resp.data) {\n return { data: null, error: resp.error, status: resp.status };\n }\n return {\n data: buildDocumentRef<T>(http, `${path}/${resp.data.id}`),\n error: null,\n status: resp.status,\n };\n },\n\n // Each narrowing returns a NEW ref. A builder that mutated in place would\n // leak one caller's filter into a query another caller had already held.\n where(field: string, op: PalbaseWhereOperator, value: unknown) {\n return buildCollectionRef<T>(http, path, {\n ...state,\n where: [...state.where, { field, op, value }],\n });\n },\n orderBy(field: string, direction: \"asc\" | \"desc\" = \"asc\") {\n return buildCollectionRef<T>(http, path, {\n ...state,\n orderBy: [...state.orderBy, { field, direction }],\n });\n },\n limit(n: number) {\n return buildCollectionRef<T>(http, path, { ...state, limit: n });\n },\n\n async get(): Promise<PalbaseResult<PalbaseQuerySnapshot<T>>> {\n const narrowed =\n state.where.length > 0 || state.orderBy.length > 0 || state.limit !== undefined;\n\n const resp = narrowed\n ? await http.request<{ documents?: { id: string; data: Record<string, unknown> }[] }>(\n \"POST\",\n `/v1/docs/${path}/query`,\n { body: queryBody(state) },\n )\n : await http.request<{ documents?: { id: string; data: Record<string, unknown> }[] }>(\n \"GET\",\n `/v1/docs/${path}`,\n );\n\n if (resp.error) return { data: null, error: resp.error, status: resp.status };\n const docs = (resp.data?.documents ?? []).map(snapshot);\n return { data: querySnapshot(docs), error: null, status: resp.status };\n },\n };\n}\n\nfunction queryBody(state: ChainState): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (state.where.length > 0) {\n body.where = state.where.map((w) => ({ field: w.field, op: w.op, value: w.value }));\n }\n if (state.orderBy.length > 0) {\n body.orderBy = state.orderBy.map((o) => ({ field: o.field, direction: o.direction }));\n }\n if (state.limit !== undefined) body.limit = state.limit;\n return body;\n}\n\n/** The largest batch the platform accepts in one call. */\nconst MAX_BATCH = 500;\n\nexport function buildDocumentsClient(http: ModuleTransport): PalbaseDocsClient {\n return {\n /**\n * `Documents.doc(\"users/alice\")` — segments are collection/documentId PAIRS,\n * so an odd count addresses a COLLECTION and is refused. Accepting it would\n * write a document whose id happens to be a collection's name.\n */\n doc<T extends Record<string, unknown>>(path: string): PalbaseDocumentRef<T> {\n const segments = String(path)\n .split(\"/\")\n .filter((s) => s.length > 0);\n if (segments.length === 0 || segments.length % 2 !== 0) {\n throw new Error(\n `Invalid document path: \"${path}\". Expected collection/documentId pairs, got ${segments.length} segment(s).`,\n );\n }\n segments.forEach((s, i) => validateSegment(s, i % 2 === 0 ? \"collection name\" : \"document ID\"));\n return buildDocumentRef<T>(http, segments.join(\"/\"));\n },\n\n collection<T extends Record<string, unknown>>(name: string): PalbaseCollectionRef<T> {\n validateSegment(name, \"collection name\");\n return buildCollectionRef<T>(http, name);\n },\n\n async batch(operations) {\n // Refused HERE, without a request: the server would refuse it too, and\n // spending a round trip to be told so is the caller's time.\n if (operations.length > MAX_BATCH) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"batch_too_large\",\n `Batch size ${operations.length} exceeds maximum of ${MAX_BATCH}`,\n 400,\n ),\n status: 400,\n };\n }\n if (operations.length === 0) return { data: null, error: null, status: 200 };\n\n return http.request<void>(\"POST\", \"/v1/docs/batch\", {\n body: operations.map((op) => ({ op: op.op, path: op.ref.path, data: op.data })),\n });\n },\n };\n}\n","/**\n * flags.ts — feature flags, resolved for the request's own user.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:941-1164`.\n *\n * THE ONE RULE WORTH STATING: the user a flag resolves for comes from the\n * SDK's own request scope, never from anything the caller passed on the wire.\n * A handler can pass an explicit context (including an explicit `null` for a\n * deliberate anonymous read) and that wins — but the default is the person the\n * request is being served for, which is what makes `Flags.get(\"x\")` mean the\n * obvious thing inside a handler.\n *\n * Writes mirror the Database model: `setOverride` writes for the CURRENT user\n * and needs no admin power; cross-user writes live behind `asService()` so they\n * are explicit and greppable.\n */\n\nimport type {\n PalbaseBatchOverrideOperation,\n PalbaseFlagContext,\n PalbaseFlagValue,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\nconst FLAG_NAME_RE = /^[A-Za-z0-9_.-]+$/;\n\nexport interface FlagsConfig {\n /** The request's user, read from the SDK's ALS box — never from the caller. */\n getCurrentUserId: () => string | null;\n}\n\nfunction assertFlagName(flagName: string): void {\n if (!FLAG_NAME_RE.test(flagName)) {\n throw new Error(`Invalid flag name: \"${flagName}\". Flag names must match ${FLAG_NAME_RE.source}`);\n }\n}\n\n/** A truthy flag value, in the platform's own terms. */\nfunction flagEnabled(value: unknown): boolean {\n if (typeof value === \"boolean\") return value;\n return value != null && value !== 0 && value !== \"\";\n}\n\nfunction flagVariant(value: unknown): { name: string } | null {\n return typeof value === \"string\" ? { name: value } : null;\n}\n\n/**\n * A context object carries `userId`/`properties`; anything else passed in that\n * position is a DEFAULT VALUE. This is what tells `Flags.get(key, ctx)` apart\n * from `Flags.get(key, someObjectDefault)`.\n */\nfunction isContextObject(v: unknown): v is PalbaseFlagContext {\n return (\n v !== null && typeof v === \"object\" && !Array.isArray(v) && (\"userId\" in v || \"properties\" in v)\n );\n}\n\ninterface MergedSnapshot {\n values?: Record<string, PalbaseFlagValue>;\n}\n\nexport function buildFlagsClient(http: ModuleTransport, cfg: FlagsConfig): PalbaseFlagsClient {\n /**\n * The effective user for a call. An explicit `userId` in the context wins —\n * INCLUDING an explicit `null`, which is a deliberate anonymous read.\n */\n function resolveUserId(context?: PalbaseFlagContext): string | null | undefined {\n if (context && \"userId\" in context) return context.userId ?? null;\n return cfg.getCurrentUserId() || undefined;\n }\n\n function mergedPath(context?: PalbaseFlagContext): string {\n const uid = resolveUserId(context);\n return uid ? `/v1/user-flags/users/${encodeURIComponent(uid)}` : \"/v1/user-flags\";\n }\n\n function fetchMerged(context?: PalbaseFlagContext) {\n return http.request<MergedSnapshot>(\"GET\", mergedPath(context));\n }\n\n const service: PalbaseFlagsServiceClient = {\n async setOverrideForUser(userId, key, value) {\n return http.request(\n \"PUT\",\n `/v1/user-flags/users/${encodeURIComponent(userId)}/${encodeURIComponent(key)}`,\n { body: { value } },\n );\n },\n async setOverridesForUser(userId, values) {\n return http.request(\"PUT\", `/v1/user-flags/users/${encodeURIComponent(userId)}`, {\n body: { values },\n });\n },\n async clearOverrideForUser(userId, key) {\n return http.request(\n \"DELETE\",\n `/v1/user-flags/users/${encodeURIComponent(userId)}/${encodeURIComponent(key)}`,\n );\n },\n async clearAllOverridesForUser(userId) {\n return http.request(\"DELETE\", `/v1/user-flags/users/${encodeURIComponent(userId)}`);\n },\n async batchSetOverrides(operations: ReadonlyArray<PalbaseBatchOverrideOperation>) {\n // The argument is camelCase, the wire is snake_case. Mapped here so a\n // stray `userId` never reaches the server — and an explicit `user_id`, if\n // a caller already wrote one, is preserved.\n const ops = (operations ?? []).map((op) => {\n const raw = op as unknown as { userId?: string; user_id?: string; values: unknown };\n return { user_id: raw.userId ?? raw.user_id, values: raw.values };\n });\n return http.request(\"POST\", \"/v1/user-flags/batch\", { body: { operations: ops } });\n },\n };\n\n return {\n async isEnabled(flagName: string, context?: PalbaseFlagContext) {\n assertFlagName(flagName);\n const res = await fetchMerged(context);\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n return { data: flagEnabled(res.data.values?.[flagName]), error: null, status: res.status };\n },\n\n async getVariant(flagName: string, context?: PalbaseFlagContext) {\n assertFlagName(flagName);\n const res = await fetchMerged(context);\n // A missing or non-string value is a NULL variant on a successful read;\n // errors and empty bodies pass through as null too, which is why this is\n // written out rather than mapped.\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n return { data: flagVariant(res.data.values?.[flagName]), error: null, status: res.status };\n },\n\n /**\n * `get(key)` · `get(key, default)` · `get(key, default, ctx)` · `get(key, ctx)`.\n *\n * The default is substituted when the flag is ABSENT or when the flags\n * service is unreachable — a product that hides a feature because a lookup\n * timed out is behaving correctly; one that crashes is not.\n */\n async get(\n flagName: string,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n assertFlagName(flagName);\n\n let defaultValue: PalbaseFlagValue | undefined;\n let context: PalbaseFlagContext | undefined;\n let hasDefault = false;\n if (maybeContext !== undefined) {\n defaultValue = defaultOrContext as PalbaseFlagValue;\n hasDefault = true;\n context = maybeContext;\n } else if (isContextObject(defaultOrContext)) {\n context = defaultOrContext;\n } else if (defaultOrContext !== undefined) {\n defaultValue = defaultOrContext as PalbaseFlagValue;\n hasDefault = true;\n }\n\n const resp = await fetchMerged(context);\n if (resp.error !== null) {\n if (hasDefault) return { data: defaultValue ?? null, error: null, status: resp.status };\n return { data: null, error: resp.error, status: resp.status };\n }\n const values = resp.data?.values ?? {};\n const value = values[flagName];\n // An absent key on a SUCCESSFUL read is not an error.\n if (value === undefined) {\n return { data: hasDefault ? (defaultValue ?? null) : null, error: null, status: resp.status };\n }\n return { data: value, error: null, status: resp.status };\n },\n\n async getAll(context?: PalbaseFlagContext) {\n const res = await fetchMerged(context);\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n const values = res.data.values ?? {};\n return {\n data: Object.keys(values).map((name) => {\n const value = values[name];\n const flag: { name: string; enabled: boolean; variant?: { name: string } } = {\n name,\n enabled: flagEnabled(value),\n };\n if (typeof value === \"string\") flag.variant = { name: value };\n return flag;\n }),\n error: null,\n status: res.status,\n };\n },\n\n /**\n * Override a flag for the CURRENT request user.\n *\n * On an anonymous request this does not silently no-op and does not write\n * for nobody: it refuses and names the call that does cross-user writes.\n */\n async setOverride(key: string, value: PalbaseFlagValue) {\n const uid = cfg.getCurrentUserId();\n if (!uid) {\n return {\n data: null,\n error: {\n message:\n \"setOverride requires a signed-in user; use Flags.asService().setOverrideForUser(userId, key, value) for cross-user writes\",\n },\n status: 400,\n };\n }\n return http.request(\n \"PUT\",\n `/v1/user-flags/users/${encodeURIComponent(uid)}/${encodeURIComponent(key)}`,\n { body: { value } },\n );\n },\n\n asService() {\n return service;\n },\n };\n}\n","/**\n * notifications.ts — push, email, SMS, verifications, inbox, preferences and\n * the two template surfaces.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:1180-1379`.\n *\n * The theme of this file is a NAME GAP: the SDK speaks camelCase and palnotify\n * speaks snake_case, and every place they meet is a place a field can be\n * dropped in silence. One of them cost a live afternoon — `email.send({ html })`\n * was forwarded verbatim, palnotify reads `html_body`, and the answer was a 400\n * about a field the caller had supplied. The mappings below are that lesson,\n * and they are now checked against the declared parameter types instead of\n * being hand-carried across a package boundary.\n */\n\nimport type {\n PalbaseEmailClient,\n PalbaseEmailTemplate,\n PalbaseEmailTemplatesClient,\n PalbaseInboxClient,\n PalbaseNotificationsClient,\n PalbasePreferencesClient,\n PalbasePushClient,\n PalbaseSMSTemplate,\n PalbaseSMSTemplatesClient,\n PalbaseSmsClient,\n PalbaseVerificationsClient,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\n/** Re-map the data of a SUCCESSFUL envelope; errors pass through untouched. */\nfunction mapEnvelope<In, Out>(res: PalbaseResult<In>, map: (data: In) => Out): PalbaseResult<Out> {\n if (res.error !== null || res.data === null || res.data === undefined) {\n return { data: null, error: res.error, status: res.status };\n }\n return { data: map(res.data), error: null, status: res.status };\n}\n\ntype Wire = Record<string, unknown>;\n\nfunction toEmailTemplate(wire: Wire): PalbaseEmailTemplate {\n const view: PalbaseEmailTemplate = {\n id: wire.id as string,\n slug: wire.slug as string,\n locale: wire.locale as string,\n subject: wire.subject as string,\n htmlBody: wire.html_body as string,\n variables: (wire.variables as string[]) ?? [],\n isDefault: wire.is_default as boolean,\n createdAt: wire.created_at as string,\n updatedAt: wire.updated_at as string,\n };\n if (wire.text_body !== undefined) view.textBody = wire.text_body as string;\n return view;\n}\n\nfunction toSmsTemplate(wire: Wire): PalbaseSMSTemplate {\n return {\n id: wire.id as string,\n slug: wire.slug as string,\n locale: wire.locale as string,\n body: wire.body as string,\n variables: (wire.variables as string[]) ?? [],\n isDefault: wire.is_default as boolean,\n createdAt: wire.created_at as string,\n updatedAt: wire.updated_at as string,\n };\n}\n\nexport function buildNotificationsClient(http: ModuleTransport): PalbaseNotificationsClient {\n const push: PalbasePushClient = {\n async send(params) {\n return http.request(\"POST\", \"/v1/notifications/push\", { body: params });\n },\n };\n\n const email: PalbaseEmailClient = {\n async send(params) {\n // `html`/`text` are what the SDK declares; palnotify reads\n // `html_body`/`text_body`. Forwarding them verbatim answered 400 about a\n // field the caller HAD supplied — live on todoapp, 2026-07-30.\n const { templateSlug, html, text, ...rest } = params;\n const body: Record<string, unknown> = { ...rest };\n if (templateSlug !== undefined) body.template_slug = templateSlug;\n if (html !== undefined) body.html_body = html;\n if (text !== undefined) body.text_body = text;\n return http.request(\"POST\", \"/v1/notifications/email\", { body });\n },\n };\n\n const sms: PalbaseSmsClient = {\n async send(params) {\n const { templateSlug, ...rest } = params;\n const body = templateSlug !== undefined ? { ...rest, template_slug: templateSlug } : rest;\n return http.request(\"POST\", \"/v1/notifications/sms\", { body });\n },\n };\n\n // Phone verification (OTP). Separate from sms.send on purpose: there is no\n // body here — the provider generates the code and the message text itself.\n const verifications: PalbaseVerificationsClient = {\n async start(params) {\n return http.request(\"POST\", \"/v1/notifications/verifications\", { body: params });\n },\n async check(params) {\n return http.request(\"POST\", \"/v1/notifications/verifications/check\", { body: params });\n },\n };\n\n const inbox: PalbaseInboxClient = {\n async send(params) {\n return http.request(\"POST\", \"/v1/notifications/inbox\", { body: params });\n },\n async list(options?: {\n cursor?: string;\n limit?: number;\n is_read?: boolean;\n category?: string;\n include_archived?: boolean;\n }) {\n const opts = options ?? {};\n const params = new URLSearchParams();\n if (opts.cursor) params.set(\"cursor\", opts.cursor);\n if (opts.limit !== undefined) params.set(\"limit\", String(opts.limit));\n if (opts.is_read !== undefined) params.set(\"is_read\", opts.is_read ? \"true\" : \"false\");\n if (opts.category) params.set(\"category\", opts.category);\n if (opts.include_archived) params.set(\"include_archived\", \"true\");\n const query = params.toString();\n return http.request(\"GET\", `/v1/notifications/inbox${query ? `?${query}` : \"\"}`);\n },\n async unreadCount() {\n return http.request(\"GET\", \"/v1/notifications/inbox/unread-count\");\n },\n async markRead(id: string) {\n return http.request(\"PATCH\", `/v1/notifications/inbox/${encodeURIComponent(id)}/read`);\n },\n async markAllRead() {\n return http.request(\"POST\", \"/v1/notifications/inbox/read-all\");\n },\n async archive(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/inbox/${encodeURIComponent(id)}`);\n },\n };\n\n const preferences: PalbasePreferencesClient = {\n async get() {\n return http.request(\"GET\", \"/v1/notifications/preferences\");\n },\n async update(params) {\n return http.request(\"PUT\", \"/v1/notifications/preferences\", { body: params });\n },\n };\n\n const emailTemplates: PalbaseEmailTemplatesClient = {\n async list() {\n const resp = await http.request<Wire[]>(\"GET\", \"/v1/notifications/templates\");\n return mapEnvelope(resp, (rows) => (rows ?? []).map(toEmailTemplate));\n },\n async get(id: string) {\n const resp = await http.request<Wire>(\n \"GET\",\n `/v1/notifications/templates/${encodeURIComponent(id)}`,\n );\n return mapEnvelope(resp, toEmailTemplate);\n },\n async create(input: { slug: string; subject: string; htmlBody: string; textBody?: string; variables?: string[] }) {\n const body: Record<string, unknown> = {\n slug: input.slug,\n subject: input.subject,\n html_body: input.htmlBody,\n };\n if (input.textBody !== undefined) body.text_body = input.textBody;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\"POST\", \"/v1/notifications/templates\", { body });\n return mapEnvelope(resp, toEmailTemplate);\n },\n async update(\n id: string,\n input: { subject?: string; htmlBody?: string; textBody?: string; variables?: string[] },\n ) {\n const body: Record<string, unknown> = {};\n if (input.subject !== undefined) body.subject = input.subject;\n if (input.htmlBody !== undefined) body.html_body = input.htmlBody;\n if (input.textBody !== undefined) body.text_body = input.textBody;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\n \"PUT\",\n `/v1/notifications/templates/${encodeURIComponent(id)}`,\n { body },\n );\n return mapEnvelope(resp, toEmailTemplate);\n },\n async delete(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/templates/${encodeURIComponent(id)}`);\n },\n };\n\n const smsTemplates: PalbaseSMSTemplatesClient = {\n async list() {\n const resp = await http.request<Wire[]>(\"GET\", \"/v1/notifications/sms-templates\");\n return mapEnvelope(resp, (rows) => (rows ?? []).map(toSmsTemplate));\n },\n async get(id: string) {\n const resp = await http.request<Wire>(\n \"GET\",\n `/v1/notifications/sms-templates/${encodeURIComponent(id)}`,\n );\n return mapEnvelope(resp, toSmsTemplate);\n },\n async create(input: { slug: string; body: string; variables?: string[] }) {\n const body: Record<string, unknown> = { slug: input.slug, body: input.body };\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\"POST\", \"/v1/notifications/sms-templates\", { body });\n return mapEnvelope(resp, toSmsTemplate);\n },\n async update(id: string, input: { body?: string; variables?: string[] }) {\n const body: Record<string, unknown> = {};\n if (input.body !== undefined) body.body = input.body;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\n \"PUT\",\n `/v1/notifications/sms-templates/${encodeURIComponent(id)}`,\n { body },\n );\n return mapEnvelope(resp, toSmsTemplate);\n },\n async delete(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/sms-templates/${encodeURIComponent(id)}`);\n },\n };\n\n return {\n push,\n email,\n sms,\n verifications,\n inbox,\n preferences,\n templates: { email: emailTemplates, sms: smsTemplates },\n async registerDevice(params) {\n return http.request(\"POST\", \"/v1/notifications/devices\", { body: params });\n },\n async unregisterDevice(deviceId: string) {\n return http.request(\"DELETE\", `/v1/notifications/devices/${encodeURIComponent(deviceId)}`);\n },\n };\n}\n","/**\n * realtime.ts — broadcast, and only broadcast.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:811-883`.\n *\n * There is no `subscribe()` here, deliberately: a backend handler answers one\n * request and ends, so there is no honest place to hold a long-lived socket.\n * Subscription lives in the client SDKs; this side pushes.\n *\n * The V1 host/executor branch is GONE. It existed so an isolate could delegate\n * the secret-bearing token mint to a host that held the credential — and the\n * isolate was removed on 2026-08-14. A single-tenant process has nobody to hide\n * its own tenant's key from.\n */\n\nimport { createHmac } from \"node:crypto\";\n\nimport type { PalbaseRealtimeClient } from \"../clients.js\";\nimport { PalbaseModuleError } from \"./http.js\";\n\nexport interface RealtimeConfig {\n baseUrl: string;\n /**\n * The shared Realtime API secret. Empty means realtime is not provisioned for\n * this environment, and broadcast says so by name rather than failing oddly.\n */\n apiJwtSecret: string;\n /** Resolved at CALL time — see the note in http.ts. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * A short-lived HS256 token Realtime's broadcast pipeline accepts.\n *\n * It needs a valid signature and a future `exp`, nothing more — this is a\n * service-to-service hop inside the stack, not a user session.\n */\nfunction mintToken(secret: string): string {\n const now = Math.floor(Date.now() / 1000);\n const header = Buffer.from(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" })).toString(\"base64url\");\n const payload = Buffer.from(\n JSON.stringify({ iss: \"backend-runtime\", role: \"service_role\", iat: now, exp: now + 60 }),\n ).toString(\"base64url\");\n const sig = createHmac(\"sha256\", secret).update(`${header}.${payload}`).digest(\"base64url\");\n return `${header}.${payload}.${sig}`;\n}\n\nexport function buildRealtimeClient(cfg: RealtimeConfig): PalbaseRealtimeClient {\n const url = `${cfg.baseUrl}/realtime/api/broadcast`;\n const stateUrl = `${cfg.baseUrl}/realtime/api/state`;\n\n /** One state write or clear. Same credential, same fire-and-forget contract\n * as broadcast: a handler that wrote a row must not lose it because the\n * pubsub layer was unreachable. */\n async function writeState(\n topic: string,\n key: string,\n value: Record<string, unknown> | undefined,\n del: boolean,\n ) {\n if (typeof topic !== \"string\" || topic.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"topic must be a non-empty string\", 400),\n };\n }\n if (typeof key !== \"string\" || key.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"key must be a non-empty string\", 400),\n };\n }\n if (!cfg.apiJwtSecret) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_unconfigured\",\n \"Realtime.state is unavailable: realtime is not provisioned for this Environment \" +\n \"(PALBASE_REALTIME_API_JWT_SECRET unset).\",\n 503,\n ),\n };\n }\n\n let token: string;\n try {\n token = mintToken(cfg.apiJwtSecret);\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_token_error\",\n err instanceof Error ? err.message : \"token mint failed\",\n 500,\n ),\n };\n }\n\n const op = del ? { topic, key, del: true } : { topic, key, value: value ?? {} };\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n let response: Response;\n try {\n response = await doFetch(stateUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${token}` },\n body: JSON.stringify({ ops: [op] }),\n });\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"state request failed\",\n 0,\n ),\n };\n }\n if (response.status === 202 || response.status === 200) {\n return { data: undefined, error: null };\n }\n const detail = await response.text().catch(() => \"\");\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_state_failed\",\n `realtime state write returned ${response.status}${detail ? `: ${detail}` : \"\"}`,\n response.status,\n ),\n };\n }\n\n return {\n state: {\n /** Write one DURABLE entry on a channel's shared state.\n *\n * The difference from broadcast is WHO it reaches: a broadcast reaches\n * whoever is listening at that instant, while state is also handed to\n * whoever joins afterwards. \"This value is now X\" wants the second — a\n * client connecting a second later should not have to wait for the next\n * change to learn X. */\n set: (topic: string, key: string, value: Record<string, unknown>) =>\n writeState(topic, key, value, false),\n /** Remove one entry. */\n clear: (topic: string, key: string) => writeState(topic, key, undefined, true),\n },\n\n async broadcast(channel: string, event: string, payload?: Record<string, unknown>) {\n // Cheap argument checks first, locally: a bad call gets an answer without\n // spending a round trip to be told the obvious.\n if (typeof channel !== \"string\" || channel.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"channel must be a non-empty string\", 400),\n };\n }\n if (typeof event !== \"string\" || event.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"event must be a non-empty string\", 400),\n };\n }\n if (!cfg.apiJwtSecret) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_unconfigured\",\n \"Realtime.broadcast is unavailable: realtime is not provisioned for this Environment \" +\n \"(PALBASE_REALTIME_API_JWT_SECRET unset).\",\n 503,\n ),\n };\n }\n\n let token: string;\n try {\n token = mintToken(cfg.apiJwtSecret);\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_token_error\",\n err instanceof Error ? err.message : \"token mint failed\",\n 500,\n ),\n };\n }\n\n // The BARE sub-topic. Realtime prepends \"realtime:\" on delivery, and a\n // pre-prefixed topic double-prefixes and is silently dropped — proven live.\n const body = JSON.stringify({\n messages: [{ topic: channel, event, payload: payload ?? {}, private: false }],\n });\n\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n let response: Response;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${token}` },\n body,\n });\n } catch (err) {\n // FIRE AND FORGET: a handler that wrote a row and then broadcast must\n // not lose the row because the pubsub layer was unreachable. This is the\n // one client that answers with an envelope on a network failure rather\n // than throwing, and it is why.\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"broadcast request failed\",\n 0,\n ),\n };\n }\n\n if (response.status === 202 || response.status === 200) {\n return { data: undefined, error: null };\n }\n\n const detail = await response.text().catch(() => \"\");\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_broadcast_failed\",\n `broadcast returned ${response.status}: ${detail.slice(0, 200)}`,\n response.status,\n ),\n };\n },\n };\n}\n","/**\n * storage.ts — the Storage client.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:474-589`. That\n * code addressed the native Supabase Storage wire under `/storage/v1` until\n * 2026-08-15, when it was repointed at this stack's own module — measured\n * against the live stack, where the old path answers 404 and the new one 200.\n * It arrives here so the SHAPE it returns and the type that declares that shape\n * are checked against each other: they were not, and the type spent a major\n * version describing another server's columns.\n */\n\nimport type {\n PalbaseBucketClient,\n PalbaseFileObject,\n PalbaseListOptions,\n PalbaseSignedUrlResponse,\n PalbaseStorageClient,\n PalbaseUploadOptions,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\n/** What the platform accepts as a bucket name (schema: `^[a-z][a-z0-9-]{1,62}$`). */\nconst BUCKET_NAME_RE = /^[a-zA-Z0-9_-]+$/;\n/** What the platform accepts as an object path. */\nconst STORAGE_PATH_RE = /^[a-zA-Z0-9_./-]+$/;\nconst STORAGE_TRAVERSAL_RE = /(?:^|\\/)\\.\\.(?:\\/|$)/;\n\n/**\n * Refused HERE, before any request.\n *\n * A traversing path is a programming mistake, and the useful moment to hear\n * about it is the call that made it — not a 400 three layers away.\n */\nfunction validateStoragePath(p: string): void {\n if (!STORAGE_PATH_RE.test(p) || STORAGE_TRAVERSAL_RE.test(p)) {\n throw new Error(\n `Invalid file path: \"${p}\". Paths must not contain traversal sequences and must match ${STORAGE_PATH_RE.source}`,\n );\n }\n}\n\n/**\n * The wire's own shape, mapped onto what this package declares.\n *\n * v2's storage answers in camelCase with the variants and the thumbhash already\n * in it, so this maps rather than translates. The snake_case unwrapping that\n * used to live here (`metadata.mimetype`, `bucket_id`, `created_at`) belonged to\n * a different server, and reading those names off this wire produced an object\n * whose size was 0 and whose content type was \"\".\n */\nfunction toFileObject(bucket: string, row: Record<string, unknown>): PalbaseFileObject {\n return {\n name: (row.path as string) ?? \"\",\n path: (row.path as string) ?? \"\",\n bucket: (row.bucket as string) ?? bucket,\n size: typeof row.size === \"number\" ? row.size : 0,\n contentType: (row.contentType as string) ?? \"\",\n checksum: (row.checksum as string) ?? \"\",\n width: row.width as number | undefined,\n height: row.height as number | undefined,\n thumbhash: row.thumbhash as string | undefined,\n variants: (row.variants as Record<string, string>) ?? {},\n };\n}\n\n/** Re-map the data of a SUCCESSFUL envelope; pass errors through untouched. */\nfunction mapResponse<In, Out>(\n res: PalbaseResult<In>,\n map: (data: In) => Out,\n): PalbaseResult<Out> {\n if (res.error || res.data === null || res.data === undefined) {\n return { data: null, error: res.error, status: res.status };\n }\n return { data: map(res.data), error: null, status: res.status };\n}\n\nfunction buildBucketClient(\n http: ModuleTransport,\n bucketName: string,\n publicOrigin: string,\n): PalbaseBucketClient {\n const objectPath = (path: string) => `/v1/storage/object/${bucketName}/${path}`;\n\n return {\n async upload(path, file, options?: PalbaseUploadOptions) {\n validateStoragePath(path);\n const headers: Record<string, string> = {\n \"Content-Type\": options?.contentType ?? \"application/octet-stream\",\n };\n if (options?.upsert) headers[\"x-upsert\"] = \"true\";\n // The BYTES, as the body. Storage sniffs the content and decides for\n // itself what this is; the declared type is a hint it may overrule,\n // because a name and a header are both things a caller can be wrong about.\n const body = file instanceof ArrayBuffer ? new Uint8Array(file) : file;\n const res = await http.request<Record<string, unknown>>(\"PUT\", objectPath(path), {\n body,\n headers,\n });\n return mapResponse(res, (r) => toFileObject(bucketName, r ?? {}));\n },\n\n async download(path) {\n validateStoragePath(path);\n // The AUTHENTICATED read: the project already holds a credential this\n // stack verified, so it does not have to mint a signature to open its own\n // object — and this route serves private buckets, which the public one\n // refuses on purpose.\n return http.request<Blob>(\"GET\", objectPath(path), { headers: { Accept: \"*/*\" } });\n },\n\n getPublicUrl(path, options) {\n validateStoragePath(path);\n const variant = options?.variant ? `?variant=${encodeURIComponent(options.variant)}` : \"\";\n // ABSOLUTE — and the origin is a value the stack is TOLD, not the\n // transport's baseUrl.\n //\n // Those are two different addresses and conflating them is how this broke\n // once already: the transport points at palsvc over the loopback\n // (`http://127.0.0.1:8080`), and a URL built from it resolves nowhere\n // outside the pod. So this used to return the path alone.\n //\n // The path alone is not a smaller answer, it is a wrong one. A public URL\n // LEAVES the response body — into an <img>, an email, another app on\n // another host — and none of those have a base to resolve it against.\n // Measured live 24.08.2026: an iOS client handed the returned\n // `/v1/files/post-images/…` straight to URLSession and got\n // NSURLErrorUnsupportedURL (-1002). The upload had worked; only the URL\n // was unusable.\n //\n // `PALBASE_PUBLIC_ORIGIN` is set by whoever publishes the stack, because\n // only they know it: in the cloud the operator writes\n // `https://<ref>.<domain>`, and a self-hosted stack carries whatever\n // domain its certificate is for.\n if (!publicOrigin) {\n // NAMED, not silent — the same doctrine as the other unconfigured\n // modules in engine/config.ts (\"throw a named error on first use rather\n // than silently no-op\"). A returned path would pass every test here and\n // fail in the one place nobody is watching.\n throw new Error(\n `Storage.bucket(\"${bucketName}\").getPublicUrl() needs this stack's public origin, ` +\n \"and it was not configured. Set PALBASE_PUBLIC_ORIGIN to the address clients reach \" +\n \"this stack at (e.g. https://myproject.palbase.studio).\",\n );\n }\n return `${publicOrigin}/v1/files/${bucketName}/${path}${variant}`;\n },\n\n async createSignedUrl(path, options): Promise<PalbaseResult<PalbaseSignedUrlResponse>> {\n validateStoragePath(path);\n // A DURATION — `{ expiresIn: \"1h\" }`. A bare number is ambiguous between\n // seconds and minutes at every call site that reads it, and the ambiguity\n // is only discovered when a link outlives the object it opened.\n return http.request<PalbaseSignedUrlResponse>(\"POST\", `/v1/storage/sign/${bucketName}/${path}`, {\n body: { expiresIn: options.expiresIn },\n });\n },\n\n async list(prefix?: string, options?: PalbaseListOptions) {\n if (prefix) validateStoragePath(prefix);\n const params = new URLSearchParams();\n if (prefix) params.set(\"prefix\", prefix);\n if (options?.limit !== undefined) params.set(\"limit\", String(options.limit));\n const query = params.toString();\n const res = await http.request<{ objects?: Record<string, unknown>[] }>(\n \"GET\",\n `/v1/storage/bucket/${bucketName}${query ? `?${query}` : \"\"}`,\n );\n // `{objects: [...]}`, not a bare array: the envelope leaves room for the\n // paging this will grow, and unwrapping it here keeps that off callers.\n return mapResponse(res, (body) => (body?.objects ?? []).map((row) => toFileObject(bucketName, row)));\n },\n\n async remove(paths) {\n for (const p of paths) validateStoragePath(p);\n // One request per object: the module deletes an object WITH its variants,\n // and a batch endpoint reporting partial success would need a result shape\n // nobody would read. The first refusal ends it — continuing would report a\n // partial delete as a whole one.\n const removed: PalbaseFileObject[] = [];\n for (const p of paths) {\n const res = await http.request<void>(\"DELETE\", objectPath(p));\n if (res.error) return { data: null, error: res.error, status: res.status };\n removed.push(toFileObject(bucketName, { path: p }));\n }\n return { data: removed, error: null, status: 200 };\n },\n\n async move(from, to) {\n validateStoragePath(from);\n validateStoragePath(to);\n return http.request<void>(\"POST\", `/v1/storage/move/${bucketName}`, { body: { from, to } });\n },\n\n async copy(from, to) {\n validateStoragePath(from);\n validateStoragePath(to);\n return http.request<void>(\"POST\", `/v1/storage/copy/${bucketName}`, { body: { from, to } });\n },\n };\n}\n\n/**\n * @param publicOrigin the address CLIENTS reach this stack at — never the\n * transport's base, which is this process's internal route to palsvc. Empty\n * means it was not configured, and `getPublicUrl` refuses by name.\n */\nexport function buildStorageClient(\n http: ModuleTransport,\n publicOrigin: string,\n): PalbaseStorageClient {\n return {\n bucket(name: string) {\n if (!BUCKET_NAME_RE.test(name)) {\n throw new Error(`Invalid bucket name: \"${name}\". Bucket names must match ${BUCKET_NAME_RE.source}`);\n }\n // Sondaki eğik çizgi BURADA kırpılır: `${origin}/v1/files/...` iki\n // eğik çizgiyle biten bir yol üretirdi ve bazı sunucular onu ayrı bir\n // nesne sayar.\n return buildBucketClient(http, name, publicOrigin.replace(/\\/+$/, \"\"));\n },\n };\n}\n","/**\n * clients/index.ts — the composition root for the module clients.\n *\n * This is what the process calls once at boot. It builds the five clients the\n * engine injects and nothing else.\n *\n * WHAT IS NOT BUILT HERE, and why each one is absent rather than forgotten:\n *\n * - `auth`, `functions`, `analytics`, `links` — the SDK exports no singleton\n * for any of them (`runtime.ts` exports ten, and these four are not among\n * them), so no handler could reach them. They were constructed on every\n * boot and thrown away.\n * - `Purchases` — its client talked to palstore, and v2 contains no palstore\n * at all. The surface was unbacked before it was untyped. Dropped from v2\n * by the user's decision on 2026-08-15, with the SDK's `src/purchases/`\n * tree left in place because that decision was \"deferred, not silently\n * taken\". It is taken now: the tree is GONE (2026-08-29), because a\n * decorator standing in front of a service nothing serves is the same\n * defect as `Resource` and `config/*`, which went with it.\n * - The V1 host/executor transport — the isolate it existed for was removed\n * on 2026-08-14. A single-tenant process has nobody to hide its own\n * tenant's credentials from.\n */\n\nimport type { ModuleClients } from \"../engine/index.js\";\nimport { buildDocumentsClient } from \"./documents.js\";\nimport { buildFlagsClient } from \"./flags.js\";\nimport { makeHttpClient } from \"./http.js\";\nimport { buildNotificationsClient } from \"./notifications.js\";\nimport { buildRealtimeClient } from \"./realtime.js\";\nimport { buildStorageClient } from \"./storage.js\";\n\nexport interface ModuleClientsConfig {\n /** Where the platform answers. Empty means \"not configured\" — see below. */\n baseUrl: string;\n /** The publishable key. Used only when no service-role key is supplied. */\n apiKey: string;\n /**\n * The service-role key, which is what a backend actually holds. Preferred\n * over `apiKey`: this process IS the project's server.\n */\n serviceRoleKey: string;\n /** The shared Realtime secret. Empty means realtime is not provisioned. */\n realtimeApiJwtSecret: string;\n /**\n * The address CLIENTS reach this stack at. Used ONLY to build public object\n * URLs; every request this bundle makes still goes over `baseUrl`.\n */\n publicOrigin: string;\n /** The request's user, read from the SDK's own scope — never from a caller. */\n getCurrentUserId: () => string | null;\n /** Injected in tests; resolved at call time in production. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Build the module clients.\n *\n * Returns an EMPTY bundle when there is no base URL, deliberately: the engine\n * then injects its named stubs, so a handler that reaches for `Storage` gets an\n * error saying which module is unconfigured rather than a crash reading a\n * property of undefined. Booting is not blocked — a project that never touches\n * a module runs fine without one.\n */\nexport function buildModuleClients(cfg: ModuleClientsConfig): ModuleClients {\n const baseUrl = (cfg.baseUrl || \"\").replace(/\\/+$/, \"\");\n if (!baseUrl) return {};\n\n // The service-role key when present: this process is the project's own\n // server, and the publishable key would refuse half of what it needs.\n const apiKey = cfg.serviceRoleKey || cfg.apiKey || \"\";\n const http = makeHttpClient({ baseUrl, apiKey, fetchImpl: cfg.fetchImpl });\n\n return {\n Documents: buildDocumentsClient(http),\n Storage: buildStorageClient(http, cfg.publicOrigin),\n Notifications: buildNotificationsClient(http),\n Flags: buildFlagsClient(http, { getCurrentUserId: cfg.getCurrentUserId }),\n Realtime: buildRealtimeClient({\n baseUrl,\n apiJwtSecret: cfg.realtimeApiJwtSecret,\n fetchImpl: cfg.fetchImpl,\n }),\n };\n}\n","/**\n * policy.ts — the RLS policy authoring DSL.\n *\n * `policy(name)` returns a fluent builder that mirrors the `ColumnBuilder`\n * style in columns.ts: each chainable method mutates the underlying\n * definition and returns the builder so calls compose. The terminal value is\n * a plain {@link PolicyDef} — the exact JSON shape the runtime's\n * `schema_extract.js` reads off the bundled module and the Go side parses into\n * `PolicyJSON` (CONTRACT-POLICY).\n *\n * @example\n * import { policy } from \"@palbase/backend\";\n *\n * policy(\"owner_select\")\n * .for(\"select\")\n * .to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\");\n */\n\n/** The SQL command a policy applies to. `\"all\"` covers SELECT/INSERT/UPDATE/DELETE. */\nexport type PolicyCommand = \"all\" | \"select\" | \"insert\" | \"update\" | \"delete\";\n\n/** Whether a policy is permissive (OR-combined, the default) or restrictive\n * (AND-combined). Mirrors Postgres `CREATE POLICY ... AS PERMISSIVE|RESTRICTIVE`. */\nexport type PolicyMode = \"permissive\" | \"restrictive\";\n\n/**\n * The compiled, serializable policy definition — the EXACT shape consumed by\n * `schema_extract.js` → Go `PolicyJSON` (CONTRACT-POLICY).\n *\n * - `roles`: the DB roles this policy applies to (`TO` clause). An empty array\n * means the policy applies to PUBLIC (all roles) — the Postgres default.\n * - `using`: the `USING (...)` row-visibility expression, or `null` when none.\n * - `withCheck`: the `WITH CHECK (...)` write-validation expression, or `null`.\n * - `permissive`: `true` for `AS PERMISSIVE` (default), `false` for restrictive.\n */\nexport interface PolicyDef {\n name: string;\n command: PolicyCommand;\n roles: string[];\n using: string | null;\n withCheck: string | null;\n permissive: boolean;\n}\n\n/**\n * Fluent RLS policy builder.\n *\n * Defaults (documented, applied at construction):\n * - `command`: `\"all\"` — applies to every SQL command unless `.for(...)` narrows it.\n * - `roles`: `[\"authenticated\"]` — the common case is \"rule applies to signed-in\n * users\". Call `.to(...)` to override; pass `.to()` with no roles (or never\n * call it after a reset) to target PUBLIC.\n * - `using` / `withCheck`: `null` — no row filter / write check until set.\n * - `permissive`: `true` — `AS PERMISSIVE` (policies OR together).\n *\n * Each method mutates `_def` in place and returns `this`, so the chain is a\n * single builder instance (no per-call allocation, like a tagged-template\n * compile target). The terminal `PolicyDef` is read directly off `_def` by\n * `schema_extract.js`.\n */\n/** Quote an identifier for the policy expression. Table and column names reach\n * here from the schema author; neither is allowed to become syntax. */\nfunction quote(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport class PolicyBuilder {\n readonly _def: PolicyDef;\n\n constructor(name: string) {\n this._def = {\n name,\n command: \"all\",\n roles: [\"authenticated\"],\n using: null,\n withCheck: null,\n permissive: true,\n };\n }\n\n /** Restrict the policy to a single SQL command (default `\"all\"`). */\n for(command: PolicyCommand): this {\n this._def.command = command;\n return this;\n }\n\n /**\n * Set the DB roles the policy applies to (the `TO` clause), replacing any\n * previously-set roles. Call with no arguments to target PUBLIC (all roles).\n *\n * @example\n * policy(\"p\").to(\"authenticated\")\n * policy(\"p\").to(\"authenticated\", \"service_role\")\n * policy(\"p\").to() // PUBLIC\n */\n to(...roles: string[]): this {\n this._def.roles = roles;\n return this;\n }\n\n /** Set the `USING (...)` row-visibility expression (raw SQL). */\n using(sqlExpr: string): this {\n this._def.using = sqlExpr;\n return this;\n }\n\n /**\n * \"Rows of THIS table whose owner the caller is a member of\" — the membership\n * pattern, written so it cannot recurse.\n *\n * THE TRAP IT EXISTS FOR. Written by hand, membership policies point at each\n * other: `channels` is visible to members, so its policy reads\n * `channel_members`; `channel_members` is visible to members, so its policy\n * reads `channels`. Postgres refuses the pair at query time with `infinite\n * recursion detected in policy for relation ...`, and the error names the\n * relation but not the cycle. The way out is asymmetry — the MEMBERSHIP table\n * is protected by `user_id = auth.uid()` and nothing else, and every other\n * table subqueries INTO it. That shape was in the platform's own schema and\n * written down nowhere; a customer recovered it by reading that schema.\n *\n * `(select auth.uid())` rather than a bare call: the scalar subquery is\n * evaluated ONCE per statement instead of per row.\n *\n * @example\n * // channels: visible to members. The membership table gets the simple one.\n * policy(\"member_read\").for(\"select\").to(\"authenticated\")\n * .memberOf(\"channel_members\", \"channel_id\")\n * // → id IN (SELECT \"channel_id\" FROM \"channel_members\"\n * // WHERE \"user_id\" = (select auth.uid()))\n */\n memberOf(\n membershipTable: string,\n foreignKey: string,\n options: { column?: string; userColumn?: string } = {},\n ): this {\n if (this._def.using !== null) {\n // Silently AND-ing the two would hide whichever the author meant; silently\n // replacing would hide the one they wrote. Neither is a thing to guess.\n throw new Error(\n `policy(${this._def.name}).memberOf(): this policy already has a using() expression. ` +\n \"Write one or the other — memberOf IS the using expression.\",\n );\n }\n const column = options.column ?? \"id\";\n const userColumn = options.userColumn ?? \"user_id\";\n this._def.using =\n `${quote(column)} IN (SELECT ${quote(foreignKey)} FROM ${quote(membershipTable)} ` +\n `WHERE ${quote(userColumn)} = (select auth.uid()))`;\n return this;\n }\n\n /** Set the `WITH CHECK (...)` write-validation expression (raw SQL). */\n withCheck(sqlExpr: string): this {\n this._def.withCheck = sqlExpr;\n return this;\n }\n\n /** Set the policy mode: `\"permissive\"` (default, OR-combined) or\n * `\"restrictive\"` (AND-combined). */\n as(mode: PolicyMode): this {\n this._def.permissive = mode === \"permissive\";\n return this;\n }\n}\n\n/**\n * Start authoring an RLS policy. Returns a {@link PolicyBuilder}; the resulting\n * `PolicyBuilder` is accepted directly in a table's `policies: [...]` array\n * (its `_def` is read at schema-extract time).\n *\n * @param name The policy name. Palbase reconciliation keys policies by\n * `(table, name)`, so names must be unique per table.\n */\nexport function policy(name: string): PolicyBuilder {\n return new PolicyBuilder(name);\n}\n","import type { ColumnBuilder } from \"./columns.js\";\nimport { PolicyBuilder } from \"./policy.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { PalbaseExtension } from \"./extensions.js\";\nimport type { RawConstraintDef } from \"./raw.js\";\nimport type { ChatModelRef, EmbeddingModelRef } from \"./embedding.js\";\n\n/**\n * A map of column builders keyed by column name — the value you write under\n * the `columns` key of `defineSchema({ tables: { <name>: { columns } } })`.\n *\n * The default `Record<string, ColumnBuilder>` keeps bare references compiling\n * without a type argument.\n */\nexport type ColumnMap = Record<string, ColumnBuilder>;\n\n/**\n * The author-facing value written under each table key:\n * `{ columns, rls?, policies? }`.\n *\n * - `columns`: the column map (required).\n * - `rls`: enable + FORCE row-level security on this table. **Defaults to\n * `true`**, and is forced on when `policies` is non-empty. A table with RLS\n * and no policies is deny-all, which is the starting state: nothing reads it\n * until a policy says who may. Set `rls: false` only for a genuinely public\n * table — it is an explicit opt-out that a reviewer can grep for, not\n * something you get by forgetting.\n * - `policies`: the RLS policies for this table, authored with `policy(name)`.\n * Each entry may be a {@link PolicyBuilder} (the normal `policy(...)` chain)\n * or a raw {@link PolicyDef} object.\n *\n * The `C` type parameter preserves the precise per-column phantom types so the\n * typed `Database.tables.*` surface keeps inferring insert/row shapes.\n */\n/** Arama metriği — tek kelime; opclass ve operatör bundan türetilir, asla yüzeye çıkmaz (D-5/D-6). */\nexport type SearchMetric = \"cosine\" | \"euclidean\" | \"inner_product\";\n\n/** Bir vektör arama kolu. `model` varsa auto-embed: platform yazma+sorgu embedding'ini üstlenir (D-9). */\nexport interface VectorSearchDecl {\n /** Hedef vector kolonu; tabloda TEK vector kolonu varsa atlanabilir (Go apply çözer, FR-010). */\n column?: string;\n /** Varsa auto-embed. Deskriptor düz veridir — şemayla serileşir (C-3). */\n model?: EmbeddingModelRef;\n /** model varsa ZORUNLU: embed kaynak kolonları = trigger'ın UPDATE OF listesi (C-2). */\n from?: string[];\n metric?: SearchMetric;\n /** Kaynak metin değişince ara-dönem davranışı (yalnız auto-embed'de):\n * \"null\" (vars.) — embedding anında NULL'lanır; satır yeni vektör yazılana\n * dek anlamsal aramada aday değildir. Bayat eşleşme asla servis edilmez.\n * \"keep\" — eski vektör aramada kalır, platform yenisini yazınca sessizce\n * değişir. Görünürlük penceresi sıfır; bedeli saniyeler süren bayat\n * eşleşme riski (Confluence-tipi sync yükleri için). */\n staleness?: \"null\" | \"keep\";\n}\n\n/** Tablonun arama beyanı — İKİ biçim (D-007, tek yüzey):\n *\n * YENİ (önerilen): `{ from, model, ... }` — `from` kolonları hem FTS'e hem\n * embed'e girer. Tabloda vector kolonu declare edilmişse SATIR-modu; yoksa\n * CHUNK-modu otomatiktir (D-010): vektörler türev `__palbase_chunks`\n * tablosunda yaşar, içerik otomatik bölünür. `text: false` FTS'i kapatır,\n * `text: [..]` FTS kolonlarını from'dan ayırır. `chunks` yalnız ince ayar.\n *\n * ESKİ: `text: string[]` + `vector: {...}` — aynen çalışır, wire çıktısı\n * bayt-aynı kalır (NFR-B1). İki biçim KARIŞTIRILAMAZ. */\nexport interface SearchDecl {\n text?: string[] | boolean;\n vector?: VectorSearchDecl | VectorSearchDecl[];\n /** Yeni biçim: arama kaynağı kolonlar (FTS + embed). Varlığı yeni biçimi seçer. */\n from?: string[];\n /** Yeni biçim: auto-embed modeli (zorunlu — BYO için eski biçimi kullanın). */\n model?: EmbeddingModelRef;\n metric?: SearchMetric;\n staleness?: \"null\" | \"keep\";\n /** Chunk-modu ince ayarı (yalnız vector kolonsuz tabloda anlamlı). */\n chunks?: { size?: number; overlap?: number };\n /** Sorgu-yeniden-yazımı: tek yönlü eş anlamlı haritası (FR-026). */\n synonyms?: Record<string, string[]>;\n /** Geçerlilik kolonları türetilir; arama varsayılan yalnız günceli tarar (FR-029). */\n validity?: boolean;\n}\n\n/** Hafıza beyanı (FR-032, D-019): kaynak tablonun yazımlarından platform\n * fact damıtır ve `into` tablosuna yazar. Hedef NORMAL declared tablodur —\n * kendi search/unique/validity beyanlarıyla. Okuma = Database.search(into).\n * subject default \"owner\": fact'in kime ait olduğu kolonu (iki tabloda da). */\nexport interface MemoryDecl {\n from: string[];\n into: string;\n extract: ChatModelRef;\n subject?: string;\n}\n\nexport interface TableInput<C extends ColumnMap = ColumnMap> {\n columns: C;\n rls?: boolean;\n policies?: (PolicyBuilder | PolicyDef)[];\n /** Composite/named primary key (ordered column names). Omit for single-column inline .primaryKey(). */\n primaryKey?: string[];\n /** Named multi-column UNIQUE constraints. */\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects (EXCLUDE, triggers, views) that the typed DSL cannot express. */\n raw?: RawConstraintDef[];\n /**\n * Named first-class CHECK constraints. Diffed by NAME with a BODY compare:\n * a changed `expr` (after pg normalization) recreates the constraint\n * (DROP + ADD). `expr` is trusted SQL emitted verbatim (like policy USING),\n * `name` is identifier-validated.\n */\n checks?: { name: string; expr: string }[];\n /**\n * Plain (non-unique) btree indexes over an ordered column list, emitted as\n * standalone `CREATE INDEX [IF NOT EXISTS] name ON table (col1, col2)`\n * statements (NOT a table clause — a separate migration statement category).\n * Structural compare by NAME (no expression normalization). `name` and each\n * column are identifier-validated by the Go differ.\n *\n * Scope: columns-only plain btree. Partial (`where`) and expression indexes\n * are a deliberate follow-up — modelling them needs the same raw-SQL\n * normalization round-trip CHECK uses (Task 10), so they are NOT in this\n * type yet to avoid a half-working partial-index path.\n */\n indexes?: { name: string; columns: string[] }[];\n /** Arama beyanı — bkz. SearchDecl. */\n search?: SearchDecl;\n /** Hafıza beyanı — bkz. MemoryDecl (FR-032). */\n memory?: MemoryDecl;\n}\n\n/**\n * A table definition — the runtime value the Go runtime's `schema_extract.js`\n * reads. It keys tables by `tableDef.name`, reads `tableDef.columns` for the\n * column DDL, and `tableDef.rls` + `tableDef.policies` for RLS.\n *\n * `defineSchema` derives `name` from the object key, so authors never repeat\n * the table name. `rls`/`policies` are always present after normalization\n * (defaulted to `true`/`[]`).\n *\n * The `C` type parameter preserves the precise per-column phantom types so that\n * downstream mapped types (InsertShape, RowShape) can discriminate on them.\n */\nexport interface TableDef<C extends ColumnMap = ColumnMap> {\n name: string;\n columns: C;\n rls: boolean;\n policies: PolicyDef[];\n primaryKey?: string[];\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects emitted verbatim on deploy. Tracked by name. */\n raw?: RawConstraintDef[];\n /** Named first-class CHECK constraints. Diffed by name + (normalized) body. */\n checks?: { name: string; expr: string }[];\n /** Plain btree indexes (columns-only), emitted as standalone CREATE INDEX. Diffed by name. */\n indexes?: { name: string; columns: string[] }[];\n /** Arama beyanı, doğrulanmış ve taşınmış hali. */\n search?: SearchDecl;\n /** Hafıza beyanı, doğrulanmış ve taşınmış hali (FR-032). */\n memory?: MemoryDecl;\n}\n\n/**\n * A schema definition containing multiple tables, keyed by table name.\n *\n * The `T` type parameter preserves the exact `TableDef<...>` type for each\n * table so that `SchemaDef[\"tables\"][\"rooms\"]` resolves to the precise\n * `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.\n */\nexport interface SchemaDef<\n T extends Record<string, TableDef> = Record<string, TableDef>,\n> {\n tables: T;\n /** Postgres extensions to install on deploy. Normalized to `[]` when absent. */\n extensions: PalbaseExtension[];\n}\n\n/** The author-facing input to `defineSchema` — a `tables` map whose keys are\n * the table names and whose values are `{ columns, rls?, policies? }`, plus an\n * optional `extensions` allowlist. */\nexport interface SchemaInput<\n T extends Record<string, TableInput> = Record<string, TableInput>,\n> {\n tables: T;\n /**\n * Postgres extensions to enable for this project, e.g. `[\"vector\"]`.\n * Config-as-code: installed by the deploy (CREATE EXTENSION … SCHEMA\n * extensions) with the privileged deploy connection. The type is an\n * allowlist union, so unsupported names fail typecheck.\n */\n extensions?: PalbaseExtension[];\n}\n\n/** Map the author's `{ tables: { <name>: { columns } } }` input to the\n * `{ tables: { <name>: TableDef<columns> } }` runtime/type shape, threading the\n * per-table column map `T[K][\"columns\"]` so column-level inference survives. */\ntype TablesFromInput<T extends Record<string, TableInput>> = {\n [K in keyof T]: TableDef<T[K][\"columns\"]>;\n};\n\n/** Normalize a single `policies` entry into a plain `PolicyDef` (read off a\n * `PolicyBuilder._def`, or passed through when already a `PolicyDef`). */\nfunction toPolicyDef(p: PolicyBuilder | PolicyDef): PolicyDef {\n return p instanceof PolicyBuilder ? p._def : p;\n}\n\n/**\n * Define a schema. The table NAME comes from the object key. Each table value\n * is `{ columns, rls?, policies? }`:\n *\n * export default defineSchema({\n * tables: {\n * todos: {\n * columns: {\n * id: uuid().primaryKey().defaultRandom(),\n * owner: text().notNull(),\n * title: text().notNull(),\n * },\n * rls: true,\n * policies: [\n * policy(\"owner_all\").for(\"all\").to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\")\n * .withCheck(\"owner = (select auth.uid())\"),\n * ],\n * },\n * },\n * });\n *\n * The returned value is\n * `{ tables: { todos: { name, columns, rls, policies } } }` — the exact shape\n * the runtime schema extractor parses. Per-column phantom types are preserved\n * so `Database.tables.todos.insert({...})` stays typed.\n *\n * RLS normalization: `rls` defaults to **`true`**, `policies` to `[]`. A table\n * that declares neither is therefore deny-all — nothing reads it until a policy\n * says who may, which is the safe starting point rather than a bug. Declare\n * `rls: false` for a genuinely public table; that is an explicit, greppable\n * statement of intent instead of an omission. When `policies` is non-empty,\n * `rls` is forced on (ENABLE + FORCE) regardless of the declared flag — a table\n * with policies must have RLS enabled or the policies would be inert.\n */\nexport function defineSchema<T extends Record<string, TableInput>>(\n input: SchemaInput<T>,\n): SchemaDef<TablesFromInput<T>> {\n const tables = {} as TablesFromInput<T>;\n for (const name of Object.keys(input.tables) as (keyof T)[]) {\n const table = input.tables[name];\n // `noUncheckedIndexedAccess` widens the index access to `… | undefined`,\n // but `name` comes straight from `Object.keys(input.tables)`, so the entry\n // always exists. Guard to narrow without a cast.\n if (table === undefined) continue;\n const policies = (table.policies ?? []).map(toPolicyDef);\n // Fail closed. RLS is on unless the schema explicitly says `rls: false`, and\n // policies force it on regardless — a policy on a table without RLS enabled\n // is inert, so declaring both is a contradiction that resolves towards the\n // safe reading.\n //\n // This defaulted to `false` until 2026-08-07, which meant a table nobody\n // thought about had no row-level security while `typed-db.ts` documented the\n // default `Database.*` path as RLS-enforced. Both cannot be true, and the\n // live proof settled which one was not: user B read user A's row in full\n // through the typed client, while the same request against a table declaring\n // `rls: true` returned 0 of 165 rows\n // (docs/superpowers/uat/2026-08-07-rls-fail-open-proof.md). With no policies\n // this is deny-all, so an unconsidered table now returns nothing instead of\n // returning everything to everyone.\n const rls = policies.length > 0 || table.rls !== false;\n const tableDef: TableDef<T[typeof name][\"columns\"]> = {\n name: name as string,\n columns: table.columns,\n rls,\n policies,\n };\n if (table.primaryKey !== undefined) tableDef.primaryKey = table.primaryKey;\n if (table.unique !== undefined) tableDef.unique = table.unique;\n if (table.raw !== undefined && table.raw.length > 0) tableDef.raw = table.raw.slice();\n if (table.checks !== undefined && table.checks.length > 0) tableDef.checks = table.checks.slice();\n if (table.indexes !== undefined && table.indexes.length > 0) tableDef.indexes = table.indexes.slice();\n if (table.search !== undefined) {\n const s = table.search;\n // Erken, beyan-anı doğrulama (apply doğrulamasını İKAME ETMEZ — yazım\n // hatası deploy'a gitmeden yazarın yüzüne söylenir).\n if (s.from !== undefined) {\n // YENİ biçim (D-007). Eski alanlarla karışım tek biçime zorlanır:\n // iki yarım beyanın hangisinin kazandığını okuyucu bilemez.\n if (s.vector !== undefined) {\n throw new Error(\n `table ${String(name)}: search beyanında tek biçim kullanın — 'from' (yeni) ile 'vector' (eski) birlikte olamaz`,\n );\n }\n if (s.from.length === 0) {\n throw new Error(`table ${String(name)}: search.from boş olamaz`);\n }\n if (s.model === undefined) {\n throw new Error(\n `table ${String(name)}: search.from model'siz anlamsız — auto-embed için model verin (BYO için eski 'vector' biçimini kullanın)`,\n );\n }\n if (Array.isArray(s.text) && s.text.length === 0) {\n throw new Error(`table ${String(name)}: search.text boş dizi olamaz — FTS istemiyorsan text: false yazın`);\n }\n } else {\n // ESKİ biçim — davranış ve hata metinleri aynen (NFR-B1'in DX yarısı).\n if (typeof s.text === \"boolean\") {\n throw new Error(`table ${String(name)}: text:${String(s.text)} yalnız yeni biçimde ('from' ile) geçerli`);\n }\n if (s.text === undefined && s.vector === undefined) {\n throw new Error(\n `table ${String(name)}: search beyanı boş — en az bir kol (text ya da vector) verin, yoksa alanı hiç yazmayın`,\n );\n }\n if (s.text !== undefined && s.text.length === 0) {\n throw new Error(`table ${String(name)}: search.text boş olamaz — FTS kolu istemiyorsan alanı hiç yazma`);\n }\n const legs = s.vector === undefined ? [] : Array.isArray(s.vector) ? s.vector : [s.vector];\n for (const leg of legs) {\n if (leg.model !== undefined && (leg.from === undefined || leg.from.length === 0)) {\n throw new Error(`table ${String(name)}: search.vector.model beyan edildi ama 'from' yok — embed kaynağı kolonlar zorunlu (C-2)`);\n }\n if (leg.model === undefined && leg.from !== undefined) {\n throw new Error(`table ${String(name)}: search.vector.from model'siz anlamsız — auto-embed için model verin`);\n }\n }\n }\n tableDef.search = s;\n }\n if (table.memory !== undefined) {\n if (table.memory.from.length === 0) {\n throw new Error(`table ${String(name)}: memory.from boş olamaz`);\n }\n tableDef.memory = table.memory;\n }\n tables[name] = tableDef;\n }\n // memory beyanları TABLOLAR-ARASI doğrulanır (into/subject/fact) — tüm\n // tablolar kurulduktan sonra: beyan sırasına bağımlılık olmasın (FR-032).\n for (const [name, def] of Object.entries(tables)) {\n const m = (def as TableDef).memory;\n if (m === undefined) continue;\n const target = Object.values(tables).find((t) => (t as TableDef).name === m.into) as TableDef | undefined;\n if (target === undefined) {\n throw new Error(`table ${name}: memory.into \"${m.into}\" şemada declared değil`);\n }\n const subject = m.subject ?? \"owner\";\n if (!(subject in (def as TableDef).columns)) {\n throw new Error(`table ${name}: memory.subject \"${subject}\" kolonu kaynak tabloda yok`);\n }\n if (!(subject in target.columns)) {\n throw new Error(`table ${name}: memory.subject \"${subject}\" kolonu hedef \"${m.into}\" tablosunda yok`);\n }\n const factCol = target.columns[\"fact\"];\n const factDef = factCol !== undefined && \"_def\" in (factCol as object)\n ? (factCol as { _def: { type?: string } })._def\n : (factCol as { type?: string } | undefined);\n if (factDef === undefined || factDef.type !== \"text\") {\n throw new Error(`table ${name}: memory.into \"${m.into}\" tablosunda \"fact\" (text) kolonu zorunlu`);\n }\n for (const c of m.from) {\n if (!(c in (def as TableDef).columns)) {\n throw new Error(`table ${name}: memory.from kolonu \"${c}\" kaynak tabloda yok`);\n }\n }\n }\n // Dedupe + normalize extensions (order-independent; deploy resolves deps).\n const extensions = [...new Set(input.extensions ?? [])];\n return { tables, extensions };\n}\n","// The wire shape of a declared schema — what the deploy reads.\n//\n// `defineSchema(...)` produces a value full of builders and phantom types, which\n// is the right shape for authoring and the wrong shape for anything outside this\n// process. The deploy is Go: it introspects the live database, diffs it against\n// the declaration, and applies the difference. So the declaration has to leave\n// TypeScript as data, and this file is where that happens.\n//\n// It lives in the SDK because the SDK owns the DSL. The alternative — a script\n// beside the deploy that reaches into `._def` — is a second reading of a private\n// shape, and it drifts the moment a column gains a property: the DSL keeps\n// working, the emitter silently omits it, and the database is missing something\n// nobody can see in the source.\n//\n// The field names below are a CONTRACT with Go's `schema.SchemaJSON`. Renaming\n// one here without renaming it there produces a declaration that parses to\n// something emptier than it was — the failure mode being a column, a policy, or\n// a whole table that quietly never gets created.\nimport type { ColumnBuilder, ColumnDef } from \"./columns.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { MemoryDecl, SchemaDef, SearchDecl, TableDef } from \"./schema.js\";\n\n/** One column, flattened. Mirrors Go's `schema.ColumnJSON`. */\nexport interface ColumnJSON {\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n renamedFrom?: string;\n /** See Go's `schema.ColumnJSON.Ignored` — the contraction gate's only signal. */\n ignored?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: string;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n dimensions?: number;\n}\n\n/** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */\nexport interface PolicyJSON {\n name: string;\n command: string;\n roles: string[];\n using: string | null;\n withCheck: string | null;\n permissive: boolean;\n}\n\n/** One table. Mirrors Go's `schema.TableJSON`. */\nexport interface TableJSON {\n name: string;\n columns: Record<string, ColumnJSON>;\n rls: boolean;\n policies: PolicyJSON[];\n primaryKey?: string[];\n uniqueConstraints?: { name: string; columns: string[] }[];\n rawConstraints?: { name: string; up: string; down: string | null }[];\n checks?: { name: string; expr: string }[];\n indexes?: { name: string; columns: string[] }[];\n search?: SearchJSON;\n memory?: MemoryJSON;\n}\n\n/** C-11 wire şekli — Go'nun MemoryJSON'ıyla alan-adı sözleşmesi (D-019).\n * Beyansız tablolarda alan OMIT — eski şemalar bayt-aynı (NFR-B1). */\nexport interface MemoryJSON {\n from: string[];\n into: string;\n subject?: string;\n extract: { provider: string; model: string };\n}\n\n/** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */\nexport interface SchemaJSON {\n tables: Record<string, TableJSON>;\n extensions: string[];\n}\n\n/** The definition behind a column, whichever side of the builder it arrives on. */\nfunction defOf(column: ColumnBuilder | ColumnDef): ColumnDef {\n return \"_def\" in column ? column._def : column;\n}\n\nfunction columnToJSON(column: ColumnBuilder | ColumnDef): ColumnJSON {\n const def = defOf(column);\n const out: ColumnJSON = {\n type: def.type,\n nullable: def.nullable,\n primaryKey: def.primaryKey,\n };\n // Every optional field is omitted rather than emitted as undefined: Go\n // distinguishes \"absent\" from \"present and empty\" on several of these, and a\n // `defaultValue: null` is a real default that says NULL.\n if (def.defaultValue !== undefined) out.defaultValue = def.defaultValue;\n if (def.defaultRandom === true) out.defaultRandom = true;\n if (def.defaultNow === true) out.defaultNow = true;\n if (def.renamedFrom !== undefined) out.renamedFrom = def.renamedFrom;\n // Go'daki schema.ColumnJSON'un aynası. `omitempty` karşılığı: yalnız TRUE ise yazılır,\n // böylece işaretsiz bir şemanın JSON'u bu alandan önceki hâliyle byte-eş kalır.\n if (def.ignored === true) out.ignored = true;\n if (def.references !== undefined) {\n out.references = { table: def.references.table, column: def.references.column };\n }\n if (def.onDeleteAction !== undefined) out.onDeleteAction = def.onDeleteAction;\n if (def.enumName !== undefined) out.enumName = def.enumName;\n if (def.enumValues !== undefined) out.enumValues = [...def.enumValues];\n if (def.unique === true) out.unique = true;\n if (def.dimensions !== undefined) out.dimensions = def.dimensions;\n return out;\n}\n\nfunction policyToJSON(policy: PolicyDef): PolicyJSON {\n return {\n name: policy.name,\n command: policy.command ?? \"all\",\n roles: policy.roles ? [...policy.roles] : [],\n // null rather than omitted: a policy with no USING clause is a different\n // thing from one whose clause the emitter forgot, and Go reads the\n // difference.\n using: policy.using ?? null,\n withCheck: policy.withCheck ?? null,\n permissive: policy.permissive !== false,\n };\n}\n\n/** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5).\n * `mode`/`chunks` yalnız yeni-biçim chunk-modunda emit edilir (D-010);\n * satır-modu ve eski biçim bayt-aynı kalır (NFR-B1). */\nexport interface SearchJSON {\n text?: { columns: string[] };\n vector?: {\n column?: string;\n metric: string;\n embed?: { provider: string; model: string; from: string[]; apiKeyName?: string; dimensions?: number; baseURL?: string };\n staleness?: \"null\" | \"keep\";\n mode?: \"row\" | \"chunks\";\n chunks?: { sizeChars?: number; overlapChars?: number };\n }[];\n /** FR-026: sorgu-yeniden-yazımı haritası — beyan yoksa OMIT (NFR-B1). */\n synonyms?: Record<string, string[]>;\n /** C-1: sonuç yeniden-sıralama beyanı — beyan yoksa OMIT. */\n /** FR-029: geçerlilik türevleri — beyan yoksa OMIT. */\n validity?: boolean;\n}\n\n/** T020 (C-1): iki biçimin de üst-düzey ortak alanları — beyan yoksa OMIT,\n * boş synonyms haritası da OMIT (NFR-B1 baytları kımıldamaz). */\nfunction commonSearchFields(search: SearchDecl, out: SearchJSON): void {\n if (search.synonyms !== undefined && Object.keys(search.synonyms).length > 0) {\n out.synonyms = Object.fromEntries(\n Object.entries(search.synonyms).map(([word, alts]) => [word, [...alts]]),\n );\n }\n if (search.validity === true) out.validity = true;\n}\n\n/** Beyanı normalize eder: vector her zaman DİZİ, metric her zaman dolu (vars. cosine),\n * authoring'deki `from`/`model` wire'da `embed` altında toplanır. Alan yoksa OMIT —\n * search'süz şema bayt-aynı kalır (NFR-006). */\nfunction searchToJSON(search: SearchDecl, vectorColumn: string | undefined): SearchJSON {\n if (search.from !== undefined && search.model !== undefined) {\n // YENİ biçim (D-007): from tek listedir — FTS'i de embed'i de besler.\n // Mod ŞEMADAN türer (D-010): tabloda vector kolonu varsa satır-modu\n // (column yazılır, mode OMIT — eski davranışla aynı wire), yoksa\n // chunk-modu (mode:\"chunks\", column yok — vektörler türev tabloda).\n const out: SearchJSON = {};\n const textCols =\n search.text === false ? undefined : Array.isArray(search.text) && search.text.length > 0 ? search.text : search.from;\n if (textCols !== undefined) out.text = { columns: [...textCols] };\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: search.metric ?? \"cosine\" };\n if (vectorColumn !== undefined) v.column = vectorColumn;\n v.embed = {\n provider: search.model.provider,\n model: search.model.model,\n from: [...search.from],\n ...(search.model.apiKeyName !== undefined ? { apiKeyName: search.model.apiKeyName } : {}),\n ...(search.model.dimensions !== undefined ? { dimensions: search.model.dimensions } : {}),\n ...(search.model.baseURL !== undefined ? { baseURL: search.model.baseURL } : {}),\n };\n if (search.staleness !== undefined) v.staleness = search.staleness;\n if (vectorColumn === undefined) {\n v.mode = \"chunks\";\n if (search.chunks !== undefined) {\n const c: NonNullable<typeof v.chunks> = {};\n if (search.chunks.size !== undefined && search.chunks.size > 0) c.sizeChars = search.chunks.size;\n if (search.chunks.overlap !== undefined && search.chunks.overlap > 0) c.overlapChars = search.chunks.overlap;\n if (Object.keys(c).length > 0) v.chunks = c;\n }\n }\n out.vector = [v];\n commonSearchFields(search, out);\n return out;\n }\n const out: SearchJSON = {};\n // Eski biçimde text yalnız dizi olabilir (boolean'ı defineSchema zaten\n // reddediyor); Array.isArray hem tipi daraltır hem o sözleşmeyi belgeler.\n if (Array.isArray(search.text) && search.text.length > 0) out.text = { columns: [...search.text] };\n const legs = search.vector === undefined ? []\n : Array.isArray(search.vector) ? search.vector : [search.vector];\n if (legs.length > 0) {\n out.vector = legs.map((leg) => {\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: leg.metric ?? \"cosine\" };\n if (leg.column !== undefined) v.column = leg.column;\n if (leg.staleness !== undefined) v.staleness = leg.staleness;\n if (leg.model !== undefined) {\n v.embed = {\n provider: leg.model.provider,\n model: leg.model.model,\n from: [...(leg.from ?? [])],\n ...(leg.model.apiKeyName !== undefined ? { apiKeyName: leg.model.apiKeyName } : {}),\n ...(leg.model.dimensions !== undefined ? { dimensions: leg.model.dimensions } : {}),\n ...(leg.model.baseURL !== undefined ? { baseURL: leg.model.baseURL } : {}),\n };\n }\n return v;\n });\n }\n commonSearchFields(search, out);\n return out;\n}\n\nfunction memoryToJSON(m: MemoryDecl): MemoryJSON {\n return {\n from: [...m.from],\n into: m.into,\n ...(m.subject !== undefined ? { subject: m.subject } : {}),\n extract: { provider: m.extract.provider, model: m.extract.model },\n };\n}\n\nfunction tableToJSON(table: TableDef): TableJSON {\n const columns: Record<string, ColumnJSON> = {};\n for (const [name, column] of Object.entries(table.columns)) {\n columns[name] = columnToJSON(column);\n }\n\n const out: TableJSON = {\n name: table.name,\n columns,\n // Read, not re-derived. `defineSchema` already resolves the fail-closed\n // default (RLS on unless the author wrote `rls: false`, and forced on by any\n // policy), and a second copy of a SECURITY default is exactly the thing that\n // drifts — the direction it drifted last time was \"expose everything\", and\n // the live proof was one user reading another's rows.\n rls: table.rls,\n policies: (table.policies ?? []).map(policyToJSON),\n };\n\n if (table.primaryKey !== undefined && table.primaryKey.length > 0) {\n out.primaryKey = [...table.primaryKey];\n }\n if (table.unique !== undefined && table.unique.length > 0) {\n out.uniqueConstraints = table.unique.map((u) => ({ name: u.name, columns: [...u.columns] }));\n }\n if (table.raw !== undefined && table.raw.length > 0) {\n out.rawConstraints = table.raw.map((r) => ({\n name: r.name,\n up: r.up,\n down: r.down ?? null,\n }));\n }\n if (table.checks !== undefined && table.checks.length > 0) {\n out.checks = table.checks.map((c) => ({ name: c.name, expr: c.expr }));\n }\n if (table.indexes !== undefined && table.indexes.length > 0) {\n out.indexes = table.indexes.map((i) => ({ name: i.name, columns: [...i.columns] }));\n }\n if (table.search !== undefined) {\n // D-010 mod kararının tek girdisi: tabloda dimensions'lı (vector) kolon\n // adı. Birden çoksa ilkini yazmak YANLIŞ olurdu — o durum eski biçimin\n // işidir ve yeni biçim + çoklu vector kolonu apply'da reddedilir.\n const vectorColumn = Object.entries(columns).find(([, c]) => c.dimensions !== undefined)?.[0];\n const sj = searchToJSON(table.search, vectorColumn);\n if (sj.text !== undefined || sj.vector !== undefined) out.search = sj;\n }\n if (table.memory !== undefined) {\n out.memory = memoryToJSON(table.memory);\n }\n return out;\n}\n\n/**\n * Serialize a `defineSchema(...)` result into the JSON the deploy applies.\n *\n * Keyed by the SQL table name rather than by the author's object key, because\n * that is the name the live database answers to — and the diff on the other side\n * compares against what it introspected.\n */\nexport function toSchemaJSON(schema: SchemaDef): SchemaJSON {\n const tables: Record<string, TableJSON> = {};\n for (const table of Object.values(schema.tables)) {\n const json = tableToJSON(table);\n tables[json.name] = json;\n }\n return { tables, extensions: [...new Set(schema.extensions ?? [])] };\n}\n","/**\n * channels.ts — the realtime channel authorization DSL (spec C-5).\n *\n * `defineChannels({...})` is evaluated at bundle load; the declaration is\n * anchored on globalThis under Symbol.for (the error-registry.ts pattern) so\n * the runtime — a separate module instance — reads the SAME object. The runtime\n * empties that slot before each bundle import and puts it back afterwards, so\n * the declaration belongs to the bundle that made it and not to the process.\n * Entry ORDER is the object's key order and is semantic: first match wins.\n *\n * Undeclared channels are DENIED by the server (fail-closed). ownerOnly()\n * patterns resolve with ZERO server hops; custom entries' authorize() runs\n * in the customer's own runtime with the request scope a controller gets.\n */\n\nconst CHANNELS: unique symbol = Symbol.for(\"palbase.backend.channels\") as never;\n\nexport interface ChannelGrant {\n subscribe: boolean;\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n}\n\nexport interface ChannelAuthorizeCtx {\n user: { id: string };\n params: Record<string, string>;\n}\n\ninterface OwnerEntry { kind: \"owner\" }\ninterface PublicEntry {\n kind: \"public\";\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n}\n/** What a handler receives: who published, on which channel, and what. */\nexport interface ChannelHandlerCtx {\n user: { id: string };\n params: Record<string, string>;\n channel: string;\n event: string;\n payload: Record<string, unknown>;\n}\n\ninterface CustomEntry {\n authorize: (ctx: ChannelAuthorizeCtx) => ChannelGrant | null | Promise<ChannelGrant | null>;\n /**\n * Take over publishes on this channel instead of fanning them out.\n *\n * Without it, `channel.send(...)` is relayed to the other subscribers\n * verbatim — fine for a chat message, wrong for anything the client should\n * not be trusted to assert. A bid, a vote, a game move is a REQUEST, and the\n * result is whatever this function decides and then publishes (through\n * `Realtime.broadcast` or `Realtime.state.set`).\n *\n * A function rather than the name of a route: `authorize` is already one and\n * runs in this same scope, so naming an endpoint would mean inventing a\n * resolution step for no gain.\n */\n handler?: (ctx: ChannelHandlerCtx) => void | Promise<void>;\n}\nexport type ChannelEntry = OwnerEntry | PublicEntry | CustomEntry;\nexport type ChannelsInput = Record<string, ChannelEntry>;\n\nexport interface ChannelsDef {\n entries: Array<{\n pattern: string;\n kind: \"owner\" | \"public\" | \"custom\";\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n authorize?: CustomEntry[\"authorize\"];\n handler?: CustomEntry[\"handler\"];\n }>;\n}\n\n/** Full-access-to-the-owner pattern: the pattern must carry EXACTLY one {param};\n * the server compares its value to the verified token subject with zero hops. */\nexport function ownerOnly(): OwnerEntry {\n return { kind: \"owner\" };\n}\n\n/** Anyone with a valid token may subscribe; publish/state are explicit opt-ins. */\nexport function publicChannel(\n opts: { publish?: boolean; state?: { read?: boolean; write?: boolean } } = {},\n): PublicEntry {\n return { kind: \"public\", publish: opts.publish ?? false, state: opts.state };\n}\n\nfunction paramCount(pattern: string): number {\n return pattern.split(\":\").filter((s) => s.startsWith(\"{\") && s.endsWith(\"}\")).length;\n}\n\nexport function defineChannels(map: ChannelsInput): ChannelsDef {\n const entries: ChannelsDef[\"entries\"] = [];\n for (const [pattern, entry] of Object.entries(map)) {\n if (\"kind\" in entry && entry.kind === \"owner\") {\n if (paramCount(pattern) !== 1) {\n throw new Error(\n `defineChannels: ownerOnly() pattern \"${pattern}\" must carry exactly one {param} ` +\n `(its value is compared to the token subject)`,\n );\n }\n entries.push({ pattern, kind: \"owner\" });\n } else if (\"kind\" in entry && entry.kind === \"public\") {\n entries.push({ pattern, kind: \"public\", publish: entry.publish, state: entry.state });\n } else {\n const c = entry as CustomEntry;\n entries.push({ pattern, kind: \"custom\", authorize: c.authorize, handler: c.handler });\n }\n }\n const def: ChannelsDef = { entries };\n\n // A SECOND, DIFFERENT declaration is a hard error rather than an overwrite.\n //\n // The same bundle can legitimately be evaluated twice in one process — the\n // error registry beside this file documents exactly that case — so an\n // identical re-declaration passes silently. But two DIFFERENT declarations\n // mean two channels files, and overwriting would delete the first one's\n // channels. Undeclared channels are DENIED, so the symptom would be joins\n // refused in production for channels the developer can see declared in their\n // own source, with nothing anywhere saying why. Loud here beats silent there.\n //\n // \"Already\" means WITHIN ONE BUNDLE LOAD. The runtime hands each import an\n // empty slot, so this compares two calls from the same bundle — which is what\n // it was written for. It used to reach across imports as well, and then a\n // deploy that merely ADDED a channel was refused as a second channels file,\n // with a message pointing at a file the customer did not have.\n const carrier = globalThis as Record<symbol, unknown>;\n const existing = carrier[CHANNELS] as ChannelsDef | undefined;\n if (existing && !sameDeclaration(existing, def)) {\n throw new Error(\n `defineChannels: channels were already declared (${existing.entries.length} ` +\n `pattern(s): ${existing.entries.map((e) => e.pattern).join(\", \")}). ` +\n `A project declares its channels ONCE — a second call would overwrite the ` +\n `first, and channels nobody declared are refused.`,\n );\n }\n carrier[CHANNELS] = def;\n return def;\n}\n\n/**\n * One entry as the runtime will compile it, rendered for comparison.\n *\n * NORMALIZED, because the runtime normalizes: `collectChannels` applies\n * `?? false` to publish and both state flags before the table goes on the wire.\n * Comparing the raw entries called two spellings of ONE entry a conflict —\n * `publicChannel()` fills `publish: false` where a hand-written\n * `{ kind: \"public\" }` leaves it undefined, and the two produce a byte-identical\n * table. There is one source of truth for what an entry IS, and it is the row.\n *\n * The authorize function is compared by SOURCE TEXT. Comparing the closures\n * themselves is wrong — two evaluations of one module produce two distinct\n * functions for the same source, which is the case this guard has to let\n * through — but comparing only `Boolean(fn)` called two unrelated\n * authorization rules \"the same declaration\", so the guard stayed silent while\n * one channel's access rule was swapped for another's. Same source, same text;\n * different logic, different text. Not exhaustive (two closures over different\n * captured values share a source), and better than a boolean by the whole\n * distance between \"some rule\" and \"this rule\".\n */\nfunction wireRow(e: ChannelsDef[\"entries\"][number]): string {\n return JSON.stringify([\n e.pattern,\n e.kind,\n e.publish ?? false,\n e.state?.read ?? false,\n e.state?.write ?? false,\n // The handler is compared by SOURCE, like authorize: two evaluations of one\n // module give the same text, while different logic gives different text.\n e.handler ? e.handler.toString() : \"\",\n e.authorize ? e.authorize.toString() : \"\",\n ]);\n}\n\n/** Two declarations are the same when they compile to the same rows in the same\n * ORDER — order is semantic here (first match wins). */\nfunction sameDeclaration(a: ChannelsDef, b: ChannelsDef): boolean {\n if (a.entries.length !== b.entries.length) return false;\n return a.entries.every((x, i) => wireRow(x) === wireRow(b.entries[i]!));\n}\n","/**\n * Postgres extensions a Palbase project can enable from its schema.\n *\n * Extensions are config-as-code: declare them in `defineSchema({ extensions })`\n * and the deploy installs them (CREATE EXTENSION … SCHEMA extensions) using the\n * deploy path's privileged connection. They are NOT toggled live from Studio —\n * CREATE EXTENSION requires a superuser role that only the deploy path holds.\n *\n * The list is an allowlist (a string-literal union) so editors autocomplete the\n * supported names and a typo fails typecheck. It is intentionally extensible:\n * add a name here (+ confirm the base image ships it) to support more.\n */\nexport const PALBASE_EXTENSIONS = [\n // Search & text\n \"vector\", // pgvector: AI embeddings + vector similarity search (semantic search / RAG).\n // NB: the Postgres extension is named \"vector\", not \"pgvector\" — declare \"vector\".\n \"pg_trgm\", // trigram fuzzy / typo-tolerant text search\n \"unaccent\", // accent-insensitive text search\n \"citext\", // case-insensitive text type\n // Geospatial / location\n \"cube\", // multi-dimensional cubes (dependency of earthdistance)\n \"earthdistance\", // great-circle distance (needs cube)\n // Data types & structures\n \"hstore\", // key/value pairs in a single column\n \"ltree\", // hierarchical tree-structured labels\n // Indexing & constraints\n \"btree_gist\", // GiST operator classes for scalar types — needed for EXCLUDE\n // constraints that mix \"=\" with a range/&& overlap (e.g. no-double-booking).\n // Scheduling\n // Crypto / ids (also installed by default; listable for explicitness)\n \"pgcrypto\", // cryptographic functions (hashing, encryption)\n \"uuid-ossp\", // UUID generation functions\n] as const;\n\n/** A Postgres extension supported by Palbase (allowlist union). */\nexport type PalbaseExtension = (typeof PALBASE_EXTENSIONS)[number];\n\n/**\n * Extensions that depend on another extension. The deploy installs\n * dependencies first; declaring `earthdistance` without `cube` still works\n * because the deploy resolves the order, but listing both is clearer.\n */\nexport const EXTENSION_DEPENDENCIES: Partial<Record<PalbaseExtension, PalbaseExtension[]>> = {\n earthdistance: [\"cube\"],\n};\n\n/** Runtime guard: is `name` a supported Palbase extension? */\nexport function isPalbaseExtension(name: string): name is PalbaseExtension {\n return (PALBASE_EXTENSIONS as readonly string[]).includes(name);\n}\n","/** On delete action for foreign key references. */\nexport type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';\n\n/**\n * The ON DELETE actions permitted on a foreign key to the built-in auth users\n * (`auth.users`). Both let a user's rows be removed (`cascade`) or detached\n * (`set null`) when the account is erased; `restrict` / `no action` would BLOCK\n * erasure and are therefore excluded. This is the CLIENT-SIDE mirror of the\n * server's auth-FK deletion policy — the server (validateAuthUserFK) is the real\n * boundary, this narrows the type so the common mistake is caught at compile time.\n */\nexport type AuthUserOnDelete = Extract<OnDeleteAction, 'cascade' | 'set null'>;\n\n/** Column type identifiers. */\nexport type ColumnType =\n | 'uuid'\n | 'text'\n | 'integer'\n | 'bigint'\n | 'numeric'\n | 'boolean'\n | 'timestamp'\n | 'jsonb'\n | 'enum'\n | 'vector';\n\n/** Base column definition shared by all column types. */\nexport interface ColumnDef {\n type: ColumnType;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n references?: { table: string; column: string };\n /**\n * The name this column used to have. A diff cannot tell a rename from a drop and\n * an add — both leave one name gone and another present — so the intent has to be\n * declared. Without it, renaming a column loses its data.\n */\n renamedFrom?: string;\n /**\n * This release's PROMISE that it does not reference this column — neither\n * reads it nor writes it, and never names it in a filter, a sort or a SET.\n *\n * The contraction gate reads it and nothing else does: dropping a column is\n * refused while the RUNNING release's declaration still lacks this mark, so\n * removing a column is two deploys — mark it, ship, then drop it.\n *\n * The word is `ignored` and not `deprecated` deliberately: RFC 9745 defines\n * deprecation as changing NO behaviour, and this changes what a deploy will\n * accept. Rails calls the same thing `ignored_columns`.\n */\n ignored?: boolean;\n onDeleteAction?: OnDeleteAction;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n /**\n * The value is written by the DATABASE — a trigger, a rule, an identity — not by\n * the author and not by a DEFAULT this schema declares. It makes the column\n * optional on INSERT without putting a DEFAULT in the DDL.\n *\n * Before this existed the only way to keep a trigger-filled column off the\n * INSERT type was to give it a fake `default()`: a value the schema claimed to\n * write and the trigger immediately overwrote. That made the schema lie about\n * its own data.\n */\n dbAssigned?: boolean;\n /** vector(n): the declared dimension count — part of the TYPE (typmod), read\n * by the wire serializer and the deploy's auto-index (FR-001). */\n dimensions?: number;\n /**\n * How the stored value is projected in and out of this process (FR-009).\n *\n * NOT part of the DDL: the column's Postgres type is unchanged and this pair\n * is never serialized into a migration. It exists so the row surface can hand\n * back the type the application actually works with.\n */\n transform?: ColumnTransform;\n}\n\n/**\n * The read/write pair a column may declare (FR-009).\n *\n * `fromDb` takes whatever the driver produced for this column and returns the\n * value the application sees; `toDb` is its inverse on the way out. Kept\n * deliberately unexported — a column declares one inline, nobody needs to name\n * the shape.\n */\ninterface ColumnTransform<T = unknown> {\n fromDb: (value: unknown) => T;\n toDb: (value: T) => unknown;\n}\n\n/** FR-002: a vector column cannot carry keys/defaults/references — the modifier\n * is named in the error so the author fixes the right line. */\nfunction refuseOnVector(def: ColumnDef, modifier: string): void {\n if (def.type === 'vector') {\n throw new Error(`vector column: .${modifier}() is not supported (FR-002 — allowed: nullable()/notNull())`);\n }\n}\n\n// Phantom brand symbols — never have runtime values; exist only to force\n// TypeScript's structural type system to distinguish ColumnBuilder instances\n// with different type-param combinations. Without these, TS sees all\n// ColumnBuilder<K,...> as structurally identical and the first branch of\n// ColValue matches everything.\ndeclare const __colKind: unique symbol;\ndeclare const __colNullable: unique symbol;\ndeclare const __colHasDefault: unique symbol;\ndeclare const __colEnumValues: unique symbol;\ndeclare const __colPayload: unique symbol;\ndeclare const __colTransform: unique symbol;\n\n/**\n * Fluent column builder with phantom type params:\n * K — ColumnType literal (e.g. \"text\", \"integer\")\n * N — boolean: true when nullable() has been called last (false = NOT NULL)\n * D — boolean: true when a default has been set\n * E — enum value union (never for non-enum columns)\n * P — jsonb payload shape (unknown unless jsonb<T>() supplied one)\n * T — transform target type (`never` when the column declares no transform;\n * `never` is the sentinel because it is the only type that survives\n * `[T] extends [never]` and never collides with a real target type)\n *\n * All six params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The six `declare readonly` brand fields carry the phantom types into the\n * structural shape so that conditional types like ColValue<C> can discriminate\n * on K without requiring runtime values on those fields.\n */\nexport class ColumnBuilder<\n K extends ColumnType = ColumnType,\n N extends boolean = boolean,\n D extends boolean = boolean,\n E = unknown,\n P = unknown,\n // `unknown`, not `never`: the schema's own constraint is a BARE\n // `ColumnBuilder`, whose T lands on this default. With `never` there, a\n // column that declares `.transform<number>()` is not assignable to the\n // constraint at all — `number` does not extend `never` — so a transform\n // could not appear in a schema and the whole table's `RowShape` collapsed.\n // Measured: TS2322 on `defineSchema`.\n T = unknown,\n> {\n // These fields exist only in the type layer (declared, never initialised at\n // runtime — TypeScript allows declared class members without an initializer\n // in strict mode as long as they're never read at runtime).\n declare readonly [__colKind]: K;\n declare readonly [__colNullable]: N;\n declare readonly [__colHasDefault]: D;\n declare readonly [__colEnumValues]: E;\n declare readonly [__colPayload]: P;\n declare readonly [__colTransform]: T;\n\n readonly _def: ColumnDef;\n\n constructor(type: K, existingDef?: ColumnDef) {\n this._def = existingDef ?? {\n type,\n nullable: false,\n primaryKey: false,\n };\n }\n\n /** Mark this column as the primary key. */\n primaryKey(): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'primaryKey');\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Mark this column as NOT NULL (default). */\n notNull(): ColumnBuilder<K, false, D, E, P, T> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E, P, T> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'default');\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** UUID: generate a random default (gen_random_uuid()). */\n defaultRandom(): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'defaultRandom');\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'defaultNow');\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * The DATABASE assigns this column's value — a trigger, a rule, an identity.\n *\n * The column becomes optional on INSERT (the author has nothing to send) while\n * the DDL stays free of a DEFAULT this schema would not honour. It is NOT\n * `default()`: that declares a value the schema promises to write.\n *\n * Naming: deliberately not `generated()`. Postgres has GENERATED columns and\n * they are a different thing; borrowing the word would send a reader — or a\n * model writing a schema — to the wrong feature.\n */\n dbAssigned(): ColumnBuilder<K, N, true, E, P, T> {\n this._def.dbAssigned = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a foreign key reference. */\n /**\n * Declares that this column used to be called `previous`.\n *\n * A schema diff sees one name gone and another present; it cannot know whether\n * you renamed a column or dropped one and added another, and the two are very\n * different — the second loses every value. Saying so here turns the plan into\n * `ALTER TABLE … RENAME COLUMN` instead.\n *\n * Once the rename has been applied the annotation is inert (the old name is no\n * longer there to rename), so it can be deleted at your leisure.\n */\n renamedFrom(previous: string): ColumnBuilder<K, N, D, E, P, T> {\n this._def.renamedFrom = previous;\n return this as unknown as ColumnBuilder<K, N, D, E, P, T>;\n }\n\n /**\n * See {@link ColumnDef.ignored}.\n *\n * COPIES the def rather than mutating it. The constructor takes an existing\n * def BY REFERENCE, so every builder derived from another shares one object —\n * `const a = slug.unique()` leaves `a._def === slug._def`. An in-place\n * `ignored = true` therefore marks every column sharing that def, including\n * one another table actively reads, and the gate would let THAT column be\n * dropped. Measured before this copy existed.\n *\n * The aliasing is older than this method and other fields leak through it too.\n * The reason this one cannot wait: every other leak produces a VISIBLE schema\n * difference — the plan shows it, the DDL shows it. This one is invisible by\n * design (no DDL, no diff, no plan line), so its only effect is to disarm a\n * safety gate in silence.\n */\n ignored(): ColumnBuilder<K, N, D, E, P, T> {\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, {\n ...this._def,\n ignored: true,\n });\n }\n\n references(table: string, column: string): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'references');\n this._def.references = { table, column };\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Add a real DB-level foreign key to the built-in auth users\n * (`REFERENCES auth.users(id)`), so a column like `user_id` gets true\n * database cascade/integrity instead of app-layer-only. Sugar for\n * `.references(\"auth.users\", \"id\")`.\n *\n * `auth.users` lives in the SAME tenant database (palauth-owned), so this is\n * a genuine cross-schema integrity constraint scoped to THIS tenant's users.\n * The referenced `auth.users.id` is `text` (palauth ids are `usr_<uuid>`), so\n * the referencing column must be `text()` too.\n *\n * ON DELETE is REQUIRED here and may only be `cascade` or `set null`: an\n * account-erasure request must never be blocked by a lingering FK, so\n * `restrict` / `no action` are not accepted (they don't type-check). Example:\n * `text().notNull().referencesAuthUser(\"cascade\")`, or\n * `text().nullable().referencesAuthUser(\"set null\")`. The server\n * (validateAuthUserFK) enforces this — and the remaining rules the type can't\n * express (referencing column is text, `set null` needs a nullable column) —\n * as the real boundary; this signature is the compile-time DX mirror.\n */\n referencesAuthUser(onDelete: AuthUserOnDelete): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, \"referencesAuthUser\");\n this._def.references = { table: 'auth.users', column: 'id' };\n this._def.onDeleteAction = onDelete;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Add a real DB-level foreign key to the canonical, server-minted installation\n * anchor (`REFERENCES auth.installations(id)`) — the app-scoped verified-device\n * root (`ins_...`). Sugar for `.references(\"auth.installations\", \"id\")`.\n *\n * An installation is an APP INSTALL, not a user: this FK is NOT user ownership.\n * A user-owned row STILL needs its own `.referencesAuthUser(...)` FK so account\n * erasure removes it — an installation reference alone does not tie a row to a\n * user's deletion. Use this only for install-scoped state (device prefs, push\n * routing, …), alongside a separate auth-user FK where the row is user-owned.\n *\n * `auth.installations` lives in the SAME tenant DB (palauth-owned); its `id` is\n * `text` (`ins_<uuid>`), so the referencing column must be `text()` too. ON\n * DELETE is REQUIRED and may only be `cascade` or `set null` (same allowed set\n * as an auth-user FK): an installation revoke / orphan cleanup must never be\n * blocked by a lingering FK. The server (validateAuthAnchorFK) is the real\n * boundary; this signature is the compile-time DX mirror.\n */\n referencesInstallation(onDelete: AuthUserOnDelete): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, \"referencesInstallation\");\n this._def.references = { table: 'auth.installations', column: 'id' };\n this._def.onDeleteAction = onDelete;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E, P, T> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a single-column UNIQUE constraint. */\n unique(): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'unique');\n this._def.unique = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Declare how this column's value is projected in and out of the process.\n *\n * The DDL does not move: `numeric` stays `numeric`, and the driver still hands\n * back what Postgres sent. What changes is the type the row surface exposes —\n * it becomes `Target`:\n *\n * amount: numeric().transform<number>({ fromDb: Number, toDb: String })\n *\n * `numeric` surfacing as `string` is CORRECT (a JS number cannot hold\n * arbitrary precision), and that is exactly why this exists: application code\n * that does arithmetic on the column otherwise rewrites the same\n * `Number(row.amount)` / `String(x)` pair in every controller that touches it,\n * and each rewrite is a place the two directions can drift apart.\n *\n * A transform is a PROJECTION, never a constraint: it lives only in this\n * process, so it can neither validate nor migrate what is stored.\n */\n transform<Target>(fns: ColumnTransform<Target>): ColumnBuilder<K, N, D, E, P, Target> {\n // The cast is the variance, not a shortcut: `toDb` takes `Target`, and a\n // `ColumnTransform<unknown>` would have to accept anything. The stored pair\n // is only ever called with this column's own values.\n this._def.transform = fns as ColumnTransform;\n return new ColumnBuilder<K, N, D, E, P, Target>(this._def.type as K, this._def);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type extractors — imported by Task 2 to derive insert/row shapes.\n// ---------------------------------------------------------------------------\n\n/**\n * Extracts the TypeScript value type for a column, respecting nullability.\n * - \"uuid\" | \"text\" | \"timestamp\" | \"bigint\" | \"numeric\" → string (or string | null when N = true)\n * Note: bigint/numeric surface as string — JS number loses precision past 2^53,\n * and pgx/PostgREST serialize int8/numeric as strings. App code uses\n * BigInt(row.amount) for bigint, or a decimal lib for numeric.\n * - \"integer\" → number\n * - \"boolean\" → boolean\n * - \"jsonb\" → P (the dev-supplied payload shape from jsonb<T>(), else unknown)\n * - \"enum\" → E (the union of literal values)\n *\n * A declared `.transform<T>()` OVERRIDES the table above: the column then\n * surfaces as T (or T | null when nullable), because that is the value the\n * application is handed. Nullability is still the column's, not the\n * transform's — `fromDb` is not called for a NULL.\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<ColumnType, infer N, boolean, unknown, unknown, infer T>\n ? [unknown] extends [T]\n ? ColStoredValue<C>\n : N extends true\n ? T | null\n : T\n : never;\n\n/** The value as the DATABASE hands it over — the branch table above, before any\n * transform. This is what a column's `fromDb` receives. */\ntype ColStoredValue<C> =\n C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? string | null\n : string\n : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number | null\n : number\n : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? boolean | null\n : boolean\n : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P>\n ? N extends true\n ? P | null\n : P\n : C extends ColumnBuilder<'vector', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number[] | null\n : number[]\n : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P>\n ? N extends true\n ? E | null\n : E\n : never;\n\n/**\n * True when a column is optional on INSERT:\n * - nullable columns (N = true) — the DB allows NULL so the field may be omitted\n * - columns with a default (D = true) — the DB fills in the value when absent\n */\nexport type ColIsOptionalOnInsert<C> =\n C extends ColumnBuilder<ColumnType, true, boolean, unknown, unknown, unknown>\n ? true\n : C extends ColumnBuilder<ColumnType, boolean, true, unknown, unknown, unknown>\n ? true\n : false;\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/** Create a UUID column. */\nexport function uuid(): ColumnBuilder<'uuid', false, false, never> {\n return new ColumnBuilder('uuid');\n}\n\n/** Create a TEXT column. */\nexport function text(): ColumnBuilder<'text', false, false, never> {\n return new ColumnBuilder('text');\n}\n\n/** Create an INTEGER column. Emits int4 (max ~2.1B). */\nexport function integer(): ColumnBuilder<'integer', false, false, never> {\n return new ColumnBuilder('integer');\n}\n\n/**\n * Create a BIGINT column (Postgres int8, max ~9.2×10^18).\n * Surfaces as `string` in row/insert types — JS number loses precision past 2^53\n * and pgx/PostgREST serialize int8 as a JSON string. Use BigInt(row.column) in app code.\n */\nexport function bigint(): ColumnBuilder<'bigint', false, false, never> {\n return new ColumnBuilder('bigint');\n}\n\n/**\n * Create a NUMERIC column (Postgres `numeric`/`decimal`, arbitrary precision).\n * For exact fractional values (money with cents as a decimal, rates, weights)\n * where int4/int8 don't fit. Surfaces as `string` in row/insert types — JS\n * number can't hold arbitrary-precision decimals without rounding, and\n * pgx/PostgREST serialize numeric as a JSON string. Parse with a decimal lib\n * (or BigInt for scaled integers) in app code.\n */\nexport function numeric(): ColumnBuilder<'numeric', false, false, never> {\n return new ColumnBuilder('numeric');\n}\n\n/** Create a BOOLEAN column. */\nexport function boolean(): ColumnBuilder<'boolean', false, false, never> {\n return new ColumnBuilder('boolean');\n}\n\n/** Create a TIMESTAMP column. */\nexport function timestamp(): ColumnBuilder<'timestamp', false, false, never> {\n return new ColumnBuilder('timestamp');\n}\n\n/**\n * Create a JSONB column. Pass a payload type to make the generated row/insert\n * type concrete instead of `unknown`:\n *\n * tags: jsonb<string[]>() // row.tags: string[]\n * meta: jsonb<{ tier: string }>() // row.meta: { tier: string }\n * raw: jsonb() // row.raw: unknown (back-compat)\n *\n * The runtime accepts a plain JS object/array directly (no JSON.stringify); the\n * generic only refines the TYPE the env codegen emits.\n */\nexport function jsonb<T = unknown>(): ColumnBuilder<'jsonb', false, false, never, T> {\n return new ColumnBuilder('jsonb');\n}\n\n/**\n * Create an ENUM column.\n * @param name The PostgreSQL enum type name (used in DDL).\n * @param values A readonly tuple of valid string values — kept `const` so the\n * union `V[number]` is as narrow as possible.\n */\nexport function enumType<const V extends readonly string[]>(\n name: string,\n values: V,\n): ColumnBuilder<'enum', false, false, V[number]> {\n const builder = new ColumnBuilder<'enum', false, false, V[number]>('enum');\n builder._def.enumName = name;\n builder._def.enumValues = [...values];\n return builder;\n}\n\n/** vector(n) — pgvector kolonu. n TİPİN parçasıdır (typmod) ve [1, 2000] —\n * 2000 = pgvector'ün HNSW-indekslenebilir tavanı; auto-index bu beyanla bağlı\n * (spec FR-001, D-3). */\nexport function vector(dimensions: number): ColumnBuilder<'vector', false, false, unknown, number[]> {\n if (!Number.isInteger(dimensions) || dimensions < 1 || dimensions > 2000) {\n throw new Error(`vector(): dimensions must be an integer in [1, 2000], got ${String(dimensions)}`);\n }\n const b = new ColumnBuilder('vector') as ColumnBuilder<'vector', false, false, unknown, number[]>;\n (b._def as { dimensions?: number }).dimensions = dimensions;\n return b;\n}\n","/**\n * A named raw-SQL DDL object declared in db/schema.ts for anything the typed DSL\n * cannot express (EXCLUDE, CHECK, partial/expression indexes, triggers, views).\n * The deploy emits `up` verbatim on the privileged DDL connection — same trust\n * posture as policy().using(). Tracked by NAME (not by diffing the body), so a\n * changed body needs a new name or an explicit drop+add.\n */\nexport interface RawConstraintDef {\n name: string;\n up: string;\n down?: string;\n}\n\nexport function raw(name: string, up: string, opts?: { down?: string }): RawConstraintDef {\n return { name, up, ...(opts?.down != null ? { down: opts.down } : {}) };\n}\n","/** Embedding sağlayıcı DESKRIPTORU — canlı istemci değil, düz veri: şemayla\n * birlikte serileşir, çağrıyı Go worker (yazma) ve engine (sorgu) yapar.\n * Adlandırma Vercel AI SDK'nın aynasıdır (openai.embedding(\"...\")) ama paket\n * bağımlılığı bilinçli olarak YOKTUR (spec C-3, UD-016). v1 sağlayıcı: openai (D-10). */\nexport interface EmbeddingModelRef {\n provider: \"openai\";\n model: string;\n dimensions?: number;\n apiKeyName?: string;\n baseURL?: string;\n}\n/** Chat/damıtma modeli DESKRIPTORU (C-11, D-019) — memory beyanının extract'i.\n * Embedding gibi düz veridir; çağrıyı worker yapar, anahtar vault'taki\n * OPENAI_API_KEY'dir (D-017: aynı sağlayıcı, yeni dış sistem yok). */\nexport interface ChatModelRef {\n provider: \"openai\";\n model: string;\n}\nexport const openai = {\n embedding(\n model: string,\n opts?: { dimensions?: number; apiKeyName?: string; baseURL?: string },\n ): EmbeddingModelRef {\n return { provider: \"openai\", model, apiKeyName: opts?.apiKeyName ?? \"OPENAI_API_KEY\",\n ...(opts?.dimensions !== undefined ? { dimensions: opts.dimensions } : {}),\n ...(opts?.baseURL !== undefined ? { baseURL: opts.baseURL } : {}) };\n },\n chat(model: string): ChatModelRef {\n return { provider: \"openai\", model };\n },\n};\n","/**\n * typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.\n *\n * Derives INSERT and full-row TypeScript types from a `defineSchema()` result\n * and wraps the untyped runtime `DBClient` with a typed facade.\n *\n * No value-any. No `as unknown as X`. The two narrow `as` casts in\n * `makeTypedTable` are safe because:\n * - `data as Record<string, unknown>`: InsertShape<T> maps string keys to\n * typed values; all value types are subsets of `unknown`, so the cast is\n * structurally sound.\n * - `result as RowShape<T>`: The runtime DBClient returns `Record<string,\n * unknown>` which is the erased form of the typed row; we're narrowing back\n * to the precise shape that the schema declared.\n * Both casts are narrowing only (not widening) and correctness is guaranteed\n * by the schema the caller provides.\n */\n\nimport type { ColValue, ColIsOptionalOnInsert, ColumnBuilder } from \"./columns.js\";\nimport type { TableDef, SchemaDef } from \"./schema.js\";\nimport type { Tables, TableTypes } from \"./env.js\";\nimport type { DBClient, DBOps } from \"../endpoint.js\";\nimport type { Materialized, TxPlanHandle, TxTable } from \"./tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./tx-plan.js\";\n\n// ---------------------------------------------------------------------------\n// Key discriminators — split a column map into required vs optional keys.\n// ---------------------------------------------------------------------------\n\n/** Keys of C whose columns are required on INSERT (not nullable, no default). */\ntype RequiredKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;\n}[keyof C];\n\n/** Keys of C whose columns are optional on INSERT (nullable or has a default). */\ntype OptionalKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;\n}[keyof C];\n\n// ---------------------------------------------------------------------------\n// Public shape types — exported so callers can reference them directly.\n// ---------------------------------------------------------------------------\n\n/**\n * The TypeScript type for an INSERT payload for table `T`.\n * - Required: columns that are NOT NULL and have no DB-level default.\n * - Optional: columns that are nullable or carry a default.\n *\n * When all columns are optional, `RequiredKeys<C>` resolves to `never` and\n * the first part becomes `{}`, which is a neutral element for `&`.\n */\nexport type InsertShape<T extends TableDef> = {\n [K in RequiredKeys<T[\"columns\"]>]: ColValue<T[\"columns\"][K]>;\n} & {\n [K in OptionalKeys<T[\"columns\"]>]?: ColValue<T[\"columns\"][K]>;\n};\n\n/**\n * The TypeScript type for a full row returned by the DB for table `T`.\n * Every column is present; nullable columns resolve to `T | null`.\n */\nexport type RowShape<T extends TableDef> = {\n [K in keyof T[\"columns\"]]: ColValue<T[\"columns\"][K]>;\n};\n\n// ---------------------------------------------------------------------------\n// TypedTable + TypedDB interfaces.\n// ---------------------------------------------------------------------------\n\n/** A typed table accessor that mirrors the runtime DBClient surface. */\nexport interface TypedTable<T extends TableDef> {\n insert(data: InsertShape<T>): Promise<RowShape<T>>;\n upsert(data: InsertShape<T>, opts: { onConflict: readonly string[] }): Promise<RowShape<T>>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T> | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<RowShape<T> | null>;\n /** Rows matching the filter. Operators, ordering and paging are the ENGINE's\n * surface — this declaration is what makes them callable. */\n findMany(\n query?: WhereFilter<RowShape<T>>,\n opts?: FindManyOpts<RowShape<T>>,\n ): Promise<RowShape<T>[]>;\n /** Update every matching row in one statement; an empty filter is refused. */\n updateMany(\n where: WhereFilter<RowShape<T>>,\n set: Partial<InsertShape<T>>,\n ): Promise<RowShape<T>[]>;\n /** Delete every matching row; resolves to how many. Empty filter refused. */\n deleteMany(where: WhereFilter<RowShape<T>>): Promise<number>;\n /** How many rows match. An empty filter is legitimate: counting is a read. */\n count(where?: WhereFilter<RowShape<T>>): Promise<number>;\n}\n\n/** A typed DB facade covering all tables declared in schema `S`. */\nexport interface TypedDB<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n /** Run a transaction plan. See {@link EnvTypedDatabase.transaction}. */\n transaction<T>(\n fn: (tx: TypedTx<S>) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>>;\n}\n\n/** The plan-building handle a `TypedDB<S>` transaction callback receives: the\n * schema's tables, expressed as plan operations rather than awaited calls. */\nexport type TypedTx<S extends SchemaDef> = TxPlanHandle<{\n [K in keyof S[\"tables\"]]: TxTable<RowShape<S[\"tables\"][K]>, InsertShape<S[\"tables\"][K]>>;\n}>;\n\n// ---------------------------------------------------------------------------\n// Runtime factory.\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a typed table accessor that delegates every call to `raw` using the\n * runtime table name string. Two narrow `as` casts bridge the mapped-type\n * shapes to/from `Record<string, unknown>` — see module-level doc comment.\n *\n * The `raw` param is typed `DBOps` (the six string-keyed ops) because this only\n * ever calls those — never `txPlan`, which builds its own operations rather than\n * delegating to these.\n */\nfunction makeTypedTable<T extends TableDef<Record<string, ColumnBuilder>>>(\n name: string,\n raw: DBOps,\n): TypedTable<T> {\n return {\n insert: (data: InsertShape<T>) =>\n raw.insert(name, data as Record<string, unknown>) as Promise<RowShape<T>>,\n\n upsert: (data: InsertShape<T>, opts: { onConflict: readonly string[] }) =>\n raw.upsert(name, data as Record<string, unknown>, opts) as Promise<RowShape<T>>,\n\n update: (id: string, data: Partial<InsertShape<T>>) =>\n raw.update(name, id, data as Record<string, unknown>) as Promise<RowShape<T> | null>,\n\n delete: (id: string) => raw.delete(name, id),\n\n findById: (id: string) =>\n raw.findById(name, id) as Promise<RowShape<T> | null>,\n\n findMany: (query?: WhereFilter<RowShape<T>>, opts?: FindManyOpts<RowShape<T>>) =>\n raw.findMany(name, query as Record<string, unknown> | undefined, opts) as Promise<RowShape<T>[]>,\n\n updateMany: (where: WhereFilter<RowShape<T>>, set: Partial<InsertShape<T>>) =>\n raw.updateMany(\n name,\n where as Record<string, unknown>,\n set as Record<string, unknown>,\n ) as Promise<RowShape<T>[]>,\n\n deleteMany: (where: WhereFilter<RowShape<T>>) =>\n raw.deleteMany(name, where as Record<string, unknown>),\n\n count: (where?: WhereFilter<RowShape<T>>) =>\n raw.count(name, where as Record<string, unknown> | undefined),\n };\n}\n\n/**\n * Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from\n * the provided schema. No behavior change for the direct ops — all calls\n * delegate to `raw` with the table name as a plain string.\n *\n * `transaction` does NOT delegate to a per-op client: the callback describes a\n * plan against a fresh {@link TxPlanBuilder}, and the whole plan travels in one\n * `raw.txPlan` call. The schema is used only for its table NAMES; the values\n * are typed by `S` at compile time and are plain strings at run time.\n *\n * The `as` casts are single structural narrowings from a dynamically-built\n * object to the precise mapped type (TS cannot infer the mapped-type result\n * through `Object.keys` iteration) — see the module-level doc comment.\n */\nexport function makeTypedDB<S extends SchemaDef>(\n schema: S,\n raw: DBClient,\n): TypedDB<S> {\n const tables = {} as Record<string, TypedTable<TableDef>>;\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) {\n tables[key] = makeTypedTable(tableDef.name, raw);\n }\n }\n\n const result = {\n tables,\n transaction<T>(\n fn: (tx: TypedTx<S>) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>> {\n const builder = new TxPlanBuilder();\n const planTables: Record<string, unknown> = {};\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) planTables[key] = builder.table(tableDef.name);\n }\n // Two narrowings at the same seam: the plan tables are built by NAME, so\n // TS cannot see the mapped type through the loop, and the driver erases\n // the callback's return type (see runTxPlan's doc). Both are the erasure\n // this facade exists to undo.\n return runTxPlan(\n raw,\n planTables as TypedTx<S>[\"tables\"],\n builder,\n fn,\n ) as Promise<Materialized<T>>;\n },\n };\n\n // Narrow cast: `result.tables` is structurally identical to\n // TypedDB<S>[\"tables\"] — each key maps to a TypedTable for the matching\n // TableDef. TS cannot infer the mapped-type result through Object.keys\n // iteration, so a single `as` bridges the gap.\n return result as TypedDB<S>;\n}\n\n// ---------------------------------------------------------------------------\n// Env-augmentation-driven typed surface — the typed-by-default `Database`.\n//\n// These types read the globally-augmented `Tables` interface from\n// `@palbase/backend/env` (filled by the generated `palbase-env.d.ts`). They\n// back `Database.tables.<name>` so handler code is typed with no import and no\n// generic (C5). They DELIBERATELY do not reference `ColumnBuilder` — the env\n// `Tables` interface carries flat `row`/`insert` object types.\n// ---------------------------------------------------------------------------\n\n/** Bir where değeri: düz eşitlik YA DA operatör nesnesi (FR-016). */\nexport type WhereOp<V> = V | { gt?: V; gte?: V; lt?: V; lte?: V; neq?: V; in?: V[] };\n\n/**\n * A filter over a row: every field optional, each one a plain value (equality)\n * or an operator object. THE filter language — `findMany`, `updateMany`,\n * `deleteMany` and `count` all take this one, because two spellings of a filter\n * is how the two come to disagree.\n */\nexport type WhereFilter<Row> = { [K in keyof Row]?: WhereOp<Row[K]> };\n\n/**\n * Ordering and paging for a read.\n *\n * `column` is `keyof Row`, not `string`: a mistyped column name is a compile\n * error here rather than a runtime rejection three layers down. `offset`\n * without `limit` is refused by the engine — a page with no size is not a page.\n */\nexport type FindManyOpts<Row> = {\n orderBy?: { column: Extract<keyof Row, string>; direction?: \"asc\" | \"desc\" };\n limit?: number;\n offset?: number;\n};\n\n/** search() parametreleri, satır tipiyle koşullanmış (FR-013). `offset` BİLEREK yok (UD-013). */\nexport interface SearchParamsTyped<T extends TableTypes> {\n /** Metin sorgusu: FTS kolunu besler; embed beyanlıysa sorgu vektörü de bundan üretilir. */\n query?: string;\n /** Hazır sorgu vektörü — verilirse embed çağrısı olmaz (FR-025). */\n vector?: number[];\n where?: { [K in keyof T[\"row\"]]?: WhereOp<T[\"row\"][K]> };\n /** default 20, tavan 100 (engine uygular). */\n limit?: number;\n /** Birden çok vektör kolonunda hedef seçimi (model geçişi, FR-013/using). */\n using?: string;\n mode?: \"hybrid\" | \"text\" | \"vector\";\n /** Nihai (RRF-sonrası) skor alt eşiği — süzme LIMIT'ten önce uygulanır (FR-001). */\n minScore?: number;\n /** Chunk-modunda satır başına en iyi blok sayısı (1..10, vars. 3; FR-015). */\n blocksPerRow?: number;\n /** Tazelik çürümesi: nihai skor RRF-sonrası exp(-ln(2)*yaş/halfLife) ile çarpılır;\n * field bir timestamp kolonu, halfLife \"90s\" | \"15m\" | \"12h\" | \"30d\" biçiminde (FR-004). */\n recency?: { field: Extract<keyof T[\"row\"], string>; halfLife: string };\n /** Filtrelenmiş küme üzerinde kolon başına top-20 değer sayacı — dönüş\n * dizisinin `_facets` özelliği (FR-027). */\n facets?: Extract<keyof T[\"row\"], string>[];\n /** Satır-modunda FTS eşleşme vurgusu: sonuç satırına `_highlight` ekler;\n * chunk-modda no-op — bloklar zaten eşleşen kesittir (FR-025). */\n highlight?: boolean;\n /** Validity'li tabloda zaman penceresi: varsayılan yalnız güncel versiyon;\n * \"all\" tüm versiyonlar; {asOf} o anda geçerli olan (FR-029). */\n validity?: \"all\" | { asOf: string };\n /** Alan-boost (FR-030): skor * (1 + w·x/(1+x)) — sayısal kolonla sınırlı\n * çarpan, dış servissiz; bileşim RRF → boost → recency → minScore. */\n boost?: { field: Extract<keyof T[\"row\"], string>; weight: number };\n}\n\n/** search() dönüş dizisinin sorgu-düzeyi ekleri (FR-027): `_facets` dizinin\n * ÖZELLİĞİDİR, satırlara kopyalanmaz (JSON'a satır başına şişme olmasın). */\nexport type SearchFacets = Record<string, { value: string | null; count: number }[]>;\n\n/** similar()/recommend() taşıyıcı opsiyonları (T018, FR-022): search'ün\n * paramlarından query/vector/mode düşer — hedef vektörü metodun kendisi\n * DB'den kurar; facets/highlight de düşer (T020) — engine bu ikisini\n * similar/recommend'e geçirmez, tip vaadi gerçekle aynı kalır. */\nexport type SimilarParamsTyped<T extends TableTypes> = Omit<\n SearchParamsTyped<T>,\n \"query\" | \"vector\" | \"mode\" | \"facets\" | \"highlight\"\n>;\n\n/** recommend() parametreleri (T018, FR-023). */\nexport type RecommendParamsTyped<T extends TableTypes> = SimilarParamsTyped<T> & {\n /** Kaynak beğeniler — hedef vektör bunların DB-içi avg'ı; boş olamaz. */\n positive: string[];\n /** İtilen örnekler — hedef pos.v + (pos.v - neg.v) ile yönlenir. */\n negative?: string[];\n};\n\n/** Temel tablo erişimcisi — search'süz beş op. */\nexport interface EnvTypedTableBase<T extends TableTypes> {\n insert(data: T[\"insert\"]): Promise<T[\"row\"]>;\n /**\n * Insert the row, or update it when it collides on `onConflict`.\n *\n * The conflict columns must carry a unique constraint or index — that is what\n * Postgres matches on — and they are excluded from the update, since they are\n * what matched.\n */\n upsert(data: T[\"insert\"], opts: { onConflict: readonly Extract<keyof T[\"row\"], string>[] }): Promise<T[\"row\"]>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<T[\"insert\"]>): Promise<T[\"row\"] | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<T[\"row\"] | null>;\n /** Rows matching the filter. See {@link WhereFilter} / {@link FindManyOpts} —\n * this declaration is what makes the engine's operators callable. */\n findMany(\n query?: WhereFilter<T[\"row\"]>,\n opts?: FindManyOpts<T[\"row\"]>,\n ): Promise<T[\"row\"][]>;\n /** Update every matching row in one statement; an empty filter is refused. */\n updateMany(where: WhereFilter<T[\"row\"]>, set: Partial<T[\"insert\"]>): Promise<T[\"row\"][]>;\n /** Delete every matching row; resolves to how many. Empty filter refused. */\n deleteMany(where: WhereFilter<T[\"row\"]>): Promise<number>;\n /** How many rows match. An empty filter is legitimate: counting is a read. */\n count(where?: WhereFilter<T[\"row\"]>): Promise<number>;\n /** Validity'li tabloda satırın yeni versiyonu (FR-029, C-9): eski satır\n * kapanır (valid_to/superseded_by), yenisi TEK savepoint'te eklenir; dönüş\n * yeni satır. Validity beyanı olmayan tabloda adlandırılmış çalışma-zamanı\n * hatası — tip düzeyinde ayrım env `Tables` bayrağı taşımadığından yapılamaz. */\n supersede(id: string, row: T[\"insert\"]): Promise<T[\"row\"]>;\n}\n\n/** Tablo erişimcisi: env girdisi `searchable: true` taşıyorsa (vector kolonu ya da\n * search beyanı — env-gen üretir) `search()` üyesi VARDIR; yoksa üye hiç yoktur ve\n * çağrı derleme hatasıdır (FR-013). Yapısal koşul TableTypes'ı genişletmeden çalışır. */\nexport type EnvTypedTable<T extends TableTypes> = EnvTypedTableBase<T> &\n (T extends { searchable: true }\n ? {\n search(\n params: SearchParamsTyped<T>,\n ): Promise<Array<T[\"row\"] & { _score: number }> & { _facets?: SearchFacets }>;\n /** \"Bu satıra benzeyenler\" (FR-022): hedef vektör DB'den okunur,\n * kaynak satır sonuçta yoktur; id yoksa adlandırılmış hata. */\n similar(id: string, params?: SimilarParamsTyped<T>): Promise<Array<T[\"row\"] & { _score: number }>>;\n /** D-021: sayaçlar bağımsız dönüşle — search'ün dizi-üstü _facets'i\n * JSON.stringify'da kaybolur; ciddi sözleşme budur. */\n facets(params: { facets: Array<keyof T[\"row\"] & string>; where?: Partial<T[\"row\"]>; validity?: \"all\" | { asOf: string } }): Promise<Record<string, { value: string | null; count: number }[]>>;\n /** positive/negative beğenilerden öneri (FR-023): hedef vektör DB-içi\n * avg CTE'leriyle; kaynak id'ler sonuçta yoktur. */\n recommend(params: RecommendParamsTyped<T>): Promise<Array<T[\"row\"] & { _score: number }>>;\n }\n : Record<never, never>);\n\n/** The `tables` map exposed on `Database`/`tx`, keyed by the env `Tables`\n * interface. When no schema is declared `Tables` is empty, so `tables` is an\n * empty object — accessing `.tables.foo` is then a compile error (no member). */\nexport type EnvTables = {\n [K in keyof Tables]: EnvTypedTable<Tables[K]>;\n};\n\n/** The project's tables as PLAN operations, keyed by the env `Tables`\n * interface. The transaction twin of {@link EnvTables}. */\nexport type TxTables = {\n [K in keyof Tables]: TxTable<Tables[K][\"row\"], Tables[K][\"insert\"]>;\n};\n\n/**\n * The handle a `Database.transaction(…)` callback receives.\n *\n * Tables only — no `query`, no `findById`, no `asService`. A read whose value\n * the plan does not write belongs outside the transaction, where it costs one\n * round trip and is an ordinary value you can branch on.\n */\nexport type TxPlan = TxPlanHandle<TxTables>;\n\n/**\n * The RLS-bypass sibling returned by `Database.asService()`. Same typed surface\n * as {@link EnvTypedDatabase} — `tables`, the raw string ops, and a typed\n * `transaction` — but it does NOT re-expose `asService` (no double-bypass).\n * Every op it performs runs as the `service_role` (BYPASSRLS).\n */\nexport interface EnvServiceDatabase extends Omit<DBClient, \"txPlan\" | \"asService\"> {\n tables: EnvTables;\n transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;\n}\n\n/**\n * The typed-by-default Database surface: the raw string-keyed `DBClient` ops\n * PLUS a `tables` map typed against the project's generated `palbase-env.d.ts`,\n * a `transaction` that runs a whole plan in one request, and `asService()` for\n * the explicit RLS-bypass sibling.\n *\n * The low-level `txPlan` op is deliberately NOT re-exposed here: `transaction`\n * is the surface, and a hand-built plan would bypass the ref/guard machinery\n * that makes one safe to write.\n */\nexport interface EnvTypedDatabase extends Omit<DBClient, \"txPlan\" | \"asService\"> {\n tables: EnvTables;\n /**\n * Run a transaction. The callback DESCRIBES the operations; the whole\n * description travels in one request and the broker runs it inside a single\n * transaction — committing when it finishes, rolling back on any failure.\n *\n * The callback is SYNCHRONOUS: nothing has run when it returns, so there is\n * nothing to await. `async` on it and `await` inside it are compile errors.\n * Values a later operation needs are {@link Ref}s, written straight into the\n * next operation; values the CALLER needs are returned and substituted before\n * this promise resolves.\n *\n * @example\n * const { statementId } = await Database.transaction((tx) => {\n * const st = tx.tables.statements\n * .insert({ household_id: hid, file_sha256: sha, status: \"reviewing\" })\n * .expectOne(new Internal(\"statement insert failed\"));\n *\n * tx.tables.statement_lines.insertMany(\n * lines.map((l) => ({ statement_id: st.id, category: resolveCategory(l) })),\n * );\n *\n * return { statementId: st.id };\n * });\n */\n transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;\n /**\n * Run `fn` inside a SAVEPOINT, so a write that fails in it does not poison the\n * rest of the request.\n *\n * A request is ONE Postgres transaction: a failed statement aborts it and\n * every later one answers `current transaction is aborted`. That is why\n * \"insert, catch the unique violation, update instead\" cannot be written\n * directly — and why {@link EnvTypedTableBase.upsert} exists for the common\n * case. Reach for `attempt` when the recovery is not an upsert.\n *\n * The handle is a parameter, not the ambient `Database`: only what `tx` writes\n * is inside the boundary, so a concurrent branch of the same request cannot be\n * rolled back by someone else's failure.\n *\n * @example\n * const claimed = await Database.attempt(async (tx) => {\n * await tx.insert(\"seats\", { row: 4, seat: 12, user_id: user.id });\n * return true;\n * }).catch(() => false);\n */\n attempt<T>(fn: (tx: Omit<DBClient, \"attempt\" | \"txPlan\" | \"asService\">) => Promise<T>): Promise<T>;\n /**\n * Return a sibling that bypasses RLS by running as the `service_role`. Use\n * sparingly and explicitly — the default `Database.*` path is RLS-enforced.\n *\n * @example\n * const all = await Database.asService().tables.todos.findMany({});\n * const rows = await Database.asService().query(\"SELECT * FROM todos\");\n */\n asService(): EnvServiceDatabase;\n}\n","/**\n * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`\n * result.\n *\n * The CLI (`palbase build`) and the deploy pipeline call\n * {@link makeEnvDts} with the project's schema and write the returned string to\n * `palbase-env.d.ts` at the project root. That file AUGMENTS the\n * `@palbase/backend/env` `Tables` interface (controlled global augmentation,\n * C5) so `Database.tables.<name>` is typed with no import and no generic.\n *\n * The output is FLAT: each table gets a `{ row: {...}; insert: {...} }` entry\n * with plain TypeScript object types. The phantom `ColumnBuilder<...>` type\n * NEVER appears in the generated `.d.ts` — that type only lives at authoring\n * time inside `db/schema.ts`.\n */\n\nimport type { ColumnDef } from \"./columns.js\";\nimport type { SchemaDef, TableDef } from \"./schema.js\";\n\n/** The TypeScript value type for a column, ignoring nullability (added by the\n * caller). Mirrors the `ColValue` mapped type in columns.ts exactly. */\nfunction baseTsType(def: ColumnDef): string {\n switch (def.type) {\n case \"uuid\":\n case \"text\":\n case \"timestamp\":\n return \"string\";\n case \"integer\":\n return \"number\";\n // Both are exact-precision in Postgres and lossy as a JSON number, so the\n // database proxy serializes them as strings — measured: 9007199254740993\n // used to arrive as ...992 and 41.00821234567890123 as 41.0082123456789.\n // numeric had no case at all and fell through to `unknown`, which typed\n // every numeric column out of existence.\n case \"bigint\":\n case \"numeric\":\n return \"string\";\n case \"boolean\":\n return \"boolean\";\n case \"jsonb\":\n return \"unknown\";\n // FR-008: the authoring type of a pgvector column. The default `unknown`\n // branch below STAYS — an unknown wire type is refused on the Go side\n // (FR-005), never papered over here.\n case \"vector\":\n return \"number[]\";\n case \"enum\": {\n const values = def.enumValues ?? [];\n if (values.length === 0) return \"string\";\n return values.map((v) => JSON.stringify(v)).join(\" | \");\n }\n default:\n return \"unknown\";\n }\n}\n\n/** The full row type for a column: base type, `| null` when nullable. */\nfunction rowType(def: ColumnDef): string {\n const base = baseTsType(def);\n return def.nullable ? `${base} | null` : base;\n}\n\n/** True when a column may be omitted on INSERT — nullable OR has any default.\n * Mirrors `ColIsOptionalOnInsert` in columns.ts. */\nfunction optionalOnInsert(def: ColumnDef): boolean {\n return (\n def.nullable === true ||\n def.defaultRandom === true ||\n def.defaultNow === true ||\n def.defaultValue !== undefined\n );\n}\n\n/** The table a foreign key must target for its column to be the OWNER column —\n * what `.referencesAuthUser(...)` writes into `ColumnDef.references.table`. */\nconst AUTH_USERS_TABLE = \"auth.users\";\n\n/**\n * The table's owner column: the one that foreign-keys `auth.users`, i.e. the\n * column a row is \"owned by\". Declared in `db/schema.ts` via\n * `.referencesAuthUser(...)` — we read the declaration rather than parsing the\n * RLS policy body, because the FK IS the ownership statement.\n *\n * When several columns reference `auth.users` (e.g. `user_id` and `created_by`)\n * the FIRST in declaration order wins — deterministic, and the remaining ones\n * stay ordinary writable columns.\n */\nfunction ownerColumnOf(table: TableDef): string | null {\n for (const [col, builder] of Object.entries(table.columns)) {\n if (builder._def.references?.table === AUTH_USERS_TABLE) return col;\n }\n return null;\n}\n\n/** One FK edge: `child.column` points at the parent table this edge hangs off. */\ntype ChildEdge = { child: string; column: string };\n\n/**\n * Collect the raw parent → children FK edges across the schema.\n *\n * Only edges between tables IN this schema participate — a reference to\n * `auth.users` / `auth.installations` (or any table the project doesn't\n * declare) has no parent bucket and is skipped. Self-FKs are skipped outright.\n *\n * A child that references the same parent through TWO columns is recorded once,\n * on the first column in declaration order: `children` maps a child table to a\n * single FK column, and the second FK stays an ordinary writable column.\n */\nfunction buildChildEdges(schema: SchemaDef): Map<string, ChildEdge[]> {\n const edges = new Map<string, ChildEdge[]>();\n for (const name of Object.keys(schema.tables)) edges.set(name, []);\n\n for (const childName of Object.keys(schema.tables)) {\n const table = schema.tables[childName];\n if (table === undefined) continue;\n for (const [col, builder] of Object.entries(table.columns)) {\n const ref = builder._def.references;\n if (ref === undefined) continue;\n if (ref.table === childName) continue; // self-FK\n const bucket = edges.get(ref.table);\n if (bucket === undefined) continue; // targets a table outside this schema\n if (bucket.some((e) => e.child === childName)) continue; // already linked\n bucket.push({ child: childName, column: col });\n }\n }\n return edges;\n}\n\n/**\n * Drop cycle back-edges from the FK graph.\n *\n * `children` feeds a RECURSIVE type in the seed/fixture DSL\n * (`SeedRow<T>` expands each child's own `children`). A cycle — `lists → todos`\n * plus `todos → lists` through a second FK — would make that type infinite\n * (\"Type instantiation is excessively deep\"). So we walk the graph depth-first\n * in declaration order and drop any edge pointing back at a table currently on\n * the DFS stack. Cross-edges into an already-FINISHED subtree are KEPT: they\n * re-expand a finite subtree, which terminates.\n *\n * Declaration order makes the choice of which edge to drop deterministic (the\n * generated .d.ts is golden-tested).\n */\nfunction pruneCycles(raw: Map<string, ChildEdge[]>): Map<string, ChildEdge[]> {\n const pruned = new Map<string, ChildEdge[]>();\n for (const table of raw.keys()) pruned.set(table, []);\n const state = new Map<string, \"visiting\" | \"done\">();\n\n function visit(table: string): void {\n state.set(table, \"visiting\");\n for (const edge of raw.get(table) ?? []) {\n if (state.get(edge.child) === \"visiting\") continue; // back-edge → drop\n pruned.get(table)?.push(edge);\n if (state.get(edge.child) === undefined) visit(edge.child);\n }\n state.set(table, \"done\");\n }\n\n for (const table of raw.keys()) {\n if (state.get(table) === undefined) visit(table);\n }\n return pruned;\n}\n\n/** Emit the `row` / `insert` / `owner` / `children` blocks for one table at the\n * given base indentation. */\nfunction tableBlock(table: TableDef, children: ChildEdge[], indent: string): string {\n const cols = Object.entries(table.columns);\n const rowLines = cols.map(([col, builder]) => {\n return `${indent} ${col}: ${rowType(builder._def)};`;\n });\n const insertLines = cols.map(([col, builder]) => {\n const def = builder._def;\n const opt = optionalOnInsert(def) ? \"?\" : \"\";\n return `${indent} ${col}${opt}: ${rowType(def)};`;\n });\n const owner = ownerColumnOf(table);\n const childEntries = children\n .map((e) => `${JSON.stringify(e.child)}: ${JSON.stringify(e.column)}`)\n .join(\"; \");\n return [\n `${indent}${table.name}: {`,\n `${indent} row: {`,\n ...rowLines,\n `${indent} };`,\n `${indent} insert: {`,\n ...insertLines,\n `${indent} };`,\n `${indent} owner: ${owner === null ? \"null\" : JSON.stringify(owner)};`,\n `${indent} children: {${childEntries === \"\" ? \"\" : ` ${childEntries} `}};`,\n // searchable: vector kolonu YA DA search beyanı → EnvTypedTable'da search()\n // üyesini açan yapısal bayrak (FR-013). Yokken satır hiç üretilmez ki\n // mevcut şemaların d.ts'i bayt-aynı kalsın.\n ...(cols.some(([, b]) => b._def.type === \"vector\") || table.search !== undefined\n ? [`${indent} searchable: true;`]\n : []),\n `${indent}};`,\n ].join(\"\\n\");\n}\n\n/**\n * Generate the full `palbase-env.d.ts` text for a schema.\n *\n * @example\n * import { makeEnvDts } from \"@palbase/backend\";\n * import schema from \"./db/schema.js\";\n * writeFileSync(\"palbase-env.d.ts\", makeEnvDts(schema));\n */\nexport function makeEnvDts(schema: SchemaDef): string {\n const tableNames = Object.keys(schema.tables);\n const children = pruneCycles(buildChildEdges(schema));\n const blocks = tableNames.map((name) =>\n tableBlock(schema.tables[name]!, children.get(name) ?? [], \" \"),\n );\n const body = blocks.length > 0 ? `\\n${blocks.join(\"\\n\")}\\n ` : \"\";\n return `// AUTO-GENERATED by @palbase/backend — DO NOT EDIT.\n// Regenerated from db/schema.ts by \\`palbase build\\` and by every deploy.\n// Augments the @palbase/backend/env \\`Tables\\` interface so \\`Database.tables.*\\`\n// is typed with no import and no generic.\n\ndeclare module \"@palbase/backend/env\" {\n interface Tables {${body}}\n}\n\nexport {};\n`;\n}\n","/**\n * stack-gen.ts — generate the `palbase-stack.d.ts` text from the names the\n * linked environment's stack holds.\n *\n * The twin of `db/env-gen.ts`: the CLI calls\n * {@link makeStackDts} with the three name sets it read off the stack and\n * writes the result to `palbase-stack.d.ts` at the project root. That file\n * augments the `@palbase/backend/stack` interfaces, so `Secrets.get(...)`, the\n * Flags client and `@Upload({ bucket })` accept the project's real names and\n * nothing else.\n *\n * The generator does NOT reach the network and does NOT decide what a name is:\n * it renders what it is handed. The stack is the authority on which names exist\n * (`GET /v1/management/secrets`, `/flags`, `/storage/buckets`); re-deciding that\n * here would be a second, weaker copy of it.\n *\n * The emitted file ends in `export {};` — same as `makeEnvDts` and\n * `makePurchasesDts`. Without it the `.d.ts` is a global script, and\n * `declare module \"…\"` there DECLARES an ambient module (shadowing the real one,\n * so every name silently becomes invalid) instead of AUGMENTING it.\n */\n\n/** The three name sets read off the stack. Order is irrelevant — each set is\n * sorted here so the same stack always renders the same bytes and a diff shows\n * what CHANGED rather than how the API happened to order its answer. */\n/** One bucket and the renditions it declares. */\nexport interface BucketInput {\n name: string;\n variants: readonly string[];\n}\n\nexport interface StackNames {\n /** Secret names from the project's vault. */\n secrets: readonly string[];\n /** Flag keys from the project's flag store. */\n flags: readonly string[];\n /**\n * Buckets from the project's storage — a bare name, or a name with the\n * renditions it declares.\n *\n * A bucket is not only a NAME: `Storage.buckets.docs.getPublicUrl(p, {\n * variant })` refuses a rendition the bucket does not have, so the variant\n * union has to travel with it. The bare-string form is shorthand for \"no\n * variants\", which renders `never` and accepts none.\n */\n buckets: readonly (string | BucketInput)[];\n}\n\n/** Sorted, de-duplicated names. A stack that reports one twice (two pages of a\n * listing overlapping, say) must not render a duplicate member — TypeScript\n * accepts it, but the file stops being a function of the stack's contents. */\nfunction liveNames(names: readonly string[]): string[] {\n return [...new Set(names)].sort();\n}\n\n/** A bare identifier stays bare; anything else is quoted. Bucket names carry\n * dashes and dots (the Storage module's allowed shape), and an unquoted\n * `my-bucket` parses as a subtraction rather than a member name. */\nfunction memberName(name: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n}\n\nfunction members(names: string[]): string {\n if (names.length === 0) return \"\";\n return `\\n${names.map((n) => ` ${memberName(n)}: true;`).join(\"\\n\")}\\n `;\n}\n\n/** Buckets render a SHAPE rather than a marker, because each carries its variant\n * union. `never` for a bucket with none: the type then accepts no variant name\n * at all, which is exactly what a bucket without renditions offers. */\nfunction bucketMembers(buckets: readonly (string | BucketInput)[]): string {\n const normalized = buckets.map((b) => (typeof b === \"string\" ? { name: b, variants: [] as readonly string[] } : b));\n const byName = new Map<string, readonly string[]>();\n for (const b of normalized) byName.set(b.name, b.variants);\n const names = [...byName.keys()].sort();\n if (names.length === 0) return \"\";\n const rows = names.map((name) => {\n const variants = [...new Set(byName.get(name) ?? [])].sort();\n const union = variants.length === 0 ? \"never\" : variants.map((v) => JSON.stringify(v)).join(\" | \");\n return ` ${memberName(name)}: { variants: ${union} };`;\n });\n return `\\n${rows.join(\"\\n\")}\\n `;\n}\n\n/**\n * Render the project's `palbase-stack.d.ts`.\n *\n * An empty set renders an empty interface, which is a MEANINGFUL value: the\n * stack holds no such names, so the corresponding union is `never` and every\n * call spelling one fails to compile. It is not the same as \"the file was never\n * generated\" only in that the file exists — both states refuse every name, and\n * both are correct.\n */\nexport function makeStackDts(names: StackNames): string {\n const secrets = liveNames(names.secrets);\n const flags = liveNames(names.flags);\n\n\n return `// palbase-stack.d.ts — GENERATED by @palbase/backend. Do not edit.\n// Source: the linked environment's stack.\n\ndeclare module \"@palbase/backend/stack\" {\n interface Secrets {${members(secrets)}}\n\n interface Flags {${members(flags)}}\n\n interface Buckets {${bucketMembers(names.buckets)}}\n}\n\nexport {};\n`;\n}\n","// The decorator registry — the single plain-data store the method + parameter\n// decorators write into, and the deploy/dispatch pipeline reads back. No\n// `reflect-metadata`, no `emitDecoratorMetadata`: the registry is built from the\n// decorator arguments + the parameter INDEX that esbuild/tsc preserve for legacy\n// parameter decorators (verified — see the design spec §0/§4.1).\n//\n// A controller class carries its route metadata on a symbol-keyed static\n// property (`ROUTES`). `@Get`/`@Post`/… append a {@link RouteMeta} entry;\n// `@Body`/`@User`/… append a {@link ParamMeta} entry onto the route for the\n// method they decorate. Because parameter decorators run BEFORE the method\n// decorator for the same member (TS evaluates innermost-first, params before the\n// method), the route entry may not exist yet when a param decorator fires — so\n// param metadata is buffered per method name and merged when the method\n// decorator creates the route entry.\nimport type { AuthSpec, RateLimitConfig } from \"../endpoint.js\";\nimport type { UploadConfig } from \"./upload.js\";\nimport type { SseConfig } from \"./sse.js\";\nimport type { ZodTypeAny } from \"zod\";\n\n/** The HTTP verbs a route may declare, upper-cased (the runtime router +\n * OpenAPI lower-case on their own). */\nexport type HttpMethodUpper = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"QUERY\";\n\n/** Route-level options accepted by the method decorators (`@Get`/`@Post`/…). */\nexport interface RouteOptions {\n /** OVERRIDES the controller-level default auth for this one route. */\n auth?: AuthSpec;\n /** Per-route rate limit. */\n rateLimit?: RateLimitConfig;\n /** Direct-storage upload config — present ONLY on `@Upload` routes (the\n * `@Get`/`@Post`/… decorators never set it). Its presence is what MARKS a\n * route as an upload route through the whole pipeline (registry → flatten →\n * openapi → codegen). The bytes go client→storage directly; the method body\n * runs as the completion handler. See {@link UploadConfig} (decorators/upload.ts). */\n uploadConfig?: UploadConfig;\n /** Streaming config — present ONLY on `@Sse` routes (the `@Get`/`@Post`/…\n * decorators never set it). Its presence is what MARKS a route as a streaming\n * route through the whole pipeline (registry → flatten → openapi → codegen),\n * exactly as `uploadConfig` does for uploads — never a special HTTP verb. An\n * `@Sse` route registers POST like any input-bearing route, so the verb cannot\n * carry the distinction. See {@link SseConfig} (decorators/sse.ts). */\n sseConfig?: SseConfig;\n}\n\n/** The kind of value a parameter decorator injects. Drives both dispatch\n * (which request slice to inject) and codegen (which OpenAPI parameter source a\n * schema-bearing kind maps to). */\nexport type ParamKind =\n | \"body\"\n | \"query\"\n | \"param\"\n | \"headers\"\n | \"user\"\n | \"optionalUser\"\n | \"client\"\n | \"requestId\"\n | \"traceId\"\n | \"req\"\n // `@UploadedObject()` — injects the uploaded object (completion input) on an\n // `@Upload` route. No schema (the shape is the fixed UploadedObject type).\n | \"uploadedObject\"\n // `@SseOut()` — injects the frame writer on an `@Sse` route. No schema (the\n // shape is the fixed SseWriter type).\n | \"sseOut\"\n // `@Signal()` — injects the request's AbortSignal, which aborts when the\n // client disconnects. No schema. NOT derivable from `@Req()`: PBRequest\n // carries only request-scoped data and has no signal (endpoint.ts:358-363).\n | \"signal\";\n\n/** One parameter decorator's recorded metadata. `index` is the parameter\n * position esbuild/tsc preserve; `schema` is present for the schema-bearing\n * kinds (`body`/`query`/`headers`); `name` is the path-param name for `param`. */\nexport interface ParamMeta {\n index: number;\n kind: ParamKind;\n /** Zod schema for `body`/`query`/`headers` (validation + codegen source). */\n schema?: ZodTypeAny;\n /** Path-param name for `@Param(\"id\")`. */\n name?: string;\n}\n\n/** One inferred throw site: the error CLASS name (e.g. \"TodoLocked\") and its\n * wire code (e.g. \"todo_locked\"). `status`, `hasData`, and the data JSON schema\n * are NOT carried here — they resolve from the error registry by `code` at\n * extract/openapi time (single source of truth). */\nexport interface ThrowDescriptor {\n name: string;\n code: string;\n}\n\n/** One route's recorded metadata: the verb + subpath + method name + options,\n * the ordered parameter metas, and the resolved return schema (injected by the\n * codegen step — see `returnSchema`). */\nexport interface RouteMeta {\n method: HttpMethodUpper;\n subpath: string;\n fnName: string;\n options: RouteOptions;\n params: ParamMeta[];\n /** Response schema for the route, if any. Derived from the method's RETURN\n * TYPE by codegen and written here via `recordReturn` (a generated top-level\n * IIFE injected per controller), not by an author-written decorator. */\n returnSchema?: ZodTypeAny;\n /** Error classes this route can throw, if inferred. Derived from the method\n * body + service call graph by the deploy stager's throw analysis and written\n * here via `recordThrows` (a generated top-level IIFE injected per controller,\n * the `recordReturn` twin), not by an author-written decorator. */\n throws?: ThrowDescriptor[];\n}\n\n/** Symbol the route metadata list is stored under on a controller class. Using\n * a symbol (not a string key) keeps it off the public structural surface and\n * avoids any chance of an authored property collision. */\nexport const ROUTES: unique symbol = Symbol.for(\"palbase.backend.routes\");\n\n/** Symbol the per-method buffered parameter metas are stored under while a class\n * is being decorated. Parameter decorators fire before the method decorator, so\n * they buffer here keyed by method name; the method decorator drains the buffer\n * into the route entry it creates. */\nconst PARAM_BUFFER: unique symbol = Symbol.for(\"palbase.backend.paramBuffer\");\n\n/** Symbol the per-method buffered return-type schemas are stored under while a\n * class's registry is being populated. The codegen-injected `recordReturn` call\n * can fire before OR after the method decorator; it buffers here keyed by method\n * name and `recordRoute` drains it into the route entry (and `recordReturn`\n * writes through if the route already exists). Buffering on BOTH sides means a\n * fully-formed route entry always carries its return schema — a raw-symbol\n * reader (the runtime) never has to re-merge. */\nconst RETURN_BUFFER: unique symbol = Symbol.for(\"palbase.backend.returnBuffer\");\n\n/** Symbol the per-method buffered throw descriptors are stored under while a\n * class's registry is being populated. The stager-injected `recordThrows` call\n * can fire before OR after the method decorator; it buffers here keyed by method\n * name and `recordRoute` drains it into the route entry (and `recordThrows`\n * writes through if the route already exists). Buffering on BOTH sides means a\n * fully-formed route entry always carries its throw descriptors — a raw-symbol\n * reader (the runtime) never has to re-merge. */\nconst THROWS_BUFFER: unique symbol = Symbol.for(\"palbase.backend.throwsBuffer\");\n\n/** A class constructor carrying the symbol-keyed registry slots. We type the\n * registry-bearing class as this so the decorators can read/write the slots\n * without `any` — a plain `Function` does not carry index signatures. */\ninterface RegistryCarrier {\n [ROUTES]?: RouteMeta[];\n [PARAM_BUFFER]?: Record<string, ParamMeta[]>;\n [RETURN_BUFFER]?: Record<string, ZodTypeAny>;\n [THROWS_BUFFER]?: Record<string, ThrowDescriptor[]>;\n}\n\n/** Coerce a decorated target (class constructor or its prototype) into the\n * registry carrier that owns the slots. Method/param decorators receive the\n * PROTOTYPE as their target; the class decorator receives the constructor. We\n * always anchor the registry on the CONSTRUCTOR so `getRoutes(ctor)` finds it. */\nfunction carrierOf(target: object): RegistryCarrier {\n // For instance-member decorators, `target` is the prototype; its `.constructor`\n // is the class. For a static member or the class decorator, `target` is the\n // constructor already. Resolve to the constructor either way.\n const ctor =\n typeof target === \"function\"\n ? (target as unknown as RegistryCarrier)\n : (((target as { constructor?: unknown }).constructor ??\n target) as unknown as RegistryCarrier);\n return ctor;\n}\n\n/** Get (creating if absent) the own route list for a class constructor. Own —\n * not inherited — so a subclass does not mutate its base's routes. */\nfunction ownRoutes(carrier: RegistryCarrier): RouteMeta[] {\n if (!Object.prototype.hasOwnProperty.call(carrier, ROUTES)) {\n carrier[ROUTES] = [];\n }\n return carrier[ROUTES] as RouteMeta[];\n}\n\n/** Get (creating if absent) the own per-method param buffer for a class. */\nfunction ownParamBuffer(carrier: RegistryCarrier): Record<string, ParamMeta[]> {\n if (!Object.prototype.hasOwnProperty.call(carrier, PARAM_BUFFER)) {\n carrier[PARAM_BUFFER] = {};\n }\n return carrier[PARAM_BUFFER] as Record<string, ParamMeta[]>;\n}\n\n/** Record a route (called by the method decorators). Drains any parameter\n * metas already buffered for `fnName` into the new route entry, then sorts them\n * by parameter index so dispatch can inject positionally. */\nexport function recordRoute(\n target: object,\n fnName: string,\n method: HttpMethodUpper,\n subpath: string,\n options: RouteOptions,\n): void {\n const carrier = carrierOf(target);\n const routes = ownRoutes(carrier);\n const buffer = ownParamBuffer(carrier);\n const params = (buffer[fnName] ?? []).slice().sort((a, b) => a.index - b.index);\n const route: RouteMeta = { method, subpath, fnName, options, params };\n // Drain a buffered return schema (the recordReturn-ran-first ordering) so the\n // route entry is complete the moment it's created — a raw-symbol consumer\n // (the runtime extractor/worker) sees the return schema without re-merging.\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer && returnBuffer[fnName] !== undefined) {\n route.returnSchema = returnBuffer[fnName];\n }\n // Same drain for buffered throw descriptors (the recordThrows-ran-first\n // ordering) — the route entry is complete the moment it's created.\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer && throwsBuffer[fnName] !== undefined) {\n route.throws = throwsBuffer[fnName];\n }\n routes.push(route);\n}\n\n/** Record one parameter decorator (called by `@Body`/`@User`/…). Buffers per\n * method name; the method decorator merges the buffer into the route entry. If\n * the route already exists (method decorator ran first — TS does evaluate the\n * method decorator AFTER its parameter decorators, but we stay order-robust),\n * the meta is also appended directly so neither ordering loses it. */\nexport function recordParam(target: object, fnName: string, meta: ParamMeta): void {\n const carrier = carrierOf(target);\n const buffer = ownParamBuffer(carrier);\n (buffer[fnName] ??= []).push(meta);\n\n // Order-robust: if the route already exists, merge in place + keep sorted.\n const routes = carrier[ROUTES];\n if (routes) {\n const route = routes.find((r) => r.fnName === fnName);\n if (route) {\n route.params.push(meta);\n route.params.sort((a, b) => a.index - b.index);\n }\n }\n}\n\n/** Attach a return schema to the route for `fnName` (called by the codegen\n * injection that reads the method's return type). If the route does not exist\n * yet, the schema is buffered (RETURN_BUFFER) and drained into the route by\n * `recordRoute` when the method decorator runs. */\nexport function recordReturn(target: object, fnName: string, schema: ZodTypeAny): void {\n const carrier = carrierOf(target);\n const routes = carrier[ROUTES];\n const route = routes?.find((r) => r.fnName === fnName);\n if (route) {\n route.returnSchema = schema;\n return;\n }\n if (!Object.prototype.hasOwnProperty.call(carrier, RETURN_BUFFER)) {\n carrier[RETURN_BUFFER] = {};\n }\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer) returnBuffer[fnName] = schema;\n}\n\n/** Attach the inferred throw descriptors to the route for `fnName` (called by\n * the stager-injected IIFE that carries the throw analysis result — the\n * `recordReturn` twin). If the route does not exist yet, the descriptors are\n * buffered (THROWS_BUFFER) and drained into the route by `recordRoute` when the\n * method decorator runs. */\nexport function recordThrows(target: object, fnName: string, throws: ThrowDescriptor[]): void {\n const carrier = carrierOf(target);\n const routes = carrier[ROUTES];\n const route = routes?.find((r) => r.fnName === fnName);\n if (route) {\n route.throws = throws;\n return;\n }\n if (!Object.prototype.hasOwnProperty.call(carrier, THROWS_BUFFER)) {\n carrier[THROWS_BUFFER] = {};\n }\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer) throwsBuffer[fnName] = throws;\n}\n\n/** Read the route metadata for a controller class (the deploy/dispatch entry\n * point). Applies any buffered return schemas + throw descriptors (for the\n * recordReturn/recordThrows-runs-before orderings) and returns a defensive copy\n * so callers cannot mutate the registry.\n */\nexport function getRoutes(ctor: object): RouteMeta[] {\n const carrier = carrierOf(ctor);\n const routes = carrier[ROUTES] ?? [];\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer) {\n for (const route of routes) {\n const buffered = returnBuffer[route.fnName];\n if (buffered && route.returnSchema === undefined) {\n route.returnSchema = buffered;\n }\n }\n }\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer) {\n for (const route of routes) {\n const buffered = throwsBuffer[route.fnName];\n if (buffered && route.throws === undefined) {\n route.throws = buffered;\n }\n }\n }\n return routes.map((r) => ({\n ...r,\n params: r.params.slice(),\n ...(r.throws !== undefined ? { throws: r.throws.slice() } : {}),\n }));\n}\n","// `@Controller(basePath, options?)` — the class decorator that marks a class as\n// a Palbase backend controller. It stamps a non-enumerable `__palbase`\n// discriminant + the resolved controller metadata onto the class so the\n// deploy/dispatch pipeline (and `isController`/`resolveController`) can detect\n// and read it without `reflect-metadata`.\nimport type { AuthSpec } from \"../endpoint.js\";\nimport { getRoutes } from \"./registry.js\";\n\n/** The controller metadata stamped onto a `@Controller`-decorated class. The\n * default export of a `controllers/*.controller.ts` file resolves to this via\n * {@link resolveController}. */\nexport interface ControllerMeta {\n /** Discriminant the runtime + tooling read. */\n readonly __palbase: \"controller\";\n /** The base path every route in this controller mounts under (e.g. \"/todos\"). */\n basePath: string;\n /** Controller-level default auth, applied to routes that don't set their own\n * (`@Get(\"/x\", { auth })` overrides this). `undefined` ⇒ the application\n * default ({@link defineDefaultAuth}), and secure-by-default below that —\n * see {@link resolveEffectiveAuth} for the whole cascade. */\n defaultAuth?: AuthSpec;\n}\n\n/** Options accepted by `@Controller`. */\nexport interface ControllerOptions {\n /** Default auth for ALL routes in this controller (route-level overrides;\n * omitting it falls through to the application default declared with\n * {@link defineDefaultAuth}). */\n auth?: AuthSpec;\n}\n\n/** Symbol the controller metadata is stamped under. Symbol-keyed (not a string\n * property) so it never collides with an authored member and stays off the\n * structural surface. */\nexport const CONTROLLER_META: unique symbol = Symbol.for(\"palbase.backend.controllerMeta\");\n\n/**\n * Every class `@Controller` has decorated, in decoration order.\n *\n * This is what lets a controller file need no export at all: importing the file\n * runs the decorator, the decorator records the class here, and the runtime\n * reads the list. Without it the only handle on a class is its export name, so\n * every controller had to be exported AND named in a generated entry — the\n * ceremony NestJS still charges (`export class` PLUS\n * `@Module({controllers:[…]})`).\n *\n * Keyed on a well-known Symbol against globalThis rather than held in a module\n * variable, because a deployed bundle inlines its own copy of this package: two\n * copies would keep two lists, and the runtime would read the empty one. The\n * same hazard `runtimeHooks` exists for, closed the same way — one shared slot.\n */\nconst REGISTRY: unique symbol = Symbol.for(\"palbase.backend.allControllers\") as never;\n\nfunction registry(): unknown[] {\n const g = globalThis as unknown as Record<symbol, unknown[] | undefined>;\n const existing = g[REGISTRY];\n if (existing) return existing;\n const fresh: unknown[] = [];\n g[REGISTRY] = fresh;\n return fresh;\n}\n\n/**\n * The controller classes this process has loaded, in decoration order.\n *\n * Decoration order is import order, which the bundler fixes by sorting the\n * files it emits imports for — so two builds of one tree produce the same\n * route table, and route precedence is not a function of module-resolution\n * accidents.\n */\nexport function getRegisteredControllers(): readonly unknown[] {\n return registry().slice();\n}\n\n/** Empty the registry. For tests, which load controllers repeatedly. */\nexport function __resetRegisteredControllers(): void {\n registry().length = 0;\n}\n\n/**\n * The APPLICATION-level default auth.\n *\n * Held on globalThis under a well-known Symbol for exactly the reason\n * {@link REGISTRY} is: a deployed bundle inlines its own copy of this package,\n * and two copies keeping two defaults is how a security setting silently\n * becomes two different settings.\n */\nconst APP_DEFAULT_AUTH: unique symbol = Symbol.for(\"palbase.backend.appDefaultAuth\") as never;\n\nfunction appAuthSlot(): Record<symbol, AuthSpec | undefined> {\n return globalThis as unknown as Record<symbol, AuthSpec | undefined>;\n}\n\n/**\n * Declare the default auth for EVERY route in the application — the ring the\n * cascade consults when neither the route nor its controller says anything.\n *\n * The measured problem it removes: `auth: { verifiedEmail: true }` repeated by\n * hand on ten `@Controller`s. A security setting that must be repeated is a\n * security setting that will be forgotten — the eleventh controller opens the\n * door and nothing says so.\n *\n * Call it at MODULE SCOPE in a file the application imports (the controllers'\n * own barrel, or a module a controller imports). The cascade reads this slot\n * when the route table is built and when the spec is emitted — both of which\n * run after module loading — so declaration order does not matter, but being\n * imported at all does.\n *\n * @example\n * defineDefaultAuth({ verifiedEmail: true }); // every route, unless it says otherwise\n */\nexport function defineDefaultAuth(auth: AuthSpec): void {\n appAuthSlot()[APP_DEFAULT_AUTH] = auth;\n}\n\n/** The declared application default, or `undefined` when none was declared. */\nexport function getDefaultAuth(): AuthSpec | undefined {\n return appAuthSlot()[APP_DEFAULT_AUTH];\n}\n\n/** Clear the application default. For tests, which declare it repeatedly. */\nexport function __resetDefaultAuth(): void {\n delete appAuthSlot()[APP_DEFAULT_AUTH];\n}\n\n/**\n * THE auth cascade: route → controller → application → `true`.\n *\n * One function, every caller — the route table (`engine/router.ts`) and the\n * spec emitter (`openapi/controllers.ts`) ASK for the answer instead of\n * spelling the chain themselves. Two hand-written copies of a cascade is how\n * the build-time answer and the runtime answer come to disagree about who may\n * call an endpoint, and the disagreement shows up as an open door.\n *\n * The terminal `true` is secure-by-default and is load-bearing: a route that\n * declared nothing, under a controller that declared nothing, in an\n * application that declared nothing, is CLOSED.\n */\nexport function resolveEffectiveAuth(\n routeAuth: AuthSpec | undefined,\n controllerAuth: AuthSpec | undefined,\n): AuthSpec {\n return routeAuth ?? controllerAuth ?? getDefaultAuth() ?? true;\n}\n\n/** A class carrying the stamped controller metadata + discriminant. */\ninterface ControllerCarrier {\n __palbase?: \"controller\";\n [CONTROLLER_META]?: ControllerMeta;\n}\n\n/** The one path segment the platform owns. The isolate matches\n * `^/webhooks/([^/]+)$` on the raw request path BEFORE controller dispatch, so\n * anything a controller resolves to under it answers `404 webhook_not_found`\n * and never runs. */\nconst RESERVED_FIRST_SEGMENT = \"webhooks\";\n\n/**\n * Throw if `path` resolves under the reserved segment. Segments are compared the\n * way the isolate compares them — `split(\"/\").filter(Boolean)` — NOT by string\n * prefix, because empty segments collapse there: `@Controller(\"/\")` +\n * `@Post(\"/webhooks/x\")` composes to `//webhooks/x`, which the isolate serves as\n * `/webhooks/x`. A prefix check reads that as safe; the segment check does not.\n * `/webhooksy` stays allowed for the same reason — it is a different segment.\n *\n * Every verb is refused, not just the POST the isolate currently intercepts: the\n * reservation is of the URL namespace, so a `@Get(\"/webhooks/x\")` that happens\n * to work today would be silently shadowed the moment the isolate's method gate\n * widens. Refusing at build is recoverable; discovering it as a 404 is not.\n */\nfunction assertNotReserved(path: string, subject: string): void {\n const [first] = path.split(\"/\").filter(Boolean);\n if (first === RESERVED_FIRST_SEGMENT) {\n throw new Error(\n `${subject} resolves under the reserved /${RESERVED_FIRST_SEGMENT} path — ` +\n \"inbound webhooks are served there and would shadow this route\",\n );\n }\n}\n\n/**\n * Mark a class as a Palbase backend controller. `basePath` is the mount path\n * for every route the class declares; `options.auth` sets the controller-level\n * default auth (a route's own `auth` overrides it; absent ⇒ secure-by-default).\n *\n * @example\n * \\@Controller(\"/todos\", { auth: false })\n * export class TodosController {\n * \\@Get(\"\") list(\\@QueryParams(ListTodosQuery) q: ListTodosQuery): TodoSchema[] { … }\n * }\n */\nexport function Controller(basePath: string, options: ControllerOptions = {}) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n // /webhooks/* belongs to the platform: the isolate matches the inbound\n // webhook route before controller dispatch, so a controller mounted here\n // would never receive a request. Silent shadowing is the failure mode this\n // whole change exists to remove, so refuse it at build.\n //\n // The COMPOSED path is what gets shadowed, not the base path. `@Controller(\"\")`\n // and `@Controller(\"/\")` both pass a base-path-only check while a\n // `@Post(\"/webhooks/stripe\")` inside them resolves to exactly the path the\n // isolate intercepts. Method decorators run BEFORE the class decorator (TS\n // evaluates members first), so every route this class declares is already in\n // the registry here — which is why the composed check can live at this one\n // seam instead of on the dispatch read path. The `@Controller(\"\") +\n // @Post(\"/webhooks/stripe\")` test is the lock on that ordering: if it ever\n // stopped holding, that test goes red.\n assertNotReserved(basePath, `@Controller(\"${basePath}\")`);\n for (const route of getRoutes(ctor)) {\n assertNotReserved(\n `${basePath}${route.subpath}`,\n `@${route.method}(\"${route.subpath}\") in @Controller(\"${basePath}\")`,\n );\n }\n\n const carrier = ctor as unknown as ControllerCarrier;\n const meta: ControllerMeta = {\n __palbase: \"controller\",\n basePath,\n ...(options.auth !== undefined ? { defaultAuth: options.auth } : {}),\n };\n // Non-enumerable so it doesn't leak onto instances / structural checks.\n Object.defineProperty(carrier, CONTROLLER_META, {\n value: meta,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // The bare `__palbase` discriminant is the cheap detection marker the\n // runtime/extractor checks; keep it readable but non-enumerable.\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"controller\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // Record it, so importing the file is enough and exporting is optional.\n // Guarded against a double-decoration re-entering the same class twice.\n const all = registry();\n if (!all.includes(ctor)) all.push(ctor);\n return ctor;\n };\n}\n\n/** True when `value` is a `@Controller`-decorated class (cheap discriminant\n * check). Accepts the class constructor (the default export of a controller\n * file). */\nexport function isController(value: unknown): boolean {\n if (typeof value !== \"function\" && (typeof value !== \"object\" || value === null)) {\n return false;\n }\n const carrier = value as ControllerCarrier;\n return carrier.__palbase === \"controller\" && carrier[CONTROLLER_META] !== undefined;\n}\n\n/** Read the resolved controller metadata off a `@Controller`-decorated class.\n * Throws if the class was not decorated — callers should gate with\n * {@link isController} first (the loader does). */\nexport function resolveController(ctor: unknown): ControllerMeta {\n if (typeof ctor !== \"function\" && (typeof ctor !== \"object\" || ctor === null)) {\n throw new TypeError(\"resolveController: value is not a class\");\n }\n const meta = (ctor as ControllerCarrier)[CONTROLLER_META];\n if (!meta) {\n throw new TypeError(\n \"resolveController: class is not a @Controller — every controller file must `export default` a @Controller-decorated class\",\n );\n }\n return meta;\n}\n\n/**\n * A class the runtime constructs takes NO constructor parameters.\n *\n * ONE writer, four callers (controller, hook, job, webhook) and the build's own\n * check. Four hand-written copies of this message is how the four come to\n * disagree about what is refused — and the disagreement is silent, because a\n * class that slips past one of them still ends up with `undefined` fields.\n *\n * Why it is refused rather than injected: there is no container. The parameter\n * would arrive `undefined`, the code would compile, deploy, and fail at the\n * first request that touches the field — the most expensive place to learn it.\n */\nexport function assertZeroArgConstructor(Ctrl: unknown, kind: string): void {\n const arity = (Ctrl as { length?: number }).length ?? 0;\n if (arity === 0) return;\n const name = (Ctrl as { name?: string }).name ?? \"<anonymous>\";\n throw new Error(\n `${kind} ${name} declares a constructor with ${arity} parameter(s). ` +\n `A ${kind} is constructed by the runtime with a zero-argument constructor — ` +\n `there is no injector to supply them, so every parameter would arrive as ` +\n `undefined. Hold the dependency as a module-level singleton the ${kind} ` +\n \"imports (`const repo = makeRepo()` beside the class), and construct the \" +\n \"service directly in tests (e.g. `new TodoService(fakeDatabase().db)`).\",\n );\n}\n","// Method decorators: `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` /\n// `@Query` declare a route (verb + subpath + options) on a controller method. These are LEGACY\n// method decorators (`experimentalDecorators`), receiving\n// `(prototype, methodName, descriptor)`. They write into the per-class registry\n// (registry.ts). The success-response schema is NOT declared here: it is derived\n// from the method's RETURN TYPE by a codegen step and injected onto the route at\n// runtime via `recordReturn` (registry.ts).\nimport {\n recordRoute,\n type HttpMethodUpper,\n type RouteOptions,\n} from \"./registry.js\";\n\n/** A legacy method decorator. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** Build a method decorator for one HTTP verb. The decorated method's name is\n * the route `fnName` — and it is PUBLIC API, not authoring sugar: the runtime\n * derives the operationId as `<controllerName>.<fnName>` (the dotted namespace\n * the SDKs expose as `pb.todos.list()`), so renaming this method renames every\n * client call. The flat verb+path id is only the fallback for routes with no\n * controller metadata. See openapi/discover.ts. */\nfunction makeMethodDecorator(method: HttpMethodUpper) {\n return function (subpath: string, options: RouteOptions = {}): MethodDecorator {\n // Runtime guard for stale pre-9.0.0 code: `@Query(zodSchema)` used to be\n // the query-string PARAM decorator. Applied against this SDK it would\n // silently record a garbage route (schema-as-subpath) and fail the deploy\n // with a baffling self-conflict — fail loud and name the migration instead.\n if (typeof subpath !== \"string\") {\n throw new Error(\n `@${method[0]}${method.slice(1).toLowerCase()}(subpath) expects a string subpath, got ${typeof subpath}.` +\n (method === \"QUERY\"\n ? \" If this is a zod schema on a method parameter: the query-string param decorator was renamed @QueryParams(schema) in @palbase/backend 9.0.0.\"\n : \"\"),\n );\n }\n return function (target, propertyKey) {\n recordRoute(target, String(propertyKey), method, subpath, options);\n };\n };\n}\n\n/** `@Get(subpath, options?)` — declare a GET route. */\nexport const Get = makeMethodDecorator(\"GET\");\n/** `@Post(subpath, options?)` — declare a POST route. */\nexport const Post = makeMethodDecorator(\"POST\");\n/** `@Put(subpath, options?)` — declare a PUT route. */\nexport const Put = makeMethodDecorator(\"PUT\");\n/** `@Patch(subpath, options?)` — declare a PATCH route. */\nexport const Patch = makeMethodDecorator(\"PATCH\");\n/** `@Delete(subpath, options?)` — declare a DELETE route. */\nexport const Delete = makeMethodDecorator(\"DELETE\");\n/** `@Query(subpath, options?)` — declare an HTTP QUERY route (RFC 10008):\n * safe + idempotent like GET, body-carrying like POST. Input rides `@Body`. */\nexport const Query = makeMethodDecorator(\"QUERY\");\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Webhook / @On — the inbound-webhook half of the decorator surface.\n//\n// Mirrors decorators/controller.ts exactly: symbol-keyed, non-enumerable\n// metadata on the constructor plus a `__palbase` discriminant, read back by a\n// resolver. The resolver is the ONLY translation point — it returns the shape\n// the runtime already consumes, so the isolate's dispatch and the signature\n// engine's cross-binding golden are untouched by the authoring change.\nimport type { WebhookMeta, WebhookProvider } from \"../webhook.js\";\n\n/** A signature scheme spelled out, for a service with no preset. The presets\n * (`provider`) are named configurations of this same shape. */\nexport interface SignatureSpec {\n /** Header carrying the signature. */\n header: string;\n /** Stripped before comparison (e.g. `sha256=`). Omit when absent. */\n prefix?: string;\n algo: \"hmac-sha256\" | \"hmac-sha1\";\n encoding: \"hex\" | \"base64\";\n /** What the HMAC covers. Exactly two placeholders: `{body}` and `{ts}`.\n * Everything else is literal. `{ts}` requires `timestampHeader` and brings\n * the five-minute replay window with it. */\n signs: string;\n timestampHeader?: string;\n}\n\nexport interface WebhookOptions {\n provider?: WebhookProvider;\n signature?: SignatureSpec;\n /** Env-var REFERENCE for the signing secret — the platform never holds it. */\n secret: { env: string };\n}\n\nexport type WebhookEventHandler = (event: unknown, meta: WebhookMeta) => Promise<void>;\n\nexport interface ResolvedWebhook {\n provider?: WebhookProvider;\n signature?: SignatureSpec;\n secret: { env: string };\n events: Record<string, WebhookEventHandler>;\n}\n\nexport const WEBHOOK_META: unique symbol = Symbol.for(\"palbase.backend.webhookMeta\");\nexport const WEBHOOK_EVENTS: unique symbol = Symbol.for(\"palbase.backend.webhookEvents\");\n\ninterface EventEntry {\n event: string;\n fnName: string;\n}\n\ninterface WebhookCarrier {\n __palbase?: \"webhook\";\n [WEBHOOK_META]?: WebhookOptions;\n [WEBHOOK_EVENTS]?: EventEntry[];\n}\n\nfunction carrierOf(ctor: object): WebhookCarrier {\n return ctor as WebhookCarrier;\n}\n\n/** Mark a class as an inbound webhook. The mount name is the FILE name — there\n * is deliberately no `name` option, because the file name IS the public URL. */\nexport function Webhook(options: WebhookOptions) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n const carrier = carrierOf(ctor);\n Object.defineProperty(carrier, WEBHOOK_META, {\n value: options,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"webhook\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return ctor;\n };\n}\n\n/** Bind a method to one event name. Any string is valid: presets provide\n * autocomplete, never a constraint, because we do not carry provider catalogs. */\nexport function On(event: string) {\n return function (target: object, fnName: string | symbol): void {\n // Method decorators receive the PROTOTYPE; metadata belongs on the ctor.\n const carrier = carrierOf((target as { constructor: object }).constructor);\n const existing = carrier[WEBHOOK_EVENTS];\n const entries: EventEntry[] = existing ? [...existing] : [];\n entries.push({ event, fnName: String(fnName) });\n Object.defineProperty(carrier, WEBHOOK_EVENTS, {\n value: entries,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n };\n}\n\n/** Read a decorated class back as the resolved config the runtime consumes.\n * Every misuse throws HERE, at build time, rather than becoming a webhook that\n * answers 200 and does nothing.\n *\n * @throws when the class declares constructor parameters (FR-011) — nothing\n * here supplies them, so the field would be `undefined` on every delivery. */\nexport function getWebhookConfig(ctor: object): ResolvedWebhook {\n const carrier = carrierOf(ctor);\n const meta = carrier[WEBHOOK_META];\n const entries = carrier[WEBHOOK_EVENTS] ?? [];\n\n if (!meta) {\n throw new Error(\n `@On used on a class that is not decorated with @Webhook (${(ctor as { name?: string }).name ?? \"anonymous\"})`,\n );\n }\n if (!meta.provider && !meta.signature) {\n throw new Error(\n \"@Webhook requires either a `provider` preset or an explicit `signature` — \" +\n \"an endpoint with no verification would accept forged deliveries\",\n );\n }\n // EITHER, not both. The isolate picks `provider` when both are present and\n // never looks at `signature`, so a tenant that wrote both gets deliveries\n // verified against a scheme they did not choose — silently, and with no way to\n // tell from the outside which one ran. Ambiguity about WHICH signature check\n // guards an endpoint is not something to resolve by precedence.\n if (meta.provider && meta.signature) {\n throw new Error(\n \"@Webhook declares BOTH a `provider` preset and an explicit `signature` — \" +\n \"these are alternatives; keep the one that describes the sender, because only `provider` would be used\",\n );\n }\n if (meta.signature) {\n const sig = meta.signature;\n // Mirrors Go's NewTemplateVerifier (internal/webhook/verify.go). Both sides\n // reject the same specs; this one rejects at build, which is the only place\n // a tenant can still act on it.\n if (!sig.header) {\n throw new Error(\"@Webhook signature requires `header` — the header the signature arrives in\");\n }\n if (sig.algo !== \"hmac-sha256\" && sig.algo !== \"hmac-sha1\") {\n throw new Error(`@Webhook signature has an unsupported algo \"${sig.algo}\"`);\n }\n if (sig.encoding !== \"hex\" && sig.encoding !== \"base64\") {\n throw new Error(`@Webhook signature has an unsupported encoding \"${sig.encoding}\"`);\n }\n if (!sig.signs?.includes(\"{body}\")) {\n throw new Error(\"@Webhook signature `signs` must contain {body} — signing a constant is not a signature\");\n }\n if (sig.signs.includes(\"{ts}\") && !sig.timestampHeader) {\n throw new Error(\"@Webhook signature uses {ts} but declares no `timestampHeader` to read it from\");\n }\n }\n if (!meta.secret?.env) {\n throw new Error(\"@Webhook requires `secret: { env: \\\"VAR_NAME\\\" }`\");\n }\n if (entries.length === 0) {\n throw new Error(\"@Webhook requires at least one @On handler\");\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first delivery. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"webhook class\");\n\n const instance = new (ctor as new () => Record<string, WebhookEventHandler>)();\n // Object.create(null), not {} — event names are free-form, so `@On(\"constructor\")`\n // and `@On(\"toString\")` are legal. A plain literal inherits those keys from\n // Object.prototype, and the duplicate check below would reject the FIRST and\n // only handler for them as a redeclaration.\n const events: Record<string, WebhookEventHandler> = Object.create(null) as Record<string, WebhookEventHandler>;\n for (const entry of entries) {\n if (Object.prototype.hasOwnProperty.call(events, entry.event)) {\n throw new Error(`@On(\"${entry.event}\") declared twice on the same webhook`);\n }\n events[entry.event] = (event, metaArg) =>\n (instance[entry.fnName] as WebhookEventHandler).call(instance, event, metaArg);\n }\n\n return {\n ...(meta.provider ? { provider: meta.provider } : {}),\n ...(meta.signature ? { signature: meta.signature } : {}),\n secret: meta.secret,\n events,\n };\n}\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Hook — the BLOCKING half of the internal-event surface.\n//\n// Two axes decide which decorator a handler wants. Where does the event come\n// from, and can the handler stop it?\n//\n// @Webhook + @On an OUTSIDE service (Stripe, GitHub…) — cannot block\n// @Hook an event this stack raised — CAN block: `throw` cancels it\n// @On an event this stack raised — listens only, a monitor\n//\n// The blocking power lives in the NAME `@Hook`, not in the method decorator's\n// shape, which is why `@On` keeps meaning \"listener\" in both worlds and needs\n// no change. `@Upload` is the same pattern already shipped: the storage module\n// calls the tenant's method, and a method that answers 4xx discards the object\n// and hands its exact status, body and content-type back to the client.\n//\n// Mirrors decorators/webhook.ts: symbol-keyed, non-enumerable metadata on the\n// constructor, read back by one resolver. The resolver is the only translation\n// point, so the runtime consumes a shape the authoring surface never leaks.\nimport type { HookMeta } from \"../hooks.js\";\nimport { WEBHOOK_EVENTS } from \"./webhook.js\";\n\n/** A hook handler. Returning quietly ALLOWS; throwing DENIES (blocking hooks). */\nexport type HookFn = (event: unknown, meta: HookMeta) => Promise<unknown>;\n\nexport interface ResolvedHookClass {\n /** `@Hook` handlers, by event. A throw here cancels the operation. */\n blocking: Record<string, HookFn>;\n /** `@On` handlers, by event. A throw here reaches nobody but the log. */\n listeners: Record<string, HookFn>;\n}\n\n/** A hook's refusal, with the reason the caller will see.\n *\n * Any thrown error denies — this class exists so the REASON travels as a\n * deliberate message rather than as whatever a stray TypeError happened to say.\n * The engine is fail-closed by design (an unreachable hook denies), so a hook\n * body should stay narrow: an accidental throw refuses a real user. */\nexport class Deny extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"Deny\";\n }\n}\n\nexport const HOOK_BLOCKING: unique symbol = Symbol.for(\"palbase.backend.hookBlocking\");\n\ninterface EventEntry {\n event: string;\n fnName: string;\n}\n\n/** `@Hook(\"before.user.create\")` — a blocking handler for one stack event. */\nexport function Hook(event: string) {\n return function (target: object, fnName: string | symbol): void {\n const carrier = (target as { constructor: object }).constructor as Record<symbol, unknown>;\n const existing = carrier[HOOK_BLOCKING] as EventEntry[] | undefined;\n const entries: EventEntry[] = existing ? [...existing] : [];\n entries.push({ event, fnName: String(fnName) });\n Object.defineProperty(carrier, HOOK_BLOCKING, {\n value: entries,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n };\n}\n\n/** Binds one decorator's entries onto a single instance of the class.\n *\n * ONE instance for the whole class, built here rather than per call: a hook\n * that opens a client or reads a list in its constructor would otherwise pay\n * for it on every signup. */\nfunction bind(instance: Record<string, HookFn>, entries: EventEntry[], kind: string) {\n const out: Record<string, HookFn> = Object.create(null) as Record<string, HookFn>;\n for (const entry of entries) {\n if (Object.prototype.hasOwnProperty.call(out, entry.event)) {\n throw new Error(`${kind}(\"${entry.event}\") declared twice on the same hook class`);\n }\n // Resolved ONCE, here, so a decorator naming a method that does not exist\n // fails at build time with the name in the message — rather than at the\n // first signup, as \"instance[fnName] is not a function\".\n const fn = instance[entry.fnName];\n if (typeof fn !== \"function\") {\n throw new Error(`${kind}(\"${entry.event}\") names no method \"${entry.fnName}\" on the class`);\n }\n out[entry.event] = (event, meta) => fn.call(instance, event, meta);\n }\n return out;\n}\n\n/** Resolves a hook class into the two maps the runtime dispatches from.\n *\n * Every misuse throws HERE, at build time, rather than becoming a hook that is\n * silently never called — the failure mode this whole change exists to end.\n *\n * @throws when the class declares constructor parameters (FR-011) — nothing\n * here supplies them, so the field would be `undefined` on every event. */\nexport function getHookConfig(ctor: object): ResolvedHookClass {\n const carrier = ctor as Record<symbol, unknown>;\n const blockingEntries = (carrier[HOOK_BLOCKING] ?? []) as EventEntry[];\n const listenerEntries = (carrier[WEBHOOK_EVENTS] ?? []) as EventEntry[];\n\n if (blockingEntries.length === 0 && listenerEntries.length === 0) {\n throw new Error(\n `${(ctor as { name?: string }).name ?? \"a hook class\"} carries no handler — ` +\n \"a hook file must declare at least one @Hook (blocking) or @On (listener) method\",\n );\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first event. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"hook class\");\n\n const instance = new (ctor as new () => Record<string, HookFn>)();\n return {\n blocking: bind(instance, blockingEntries, \"@Hook\"),\n listeners: bind(instance, listenerEntries, \"@On\"),\n };\n}\n","// `@Upload` — the single-method direct-storage upload decorator, and its\n// `@UploadedObject` parameter companion + `UploadConfig`/`UploadedObject` types.\n//\n// Unlike `@Get`/`@Post`/… (where bytes flow THROUGH the br-pod), an `@Upload`\n// route never sees the file bytes: the client uploads DIRECTLY to storage via a\n// signed URL the br-pod mints in an authorize pre-flight. The decorated method\n// body is the COMPLETION handler — it runs once, after storage confirms the\n// object landed (via an HMAC-signed completion webhook), and returns the typed\n// result the client awaits. There is exactly one method: it is BOTH the\n// authorize gate (its uploadConfig drives the guard + signed-URL pinning) AND\n// the completion handler (its body).\n//\n// On the wire the authorize pre-flight is a POST; what marks a route as an\n// upload route through the whole pipeline (registry → flatten → openapi →\n// codegen) is the PRESENCE of `uploadConfig` on the route — never a special HTTP\n// verb. The `@Get`/`@Post`/… decorators never set it.\nimport { recordRoute, recordParam } from \"./registry.js\";\nimport type { RouteOptions } from \"./registry.js\";\nimport type { PalbaseBucketName } from \"../stack.js\";\n\n/** A legacy method decorator (`experimentalDecorators`): `(prototype, name,\n * descriptor)`. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** A legacy parameter decorator: `(prototype, name, paramIndex)`. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/**\n * Direct-storage upload settings for an `@Upload` route. The br-pod validates an\n * authorize request against these (size/type), then mints a signed upload URL\n * that PINS the limits so storage itself rejects an over-limit / wrong-type PUT\n * — the client cannot exceed what it declared.\n */\nexport interface UploadConfig {\n /**\n * Target bucket NAME — one the STACK holds.\n *\n * The union comes from the generated `palbase-stack.d.ts`, so a bucket the\n * stack does not carry is a compile error. It used to say \"MUST exist in\n * `config/storage.ts` defineStorage(...)\", and that invariant was carried by\n * this sentence plus a cross-check nothing called; it is carried by the type\n * now.\n *\n * The bucket is the SINGLE SOURCE OF TRUTH for the size limit + MIME allowlist:\n * `bucket({ fileSizeLimit, allowedMimeTypes })`. Storage enforces those at the\n * actual PUT (the only guard a client cannot skip), so `@Upload` deliberately\n * does NOT take its own `maxSize`/`allowedTypes` — duplicating them here would\n * let a route declare a tighter limit than its bucket that storage would not\n * enforce (a real bypass: declare 10 bytes at authorize, then PUT up to the\n * bucket ceiling straight at the signed URL). One bucket, one limit, enforced.\n */\n bucket: PalbaseBucketName;\n /**\n * SERVER-side object key template. The client NEVER chooses the path. Tokens:\n * `{userId}` (authenticated user id), `{uploadId}` (server-minted), and\n * `{filename}` (the client-declared filename, sanitized). e.g.\n * `\"{userId}/{uploadId}-{filename}\"`.\n */\n pathTemplate: string;\n}\n\n/**\n * The uploaded object, injected into an `@Upload` method body by\n * `@UploadedObject()` once storage confirms the upload. Bytes are NOT present\n * (they went straight to storage) — this is the metadata the completion handler\n * persists.\n */\nexport interface UploadedObject {\n /** Server-minted id correlating authorize ↔ completion (idempotency key). */\n uploadId: string;\n /** Final object key in the bucket (rendered from `pathTemplate`). */\n path: string;\n /** Bucket the object landed in. */\n bucket: string;\n /** Object size in bytes, as reported by storage. */\n size: number;\n /** Object MIME type, as reported by storage — detected from the BYTES, not\n * from the filename or from what the client claimed. */\n contentType: string;\n /** SHA-256 of the stored bytes, hex. The same value the object's ETag is\n * derived from, so a client that has it can tell whether it already holds\n * these bytes. */\n checksum: string;\n /** Pixel width, for an image. Absent otherwise — a PDF has no dimensions,\n * and reporting 0 would be a measurement rather than an absence. */\n width?: number;\n /** Pixel height, for an image. */\n height?: number;\n /**\n * A ~25-byte placeholder the client paints INSTANTLY while the real image\n * downloads — the thing that replaces a grey skeleton with something already\n * shaped like the picture. Absent for non-images.\n *\n * Persist it beside the object's path: it costs a column and saves a request\n * per picture on every gallery render.\n */\n thumbhash?: string;\n /**\n * The renditions the bucket declared, by name, as URLs ready to use.\n *\n * Present on the completion input so the handler that stores the row has\n * everything it needs in one place — asking for them afterwards would be a\n * second call per upload, and per picture on every read.\n */\n variants: Record<string, string>;\n}\n\n/**\n * `@Upload(subpath, config)` — declare a direct-storage upload route. The method\n * body is the completion handler; `config.uploadConfig` drives the authorize\n * guard + signed-URL pinning.\n *\n * @example\n * @Upload(\"/\", { bucket: \"docs\", pathTemplate: \"{userId}/{uploadId}-{filename}\" })\n * async upload(@UploadedObject() obj: UploadedObject, @User() user): Promise<DocResult> { ... }\n * // The size limit + MIME allowlist come from the \"docs\" bucket ON THE STACK\n * // — storage enforces them at the PUT.\n */\nexport function Upload(\n subpath: string,\n config: UploadConfig & Pick<RouteOptions, \"auth\" | \"rateLimit\">,\n): MethodDecorator {\n const { auth, rateLimit, ...uploadConfig } = config;\n validateUploadConfigShape(uploadConfig);\n const options: RouteOptions = {\n uploadConfig,\n ...(auth !== undefined ? { auth } : {}),\n ...(rateLimit !== undefined ? { rateLimit } : {}),\n };\n return function (target, propertyKey) {\n // On the wire the authorize pre-flight is a POST; `uploadConfig` is what\n // marks this as an upload route downstream.\n recordRoute(target, String(propertyKey), \"POST\", subpath, options);\n };\n}\n\n/**\n * `@UploadedObject()` — inject the uploaded object (`: UploadedObject`) into an\n * `@Upload` method body (the completion input). Only valid on an `@Upload`\n * route; the bytes are NOT present (they went directly to storage), this is the\n * confirmed object's metadata.\n *\n * Co-located with the {@link UploadedObject} TYPE so a single exported name\n * `UploadedObject` carries BOTH the decorator value and the type annotation.\n */\nexport function UploadedObject(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), {\n index: parameterIndex,\n kind: \"uploadedObject\",\n });\n };\n}\n\n/**\n * Shape-validate an UploadConfig at decoration time (author-time failure beats a\n * silent deploy bug). Does NOT check that the bucket EXISTS — the generated\n * `palbase-stack.d.ts` union does that, and it does it at compile time rather\n * than at deploy.\n */\nexport function validateUploadConfigShape(c: UploadConfig): void {\n if (c === null || typeof c !== \"object\") {\n throw new Error(\"@Upload config must be an object { bucket, pathTemplate, ... }\");\n }\n // Read the bucket through a WIDENED view on purpose. Its declared type is\n // `PalbaseBucketName`, which is `never` until the project generates\n // `palbase-stack.d.ts` — and `never.length` does not typecheck. This function\n // is a RUNTIME guard against a shape the compiler never saw (a plain-JS\n // caller, a bundle boundary), so the value arriving here is genuinely unknown\n // and reading it as such is the honest signature, not a cast to dodge an error.\n const bucket: unknown = (c as { bucket?: unknown }).bucket;\n if (typeof bucket !== \"string\" || bucket.length === 0) {\n throw new Error(\"@Upload config.bucket must be a non-empty bucket name\");\n }\n if (typeof c.pathTemplate !== \"string\" || c.pathTemplate.length === 0) {\n throw new Error(\"@Upload config.pathTemplate must be a non-empty key template\");\n }\n}\n\n","// `@Sse` — the streaming-response decorator, and its `@SseOut` / `@Signal`\n// parameter companions.\n//\n// Unlike `@Get`/`@Post`/… (where the handler's RETURN VALUE is serialised to\n// JSON), an `@Sse` route's method body WRITES frames as it goes and its return\n// value is discarded. The response is `text/event-stream` and stays open until\n// the body returns or the client disconnects.\n//\n// On the wire an `@Sse` route is a POST — a stream is started by a request that\n// carries input. What marks it as a streaming route through the whole pipeline\n// (registry → flatten → openapi → codegen) is the PRESENCE of `sseConfig` on the\n// route, NEVER the verb: an ordinary `@Post` route is also POST, so the verb\n// cannot carry the distinction. This is the same rule `@Upload` states, for the\n// same reason.\n//\n// The problem this solves: a provider on the server (an AI client, a job queue,\n// any long-running producer) streams from a session; while a client is connected\n// the frames reach it, and when the client disconnects the provider must stop\n// being pulled. That last half is what `@Signal()` exists for.\nimport { recordRoute, recordParam } from \"./registry.js\";\nimport type { RouteOptions } from \"./registry.js\";\nimport type { ZodTypeAny } from \"zod\";\n\n/** A legacy method decorator (`experimentalDecorators`): `(prototype, name,\n * descriptor)`. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** A legacy parameter decorator: `(prototype, name, paramIndex)`. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/**\n * Settings for an `@Sse` route.\n *\n * EMPTY in v1, and deliberately so: the pipeline keys off this object's\n * PRESENCE, not its contents (see the file header). Declaring the type now means\n * a later setting arrives as a field on an existing marker rather than as a\n * second marker nothing downstream reads.\n */\nexport interface SseConfig {\n /**\n * The shape of ONE frame — what a single `out.write(value)` carries.\n *\n * REQUIRED, not optional, and that is the whole point. An `@Sse` handler\n * returns `Promise<void>`, so the codegen-injected `recordReturn` has no type\n * to record and nothing downstream can infer what a frame is. A route without\n * this declares a stream whose element type is unknown, and every generated\n * client from that contract is opaque — which is precisely the failure\n * `x-palbase-sse` exists to prevent. Making it optional would have left that\n * failure one forgotten field away.\n *\n * Measured live on a real pushed stack (2026-08-29): the contract gate refused\n * the deploy with \"2 untyped response(s) — every generated client from it is\n * opaque\", naming both routes that omitted it.\n */\n frame: ZodTypeAny;\n}\n\n/**\n * The writer injected by `@SseOut()`. Each `write` emits ONE SSE `data:` frame\n * carrying `value` JSON-encoded.\n *\n * The FIRST `write` is load-bearing beyond its frame: it settles the request's\n * database transaction. A streaming response may run for minutes, and the\n * handler runs inside the request's transaction — holding one open for the life\n * of a stream exhausts the connection pool, a failure invisible to a unit test\n * that only dies under load. So the first frame is the point at which the\n * request phase is declared over, and database access after it is refused by\n * name rather than silently run against a settled transaction.\n *\n * The practical rule for a handler: do the database work BEFORE the first write.\n */\nexport interface SseWriter {\n write(value: unknown): void;\n}\n\n/**\n * `@Sse(subpath, config)` — declare a streaming route.\n *\n * @example\n * @Sse(\"/chat\", { frame: ChatFrame })\n * async chat(@Body() b: ChatInput, @SseOut() out: SseWriter, @Signal() signal: AbortSignal) {\n * const stream = await openai.chat.completions.create(\n * { model: \"gpt-5.6\", messages: b.messages, stream: true },\n * { signal },\n * );\n * for await (const chunk of stream) out.write(chunk);\n * }\n * // The client disconnects → `signal` aborts → the provider stops being pulled.\n * // The signal is a plain AbortSignal, so it goes wherever the provider takes\n * // one: `{ signal }` for the OpenAI and Anthropic SDKs, `abortSignal:` for the\n * // Vercel AI SDK, `fetch(url, { signal })` for a raw call.\n */\nexport function Sse(\n subpath = \"\",\n config: SseConfig & Pick<RouteOptions, \"auth\" | \"rateLimit\">,\n): MethodDecorator {\n const { auth, rateLimit, ...sseConfig } = config;\n const options: RouteOptions = {\n sseConfig,\n ...(auth !== undefined ? { auth } : {}),\n ...(rateLimit !== undefined ? { rateLimit } : {}),\n };\n return function (target, propertyKey) {\n recordRoute(target, String(propertyKey), \"POST\", subpath, options);\n };\n}\n\n/**\n * `@SseOut()` — inject the frame writer (`: SseWriter`) into an `@Sse` method\n * body. Only meaningful on an `@Sse` route.\n */\nexport function SseOut(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), { index: parameterIndex, kind: \"sseOut\" });\n };\n}\n\n/**\n * `@Signal()` — inject the request's `AbortSignal`, which enters the aborted\n * state when the client disconnects.\n *\n * NOT derivable from `@Req()`: `PBRequest` carries only request-scoped data —\n * the typed input, route/query params, headers, the authenticated user, calling\n * client metadata, trace ids, and the declared error throwers — and no signal\n * (endpoint.ts:358-363).\n *\n * Measured 2026-08-29 on Bun: an infinite producer guarded by this signal\n * stopped four frames after the client was killed, and the handler's `finally`\n * ran. It is the same mechanism a NestJS handler reaches through\n * `req.on(\"close\")`.\n */\nexport function Signal(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), { index: parameterIndex, kind: \"signal\" });\n };\n}\n","// Parameter decorators: `@Body` / `@QueryParams` / `@Param` / `@Headers` / `@User` /\n// `@OptionalUser` / `@Client` / `@RequestId` / `@TraceId` / `@Req`. Each records\n// `{ index, kind, schema?, name? }` into the per-class registry for the method\n// it decorates. These are LEGACY parameter decorators\n// (`experimentalDecorators`), receiving `(prototype, methodName, paramIndex)` —\n// esbuild/tsc preserve the param index at runtime (verified, design §0), which\n// is how dispatch injects positionally. No type reflection\n// (`emitDecoratorMetadata`) is used: validation comes from the zod schema, the\n// type annotation the developer writes is purely for autocomplete.\nimport type { ZodTypeAny } from \"zod\";\nimport { recordParam, type ParamKind } from \"./registry.js\";\n\n/** A legacy parameter decorator. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/** Build a parameter decorator that records the given kind (+ optional schema /\n * name) at the decorated parameter's index. */\nfunction makeParamDecorator(\n kind: ParamKind,\n extra?: { schema?: ZodTypeAny; name?: string },\n): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), {\n index: parameterIndex,\n kind,\n ...(extra?.schema !== undefined ? { schema: extra.schema } : {}),\n ...(extra?.name !== undefined ? { name: extra.name } : {}),\n });\n };\n}\n\n/** `@Body(schema)` — inject the request body, validated against `schema`. The\n * developer writes `: T` (= `z.infer<schema>`, same name) for autocomplete. */\nexport function Body(schema: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"body\", { schema });\n}\n\n/** `@QueryParams(schema)` — inject the parsed query params, validated against\n * `schema`. */\nexport function QueryParams(schema: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"query\", { schema });\n}\n\n/** `@Headers(schema?)` — inject the request headers (lowercase keys). With a\n * schema, headers are validated + the codegen emits header parameters. */\nexport function Headers(schema?: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"headers\", schema !== undefined ? { schema } : undefined);\n}\n\n/** `@Param(\"id\")` — inject one matched path param by name. */\nexport function Param(name: string): ParameterDecorator {\n return makeParamDecorator(\"param\", { name });\n}\n\n/** `@User()` — inject the authenticated user (`: User`, non-null for an\n * effective-required route). The runtime resolves the effective auth. */\nexport function User(): ParameterDecorator {\n return makeParamDecorator(\"user\");\n}\n\n/** `@OptionalUser()` — inject the user as `User | null` (for routes whose\n * effective auth is `false` / `{ required: false }`). */\nexport function OptionalUser(): ParameterDecorator {\n return makeParamDecorator(\"optionalUser\");\n}\n\n/** `@Client()` — inject the parsed calling-client metadata (`: ClientInfo`). */\nexport function Client(): ParameterDecorator {\n return makeParamDecorator(\"client\");\n}\n\n/** `@RequestId()` — inject the per-request id (`: string`). */\nexport function RequestId(): ParameterDecorator {\n return makeParamDecorator(\"requestId\");\n}\n\n/** `@TraceId()` — inject the W3C trace id (`: string`). */\nexport function TraceId(): ParameterDecorator {\n return makeParamDecorator(\"traceId\");\n}\n\n/** `@Req()` — inject the raw request object (escape hatch, `: PBRequest`). */\nexport function Req(): ParameterDecorator {\n return makeParamDecorator(\"req\");\n}\n\n// NOTE: `@UploadedObject()` lives in decorators/upload.ts (co-located with the\n// `UploadedObject` TYPE) so a single exported name carries both the value (the\n// decorator) and the type — TS can only merge value+type under one export name\n// when both are declared in the SAME module.\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients } from \"./endpoint.js\";\nimport type { User } from \"./types.js\";\n\n/** Middleware context — subset of EndpointContext without input (not yet validated). */\nexport interface MiddlewareContext extends PalbaseModuleClients {\n params: Record<string, string>;\n query: Record<string, string>;\n headers: Record<string, string>;\n user: User | null;\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n requestId: string;\n environmentId: string;\n}\n\n/** Middleware function signature — receives context and next function. */\nexport type MiddlewareHandler = (\n ctx: MiddlewareContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/**\n * Define a middleware function for use in the middleware/ directory or\n * as endpoint-specific middleware.\n *\n * Middleware runs before the handler. Call `next()` to pass control\n * to the next middleware or handler. If `next()` is not called, the\n * handler will not execute.\n *\n * Errors thrown in middleware are caught by the pipeline and returned\n * as error responses.\n */\nexport function defineMiddleware(fn: MiddlewareHandler): MiddlewareHandler {\n return fn;\n}\n","/**\n * The brand that identifies an HttpError ACROSS SDK instances.\n *\n * A process legitimately holds more than one copy of this SDK — the runtime\n * loads the engine from its own node_modules while the tenant's bundle carries\n * an inlined copy, which is why the controller registry and the error registry\n * are both anchored on `Symbol.for`. The one place that did not follow the\n * pattern was the engine's catch: `err instanceof HttpError` compares CLASS\n * IDENTITY, so a `throw new NotFound()` from the bundle's copy did not match\n * the engine's copy and every typed error in every deployed backend degraded to\n * `500 internal_error`. Measured through the edge on a real deploy: a route\n * throwing `NotFound` answered 500 while the runtime's own log printed the\n * error object with `status: 404` right beside it.\n *\n * `Symbol.for` puts this in the cross-realm registry, so every copy of the SDK\n * agrees on it by VALUE rather than by identity.\n */\nexport const HTTP_ERROR_BRAND: unique symbol = Symbol.for(\"palbase.backend.httpError\");\n\n/**\n * Set on an `HttpError` the ENGINE built out of a driver failure, as opposed to\n * one the author constructed to ANSWER a request.\n *\n * The distinction cannot be read off the status, and 409 is why. The scaffold\n * teaches `throw new Conflict(\"title already taken\")` as the way to answer\n * (template/AGENTS.md), and the engine raises `UniqueViolation` — also a 409 —\n * when a write hits a unique index. Logging by status therefore either loses the\n * engine's event or writes an \"unhandled\" line every time an author takes the\n * documented path. Measured: it did the second.\n *\n * `Symbol.for` so the mark survives the bundle/runtime SDK split, the same way\n * {@link HTTP_ERROR_BRAND} does.\n */\nexport const ENGINE_RAISED: unique symbol = Symbol.for(\"palbase.backend.engineRaised\") as never;\n\n/** Mark `e` as engine-raised and return it, so a conversion site reads as one expression. */\nexport function markEngineRaised<E extends object>(e: E): E {\n (e as Record<symbol, unknown>)[ENGINE_RAISED] = true;\n return e;\n}\n\n/** Whether the engine built this error, rather than the author throwing it to answer. */\nexport function isEngineRaised(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as Record<symbol, unknown>)[ENGINE_RAISED] === true;\n}\n\n/**\n * Whether a thrown value is an HttpError from ANY copy of this SDK.\n *\n * The shape is checked as well as the brand: the brand says \"this claims to be\n * one of ours\", the fields say the envelope can actually be built from it, and\n * a half-formed object must fall through to the 500 path rather than produce a\n * malformed response.\n */\nexport function isHttpError(err: unknown): err is HttpError {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as Record<PropertyKey, unknown>;\n return (\n e[HTTP_ERROR_BRAND] === true &&\n typeof e.status === \"number\" &&\n typeof e.error === \"string\" &&\n typeof e.errorDescription === \"string\"\n );\n}\n\n/** HTTP error with structured error response format.\n *\n * The base class for the throwable error classes (`PalError`, `Conflict`,\n * `NotFound`, …). Construct one directly with `throw new HttpError(404,\n * \"todo_not_found\", \"No such todo\")`, or throw a named subclass\n * (`throw new NotFound(\"todo not found\")`). The runtime catches any `HttpError`\n * and emits the standard envelope; on the wire (and to iOS) it surfaces as\n * `BackendError.server(code, status, message, requestId)`.\n *\n * The optional `data` field carries a structured payload alongside the\n * standard envelope — for errors that need to ship extra context\n * (e.g. `new Conflict(\"locked\", \"title_locked\", { retryAfter: 30 })`). It rides\n * through to the iOS typed enum's associated value.\n */\nexport class HttpError extends Error {\n public readonly status: number;\n public readonly error: string;\n public readonly errorDescription: string;\n public readonly data?: unknown;\n /** See {@link HTTP_ERROR_BRAND} — how the engine recognises this across SDK copies. */\n public readonly [HTTP_ERROR_BRAND] = true;\n\n constructor(status: number, error: string, errorDescription: string, data?: unknown) {\n super(errorDescription);\n this.name = \"HttpError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n if (data !== undefined) {\n this.data = data;\n }\n }\n\n /**\n * Serialize to the standard Palbase error response format.\n * The `requestId` is injected by the runtime layer from the request context.\n * When called without arguments (e.g. JSON.stringify), request_id is omitted.\n * When `data` is set, it is appended as a strict-superset field.\n */\n toJSON(requestId?: string): {\n error: string;\n error_description: string;\n status: number;\n request_id?: string;\n data?: unknown;\n } {\n const result: {\n error: string;\n error_description: string;\n status: number;\n request_id?: string;\n data?: unknown;\n } = {\n error: this.error,\n error_description: this.errorDescription,\n status: this.status,\n };\n if (requestId) {\n result.request_id = requestId;\n }\n if (this.data !== undefined) {\n result.data = this.data;\n }\n return result;\n }\n}\n\n/**\n * Throw with a custom HTTP status + wire code. The general-purpose escape hatch\n * when none of the named classes (`Conflict`/`NotFound`/…) fits.\n *\n * @example\n * throw new PalError(418, \"teapot\", \"I'm a teapot\");\n */\nexport class PalError extends HttpError {\n constructor(status: number, code: string, description: string, data?: unknown) {\n super(status, code, description, data);\n this.name = \"PalError\";\n }\n}\n\n/** Base for the named status classes. Each subclass fixes its HTTP status; the\n * `code` defaults to the class's canonical wire code (overridable), and the\n * `message` defaults to a human-readable label (overridable). */\nabstract class NamedHttpError extends HttpError {\n protected constructor(\n status: number,\n defaultCode: string,\n name: string,\n message?: string,\n code?: string,\n data?: unknown,\n ) {\n super(status, code ?? defaultCode, message ?? defaultMessage(name), data);\n this.name = name;\n }\n}\n\n/** Derive a default human-readable message from a class name\n * (\"NotFound\" → \"Not found\", \"TooManyRequests\" → \"Too many requests\"). */\nfunction defaultMessage(name: string): string {\n const spaced = name.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\");\n return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n}\n\n/**\n * 400 — the request was malformed or failed validation. Carries a fixed typed\n * payload: `new BadRequest({ fields: [{ field: \"email\", message: \"invalid\" }] })`.\n * The shape is declared once in the SDK so codegen surfaces `error.data.fields`\n * typed on the client.\n */\nexport class BadRequest extends NamedHttpError {\n public declare readonly data: BadRequestData;\n constructor(data: BadRequestData, message?: string) {\n super(400, \"bad_request\", \"BadRequest\", message, undefined, data);\n }\n}\n\n/** 401 — the caller is not authenticated. */\nexport class Unauthorized extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(401, \"unauthorized\", \"Unauthorized\", message, code, data);\n }\n}\n\n/** 403 — the caller is authenticated but not allowed. */\nexport class Forbidden extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(403, \"forbidden\", \"Forbidden\", message, code, data);\n }\n}\n\n/** 404 — the requested resource does not exist. */\nexport class NotFound extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(404, \"not_found\", \"NotFound\", message, code, data);\n }\n}\n\n/** 409 — the request conflicts with the current state. */\nexport class Conflict extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(409, \"conflict\", \"Conflict\", message, code, data);\n }\n}\n\n/**\n * 409 — a write was refused because it would duplicate an existing row.\n * Carries the NAME of the unique constraint Postgres named (`users_email_key`).\n *\n * The engine produces it: a statement rejected with SQLSTATE `23505` is\n * converted here rather than surfacing as an opaque driver error (see\n * `engine/db.ts`, `diagnosingDriver`). What that removes is the string match —\n * before this, the only way to act on a duplicate was to test the driver\n * message for \"duplicate key value violates unique constraint\", a contract\n * nobody signed that breaks on a Postgres upgrade, a locale, or a constraint\n * rename, silently and in production.\n *\n * THE NAME IS A FIELD AND STAYS OUT OF THE DEFAULT MESSAGE. The two are not\n * the same audience. `constraint` is read by the code that catches this — the\n * developer, who already knows the schema. `errorDescription` is the HTTP\n * response body, and an UNCAUGHT duplicate puts it in front of the\n * application's end user: `users_email_key` there discloses how the schema is\n * built to whoever sent the request. The platform's own data API took the same\n * decision one surface over and wrote down why —\n * `v2/internal/modules/database/internal/handler/pgerror.go:83-87` collapses\n * every 23xxx to a generic conflict, \"never disclose the constraint/column\n * name\". A thrower who WANTS the name on the wire passes it deliberately\n * (`new UniqueViolation(c, \\`\\${c} already exists\\`)`, or through `data`).\n *\n * @example\n * try {\n * await Database.tables.users.insert({ email });\n * } catch (e) {\n * if (UniqueViolation.is(e) && e.constraint === \"users_email_key\") {\n * throw new Conflict(\"That email is taken\", \"email_taken\");\n * }\n * throw e;\n * }\n */\nexport class UniqueViolation extends Conflict {\n /**\n * Whether `e` is a unique violation — REGARDLESS of which copy of this SDK\n * constructed it.\n *\n * Use this instead of `instanceof`. Measured on a live stack: a controller\n * bundle INLINES its own copy of `@palbase/backend`, and the engine that\n * raises this error is the runtime's copy. Two copies, two class identities,\n * and `e instanceof UniqueViolation` is false in the one place a caller\n * writes it — a check that reads as correct and silently never matches.\n */\n static is(e: unknown): e is UniqueViolation {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { name?: unknown }).name === \"UniqueViolation\" &&\n typeof (e as { constraint?: unknown }).constraint === \"string\"\n );\n }\n\n /** The unique constraint the statement violated, as Postgres named it.\n * `\"\"` when the driver did not say which — see `engine/db.ts`. */\n public readonly constraint: string;\n\n constructor(constraint: string, message?: string, code?: string, data?: unknown) {\n super(message ?? \"Unique constraint violated\", code ?? \"unique_violation\", data);\n this.name = \"UniqueViolation\";\n this.constraint = constraint;\n }\n}\n\n/** A single field-level validation failure carried by {@link BadRequest}. */\nexport interface FieldError {\n /** The offending field's name (dotted path for nested fields). */\n field: string;\n /** Human-readable reason the field failed. */\n message: string;\n}\n\n/** The fixed, typed payload {@link BadRequest} ships. */\nexport interface BadRequestData {\n /** The fields that failed validation. */\n fields: FieldError[];\n}\n\n/** The fixed, typed payload {@link TooManyRequests} ships. */\nexport interface TooManyRequestsData {\n /** Seconds the caller should wait before retrying. */\n retryAfter: number;\n}\n\n/**\n * 429 — the caller has exceeded the rate limit. Carries a fixed typed payload:\n * `new TooManyRequests({ retryAfter: 30 })`. The shape is declared once in the\n * SDK (error-registry pre-seed) so codegen surfaces `error.data.retryAfter`\n * typed on the client — no per-project definition needed.\n */\nexport class TooManyRequests extends NamedHttpError {\n public declare readonly data: TooManyRequestsData;\n constructor(data: TooManyRequestsData, message?: string) {\n super(429, \"too_many_requests\", \"TooManyRequests\", message, undefined, data);\n }\n}\n","// defineError — project-defined typed error classes + the module-global error\n// registry the OpenAPI spec twins join against.\n//\n// `defineError(code, status, dataSchema?)` returns an `HttpError` subclass whose\n// constructor is typed by the zod schema (`new TodoLocked({ retryAfter: 30 })`).\n// Each call self-registers `{ code, status, className, dataSchema }` in a\n// registry anchored on `globalThis` under `Symbol.for(...)` — mirroring the\n// ROUTES pattern — so the deploy bundle's registrations land on the single SDK\n// instance the extractor `require()`s. The registry is pre-seeded with the named\n// built-in classes (`NotFound`, `Conflict`, …) so throw inference can resolve\n// ad-hoc `throw new NotFound(...)` sites by their canonical wire codes.\n//\n// Duplicate code with a DIFFERENT shape (status OR converted data schema) is a\n// hard error at registration time (deploy fails loudly — error codes are\n// project-unique); structurally-identical re-registration is idempotent (each\n// controller BUNDLE carries its own copy of a shared models/errors.ts, so the\n// same defineError line legitimately runs once per bundle in one process).\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z, type ZodTypeAny } from \"zod\";\nimport { HttpError } from \"./errors.js\";\n\nextendZodWithOpenApi(z);\n\n/** One registered error: the wire code, HTTP status, the class name the\n * analyzer sees, the optional data payload schema, and whether it is one of the\n * pre-seeded built-in named classes. */\nexport interface RegisteredError {\n code: string;\n status: number;\n className: string;\n dataSchema?: ZodTypeAny;\n /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec\n * twins would emit an identical `data` schema for this error. */\n dataDigest?: string;\n builtin: boolean;\n}\n\n/** The cross-module-instance registry anchor (the pinned contract symbol). */\nconst ERROR_REGISTRY: unique symbol = Symbol.for(\"palbase.backend.errorRegistry\");\n\ninterface RegistryCarrier {\n [ERROR_REGISTRY]?: Map<string, RegisteredError>;\n}\n\n/** Get (creating + pre-seeding if absent) the project-global error registry,\n * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a\n * process shares the one registry. */\n/** The fixed data schemas the built-in named errors ship. Declared HERE (not in\n * errors.ts, which stays zod-free) because this is where the registry converts\n * them to JSON-schema for the spec — keying codegen's typed `error.data`. Only\n * the errors that semantically carry a payload have a schema; the rest are\n * data-less. `.int()` is preserved so the wire/codegen sees an integer. */\nconst BUILTIN_DATA_SCHEMAS: Record<string, ZodTypeAny> = {\n bad_request: z.object({\n fields: z.array(z.object({ field: z.string(), message: z.string() })),\n }),\n too_many_requests: z.object({ retryAfter: z.number().int() }),\n};\n\nexport function getErrorRegistry(): Map<string, RegisteredError> {\n const g = globalThis as RegistryCarrier;\n if (!g[ERROR_REGISTRY]) {\n const m = new Map<string, RegisteredError>();\n for (const [code, status, className] of [\n [\"bad_request\", 400, \"BadRequest\"],\n [\"unauthorized\", 401, \"Unauthorized\"],\n [\"forbidden\", 403, \"Forbidden\"],\n [\"not_found\", 404, \"NotFound\"],\n [\"conflict\", 409, \"Conflict\"],\n // The engine's own 23505 conversion (engine/db.ts) throws this, and an\n // author may too. Registered like every other built-in so the spec\n // emitter resolves it — an unregistered code is SKIPPED silently there\n // (openapi/convert.ts) and would degrade to the client's `.other` case.\n [\"unique_violation\", 409, \"UniqueViolation\"],\n [\"too_many_requests\", 429, \"TooManyRequests\"],\n ] as const) {\n const dataSchema = BUILTIN_DATA_SCHEMAS[code];\n m.set(code, {\n code,\n status,\n className,\n builtin: true,\n ...(dataSchema ? { dataSchema, dataDigest: digestOf(code, dataSchema) } : {}),\n });\n }\n g[ERROR_REGISTRY] = m;\n }\n return g[ERROR_REGISTRY];\n}\n\n/** Class returned for schema-bearing errors: ctor(data, message?). */\nexport interface DefinedErrorWithData<S extends ZodTypeAny> {\n new (data: z.input<S>, message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/** Class returned for schema-less errors: ctor(message?). */\nexport interface DefinedError {\n new (message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/**\n * Define a project error class. MUST be called with literal args (string\n * literal `code`, numeric literal `status`) at module top level — the deploy\n * stager's static analyzer reads those literals to resolve throw sites.\n *\n * @example\n * // models/todos/errors.ts\n * export const TodoLocked = defineError(\"todo_locked\", 409, z.object({ retryAfter: z.number() }));\n * // services/todo.service.ts\n * throw new TodoLocked({ retryAfter: 30 });\n */\nexport function defineError<S extends ZodTypeAny>(\n code: string,\n status: number,\n dataSchema: S,\n): DefinedErrorWithData<S>;\nexport function defineError(code: string, status: number): DefinedError;\nexport function defineError(code: string, status: number, dataSchema?: ZodTypeAny): unknown {\n if (!Number.isInteger(status) || status < 400 || status > 599) {\n throw new Error(\n `defineError: status for \"${code}\" must be a 4xx/5xx integer, got ${status} — ` +\n `error responses must not clobber success responses in the project spec.`,\n );\n }\n const registry = getErrorRegistry();\n const existing = registry.get(code);\n const className = defaultClassName(code);\n const dataDigest = dataSchema ? digestOf(code, dataSchema) : undefined;\n if (existing) {\n const sameShape =\n existing.status === status && !existing.builtin && existing.dataDigest === dataDigest;\n if (!sameShape) {\n throw new Error(\n `defineError: duplicate error code \"${code}\" with a different shape ` +\n `(existing: status ${existing.status}${existing.builtin ? \", built-in\" : \"\"}` +\n `${existing.status === status && !existing.builtin ? \", different data schema\" : \"\"}). ` +\n `Error codes are project-unique.`,\n );\n }\n }\n // Local factories so the class-constructor closures capture a NON-optional\n // schema binding (narrowing does not flow into closures created in a branch).\n const makeWithData = (schema: ZodTypeAny) =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(data: unknown, message?: string) {\n super(status, code, message ?? humanize(code), schema.parse(data));\n this.name = className;\n }\n };\n const makeWithoutData = () =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(message?: string) {\n super(status, code, message ?? humanize(code));\n this.name = className;\n }\n };\n const cls = dataSchema ? makeWithData(dataSchema) : makeWithoutData();\n Object.defineProperty(cls, \"name\", { value: className });\n registry.set(code, {\n code,\n status,\n className,\n builtin: false,\n ...(dataSchema ? { dataSchema } : {}),\n ...(dataDigest !== undefined ? { dataDigest } : {}),\n });\n return cls;\n}\n\n/** Convert a data schema through the SAME library the spec twins use and\n * return its JSON-schema digest (the duplicate-shape comparison key). Doubles\n * as the self-containment guard: a schema carrying `.openapi(refId)` metadata\n * (top-level or nested) converts to `$ref` pointers into components the\n * project spec never emits — a dangling ref every spec consumer would choke\n * on — so it is rejected here, at the definition site, with a fixable message. */\nfunction digestOf(code: string, dataSchema: ZodTypeAny): string {\n const TMP_REF = \"__PalbaseErrorDataDigest\";\n const tmpRegistry = new OpenAPIRegistry();\n // Wrap the schema as a property — exactly how the envelope embeds it — so a\n // TOP-LEVEL .openapi(refId) is not masked by the registration refId and\n // surfaces as the same $ref the real emission would produce.\n tmpRegistry.register(TMP_REF, z.object({ data: dataSchema }).openapi(TMP_REF));\n const generated = new OpenApiGeneratorV31(tmpRegistry.definitions).generateComponents();\n const out = generated.components?.schemas?.[TMP_REF];\n const digest = JSON.stringify(out ?? null);\n if (digest.includes('\"$ref\"')) {\n throw new Error(\n `defineError: dataSchema for \"${code}\" carries .openapi(refId) metadata — ` +\n `it would emit dangling $ref pointers in the project spec. ` +\n `Use a plain zod schema (z.object({...})) without .openapi(...).`,\n );\n }\n return digest;\n}\n\n/** \"todo_locked\" → \"TodoLocked\" (used as Error.name; the source class NAME the\n * analyzer sees is whatever the user assigned the const to — they should match\n * by convention, and the descriptor carries the analyzed const name anyway). */\nfunction defaultClassName(code: string): string {\n return code\n .split(\"_\")\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n}\n\n/** \"todo_locked\" → \"Todo locked\" — the default human-readable message. */\nfunction humanize(code: string): string {\n const s = code.replace(/_/g, \" \");\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n","/** Non-service, per-invocation data for job handlers.\n * Services (Database, Log, …) are imported as singletons, not passed here. */\nexport interface JobMeta {\n /** Environment-scoped env vars. */\n env: Record<string, string>;\n /** The globally unique Environment runtime identifier. */\n environmentId: string;\n}\n\n/**\n * Cron expression validation.\n * Supports standard 5-field cron: minute hour day-of-month month day-of-week.\n * Each field allows: number, *, ranges (1-5), steps (star/2), lists (1,3,5).\n */\nexport function validateCronExpression(expression: string): string | null {\n const trimmed = expression.trim();\n if (trimmed === \"\") {\n return \"Cron expression is required\";\n }\n\n const parts = trimmed.split(/\\s+/);\n if (parts.length !== 5) {\n return `Invalid cron expression \"${trimmed}\": expected 5 fields (minute hour day month weekday), got ${parts.length}`;\n }\n\n const fieldNames = [\"minute\", \"hour\", \"day of month\", \"month\", \"day of week\"];\n const fieldRanges: [number, number][] = [\n [0, 59],\n [0, 23],\n [1, 31],\n [1, 12],\n [0, 7],\n ];\n\n for (let i = 0; i < 5; i++) {\n const field = parts[i]!;\n const name = fieldNames[i]!;\n const [min, max] = fieldRanges[i]!;\n\n const error = validateCronField(field, name, min, max);\n if (error !== null) {\n return error;\n }\n }\n\n return null;\n}\n\nfunction validateCronField(\n field: string,\n name: string,\n min: number,\n max: number,\n): string | null {\n // Split by comma for lists\n const listParts = field.split(\",\");\n for (const part of listParts) {\n // Check for step: */2, 1-5/2\n const stepParts = part.split(\"/\");\n if (stepParts.length > 2) {\n return `Invalid ${name} field: \"${field}\"`;\n }\n\n const base = stepParts[0]!;\n const step = stepParts[1];\n\n if (step !== undefined) {\n const stepNum = Number(step);\n if (!Number.isInteger(stepNum) || stepNum < 1) {\n return `Invalid step value in ${name} field: \"${field}\"`;\n }\n }\n\n if (base === \"*\") {\n continue;\n }\n\n // Check for range: 1-5\n if (base.includes(\"-\")) {\n const rangeParts = base.split(\"-\");\n if (rangeParts.length !== 2) {\n return `Invalid range in ${name} field: \"${field}\"`;\n }\n const rangeStart = Number(rangeParts[0]);\n const rangeEnd = Number(rangeParts[1]);\n if (\n !Number.isInteger(rangeStart) ||\n !Number.isInteger(rangeEnd) ||\n rangeStart < min ||\n rangeEnd > max ||\n rangeStart > rangeEnd\n ) {\n return `Invalid range in ${name} field: \"${field}\"`;\n }\n continue;\n }\n\n // Single number\n const num = Number(base);\n if (!Number.isInteger(num) || num < min || num > max) {\n return `Invalid value in ${name} field: \"${field}\"`;\n }\n }\n\n return null;\n}\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Job — the cron half of the decorator surface. Same metadata mechanism as\n// @Webhook/@Controller. The job's NAME is not here on purpose: it is the file\n// name, which is also what the Temporal schedule id is built from. Two names\n// with nothing reconciling them is what this replaces.\nimport type { JobMeta } from \"../job.js\";\nimport { validateCronExpression } from \"../job.js\";\n\nexport interface JobOptions {\n /** Cron expression, five fields (e.g. \"0 3 * * *\"). */\n schedule: string;\n /** Execution timeout in seconds. Defaults to 30, ceiling 300 (sandbox limit). */\n timeout?: number;\n /**\n * How many times a FAILED run is retried before the run is recorded failed.\n * Defaults to 5, ceiling 10; 0 disables retrying entirely.\n *\n * Retries exist for the transient half of the failure space — the runtime\n * still waking, a network blip — not for a job that is wrong. A permanent\n * failure still lands in the run history, it just lands after the retries\n * are spent rather than instead of them.\n */\n retry?: number;\n}\n\nexport interface ResolvedJob {\n schedule: string;\n timeout: number;\n retry: number;\n handler: (meta: JobMeta) => Promise<void>;\n}\n\nconst DEFAULT_TIMEOUT_SECONDS = 30;\nconst MAX_TIMEOUT_SECONDS = 300;\nconst DEFAULT_RETRY = 5;\nconst MAX_RETRY = 10;\n\nexport const JOB_META: unique symbol = Symbol.for(\"palbase.backend.jobMeta\");\n\ninterface JobCarrier {\n __palbase?: \"job\";\n [JOB_META]?: JobOptions;\n}\n\nexport function Job(options: JobOptions) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n const carrier = ctor as unknown as JobCarrier;\n Object.defineProperty(carrier, JOB_META, {\n value: options,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"job\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return ctor;\n };\n}\n\nexport function getJobConfig(ctor: object): ResolvedJob {\n const meta = (ctor as JobCarrier)[JOB_META];\n if (!meta) {\n throw new Error(\n `getJobConfig on a class with no @Job decorator (${(ctor as { name?: string }).name ?? \"anonymous\"})`,\n );\n }\n if (!meta.schedule || meta.schedule.trim() === \"\") {\n throw new Error(\"@Job requires a `schedule` cron expression\");\n }\n const cronError = validateCronExpression(meta.schedule);\n if (cronError) {\n throw new Error(`@Job has an invalid cron schedule: ${cronError}`);\n }\n\n const timeout = meta.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n if (!Number.isInteger(timeout) || timeout <= 0) {\n throw new Error(\"@Job `timeout` must be a positive whole number of seconds\");\n }\n if (timeout > MAX_TIMEOUT_SECONDS) {\n throw new Error(`@Job \\`timeout\\` exceeds the ${MAX_TIMEOUT_SECONDS}s sandbox ceiling`);\n }\n\n const retry = meta.retry ?? DEFAULT_RETRY;\n if (!Number.isInteger(retry) || retry < 0) {\n throw new Error(\"@Job `retry` must be a whole number of attempts, zero or more\");\n }\n if (retry > MAX_RETRY) {\n throw new Error(`@Job \\`retry\\` exceeds the ceiling of ${MAX_RETRY}`);\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first scheduled run. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"job class\");\n\n const instance = new (ctor as new () => { run?: (meta: JobMeta) => Promise<void> })();\n if (typeof instance.run !== \"function\") {\n throw new Error(\"@Job class must declare an async run() method\");\n }\n const run = instance.run.bind(instance);\n\n return { schedule: meta.schedule, timeout, retry, handler: run };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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cAAc;AAAA,MACd,UAAU;AAAA,IACZ,CAAC;AACD,WAAO;AAAA,EACT;AACF;AAEO,SAAS,aAAa,MAA2B;AACtD,QAAM,OAAQ,KAAoB,QAAQ;AAC1C,MAAI,CAAC,MAAM;AACT,UAAM,IAAI;AAAA,MACR,mDAAoD,KAA2B,QAAQ,WAAW;AAAA,IACpG;AAAA,EACF;AACA,MAAI,CAAC,KAAK,YAAY,KAAK,SAAS,KAAK,MAAM,IAAI;AACjD,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,QAAM,YAAY,uBAAuB,KAAK,QAAQ;AACtD,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,sCAAsC,SAAS,EAAE;AAAA,EACnE;AAEA,QAAM,UAAU,KAAK,WAAW;AAChC,MAAI,CAAC,OAAO,UAAU,OAAO,KAAK,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,2DAA2D;AAAA,EAC7E;AACA,MAAI,UAAU,qBAAqB;AACjC,UAAM,IAAI,MAAM,gCAAgC,mBAAmB,mBAAmB;AAAA,EACxF;AAEA,QAAM,QAAQ,KAAK,SAAS;AAC5B,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG;AACzC,UAAM,IAAI,MAAM,+DAA+D;AAAA,EACjF;AACA,MAAI,QAAQ,WAAW;AACrB,UAAM,IAAI,MAAM,yCAAyC,SAAS,EAAE;AAAA,EACtE;AAOA,2BAAyB,MAAM,WAAW;AAE1C,QAAM,WAAW,IAAK,KAA8D;AACpF,MAAI,OAAO,SAAS,QAAQ,YAAY;AACtC,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACjE;AACA,QAAM,MAAM,SAAS,IAAI,KAAK,QAAQ;AAEtC,SAAO,EAAE,UAAU,KAAK,UAAU,SAAS,OAAO,SAAS,IAAI;AACjE;;;AjCuPA,IAAAC,cAAkB;","names":["raw","raw","raw","text","now","policy","out","raw","raw","carrierOf","reason","registry","import_zod"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/runtime.ts","../src/db/tx-plan.ts","../src/clients/http.ts","../src/clients/documents.ts","../src/clients/flags.ts","../src/clients/notifications.ts","../src/clients/realtime.ts","../src/clients/storage.ts","../src/clients/index.ts","../src/db/schema-json.ts","../src/db/policy.ts","../src/db/schema.ts","../src/channels.ts","../src/db/extensions.ts","../src/db/columns.ts","../src/db/raw.ts","../src/db/embedding.ts","../src/db/typed-db.ts","../src/db/env-gen.ts","../src/stack-gen.ts","../src/decorators/registry.ts","../src/decorators/controller.ts","../src/decorators/methods.ts","../src/decorators/webhook.ts","../src/decorators/hook.ts","../src/decorators/upload.ts","../src/decorators/sse.ts","../src/decorators/room.ts","../src/decorators/params.ts","../src/middleware.ts","../src/errors.ts","../src/error-registry.ts","../src/job.ts","../src/decorators/job.ts"],"sourcesContent":["export type {\n PBRequest,\n ClientInfo,\n RateLimitConfig,\n DBClient,\n DBOps,\n FileContext,\n Logger,\n CacheClient,\n SecretsService,\n PalbaseDocsClient,\n PalbaseCollectionRef,\n PalbaseDocumentRef,\n PalbaseDocumentSnapshot,\n PalbaseQuerySnapshot,\n PalbaseWhereOperator,\n PalbaseResult,\n Middleware,\n ErrorDef,\n ErrorMap,\n ErrorThrowers,\n} from \"./endpoint.js\";\nexport {\n Database,\n Documents,\n Storage,\n Cache,\n Secrets,\n Log,\n Notifications,\n Flags,\n Realtime,\n __setRuntime,\n __runWithRuntime,\n __requestALS,\n __getRuntime,\n // Where a long-lived resource lives: opened once as the app comes up, closed\n // when it goes away. `__runStartHooks` is the engine's door to them (it\n // CLAIMS the declarations, so a candidate release loaded beside the live one\n // never closes the live one's pool); `__resetLifecycleHooks` is for tests.\n onStart,\n onShutdown,\n __runStartHooks,\n __resetLifecycleHooks,\n} from \"./runtime.js\";\nexport type {\n RuntimeServices,\n RequestStore,\n LifecycleHook,\n ShutdownRunner,\n} from \"./runtime.js\";\n\n// The module clients and their composition root. The PROCESS calls\n// buildModuleClients once at boot and hands the result to createApp — which is\n// the whole reason this package now contains the implementations and not just\n// the interfaces they were being checked against by nobody.\nexport { buildModuleClients } from \"./clients/index.js\";\nexport type { ModuleClientsConfig } from \"./clients/index.js\";\nexport { makeHttpClient, PalbaseModuleError } from \"./clients/http.js\";\nexport type { ModuleTransport, RequestOptions, TransportConfig } from \"./clients/http.js\";\n\nexport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseInvokeOptions,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseFlagSource,\n PalbaseSetOverrideResult,\n PalbaseSetOverridesResult,\n PalbaseClearOverrideResult,\n PalbaseClearAllOverridesResult,\n PalbaseBatchOverrideOperation,\n PalbaseBatchSetOverridesResult,\n PalbaseNotificationsClient,\n PalbasePushClient,\n PalbaseEmailClient,\n PalbaseSmsClient,\n PalbaseInboxClient,\n PalbasePreferencesClient,\n PalbaseAnalyticsClient,\n PalbaseAnalyticsQueryNamespace,\n PalbaseAnalyticsManagementNamespace,\n PalbaseLinksClient,\n // Shared local types\n PalbaseUser,\n PalbaseSession,\n PalbaseDeviceInfo,\n PalbaseAttestAndroidParams,\n PalbaseAttestAndroidResult,\n PalbaseAttestiOSParams,\n PalbaseAttestiOSResult,\n PalbaseBindDeviceParams,\n PalbaseVerifyRequestSignatureParams,\n PalbaseFileObject,\n PalbaseSignedUrlResponse,\n PalbaseUploadOptions,\n PalbaseTransformOptions,\n PalbaseListOptions,\n PalbasePushSendParams,\n PalbasePushSendResponse,\n PalbaseEmailSendParams,\n PalbaseEmailSendResponse,\n PalbaseSmsSendParams,\n PalbaseSmsSendResponse,\n PalbaseInboxSendParams,\n PalbaseInboxSendResponse,\n PalbaseInboxMessage,\n PalbaseInboxListOptions,\n PalbaseInboxListResult,\n PalbasePreferences,\n PalbaseRegisterDeviceParams,\n PalbaseDeviceTokenView,\n PalbaseMultiChannelResponse,\n PalbaseAnalyticsProperties,\n PalbaseIdentifyTraits,\n PalbaseCountQueryInput,\n PalbaseCountResult,\n PalbaseEventsQueryInput,\n PalbaseEventsResult,\n PalbaseUsersQueryInput,\n PalbaseUsersResult,\n PalbaseFunnelQueryInput,\n PalbaseFunnelResult,\n PalbaseRetentionQueryInput,\n PalbaseRetentionResult,\n PalbaseCohortQueryInput,\n PalbaseCohortResult,\n PalbaseOverviewResult,\n PalbaseEventNamesResult,\n PalbaseUserDetailResult,\n PalbaseCreateLinkParams,\n PalbaseUpdateLinkParams,\n PalbaseLink,\n PalbaseLinkDetails,\n PalbaseLinkAnalytics,\n PalbaseQrCodeOptions,\n PalbaseMatchParams,\n PalbaseInitialLink,\n PalbaseListLinksOptions,\n PalbaseListLinksResult,\n} from \"./clients.js\";\nexport { defineSchema, defineTable, TABLE_META } from \"./db/schema.js\";\n// The declaration as DATA — what the deploy reads to build the database. The\n// bundler calls this; a project never has to.\nexport { toSchemaJSON } from \"./db/schema-json.js\";\nexport type { SchemaJSON, TableJSON, ColumnJSON, PolicyJSON } from \"./db/schema-json.js\";\nexport type { SchemaDef, TableDef, TableInput, ColumnMap, SchemaInput, TableHandle } from \"./db/schema.js\";\nexport { policy, PolicyBuilder } from \"./db/policy.js\";\nexport type { PolicyDef, PolicyCommand, PolicyMode } from \"./db/policy.js\";\n// The realtime twin of `policy`: which channels exist and who may join them.\n// Undeclared channels are denied by the server, so this declaration is the\n// whole surface — the runtime reads it back off globalThis at boot.\nexport { defineChannels, ownerOnly, publicChannel } from \"./channels.js\";\nexport type { ChannelsDef, ChannelEntry, ChannelsInput, ChannelGrant, ChannelAuthorizeCtx } from \"./channels.js\";\nexport { PALBASE_EXTENSIONS, EXTENSION_DEPENDENCIES, isPalbaseExtension } from \"./db/extensions.js\";\nexport type { PalbaseExtension } from \"./db/extensions.js\";\nexport {\n uuid, text, integer, bigint, numeric, boolean, timestamp, jsonb, enumType, vector,\n ownedByUser, userRef, installationRef,\n} from \"./db/columns.js\";\nexport type { ColumnBuilder, ColumnDef, ColumnType, OnDeleteAction, AnyColumn } from \"./db/columns.js\";\nexport { raw } from \"./db/raw.js\";\nexport type { RawConstraintDef } from \"./db/raw.js\";\nexport { openai } from \"./db/embedding.js\";\nexport type { EmbeddingModelRef } from \"./db/embedding.js\";\nexport { makeTypedDB } from \"./db/typed-db.js\";\nexport type {\n TypedDB,\n TypedTx,\n TypedTable,\n InsertShape,\n RowShape,\n EnvTypedDatabase,\n EnvServiceDatabase,\n EnvTypedTable,\n EnvTables,\n EnvSchemas,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\n// Transaction plans: the `tx.tables.*` operation surface, its handles, and the\n// expressions a plan may write. `Database.transaction()` is on `Database`.\nexport { inc, dec, now, TxRefError, TxPlanError } from \"./db/tx-plan.js\";\nexport type {\n Ref,\n TxRow,\n TxRows,\n TxTable,\n TxPlanHandle,\n Materialized,\n TxNow,\n TxColumnExpr,\n TxInsertValue,\n TxSetValue,\n TxInsertShape,\n TxSetShape,\n TxWhere,\n TxSelectOptions,\n TxPlanBody,\n TxPlanResponse,\n TxPlanOpResult,\n TxPlanRejection,\n TxWireOp,\n TxWireRef,\n TxWireExpr,\n TxWireGuard,\n TxWireValue,\n} from \"./db/tx-plan.js\";\nexport type { Tables, TableTypes } from \"./db/env.js\";\nexport { makeEnvDts } from \"./db/env-gen.js\";\n// `config/` IS GONE, and so is the purchases family. Both were author-facing\n// surfaces with nothing behind them.\n//\n// The five config declarations nobody applied — storage, flags, notifications,\n// egress, auth — stopped being applied when the server-side declaration applier\n// was retired (v2 S-005, \"settings have one door, and a second one is how the\n// two disagree\"); `contract_lock_test.go` keeps it retired, and its own comment\n// records that the applier produced that silent failure FIVE times. The two that\n// still worked travelled by CLI courier: `config/secrets.ts` gated the push and\n// `config/test-users.ts` was PUT at the stack. Both jobs are now done where the\n// setting lives — `palbase secret set`, `palbase test-user templates set` — and\n// what a controller may SPELL comes back as a type instead of a declaration.\n//\n// `purchases` never had a v2 backend at all: v2 contains no palstore, which\n// `clients/index.ts` recorded on 2026-08-15 while deliberately leaving the tree\n// in place. It is taken now.\n//\n// The rule that replaced all of it: `db/schema.ts` and behaviour-carrying code\n// live in the repo; everything else is CONFIGURATION and is set through the CLI\n// (later MCP) against the stack. Codegen exists so that code can be written\n// against it — a generated type is not a declaration, and it produces no file an\n// author edits.\nexport type { PalbaseSecretName, PalbaseFlagKey, PalbaseBucketName } from \"./stack.js\";\nexport { makeStackDts } from \"./stack-gen.js\";\nexport type { StackNames } from \"./stack-gen.js\";\n// Class-controller decorator model (replaces defineController/defineHandler/route).\n// `getRegisteredControllers` is what makes exporting a controller OPTIONAL:\n// importing the file registers it. `Controller` stays exported for authoring.\nexport { Controller, getRegisteredControllers, __resetRegisteredControllers } from \"./decorators/controller.js\";\n// The APPLICATION-level ring of the auth cascade (route → controller →\n// application → true). Declared once at module scope instead of repeating the\n// same `auth` on every @Controller — the repetition is what gets forgotten.\nexport { defineDefaultAuth, __resetDefaultAuth, assertZeroArgConstructor, resolveEffectiveAuth } from \"./decorators/controller.js\";\nexport type { ControllerOptions } from \"./decorators/controller.js\";\nexport { Get, Post, Put, Patch, Delete, Query } from \"./decorators/methods.js\";\nexport { Deny, getHookConfig, Hook } from \"./decorators/hook.js\";\nexport type { HookFn, ResolvedHookClass } from \"./decorators/hook.js\";\nexport { Upload } from \"./decorators/upload.js\";\nexport type { UploadConfig } from \"./decorators/upload.js\";\n// `UploadedObject` is exported from upload.js, where BOTH the `@UploadedObject()`\n// decorator value AND the `UploadedObject` type are declared. One module → one\n// export name carries both — authors write `@UploadedObject()` (value) and\n// `: UploadedObject` (type) with a single imported name.\nexport { UploadedObject } from \"./decorators/upload.js\";\n// `@Sse` + its two parameter companions. `SseWriter` is the writer `@SseOut()`\n// injects; `SseConfig` is the route marker's type. The pipeline keys off the\n// config's PRESENCE, not the HTTP verb — see decorators/sse.ts.\nexport { Sse, SseOut, Signal } from \"./decorators/sse.js\";\nexport type { SseConfig, SseWriter } from \"./decorators/sse.js\";\n\n// `@Room` + its six lifecycle hooks. A room is the realtime surface a backend\n// can MANAGE rather than only talk on: it sees who joined, who left, and when\n// nobody is watching any more. Marked by the config's PRESENCE, like every\n// other decorator here — see decorators/room.ts.\nexport {\n Room,\n OnAuthorize,\n OnFirst,\n OnJoin,\n OnLeave,\n OnEmpty,\n OnMessage,\n} from \"./decorators/room.js\";\nexport type { RoomOptions } from \"./decorators/room.js\";\nexport {\n Body,\n QueryParams,\n Headers,\n Param,\n User,\n OptionalUser,\n Client,\n RequestId,\n TraceId,\n Req,\n} from \"./decorators/params.js\";\nexport type { RouteOptions, HttpMethodUpper, ThrowDescriptor, RouteMeta, ParamMeta, ParamKind } from \"./decorators/registry.js\";\n// recordThrows is the stager-injected carrier for inferred throw descriptors\n// (the recordReturn twin) — public so the injected IIFE in a deployed bundle\n// can call it via `require(\"@palbase/backend\").recordThrows(...)`.\nexport { recordThrows } from \"./decorators/registry.js\";\n// getRoutes reads a controller's RouteMeta[] straight from the registry — the\n// isolate runtime enumerates routes with it instead of the worker.js raw-Symbol\n// fallback (the ROUTES symbol stays, both fallbacks keep reading it).\nexport { getRoutes } from \"./decorators/registry.js\";\nexport { defineMiddleware } from \"./middleware.js\";\nexport type { MiddlewareContext, MiddlewareHandler } from \"./middleware.js\";\n// The authenticated-user TYPE is exported as `UserT` (not `User`) because the\n// value name `User` is the @User() parameter decorator (exported above). A\n// controller annotates `@User() user: UserT` — decorator for the value\n// position, `UserT` for the type. (NestJS-style: same name as the decorator\n// would collide in the value+type namespaces.)\nexport type { User as UserT, VerifiedDevice, HttpMethod, AuthConfig } from \"./types.js\";\nexport {\n HttpError,\n PalError,\n BadRequest,\n Unauthorized,\n Forbidden,\n NotFound,\n Conflict,\n TooManyRequests,\n // 23505, typed. The engine throws it; a caller branches on `.constraint`\n // instead of matching the driver's message string.\n UniqueViolation,\n} from \"./errors.js\";\n// Typed project errors — defineError returns an HttpError subclass and\n// self-registers {code, status, dataSchema} in the project-global error\n// registry (the OpenAPI spec twins join `RouteMeta.throws` against it).\nexport { defineError, getErrorRegistry } from \"./error-registry.js\";\nexport type { RegisteredError, DefinedError, DefinedErrorWithData } from \"./error-registry.js\";\nexport type { JobMeta } from \"./job.js\";\nexport type { WebhookProvider, WebhookMeta, WebhookRequest } from \"./webhook.js\";\n// Webhooks and jobs are classes: `@Webhook`/`@On` for inbound webhooks,\n// `@Job` for cron. Both take their name from their file — see decorators/*.\nexport { getWebhookConfig, On, Webhook } from \"./decorators/webhook.js\";\nexport type { ResolvedWebhook, SignatureSpec, WebhookEventHandler, WebhookOptions } from \"./decorators/webhook.js\";\nexport { getJobConfig, Job } from \"./decorators/job.js\";\nexport type { JobOptions, ResolvedJob } from \"./decorators/job.js\";\n// `Resource` is GONE, not deprecated. Its boot registry was never wired: nothing\n// in the runtime ever called `__runResourceBoot` (measured 2026-08-29 —\n// `grep -rn \"ResourceBoot\"` across v2/runtime and palsvc returned nothing), so\n// `init(env)` never ran, the declared secrets never arrived, and a project that\n// wrote one got an object whose fields sat at their initializers with no error\n// anywhere. That is the same silence the `auth`/`storage`/`documents` hook\n// helpers were removed for, one surface down.\n//\n// Nothing replaces it, because the thing it was ceremony around is already the\n// stack's: the VAULT holds what a backend may read, the runtime lists those names\n// off it and mirrors them into `process.env` at boot, and `Secrets.get()` reads a\n// value with the rotation the deploy generation already carries. A field frozen\n// once inside `init(env)` could not have that. `static secrets` was therefore a\n// third list of names, behind the vault and behind `config/secrets.ts` — which is\n// itself down to a hint rather than a constraint (v2/runtime/src/server.ts:517).\n// `config/egress.ts` fences the calls a resource would have made and\n// `openai.embedding(...)` in the schema puts the one vendor client the platform\n// actually runs where the platform runs it. `resources/` stays exactly what the\n// bundler already treats it as — a directory of plain modules a controller\n// imports.\n// Types only. A hook is declared with @Hook/@On in hooks/*.ts.\n//\n// The `auth`/`storage`/`documents` helpers that used to live here are gone, not\n// deprecated: they returned a record nothing in the runtime or the bundler ever\n// read, so a project that called one got a handler that never ran and no error\n// anywhere. api-surface.mjs asks for a deprecation bridge because a major locks\n// every tenant's deploy — a real cost, and the reason this shipped as a bridge\n// in 20.0.0. There are no production tenants to lock yet (owner's call,\n// 2026-08-22), so the bridge is spending a release to soften a break nobody can\n// feel, and the honest surface is the one with no dead names in it.\nexport type {\n HookMeta,\n AuthHookEvent,\n DocumentHookEvent,\n FileUploadedEvent,\n FileDeletedEvent,\n} from \"./hooks.js\";\nexport { z } from \"zod\";\n","/**\n * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, controller methods import PascalCase service singletons directly:\n *\n * import { Controller, Post, Body, Database } from \"@palbase/backend\";\n *\n * \\@Controller(\"/todos\")\n * export default class TodosController {\n * \\@Post(\"\") create(\\@Body(CreateTodoBody) body: CreateTodoBody): unknown {\n * return Database.insert(\"todos\", { title: body.title });\n * }\n * }\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport type { PalbaseFlagKey } from \"./stack.js\";\nimport type { Buckets, BucketTypes, Schemas } from \"./db/env.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n DBOps,\n CacheClient,\n Logger,\n PalbaseDocsClient,\n SecretsService,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseSetOverrideResult,\n PalbaseRealtimeClient,\n} from \"./clients.js\";\nimport type { PalbaseResult } from \"./endpoint.js\";\nimport type {\n EnvTypedDatabase,\n EnvServiceDatabase,\n EnvSchemas,\n EnvTables,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\nimport type { Materialized } from \"./db/tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./db/tx-plan.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but\n * cannot hold a subscription socket — `subscribe()` lives on the client SDK).\n *\n * EXCLUDED on purpose: Functions, Links, Analytics, Auth. They are not\n * exposed as backend handler singletons (auth lives on the client SDK; the rest\n * are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Secrets: SecretsService;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n Realtime: PalbaseRealtimeClient;\n}\n\n/**\n * The per-request ALS box.\n *\n * `runtime` is the service bundle. `userId` is the request's authenticated user\n * id, written by the runtime immediately after it assembles the request object\n * (worker.js: `requestALS.getStore().userId = pbReq.user?.id || null`) and\n * `null` on an anonymous request. It was already being written there for the\n * Flags client's auto-bind; declaring it here makes the existing contract typed\n * instead of implicit, which is what lets `currentSubjectId()` read a\n * server-owned identity rather than trusting anything the caller sent.\n */\nexport interface RequestStore {\n runtime: RuntimeServices;\n userId?: string | null;\n /** This request's id (`req_…`), written by the runtime. Used as the spend\n * idempotency scope when the caller supplied no `Idempotency-Key`. */\n requestId?: string;\n /** The caller's `Idempotency-Key` header, or `null` when absent. What makes a\n * client's retry replay its first result instead of charging twice. */\n idempotencyKey?: string | null;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\nexport const __requestALS = new AsyncLocalStorage<RequestStore>();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return scoped.runtime;\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n// ─── lifecycle: where a long-lived resource lives (FR-013) ─────────────────\n//\n// `Resource` was removed in 23.0.0 and nothing replaced the LIFECYCLE half of\n// it. What that left behind is measurable: a connection pool (the driver in\n// `docs/resources.md`'s own example was Neo4j) had no documented place to be\n// opened and NO WAY AT ALL to be closed, so every deploy left the pool it\n// opened behind. These two hooks are that half — and only that half. The\n// secret-distribution half does not come back: a handler reads `Secrets.get`,\n// and a start hook, which runs before any request scope exists, reads the\n// `process.env` the runtime mirrors the vault into at boot.\n\n/** A lifecycle hook. Sync or async; the runtime awaits what it returns. */\nexport type LifecycleHook = () => void | Promise<void>;\n\n/** Runs one release's shutdown hooks. Handed back by {@link __runStartHooks}\n * and called by the engine's `app.shutdown()`. Idempotent. */\nexport type ShutdownRunner = () => Promise<void>;\n\ninterface DeclaredHook {\n name: string;\n run: LifecycleHook;\n}\n\ninterface DeclaredLifecycle {\n start: DeclaredHook[];\n shutdown: DeclaredHook[];\n}\n\n/**\n * What has been DECLARED and not yet claimed by an app.\n *\n * On globalThis under a well-known Symbol for the reason the controller\n * registry is (`decorators/controller.ts`): a deployed bundle inlines its own\n * copy of this package, and the engine that has to RUN these hooks holds the\n * other copy. Two module-local arrays would mean the engine reads the empty one\n * and every declared hook is silently never run — which is exactly how\n * `Resource`'s `init(env)` died.\n */\nconst LIFECYCLE: unique symbol = Symbol.for(\"palbase.backend.lifecycleHooks\") as never;\n\nfunction declaredLifecycle(): DeclaredLifecycle {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n return (g[LIFECYCLE] ??= { start: [], shutdown: [] });\n}\n\n/**\n * Run `hook` ONCE while the application comes up, before it serves anything.\n *\n * Call it at MODULE SCOPE in a file the application imports — the same rule\n * `defineDefaultAuth` and `@Controller` follow, and for the same reason: the\n * declaration is claimed when the app boots, which is after module loading and\n * before the first request. `name` is not decoration: a hook that throws is\n * reported by that name and the boot is REFUSED, so it is what tells an\n * operator which resource did not come up.\n *\n * There is no request scope yet, so the `Database`/`Secrets`/… singletons are\n * NOT available inside a start hook. A secret is read from `process.env` here\n * (the runtime mirrors the vault into it at boot).\n *\n * @example\n * // resources/graph.ts\n * import neo4j from \"neo4j-driver\";\n * import { onStart, onShutdown } from \"@palbase/backend\";\n *\n * export let graph: Driver;\n * onStart(\"graph\", () => {\n * graph = neo4j.driver(process.env.NEO4J_URL!, neo4j.auth.basic(\"neo4j\", process.env.NEO4J_PASSWORD!));\n * });\n * onShutdown(\"graph\", () => graph.close());\n */\nexport function onStart(name: string, hook: LifecycleHook): void {\n declaredLifecycle().start.push({ name, run: hook });\n}\n\n/**\n * Run `hook` while the application shuts down — the place a pool opened in\n * {@link onStart} is closed.\n *\n * Shutdown is BEST-EFFORT by design: a hook that throws is reported by name and\n * the rest still run. A drain that abandoned the remaining hooks on the first\n * failure would leak exactly what this exists to release, and the process is\n * leaving anyway.\n *\n * Hooks run in REVERSE declaration order, so a resource is released before what\n * it was built on.\n */\nexport function onShutdown(name: string, hook: LifecycleHook): void {\n declaredLifecycle().shutdown.push({ name, run: hook });\n}\n\nfunction reason(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Best-effort drain: every hook runs, a failure is reported, none is silent. */\nasync function drain(hooks: DeclaredHook[]): Promise<void> {\n for (const h of [...hooks].reverse()) {\n try {\n await h.run();\n } catch (err) {\n console.error(`[palbase] shutdown hook \"${h.name}\" failed: ${reason(err)}`, err);\n }\n }\n}\n\n/**\n * CLAIM what has been declared, run the start hooks, and hand back the runner\n * for this release's shutdown hooks. Called by the engine's `createApp`; the\n * `App.shutdown()` it builds calls what comes back. NOT part of the public\n * author-facing API.\n *\n * IT CLAIMS RATHER THAN READS, which is what makes it correct in this runtime:\n * a candidate release is loaded BESIDE the live one in one process\n * (`v2/runtime/src/registry-scope.ts`), and both bundles append to the one\n * shared slot above. If each app read the whole list, the live app's shutdown\n * would close the candidate's pool and the candidate's would close the live\n * app's. Taking the declarations leaves each app holding exactly its own.\n *\n * A start hook that throws REFUSES THE BOOT — with the hook's name in the\n * message — after releasing whatever the earlier hooks already opened. Serving\n * from a half-initialised app is the silence this whole surface replaces, and a\n * boot that dies holding an open pool is the leak it replaces.\n */\nexport async function __runStartHooks(): Promise<ShutdownRunner> {\n const slot = declaredLifecycle();\n const start = slot.start.splice(0);\n const shutdown = slot.shutdown.splice(0);\n\n for (const h of start) {\n try {\n await h.run();\n } catch (err) {\n await drain(shutdown);\n throw new Error(`[palbase] start hook \"${h.name}\" failed: ${reason(err)}`, { cause: err });\n }\n }\n\n let drained = false;\n return async () => {\n // SIGTERM racing a redeploy asks twice; a pool is closed once.\n if (drained) return;\n drained = true;\n await drain(shutdown);\n };\n}\n\n/** Drop every declaration. For tests, which declare repeatedly in one process.\n * NOT part of the public author-facing API. */\nexport function __resetLifecycleHooks(): void {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n delete g[LIFECYCLE];\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/**\n * Build the `.tables` accessor for the top-level `Database`. Each\n * `tables.<name>` access returns a small object that forwards the five CRUD ops\n * to the underlying client using `name` as the string table identifier. The\n * shapes are typed against the generated `palbase-env.d.ts` (`EnvTables`); at\n * runtime they are plain string-keyed calls, so no schema value is needed here.\n *\n * Returns `EnvTables` — TS cannot infer the mapped type through the Proxy, so\n * a single structural narrowing names the surface (the proxy returns a\n * correctly-shaped accessor for whatever string member is read).\n */\n/** T018 (C-8): similar/recommend'in string-keyed yüzü. DBOps'a (endpoint.ts)\n * BİLEREK eklenmedi — search-param imza üçlüsü (engine/db + typed-db +\n * endpoint) büyümesin: proxy dispatch runtime'da engine ops'una zaten ulaşır,\n * derleme güvenliğini typed yüzey (EnvTypedTable) verir. */\ninterface RecoOps {\n similar(table: string, id: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n recommend(table: string, params: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\n/**\n * The Proxy behind EVERY `.tables` map — public's and every other schema's.\n *\n * `prefix` is what the wire name is built from: `\"\"` for `public`, so its tables\n * stay BARE, and `\"<schema>.\"` for any other, so `schema(\"billing\").tables\n * .invoices` reaches the broker as `billing.invoices` (D-10 — the same\n * schema-qualified key `toSchemaJSON` and the generated `relations` use).\n *\n * One trap for both surfaces: two copies would be two op lists that can drift,\n * and the one that forgets an op does not complain — it answers `undefined`.\n */\nfunction makeTableProxy(ops: () => DBOps & RecoOps, prefix: string): object {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n const name = `${prefix}${prop}`;\n return {\n insert: (data: Record<string, unknown>) => ops().insert(name, data),\n update: (id: string, data: Record<string, unknown>) => ops().update(name, id, data),\n delete: (id: string) => ops().delete(name, id),\n findById: (id: string) => ops().findById(name, id),\n findMany: (query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n ops().findMany(name, query, opts),\n upsert: (data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n ops().upsert(name, data, opts),\n search: (params?: Record<string, unknown>) => ops().search(name, params),\n similar: (id: string, params?: Record<string, unknown>) => ops().similar(name, id, params),\n recommend: (params: Record<string, unknown>) => ops().recommend(name, params),\n facets: (params: { facets: string[] } & Record<string, unknown>) => ops().facets(name, params),\n supersede: (id: string, row: Record<string, unknown>) => ops().supersede(name, id, row),\n };\n },\n },\n );\n}\n\nfunction makeTablesAccessor(ops: () => DBOps & RecoOps): EnvTables {\n return makeTableProxy(ops, \"\") as EnvTables;\n}\n\n/**\n * The `.tables` map of ONE schema other than `public`, as\n * `Database.schema(\"billing\")` returns it.\n *\n * Same accessor, one difference: the wire name is schema-qualified. Nothing here\n * decides whether the schema is reachable — `exposed` is the schema's own\n * declaration and the broker checks it.\n */\nfunction makeSchemaAccessor<S extends keyof Schemas>(\n ops: () => DBOps & RecoOps,\n schema: S,\n): EnvSchemas[S] {\n return { tables: makeTableProxy(ops, `${String(schema)}.`) } as EnvSchemas[S];\n}\n\n/** The raw string-keyed `DBClient` for the current request scope. */\nconst rawDatabase: DBClient = makeServiceProxy(\"Database\");\n\n/**\n * Wrap a raw `DBClient` into the typed `{ ...ops, tables, transaction }`\n * surface. The five string ops forward straight through; `tables` is the\n * env-typed accessor; `transaction` yields typed tables. Reused for both the\n * default (RLS-enforced) `Database` and the `asService()` sibling — each is\n * fed its own raw client (the default proxy vs `rawDatabase.asService()`).\n *\n * The `satisfies` pins the op surface so a missing/renamed op is a compile\n * error; the assembled object carries `tables`/`transaction` alongside.\n */\nfunction makeTypedSurface(raw: Omit<DBClient, \"asService\">): EnvServiceDatabase {\n // Proxy dispatch her üyeyi taşır; RecoOps tipi DBClient'a eklenmediğinden\n // (yukarıdaki karar) similar/recommend erişimi bu daraltmadan geçer.\n const reco = raw as Omit<DBClient, \"asService\"> & RecoOps;\n const ops = {\n query: (sql: string, params?: unknown[]) => raw.query(sql, params),\n insert: (table: string, data: Record<string, unknown>) => raw.insert(table, data),\n update: (table: string, id: string, data: Record<string, unknown>) =>\n raw.update(table, id, data),\n delete: (table: string, id: string) => raw.delete(table, id),\n findById: (table: string, id: string) => raw.findById(table, id),\n findMany: (table: string, query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n raw.findMany(table, query, opts),\n upsert: (table: string, data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n raw.upsert(table, data, opts),\n updateMany: (table: string, where: Record<string, unknown>, set: Record<string, unknown>) =>\n raw.updateMany(table, where, set),\n deleteMany: (table: string, where: Record<string, unknown>) => raw.deleteMany(table, where),\n count: (table: string, where?: Record<string, unknown>) => raw.count(table, where),\n search: (table: string, params?: Record<string, unknown>) => raw.search(table, params),\n similar: (table: string, id: string, params?: Record<string, unknown>) =>\n reco.similar(table, id, params),\n recommend: (table: string, params: Record<string, unknown>) => reco.recommend(table, params),\n facets: (table: string, params: { facets: string[] } & Record<string, unknown>) => reco.facets(table, params),\n supersede: (table: string, id: string, row: Record<string, unknown>) =>\n raw.supersede(table, id, row),\n } satisfies DBOps & RecoOps;\n return Object.assign(ops, {\n // Both surfaces get it: a savepoint on the service transaction is as useful\n // as one on the request's, and each is bound to its own connection.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>) => raw.attempt(fn),\n tables: makeTablesAccessor(() => reco),\n schema: <S extends keyof Schemas>(name: S): EnvSchemas[S] =>\n makeSchemaAccessor(() => reco, name),\n transaction<T>(\n fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>> {\n // A FRESH builder per call: it holds this transaction's ops and its error\n // slot table, and the runtime serves concurrent requests on one event loop.\n // A shared builder would splice one request's writes into another's plan.\n const builder = new TxPlanBuilder();\n return runTxPlan(raw, makeTxTablesAccessor(builder), builder, fn) as Promise<\n Materialized<T>\n >;\n },\n });\n}\n\n/**\n * The transaction twin of {@link makeTablesAccessor}: `tables.<name>` yields the\n * table's PLAN operations, recorded into `builder` instead of sent one by one.\n *\n * Same Proxy shape and same reason for the single narrowing — TS cannot infer a\n * mapped type through a Proxy, so the cast names what the trap returns.\n */\nfunction makeTxTablesAccessor(builder: TxPlanBuilder): TxTables {\n const tablesProxy = new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return builder.table(prop);\n },\n },\n );\n return tablesProxy as TxTables;\n}\n\n/**\n * The project's own Postgres (pgx, schema `env_<envId>`).\n *\n * Typed by default: `Database.tables.<name>.insert({...})` is typed against\n * the project's generated `palbase-env.d.ts` with NO import and NO generic.\n * The raw string ops (`query`/`insert`/`update`/`delete`/`findById`/`findMany`)\n * are also available for dynamic table names and read-only SQL.\n *\n * RLS is enforced by default (the runtime runs each op as `authenticated` with\n * the verified user's claims). To bypass RLS, call `Database.asService()` —\n * explicit and greppable — which runs as the `service_role` (BYPASSRLS).\n *\n * @example\n * import { Database } from \"@palbase/backend\";\n *\n * const todo = await Database.tables.todos.insert({ title: req.input.title });\n * todo.id; // string ✓\n * const rows = await Database.query(\"SELECT id FROM todos WHERE done = $1\", [false]);\n * const all = await Database.asService().tables.todos.findMany({}); // RLS bypass\n */\nexport const Database: EnvTypedDatabase = Object.assign(makeTypedSurface(rawDatabase), {\n /**\n * Lazily resolve the runtime's service-role sibling on each call. We do NOT\n * cache it: `rawDatabase.asService()` reads the CURRENT request scope through\n * the runtime proxy, and the per-request runtime injects a service client\n * bound to that request's identity headers — caching would leak one request's\n * sibling into another concurrent request.\n */\n asService(): EnvServiceDatabase {\n return makeTypedSurface(rawDatabase.asService());\n },\n});\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/**\n * `buckets.<name>` — the storage twin of `Database.tables.<name>`, and the same\n * mechanism: `config/storage.ts` generates a `Buckets` augmentation into\n * `palbase-env.d.ts`, so a bucket name is a property with no import and no\n * generic, and a typo is a compile error.\n *\n * The intermediate `.buckets` is there for the reason `.tables` is: bucket\n * names must not share a namespace with the client's own methods, or the day\n * somebody declares a bucket called `bucket` the surface breaks.\n */\nexport type EnvBuckets = {\n [K in keyof Buckets]: TypedBucketClient<Buckets[K] extends BucketTypes ? Buckets[K] : BucketTypes>;\n};\n\n/** One bucket, with its declared variant names in the type. */\nexport interface TypedBucketClient<B extends BucketTypes> extends Omit<PalbaseBucketClient, \"getPublicUrl\"> {\n /** The public URL for the object, or for one of THIS bucket's declared\n * renditions. A name the bucket does not declare is a compile error. */\n getPublicUrl(path: string, options?: { variant?: B[\"variants\"] }): string;\n}\n\nfunction makeBucketsAccessor(storage: () => PalbaseStorageClient): EnvBuckets {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return storage().bucket(prop);\n },\n },\n ) as EnvBuckets;\n}\n\nconst rawStorage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/**\n * Object storage: buckets, objects, renditions and signed URLs.\n *\n * `Storage.buckets.posts.upload(...)` is the typed path. `Storage.bucket(name)`\n * remains for a name computed at runtime — rare, and it gives up the typing,\n * which is the honest trade rather than a second blessed way to do it.\n */\nexport const Storage: PalbaseStorageClient & { buckets: EnvBuckets } = Object.assign(\n {\n // FORWARDED explicitly, not assigned onto the service proxy.\n //\n // `Object.assign(rawStorage, {buckets})` writes onto the proxy's TARGET, and\n // the proxy's only trap is `get`, which forwards every read to the module\n // client — so the property landed somewhere nothing reads and\n // `Storage.buckets.docs` was `undefined` in a deployed handler. It\n // typechecked, every test passed, and the live call answered\n // \"TypeError: undefined is not an object\". `Database` never had the bug\n // because it builds a plain surface the same way this now does.\n bucket: (name: string) => rawStorage.bucket(name),\n },\n { buckets: makeBucketsAccessor(() => rawStorage) },\n);\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n\n/**\n * This tenant's secrets — API keys, provider credentials, signing material the\n * BACKEND owns.\n *\n * `await Secrets.get(\"STRIPE_KEY\")` in a handler. There is no `.env` to read\n * and no file to mount: a secret is written through the vault's authenticated\n * API (or the CLI/MCP that calls it), and this is how the deployed code reads\n * it back. A name this tenant has not set answers null — as does every name\n * the STACK holds, because no route returns a platform secret's value at all.\n */\nexport const Secrets: SecretsService = makeServiceProxy(\"Secrets\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n\n/**\n * The raw runtime Flags client for the current request scope. Carries the\n * default-surface reads + `setOverride` AND the runtime's `asService()` sibling\n * (the br-pod's `buildFlagsClient` returns both). The default `Flags` singleton\n * below forwards reads + `setOverride` through here; `Flags.asService()`\n * forwards to this client's own `asService()`.\n */\nconst rawFlags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Feature flags.\n *\n * Mirrors the `Database` / `Database.asService()` model. The default surface is\n * RLS-equivalent for flags: reads resolve against the CURRENT request user and\n * `Flags.setOverride(key, value)` writes an override for that same signed-in\n * user (no userId argument, no admin power). Cross-user admin writes\n * (`setOverrideForUser`, …) live behind `Flags.asService()` — explicit and\n * greppable, just like `Database.asService()`.\n *\n * @example\n * import { Flags } from \"@palbase/backend\";\n *\n * if (await Flags.isEnabled(\"new_checkout\")) { ... } // current user\n * await Flags.setOverride(\"new_checkout\", true); // current user\n * await Flags.asService().setOverrideForUser(\"u_9\", \"x\", true); // cross-user\n */\nexport const Flags: PalbaseFlagsClient = Object.assign(\n {\n isEnabled(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<boolean>> {\n return rawFlags.isEnabled(flagName, context);\n },\n getVariant(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagVariant>> {\n return rawFlags.getVariant(flagName, context);\n },\n getAll(context?: PalbaseFlagContext): Promise<PalbaseResult<PalbaseFlag[]>> {\n return rawFlags.getAll(context);\n },\n /**\n * Resolve a flag's value, with an optional fallback.\n *\n * FORWARDED as of 2026-08-15. This surface is written out by hand, method\n * by method, and `get` was missing from it — so the client implemented it,\n * thirty assertions covered it, and `Flags.get(\"x\")` was `undefined` in a\n * deployed handler. Exactly the shape of the `Storage.buckets` defect found\n * the same day: a hand-maintained forwarding list is a list somebody has to\n * remember to update.\n */\n get(\n flagName: PalbaseFlagKey,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n return rawFlags.get(flagName, defaultOrContext, maybeContext);\n },\n setOverride(\n key: PalbaseFlagKey,\n value: PalbaseFlagValue,\n ): Promise<PalbaseResult<PalbaseSetOverrideResult>> {\n return rawFlags.setOverride(key, value);\n },\n },\n {\n /**\n * Lazily resolve the runtime's cross-user sibling on each call. We do NOT\n * cache it: `rawFlags.asService()` reads the CURRENT request scope through\n * the runtime proxy, so caching would leak one request's sibling into\n * another concurrent request. Mirrors `Database.asService()`.\n */\n asService(): PalbaseFlagsServiceClient {\n return rawFlags.asService();\n },\n },\n);\n\n/**\n * The Realtime broadcast singleton for the current request scope. Backend-side\n * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —\n * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:\n * `broadcast` resolves once accepted (or with an `error`), never blocking the\n * handler on subscribers.\n *\n * @example\n * import { Realtime } from \"@palbase/backend\";\n *\n * await Realtime.broadcast(\"room:42\", \"message\", { text, from: user.id });\n */\nexport const Realtime: PalbaseRealtimeClient = makeServiceProxy(\"Realtime\");\n","/**\n * tx-plan.ts — `Database.transaction()` as a PLAN, not a pinned session.\n *\n * A transaction used to be a conversation: BEGIN, then one network round trip\n * per operation, then COMMIT. Each of those round trips cost ~4 ms and, because\n * the pooler runs in transaction mode, an open transaction pinned a Postgres\n * backend for the whole conversation. A 121-operation statement upload pinned\n * one backend for ~490 ms.\n *\n * So the callback no longer TALKS to the database. It DESCRIBES what should\n * happen; the description is serialised and sent once; the broker runs the whole\n * thing inside one transaction and answers once. Committing on return and\n * rolling back on throw is unchanged — that is the only property tenant code\n * actually asked for.\n *\n * The consequences, stated plainly, because they are the whole design:\n *\n * - The callback is SYNCHRONOUS. There is nothing to await: no statement has\n * run yet when it returns. `async` on the callback and `await` inside it are\n * both compile errors (see {@link TxPlan} and {@link NotAwaitable}).\n * - `insert()` does not hand back a row, it hands back {@link TxRows}. Reading\n * a field requires `.expectOne(err)` first, which makes \"what if the row\n * isn't there\" a question you cannot route around: it is the argument.\n * - A field read from a row is a {@link Ref} — a PROMISE OF A VALUE THE SERVER\n * WILL PRODUCE, not the value. It can be written into a later operation and\n * it can be returned from the callback (it is substituted for the real value\n * before `transaction()` resolves). It cannot be branched on. See the\n * \"Truthiness\" note below — this is the sharp edge of the whole design.\n * - Control flow that needs a real value must move OUT of the callback: read\n * before the transaction, or express the condition as a guard\n * (`updateWhere({ id, accepted_at: null }, …).expectOne(new Conflict(…))`)\n * which the server evaluates and which rolls the whole plan back.\n *\n * # Truthiness — the hole this file CANNOT close\n *\n * JavaScript does not let a Proxy trap truthiness. `if (ref)` takes the true\n * branch, always, for every Ref, and no `get` handler ever runs. `tsc` is silent\n * because a Ref is a perfectly good object. So:\n *\n * const pot = tx.tables.pots.select({ id }, { limit: 1 }).expectOne(e);\n * if (!pot.balance) { … } // ← ALWAYS false. Silently wrong data.\n *\n * What this file does close: coercion (`Symbol.toPrimitive`/`valueOf`/\n * `toString`), awaiting (`then` is a callable member with a non-thenable\n * signature, which is a *compile* error), serialisation (`toJSON`), and nesting\n * a Ref inside a literal value where the server would store it as data. What it\n * cannot close is a bare truthiness test. The real defence is the build-time\n * static analysis (`tx_analysis.js`, phase P4); until that ships, this hole is\n * open and this comment is the only warning.\n *\n * # Wire contract\n *\n * The JSON this file emits is consumed by\n * the plan executor in `engine/db.ts`. That executor rejects\n * unknown fields at every level, so an op carries EXACTLY the fields its kind\n * takes. Everything here that looks like a needless restriction is one of the\n * server's rules made visible early:\n *\n * - `$ref` only points BACKWARDS, and only at an op statically known to yield\n * at most one row (insert, or a `one`/`atMost 1` guard, or `select limit 1`).\n * `.expectOne()` is what this file uses to satisfy that, always.\n * - `$expr` is a closed set: `inc`/`dec` (update only — they read the column's\n * current value) and `now()`.\n * - `update`/`delete` require a `where`; `insert` refuses one.\n * - `insertMany` rows must all set the same columns.\n * - ≤1000 ops, ≤5000 rows per insertMany, ≤8 MiB of JSON.\n *\n * Column keys are emitted SORTED, so the same callback always produces byte-\n * identical JSON. That is what lets the Go decoder be locked to golden files\n * this SDK emits (`testdata/tx_plan_golden/`).\n */\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * A plan handle was used as if it were a value: awaited, coerced to a string or\n * number, serialised, or nested inside another value.\n *\n * Thrown while the callback is still BUILDING the plan, so nothing has been sent\n * and nothing has been written.\n */\nexport class TxRefError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxRefError\";\n }\n}\n\n/**\n * The plan the callback described cannot be sent: it breaks a rule the server\n * would reject, and rejecting it here names the line that wrote it instead of\n * returning a 400 about an op index.\n */\nexport class TxPlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxPlanError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Wire types — mirror the plan executor in `engine/db.ts` exactly.\n// ---------------------------------------------------------------------------\n\n/** A backwards reference to an earlier op's single-row result. */\nexport interface TxWireRef {\n $ref: { op: number; field: string };\n}\n\n/** A call from the server's closed function set. */\nexport interface TxWireExpr {\n $expr: { fn: \"inc\" | \"dec\"; by: number } | { fn: \"now\" };\n}\n\n/** One value in a `values`/`set`/`where` map: a literal, a `$ref` or a `$expr`. */\nexport type TxWireValue = TxWireRef | TxWireExpr | unknown;\n\n/** The tenant's declared expectation about an op's row count. `slot` indexes the\n * client-side error table — the error OBJECT never travels. */\nexport interface TxWireGuard {\n kind: \"one\" | \"none\" | \"atLeast\" | \"atMost\";\n n: number;\n slot: number;\n}\n\n/** One operation in the wire plan. Fields are omitted, never null: the decoder\n * rejects a field that does not belong to the op's kind. */\nexport interface TxWireOp {\n /** upsert and insertMany: the columns Postgres matches on. */\n onConflict?: readonly string[];\n /** insertMany only: what a collision does. Absent means no ON CONFLICT clause\n * at all, which is what every insertMany did before this option existed. */\n action?: \"ignore\" | \"update\";\n op: \"insert\" | \"insertMany\" | \"upsert\" | \"update\" | \"delete\" | \"select\";\n table: string;\n values?: Record<string, TxWireValue>;\n rows?: Record<string, TxWireValue>[];\n set?: Record<string, TxWireValue>;\n where?: Record<string, TxWireValue>;\n limit?: number;\n lock?: \"update\";\n guard?: TxWireGuard;\n}\n\n/** The plan the engine executes on the request's own transaction. */\nexport interface TxPlanBody {\n ops: TxWireOp[];\n}\n\n/** One op's outcome, positionally matched to the plan's ops. */\nexport interface TxPlanOpResult {\n rows: Record<string, unknown>[];\n rows_affected: number;\n}\n\n/** One result per op, in plan order. */\nexport interface TxPlanResponse {\n results: TxPlanOpResult[];\n}\n\n/**\n * The fields the runtime must copy from the broker's error envelope onto the\n * rejection it throws out of {@link DBClient.txPlan}.\n *\n * `slot` is the whole point: on a guard failure the server answers with the\n * INDEX of the expectation that did not hold, never with an error message of its\n * own, and this SDK maps that index back to the `Error` the callback handed to\n * `.expectOne(…)`. Without `slot` a guard failure degrades to a generic 409.\n */\nexport interface TxPlanRejection {\n status?: number;\n /** `tx_plan_invalid` | `tx_guard_failed` | `tx_ref_unresolved` | a pg class. */\n error_code?: string;\n /** Present only for `tx_guard_failed`: the client-side error table index. */\n slot?: number;\n /** Present on a database error: which op failed. */\n op?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Handle types\n// ---------------------------------------------------------------------------\n\ndeclare const refBrand: unique symbol;\ndeclare const rowBrand: unique symbol;\ndeclare const rowsBrand: unique symbol;\n\n/**\n * Makes a handle a compile error to `await`.\n *\n * `then` is declared as a CALLABLE member whose signature is not `PromiseLike`,\n * which is precisely the shape TypeScript rejects: `await handle` is TS1320 and\n * `async () => handle` is TS1058. A non-callable `then` would not do it — the\n * compiler simply ignores those.\n */\nexport interface NotAwaitable {\n /** Not a promise. Nothing here has run yet; there is nothing to await. */\n then(doNotAwaitAPlanHandle: \"a transaction plan is built synchronously\"): never;\n}\n\n/**\n * A value the SERVER will produce, standing in for a column of a row this plan\n * writes or reads.\n *\n * Legal uses: write it into a later operation's `values`/`set`/`where`, or\n * return it from the callback (it is replaced by the real value before\n * `transaction()` resolves).\n *\n * Illegal, and caught: `await`, `String(ref)`, `` `${ref}` ``, `ref + 1`,\n * `JSON.stringify(ref)`, burying it inside a jsonb object.\n *\n * Illegal, and NOT caught: `if (ref)`. See the truthiness note at the top.\n */\nexport interface Ref<T> extends NotAwaitable {\n readonly [refBrand]: T;\n}\n\n/** The brand carried by a single-row handle, and the seam `Materialized` reads\n * to turn `return st` into the whole row. */\nexport interface TxRowHandle<Row> extends NotAwaitable {\n readonly [rowBrand]: Row;\n}\n\n/**\n * A row this plan is known to produce exactly one of. Every property is a\n * {@link Ref}; returning the handle itself yields the whole row.\n *\n * Only `.expectOne(err)` produces one — which is the design: a row you can read\n * fields from is a row whose absence you have already answered for.\n */\nexport type TxRow<Row> = { readonly [K in keyof Row]: Ref<Row[K]> } & TxRowHandle<Row>;\n\n/**\n * The result of one operation, before any expectation is declared about it.\n *\n * Deliberately not a row and not a list: an operation's row count is not known\n * until the server runs it, so the only thing that can be said about it here is\n * an EXPECTATION. Declaring one is also the only way to get a readable row.\n *\n * At most one expectation per operation — the wire carries one guard per op, and\n * a second call throws rather than silently dropping the first.\n */\nexport interface TxRows<Row> extends NotAwaitable {\n readonly [rowsBrand]: Row;\n /**\n * Require exactly one row, and read it. On any other count the server rolls\n * the whole transaction back and this `error` is thrown to the caller.\n *\n * This is the only way to reach a row's fields, and the only shape a `$ref`\n * may point at.\n */\n expectOne(error: Error): TxRow<Row>;\n /** Require zero rows (e.g. \"this membership must not already exist\"). */\n expectNone(error: Error): void;\n /** Require at least `n` rows. */\n expectAtLeast(n: number, error: Error): void;\n /** Require at most `n` rows. */\n expectAtMost(n: number, error: Error): void;\n}\n\n/** `now()` — the server's clock, usable wherever a value is. */\nexport interface TxNow extends NotAwaitable {\n readonly $expr: { fn: \"now\" };\n}\n\n/** `inc(n)` / `dec(n)` — read the column's CURRENT value and write it back\n * changed. Only meaningful in an update's `set`, which is where the types allow\n * it and where the server allows it. */\nexport interface TxColumnExpr extends NotAwaitable {\n readonly $expr: { fn: \"inc\" | \"dec\"; by: number };\n}\n\n/**\n * Resolve a callback's return type against what actually comes back: every\n * {@link Ref} becomes its value, every {@link TxRow} becomes its row, and\n * anything else keeps its shape.\n *\n * A {@link TxRows} resolves to an explanatory string type rather than a row\n * list: it has no single answer to give, and saying so in the type is louder\n * than a runtime throw.\n */\nexport type Materialized<T> = T extends Ref<infer U>\n ? U\n : T extends TxRowHandle<infer R>\n ? R\n : T extends TxRows<unknown>\n ? \"a TxRows cannot leave the transaction callback — read a row with .expectOne(err) first\"\n : T extends Date\n ? T\n : T extends object\n ? { [K in keyof T]: Materialized<T[K]> }\n : T;\n\n// ---------------------------------------------------------------------------\n// Author-facing value types\n// ---------------------------------------------------------------------------\n\n/** A value written by an INSERT: a literal, an earlier row's field, or `now()`.\n * `inc`/`dec` are absent on purpose — they read a current value, and an inserted\n * row has none. */\nexport type TxInsertValue<V> = V | Ref<V> | TxNow;\n\n/** A value written by an UPDATE's `set`: everything an insert takes, plus the\n * read-modify-write expressions. */\nexport type TxSetValue<V> = V | Ref<V> | TxNow | TxColumnExpr;\n\n/** An insert payload: the table's insert shape, with refs and `now()` allowed. */\nexport type TxInsertShape<Insert> = { [K in keyof Insert]: TxInsertValue<Insert[K]> };\n\n/** An update's `set`: any subset of the insert shape, with expressions allowed. */\nexport type TxSetShape<Insert> = { [K in keyof Insert]?: TxSetValue<Insert[K]> };\n\n/**\n * A filter. Every entry is an equality test and they are AND-ed; a `null`\n * becomes `IS NULL`, which is what makes `{ accepted_at: null }` a usable\n * \"not yet accepted\" guard rather than a clause that matches nothing.\n */\nexport type TxWhere<Row> = { [K in keyof Row]?: Row[K] | Ref<Row[K]> };\n\n/** Options for a plan `select`. */\nexport interface TxSelectOptions {\n /** Cap the rows read. */\n limit?: number;\n /** Take a real `FOR UPDATE` row lock for the rest of the transaction. */\n lock?: \"update\";\n}\n\n/** One table, as the plan sees it. */\nexport interface TxTable<Row, Insert> {\n /** Insert one row. Returns a handle — call `.expectOne(err)` to read fields. */\n insert(values: TxInsertShape<Insert>): TxRows<Row>;\n /**\n * Insert many rows in ONE statement. Every row must set the same columns\n * (a row that omits one would silently take the column's default).\n *\n * An empty list writes nothing and sends nothing.\n */\n /**\n * Insert many rows in ONE statement, optionally choosing what a collision does.\n *\n * Without `opts` this is a plain multi-row INSERT and a collision aborts the\n * transaction — the behaviour every call had before the option existed.\n *\n * `action: \"ignore\"` emits `ON CONFLICT DO NOTHING`, which is how \"insert the\n * ones that are new\" becomes one round-trip instead of one per row with a\n * 23505 caught around each. **The returned rows are the ones actually\n * INSERTED**: a row that collided is skipped, so it is absent from the result\n * — Postgres does not return what it did not write.\n *\n * `action: \"update\"` emits `ON CONFLICT DO UPDATE`, setting every non-conflict\n * column from the incoming row, and every row comes back.\n */\n insertMany(\n rows: readonly TxInsertShape<Insert>[],\n opts?: {\n onConflict: readonly Extract<keyof Row, string>[];\n action?: \"ignore\" | \"update\";\n },\n ): TxRows<Row>;\n /**\n * Insert the row, or update it when it collides on `onConflict` — inside the\n * plan's savepoint, with the same meaning `tables.<t>.upsert()` has outside it.\n *\n * It is an operation because the alternative is not writable here: a failed\n * insert aborts the whole transaction, so \"try, then fall back\" cannot be two\n * plan steps.\n */\n upsert(\n values: TxInsertShape<Insert>,\n options: { onConflict: readonly Extract<keyof Row, string>[] },\n ): TxRows<Row>;\n /**\n * Update every row matching `where`. The filter comes first because it is the\n * dangerous half: an update whose `where` you got wrong rewrites rows you\n * never looked at. The server refuses an update with no `where` at all.\n */\n updateWhere(where: TxWhere<Row>, set: TxSetShape<Insert>): TxRows<Row>;\n /** Delete every row matching `where`. The server refuses an unfiltered delete. */\n deleteWhere(where: TxWhere<Row>): TxRows<Row>;\n /** Read rows, optionally locking them for the rest of the transaction. */\n select(where?: TxWhere<Row>, options?: TxSelectOptions): TxRows<Row>;\n}\n\n/**\n * The handle a transaction callback receives.\n *\n * It carries tables and nothing else: no `query`, no `findById`, no `asService`.\n * A read whose value the plan does not write belongs OUTSIDE the transaction,\n * where it costs one round trip and can be branched on like an ordinary value.\n */\nexport interface TxPlanHandle<TTables> {\n tables: TTables;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — expressions\n// ---------------------------------------------------------------------------\n\n/** Internal marker read by the serialiser. */\nconst EXPR = Symbol.for(\"palbase.tx.expr\");\nconst REF = Symbol.for(\"palbase.tx.ref\");\nconst ROW = Symbol.for(\"palbase.tx.row\");\nconst ROWS = Symbol.for(\"palbase.tx.rows\");\n\ninterface RefDescriptor {\n op: number;\n field: string;\n}\n\n/** Property reads that must not silently produce a value on a plan handle.\n * `then` is the one that matters for correctness (it makes `await` a compile\n * error AND stops a handle from being adopted by a promise); the rest turn a\n * silent wrong answer — `\"[object Object]\"`, `NaN`, `{}` — into a thrown one. */\nconst TRAPPED_PROPS: readonly (string | symbol)[] = [\n \"then\",\n \"valueOf\",\n \"toString\",\n \"toJSON\",\n Symbol.toPrimitive,\n];\n\nfunction trap(prop: string | symbol, what: string, hint: string): never {\n const name = typeof prop === \"symbol\" ? prop.description ?? String(prop) : prop;\n throw new TxRefError(\n `${what} was used as a value (via \\`${name}\\`). Nothing in a transaction ` +\n `callback has run yet, so there is no value to read. ${hint}`,\n );\n}\n\n/** The server's `now()`. */\nexport function now(): TxNow {\n return makeExpr({ fn: \"now\" }) as TxNow;\n}\n\n/** Add `by` to the column's current value. Only valid in an update's `set`. */\nexport function inc(by: number): TxColumnExpr {\n assertFiniteNumber(by, \"inc\");\n return makeExpr({ fn: \"inc\", by }) as TxColumnExpr;\n}\n\n/** Subtract `by` from the column's current value. Only valid in an update's `set`. */\nexport function dec(by: number): TxColumnExpr {\n assertFiniteNumber(by, \"dec\");\n return makeExpr({ fn: \"dec\", by }) as TxColumnExpr;\n}\n\nfunction assertFiniteNumber(by: number, fn: string): void {\n if (typeof by !== \"number\" || !Number.isFinite(by)) {\n // JSON has no NaN/Infinity: they would serialise to `null` and the server\n // would reject the plan with an unhelpful decode error.\n throw new TxPlanError(`${fn}() needs a finite number, got ${String(by)}`);\n }\n}\n\nfunction makeExpr(expr: TxWireExpr[\"$expr\"]): unknown {\n return new Proxy(\n { [EXPR]: expr } as Record<string | symbol, unknown>,\n {\n get(target, prop) {\n if (prop === EXPR) return target[EXPR];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(prop, \"A plan expression\", \"Write it into an operation instead.\");\n }\n return undefined;\n },\n },\n );\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — refs and row handles\n// ---------------------------------------------------------------------------\n\nfunction makeRef(op: number, field: string): unknown {\n const target: Record<string | symbol, unknown> = { [REF]: { op, field } satisfies RefDescriptor };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === REF) return t[REF];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n `\\`${field}\\` of a row this transaction has not written yet`,\n \"Pass it to another operation in the same plan, or return it from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n return undefined;\n },\n });\n}\n\nfunction makeRowHandle(op: number): unknown {\n const target: Record<string | symbol, unknown> = { [ROW]: op };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === ROW) return t[ROW];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n \"A row this transaction has not written yet\",\n \"Read one of its columns to reference it, or return the row from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n if (typeof prop === \"symbol\") return undefined;\n return makeRef(op, prop);\n },\n });\n}\n\nfunction refDescriptor(v: unknown): RefDescriptor | null {\n if (typeof v !== \"object\" || v === null) return null;\n const d = (v as Record<symbol, unknown>)[REF];\n return isRefDescriptor(d) ? d : null;\n}\n\nfunction isRefDescriptor(d: unknown): d is RefDescriptor {\n return (\n typeof d === \"object\" &&\n d !== null &&\n typeof (d as RefDescriptor).op === \"number\" &&\n typeof (d as RefDescriptor).field === \"string\"\n );\n}\n\nfunction rowOpIndex(v: unknown): number | null {\n if (typeof v !== \"object\" || v === null) return null;\n const op = (v as Record<symbol, unknown>)[ROW];\n return typeof op === \"number\" ? op : null;\n}\n\nfunction exprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n if (typeof v !== \"object\" || v === null) return null;\n const e = (v as Record<symbol, unknown>)[EXPR];\n return typeof e === \"object\" && e !== null ? (e as TxWireExpr[\"$expr\"]) : null;\n}\n\nfunction isRowsHandle(v: unknown): boolean {\n return typeof v === \"object\" && v !== null && (v as Record<symbol, unknown>)[ROWS] !== undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — value encoding\n// ---------------------------------------------------------------------------\n\n/**\n * Encode one value of a `values`/`set`/`where` map.\n *\n * The nesting check is not defensive tidiness. The server treats `$ref` as a\n * tagged value only at the TOP of a column's value; a ref buried inside a jsonb\n * payload is just data, and would be stored as the literal object\n * `{\"$ref\":{...}}` — a write that succeeds, commits, and is wrong. So a nested\n * handle is a hard error here, where the line that wrote it is still on the\n * stack.\n */\nfunction encodeValue(value: unknown, column: string, allowColumnExpr: boolean): TxWireValue {\n const ref = refDescriptor(value);\n if (ref) return { $ref: { op: ref.op, field: ref.field } } satisfies TxWireRef;\n\n const expr = exprOf(value);\n if (expr) {\n if (expr.fn !== \"now\" && !allowColumnExpr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() reads the column's current value, so it is ` +\n `only valid in updateWhere(where, set).`,\n );\n }\n return { $expr: expr } satisfies TxWireExpr;\n }\n\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant ` +\n `(e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n\n assertNoNestedHandles(value, column);\n return value;\n}\n\nfunction assertNoNestedHandles(value: unknown, column: string): void {\n if (typeof value !== \"object\" || value === null) return;\n if (value instanceof Date) return;\n if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: a plan handle is nested inside a value. The server would ` +\n `store it as literal JSON, not resolve it. Put the reference directly in ` +\n `the column.`,\n );\n }\n if (Array.isArray(value)) {\n for (const item of value) assertNoNestedHandles(item, column);\n return;\n }\n for (const item of Object.values(value as Record<string, unknown>)) {\n assertNoNestedHandles(item, column);\n }\n}\n\n/**\n * Encode a column map, dropping `undefined` and emitting keys SORTED.\n *\n * Sorting is what makes the same callback produce byte-identical JSON every\n * time, which is what lets the Go decoder be locked to goldens this SDK emits.\n * Dropping `undefined` mirrors what `JSON.stringify` would do anyway, but does\n * it where the resulting column list is still checkable.\n */\nfunction encodeMap(\n map: Record<string, unknown>,\n allowColumnExpr: boolean,\n): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n if (value === undefined) continue;\n out[key] = encodeValue(value, key, allowColumnExpr);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the builder\n// ---------------------------------------------------------------------------\n\n/** How many rows an op can produce, as far as the CLIENT can tell before it\n * runs. Only the empty `insertMany` is knowable, and knowing it is what lets a\n * doomed expectation fail on the line that declared it. */\nconst SKIPPED_OP = -1;\n\nclass TxRowsImpl<Row> implements TxRows<Row> {\n // Present so `isRowsHandle` recognises the object; never read for its value.\n readonly [ROWS] = true;\n // Phantom: the type brand that stops a bare object passing as a TxRows. Never\n // present at run time, which is what `declare` says.\n declare readonly [rowsBrand]: Row;\n private guarded = false;\n\n constructor(\n private readonly builder: TxPlanBuilder,\n private readonly opIndex: number,\n private readonly what: string,\n ) {}\n\n // The type-level `await` guard made real: TS rejects `await rows` at compile\n // time, and reaching this means someone called `.then(...)` by hand.\n then(): never {\n throw new TxRefError(\n `${this.what} cannot be awaited: a transaction callback builds a plan, it ` +\n `does not run statements. Remove the \\`await\\`.`,\n );\n }\n\n expectOne(error: Error): TxRow<Row> {\n this.declareGuard(\"one\", 1, error);\n if (this.opIndex === SKIPPED_OP) throw error;\n return makeRowHandle(this.opIndex) as TxRow<Row>;\n }\n\n expectNone(error: Error): void {\n this.declareGuard(\"none\", 0, error);\n }\n\n expectAtLeast(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtLeast\");\n this.declareGuard(\"atLeast\", n, error);\n if (this.opIndex === SKIPPED_OP && n > 0) throw error;\n }\n\n expectAtMost(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtMost\");\n this.declareGuard(\"atMost\", n, error);\n }\n\n private declareGuard(kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n if (!(error instanceof Error)) {\n // The error object is the ONLY thing that describes this failure to the\n // caller — the server sends back an index, never a message.\n throw new TxPlanError(\n `${this.what}: an expectation needs the Error to throw when it does not ` +\n `hold (e.g. \\`.expect…(new Conflict(\"already accepted\"))\\`).`,\n );\n }\n if (this.guarded) {\n throw new TxPlanError(\n `${this.what} already has an expectation. One operation carries one ` +\n `expectation; declare the second one on its own operation.`,\n );\n }\n this.guarded = true;\n if (this.opIndex === SKIPPED_OP) return;\n this.builder.attachGuard(this.opIndex, kind, n, error);\n }\n}\n\nfunction assertGuardCount(n: number, fn: string): void {\n if (!Number.isInteger(n) || n < 0) {\n throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);\n }\n}\n\n/** Bounds mirrored from the plan executor so an over-sized plan is named here rather\n * than rejected as an opaque 400 after it has crossed the network. */\nconst MAX_OPS = 1000;\nconst MAX_ROWS = 5000;\n\n/**\n * Accumulates ops and the client-side error table while the callback runs.\n *\n * Exported for the runtime and for tests that need the serialised plan without\n * a server; author code never sees it.\n */\nexport class TxPlanBuilder {\n private readonly ops: TxWireOp[] = [];\n /** Errors handed to expectations, indexed by the `slot` the server echoes. */\n private readonly slots: Error[] = [];\n\n /** The table surface handed to the callback. Untyped here; the public\n * `transaction()` signatures put the schema types on top. */\n table(name: string): TxTable<Record<string, unknown>, Record<string, unknown>> {\n return {\n insert: (values) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.insert() needs at least one column`);\n }\n return this.push({ op: \"insert\", table: name, values: encoded }, `${name}.insert()`);\n },\n\n upsert: (values, options) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.upsert() needs at least one column`);\n }\n if (options.onConflict.length === 0) {\n throw new TxPlanError(`${name}.upsert() needs at least one onConflict column`);\n }\n return this.push(\n { op: \"upsert\", table: name, values: encoded, onConflict: options.onConflict },\n `${name}.upsert()`,\n );\n },\n\n insertMany: (rows, opts) => {\n if (rows.length === 0) {\n // Nothing to write. Emitting an op would be a guaranteed 400 (the\n // server requires rows), and refusing outright would punish the\n // ordinary \"filtered every candidate out\" case.\n return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);\n }\n if (rows.length > MAX_ROWS) {\n throw new TxPlanError(\n `${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. ` +\n `Split the write across requests.`,\n );\n }\n const encoded = rows.map((row) => encodeMap(row as Record<string, unknown>, false));\n assertUniformRows(encoded, name);\n if (opts !== undefined && opts.onConflict.length === 0) {\n throw new TxPlanError(\n `${name}.insertMany() was given a conflict action with no onConflict ` +\n `columns. Postgres matches a collision on columns, so name them.`,\n );\n }\n return this.push(\n {\n op: \"insertMany\",\n table: name,\n rows: encoded,\n // Omitted entirely when no options were given, so the op a plain\n // insertMany produces is byte-identical to the one it produced\n // before this option existed.\n ...(opts !== undefined\n ? { onConflict: opts.onConflict, action: opts.action ?? \"ignore\" }\n : {}),\n },\n `${name}.insertMany()`,\n );\n },\n\n updateWhere: (where, set) => {\n const encodedWhere = encodeMap(where as Record<string, unknown>, false);\n const encodedSet = encodeMap(set as Record<string, unknown>, true);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.updateWhere() needs a filter. An update with no filter ` +\n `rewrites the whole table.`,\n );\n }\n if (Object.keys(encodedSet).length === 0) {\n throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);\n }\n return this.push(\n { op: \"update\", table: name, set: encodedSet, where: encodedWhere },\n `${name}.updateWhere()`,\n );\n },\n\n deleteWhere: (where) => {\n const encodedWhere = encodeMap(where as Record<string, unknown>, false);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.deleteWhere() needs a filter. A delete with no filter empties ` +\n `the table.`,\n );\n }\n return this.push(\n { op: \"delete\", table: name, where: encodedWhere },\n `${name}.deleteWhere()`,\n );\n },\n\n select: (where, options) => {\n const op: TxWireOp = { op: \"select\", table: name };\n const encodedWhere = encodeMap((where ?? {}) as Record<string, unknown>, false);\n if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;\n if (options?.limit !== undefined) {\n if (!Number.isInteger(options.limit) || options.limit < 0) {\n throw new TxPlanError(\n `${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`,\n );\n }\n op.limit = options.limit;\n }\n if (options?.lock !== undefined) op.lock = options.lock;\n return this.push(op, `${name}.select()`);\n },\n };\n }\n\n private push(op: TxWireOp, what: string): TxRows<Record<string, unknown>> {\n if (this.ops.length >= MAX_OPS) {\n throw new TxPlanError(\n `this transaction has ${MAX_OPS} operations, which is the limit. Use ` +\n `insertMany() for bulk writes, or split the work across requests.`,\n );\n }\n const index = this.ops.length;\n this.ops.push(op);\n return new TxRowsImpl(this, index, what);\n }\n\n /** Attach an expectation to an op and record its error in the slot table. */\n attachGuard(opIndex: number, kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n const op = this.ops[opIndex];\n // Unreachable: the index came from `push`. A loud failure beats a silently\n // unguarded write if that ever stops being true.\n if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);\n const slot = this.slots.length;\n this.slots.push(error);\n op.guard = { kind, n, slot };\n }\n\n /** The serialisable plan. Empty when the callback described no writes. */\n body(): TxPlanBody {\n return { ops: this.ops };\n }\n\n /** The error the server's `slot` selects, or `null` when it names one this\n * plan never declared (a server/client disagreement, not a tenant error). */\n errorForSlot(slot: number): Error | null {\n return this.slots[slot] ?? null;\n }\n}\n\nfunction assertUniformRows(rows: Record<string, TxWireValue>[], table: string): void {\n const first = rows[0];\n if (!first) return;\n const want = Object.keys(first);\n const wantKey = want.join(\",\");\n for (let i = 1; i < rows.length; i++) {\n const got = Object.keys(rows[i] as Record<string, TxWireValue>);\n if (got.join(\",\") !== wantKey) {\n // One statement, one column list. A ragged row would take the DB default\n // for the column it omitted — a write that succeeds and is wrong.\n throw new TxPlanError(\n `${table}.insertMany(): every row must set the same columns. Row 0 sets ` +\n `[${want.join(\", \")}] but row ${i} sets [${got.join(\", \")}]. ` +\n `(A property set to \\`undefined\\` counts as absent — use \\`null\\`.)`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — materialisation\n// ---------------------------------------------------------------------------\n\n/**\n * Replace every handle in the callback's return value with what the server\n * actually produced.\n *\n * Walks arrays and PLAIN objects only. Class instances (a Date, a Zod schema, a\n * domain object) are returned untouched — recursing into them would rebuild them\n * as bare objects, and nothing inside one can be a handle that this SDK created.\n */\nexport function materializeResult(value: unknown, results: TxPlanOpResult[]): unknown {\n const ref = refDescriptor(value);\n if (ref) {\n const row = rowOf(results, ref.op, `\\`${ref.field}\\``);\n if (!(ref.field in row)) {\n throw new TxPlanError(\n `the transaction's operation ${ref.op} returned no column \\`${ref.field}\\`.`,\n );\n }\n return row[ref.field];\n }\n\n const rowOp = rowOpIndex(value);\n if (rowOp !== null) return rowOf(results, rowOp, \"a row\");\n\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n \"an operation result cannot be returned from a transaction callback: its \" +\n \"row count is not known until the plan runs. Declare an expectation \" +\n \"(`.expectOne(err)`) and return the row, or a column of it.\",\n );\n }\n\n if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);\n return out;\n }\n\n return value;\n}\n\nfunction rowOf(results: TxPlanOpResult[], opIndex: number, what: string): Record<string, unknown> {\n const result = results[opIndex];\n if (!result) {\n throw new TxPlanError(\n `the transaction returned no result for operation ${opIndex}, so ${what} ` +\n `cannot be read.`,\n );\n }\n const row = result.rows[0];\n if (!row) {\n // Unreachable through the public API: a handle only exists behind an\n // `expectOne`, and the server rolls back rather than answering 200 with a\n // guard unmet. Loud, because the alternative is `undefined` in tenant data.\n throw new TxPlanError(\n `the transaction's operation ${opIndex} returned no row, so ${what} cannot ` +\n `be read.`,\n );\n }\n return row;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the driver\n// ---------------------------------------------------------------------------\n\n/** What {@link runTxPlan} needs from the runtime: one call, one transaction. */\nexport interface TxPlanTransport {\n txPlan(plan: TxPlanBody): Promise<TxPlanResponse>;\n}\n\n/**\n * Build the plan, send it, and resolve the callback's return value.\n *\n * A callback that throws never reaches the network: there is nothing to roll\n * back because nothing was sent. A callback that describes no writes also skips\n * the round trip entirely.\n *\n * The RETURN type is `unknown` here on purpose. `Materialized<T>` is a compile-\n * time rewrite of the callback's return type, and it belongs on the public\n * `transaction()` signatures where `T` is inferred from the author's callback;\n * threading it through this driver as well would mean inferring `T` twice, from\n * two different positions, and reconciling them. The public wrappers narrow\n * once, at the seam where the value types were erased anyway.\n */\nexport async function runTxPlan<TTables>(\n transport: TxPlanTransport,\n tables: TTables,\n builder: TxPlanBuilder,\n fn: (tx: TxPlanHandle<TTables>) => unknown,\n): Promise<unknown> {\n const returned = fn({ tables });\n const body = builder.body();\n if (body.ops.length === 0) {\n return materializeResult(returned, []);\n }\n\n let response: TxPlanResponse;\n try {\n response = await transport.txPlan(body);\n } catch (err) {\n throw translateRejection(err, builder);\n }\n return materializeResult(returned, response.results);\n}\n\n/**\n * Turn the broker's rejection back into the tenant's own error.\n *\n * The server never sees the `Error` an expectation was given — only its slot\n * index — so this is the only place the intended error can be produced. A\n * rejection this SDK does not recognise passes through untouched: inventing an\n * error for it would hide the real failure.\n */\nfunction translateRejection(err: unknown, builder: TxPlanBuilder): unknown {\n if (typeof err !== \"object\" || err === null) return err;\n const rejection = err as TxPlanRejection;\n if (rejection.error_code !== \"tx_guard_failed\" || typeof rejection.slot !== \"number\") {\n return err;\n }\n return builder.errorForSlot(rejection.slot) ?? err;\n}\n","/**\n * http.ts — the transport every module client speaks over.\n *\n * WHY IT IS HERE. This code, and the five clients built on it, spent their life\n * in `v2/runtime/internal/runtime/module-clients.js`: 1,768 lines of untyped\n * CommonJS that entered the SDK through an `@ts-expect-error` and left through\n * `unknown` casts. The interfaces those clients implement were always in this\n * package — only the implementations were outside it, where nothing checked one\n * against the other. Two defects came through that gap on 2026-08-15 (a type\n * that described a different server's columns; an accessor that was `undefined`\n * in a deployed handler), and both were green on each side alone.\n *\n * WHAT IT IS NOT. Nothing Bun-specific lives here. The transport is a `fetch`\n * the caller may supply, so this package stays runtime-agnostic and the process\n * that knows which runtime it is decides what to hand in.\n */\n\nimport type { PalbaseResult } from \"../endpoint.js\";\n\n/** Per-request options a module client may pass. */\nexport interface RequestOptions {\n /** JSON-serialised unless it is a string, a Uint8Array, a Blob or FormData. */\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/**\n * What a module client is given. An INTERFACE rather than a class, because the\n * clients depend on this shape and not on the thing that implements it — which\n * is what lets a test drive a whole client without a server.\n */\nexport interface ModuleTransport {\n /** The platform's base URL, for the rare client that must build a URL. */\n readonly baseUrl: string;\n request<T = unknown>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResult<T>>;\n}\n\nexport interface TransportConfig {\n baseUrl: string;\n apiKey: string;\n /**\n * The `fetch` to use. Omitted means the ambient one — resolved at CALL time,\n * never captured here: the egress fence replaces `globalThis.fetch` after the\n * clients are built, and a captured reference would keep calling the\n * un-fenced original.\n */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * A module call that failed.\n *\n * `code` is the platform's own error code (`forbidden`, `not_found`, …) so a\n * caller can branch on it without matching message text.\n */\nexport class PalbaseModuleError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details: Record<string, unknown>;\n\n constructor(code: string, message: string, status: number, details: Record<string, unknown> = {}) {\n super(message);\n this.name = \"PalbaseModuleError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n\nexport function makeHttpClient(cfg: TransportConfig): ModuleTransport {\n async function request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<PalbaseResult<T>> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(options.headers ?? {}),\n };\n if (cfg.apiKey) headers[\"apikey\"] = cfg.apiKey;\n\n const init: RequestInit = { method, headers };\n if (options.body !== undefined) {\n if (typeof options.body === \"string\" || options.body instanceof Uint8Array) {\n init.body = options.body as RequestInit[\"body\"];\n } else if (typeof FormData !== \"undefined\" && options.body instanceof FormData) {\n // The platform writes Content-Type itself, WITH the multipart boundary.\n // Setting it here omits the boundary, and the server then parses zero\n // parts from a request that looks perfectly well formed.\n delete headers[\"Content-Type\"];\n init.body = options.body;\n } else if (typeof Blob !== \"undefined\" && options.body instanceof Blob) {\n delete headers[\"Content-Type\"];\n init.body = options.body;\n } else {\n init.body = JSON.stringify(options.body);\n }\n }\n if (options.signal) init.signal = options.signal;\n\n // Resolved HERE, per call. See TransportConfig.fetchImpl.\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n\n let response: Response;\n try {\n response = await doFetch(`${cfg.baseUrl}${path}`, init);\n } catch (err) {\n // AN ENVELOPE, not an exception.\n //\n // This threw until 2026-08-15, and the throw made three separate claims\n // false at once:\n //\n // 1. The package's own rule — \"Response: { data, error }, no thrown API\n // errors\". Every client here is written to that contract.\n // 2. `Flags.get(key, default)`, whose documented behaviour is that the\n // default applies when the flag is absent AND when the service is\n // unreachable. It reads `resp.error !== null` to decide, and a throw\n // never reaches that branch: measured, `get(\"beta\", \"DEFAULT\")`\n // raised `connect ECONNREFUSED` instead of answering \"DEFAULT\". The\n // test that was supposed to cover it handed the client a hand-made\n // error envelope — a shape this code could not produce.\n // 3. Consistency with the Realtime client, which already envelopes a\n // network failure so a handler that wrote a row does not lose it\n // because pubsub was down.\n //\n // A caller destructuring { data, error } and checking `error` was being\n // defeated by an exception: the defensive code existed and did not help,\n // which is the worst kind of surprise to leave in a package.\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"Network request failed\",\n 0,\n ),\n status: 0,\n };\n }\n\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n let parsed: unknown = null;\n if (method !== \"HEAD\" && contentType.includes(\"json\")) {\n parsed = await response.json().catch(() => null);\n } else if (method !== \"HEAD\" && contentType.startsWith(\"image/\")) {\n // QR codes and the like: hand back bytes the caller can write or forward.\n parsed = new Uint8Array(await response.arrayBuffer());\n } else if (method !== \"HEAD\" && response.body) {\n // A non-JSON error still says something; \"request failed\" says nothing.\n parsed = await response.text().catch(() => null);\n }\n\n if (!response.ok) {\n const body = (parsed && typeof parsed === \"object\" ? parsed : {}) as Record<string, unknown>;\n const code = typeof body.error === \"string\" && body.error ? body.error : \"unknown_error\";\n const message =\n (typeof body.error_description === \"string\" && body.error_description) ||\n response.statusText ||\n \"request failed\";\n return {\n data: null,\n error: new PalbaseModuleError(code, message, response.status, body),\n status: response.status,\n };\n }\n\n return { data: parsed as T, error: null, status: response.status };\n }\n\n return { baseUrl: cfg.baseUrl, request };\n}\n","/**\n * documents.ts — the Documents client, Firestore-shaped.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:705-773` (plus\n * the `buildDocumentRef` / `buildCollectionRef` helpers above it) with its\n * behaviour intact: the same methods, the same paths, the same bodies. What\n * changed is that it now sits beside the interface it implements, so a drift\n * between the two is a compile error rather than a runtime surprise.\n */\n\nimport type {\n PalbaseCollectionRef,\n PalbaseDocsClient,\n PalbaseDocumentRef,\n PalbaseDocumentSnapshot,\n PalbaseQuerySnapshot,\n PalbaseResult,\n PalbaseWhereOperator,\n} from \"../endpoint.js\";\nimport { PalbaseModuleError, type ModuleTransport } from \"./http.js\";\n\n/**\n * A path segment the platform will accept.\n *\n * Validated HERE rather than at the server, because a rejected segment is a\n * programming mistake and the useful moment to hear about it is the call.\n */\nconst SEGMENT_RE = /^[A-Za-z0-9_-]+$/;\n\nfunction validateSegment(segment: string, label: string): void {\n if (!SEGMENT_RE.test(segment)) {\n throw new Error(`Invalid ${label}: \"${segment}\". Must match ${SEGMENT_RE.source}`);\n }\n}\n\ninterface WhereClause {\n field: string;\n op: PalbaseWhereOperator;\n value: unknown;\n}\ninterface OrderClause {\n field: string;\n direction: \"asc\" | \"desc\";\n}\ninterface ChainState {\n where: WhereClause[];\n orderBy: OrderClause[];\n limit?: number;\n}\n\ninterface RawDocument {\n id?: string;\n exists?: boolean;\n data?: Record<string, unknown>;\n}\n\nfunction buildDocumentRef<T extends Record<string, unknown>>(\n http: ModuleTransport,\n path: string,\n): PalbaseDocumentRef<T> {\n return {\n path,\n async set(data: T) {\n return http.request<void>(\"PUT\", `/v1/docs/${path}`, { body: data });\n },\n async get(): Promise<PalbaseResult<PalbaseDocumentSnapshot<T>>> {\n const response = await http.request<RawDocument>(\"GET\", `/v1/docs/${path}`);\n if (response.error) return { data: null, error: response.error, status: response.status };\n const raw = response.data ?? {};\n const exists = raw.exists !== undefined ? raw.exists : Boolean(raw.data || raw.id);\n const segments = path.split(\"/\");\n const id = raw.id || segments[segments.length - 1] || \"\";\n return {\n data: { id, exists, data: () => raw.data as T | undefined, ref: { path } },\n error: null,\n status: response.status,\n };\n },\n async update(data: Partial<T>) {\n return http.request<void>(\"PATCH\", `/v1/docs/${path}`, { body: data });\n },\n async delete() {\n return http.request<void>(\"DELETE\", `/v1/docs/${path}`);\n },\n collection<C extends Record<string, unknown>>(name: string): PalbaseCollectionRef<C> {\n validateSegment(name, \"subcollection name\");\n return buildCollectionRef<C>(http, `${path}/${name}`);\n },\n };\n}\n\nfunction buildCollectionRef<T extends Record<string, unknown>>(\n http: ModuleTransport,\n path: string,\n state: ChainState = { where: [], orderBy: [] },\n): PalbaseCollectionRef<T> {\n function snapshot(doc: { id: string; data: Record<string, unknown> }): PalbaseDocumentSnapshot<T> {\n return {\n id: doc.id,\n exists: true,\n data: () => doc.data as T,\n ref: { path: `${path}/${doc.id}` },\n };\n }\n\n function querySnapshot(docs: PalbaseDocumentSnapshot<T>[]): PalbaseQuerySnapshot<T> {\n return {\n docs,\n empty: docs.length === 0,\n size: docs.length,\n docChanges: () => docs.map((doc) => ({ type: \"added\" as const, doc })),\n };\n }\n\n return {\n path,\n\n doc(id: string) {\n validateSegment(id, \"document ID\");\n return buildDocumentRef<T>(http, `${path}/${id}`);\n },\n\n async add(data: T) {\n const resp = await http.request<{ id: string }>(\"POST\", `/v1/docs/${path}`, { body: data });\n if (resp.error || !resp.data) {\n return { data: null, error: resp.error, status: resp.status };\n }\n return {\n data: buildDocumentRef<T>(http, `${path}/${resp.data.id}`),\n error: null,\n status: resp.status,\n };\n },\n\n // Each narrowing returns a NEW ref. A builder that mutated in place would\n // leak one caller's filter into a query another caller had already held.\n where(field: string, op: PalbaseWhereOperator, value: unknown) {\n return buildCollectionRef<T>(http, path, {\n ...state,\n where: [...state.where, { field, op, value }],\n });\n },\n orderBy(field: string, direction: \"asc\" | \"desc\" = \"asc\") {\n return buildCollectionRef<T>(http, path, {\n ...state,\n orderBy: [...state.orderBy, { field, direction }],\n });\n },\n limit(n: number) {\n return buildCollectionRef<T>(http, path, { ...state, limit: n });\n },\n\n async get(): Promise<PalbaseResult<PalbaseQuerySnapshot<T>>> {\n const narrowed =\n state.where.length > 0 || state.orderBy.length > 0 || state.limit !== undefined;\n\n const resp = narrowed\n ? await http.request<{ documents?: { id: string; data: Record<string, unknown> }[] }>(\n \"POST\",\n `/v1/docs/${path}/query`,\n { body: queryBody(state) },\n )\n : await http.request<{ documents?: { id: string; data: Record<string, unknown> }[] }>(\n \"GET\",\n `/v1/docs/${path}`,\n );\n\n if (resp.error) return { data: null, error: resp.error, status: resp.status };\n const docs = (resp.data?.documents ?? []).map(snapshot);\n return { data: querySnapshot(docs), error: null, status: resp.status };\n },\n };\n}\n\nfunction queryBody(state: ChainState): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (state.where.length > 0) {\n body.where = state.where.map((w) => ({ field: w.field, op: w.op, value: w.value }));\n }\n if (state.orderBy.length > 0) {\n body.orderBy = state.orderBy.map((o) => ({ field: o.field, direction: o.direction }));\n }\n if (state.limit !== undefined) body.limit = state.limit;\n return body;\n}\n\n/** The largest batch the platform accepts in one call. */\nconst MAX_BATCH = 500;\n\nexport function buildDocumentsClient(http: ModuleTransport): PalbaseDocsClient {\n return {\n /**\n * `Documents.doc(\"users/alice\")` — segments are collection/documentId PAIRS,\n * so an odd count addresses a COLLECTION and is refused. Accepting it would\n * write a document whose id happens to be a collection's name.\n */\n doc<T extends Record<string, unknown>>(path: string): PalbaseDocumentRef<T> {\n const segments = String(path)\n .split(\"/\")\n .filter((s) => s.length > 0);\n if (segments.length === 0 || segments.length % 2 !== 0) {\n throw new Error(\n `Invalid document path: \"${path}\". Expected collection/documentId pairs, got ${segments.length} segment(s).`,\n );\n }\n segments.forEach((s, i) => validateSegment(s, i % 2 === 0 ? \"collection name\" : \"document ID\"));\n return buildDocumentRef<T>(http, segments.join(\"/\"));\n },\n\n collection<T extends Record<string, unknown>>(name: string): PalbaseCollectionRef<T> {\n validateSegment(name, \"collection name\");\n return buildCollectionRef<T>(http, name);\n },\n\n async batch(operations) {\n // Refused HERE, without a request: the server would refuse it too, and\n // spending a round trip to be told so is the caller's time.\n if (operations.length > MAX_BATCH) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"batch_too_large\",\n `Batch size ${operations.length} exceeds maximum of ${MAX_BATCH}`,\n 400,\n ),\n status: 400,\n };\n }\n if (operations.length === 0) return { data: null, error: null, status: 200 };\n\n return http.request<void>(\"POST\", \"/v1/docs/batch\", {\n body: operations.map((op) => ({ op: op.op, path: op.ref.path, data: op.data })),\n });\n },\n };\n}\n","/**\n * flags.ts — feature flags, resolved for the request's own user.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:941-1164`.\n *\n * THE ONE RULE WORTH STATING: the user a flag resolves for comes from the\n * SDK's own request scope, never from anything the caller passed on the wire.\n * A handler can pass an explicit context (including an explicit `null` for a\n * deliberate anonymous read) and that wins — but the default is the person the\n * request is being served for, which is what makes `Flags.get(\"x\")` mean the\n * obvious thing inside a handler.\n *\n * Writes mirror the Database model: `setOverride` writes for the CURRENT user\n * and needs no admin power; cross-user writes live behind `asService()` so they\n * are explicit and greppable.\n */\n\nimport type {\n PalbaseBatchOverrideOperation,\n PalbaseFlagContext,\n PalbaseFlagValue,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\nconst FLAG_NAME_RE = /^[A-Za-z0-9_.-]+$/;\n\nexport interface FlagsConfig {\n /** The request's user, read from the SDK's ALS box — never from the caller. */\n getCurrentUserId: () => string | null;\n}\n\nfunction assertFlagName(flagName: string): void {\n if (!FLAG_NAME_RE.test(flagName)) {\n throw new Error(`Invalid flag name: \"${flagName}\". Flag names must match ${FLAG_NAME_RE.source}`);\n }\n}\n\n/** A truthy flag value, in the platform's own terms. */\nfunction flagEnabled(value: unknown): boolean {\n if (typeof value === \"boolean\") return value;\n return value != null && value !== 0 && value !== \"\";\n}\n\nfunction flagVariant(value: unknown): { name: string } | null {\n return typeof value === \"string\" ? { name: value } : null;\n}\n\n/**\n * A context object carries `userId`/`properties`; anything else passed in that\n * position is a DEFAULT VALUE. This is what tells `Flags.get(key, ctx)` apart\n * from `Flags.get(key, someObjectDefault)`.\n */\nfunction isContextObject(v: unknown): v is PalbaseFlagContext {\n return (\n v !== null && typeof v === \"object\" && !Array.isArray(v) && (\"userId\" in v || \"properties\" in v)\n );\n}\n\ninterface MergedSnapshot {\n values?: Record<string, PalbaseFlagValue>;\n}\n\nexport function buildFlagsClient(http: ModuleTransport, cfg: FlagsConfig): PalbaseFlagsClient {\n /**\n * The effective user for a call. An explicit `userId` in the context wins —\n * INCLUDING an explicit `null`, which is a deliberate anonymous read.\n */\n function resolveUserId(context?: PalbaseFlagContext): string | null | undefined {\n if (context && \"userId\" in context) return context.userId ?? null;\n return cfg.getCurrentUserId() || undefined;\n }\n\n function mergedPath(context?: PalbaseFlagContext): string {\n const uid = resolveUserId(context);\n return uid ? `/v1/user-flags/users/${encodeURIComponent(uid)}` : \"/v1/user-flags\";\n }\n\n function fetchMerged(context?: PalbaseFlagContext) {\n return http.request<MergedSnapshot>(\"GET\", mergedPath(context));\n }\n\n const service: PalbaseFlagsServiceClient = {\n async setOverrideForUser(userId, key, value) {\n return http.request(\n \"PUT\",\n `/v1/user-flags/users/${encodeURIComponent(userId)}/${encodeURIComponent(key)}`,\n { body: { value } },\n );\n },\n async setOverridesForUser(userId, values) {\n return http.request(\"PUT\", `/v1/user-flags/users/${encodeURIComponent(userId)}`, {\n body: { values },\n });\n },\n async clearOverrideForUser(userId, key) {\n return http.request(\n \"DELETE\",\n `/v1/user-flags/users/${encodeURIComponent(userId)}/${encodeURIComponent(key)}`,\n );\n },\n async clearAllOverridesForUser(userId) {\n return http.request(\"DELETE\", `/v1/user-flags/users/${encodeURIComponent(userId)}`);\n },\n async batchSetOverrides(operations: ReadonlyArray<PalbaseBatchOverrideOperation>) {\n // The argument is camelCase, the wire is snake_case. Mapped here so a\n // stray `userId` never reaches the server — and an explicit `user_id`, if\n // a caller already wrote one, is preserved.\n const ops = (operations ?? []).map((op) => {\n const raw = op as unknown as { userId?: string; user_id?: string; values: unknown };\n return { user_id: raw.userId ?? raw.user_id, values: raw.values };\n });\n return http.request(\"POST\", \"/v1/user-flags/batch\", { body: { operations: ops } });\n },\n };\n\n return {\n async isEnabled(flagName: string, context?: PalbaseFlagContext) {\n assertFlagName(flagName);\n const res = await fetchMerged(context);\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n return { data: flagEnabled(res.data.values?.[flagName]), error: null, status: res.status };\n },\n\n async getVariant(flagName: string, context?: PalbaseFlagContext) {\n assertFlagName(flagName);\n const res = await fetchMerged(context);\n // A missing or non-string value is a NULL variant on a successful read;\n // errors and empty bodies pass through as null too, which is why this is\n // written out rather than mapped.\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n return { data: flagVariant(res.data.values?.[flagName]), error: null, status: res.status };\n },\n\n /**\n * `get(key)` · `get(key, default)` · `get(key, default, ctx)` · `get(key, ctx)`.\n *\n * The default is substituted when the flag is ABSENT or when the flags\n * service is unreachable — a product that hides a feature because a lookup\n * timed out is behaving correctly; one that crashes is not.\n */\n async get(\n flagName: string,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n assertFlagName(flagName);\n\n let defaultValue: PalbaseFlagValue | undefined;\n let context: PalbaseFlagContext | undefined;\n let hasDefault = false;\n if (maybeContext !== undefined) {\n defaultValue = defaultOrContext as PalbaseFlagValue;\n hasDefault = true;\n context = maybeContext;\n } else if (isContextObject(defaultOrContext)) {\n context = defaultOrContext;\n } else if (defaultOrContext !== undefined) {\n defaultValue = defaultOrContext as PalbaseFlagValue;\n hasDefault = true;\n }\n\n const resp = await fetchMerged(context);\n if (resp.error !== null) {\n if (hasDefault) return { data: defaultValue ?? null, error: null, status: resp.status };\n return { data: null, error: resp.error, status: resp.status };\n }\n const values = resp.data?.values ?? {};\n const value = values[flagName];\n // An absent key on a SUCCESSFUL read is not an error.\n if (value === undefined) {\n return { data: hasDefault ? (defaultValue ?? null) : null, error: null, status: resp.status };\n }\n return { data: value, error: null, status: resp.status };\n },\n\n async getAll(context?: PalbaseFlagContext) {\n const res = await fetchMerged(context);\n if (res.error || res.data == null) return { data: null, error: res.error, status: res.status };\n const values = res.data.values ?? {};\n return {\n data: Object.keys(values).map((name) => {\n const value = values[name];\n const flag: { name: string; enabled: boolean; variant?: { name: string } } = {\n name,\n enabled: flagEnabled(value),\n };\n if (typeof value === \"string\") flag.variant = { name: value };\n return flag;\n }),\n error: null,\n status: res.status,\n };\n },\n\n /**\n * Override a flag for the CURRENT request user.\n *\n * On an anonymous request this does not silently no-op and does not write\n * for nobody: it refuses and names the call that does cross-user writes.\n */\n async setOverride(key: string, value: PalbaseFlagValue) {\n const uid = cfg.getCurrentUserId();\n if (!uid) {\n return {\n data: null,\n error: {\n message:\n \"setOverride requires a signed-in user; use Flags.asService().setOverrideForUser(userId, key, value) for cross-user writes\",\n },\n status: 400,\n };\n }\n return http.request(\n \"PUT\",\n `/v1/user-flags/users/${encodeURIComponent(uid)}/${encodeURIComponent(key)}`,\n { body: { value } },\n );\n },\n\n asService() {\n return service;\n },\n };\n}\n","/**\n * notifications.ts — push, email, SMS, verifications, inbox, preferences and\n * the two template surfaces.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:1180-1379`.\n *\n * The theme of this file is a NAME GAP: the SDK speaks camelCase and palnotify\n * speaks snake_case, and every place they meet is a place a field can be\n * dropped in silence. One of them cost a live afternoon — `email.send({ html })`\n * was forwarded verbatim, palnotify reads `html_body`, and the answer was a 400\n * about a field the caller had supplied. The mappings below are that lesson,\n * and they are now checked against the declared parameter types instead of\n * being hand-carried across a package boundary.\n */\n\nimport type {\n PalbaseEmailClient,\n PalbaseEmailTemplate,\n PalbaseEmailTemplatesClient,\n PalbaseInboxClient,\n PalbaseNotificationsClient,\n PalbasePreferencesClient,\n PalbasePushClient,\n PalbaseSMSTemplate,\n PalbaseSMSTemplatesClient,\n PalbaseSmsClient,\n PalbaseVerificationsClient,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\n/** Re-map the data of a SUCCESSFUL envelope; errors pass through untouched. */\nfunction mapEnvelope<In, Out>(res: PalbaseResult<In>, map: (data: In) => Out): PalbaseResult<Out> {\n if (res.error !== null || res.data === null || res.data === undefined) {\n return { data: null, error: res.error, status: res.status };\n }\n return { data: map(res.data), error: null, status: res.status };\n}\n\ntype Wire = Record<string, unknown>;\n\nfunction toEmailTemplate(wire: Wire): PalbaseEmailTemplate {\n const view: PalbaseEmailTemplate = {\n id: wire.id as string,\n slug: wire.slug as string,\n locale: wire.locale as string,\n subject: wire.subject as string,\n htmlBody: wire.html_body as string,\n variables: (wire.variables as string[]) ?? [],\n isDefault: wire.is_default as boolean,\n createdAt: wire.created_at as string,\n updatedAt: wire.updated_at as string,\n };\n if (wire.text_body !== undefined) view.textBody = wire.text_body as string;\n return view;\n}\n\nfunction toSmsTemplate(wire: Wire): PalbaseSMSTemplate {\n return {\n id: wire.id as string,\n slug: wire.slug as string,\n locale: wire.locale as string,\n body: wire.body as string,\n variables: (wire.variables as string[]) ?? [],\n isDefault: wire.is_default as boolean,\n createdAt: wire.created_at as string,\n updatedAt: wire.updated_at as string,\n };\n}\n\nexport function buildNotificationsClient(http: ModuleTransport): PalbaseNotificationsClient {\n const push: PalbasePushClient = {\n async send(params) {\n return http.request(\"POST\", \"/v1/notifications/push\", { body: params });\n },\n };\n\n const email: PalbaseEmailClient = {\n async send(params) {\n // `html`/`text` are what the SDK declares; palnotify reads\n // `html_body`/`text_body`. Forwarding them verbatim answered 400 about a\n // field the caller HAD supplied — live on todoapp, 2026-07-30.\n const { templateSlug, html, text, ...rest } = params;\n const body: Record<string, unknown> = { ...rest };\n if (templateSlug !== undefined) body.template_slug = templateSlug;\n if (html !== undefined) body.html_body = html;\n if (text !== undefined) body.text_body = text;\n return http.request(\"POST\", \"/v1/notifications/email\", { body });\n },\n };\n\n const sms: PalbaseSmsClient = {\n async send(params) {\n const { templateSlug, ...rest } = params;\n const body = templateSlug !== undefined ? { ...rest, template_slug: templateSlug } : rest;\n return http.request(\"POST\", \"/v1/notifications/sms\", { body });\n },\n };\n\n // Phone verification (OTP). Separate from sms.send on purpose: there is no\n // body here — the provider generates the code and the message text itself.\n const verifications: PalbaseVerificationsClient = {\n async start(params) {\n return http.request(\"POST\", \"/v1/notifications/verifications\", { body: params });\n },\n async check(params) {\n return http.request(\"POST\", \"/v1/notifications/verifications/check\", { body: params });\n },\n };\n\n const inbox: PalbaseInboxClient = {\n async send(params) {\n return http.request(\"POST\", \"/v1/notifications/inbox\", { body: params });\n },\n async list(options?: {\n cursor?: string;\n limit?: number;\n is_read?: boolean;\n category?: string;\n include_archived?: boolean;\n }) {\n const opts = options ?? {};\n const params = new URLSearchParams();\n if (opts.cursor) params.set(\"cursor\", opts.cursor);\n if (opts.limit !== undefined) params.set(\"limit\", String(opts.limit));\n if (opts.is_read !== undefined) params.set(\"is_read\", opts.is_read ? \"true\" : \"false\");\n if (opts.category) params.set(\"category\", opts.category);\n if (opts.include_archived) params.set(\"include_archived\", \"true\");\n const query = params.toString();\n return http.request(\"GET\", `/v1/notifications/inbox${query ? `?${query}` : \"\"}`);\n },\n async unreadCount() {\n return http.request(\"GET\", \"/v1/notifications/inbox/unread-count\");\n },\n async markRead(id: string) {\n return http.request(\"PATCH\", `/v1/notifications/inbox/${encodeURIComponent(id)}/read`);\n },\n async markAllRead() {\n return http.request(\"POST\", \"/v1/notifications/inbox/read-all\");\n },\n async archive(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/inbox/${encodeURIComponent(id)}`);\n },\n };\n\n const preferences: PalbasePreferencesClient = {\n async get() {\n return http.request(\"GET\", \"/v1/notifications/preferences\");\n },\n async update(params) {\n return http.request(\"PUT\", \"/v1/notifications/preferences\", { body: params });\n },\n };\n\n const emailTemplates: PalbaseEmailTemplatesClient = {\n async list() {\n const resp = await http.request<Wire[]>(\"GET\", \"/v1/notifications/templates\");\n return mapEnvelope(resp, (rows) => (rows ?? []).map(toEmailTemplate));\n },\n async get(id: string) {\n const resp = await http.request<Wire>(\n \"GET\",\n `/v1/notifications/templates/${encodeURIComponent(id)}`,\n );\n return mapEnvelope(resp, toEmailTemplate);\n },\n async create(input: { slug: string; subject: string; htmlBody: string; textBody?: string; variables?: string[] }) {\n const body: Record<string, unknown> = {\n slug: input.slug,\n subject: input.subject,\n html_body: input.htmlBody,\n };\n if (input.textBody !== undefined) body.text_body = input.textBody;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\"POST\", \"/v1/notifications/templates\", { body });\n return mapEnvelope(resp, toEmailTemplate);\n },\n async update(\n id: string,\n input: { subject?: string; htmlBody?: string; textBody?: string; variables?: string[] },\n ) {\n const body: Record<string, unknown> = {};\n if (input.subject !== undefined) body.subject = input.subject;\n if (input.htmlBody !== undefined) body.html_body = input.htmlBody;\n if (input.textBody !== undefined) body.text_body = input.textBody;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\n \"PUT\",\n `/v1/notifications/templates/${encodeURIComponent(id)}`,\n { body },\n );\n return mapEnvelope(resp, toEmailTemplate);\n },\n async delete(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/templates/${encodeURIComponent(id)}`);\n },\n };\n\n const smsTemplates: PalbaseSMSTemplatesClient = {\n async list() {\n const resp = await http.request<Wire[]>(\"GET\", \"/v1/notifications/sms-templates\");\n return mapEnvelope(resp, (rows) => (rows ?? []).map(toSmsTemplate));\n },\n async get(id: string) {\n const resp = await http.request<Wire>(\n \"GET\",\n `/v1/notifications/sms-templates/${encodeURIComponent(id)}`,\n );\n return mapEnvelope(resp, toSmsTemplate);\n },\n async create(input: { slug: string; body: string; variables?: string[] }) {\n const body: Record<string, unknown> = { slug: input.slug, body: input.body };\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\"POST\", \"/v1/notifications/sms-templates\", { body });\n return mapEnvelope(resp, toSmsTemplate);\n },\n async update(id: string, input: { body?: string; variables?: string[] }) {\n const body: Record<string, unknown> = {};\n if (input.body !== undefined) body.body = input.body;\n if (input.variables !== undefined) body.variables = input.variables;\n const resp = await http.request<Wire>(\n \"PUT\",\n `/v1/notifications/sms-templates/${encodeURIComponent(id)}`,\n { body },\n );\n return mapEnvelope(resp, toSmsTemplate);\n },\n async delete(id: string) {\n return http.request(\"DELETE\", `/v1/notifications/sms-templates/${encodeURIComponent(id)}`);\n },\n };\n\n return {\n push,\n email,\n sms,\n verifications,\n inbox,\n preferences,\n templates: { email: emailTemplates, sms: smsTemplates },\n async registerDevice(params) {\n return http.request(\"POST\", \"/v1/notifications/devices\", { body: params });\n },\n async unregisterDevice(deviceId: string) {\n return http.request(\"DELETE\", `/v1/notifications/devices/${encodeURIComponent(deviceId)}`);\n },\n };\n}\n","/**\n * realtime.ts — broadcast, and only broadcast.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:811-883`.\n *\n * There is no `subscribe()` here, deliberately: a backend handler answers one\n * request and ends, so there is no honest place to hold a long-lived socket.\n * Subscription lives in the client SDKs; this side pushes.\n *\n * The V1 host/executor branch is GONE. It existed so an isolate could delegate\n * the secret-bearing token mint to a host that held the credential — and the\n * isolate was removed on 2026-08-14. A single-tenant process has nobody to hide\n * its own tenant's key from.\n */\n\nimport { createHmac } from \"node:crypto\";\n\nimport type { PalbaseRealtimeClient } from \"../clients.js\";\nimport { PalbaseModuleError } from \"./http.js\";\n\nexport interface RealtimeConfig {\n baseUrl: string;\n /**\n * The shared Realtime API secret. Empty means realtime is not provisioned for\n * this environment, and broadcast says so by name rather than failing oddly.\n */\n apiJwtSecret: string;\n /** Resolved at CALL time — see the note in http.ts. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * A short-lived HS256 token Realtime's broadcast pipeline accepts.\n *\n * It needs a valid signature and a future `exp`, nothing more — this is a\n * service-to-service hop inside the stack, not a user session.\n */\nfunction mintToken(secret: string): string {\n const now = Math.floor(Date.now() / 1000);\n const header = Buffer.from(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" })).toString(\"base64url\");\n const payload = Buffer.from(\n JSON.stringify({ iss: \"backend-runtime\", role: \"service_role\", iat: now, exp: now + 60 }),\n ).toString(\"base64url\");\n const sig = createHmac(\"sha256\", secret).update(`${header}.${payload}`).digest(\"base64url\");\n return `${header}.${payload}.${sig}`;\n}\n\nexport function buildRealtimeClient(cfg: RealtimeConfig): PalbaseRealtimeClient {\n const url = `${cfg.baseUrl}/realtime/api/broadcast`;\n const stateUrl = `${cfg.baseUrl}/realtime/api/state`;\n\n /** One state write or clear. Same credential, same fire-and-forget contract\n * as broadcast: a handler that wrote a row must not lose it because the\n * pubsub layer was unreachable. */\n async function writeState(\n topic: string,\n key: string,\n value: Record<string, unknown> | undefined,\n del: boolean,\n ) {\n if (typeof topic !== \"string\" || topic.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"topic must be a non-empty string\", 400),\n };\n }\n if (typeof key !== \"string\" || key.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"key must be a non-empty string\", 400),\n };\n }\n if (!cfg.apiJwtSecret) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_unconfigured\",\n \"Realtime.state is unavailable: realtime is not provisioned for this Environment \" +\n \"(PALBASE_REALTIME_API_JWT_SECRET unset).\",\n 503,\n ),\n };\n }\n\n let token: string;\n try {\n token = mintToken(cfg.apiJwtSecret);\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_token_error\",\n err instanceof Error ? err.message : \"token mint failed\",\n 500,\n ),\n };\n }\n\n const op = del ? { topic, key, del: true } : { topic, key, value: value ?? {} };\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n let response: Response;\n try {\n response = await doFetch(stateUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${token}` },\n body: JSON.stringify({ ops: [op] }),\n });\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"state request failed\",\n 0,\n ),\n };\n }\n if (response.status === 202 || response.status === 200) {\n return { data: undefined, error: null };\n }\n const detail = await response.text().catch(() => \"\");\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_state_failed\",\n `realtime state write returned ${response.status}${detail ? `: ${detail}` : \"\"}`,\n response.status,\n ),\n };\n }\n\n return {\n state: {\n /** Write one DURABLE entry on a channel's shared state.\n *\n * The difference from broadcast is WHO it reaches: a broadcast reaches\n * whoever is listening at that instant, while state is also handed to\n * whoever joins afterwards. \"This value is now X\" wants the second — a\n * client connecting a second later should not have to wait for the next\n * change to learn X. */\n set: (topic: string, key: string, value: Record<string, unknown>) =>\n writeState(topic, key, value, false),\n /** Remove one entry. */\n clear: (topic: string, key: string) => writeState(topic, key, undefined, true),\n },\n\n async broadcast(channel: string, event: string, payload?: Record<string, unknown>) {\n // Cheap argument checks first, locally: a bad call gets an answer without\n // spending a round trip to be told the obvious.\n if (typeof channel !== \"string\" || channel.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"channel must be a non-empty string\", 400),\n };\n }\n if (typeof event !== \"string\" || event.length === 0) {\n return {\n data: null,\n error: new PalbaseModuleError(\"invalid_argument\", \"event must be a non-empty string\", 400),\n };\n }\n if (!cfg.apiJwtSecret) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_unconfigured\",\n \"Realtime.broadcast is unavailable: realtime is not provisioned for this Environment \" +\n \"(PALBASE_REALTIME_API_JWT_SECRET unset).\",\n 503,\n ),\n };\n }\n\n let token: string;\n try {\n token = mintToken(cfg.apiJwtSecret);\n } catch (err) {\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_token_error\",\n err instanceof Error ? err.message : \"token mint failed\",\n 500,\n ),\n };\n }\n\n // The BARE sub-topic. Realtime prepends \"realtime:\" on delivery, and a\n // pre-prefixed topic double-prefixes and is silently dropped — proven live.\n const body = JSON.stringify({\n messages: [{ topic: channel, event, payload: payload ?? {}, private: false }],\n });\n\n const doFetch = cfg.fetchImpl ?? globalThis.fetch;\n let response: Response;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${token}` },\n body,\n });\n } catch (err) {\n // FIRE AND FORGET: a handler that wrote a row and then broadcast must\n // not lose the row because the pubsub layer was unreachable. This is the\n // one client that answers with an envelope on a network failure rather\n // than throwing, and it is why.\n return {\n data: null,\n error: new PalbaseModuleError(\n \"network_error\",\n err instanceof Error ? err.message : \"broadcast request failed\",\n 0,\n ),\n };\n }\n\n if (response.status === 202 || response.status === 200) {\n return { data: undefined, error: null };\n }\n\n const detail = await response.text().catch(() => \"\");\n return {\n data: null,\n error: new PalbaseModuleError(\n \"realtime_broadcast_failed\",\n `broadcast returned ${response.status}: ${detail.slice(0, 200)}`,\n response.status,\n ),\n };\n },\n };\n}\n","/**\n * storage.ts — the Storage client.\n *\n * Moved in from `v2/runtime/internal/runtime/module-clients.js:474-589`. That\n * code addressed the native Supabase Storage wire under `/storage/v1` until\n * 2026-08-15, when it was repointed at this stack's own module — measured\n * against the live stack, where the old path answers 404 and the new one 200.\n * It arrives here so the SHAPE it returns and the type that declares that shape\n * are checked against each other: they were not, and the type spent a major\n * version describing another server's columns.\n */\n\nimport type {\n PalbaseBucketClient,\n PalbaseFileObject,\n PalbaseListOptions,\n PalbaseSignedUrlResponse,\n PalbaseStorageClient,\n PalbaseUploadOptions,\n} from \"../clients.js\";\nimport type { PalbaseResult } from \"../endpoint.js\";\nimport type { ModuleTransport } from \"./http.js\";\n\n/** What the platform accepts as a bucket name (schema: `^[a-z][a-z0-9-]{1,62}$`). */\nconst BUCKET_NAME_RE = /^[a-zA-Z0-9_-]+$/;\n/** What the platform accepts as an object path. */\nconst STORAGE_PATH_RE = /^[a-zA-Z0-9_./-]+$/;\nconst STORAGE_TRAVERSAL_RE = /(?:^|\\/)\\.\\.(?:\\/|$)/;\n\n/**\n * Refused HERE, before any request.\n *\n * A traversing path is a programming mistake, and the useful moment to hear\n * about it is the call that made it — not a 400 three layers away.\n */\nfunction validateStoragePath(p: string): void {\n if (!STORAGE_PATH_RE.test(p) || STORAGE_TRAVERSAL_RE.test(p)) {\n throw new Error(\n `Invalid file path: \"${p}\". Paths must not contain traversal sequences and must match ${STORAGE_PATH_RE.source}`,\n );\n }\n}\n\n/**\n * The wire's own shape, mapped onto what this package declares.\n *\n * v2's storage answers in camelCase with the variants and the thumbhash already\n * in it, so this maps rather than translates. The snake_case unwrapping that\n * used to live here (`metadata.mimetype`, `bucket_id`, `created_at`) belonged to\n * a different server, and reading those names off this wire produced an object\n * whose size was 0 and whose content type was \"\".\n */\nfunction toFileObject(bucket: string, row: Record<string, unknown>): PalbaseFileObject {\n return {\n name: (row.path as string) ?? \"\",\n path: (row.path as string) ?? \"\",\n bucket: (row.bucket as string) ?? bucket,\n size: typeof row.size === \"number\" ? row.size : 0,\n contentType: (row.contentType as string) ?? \"\",\n checksum: (row.checksum as string) ?? \"\",\n width: row.width as number | undefined,\n height: row.height as number | undefined,\n thumbhash: row.thumbhash as string | undefined,\n variants: (row.variants as Record<string, string>) ?? {},\n };\n}\n\n/** Re-map the data of a SUCCESSFUL envelope; pass errors through untouched. */\nfunction mapResponse<In, Out>(\n res: PalbaseResult<In>,\n map: (data: In) => Out,\n): PalbaseResult<Out> {\n if (res.error || res.data === null || res.data === undefined) {\n return { data: null, error: res.error, status: res.status };\n }\n return { data: map(res.data), error: null, status: res.status };\n}\n\nfunction buildBucketClient(\n http: ModuleTransport,\n bucketName: string,\n publicOrigin: string,\n): PalbaseBucketClient {\n const objectPath = (path: string) => `/v1/storage/object/${bucketName}/${path}`;\n\n return {\n async upload(path, file, options?: PalbaseUploadOptions) {\n validateStoragePath(path);\n const headers: Record<string, string> = {\n \"Content-Type\": options?.contentType ?? \"application/octet-stream\",\n };\n if (options?.upsert) headers[\"x-upsert\"] = \"true\";\n // The BYTES, as the body. Storage sniffs the content and decides for\n // itself what this is; the declared type is a hint it may overrule,\n // because a name and a header are both things a caller can be wrong about.\n const body = file instanceof ArrayBuffer ? new Uint8Array(file) : file;\n const res = await http.request<Record<string, unknown>>(\"PUT\", objectPath(path), {\n body,\n headers,\n });\n return mapResponse(res, (r) => toFileObject(bucketName, r ?? {}));\n },\n\n async download(path) {\n validateStoragePath(path);\n // The AUTHENTICATED read: the project already holds a credential this\n // stack verified, so it does not have to mint a signature to open its own\n // object — and this route serves private buckets, which the public one\n // refuses on purpose.\n return http.request<Blob>(\"GET\", objectPath(path), { headers: { Accept: \"*/*\" } });\n },\n\n getPublicUrl(path, options) {\n validateStoragePath(path);\n const variant = options?.variant ? `?variant=${encodeURIComponent(options.variant)}` : \"\";\n // ABSOLUTE — and the origin is a value the stack is TOLD, not the\n // transport's baseUrl.\n //\n // Those are two different addresses and conflating them is how this broke\n // once already: the transport points at palsvc over the loopback\n // (`http://127.0.0.1:8080`), and a URL built from it resolves nowhere\n // outside the pod. So this used to return the path alone.\n //\n // The path alone is not a smaller answer, it is a wrong one. A public URL\n // LEAVES the response body — into an <img>, an email, another app on\n // another host — and none of those have a base to resolve it against.\n // Measured live 24.08.2026: an iOS client handed the returned\n // `/v1/files/post-images/…` straight to URLSession and got\n // NSURLErrorUnsupportedURL (-1002). The upload had worked; only the URL\n // was unusable.\n //\n // `PALBASE_PUBLIC_ORIGIN` is set by whoever publishes the stack, because\n // only they know it: in the cloud the operator writes\n // `https://<ref>.<domain>`, and a self-hosted stack carries whatever\n // domain its certificate is for.\n if (!publicOrigin) {\n // NAMED, not silent — the same doctrine as the other unconfigured\n // modules in engine/config.ts (\"throw a named error on first use rather\n // than silently no-op\"). A returned path would pass every test here and\n // fail in the one place nobody is watching.\n throw new Error(\n `Storage.bucket(\"${bucketName}\").getPublicUrl() needs this stack's public origin, ` +\n \"and it was not configured. Set PALBASE_PUBLIC_ORIGIN to the address clients reach \" +\n \"this stack at (e.g. https://myproject.palbase.studio).\",\n );\n }\n return `${publicOrigin}/v1/files/${bucketName}/${path}${variant}`;\n },\n\n async createSignedUrl(path, options): Promise<PalbaseResult<PalbaseSignedUrlResponse>> {\n validateStoragePath(path);\n // A DURATION — `{ expiresIn: \"1h\" }`. A bare number is ambiguous between\n // seconds and minutes at every call site that reads it, and the ambiguity\n // is only discovered when a link outlives the object it opened.\n return http.request<PalbaseSignedUrlResponse>(\"POST\", `/v1/storage/sign/${bucketName}/${path}`, {\n body: { expiresIn: options.expiresIn },\n });\n },\n\n async list(prefix?: string, options?: PalbaseListOptions) {\n if (prefix) validateStoragePath(prefix);\n const params = new URLSearchParams();\n if (prefix) params.set(\"prefix\", prefix);\n if (options?.limit !== undefined) params.set(\"limit\", String(options.limit));\n const query = params.toString();\n const res = await http.request<{ objects?: Record<string, unknown>[] }>(\n \"GET\",\n `/v1/storage/bucket/${bucketName}${query ? `?${query}` : \"\"}`,\n );\n // `{objects: [...]}`, not a bare array: the envelope leaves room for the\n // paging this will grow, and unwrapping it here keeps that off callers.\n return mapResponse(res, (body) => (body?.objects ?? []).map((row) => toFileObject(bucketName, row)));\n },\n\n async remove(paths) {\n for (const p of paths) validateStoragePath(p);\n // One request per object: the module deletes an object WITH its variants,\n // and a batch endpoint reporting partial success would need a result shape\n // nobody would read. The first refusal ends it — continuing would report a\n // partial delete as a whole one.\n const removed: PalbaseFileObject[] = [];\n for (const p of paths) {\n const res = await http.request<void>(\"DELETE\", objectPath(p));\n if (res.error) return { data: null, error: res.error, status: res.status };\n removed.push(toFileObject(bucketName, { path: p }));\n }\n return { data: removed, error: null, status: 200 };\n },\n\n async move(from, to) {\n validateStoragePath(from);\n validateStoragePath(to);\n return http.request<void>(\"POST\", `/v1/storage/move/${bucketName}`, { body: { from, to } });\n },\n\n async copy(from, to) {\n validateStoragePath(from);\n validateStoragePath(to);\n return http.request<void>(\"POST\", `/v1/storage/copy/${bucketName}`, { body: { from, to } });\n },\n };\n}\n\n/**\n * @param publicOrigin the address CLIENTS reach this stack at — never the\n * transport's base, which is this process's internal route to palsvc. Empty\n * means it was not configured, and `getPublicUrl` refuses by name.\n */\nexport function buildStorageClient(\n http: ModuleTransport,\n publicOrigin: string,\n): PalbaseStorageClient {\n return {\n bucket(name: string) {\n if (!BUCKET_NAME_RE.test(name)) {\n throw new Error(`Invalid bucket name: \"${name}\". Bucket names must match ${BUCKET_NAME_RE.source}`);\n }\n // Sondaki eğik çizgi BURADA kırpılır: `${origin}/v1/files/...` iki\n // eğik çizgiyle biten bir yol üretirdi ve bazı sunucular onu ayrı bir\n // nesne sayar.\n return buildBucketClient(http, name, publicOrigin.replace(/\\/+$/, \"\"));\n },\n };\n}\n","/**\n * clients/index.ts — the composition root for the module clients.\n *\n * This is what the process calls once at boot. It builds the five clients the\n * engine injects and nothing else.\n *\n * WHAT IS NOT BUILT HERE, and why each one is absent rather than forgotten:\n *\n * - `auth`, `functions`, `analytics`, `links` — the SDK exports no singleton\n * for any of them (`runtime.ts` exports ten, and these four are not among\n * them), so no handler could reach them. They were constructed on every\n * boot and thrown away.\n * - `Purchases` — its client talked to palstore, and v2 contains no palstore\n * at all. The surface was unbacked before it was untyped. Dropped from v2\n * by the user's decision on 2026-08-15, with the SDK's `src/purchases/`\n * tree left in place because that decision was \"deferred, not silently\n * taken\". It is taken now: the tree is GONE (2026-08-29), because a\n * decorator standing in front of a service nothing serves is the same\n * defect as `Resource` and `config/*`, which went with it.\n * - The V1 host/executor transport — the isolate it existed for was removed\n * on 2026-08-14. A single-tenant process has nobody to hide its own\n * tenant's credentials from.\n */\n\nimport type { ModuleClients } from \"../engine/index.js\";\nimport { buildDocumentsClient } from \"./documents.js\";\nimport { buildFlagsClient } from \"./flags.js\";\nimport { makeHttpClient } from \"./http.js\";\nimport { buildNotificationsClient } from \"./notifications.js\";\nimport { buildRealtimeClient } from \"./realtime.js\";\nimport { buildStorageClient } from \"./storage.js\";\n\nexport interface ModuleClientsConfig {\n /** Where the platform answers. Empty means \"not configured\" — see below. */\n baseUrl: string;\n /** The publishable key. Used only when no service-role key is supplied. */\n apiKey: string;\n /**\n * The service-role key, which is what a backend actually holds. Preferred\n * over `apiKey`: this process IS the project's server.\n */\n serviceRoleKey: string;\n /** The shared Realtime secret. Empty means realtime is not provisioned. */\n realtimeApiJwtSecret: string;\n /**\n * The address CLIENTS reach this stack at. Used ONLY to build public object\n * URLs; every request this bundle makes still goes over `baseUrl`.\n */\n publicOrigin: string;\n /** The request's user, read from the SDK's own scope — never from a caller. */\n getCurrentUserId: () => string | null;\n /** Injected in tests; resolved at call time in production. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Build the module clients.\n *\n * Returns an EMPTY bundle when there is no base URL, deliberately: the engine\n * then injects its named stubs, so a handler that reaches for `Storage` gets an\n * error saying which module is unconfigured rather than a crash reading a\n * property of undefined. Booting is not blocked — a project that never touches\n * a module runs fine without one.\n */\nexport function buildModuleClients(cfg: ModuleClientsConfig): ModuleClients {\n const baseUrl = (cfg.baseUrl || \"\").replace(/\\/+$/, \"\");\n if (!baseUrl) return {};\n\n // The service-role key when present: this process is the project's own\n // server, and the publishable key would refuse half of what it needs.\n const apiKey = cfg.serviceRoleKey || cfg.apiKey || \"\";\n const http = makeHttpClient({ baseUrl, apiKey, fetchImpl: cfg.fetchImpl });\n\n return {\n Documents: buildDocumentsClient(http),\n Storage: buildStorageClient(http, cfg.publicOrigin),\n Notifications: buildNotificationsClient(http),\n Flags: buildFlagsClient(http, { getCurrentUserId: cfg.getCurrentUserId }),\n Realtime: buildRealtimeClient({\n baseUrl,\n apiJwtSecret: cfg.realtimeApiJwtSecret,\n fetchImpl: cfg.fetchImpl,\n }),\n };\n}\n","// The wire shape of a declared schema — what the deploy reads.\n//\n// `defineSchema(...)` produces a value full of builders and phantom types, which\n// is the right shape for authoring and the wrong shape for anything outside this\n// process. The deploy is Go: it introspects the live database, diffs it against\n// the declaration, and applies the difference. So the declaration has to leave\n// TypeScript as data, and this file is where that happens.\n//\n// It lives in the SDK because the SDK owns the DSL. The alternative — a script\n// beside the deploy that reaches into `._def` — is a second reading of a private\n// shape, and it drifts the moment a column gains a property: the DSL keeps\n// working, the emitter silently omits it, and the database is missing something\n// nobody can see in the source.\n//\n// The field names below are a CONTRACT with Go's `schema.SchemaJSON`. Renaming\n// one here without renaming it there produces a declaration that parses to\n// something emptier than it was — the failure mode being a column, a policy, or\n// a whole table that quietly never gets created.\nimport type { ColumnBuilder, ColumnDef } from \"./columns.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { MemoryDecl, SchemaDef, SearchDecl, TableDef } from \"./schema.js\";\n\n/** One column, flattened. Mirrors Go's `schema.ColumnJSON`. */\nexport interface ColumnJSON {\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n renamedFrom?: string;\n /** See Go's `schema.ColumnJSON.Ignored` — the contraction gate's only signal. */\n ignored?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: string;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n dimensions?: number;\n}\n\n/** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */\nexport interface PolicyJSON {\n name: string;\n command: string;\n roles: string[];\n using: string | null;\n withCheck: string | null;\n permissive: boolean;\n}\n\n/** One table. Mirrors Go's `schema.TableJSON`. */\nexport interface TableJSON {\n /**\n * The schema this table lives in. `public` unless declared otherwise.\n *\n * The table carries it because the diff iterates over KEYS but passes the\n * VALUE around: a bare name inside a qualified key space writes the migration\n * into the wrong schema, silently.\n */\n schema: string;\n name: string;\n columns: Record<string, ColumnJSON>;\n rls: boolean;\n policies: PolicyJSON[];\n primaryKey?: string[];\n uniqueConstraints?: { name: string; columns: string[] }[];\n rawConstraints?: { name: string; up: string; down: string | null }[];\n checks?: { name: string; expr: string }[];\n indexes?: { name: string; columns: string[] }[];\n search?: SearchJSON;\n memory?: MemoryJSON;\n}\n\n/** C-11 wire şekli — Go'nun MemoryJSON'ıyla alan-adı sözleşmesi (D-019).\n * Beyansız tablolarda alan OMIT — eski şemalar bayt-aynı (NFR-B1). */\nexport interface MemoryJSON {\n from: string[];\n into: string;\n subject?: string;\n extract: { provider: string; model: string };\n}\n\n/** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */\nexport interface SchemaJSON {\n tables: Record<string, TableJSON>;\n extensions: string[];\n /**\n * Every declared schema, with its HTTP reachability.\n *\n * The flag has nowhere else to live: `/v1/db` must know which schemas are\n * reachable, and introspection must know which schemas the project DECLARED —\n * a live database also contains internal module schemas that are none of the\n * diff's business.\n */\n schemas: SchemaMetaJSON[];\n}\n\nexport interface SchemaMetaJSON {\n name: string;\n exposed: boolean;\n}\n\n/** The definition behind a column, whichever side of the builder it arrives on. */\nfunction defOf(column: ColumnBuilder | ColumnDef): ColumnDef {\n return \"_def\" in column ? column._def : column;\n}\n\nfunction columnToJSON(column: ColumnBuilder | ColumnDef): ColumnJSON {\n const def = defOf(column);\n const out: ColumnJSON = {\n type: def.type,\n nullable: def.nullable,\n primaryKey: def.primaryKey,\n };\n // Every optional field is omitted rather than emitted as undefined: Go\n // distinguishes \"absent\" from \"present and empty\" on several of these, and a\n // `defaultValue: null` is a real default that says NULL.\n if (def.defaultValue !== undefined) out.defaultValue = def.defaultValue;\n if (def.defaultRandom === true) out.defaultRandom = true;\n if (def.defaultNow === true) out.defaultNow = true;\n if (def.renamedFrom !== undefined) out.renamedFrom = def.renamedFrom;\n // Go'daki schema.ColumnJSON'un aynası. `omitempty` karşılığı: yalnız TRUE ise yazılır,\n // böylece işaretsiz bir şemanın JSON'u bu alandan önceki hâliyle byte-eş kalır.\n if (def.ignored === true) out.ignored = true;\n if (def.references !== undefined) {\n out.references = { table: def.references.table, column: def.references.column };\n }\n if (def.onDeleteAction !== undefined) out.onDeleteAction = def.onDeleteAction;\n if (def.enumName !== undefined) out.enumName = def.enumName;\n if (def.enumValues !== undefined) out.enumValues = [...def.enumValues];\n if (def.unique === true) out.unique = true;\n if (def.dimensions !== undefined) out.dimensions = def.dimensions;\n return out;\n}\n\nfunction policyToJSON(policy: PolicyDef): PolicyJSON {\n return {\n name: policy.name,\n command: policy.command ?? \"all\",\n roles: policy.roles ? [...policy.roles] : [],\n // null rather than omitted: a policy with no USING clause is a different\n // thing from one whose clause the emitter forgot, and Go reads the\n // difference.\n using: policy.using ?? null,\n withCheck: policy.withCheck ?? null,\n permissive: policy.permissive !== false,\n };\n}\n\n/** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5).\n * `mode`/`chunks` yalnız yeni-biçim chunk-modunda emit edilir (D-010);\n * satır-modu ve eski biçim bayt-aynı kalır (NFR-B1). */\nexport interface SearchJSON {\n text?: { columns: string[] };\n vector?: {\n column?: string;\n metric: string;\n embed?: { provider: string; model: string; from: string[]; apiKeyName?: string; dimensions?: number; baseURL?: string };\n staleness?: \"null\" | \"keep\";\n mode?: \"row\" | \"chunks\";\n chunks?: { sizeChars?: number; overlapChars?: number };\n }[];\n /** FR-026: sorgu-yeniden-yazımı haritası — beyan yoksa OMIT (NFR-B1). */\n synonyms?: Record<string, string[]>;\n /** C-1: sonuç yeniden-sıralama beyanı — beyan yoksa OMIT. */\n /** FR-029: geçerlilik türevleri — beyan yoksa OMIT. */\n validity?: boolean;\n}\n\n/** T020 (C-1): iki biçimin de üst-düzey ortak alanları — beyan yoksa OMIT,\n * boş synonyms haritası da OMIT (NFR-B1 baytları kımıldamaz). */\nfunction commonSearchFields(search: SearchDecl, out: SearchJSON): void {\n if (search.synonyms !== undefined && Object.keys(search.synonyms).length > 0) {\n out.synonyms = Object.fromEntries(\n Object.entries(search.synonyms).map(([word, alts]) => [word, [...alts]]),\n );\n }\n if (search.validity === true) out.validity = true;\n}\n\n/** Beyanı normalize eder: vector her zaman DİZİ, metric her zaman dolu (vars. cosine),\n * authoring'deki `from`/`model` wire'da `embed` altında toplanır. Alan yoksa OMIT —\n * search'süz şema bayt-aynı kalır (NFR-006). */\nfunction searchToJSON(search: SearchDecl, vectorColumn: string | undefined): SearchJSON {\n if (search.from !== undefined && search.model !== undefined) {\n // YENİ biçim (D-007): from tek listedir — FTS'i de embed'i de besler.\n // Mod ŞEMADAN türer (D-010): tabloda vector kolonu varsa satır-modu\n // (column yazılır, mode OMIT — eski davranışla aynı wire), yoksa\n // chunk-modu (mode:\"chunks\", column yok — vektörler türev tabloda).\n const out: SearchJSON = {};\n const textCols =\n search.text === false ? undefined : Array.isArray(search.text) && search.text.length > 0 ? search.text : search.from;\n if (textCols !== undefined) out.text = { columns: [...textCols] };\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: search.metric ?? \"cosine\" };\n if (vectorColumn !== undefined) v.column = vectorColumn;\n v.embed = {\n provider: search.model.provider,\n model: search.model.model,\n from: [...search.from],\n ...(search.model.apiKeyName !== undefined ? { apiKeyName: search.model.apiKeyName } : {}),\n ...(search.model.dimensions !== undefined ? { dimensions: search.model.dimensions } : {}),\n ...(search.model.baseURL !== undefined ? { baseURL: search.model.baseURL } : {}),\n };\n if (search.staleness !== undefined) v.staleness = search.staleness;\n if (vectorColumn === undefined) {\n v.mode = \"chunks\";\n if (search.chunks !== undefined) {\n const c: NonNullable<typeof v.chunks> = {};\n if (search.chunks.size !== undefined && search.chunks.size > 0) c.sizeChars = search.chunks.size;\n if (search.chunks.overlap !== undefined && search.chunks.overlap > 0) c.overlapChars = search.chunks.overlap;\n if (Object.keys(c).length > 0) v.chunks = c;\n }\n }\n out.vector = [v];\n commonSearchFields(search, out);\n return out;\n }\n const out: SearchJSON = {};\n // Eski biçimde text yalnız dizi olabilir (boolean'ı defineSchema zaten\n // reddediyor); Array.isArray hem tipi daraltır hem o sözleşmeyi belgeler.\n if (Array.isArray(search.text) && search.text.length > 0) out.text = { columns: [...search.text] };\n const legs = search.vector === undefined ? []\n : Array.isArray(search.vector) ? search.vector : [search.vector];\n if (legs.length > 0) {\n out.vector = legs.map((leg) => {\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: leg.metric ?? \"cosine\" };\n if (leg.column !== undefined) v.column = leg.column;\n if (leg.staleness !== undefined) v.staleness = leg.staleness;\n if (leg.model !== undefined) {\n v.embed = {\n provider: leg.model.provider,\n model: leg.model.model,\n from: [...(leg.from ?? [])],\n ...(leg.model.apiKeyName !== undefined ? { apiKeyName: leg.model.apiKeyName } : {}),\n ...(leg.model.dimensions !== undefined ? { dimensions: leg.model.dimensions } : {}),\n ...(leg.model.baseURL !== undefined ? { baseURL: leg.model.baseURL } : {}),\n };\n }\n return v;\n });\n }\n commonSearchFields(search, out);\n return out;\n}\n\nfunction memoryToJSON(m: MemoryDecl): MemoryJSON {\n return {\n from: [...m.from],\n into: m.into,\n ...(m.subject !== undefined ? { subject: m.subject } : {}),\n extract: { provider: m.extract.provider, model: m.extract.model },\n };\n}\n\nfunction tableToJSON(table: TableDef, schemaName: string): TableJSON {\n const columns: Record<string, ColumnJSON> = {};\n for (const [name, column] of Object.entries(table.columns)) {\n columns[name] = columnToJSON(column);\n }\n\n const out: TableJSON = {\n name: table.name,\n schema: schemaName,\n columns,\n // Read, not re-derived. `defineSchema` already resolves the fail-closed\n // default (RLS on unless the author wrote `rls: false`, and forced on by any\n // policy), and a second copy of a SECURITY default is exactly the thing that\n // drifts — the direction it drifted last time was \"expose everything\", and\n // the live proof was one user reading another's rows.\n rls: table.rls,\n policies: (table.policies ?? []).map(policyToJSON),\n };\n\n if (table.primaryKey !== undefined && table.primaryKey.length > 0) {\n out.primaryKey = [...table.primaryKey];\n }\n if (table.unique !== undefined && table.unique.length > 0) {\n out.uniqueConstraints = table.unique.map((u) => ({ name: u.name, columns: [...u.columns] }));\n }\n if (table.raw !== undefined && table.raw.length > 0) {\n out.rawConstraints = table.raw.map((r) => ({\n name: r.name,\n up: r.up,\n down: r.down ?? null,\n }));\n }\n if (table.checks !== undefined && table.checks.length > 0) {\n out.checks = table.checks.map((c) => ({ name: c.name, expr: c.expr }));\n }\n if (table.indexes !== undefined && table.indexes.length > 0) {\n out.indexes = table.indexes.map((i) => ({ name: i.name, columns: [...i.columns] }));\n }\n if (table.search !== undefined) {\n // D-010 mod kararının tek girdisi: tabloda dimensions'lı (vector) kolon\n // adı. Birden çoksa ilkini yazmak YANLIŞ olurdu — o durum eski biçimin\n // işidir ve yeni biçim + çoklu vector kolonu apply'da reddedilir.\n const vectorColumn = Object.entries(columns).find(([, c]) => c.dimensions !== undefined)?.[0];\n const sj = searchToJSON(table.search, vectorColumn);\n if (sj.text !== undefined || sj.vector !== undefined) out.search = sj;\n }\n if (table.memory !== undefined) {\n out.memory = memoryToJSON(table.memory);\n }\n return out;\n}\n\n/**\n * The key a table answers to in `SchemaJSON.tables`.\n *\n * A public table is BARE, anything else is schema-qualified. This is not a new\n * convention: `RefJSON.Table` already carries `auth.users`, and introspection\n * already returns a public referent bare and a non-public one qualified. Adding\n * a second key space would make two interpreters of the same database.\n */\nexport function qualifiedTableKey(schemaName: string, tableName: string): string {\n return schemaName === \"public\" ? tableName : `${schemaName}.${tableName}`;\n}\n\n/**\n * Serialize declared schemas into the JSON the deploy applies.\n *\n * Takes every schema the project declares — one file per schema — because a\n * cross-schema foreign key can only be checked when both ends are in hand.\n */\nexport function toSchemaJSON(schemas: readonly SchemaDef[]): SchemaJSON {\n const tables: Record<string, TableJSON> = {};\n const extensions: string[] = [];\n const meta: SchemaMetaJSON[] = [];\n const seen = new Set<string>();\n for (const schema of schemas) {\n if (seen.has(schema.name)) {\n throw new Error(`two schemas declare the name \"${schema.name}\" — schema names must be unique`);\n }\n seen.add(schema.name);\n for (const table of Object.values(schema.tables)) {\n const json = tableToJSON(table, schema.name);\n tables[qualifiedTableKey(schema.name, json.name)] = json;\n }\n extensions.push(...(schema.extensions ?? []));\n // The schema list travels because the flag has nowhere else to live: without\n // it /v1/db cannot know which schemas are reachable over HTTP, and nothing\n // downstream can read the DECLARED schema set that introspection needs.\n meta.push({ name: schema.name, exposed: schema.exposed });\n }\n return { tables, extensions: [...new Set(extensions)], schemas: meta };\n}\n","/**\n * policy.ts — the RLS policy authoring DSL.\n *\n * `policy(name)` returns a fluent builder that mirrors the `ColumnBuilder`\n * style in columns.ts: each chainable method mutates the underlying\n * definition and returns the builder so calls compose. The terminal value is\n * a plain {@link PolicyDef} — the exact JSON shape the runtime's\n * `schema_extract.js` reads off the bundled module and the Go side parses into\n * `PolicyJSON` (CONTRACT-POLICY).\n *\n * @example\n * import { policy } from \"@palbase/backend\";\n *\n * policy(\"owner_select\")\n * .for(\"select\")\n * .to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\");\n */\n\n/** The SQL command a policy applies to. `\"all\"` covers SELECT/INSERT/UPDATE/DELETE. */\nexport type PolicyCommand = \"all\" | \"select\" | \"insert\" | \"update\" | \"delete\";\n\n/** Whether a policy is permissive (OR-combined, the default) or restrictive\n * (AND-combined). Mirrors Postgres `CREATE POLICY ... AS PERMISSIVE|RESTRICTIVE`. */\nexport type PolicyMode = \"permissive\" | \"restrictive\";\n\n/**\n * The compiled, serializable policy definition — the EXACT shape consumed by\n * `schema_extract.js` → Go `PolicyJSON` (CONTRACT-POLICY).\n *\n * - `roles`: the DB roles this policy applies to (`TO` clause). An empty array\n * means the policy applies to PUBLIC (all roles) — the Postgres default.\n * - `using`: the `USING (...)` row-visibility expression, or `null` when none.\n * - `withCheck`: the `WITH CHECK (...)` write-validation expression, or `null`.\n * - `permissive`: `true` for `AS PERMISSIVE` (default), `false` for restrictive.\n */\nexport interface PolicyDef {\n name: string;\n command: PolicyCommand;\n roles: string[];\n using: string | null;\n withCheck: string | null;\n permissive: boolean;\n}\n\n/**\n * Fluent RLS policy builder.\n *\n * Defaults (documented, applied at construction):\n * - `command`: `\"all\"` — applies to every SQL command unless `.for(...)` narrows it.\n * - `roles`: `[\"authenticated\"]` — the common case is \"rule applies to signed-in\n * users\". Call `.to(...)` to override; pass `.to()` with no roles (or never\n * call it after a reset) to target PUBLIC.\n * - `using` / `withCheck`: `null` — no row filter / write check until set.\n * - `permissive`: `true` — `AS PERMISSIVE` (policies OR together).\n *\n * Each method mutates `_def` in place and returns `this`, so the chain is a\n * single builder instance (no per-call allocation, like a tagged-template\n * compile target). The terminal `PolicyDef` is read directly off `_def` by\n * `schema_extract.js`.\n */\n/** Quote an identifier for the policy expression. Table and column names reach\n * here from the schema author; neither is allowed to become syntax. */\nfunction quote(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nexport class PolicyBuilder {\n readonly _def: PolicyDef;\n\n constructor(name: string) {\n this._def = {\n name,\n command: \"all\",\n roles: [\"authenticated\"],\n using: null,\n withCheck: null,\n permissive: true,\n };\n }\n\n /** Restrict the policy to a single SQL command (default `\"all\"`). */\n for(command: PolicyCommand): this {\n this._def.command = command;\n return this;\n }\n\n /**\n * Set the DB roles the policy applies to (the `TO` clause), replacing any\n * previously-set roles. Call with no arguments to target PUBLIC (all roles).\n *\n * @example\n * policy(\"p\").to(\"authenticated\")\n * policy(\"p\").to(\"authenticated\", \"service_role\")\n * policy(\"p\").to() // PUBLIC\n */\n to(...roles: string[]): this {\n this._def.roles = roles;\n return this;\n }\n\n /** Set the `USING (...)` row-visibility expression (raw SQL). */\n using(sqlExpr: string): this {\n this._def.using = sqlExpr;\n return this;\n }\n\n /**\n * \"Rows of THIS table whose owner the caller is a member of\" — the membership\n * pattern, written so it cannot recurse.\n *\n * THE TRAP IT EXISTS FOR. Written by hand, membership policies point at each\n * other: `channels` is visible to members, so its policy reads\n * `channel_members`; `channel_members` is visible to members, so its policy\n * reads `channels`. Postgres refuses the pair at query time with `infinite\n * recursion detected in policy for relation ...`, and the error names the\n * relation but not the cycle. The way out is asymmetry — the MEMBERSHIP table\n * is protected by `user_id = auth.uid()` and nothing else, and every other\n * table subqueries INTO it. That shape was in the platform's own schema and\n * written down nowhere; a customer recovered it by reading that schema.\n *\n * `(select auth.uid())` rather than a bare call: the scalar subquery is\n * evaluated ONCE per statement instead of per row.\n *\n * @example\n * // channels: visible to members. The membership table gets the simple one.\n * policy(\"member_read\").for(\"select\").to(\"authenticated\")\n * .memberOf(\"channel_members\", \"channel_id\")\n * // → id IN (SELECT \"channel_id\" FROM \"channel_members\"\n * // WHERE \"user_id\" = (select auth.uid()))\n */\n memberOf(\n membershipTable: string,\n foreignKey: string,\n options: { column?: string; userColumn?: string } = {},\n ): this {\n if (this._def.using !== null) {\n // Silently AND-ing the two would hide whichever the author meant; silently\n // replacing would hide the one they wrote. Neither is a thing to guess.\n throw new Error(\n `policy(${this._def.name}).memberOf(): this policy already has a using() expression. ` +\n \"Write one or the other — memberOf IS the using expression.\",\n );\n }\n const column = options.column ?? \"id\";\n const userColumn = options.userColumn ?? \"user_id\";\n this._def.using =\n `${quote(column)} IN (SELECT ${quote(foreignKey)} FROM ${quote(membershipTable)} ` +\n `WHERE ${quote(userColumn)} = (select auth.uid()))`;\n return this;\n }\n\n /** Set the `WITH CHECK (...)` write-validation expression (raw SQL). */\n withCheck(sqlExpr: string): this {\n this._def.withCheck = sqlExpr;\n return this;\n }\n\n /** Set the policy mode: `\"permissive\"` (default, OR-combined) or\n * `\"restrictive\"` (AND-combined). */\n as(mode: PolicyMode): this {\n this._def.permissive = mode === \"permissive\";\n return this;\n }\n}\n\n/**\n * Start authoring an RLS policy. Returns a {@link PolicyBuilder}; the resulting\n * `PolicyBuilder` is accepted directly in a table's `policies: [...]` array\n * (its `_def` is read at schema-extract time).\n *\n * @param name The policy name. Palbase reconciliation keys policies by\n * `(table, name)`, so names must be unique per table.\n */\nexport function policy(name: string): PolicyBuilder {\n return new PolicyBuilder(name);\n}\n","import type { ColumnBuilder } from \"./columns.js\";\nimport { qualifiedTableKey } from \"./schema-json.js\";\nimport { PolicyBuilder } from \"./policy.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { PalbaseExtension } from \"./extensions.js\";\nimport type { RawConstraintDef } from \"./raw.js\";\nimport type { ChatModelRef, EmbeddingModelRef } from \"./embedding.js\";\n\n/**\n * A map of column builders keyed by column name — the value you write under\n * the `columns` key of `defineTable(\"<name>\", { columns })`.\n *\n * The default `Record<string, ColumnBuilder>` keeps bare references compiling\n * without a type argument.\n */\nexport type ColumnMap = Record<string, ColumnBuilder>;\n\n/**\n * The author-facing value written under each table key:\n * `{ columns, rls?, policies? }`.\n *\n * - `columns`: the column map (required).\n * - `rls`: enable + FORCE row-level security on this table. **Defaults to\n * `true`**, and is forced on when `policies` is non-empty. A table with RLS\n * and no policies is deny-all, which is the starting state: nothing reads it\n * until a policy says who may. Set `rls: false` only for a genuinely public\n * table — it is an explicit opt-out that a reviewer can grep for, not\n * something you get by forgetting.\n * - `policies`: the RLS policies for this table, authored with `policy(name)`.\n * Each entry may be a {@link PolicyBuilder} (the normal `policy(...)` chain)\n * or a raw {@link PolicyDef} object.\n *\n * The `C` type parameter preserves the precise per-column phantom types so the\n * typed `Database.tables.*` surface keeps inferring insert/row shapes.\n */\n/** Arama metriği — tek kelime; opclass ve operatör bundan türetilir, asla yüzeye çıkmaz (D-5/D-6). */\nexport type SearchMetric = \"cosine\" | \"euclidean\" | \"inner_product\";\n\n/** Bir vektör arama kolu. `model` varsa auto-embed: platform yazma+sorgu embedding'ini üstlenir (D-9). */\nexport interface VectorSearchDecl {\n /** Hedef vector kolonu; tabloda TEK vector kolonu varsa atlanabilir (Go apply çözer, FR-010). */\n column?: string;\n /** Varsa auto-embed. Deskriptor düz veridir — şemayla serileşir (C-3). */\n model?: EmbeddingModelRef;\n /** model varsa ZORUNLU: embed kaynak kolonları = trigger'ın UPDATE OF listesi (C-2). */\n from?: string[];\n metric?: SearchMetric;\n /** Kaynak metin değişince ara-dönem davranışı (yalnız auto-embed'de):\n * \"null\" (vars.) — embedding anında NULL'lanır; satır yeni vektör yazılana\n * dek anlamsal aramada aday değildir. Bayat eşleşme asla servis edilmez.\n * \"keep\" — eski vektör aramada kalır, platform yenisini yazınca sessizce\n * değişir. Görünürlük penceresi sıfır; bedeli saniyeler süren bayat\n * eşleşme riski (Confluence-tipi sync yükleri için). */\n staleness?: \"null\" | \"keep\";\n}\n\n/** Tablonun arama beyanı — İKİ biçim (D-007, tek yüzey):\n *\n * YENİ (önerilen): `{ from, model, ... }` — `from` kolonları hem FTS'e hem\n * embed'e girer. Tabloda vector kolonu declare edilmişse SATIR-modu; yoksa\n * CHUNK-modu otomatiktir (D-010): vektörler türev `__palbase_chunks`\n * tablosunda yaşar, içerik otomatik bölünür. `text: false` FTS'i kapatır,\n * `text: [..]` FTS kolonlarını from'dan ayırır. `chunks` yalnız ince ayar.\n *\n * ESKİ: `text: string[]` + `vector: {...}` — aynen çalışır, wire çıktısı\n * bayt-aynı kalır (NFR-B1). İki biçim KARIŞTIRILAMAZ. */\nexport interface SearchDecl {\n text?: string[] | boolean;\n vector?: VectorSearchDecl | VectorSearchDecl[];\n /** Yeni biçim: arama kaynağı kolonlar (FTS + embed). Varlığı yeni biçimi seçer. */\n from?: string[];\n /** Yeni biçim: auto-embed modeli (zorunlu — BYO için eski biçimi kullanın). */\n model?: EmbeddingModelRef;\n metric?: SearchMetric;\n staleness?: \"null\" | \"keep\";\n /** Chunk-modu ince ayarı (yalnız vector kolonsuz tabloda anlamlı). */\n chunks?: { size?: number; overlap?: number };\n /** Sorgu-yeniden-yazımı: tek yönlü eş anlamlı haritası (FR-026). */\n synonyms?: Record<string, string[]>;\n /** Geçerlilik kolonları türetilir; arama varsayılan yalnız günceli tarar (FR-029). */\n validity?: boolean;\n}\n\n/** Hafıza beyanı (FR-032, D-019): kaynak tablonun yazımlarından platform\n * fact damıtır ve `into` tablosuna yazar. Hedef NORMAL declared tablodur —\n * kendi search/unique/validity beyanlarıyla. Okuma = Database.search(into).\n * subject default \"owner\": fact'in kime ait olduğu kolonu (iki tabloda da). */\nexport interface MemoryDecl {\n from: string[];\n into: string;\n extract: ChatModelRef;\n subject?: string;\n}\n\nexport interface TableInput<C extends ColumnMap = ColumnMap> {\n columns: C;\n rls?: boolean;\n policies?: (PolicyBuilder | PolicyDef)[];\n /** Composite/named primary key (ordered column names). Omit for single-column inline .primaryKey(). */\n primaryKey?: string[];\n /** Named multi-column UNIQUE constraints. */\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects (EXCLUDE, triggers, views) that the typed DSL cannot express. */\n raw?: RawConstraintDef[];\n /**\n * Named first-class CHECK constraints. Diffed by NAME with a BODY compare:\n * a changed `expr` (after pg normalization) recreates the constraint\n * (DROP + ADD). `expr` is trusted SQL emitted verbatim (like policy USING),\n * `name` is identifier-validated.\n */\n checks?: { name: string; expr: string }[];\n /**\n * Plain (non-unique) btree indexes over an ordered column list, emitted as\n * standalone `CREATE INDEX [IF NOT EXISTS] name ON table (col1, col2)`\n * statements (NOT a table clause — a separate migration statement category).\n * Structural compare by NAME (no expression normalization). `name` and each\n * column are identifier-validated by the Go differ.\n *\n * Scope: columns-only plain btree. Partial (`where`) and expression indexes\n * are a deliberate follow-up — modelling them needs the same raw-SQL\n * normalization round-trip CHECK uses (Task 10), so they are NOT in this\n * type yet to avoid a half-working partial-index path.\n */\n indexes?: { name: string; columns: string[] }[];\n /** Arama beyanı — bkz. SearchDecl. */\n search?: SearchDecl;\n /** Hafıza beyanı — bkz. MemoryDecl (FR-032). */\n memory?: MemoryDecl;\n}\n\n/**\n * A table definition — the runtime value the Go runtime's `schema_extract.js`\n * reads. It keys tables by `tableDef.name`, reads `tableDef.columns` for the\n * column DDL, and `tableDef.rls` + `tableDef.policies` for RLS.\n *\n * `defineSchema` derives `name` from the object key, so authors never repeat\n * the table name. `rls`/`policies` are always present after normalization\n * (defaulted to `true`/`[]`).\n *\n * The `C` type parameter preserves the precise per-column phantom types so that\n * downstream mapped types (InsertShape, RowShape) can discriminate on them.\n */\nexport interface TableDef<C extends ColumnMap = ColumnMap> {\n name: string;\n columns: C;\n rls: boolean;\n policies: PolicyDef[];\n primaryKey?: string[];\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects emitted verbatim on deploy. Tracked by name. */\n raw?: RawConstraintDef[];\n /** Named first-class CHECK constraints. Diffed by name + (normalized) body. */\n checks?: { name: string; expr: string }[];\n /** Plain btree indexes (columns-only), emitted as standalone CREATE INDEX. Diffed by name. */\n indexes?: { name: string; columns: string[] }[];\n /** Arama beyanı, doğrulanmış ve taşınmış hali. */\n search?: SearchDecl;\n /** Hafıza beyanı, doğrulanmış ve taşınmış hali (FR-032). */\n memory?: MemoryDecl;\n}\n\n/**\n * A schema definition containing multiple tables, keyed by table name.\n *\n * The `T` type parameter preserves the exact `TableDef<...>` type for each\n * table so that `SchemaDef[\"tables\"][\"rooms\"]` resolves to the precise\n * `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.\n */\nexport interface SchemaDef<\n T extends Record<string, TableDef> = Record<string, TableDef>,\n> {\n /** The schema's own name — `public`, `billing`, … Declared, never derived. */\n name: string;\n /** Reachable over HTTP? False unless the author opts in. */\n exposed: boolean;\n tables: T;\n /** Postgres extensions to install on deploy. Normalized to `[]` when absent. */\n extensions: PalbaseExtension[];\n}\n\n/** The author-facing input to `defineSchema` — a `tables` map whose keys are\n * the table names and whose values are `{ columns, rls?, policies? }`, plus an\n * optional `extensions` allowlist. */\nexport interface SchemaInput<\n T extends Record<string, TableInput> = Record<string, TableInput>,\n> {\n tables: T;\n /**\n * Postgres extensions to enable for this project, e.g. `[\"vector\"]`.\n * Config-as-code: installed by the deploy (CREATE EXTENSION … SCHEMA\n * extensions) with the privileged deploy connection. The type is an\n * allowlist union, so unsupported names fail typecheck.\n */\n extensions?: PalbaseExtension[];\n}\n\n/** Map the author's `{ tables: { <name>: { columns } } }` input to the\n * `{ tables: { <name>: TableDef<columns> } }` runtime/type shape, threading the\n * per-table column map `T[K][\"columns\"]` so column-level inference survives. */\ntype TablesByName<T extends readonly TableHandle[]> = {\n [K in T[number] as K[typeof TABLE_META][\"name\"]]: K[typeof TABLE_META];\n};\n\n/** Normalize a single `policies` entry into a plain `PolicyDef` (read off a\n * `PolicyBuilder._def`, or passed through when already a `PolicyDef`). */\nfunction toPolicyDef(p: PolicyBuilder | PolicyDef): PolicyDef {\n return p instanceof PolicyBuilder ? p._def : p;\n}\n\n/**\n * How a schema file reads. One file per schema — `db/public.ts`, `db/billing.ts`\n * — and the schema says its own name:\n *\n * const todos = defineTable(\"todos\", {\n * columns: {\n * id: uuid().primaryKey().defaultRandom(),\n * owner: text().notNull(),\n * title: text().notNull(),\n * },\n * rls: true,\n * policies: [\n * policy(\"owner_all\").for(\"all\").to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\")\n * .withCheck(\"owner = (select auth.uid())\"),\n * ],\n * });\n *\n * export default defineSchema(\"public\", { tables: [todos] });\n *\n * The dictionary form `defineSchema({ tables: { todos: {…} } })` is RETIRED and\n * refused by name: a table whose name comes from a key does not know what it is\n * called while it is being built, so it cannot resolve `references(() =>\n * other.id)`, and a schema that does not say its own name cannot tell one\n * `invoices` from another schema's `invoices`.\n *\n * The returned value is `{ name, tables: { todos: { name, columns, rls,\n * policies } }, extensions, exposed }` — the exact shape the runtime schema\n * extractor parses. Per-column phantom types are preserved so\n * `Database.tables.todos.insert({...})` stays typed.\n *\n * RLS normalization: `rls` defaults to **`true`**, `policies` to `[]`. A table\n * that declares neither is therefore deny-all — nothing reads it until a policy\n * says who may, which is the safe starting point rather than a bug. Declare\n * `rls: false` for a genuinely public table; that is an explicit, greppable\n * statement of intent instead of an omission. When `policies` is non-empty,\n * `rls` is forced on (ENABLE + FORCE) regardless of the declared flag — a table\n * with policies must have RLS enabled or the policies would be inert.\n */\n/**\n * Where a table's metadata lives.\n *\n * The table VALUE is its columns, so `lists.id` is the column — which means a\n * column called `name` would overwrite the table's own name if metadata sat in\n * a plain field. Measured, not imagined: the existing `users` / `rooms` tests\n * (both declare a `name` column) produced an `[object Object]` table key.\n * `columns`, `rls`, `search`, `memory`, `unique` and `indexes` are all plausible\n * column names too. A column cannot collide with a symbol.\n */\nexport const TABLE_META: unique symbol = Symbol.for(\"palbase.table.meta\");\n\n/** A value produced by `defineTable`: the columns, plus metadata behind the symbol. */\nexport type TableHandle<C extends ColumnMap = ColumnMap, N extends string = string> =\n C & { readonly [TABLE_META]: TableDef<C> & { name: N } };\n\n/**\n * Declare one table as a standalone value that KNOWS ITS OWN NAME.\n *\n * The name lives here, not in a dictionary key. A table whose name comes from a\n * key cannot resolve `references(() => other.id)` when it is built — it does not\n * know what to call itself — which forces a two-phase resolution with an\n * empty-name intermediate state. One name source, no empty identity.\n *\n * The returned object spreads its own columns, so a sibling can point at it:\n * `references(() => lists.id)`.\n */\nexport function defineTable<const N extends string, C extends ColumnMap>(\n name: N,\n input: TableInput<C>,\n): TableHandle<C, N> {\n if (name.trim() === \"\") {\n throw new Error(\"defineTable(name, …): name must not be empty\");\n }\n const policies = (input.policies ?? []).map(toPolicyDef);\n // Fail closed. RLS is on unless the author explicitly says `rls: false`, and\n // policies force it on regardless — a policy on a table without RLS enabled is\n // inert, so declaring both resolves towards the safe reading.\n //\n // This defaulted to `false` until 2026-08-07, which meant a table nobody\n // thought about had no row-level security while `typed-db.ts` documented the\n // default `Database.*` path as RLS-enforced. The live proof settled it: user B\n // read user A's row in full through the typed client, while the same request\n // against a table declaring `rls: true` returned 0 of 165 rows. With no\n // policies this is deny-all.\n const rls = policies.length > 0 || input.rls !== false;\n const def = {\n name,\n columns: input.columns,\n rls,\n policies,\n } as TableDef<C> & { name: N };\n if (input.primaryKey !== undefined) def.primaryKey = input.primaryKey;\n if (input.unique !== undefined) def.unique = input.unique;\n if (input.raw !== undefined && input.raw.length > 0) def.raw = input.raw.slice();\n if (input.checks !== undefined && input.checks.length > 0) def.checks = input.checks.slice();\n if (input.indexes !== undefined && input.indexes.length > 0) def.indexes = input.indexes.slice();\n if (input.search !== undefined) {\n const s = input.search;\n // Erken, beyan-anı doğrulama (apply doğrulamasını İKAME ETMEZ — yazım\n // hatası deploy'a gitmeden yazarın yüzüne söylenir).\n if (s.from !== undefined) {\n // YENİ biçim (D-007). Eski alanlarla karışım tek biçime zorlanır:\n // iki yarım beyanın hangisinin kazandığını okuyucu bilemez.\n if (s.vector !== undefined) {\n throw new Error(\n `table ${name}: search beyanında tek biçim kullanın — 'from' (yeni) ile 'vector' (eski) birlikte olamaz`,\n );\n }\n if (s.from.length === 0) {\n throw new Error(`table ${name}: search.from boş olamaz`);\n }\n if (s.model === undefined) {\n throw new Error(\n `table ${name}: search.from model'siz anlamsız — auto-embed için model verin (BYO için eski 'vector' biçimini kullanın)`,\n );\n }\n if (Array.isArray(s.text) && s.text.length === 0) {\n throw new Error(`table ${name}: search.text boş dizi olamaz — FTS istemiyorsan text: false yazın`);\n }\n } else {\n // ESKİ biçim — davranış ve hata metinleri aynen (NFR-B1'in DX yarısı).\n if (typeof s.text === \"boolean\") {\n throw new Error(`table ${name}: text:${String(s.text)} yalnız yeni biçimde ('from' ile) geçerli`);\n }\n if (s.text === undefined && s.vector === undefined) {\n throw new Error(\n `table ${name}: search beyanı boş — en az bir kol (text ya da vector) verin, yoksa alanı hiç yazmayın`,\n );\n }\n if (s.text !== undefined && s.text.length === 0) {\n throw new Error(`table ${name}: search.text boş olamaz — FTS kolu istemiyorsan alanı hiç yazma`);\n }\n const legs = s.vector === undefined ? [] : Array.isArray(s.vector) ? s.vector : [s.vector];\n for (const leg of legs) {\n if (leg.model !== undefined && (leg.from === undefined || leg.from.length === 0)) {\n throw new Error(`table ${name}: search.vector.model beyan edildi ama 'from' yok — embed kaynağı kolonlar zorunlu (C-2)`);\n }\n if (leg.model === undefined && leg.from !== undefined) {\n throw new Error(`table ${name}: search.vector.from model'siz anlamsız — auto-embed için model verin`);\n }\n }\n }\n def.search = s;\n }\n if (input.memory !== undefined) {\n if (input.memory.from.length === 0) {\n throw new Error(`table ${name}: memory.from boş olamaz`);\n }\n def.memory = input.memory;\n }\n // Every column learns which table owns it, so a reference thunk can name its\n // target when `defineSchema` resolves it.\n for (const b of Object.values(input.columns)) {\n (b as { _def: { ownerTable?: unknown } })._def.ownerTable = def;\n }\n // Columns are the enumerable surface; metadata hangs off a non-enumerable\n // symbol so it survives spreads and cannot be shadowed by a column name.\n const handle = { ...input.columns } as TableHandle<C, N>;\n Object.defineProperty(handle, TABLE_META, { value: def, enumerable: false });\n return handle;\n}\n\n/**\n * Which schema declared a table.\n *\n * A `TableDef` cannot carry it: `defineTable` runs before any schema exists, and\n * `defineSchema` is where the answer arrives. It lives OUTSIDE the def rather\n * than on it because the def is serialized — a field here would either leak into\n * the wire shape or need a second rule saying not to. A WeakMap keyed by the def\n * object is the same fact with no surface.\n *\n * It exists because a foreign key names its target and that name is only half a\n * name without the schema. `resolveReferences` reads it to write the referent\n * the way `qualifiedTableKey` writes every other table name.\n */\nconst declaringSchemaOf = new WeakMap<object, string>();\n\n/**\n * Resolve every pending reference thunk.\n *\n * Runs inside `defineSchema`, where all table bindings exist and every table\n * already carries its name — which is why the name lives on the table and not in\n * a dictionary key: resolving against a table that does not yet know what it is\n * called would need a second pass over an empty-name intermediate state.\n *\n * The written referent follows the ONE naming convention (`qualifiedTableKey`):\n * a `public` table is bare, anything else is schema-qualified. The deciding fact\n * is the REFERENT's schema, not whether the key crosses a schema boundary —\n * exactly the CASE Go's introspection uses when it reads a live FK back\n * (`introspect.go`: `CASE WHEN rn.nspname = 'public' THEN rt.relname ELSE\n * rn.nspname || '.' || rt.relname END`). Writing `invoices` for a table that\n * lives in `billing` made Go read it as `public.invoices`: a FK onto a table\n * that does not exist, or — worse and silently — onto a DIFFERENT table that\n * happened to share the name.\n */\nfunction resolveReferences(tables: Record<string, TableDef>, schemaName: string): void {\n for (const table of Object.values(tables)) {\n for (const [colName, builder] of Object.entries(table.columns)) {\n const def = (builder as { _def: ColumnDefLike })._def;\n if (def.selfRefColumn !== undefined) {\n if (!(def.selfRefColumn in table.columns)) {\n throw new Error(\n `table \"${table.name}\" column \"${colName}\": selfReferences(\"${def.selfRefColumn}\") — no such column on this table`,\n );\n }\n // A self-reference is a reference: its referent is this table, in THIS\n // schema, so it is written by the same rule as any other.\n def.references = {\n table: qualifiedTableKey(schemaName, table.name),\n column: def.selfRefColumn,\n };\n continue;\n }\n if (def.referencesThunk === undefined) continue;\n const target = def.referencesThunk();\n const owner = (target as { _def?: ColumnDefLike } | undefined)?._def?.ownerTable;\n if (owner === undefined) {\n throw new Error(\n `table \"${table.name}\" column \"${colName}\": references(() => …) must point at a column of a table declared with defineTable(...)`,\n );\n }\n const targetColumn = Object.entries(owner.columns).find(\n ([, b]) => (b as { _def: unknown })._def === (target as { _def: unknown })._def,\n )?.[0];\n if (targetColumn === undefined) {\n throw new Error(\n `table \"${table.name}\" column \"${colName}\": the referenced column was not found on table \"${owner.name}\"`,\n );\n }\n const targetSchema = declaringSchemaOf.get(owner);\n if (targetSchema === undefined) {\n // Assuming `public` here is the exact silence this resolution closes:\n // it would produce a FK onto a table that does not exist, or onto a\n // same-named one that does. Name the gap instead.\n throw new Error(\n `table \"${table.name}\" column \"${colName}\": references(() => …) points at table ` +\n `\"${owner.name}\", which no defineSchema(...) has claimed yet — a foreign key cannot ` +\n `be written without its target's schema. Declare that table's schema first ` +\n `(one file per schema: db/public.ts, db/billing.ts …, imported by this one).`,\n );\n }\n def.references = {\n table: qualifiedTableKey(targetSchema, owner.name),\n column: targetColumn,\n };\n }\n }\n}\n\ntype ColumnDefLike = {\n references?: { table: string; column: string };\n referencesThunk?: () => unknown;\n selfRefColumn?: string;\n ownerTable?: { name: string; columns: Record<string, unknown> };\n};\n\n/**\n * Collect declared tables into one schema.\n *\n * Takes an ARRAY, not a dictionary: the tables already carry their names, and a\n * second name source is a second thing that can disagree.\n */\nexport function defineSchema<const T extends readonly TableHandle[]>(\n name: string,\n input: { tables: T; exposed?: boolean; extensions?: PalbaseExtension[] },\n): SchemaDef<TablesByName<T>> {\n // The TYPE first, then the value. The retired one-argument form passes an\n // object here, and a guard that only asks whether the name is blank calls\n // `.trim()` on it — which threw `name.trim is not a function` out of the child\n // process that runs `db/*.ts` during push: no file, no form, nothing to act\n // on. `references(\"t\", \"c\")` already answers its own retirement by name.\n if (typeof name !== \"string\") {\n throw new Error(\n `defineSchema(...) takes the schema NAME first: ` +\n `defineSchema(\"public\", { tables: [todos, lists] }). ` +\n `The one-argument form defineSchema({ tables: { … } }) is gone — a schema that does not ` +\n `say its own name cannot be told apart from another schema's table of the same name, ` +\n `which is what a cross-schema foreign key has to do. ` +\n `Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts …): name the ` +\n `schema, and lift each table key onto the table itself with ` +\n `defineTable(\"todos\", { columns: { … } }), then list the tables in the array.`,\n );\n }\n if (name.trim() === \"\") {\n throw new Error(\"defineSchema(name, …): name must not be empty\");\n }\n const tables = {} as Record<string, TableDef>;\n for (const handle of input.tables) {\n const table = handle[TABLE_META];\n if (tables[table.name] !== undefined) {\n throw new Error(\n `defineSchema(\"${name}\"): two tables declare the name \"${table.name}\" — table names must be unique within a schema`,\n );\n }\n tables[table.name] = table;\n // Stamped BEFORE resolution: a reference from this schema to a sibling in it\n // must find the sibling's schema, and the sibling may be declared later in\n // the array than the table pointing at it.\n declaringSchemaOf.set(table, name);\n }\n // Thunks are invoked HERE: every binding exists and every name is already set.\n resolveReferences(tables, name);\n // memory beyanları TABLOLAR-ARASI doğrulanır (into/subject/fact) — tüm\n // tablolar kurulduktan sonra: beyan sırasına bağımlılık olmasın (FR-032).\n for (const [name, def] of Object.entries(tables)) {\n const m = (def as TableDef).memory;\n if (m === undefined) continue;\n const target = Object.values(tables).find((t) => (t as TableDef).name === m.into) as TableDef | undefined;\n if (target === undefined) {\n throw new Error(`table ${name}: memory.into \"${m.into}\" şemada declared değil`);\n }\n const subject = m.subject ?? \"owner\";\n if (!(subject in (def as TableDef).columns)) {\n throw new Error(`table ${name}: memory.subject \"${subject}\" kolonu kaynak tabloda yok`);\n }\n if (!(subject in target.columns)) {\n throw new Error(`table ${name}: memory.subject \"${subject}\" kolonu hedef \"${m.into}\" tablosunda yok`);\n }\n const factCol = target.columns[\"fact\"];\n const factDef = factCol !== undefined && \"_def\" in (factCol as object)\n ? (factCol as { _def: { type?: string } })._def\n : (factCol as { type?: string } | undefined);\n if (factDef === undefined || factDef.type !== \"text\") {\n throw new Error(`table ${name}: memory.into \"${m.into}\" tablosunda \"fact\" (text) kolonu zorunlu`);\n }\n for (const c of m.from) {\n if (!(c in (def as TableDef).columns)) {\n throw new Error(`table ${name}: memory.from kolonu \"${c}\" kaynak tabloda yok`);\n }\n }\n }\n // Dedupe + normalize extensions (order-independent; deploy resolves deps).\n const extensions = [...new Set(input.extensions ?? [])];\n // Declaring a schema is not the same as putting it on the internet, so\n // `exposed` is false unless the author says otherwise — EXCEPT for `public`,\n // which is reachable today and stays reachable. Making the default uniform\n // would silently 404 every existing project's /v1/db traffic on upgrade.\n return {\n name,\n tables: tables as TablesByName<T>,\n extensions,\n exposed: input.exposed ?? name === \"public\",\n };\n}\n","/**\n * channels.ts — the realtime channel authorization DSL (spec C-5).\n *\n * `defineChannels({...})` is evaluated at bundle load; the declaration is\n * anchored on globalThis under Symbol.for (the error-registry.ts pattern) so\n * the runtime — a separate module instance — reads the SAME object. The runtime\n * empties that slot before each bundle import and puts it back afterwards, so\n * the declaration belongs to the bundle that made it and not to the process.\n * Entry ORDER is the object's key order and is semantic: first match wins.\n *\n * Undeclared channels are DENIED by the server (fail-closed). ownerOnly()\n * patterns resolve with ZERO server hops; custom entries' authorize() runs\n * in the customer's own runtime with the request scope a controller gets.\n */\n\nconst CHANNELS: unique symbol = Symbol.for(\"palbase.backend.channels\") as never;\n\nexport interface ChannelGrant {\n subscribe: boolean;\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n}\n\nexport interface ChannelAuthorizeCtx {\n user: { id: string };\n params: Record<string, string>;\n}\n\ninterface OwnerEntry { kind: \"owner\" }\ninterface PublicEntry {\n kind: \"public\";\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n}\n/** What a handler receives: who published, on which channel, and what. */\nexport interface ChannelHandlerCtx {\n user: { id: string };\n params: Record<string, string>;\n channel: string;\n event: string;\n payload: Record<string, unknown>;\n}\n\ninterface CustomEntry {\n authorize: (ctx: ChannelAuthorizeCtx) => ChannelGrant | null | Promise<ChannelGrant | null>;\n /**\n * Take over publishes on this channel instead of fanning them out.\n *\n * Without it, `channel.send(...)` is relayed to the other subscribers\n * verbatim — fine for a chat message, wrong for anything the client should\n * not be trusted to assert. A bid, a vote, a game move is a REQUEST, and the\n * result is whatever this function decides and then publishes (through\n * `Realtime.broadcast` or `Realtime.state.set`).\n *\n * A function rather than the name of a route: `authorize` is already one and\n * runs in this same scope, so naming an endpoint would mean inventing a\n * resolution step for no gain.\n */\n handler?: (ctx: ChannelHandlerCtx) => void | Promise<void>;\n}\nexport type ChannelEntry = OwnerEntry | PublicEntry | CustomEntry;\nexport type ChannelsInput = Record<string, ChannelEntry>;\n\nexport interface ChannelsDef {\n entries: Array<{\n pattern: string;\n kind: \"owner\" | \"public\" | \"custom\";\n publish?: boolean;\n state?: { read?: boolean; write?: boolean };\n authorize?: CustomEntry[\"authorize\"];\n handler?: CustomEntry[\"handler\"];\n }>;\n}\n\n/** Full-access-to-the-owner pattern: the pattern must carry EXACTLY one {param};\n * the server compares its value to the verified token subject with zero hops. */\nexport function ownerOnly(): OwnerEntry {\n return { kind: \"owner\" };\n}\n\n/** Anyone with a valid token may subscribe; publish/state are explicit opt-ins. */\nexport function publicChannel(\n opts: { publish?: boolean; state?: { read?: boolean; write?: boolean } } = {},\n): PublicEntry {\n return { kind: \"public\", publish: opts.publish ?? false, state: opts.state };\n}\n\nfunction paramCount(pattern: string): number {\n return pattern.split(\":\").filter((s) => s.startsWith(\"{\") && s.endsWith(\"}\")).length;\n}\n\nexport function defineChannels(map: ChannelsInput): ChannelsDef {\n const entries: ChannelsDef[\"entries\"] = [];\n for (const [pattern, entry] of Object.entries(map)) {\n if (\"kind\" in entry && entry.kind === \"owner\") {\n if (paramCount(pattern) !== 1) {\n throw new Error(\n `defineChannels: ownerOnly() pattern \"${pattern}\" must carry exactly one {param} ` +\n `(its value is compared to the token subject)`,\n );\n }\n entries.push({ pattern, kind: \"owner\" });\n } else if (\"kind\" in entry && entry.kind === \"public\") {\n entries.push({ pattern, kind: \"public\", publish: entry.publish, state: entry.state });\n } else {\n const c = entry as CustomEntry;\n entries.push({ pattern, kind: \"custom\", authorize: c.authorize, handler: c.handler });\n }\n }\n const def: ChannelsDef = { entries };\n\n // A SECOND, DIFFERENT declaration is a hard error rather than an overwrite.\n //\n // The same bundle can legitimately be evaluated twice in one process — the\n // error registry beside this file documents exactly that case — so an\n // identical re-declaration passes silently. But two DIFFERENT declarations\n // mean two channels files, and overwriting would delete the first one's\n // channels. Undeclared channels are DENIED, so the symptom would be joins\n // refused in production for channels the developer can see declared in their\n // own source, with nothing anywhere saying why. Loud here beats silent there.\n //\n // \"Already\" means WITHIN ONE BUNDLE LOAD. The runtime hands each import an\n // empty slot, so this compares two calls from the same bundle — which is what\n // it was written for. It used to reach across imports as well, and then a\n // deploy that merely ADDED a channel was refused as a second channels file,\n // with a message pointing at a file the customer did not have.\n const carrier = globalThis as Record<symbol, unknown>;\n const existing = carrier[CHANNELS] as ChannelsDef | undefined;\n if (existing && !sameDeclaration(existing, def)) {\n throw new Error(\n `defineChannels: channels were already declared (${existing.entries.length} ` +\n `pattern(s): ${existing.entries.map((e) => e.pattern).join(\", \")}). ` +\n `A project declares its channels ONCE — a second call would overwrite the ` +\n `first, and channels nobody declared are refused.`,\n );\n }\n carrier[CHANNELS] = def;\n return def;\n}\n\n/**\n * One entry as the runtime will compile it, rendered for comparison.\n *\n * NORMALIZED, because the runtime normalizes: `collectChannels` applies\n * `?? false` to publish and both state flags before the table goes on the wire.\n * Comparing the raw entries called two spellings of ONE entry a conflict —\n * `publicChannel()` fills `publish: false` where a hand-written\n * `{ kind: \"public\" }` leaves it undefined, and the two produce a byte-identical\n * table. There is one source of truth for what an entry IS, and it is the row.\n *\n * The authorize function is compared by SOURCE TEXT. Comparing the closures\n * themselves is wrong — two evaluations of one module produce two distinct\n * functions for the same source, which is the case this guard has to let\n * through — but comparing only `Boolean(fn)` called two unrelated\n * authorization rules \"the same declaration\", so the guard stayed silent while\n * one channel's access rule was swapped for another's. Same source, same text;\n * different logic, different text. Not exhaustive (two closures over different\n * captured values share a source), and better than a boolean by the whole\n * distance between \"some rule\" and \"this rule\".\n */\nfunction wireRow(e: ChannelsDef[\"entries\"][number]): string {\n return JSON.stringify([\n e.pattern,\n e.kind,\n e.publish ?? false,\n e.state?.read ?? false,\n e.state?.write ?? false,\n // The handler is compared by SOURCE, like authorize: two evaluations of one\n // module give the same text, while different logic gives different text.\n e.handler ? e.handler.toString() : \"\",\n e.authorize ? e.authorize.toString() : \"\",\n ]);\n}\n\n/** Two declarations are the same when they compile to the same rows in the same\n * ORDER — order is semantic here (first match wins). */\nfunction sameDeclaration(a: ChannelsDef, b: ChannelsDef): boolean {\n if (a.entries.length !== b.entries.length) return false;\n return a.entries.every((x, i) => wireRow(x) === wireRow(b.entries[i]!));\n}\n","/**\n * Postgres extensions a Palbase project can enable from its schema.\n *\n * Extensions are config-as-code: declare them in `defineSchema({ extensions })`\n * and the deploy installs them (CREATE EXTENSION … SCHEMA extensions) using the\n * deploy path's privileged connection. They are NOT toggled live from Studio —\n * CREATE EXTENSION requires a superuser role that only the deploy path holds.\n *\n * The list is an allowlist (a string-literal union) so editors autocomplete the\n * supported names and a typo fails typecheck. It is intentionally extensible:\n * add a name here (+ confirm the base image ships it) to support more.\n */\nexport const PALBASE_EXTENSIONS = [\n // Search & text\n \"vector\", // pgvector: AI embeddings + vector similarity search (semantic search / RAG).\n // NB: the Postgres extension is named \"vector\", not \"pgvector\" — declare \"vector\".\n \"pg_trgm\", // trigram fuzzy / typo-tolerant text search\n \"unaccent\", // accent-insensitive text search\n \"citext\", // case-insensitive text type\n // Geospatial / location\n \"cube\", // multi-dimensional cubes (dependency of earthdistance)\n \"earthdistance\", // great-circle distance (needs cube)\n // Data types & structures\n \"hstore\", // key/value pairs in a single column\n \"ltree\", // hierarchical tree-structured labels\n // Indexing & constraints\n \"btree_gist\", // GiST operator classes for scalar types — needed for EXCLUDE\n // constraints that mix \"=\" with a range/&& overlap (e.g. no-double-booking).\n // Scheduling\n // Crypto / ids (also installed by default; listable for explicitness)\n \"pgcrypto\", // cryptographic functions (hashing, encryption)\n \"uuid-ossp\", // UUID generation functions\n] as const;\n\n/** A Postgres extension supported by Palbase (allowlist union). */\nexport type PalbaseExtension = (typeof PALBASE_EXTENSIONS)[number];\n\n/**\n * Extensions that depend on another extension. The deploy installs\n * dependencies first; declaring `earthdistance` without `cube` still works\n * because the deploy resolves the order, but listing both is clearer.\n */\nexport const EXTENSION_DEPENDENCIES: Partial<Record<PalbaseExtension, PalbaseExtension[]>> = {\n earthdistance: [\"cube\"],\n};\n\n/** Runtime guard: is `name` a supported Palbase extension? */\nexport function isPalbaseExtension(name: string): name is PalbaseExtension {\n return (PALBASE_EXTENSIONS as readonly string[]).includes(name);\n}\n","/** On delete action for foreign key references. */\nexport type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';\n\n/**\n * The ON DELETE actions permitted on a foreign key to the built-in auth users\n * (`auth.users`). Both let a user's rows be removed (`cascade`) or detached\n * (`set null`) when the account is erased; `restrict` / `no action` would BLOCK\n * erasure and are therefore excluded. This is the CLIENT-SIDE mirror of the\n * server's auth-FK deletion policy — the server (validateAuthUserFK) is the real\n * boundary, this narrows the type so the common mistake is caught at compile time.\n */\nexport type AuthUserOnDelete = Extract<OnDeleteAction, 'cascade' | 'set null'>;\n\n/** Column type identifiers. */\nexport type ColumnType =\n | 'uuid'\n | 'text'\n | 'integer'\n | 'bigint'\n | 'numeric'\n | 'boolean'\n | 'timestamp'\n | 'jsonb'\n | 'enum'\n | 'vector';\n\n/** Base column definition shared by all column types. */\nexport interface ColumnDef {\n type: ColumnType;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n references?: { table: string; column: string };\n /** Pending FK target, resolved by `defineSchema` once every binding exists. */\n referencesThunk?: () => ColumnBuilder;\n /** FK onto THIS table — no thunk needed, the target is the declaring table. */\n selfRefColumn?: string;\n /** This column OWNS the row: erasure, RLS and the `owner` relation read it. */\n owns?: true;\n /** Explicit relation name, when the derived one would be ambiguous. */\n refAs?: string;\n /** The table this column belongs to; set by `defineTable`. */\n ownerTable?: { name: string; columns: Record<string, ColumnBuilder> };\n /**\n * The name this column used to have. A diff cannot tell a rename from a drop and\n * an add — both leave one name gone and another present — so the intent has to be\n * declared. Without it, renaming a column loses its data.\n */\n renamedFrom?: string;\n /**\n * This release's PROMISE that it does not reference this column — neither\n * reads it nor writes it, and never names it in a filter, a sort or a SET.\n *\n * The contraction gate reads it and nothing else does: dropping a column is\n * refused while the RUNNING release's declaration still lacks this mark, so\n * removing a column is two deploys — mark it, ship, then drop it.\n *\n * The word is `ignored` and not `deprecated` deliberately: RFC 9745 defines\n * deprecation as changing NO behaviour, and this changes what a deploy will\n * accept. Rails calls the same thing `ignored_columns`.\n */\n ignored?: boolean;\n onDeleteAction?: OnDeleteAction;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n /**\n * The value is written by the DATABASE — a trigger, a rule, an identity — not by\n * the author and not by a DEFAULT this schema declares. It makes the column\n * optional on INSERT without putting a DEFAULT in the DDL.\n *\n * Before this existed the only way to keep a trigger-filled column off the\n * INSERT type was to give it a fake `default()`: a value the schema claimed to\n * write and the trigger immediately overwrote. That made the schema lie about\n * its own data.\n */\n dbAssigned?: boolean;\n /** vector(n): the declared dimension count — part of the TYPE (typmod), read\n * by the wire serializer and the deploy's auto-index (FR-001). */\n dimensions?: number;\n /**\n * How the stored value is projected in and out of this process (FR-009).\n *\n * NOT part of the DDL: the column's Postgres type is unchanged and this pair\n * is never serialized into a migration. It exists so the row surface can hand\n * back the type the application actually works with.\n */\n transform?: ColumnTransform;\n}\n\n/**\n * The read/write pair a column may declare (FR-009).\n *\n * `fromDb` takes whatever the driver produced for this column and returns the\n * value the application sees; `toDb` is its inverse on the way out. Kept\n * deliberately unexported — a column declares one inline, nobody needs to name\n * the shape.\n */\ninterface ColumnTransform<T = unknown> {\n fromDb: (value: unknown) => T;\n toDb: (value: T) => unknown;\n}\n\n/** FR-002: a vector column cannot carry keys/defaults/references — the modifier\n * is named in the error so the author fixes the right line. */\nfunction refuseOnVector(def: ColumnDef, modifier: string): void {\n if (def.type === 'vector') {\n throw new Error(`vector column: .${modifier}() is not supported (FR-002 — allowed: nullable()/notNull())`);\n }\n}\n\n// Phantom brand symbols — never have runtime values; exist only to force\n// TypeScript's structural type system to distinguish ColumnBuilder instances\n// with different type-param combinations. Without these, TS sees all\n// ColumnBuilder<K,...> as structurally identical and the first branch of\n// ColValue matches everything.\ndeclare const __colKind: unique symbol;\ndeclare const __colNullable: unique symbol;\ndeclare const __colHasDefault: unique symbol;\ndeclare const __colEnumValues: unique symbol;\ndeclare const __colPayload: unique symbol;\ndeclare const __colTransform: unique symbol;\n\n/**\n * Fluent column builder with phantom type params:\n * K — ColumnType literal (e.g. \"text\", \"integer\")\n * N — boolean: true when nullable() has been called last (false = NOT NULL)\n * D — boolean: true when a default has been set\n * E — enum value union (never for non-enum columns)\n * P — jsonb payload shape (unknown unless jsonb<T>() supplied one)\n * T — transform target type (`never` when the column declares no transform;\n * `never` is the sentinel because it is the only type that survives\n * `[T] extends [never]` and never collides with a real target type)\n *\n * All six params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The six `declare readonly` brand fields carry the phantom types into the\n * structural shape so that conditional types like ColValue<C> can discriminate\n * on K without requiring runtime values on those fields.\n */\nexport class ColumnBuilder<\n K extends ColumnType = ColumnType,\n N extends boolean = boolean,\n D extends boolean = boolean,\n E = unknown,\n P = unknown,\n // `unknown`, not `never`: the schema's own constraint is a BARE\n // `ColumnBuilder`, whose T lands on this default. With `never` there, a\n // column that declares `.transform<number>()` is not assignable to the\n // constraint at all — `number` does not extend `never` — so a transform\n // could not appear in a schema and the whole table's `RowShape` collapsed.\n // Measured: TS2322 on `defineSchema`.\n T = unknown,\n> {\n // These fields exist only in the type layer (declared, never initialised at\n // runtime — TypeScript allows declared class members without an initializer\n // in strict mode as long as they're never read at runtime).\n declare readonly [__colKind]: K;\n declare readonly [__colNullable]: N;\n declare readonly [__colHasDefault]: D;\n declare readonly [__colEnumValues]: E;\n declare readonly [__colPayload]: P;\n declare readonly [__colTransform]: T;\n\n readonly _def: ColumnDef;\n\n constructor(type: K, existingDef?: ColumnDef) {\n this._def = existingDef ?? {\n type,\n nullable: false,\n primaryKey: false,\n };\n }\n\n /** Mark this column as the primary key. */\n primaryKey(): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'primaryKey');\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Mark this column as NOT NULL (default). */\n notNull(): ColumnBuilder<K, false, D, E, P, T> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E, P, T> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'default');\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** UUID: generate a random default (gen_random_uuid()). */\n defaultRandom(): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'defaultRandom');\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'defaultNow');\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * The DATABASE assigns this column's value — a trigger, a rule, an identity.\n *\n * The column becomes optional on INSERT (the author has nothing to send) while\n * the DDL stays free of a DEFAULT this schema would not honour. It is NOT\n * `default()`: that declares a value the schema promises to write.\n *\n * Naming: deliberately not `generated()`. Postgres has GENERATED columns and\n * they are a different thing; borrowing the word would send a reader — or a\n * model writing a schema — to the wrong feature.\n */\n dbAssigned(): ColumnBuilder<K, N, true, E, P, T> {\n this._def.dbAssigned = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a foreign key reference. */\n /**\n * Declares that this column used to be called `previous`.\n *\n * A schema diff sees one name gone and another present; it cannot know whether\n * you renamed a column or dropped one and added another, and the two are very\n * different — the second loses every value. Saying so here turns the plan into\n * `ALTER TABLE … RENAME COLUMN` instead.\n *\n * Once the rename has been applied the annotation is inert (the old name is no\n * longer there to rename), so it can be deleted at your leisure.\n */\n renamedFrom(previous: string): ColumnBuilder<K, N, D, E, P, T> {\n this._def.renamedFrom = previous;\n return this as unknown as ColumnBuilder<K, N, D, E, P, T>;\n }\n\n /**\n * See {@link ColumnDef.ignored}.\n *\n * COPIES the def rather than mutating it. The constructor takes an existing\n * def BY REFERENCE, so every builder derived from another shares one object —\n * `const a = slug.unique()` leaves `a._def === slug._def`. An in-place\n * `ignored = true` therefore marks every column sharing that def, including\n * one another table actively reads, and the gate would let THAT column be\n * dropped. Measured before this copy existed.\n *\n * The aliasing is older than this method and other fields leak through it too.\n * The reason this one cannot wait: every other leak produces a VISIBLE schema\n * difference — the plan shows it, the DDL shows it. This one is invisible by\n * design (no DDL, no diff, no plan line), so its only effect is to disarm a\n * safety gate in silence.\n */\n ignored(): ColumnBuilder<K, N, D, E, P, T> {\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, {\n ...this._def,\n ignored: true,\n });\n }\n\n /**\n * Foreign key onto another table's column.\n *\n * The target is a THUNK, not a direct reference. In a cycle (`x → y`, `y → x`)\n * the second table does not exist yet when the first is built; a direct\n * reference makes TypeScript chase its own tail (TS7022 — measured, and making\n * the return type independent of the target does NOT help). The thunk is\n * invoked in `defineSchema`, where every binding exists and every table\n * already knows its name.\n *\n * In a cycle, ONE side needs an explicit return type:\n * `references((): AnyColumn => y.id)`. One side is enough — measured.\n * For a self-reference use `selfReferences(column)`: no thunk, no annotation.\n */\n references(\n target: () => AnyColumn,\n opts?: { as?: string; onDelete?: OnDeleteAction },\n ): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'references');\n if (typeof target !== 'function') {\n // Fail where the mistake is. Storing a non-thunk here surfaces three\n // layers later as \"def.referencesThunk is not a function\", inside\n // defineSchema, naming neither the column nor the call that was wrong.\n throw new Error(\n `references(...) takes a callback: write references(() => otherTable.column). ` +\n `The two-string form references(\"table\", \"column\") is gone — a string cannot be type-checked ` +\n `and cannot point at a table that does not exist yet.`,\n );\n }\n this._def.referencesThunk = target;\n if (opts?.as !== undefined) this._def.refAs = opts.as;\n if (opts?.onDelete !== undefined) this._def.onDeleteAction = opts.onDelete;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Foreign key onto THIS table (`parent_id → id`) — category trees, comment\n * replies, org charts.\n *\n * No thunk and no type annotation: the target table is the one being declared,\n * so there is nothing to defer and nothing for TypeScript to chase in a circle.\n * Drizzle forces an explicit `(): AnyPgColumn =>` here because its reference\n * always goes through a callback; measured, we do not need one.\n */\n selfReferences(\n column: string,\n opts?: { as?: string; onDelete?: OnDeleteAction },\n ): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'selfReferences');\n this._def.selfRefColumn = column;\n if (opts?.as !== undefined) this._def.refAs = opts.as;\n if (opts?.onDelete !== undefined) this._def.onDeleteAction = opts.onDelete;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E, P, T> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a single-column UNIQUE constraint. */\n unique(): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'unique');\n this._def.unique = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Declare how this column's value is projected in and out of the process.\n *\n * The DDL does not move: `numeric` stays `numeric`, and the driver still hands\n * back what Postgres sent. What changes is the type the row surface exposes —\n * it becomes `Target`:\n *\n * amount: numeric().transform<number>({ fromDb: Number, toDb: String })\n *\n * `numeric` surfacing as `string` is CORRECT (a JS number cannot hold\n * arbitrary precision), and that is exactly why this exists: application code\n * that does arithmetic on the column otherwise rewrites the same\n * `Number(row.amount)` / `String(x)` pair in every controller that touches it,\n * and each rewrite is a place the two directions can drift apart.\n *\n * A transform is a PROJECTION, never a constraint: it lives only in this\n * process, so it can neither validate nor migrate what is stored.\n */\n transform<Target>(fns: ColumnTransform<Target>): ColumnBuilder<K, N, D, E, P, Target> {\n // The cast is the variance, not a shortcut: `toDb` takes `Target`, and a\n // `ColumnTransform<unknown>` would have to accept anything. The stored pair\n // is only ever called with this column's own values.\n this._def.transform = fns as ColumnTransform;\n return new ColumnBuilder<K, N, D, E, P, Target>(this._def.type as K, this._def);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type extractors — imported by Task 2 to derive insert/row shapes.\n// ---------------------------------------------------------------------------\n\n/**\n * Extracts the TypeScript value type for a column, respecting nullability.\n * - \"uuid\" | \"text\" | \"timestamp\" | \"bigint\" | \"numeric\" → string (or string | null when N = true)\n * Note: bigint/numeric surface as string — JS number loses precision past 2^53,\n * and pgx/PostgREST serialize int8/numeric as strings. App code uses\n * BigInt(row.amount) for bigint, or a decimal lib for numeric.\n * - \"integer\" → number\n * - \"boolean\" → boolean\n * - \"jsonb\" → P (the dev-supplied payload shape from jsonb<T>(), else unknown)\n * - \"enum\" → E (the union of literal values)\n *\n * A declared `.transform<T>()` OVERRIDES the table above: the column then\n * surfaces as T (or T | null when nullable), because that is the value the\n * application is handed. Nullability is still the column's, not the\n * transform's — `fromDb` is not called for a NULL.\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<ColumnType, infer N, boolean, unknown, unknown, infer T>\n ? [unknown] extends [T]\n ? ColStoredValue<C>\n : N extends true\n ? T | null\n : T\n : never;\n\n/** The value as the DATABASE hands it over — the branch table above, before any\n * transform. This is what a column's `fromDb` receives. */\ntype ColStoredValue<C> =\n C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? string | null\n : string\n : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number | null\n : number\n : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? boolean | null\n : boolean\n : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P>\n ? N extends true\n ? P | null\n : P\n : C extends ColumnBuilder<'vector', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number[] | null\n : number[]\n : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P>\n ? N extends true\n ? E | null\n : E\n : never;\n\n/**\n * True when a column is optional on INSERT:\n * - nullable columns (N = true) — the DB allows NULL so the field may be omitted\n * - columns with a default (D = true) — the DB fills in the value when absent\n */\nexport type ColIsOptionalOnInsert<C> =\n C extends ColumnBuilder<ColumnType, true, boolean, unknown, unknown, unknown>\n ? true\n : C extends ColumnBuilder<ColumnType, boolean, true, unknown, unknown, unknown>\n ? true\n : false;\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/** Create a UUID column. */\nexport function uuid(): ColumnBuilder<'uuid', false, false, never> {\n return new ColumnBuilder('uuid');\n}\n\n/** Create a TEXT column. */\nexport function text(): ColumnBuilder<'text', false, false, never> {\n return new ColumnBuilder('text');\n}\n\n/** Create an INTEGER column. Emits int4 (max ~2.1B). */\nexport function integer(): ColumnBuilder<'integer', false, false, never> {\n return new ColumnBuilder('integer');\n}\n\n/**\n * Create a BIGINT column (Postgres int8, max ~9.2×10^18).\n * Surfaces as `string` in row/insert types — JS number loses precision past 2^53\n * and pgx/PostgREST serialize int8 as a JSON string. Use BigInt(row.column) in app code.\n */\nexport function bigint(): ColumnBuilder<'bigint', false, false, never> {\n return new ColumnBuilder('bigint');\n}\n\n/**\n * Create a NUMERIC column (Postgres `numeric`/`decimal`, arbitrary precision).\n * For exact fractional values (money with cents as a decimal, rates, weights)\n * where int4/int8 don't fit. Surfaces as `string` in row/insert types — JS\n * number can't hold arbitrary-precision decimals without rounding, and\n * pgx/PostgREST serialize numeric as a JSON string. Parse with a decimal lib\n * (or BigInt for scaled integers) in app code.\n */\nexport function numeric(): ColumnBuilder<'numeric', false, false, never> {\n return new ColumnBuilder('numeric');\n}\n\n/** Create a BOOLEAN column. */\nexport function boolean(): ColumnBuilder<'boolean', false, false, never> {\n return new ColumnBuilder('boolean');\n}\n\n/** Create a TIMESTAMP column. */\nexport function timestamp(): ColumnBuilder<'timestamp', false, false, never> {\n return new ColumnBuilder('timestamp');\n}\n\n/**\n * Create a JSONB column. Pass a payload type to make the generated row/insert\n * type concrete instead of `unknown`:\n *\n * tags: jsonb<string[]>() // row.tags: string[]\n * meta: jsonb<{ tier: string }>() // row.meta: { tier: string }\n * raw: jsonb() // row.raw: unknown (back-compat)\n *\n * The runtime accepts a plain JS object/array directly (no JSON.stringify); the\n * generic only refines the TYPE the env codegen emits.\n */\nexport function jsonb<T = unknown>(): ColumnBuilder<'jsonb', false, false, never, T> {\n return new ColumnBuilder('jsonb');\n}\n\n/**\n * Create an ENUM column.\n * @param name The PostgreSQL enum type name (used in DDL).\n * @param values A readonly tuple of valid string values — kept `const` so the\n * union `V[number]` is as narrow as possible.\n */\nexport function enumType<const V extends readonly string[]>(\n name: string,\n values: V,\n): ColumnBuilder<'enum', false, false, V[number]> {\n const builder = new ColumnBuilder<'enum', false, false, V[number]>('enum');\n builder._def.enumName = name;\n builder._def.enumValues = [...values];\n return builder;\n}\n\n/** vector(n) — pgvector kolonu. n TİPİN parçasıdır (typmod) ve [1, 2000] —\n * 2000 = pgvector'ün HNSW-indekslenebilir tavanı; auto-index bu beyanla bağlı\n * (spec FR-001, D-3). */\nexport function vector(dimensions: number): ColumnBuilder<'vector', false, false, unknown, number[]> {\n if (!Number.isInteger(dimensions) || dimensions < 1 || dimensions > 2000) {\n throw new Error(`vector(): dimensions must be an integer in [1, 2000], got ${String(dimensions)}`);\n }\n const b = new ColumnBuilder('vector') as ColumnBuilder<'vector', false, false, unknown, number[]>;\n (b._def as { dimensions?: number }).dimensions = dimensions;\n return b;\n}\n\n/**\n * Any column, whatever its type parameters.\n *\n * Exported so a cycle can be broken from ONE side:\n * `references((): AnyColumn => y.id)`.\n */\nexport type AnyColumn = ColumnBuilder;\n\n/**\n * The column that OWNS this row: a `text` FK onto `auth.users(id)`, NOT NULL,\n * ON DELETE CASCADE.\n *\n * Ownership drives account erasure, so cascade is the only correct action and\n * takes no argument. The referencing column must be `text` (palauth ids are\n * `usr_<uuid>`) and NOT NULL — both are implied here rather than left to the\n * caller, so three rules the type could not express before become UNWRITABLE.\n *\n * At most ONE per table. The old shape let several columns reference\n * `auth.users` and picked the FIRST IN DECLARATION ORDER as the owner — moving a\n * `created_by` above a `user_id` silently changed which rows an account deletion\n * took with it. A second one is now rejected at push.\n *\n * For a column that merely POINTS at a user without owning the row\n * (`created_by`, `edited_by`), use `userRef({ onDelete })`.\n */\nexport function ownedByUser(): ColumnBuilder<'text', false, false, never> {\n const b = new ColumnBuilder<'text', false, false, never>('text');\n b._def.nullable = false;\n b._def.references = { table: 'auth.users', column: 'id' };\n b._def.onDeleteAction = 'cascade';\n b._def.owns = true;\n return b;\n}\n\n/**\n * A plain FK onto `auth.users(id)` that does NOT own the row.\n *\n * `created_by` / `edited_by`: deleting that user must not delete the row. ON\n * DELETE is required and limited to `cascade | set null` so an erasure request\n * is never blocked by a lingering FK; `set null` needs a nullable column.\n */\nexport function userRef(opts: { onDelete: AuthUserOnDelete; as?: string }): ColumnBuilder<'text', boolean, false, never> {\n const b = new ColumnBuilder<'text', boolean, false, never>('text');\n b._def.references = { table: 'auth.users', column: 'id' };\n b._def.onDeleteAction = opts.onDelete;\n if (opts.as !== undefined) b._def.refAs = opts.as;\n return b;\n}\n\n/**\n * A plain FK onto `auth.installations(id)` — the app-scoped verified-device\n * anchor.\n *\n * An installation is an APP INSTALL, not a user: this is NOT ownership. A\n * user-owned row still needs its own `ownedByUser()` so account erasure removes\n * it; an installation reference alone does not tie a row to a user's deletion.\n */\nexport function installationRef(opts: { onDelete: AuthUserOnDelete; as?: string }): ColumnBuilder<'text', boolean, false, never> {\n const b = new ColumnBuilder<'text', boolean, false, never>('text');\n b._def.references = { table: 'auth.installations', column: 'id' };\n b._def.onDeleteAction = opts.onDelete;\n if (opts.as !== undefined) b._def.refAs = opts.as;\n return b;\n}\n","/**\n * A named raw-SQL DDL object declared in db/schema.ts for anything the typed DSL\n * cannot express (EXCLUDE, CHECK, partial/expression indexes, triggers, views).\n * The deploy emits `up` verbatim on the privileged DDL connection — same trust\n * posture as policy().using(). Tracked by NAME (not by diffing the body), so a\n * changed body needs a new name or an explicit drop+add.\n */\nexport interface RawConstraintDef {\n name: string;\n up: string;\n down?: string;\n}\n\nexport function raw(name: string, up: string, opts?: { down?: string }): RawConstraintDef {\n return { name, up, ...(opts?.down != null ? { down: opts.down } : {}) };\n}\n","/** Embedding sağlayıcı DESKRIPTORU — canlı istemci değil, düz veri: şemayla\n * birlikte serileşir, çağrıyı Go worker (yazma) ve engine (sorgu) yapar.\n * Adlandırma Vercel AI SDK'nın aynasıdır (openai.embedding(\"...\")) ama paket\n * bağımlılığı bilinçli olarak YOKTUR (spec C-3, UD-016). v1 sağlayıcı: openai (D-10). */\nexport interface EmbeddingModelRef {\n provider: \"openai\";\n model: string;\n dimensions?: number;\n apiKeyName?: string;\n baseURL?: string;\n}\n/** Chat/damıtma modeli DESKRIPTORU (C-11, D-019) — memory beyanının extract'i.\n * Embedding gibi düz veridir; çağrıyı worker yapar, anahtar vault'taki\n * OPENAI_API_KEY'dir (D-017: aynı sağlayıcı, yeni dış sistem yok). */\nexport interface ChatModelRef {\n provider: \"openai\";\n model: string;\n}\nexport const openai = {\n embedding(\n model: string,\n opts?: { dimensions?: number; apiKeyName?: string; baseURL?: string },\n ): EmbeddingModelRef {\n return { provider: \"openai\", model, apiKeyName: opts?.apiKeyName ?? \"OPENAI_API_KEY\",\n ...(opts?.dimensions !== undefined ? { dimensions: opts.dimensions } : {}),\n ...(opts?.baseURL !== undefined ? { baseURL: opts.baseURL } : {}) };\n },\n chat(model: string): ChatModelRef {\n return { provider: \"openai\", model };\n },\n};\n","/**\n * typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.\n *\n * Derives INSERT and full-row TypeScript types from a `defineSchema()` result\n * and wraps the untyped runtime `DBClient` with a typed facade.\n *\n * No value-any. No `as unknown as X`. The two narrow `as` casts in\n * `makeTypedTable` are safe because:\n * - `data as Record<string, unknown>`: InsertShape<T> maps string keys to\n * typed values; all value types are subsets of `unknown`, so the cast is\n * structurally sound.\n * - `result as RowShape<T>`: The runtime DBClient returns `Record<string,\n * unknown>` which is the erased form of the typed row; we're narrowing back\n * to the precise shape that the schema declared.\n * Both casts are narrowing only (not widening) and correctness is guaranteed\n * by the schema the caller provides.\n */\n\nimport type { ColValue, ColIsOptionalOnInsert, ColumnBuilder } from \"./columns.js\";\nimport type { TableDef, SchemaDef } from \"./schema.js\";\nimport type { Tables, Schemas, TableTypes } from \"./env.js\";\nimport type { DBClient, DBOps } from \"../endpoint.js\";\nimport type { Materialized, TxPlanHandle, TxTable } from \"./tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./tx-plan.js\";\n\n// ---------------------------------------------------------------------------\n// Key discriminators — split a column map into required vs optional keys.\n// ---------------------------------------------------------------------------\n\n/** Keys of C whose columns are required on INSERT (not nullable, no default). */\ntype RequiredKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;\n}[keyof C];\n\n/** Keys of C whose columns are optional on INSERT (nullable or has a default). */\ntype OptionalKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;\n}[keyof C];\n\n// ---------------------------------------------------------------------------\n// Public shape types — exported so callers can reference them directly.\n// ---------------------------------------------------------------------------\n\n/**\n * The TypeScript type for an INSERT payload for table `T`.\n * - Required: columns that are NOT NULL and have no DB-level default.\n * - Optional: columns that are nullable or carry a default.\n *\n * When all columns are optional, `RequiredKeys<C>` resolves to `never` and\n * the first part becomes `{}`, which is a neutral element for `&`.\n */\nexport type InsertShape<T extends TableDef> = {\n [K in RequiredKeys<T[\"columns\"]>]: ColValue<T[\"columns\"][K]>;\n} & {\n [K in OptionalKeys<T[\"columns\"]>]?: ColValue<T[\"columns\"][K]>;\n};\n\n/**\n * The TypeScript type for a full row returned by the DB for table `T`.\n * Every column is present; nullable columns resolve to `T | null`.\n */\nexport type RowShape<T extends TableDef> = {\n [K in keyof T[\"columns\"]]: ColValue<T[\"columns\"][K]>;\n};\n\n// ---------------------------------------------------------------------------\n// TypedTable + TypedDB interfaces.\n// ---------------------------------------------------------------------------\n\n/** A typed table accessor that mirrors the runtime DBClient surface. */\nexport interface TypedTable<T extends TableDef> {\n insert(data: InsertShape<T>): Promise<RowShape<T>>;\n upsert(data: InsertShape<T>, opts: { onConflict: readonly string[] }): Promise<RowShape<T>>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T> | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<RowShape<T> | null>;\n /** Rows matching the filter. Operators, ordering and paging are the ENGINE's\n * surface — this declaration is what makes them callable. */\n findMany(\n query?: WhereFilter<RowShape<T>>,\n opts?: FindManyOpts<RowShape<T>>,\n ): Promise<RowShape<T>[]>;\n /** Update every matching row in one statement; an empty filter is refused. */\n updateMany(\n where: WhereFilter<RowShape<T>>,\n set: Partial<InsertShape<T>>,\n ): Promise<RowShape<T>[]>;\n /** Delete every matching row; resolves to how many. Empty filter refused. */\n deleteMany(where: WhereFilter<RowShape<T>>): Promise<number>;\n /** How many rows match. An empty filter is legitimate: counting is a read. */\n count(where?: WhereFilter<RowShape<T>>): Promise<number>;\n}\n\n/** A typed DB facade covering all tables declared in schema `S`. */\nexport interface TypedDB<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n /** Run a transaction plan. See {@link EnvTypedDatabase.transaction}. */\n transaction<T>(\n fn: (tx: TypedTx<S>) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>>;\n}\n\n/** The plan-building handle a `TypedDB<S>` transaction callback receives: the\n * schema's tables, expressed as plan operations rather than awaited calls. */\nexport type TypedTx<S extends SchemaDef> = TxPlanHandle<{\n [K in keyof S[\"tables\"]]: TxTable<RowShape<S[\"tables\"][K]>, InsertShape<S[\"tables\"][K]>>;\n}>;\n\n// ---------------------------------------------------------------------------\n// Runtime factory.\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a typed table accessor that delegates every call to `raw` using the\n * runtime table name string. Two narrow `as` casts bridge the mapped-type\n * shapes to/from `Record<string, unknown>` — see module-level doc comment.\n *\n * The `raw` param is typed `DBOps` (the six string-keyed ops) because this only\n * ever calls those — never `txPlan`, which builds its own operations rather than\n * delegating to these.\n */\nfunction makeTypedTable<T extends TableDef<Record<string, ColumnBuilder>>>(\n name: string,\n raw: DBOps,\n): TypedTable<T> {\n return {\n insert: (data: InsertShape<T>) =>\n raw.insert(name, data as Record<string, unknown>) as Promise<RowShape<T>>,\n\n upsert: (data: InsertShape<T>, opts: { onConflict: readonly string[] }) =>\n raw.upsert(name, data as Record<string, unknown>, opts) as Promise<RowShape<T>>,\n\n update: (id: string, data: Partial<InsertShape<T>>) =>\n raw.update(name, id, data as Record<string, unknown>) as Promise<RowShape<T> | null>,\n\n delete: (id: string) => raw.delete(name, id),\n\n findById: (id: string) =>\n raw.findById(name, id) as Promise<RowShape<T> | null>,\n\n findMany: (query?: WhereFilter<RowShape<T>>, opts?: FindManyOpts<RowShape<T>>) =>\n raw.findMany(name, query as Record<string, unknown> | undefined, opts) as Promise<RowShape<T>[]>,\n\n updateMany: (where: WhereFilter<RowShape<T>>, set: Partial<InsertShape<T>>) =>\n raw.updateMany(\n name,\n where as Record<string, unknown>,\n set as Record<string, unknown>,\n ) as Promise<RowShape<T>[]>,\n\n deleteMany: (where: WhereFilter<RowShape<T>>) =>\n raw.deleteMany(name, where as Record<string, unknown>),\n\n count: (where?: WhereFilter<RowShape<T>>) =>\n raw.count(name, where as Record<string, unknown> | undefined),\n };\n}\n\n/**\n * Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from\n * the provided schema. No behavior change for the direct ops — all calls\n * delegate to `raw` with the table name as a plain string.\n *\n * `transaction` does NOT delegate to a per-op client: the callback describes a\n * plan against a fresh {@link TxPlanBuilder}, and the whole plan travels in one\n * `raw.txPlan` call. The schema is used only for its table NAMES; the values\n * are typed by `S` at compile time and are plain strings at run time.\n *\n * The `as` casts are single structural narrowings from a dynamically-built\n * object to the precise mapped type (TS cannot infer the mapped-type result\n * through `Object.keys` iteration) — see the module-level doc comment.\n */\nexport function makeTypedDB<S extends SchemaDef>(\n schema: S,\n raw: DBClient,\n): TypedDB<S> {\n const tables = {} as Record<string, TypedTable<TableDef>>;\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) {\n tables[key] = makeTypedTable(tableDef.name, raw);\n }\n }\n\n const result = {\n tables,\n transaction<T>(\n fn: (tx: TypedTx<S>) => T extends Promise<unknown> ? never : T,\n ): Promise<Materialized<T>> {\n const builder = new TxPlanBuilder();\n const planTables: Record<string, unknown> = {};\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) planTables[key] = builder.table(tableDef.name);\n }\n // Two narrowings at the same seam: the plan tables are built by NAME, so\n // TS cannot see the mapped type through the loop, and the driver erases\n // the callback's return type (see runTxPlan's doc). Both are the erasure\n // this facade exists to undo.\n return runTxPlan(\n raw,\n planTables as TypedTx<S>[\"tables\"],\n builder,\n fn,\n ) as Promise<Materialized<T>>;\n },\n };\n\n // Narrow cast: `result.tables` is structurally identical to\n // TypedDB<S>[\"tables\"] — each key maps to a TypedTable for the matching\n // TableDef. TS cannot infer the mapped-type result through Object.keys\n // iteration, so a single `as` bridges the gap.\n return result as TypedDB<S>;\n}\n\n// ---------------------------------------------------------------------------\n// Env-augmentation-driven typed surface — the typed-by-default `Database`.\n//\n// These types read the globally-augmented `Tables` interface from\n// `@palbase/backend/env` (filled by the generated `palbase-env.d.ts`). They\n// back `Database.tables.<name>` so handler code is typed with no import and no\n// generic (C5). They DELIBERATELY do not reference `ColumnBuilder` — the env\n// `Tables` interface carries flat `row`/`insert` object types.\n// ---------------------------------------------------------------------------\n\n/** Bir where değeri: düz eşitlik YA DA operatör nesnesi (FR-016). */\nexport type WhereOp<V> = V | { gt?: V; gte?: V; lt?: V; lte?: V; neq?: V; in?: V[] };\n\n/**\n * A filter over a row: every field optional, each one a plain value (equality)\n * or an operator object. THE filter language — `findMany`, `updateMany`,\n * `deleteMany` and `count` all take this one, because two spellings of a filter\n * is how the two come to disagree.\n */\nexport type WhereFilter<Row> = { [K in keyof Row]?: WhereOp<Row[K]> };\n\n/**\n * Ordering and paging for a read.\n *\n * `column` is `keyof Row`, not `string`: a mistyped column name is a compile\n * error here rather than a runtime rejection three layers down. `offset`\n * without `limit` is refused by the engine — a page with no size is not a page.\n */\nexport type FindManyOpts<Row> = {\n orderBy?: { column: Extract<keyof Row, string>; direction?: \"asc\" | \"desc\" };\n limit?: number;\n offset?: number;\n};\n\n/** search() parametreleri, satır tipiyle koşullanmış (FR-013). `offset` BİLEREK yok (UD-013). */\nexport interface SearchParamsTyped<T extends TableTypes> {\n /** Metin sorgusu: FTS kolunu besler; embed beyanlıysa sorgu vektörü de bundan üretilir. */\n query?: string;\n /** Hazır sorgu vektörü — verilirse embed çağrısı olmaz (FR-025). */\n vector?: number[];\n where?: { [K in keyof T[\"row\"]]?: WhereOp<T[\"row\"][K]> };\n /** default 20, tavan 100 (engine uygular). */\n limit?: number;\n /** Birden çok vektör kolonunda hedef seçimi (model geçişi, FR-013/using). */\n using?: string;\n mode?: \"hybrid\" | \"text\" | \"vector\";\n /** Nihai (RRF-sonrası) skor alt eşiği — süzme LIMIT'ten önce uygulanır (FR-001). */\n minScore?: number;\n /** Chunk-modunda satır başına en iyi blok sayısı (1..10, vars. 3; FR-015). */\n blocksPerRow?: number;\n /** Tazelik çürümesi: nihai skor RRF-sonrası exp(-ln(2)*yaş/halfLife) ile çarpılır;\n * field bir timestamp kolonu, halfLife \"90s\" | \"15m\" | \"12h\" | \"30d\" biçiminde (FR-004). */\n recency?: { field: Extract<keyof T[\"row\"], string>; halfLife: string };\n /** Filtrelenmiş küme üzerinde kolon başına top-20 değer sayacı — dönüş\n * dizisinin `_facets` özelliği (FR-027). */\n facets?: Extract<keyof T[\"row\"], string>[];\n /** Satır-modunda FTS eşleşme vurgusu: sonuç satırına `_highlight` ekler;\n * chunk-modda no-op — bloklar zaten eşleşen kesittir (FR-025). */\n highlight?: boolean;\n /** Validity'li tabloda zaman penceresi: varsayılan yalnız güncel versiyon;\n * \"all\" tüm versiyonlar; {asOf} o anda geçerli olan (FR-029). */\n validity?: \"all\" | { asOf: string };\n /** Alan-boost (FR-030): skor * (1 + w·x/(1+x)) — sayısal kolonla sınırlı\n * çarpan, dış servissiz; bileşim RRF → boost → recency → minScore. */\n boost?: { field: Extract<keyof T[\"row\"], string>; weight: number };\n}\n\n/** search() dönüş dizisinin sorgu-düzeyi ekleri (FR-027): `_facets` dizinin\n * ÖZELLİĞİDİR, satırlara kopyalanmaz (JSON'a satır başına şişme olmasın). */\nexport type SearchFacets = Record<string, { value: string | null; count: number }[]>;\n\n/** similar()/recommend() taşıyıcı opsiyonları (T018, FR-022): search'ün\n * paramlarından query/vector/mode düşer — hedef vektörü metodun kendisi\n * DB'den kurar; facets/highlight de düşer (T020) — engine bu ikisini\n * similar/recommend'e geçirmez, tip vaadi gerçekle aynı kalır. */\nexport type SimilarParamsTyped<T extends TableTypes> = Omit<\n SearchParamsTyped<T>,\n \"query\" | \"vector\" | \"mode\" | \"facets\" | \"highlight\"\n>;\n\n/** recommend() parametreleri (T018, FR-023). */\nexport type RecommendParamsTyped<T extends TableTypes> = SimilarParamsTyped<T> & {\n /** Kaynak beğeniler — hedef vektör bunların DB-içi avg'ı; boş olamaz. */\n positive: string[];\n /** İtilen örnekler — hedef pos.v + (pos.v - neg.v) ile yönlenir. */\n negative?: string[];\n};\n\n/** Temel tablo erişimcisi — search'süz beş op. */\nexport interface EnvTypedTableBase<T extends TableTypes> {\n insert(data: T[\"insert\"]): Promise<T[\"row\"]>;\n /**\n * Insert the row, or update it when it collides on `onConflict`.\n *\n * The conflict columns must carry a unique constraint or index — that is what\n * Postgres matches on — and they are excluded from the update, since they are\n * what matched.\n */\n upsert(data: T[\"insert\"], opts: { onConflict: readonly Extract<keyof T[\"row\"], string>[] }): Promise<T[\"row\"]>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<T[\"insert\"]>): Promise<T[\"row\"] | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<T[\"row\"] | null>;\n /** Rows matching the filter. See {@link WhereFilter} / {@link FindManyOpts} —\n * this declaration is what makes the engine's operators callable. */\n findMany(\n query?: WhereFilter<T[\"row\"]>,\n opts?: FindManyOpts<T[\"row\"]>,\n ): Promise<T[\"row\"][]>;\n /** Update every matching row in one statement; an empty filter is refused. */\n updateMany(where: WhereFilter<T[\"row\"]>, set: Partial<T[\"insert\"]>): Promise<T[\"row\"][]>;\n /** Delete every matching row; resolves to how many. Empty filter refused. */\n deleteMany(where: WhereFilter<T[\"row\"]>): Promise<number>;\n /** How many rows match. An empty filter is legitimate: counting is a read. */\n count(where?: WhereFilter<T[\"row\"]>): Promise<number>;\n /** Validity'li tabloda satırın yeni versiyonu (FR-029, C-9): eski satır\n * kapanır (valid_to/superseded_by), yenisi TEK savepoint'te eklenir; dönüş\n * yeni satır. Validity beyanı olmayan tabloda adlandırılmış çalışma-zamanı\n * hatası — tip düzeyinde ayrım env `Tables` bayrağı taşımadığından yapılamaz. */\n supersede(id: string, row: T[\"insert\"]): Promise<T[\"row\"]>;\n}\n\n/** Tablo erişimcisi: env girdisi `searchable: true` taşıyorsa (vector kolonu ya da\n * search beyanı — env-gen üretir) `search()` üyesi VARDIR; yoksa üye hiç yoktur ve\n * çağrı derleme hatasıdır (FR-013). Yapısal koşul TableTypes'ı genişletmeden çalışır. */\nexport type EnvTypedTable<T extends TableTypes> = EnvTypedTableBase<T> &\n (T extends { searchable: true }\n ? {\n search(\n params: SearchParamsTyped<T>,\n ): Promise<Array<T[\"row\"] & { _score: number }> & { _facets?: SearchFacets }>;\n /** \"Bu satıra benzeyenler\" (FR-022): hedef vektör DB'den okunur,\n * kaynak satır sonuçta yoktur; id yoksa adlandırılmış hata. */\n similar(id: string, params?: SimilarParamsTyped<T>): Promise<Array<T[\"row\"] & { _score: number }>>;\n /** D-021: sayaçlar bağımsız dönüşle — search'ün dizi-üstü _facets'i\n * JSON.stringify'da kaybolur; ciddi sözleşme budur. */\n facets(params: { facets: Array<keyof T[\"row\"] & string>; where?: Partial<T[\"row\"]>; validity?: \"all\" | { asOf: string } }): Promise<Record<string, { value: string | null; count: number }[]>>;\n /** positive/negative beğenilerden öneri (FR-023): hedef vektör DB-içi\n * avg CTE'leriyle; kaynak id'ler sonuçta yoktur. */\n recommend(params: RecommendParamsTyped<T>): Promise<Array<T[\"row\"] & { _score: number }>>;\n }\n : Record<never, never>);\n\n/** The `tables` map exposed on `Database`/`tx`, keyed by the env `Tables`\n * interface. When no schema is declared `Tables` is empty, so `tables` is an\n * empty object — accessing `.tables.foo` is then a compile error (no member). */\nexport type EnvTables = {\n [K in keyof Tables]: EnvTypedTable<Tables[K]>;\n};\n\n/**\n * The project's NON-public schemas, keyed by schema name, each exposing its own\n * `tables` map — the shape `Database.schema(\"billing\")` returns.\n *\n * The intermediate `tables` is there for the reason {@link EnvTables} sits under\n * `.tables`: a schema's table names must not share a namespace with anything the\n * accessor itself might grow.\n *\n * Empty by default. The generated `palbase-env.d.ts` augments `Schemas` with one\n * member per declared schema other than `public`, so a project that declares\n * none has `keyof Schemas = never` and every `schema(...)` call is a compile\n * error rather than a runtime surprise.\n */\nexport type EnvSchemas = {\n [S in keyof Schemas]: {\n tables: {\n [T in keyof Schemas[S]]: EnvTypedTable<Extract<Schemas[S][T], TableTypes>>;\n };\n };\n};\n\n/** The project's tables as PLAN operations, keyed by the env `Tables`\n * interface. The transaction twin of {@link EnvTables}. */\nexport type TxTables = {\n [K in keyof Tables]: TxTable<Tables[K][\"row\"], Tables[K][\"insert\"]>;\n};\n\n/**\n * The handle a `Database.transaction(…)` callback receives.\n *\n * Tables only — no `query`, no `findById`, no `asService`. A read whose value\n * the plan does not write belongs outside the transaction, where it costs one\n * round trip and is an ordinary value you can branch on.\n */\nexport type TxPlan = TxPlanHandle<TxTables>;\n\n/**\n * The RLS-bypass sibling returned by `Database.asService()`. Same typed surface\n * as {@link EnvTypedDatabase} — `tables`, the raw string ops, and a typed\n * `transaction` — but it does NOT re-expose `asService` (no double-bypass).\n * Every op it performs runs as the `service_role` (BYPASSRLS).\n */\nexport interface EnvServiceDatabase extends Omit<DBClient, \"txPlan\" | \"asService\"> {\n tables: EnvTables;\n /** See {@link EnvTypedDatabase.schema}. The bypass sibling reaches every\n * schema the default surface does — a `billing` table is no less reachable\n * because the caller asked to run as the service role. */\n schema<S extends keyof Schemas>(name: S): EnvSchemas[S];\n transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;\n}\n\n/**\n * The typed-by-default Database surface: the raw string-keyed `DBClient` ops\n * PLUS a `tables` map typed against the project's generated `palbase-env.d.ts`,\n * a `transaction` that runs a whole plan in one request, and `asService()` for\n * the explicit RLS-bypass sibling.\n *\n * The low-level `txPlan` op is deliberately NOT re-exposed here: `transaction`\n * is the surface, and a hand-built plan would bypass the ref/guard machinery\n * that makes one safe to write.\n */\nexport interface EnvTypedDatabase extends Omit<DBClient, \"txPlan\" | \"asService\"> {\n tables: EnvTables;\n /**\n * The tables of a schema other than `public`.\n *\n * `Database.tables.*` is the PUBLIC schema and only the public schema. Two\n * schemas may declare the same table name — `public.invoices` and\n * `billing.invoices` are different tables — so one flat namespace would make\n * `Database.tables.invoices` resolve by declaration order. It does not: the\n * bare name is always public's, and everything else is asked for by schema.\n *\n * The name is `keyof Schemas`, so a schema the project never declared is a\n * compile error. On the wire the table travels schema-qualified\n * (`billing.invoices`); `public` stays bare.\n *\n * Declaring a schema does not publish it — reachability over HTTP is the\n * schema's own `exposed` flag, checked by the broker.\n *\n * @example\n * const inv = await Database.schema(\"billing\").tables.invoices.findById(id);\n */\n schema<S extends keyof Schemas>(name: S): EnvSchemas[S];\n /**\n * Run a transaction. The callback DESCRIBES the operations; the whole\n * description travels in one request and the broker runs it inside a single\n * transaction — committing when it finishes, rolling back on any failure.\n *\n * The callback is SYNCHRONOUS: nothing has run when it returns, so there is\n * nothing to await. `async` on it and `await` inside it are compile errors.\n * Values a later operation needs are {@link Ref}s, written straight into the\n * next operation; values the CALLER needs are returned and substituted before\n * this promise resolves.\n *\n * @example\n * const { statementId } = await Database.transaction((tx) => {\n * const st = tx.tables.statements\n * .insert({ household_id: hid, file_sha256: sha, status: \"reviewing\" })\n * .expectOne(new Internal(\"statement insert failed\"));\n *\n * tx.tables.statement_lines.insertMany(\n * lines.map((l) => ({ statement_id: st.id, category: resolveCategory(l) })),\n * );\n *\n * return { statementId: st.id };\n * });\n */\n transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;\n /**\n * Run `fn` inside a SAVEPOINT, so a write that fails in it does not poison the\n * rest of the request.\n *\n * A request is ONE Postgres transaction: a failed statement aborts it and\n * every later one answers `current transaction is aborted`. That is why\n * \"insert, catch the unique violation, update instead\" cannot be written\n * directly — and why {@link EnvTypedTableBase.upsert} exists for the common\n * case. Reach for `attempt` when the recovery is not an upsert.\n *\n * The handle is a parameter, not the ambient `Database`: only what `tx` writes\n * is inside the boundary, so a concurrent branch of the same request cannot be\n * rolled back by someone else's failure.\n *\n * @example\n * const claimed = await Database.attempt(async (tx) => {\n * await tx.insert(\"seats\", { row: 4, seat: 12, user_id: user.id });\n * return true;\n * }).catch(() => false);\n */\n attempt<T>(fn: (tx: Omit<DBClient, \"attempt\" | \"txPlan\" | \"asService\">) => Promise<T>): Promise<T>;\n /**\n * Return a sibling that bypasses RLS by running as the `service_role`. Use\n * sparingly and explicitly — the default `Database.*` path is RLS-enforced.\n *\n * @example\n * const all = await Database.asService().tables.todos.findMany({});\n * const rows = await Database.asService().query(\"SELECT * FROM todos\");\n */\n asService(): EnvServiceDatabase;\n}\n","/**\n * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`\n * result.\n *\n * The CLI (`palbase build`) and the deploy pipeline call\n * {@link makeEnvDts} with the project's schema and write the returned string to\n * `palbase-env.d.ts` at the project root. That file AUGMENTS the\n * `@palbase/backend/env` `Tables` interface (controlled global augmentation,\n * C5) so `Database.tables.<name>` is typed with no import and no generic.\n *\n * The output is FLAT: each table gets a `{ row: {...}; insert: {...} }` entry\n * with plain TypeScript object types. The phantom `ColumnBuilder<...>` type\n * NEVER appears in the generated `.d.ts` — that type only lives at authoring\n * time inside `db/schema.ts`.\n */\n\nimport type { ColumnDef } from \"./columns.js\";\nimport type { SchemaDef, TableDef } from \"./schema.js\";\n\n/** The TypeScript value type for a column, ignoring nullability (added by the\n * caller). Mirrors the `ColValue` mapped type in columns.ts exactly. */\nfunction baseTsType(def: ColumnDef): string {\n switch (def.type) {\n case \"uuid\":\n case \"text\":\n case \"timestamp\":\n return \"string\";\n case \"integer\":\n return \"number\";\n // Both are exact-precision in Postgres and lossy as a JSON number, so the\n // database proxy serializes them as strings — measured: 9007199254740993\n // used to arrive as ...992 and 41.00821234567890123 as 41.0082123456789.\n // numeric had no case at all and fell through to `unknown`, which typed\n // every numeric column out of existence.\n case \"bigint\":\n case \"numeric\":\n return \"string\";\n case \"boolean\":\n return \"boolean\";\n case \"jsonb\":\n return \"unknown\";\n // FR-008: the authoring type of a pgvector column. The default `unknown`\n // branch below STAYS — an unknown wire type is refused on the Go side\n // (FR-005), never papered over here.\n case \"vector\":\n return \"number[]\";\n case \"enum\": {\n const values = def.enumValues ?? [];\n if (values.length === 0) return \"string\";\n return values.map((v) => JSON.stringify(v)).join(\" | \");\n }\n default:\n return \"unknown\";\n }\n}\n\n/** The full row type for a column: base type, `| null` when nullable. */\nfunction rowType(def: ColumnDef): string {\n const base = baseTsType(def);\n return def.nullable ? `${base} | null` : base;\n}\n\n/** True when a column may be omitted on INSERT — nullable OR has any default.\n * Mirrors `ColIsOptionalOnInsert` in columns.ts. */\nfunction optionalOnInsert(def: ColumnDef): boolean {\n return (\n def.nullable === true ||\n def.defaultRandom === true ||\n def.defaultNow === true ||\n def.defaultValue !== undefined\n );\n}\n\n\n\nexport type Relation = {\n name: string;\n to: string;\n kind: \"one\" | \"many\";\n /**\n * The foreign-key COLUMN the relation runs through.\n *\n * Without it \"there is a relation\" is half the fact, and everything that\n * consumes the map — the query builder, the seed engine, the cross-boundary\n * lock — has to re-derive the column: a second interpreter of the same graph.\n */\n via: string;\n};\n\n/** `list_id` → `list`; anything else keeps its column name. */\nfunction forwardName(column: string): string {\n return column.endsWith(\"_id\") ? column.slice(0, -3) : column;\n}\n\n/** Bare for public, schema-qualified otherwise — the convention RefJSON already uses. */\nfunction qualify(schemaName: string, tableName: string): string {\n return schemaName === \"public\" ? tableName : `${schemaName}.${tableName}`;\n}\n\n/**\n * Derive the relation graph from the declared foreign keys.\n *\n * Until now a SECOND foreign key onto the same parent was silently dropped: only\n * the first column in declaration order was recorded, and the other one quietly\n * became an ordinary writable column. Which relation you got was decided by the\n * order somebody happened to type the columns in. That silence is what this\n * function exists to end — ambiguity is rejected and named, never resolved by\n * declaration order.\n */\nexport function buildRelations(schemas: readonly SchemaDef[]): Map<string, Relation[]> {\n const out = new Map<string, Relation[]>();\n const keyOf = new Map<string, string>(); // bare table name → its qualified key\n for (const schema of schemas) {\n for (const t of Object.values(schema.tables)) {\n const key = qualify(schema.name, t.name);\n out.set(key, []);\n keyOf.set(t.name, key);\n }\n }\n\n for (const schema of schemas) {\n for (const table of Object.values(schema.tables)) {\n const childKey = qualify(schema.name, table.name);\n const bucket = out.get(childKey);\n if (bucket === undefined) continue;\n\n // Ambiguity first: several FKs onto one target, none of them named.\n const byTarget = new Map<string, string[]>();\n for (const [col, builder] of Object.entries(table.columns)) {\n const ref = builder._def.references;\n if (ref === undefined) continue;\n const list = byTarget.get(ref.table) ?? [];\n list.push(col);\n byTarget.set(ref.table, list);\n }\n for (const [target, cols] of byTarget) {\n if (cols.length < 2) continue;\n const unnamed = cols.filter((c) => {\n const d = table.columns[c]?._def;\n return d?.refAs === undefined && d?.owns !== true;\n });\n if (unnamed.length > 0) {\n throw new Error(\n `table \"${table.name}\" declares ${cols.length} foreign keys onto \"${target}\" (${cols.join(\", \")}) — name each one: references(() => …, { as: \"…\" })`,\n );\n }\n }\n\n for (const [col, builder] of Object.entries(table.columns)) {\n const def = builder._def;\n if (def.references === undefined) continue;\n const name = def.owns === true ? \"owner\" : (def.refAs ?? forwardName(col));\n if (bucket.some((r) => r.name === name)) {\n throw new Error(\n name === \"owner\"\n ? `table \"${table.name}\": two columns claim ownership of the row — a table has at most ONE ownedByUser(). If the other column only POINTS at a user, declare it userRef({ onDelete: … }) instead.`\n : `table \"${table.name}\": two relations resolve to the name \"${name}\" — give one an explicit { as: \"…\" }`,\n );\n }\n const targetKey = keyOf.get(def.references.table) ?? def.references.table;\n bucket.push({ name, to: targetKey, kind: \"one\", via: col });\n\n // Reverse edge, unless the FK points outside the declared schemas (auth.users)\n // or back at the declaring table (a self-reference has no separate parent).\n const parent = out.get(targetKey);\n if (parent === undefined || targetKey === childKey) continue;\n const reverse = def.refAs ?? table.name;\n if (parent.some((r) => r.name === reverse)) {\n throw new Error(\n `table \"${def.references.table}\": two reverse relations resolve to the name \"${reverse}\" — give one an explicit { as: \"…\" }`,\n );\n }\n parent.push({ name: reverse, to: childKey, kind: \"many\", via: col });\n }\n }\n }\n return out;\n}\n\n\n\n\n/** Emit the `row` / `insert` / `relations` blocks for one table at the given\n * base indentation. */\nfunction tableBlock(table: TableDef, relations: Relation[], indent: string): string {\n const cols = Object.entries(table.columns);\n const rowLines = cols.map(([col, builder]) => {\n return `${indent} ${col}: ${rowType(builder._def)};`;\n });\n const insertLines = cols.map(([col, builder]) => {\n const def = builder._def;\n const opt = optionalOnInsert(def) ? \"?\" : \"\";\n return `${indent} ${col}${opt}: ${rowType(def)};`;\n });\n const relEntries = relations\n .map(\n (r) =>\n `${r.name}: { to: ${JSON.stringify(r.to)}; kind: ${JSON.stringify(r.kind)}; via: ${JSON.stringify(r.via)} }`,\n )\n .join(\"; \");\n return [\n `${indent}${table.name}: {`,\n `${indent} row: {`,\n ...rowLines,\n `${indent} };`,\n `${indent} insert: {`,\n ...insertLines,\n `${indent} };`,\n `${indent} relations: {${relEntries === \"\" ? \"\" : ` ${relEntries} `}};`,\n // searchable: vector kolonu YA DA search beyanı → EnvTypedTable'da search()\n // üyesini açan yapısal bayrak (FR-013). Yokken satır hiç üretilmez ki\n // mevcut şemaların d.ts'i bayt-aynı kalsın.\n ...(cols.some(([, b]) => b._def.type === \"vector\") || table.search !== undefined\n ? [`${indent} searchable: true;`]\n : []),\n `${indent}};`,\n ].join(\"\\n\");\n}\n\n/**\n * Generate the full `palbase-env.d.ts` text for the project's schemas.\n *\n * The emitted file ends in `export {};` — same as `makeStackDts`. Without it the\n * `.d.ts` is a global script, and `declare module \"…\"` there DECLARES an ambient\n * module (shadowing the real one, so every export of `@palbase/backend/env`\n * silently becomes invalid) instead of AUGMENTING it. Measured on a minimal tsc\n * repro: with the line, exit 0; without it, `TS2305: Module '\"…\"' has no\n * exported member`. The line was dropped once in a rewrite and nothing caught\n * it, so `env-gen.test.ts` now gates it directly.\n *\n * @example\n * import { makeEnvDts } from \"@palbase/backend\";\n * import schema from \"./db/schema.js\";\n * writeFileSync(\"palbase-env.d.ts\", makeEnvDts([schema]));\n */\nexport function makeEnvDts(schemas: readonly SchemaDef[]): string {\n // No pruning: `relations` is a flat literal map, so it cannot expand into an\n // infinite type the way the old recursive `children` could. Dropping a back-edge\n // here would delete a REAL relation and make the type lie about the schema.\n const relations = buildRelations(schemas);\n const qualify = (schemaName: string, table: string): string =>\n schemaName === \"public\" ? table : `${schemaName}.${table}`;\n\n const publicSchema = schemas.find((s) => s.name === \"public\");\n const others = schemas.filter((s) => s.name !== \"public\");\n\n const publicBlocks = Object.keys(publicSchema?.tables ?? {}).map((name) =>\n tableBlock(publicSchema!.tables[name]!, relations.get(name) ?? [], \" \"),\n );\n const body = publicBlocks.length > 0 ? `\\n${publicBlocks.join(\"\\n\")}\\n ` : \"\";\n\n const schemaBlocks = others.map((schema) => {\n const inner = Object.keys(schema.tables).map((name) =>\n tableBlock(schema.tables[name]!, relations.get(qualify(schema.name, name)) ?? [], \" \"),\n );\n return ` ${schema.name}: {\\n${inner.join(\"\\n\")}\\n };`;\n });\n const schemasBody = schemaBlocks.length > 0 ? `\\n${schemaBlocks.join(\"\\n\")}\\n ` : \"\";\n\n return `// AUTO-GENERATED by @palbase/backend — DO NOT EDIT.\n// Regenerated from db/*.ts by \\`palbase build\\` and by every deploy.\n// Augments the @palbase/backend/env \\`Tables\\` interface so \\`Database.tables.*\\`\n// is typed with no import and no generic. Schemas other than \\`public\\` land\n// under \\`Schemas\\`, reached with \\`Database.schema(\"<name>\").tables.*\\`.\n\ndeclare module \"@palbase/backend/env\" {\n interface Tables {${body}}\n interface Schemas {${schemasBody}}\n}\n\nexport {};\n`;\n}\n","/**\n * stack-gen.ts — generate the `palbase-stack.d.ts` text from the names the\n * linked environment's stack holds.\n *\n * The twin of `db/env-gen.ts`: the CLI calls\n * {@link makeStackDts} with the three name sets it read off the stack and\n * writes the result to `palbase-stack.d.ts` at the project root. That file\n * augments the `@palbase/backend/stack` interfaces, so `Secrets.get(...)`, the\n * Flags client and `@Upload({ bucket })` accept the project's real names and\n * nothing else.\n *\n * The generator does NOT reach the network and does NOT decide what a name is:\n * it renders what it is handed. The stack is the authority on which names exist\n * (`GET /v1/management/secrets`, `/flags`, `/storage/buckets`); re-deciding that\n * here would be a second, weaker copy of it.\n *\n * The emitted file ends in `export {};` — same as `makeEnvDts` and\n * `makePurchasesDts`. Without it the `.d.ts` is a global script, and\n * `declare module \"…\"` there DECLARES an ambient module (shadowing the real one,\n * so every name silently becomes invalid) instead of AUGMENTING it.\n */\n\n/** The three name sets read off the stack. Order is irrelevant — each set is\n * sorted here so the same stack always renders the same bytes and a diff shows\n * what CHANGED rather than how the API happened to order its answer. */\n/** One bucket and the renditions it declares. */\nexport interface BucketInput {\n name: string;\n variants: readonly string[];\n}\n\nexport interface StackNames {\n /** Secret names from the project's vault. */\n secrets: readonly string[];\n /** Flag keys from the project's flag store. */\n flags: readonly string[];\n /**\n * Buckets from the project's storage — a bare name, or a name with the\n * renditions it declares.\n *\n * A bucket is not only a NAME: `Storage.buckets.docs.getPublicUrl(p, {\n * variant })` refuses a rendition the bucket does not have, so the variant\n * union has to travel with it. The bare-string form is shorthand for \"no\n * variants\", which renders `never` and accepts none.\n */\n buckets: readonly (string | BucketInput)[];\n}\n\n/** Sorted, de-duplicated names. A stack that reports one twice (two pages of a\n * listing overlapping, say) must not render a duplicate member — TypeScript\n * accepts it, but the file stops being a function of the stack's contents. */\nfunction liveNames(names: readonly string[]): string[] {\n return [...new Set(names)].sort();\n}\n\n/** A bare identifier stays bare; anything else is quoted. Bucket names carry\n * dashes and dots (the Storage module's allowed shape), and an unquoted\n * `my-bucket` parses as a subtraction rather than a member name. */\nfunction memberName(name: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n}\n\nfunction members(names: string[]): string {\n if (names.length === 0) return \"\";\n return `\\n${names.map((n) => ` ${memberName(n)}: true;`).join(\"\\n\")}\\n `;\n}\n\n/** Buckets render a SHAPE rather than a marker, because each carries its variant\n * union. `never` for a bucket with none: the type then accepts no variant name\n * at all, which is exactly what a bucket without renditions offers. */\nfunction bucketMembers(buckets: readonly (string | BucketInput)[]): string {\n const normalized = buckets.map((b) => (typeof b === \"string\" ? { name: b, variants: [] as readonly string[] } : b));\n const byName = new Map<string, readonly string[]>();\n for (const b of normalized) byName.set(b.name, b.variants);\n const names = [...byName.keys()].sort();\n if (names.length === 0) return \"\";\n const rows = names.map((name) => {\n const variants = [...new Set(byName.get(name) ?? [])].sort();\n const union = variants.length === 0 ? \"never\" : variants.map((v) => JSON.stringify(v)).join(\" | \");\n return ` ${memberName(name)}: { variants: ${union} };`;\n });\n return `\\n${rows.join(\"\\n\")}\\n `;\n}\n\n/**\n * Render the project's `palbase-stack.d.ts`.\n *\n * An empty set renders an empty interface, which is a MEANINGFUL value: the\n * stack holds no such names, so the corresponding union is `never` and every\n * call spelling one fails to compile. It is not the same as \"the file was never\n * generated\" only in that the file exists — both states refuse every name, and\n * both are correct.\n */\nexport function makeStackDts(names: StackNames): string {\n const secrets = liveNames(names.secrets);\n const flags = liveNames(names.flags);\n\n\n return `// palbase-stack.d.ts — GENERATED by @palbase/backend. Do not edit.\n// Source: the linked environment's stack.\n\ndeclare module \"@palbase/backend/stack\" {\n interface Secrets {${members(secrets)}}\n\n interface Flags {${members(flags)}}\n\n interface Buckets {${bucketMembers(names.buckets)}}\n}\n\nexport {};\n`;\n}\n","// The decorator registry — the single plain-data store the method + parameter\n// decorators write into, and the deploy/dispatch pipeline reads back. No\n// `reflect-metadata`, no `emitDecoratorMetadata`: the registry is built from the\n// decorator arguments + the parameter INDEX that esbuild/tsc preserve for legacy\n// parameter decorators (verified — see the design spec §0/§4.1).\n//\n// A controller class carries its route metadata on a symbol-keyed static\n// property (`ROUTES`). `@Get`/`@Post`/… append a {@link RouteMeta} entry;\n// `@Body`/`@User`/… append a {@link ParamMeta} entry onto the route for the\n// method they decorate. Because parameter decorators run BEFORE the method\n// decorator for the same member (TS evaluates innermost-first, params before the\n// method), the route entry may not exist yet when a param decorator fires — so\n// param metadata is buffered per method name and merged when the method\n// decorator creates the route entry.\nimport type { AuthSpec, RateLimitConfig } from \"../endpoint.js\";\nimport type { UploadConfig } from \"./upload.js\";\nimport type { SseConfig } from \"./sse.js\";\nimport type { ZodTypeAny } from \"zod\";\n\n/** The HTTP verbs a route may declare, upper-cased (the runtime router +\n * OpenAPI lower-case on their own). */\nexport type HttpMethodUpper = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"QUERY\";\n\n/** Route-level options accepted by the method decorators (`@Get`/`@Post`/…). */\nexport interface RouteOptions {\n /** OVERRIDES the controller-level default auth for this one route. */\n auth?: AuthSpec;\n /** Per-route rate limit. */\n rateLimit?: RateLimitConfig;\n /** Direct-storage upload config — present ONLY on `@Upload` routes (the\n * `@Get`/`@Post`/… decorators never set it). Its presence is what MARKS a\n * route as an upload route through the whole pipeline (registry → flatten →\n * openapi → codegen). The bytes go client→storage directly; the method body\n * runs as the completion handler. See {@link UploadConfig} (decorators/upload.ts). */\n uploadConfig?: UploadConfig;\n /** Streaming config — present ONLY on `@Sse` routes (the `@Get`/`@Post`/…\n * decorators never set it). Its presence is what MARKS a route as a streaming\n * route through the whole pipeline (registry → flatten → openapi → codegen),\n * exactly as `uploadConfig` does for uploads — never a special HTTP verb. An\n * `@Sse` route registers POST like any input-bearing route, so the verb cannot\n * carry the distinction. See {@link SseConfig} (decorators/sse.ts). */\n sseConfig?: SseConfig;\n}\n\n/** The kind of value a parameter decorator injects. Drives both dispatch\n * (which request slice to inject) and codegen (which OpenAPI parameter source a\n * schema-bearing kind maps to). */\nexport type ParamKind =\n | \"body\"\n | \"query\"\n | \"param\"\n | \"headers\"\n | \"user\"\n | \"optionalUser\"\n | \"client\"\n | \"requestId\"\n | \"traceId\"\n | \"req\"\n // `@UploadedObject()` — injects the uploaded object (completion input) on an\n // `@Upload` route. No schema (the shape is the fixed UploadedObject type).\n | \"uploadedObject\"\n // `@SseOut()` — injects the frame writer on an `@Sse` route. No schema (the\n // shape is the fixed SseWriter type).\n | \"sseOut\"\n // `@Signal()` — injects the request's AbortSignal, which aborts when the\n // client disconnects. No schema. NOT derivable from `@Req()`: PBRequest\n // carries only request-scoped data and has no signal (endpoint.ts:358-363).\n | \"signal\";\n\n/** One parameter decorator's recorded metadata. `index` is the parameter\n * position esbuild/tsc preserve; `schema` is present for the schema-bearing\n * kinds (`body`/`query`/`headers`); `name` is the path-param name for `param`. */\nexport interface ParamMeta {\n index: number;\n kind: ParamKind;\n /** Zod schema for `body`/`query`/`headers` (validation + codegen source). */\n schema?: ZodTypeAny;\n /** Path-param name for `@Param(\"id\")`. */\n name?: string;\n}\n\n/** One inferred throw site: the error CLASS name (e.g. \"TodoLocked\") and its\n * wire code (e.g. \"todo_locked\"). `status`, `hasData`, and the data JSON schema\n * are NOT carried here — they resolve from the error registry by `code` at\n * extract/openapi time (single source of truth). */\nexport interface ThrowDescriptor {\n name: string;\n code: string;\n}\n\n/** One route's recorded metadata: the verb + subpath + method name + options,\n * the ordered parameter metas, and the resolved return schema (injected by the\n * codegen step — see `returnSchema`). */\nexport interface RouteMeta {\n method: HttpMethodUpper;\n subpath: string;\n fnName: string;\n options: RouteOptions;\n params: ParamMeta[];\n /** Response schema for the route, if any. Derived from the method's RETURN\n * TYPE by codegen and written here via `recordReturn` (a generated top-level\n * IIFE injected per controller), not by an author-written decorator. */\n returnSchema?: ZodTypeAny;\n /** Error classes this route can throw, if inferred. Derived from the method\n * body + service call graph by the deploy stager's throw analysis and written\n * here via `recordThrows` (a generated top-level IIFE injected per controller,\n * the `recordReturn` twin), not by an author-written decorator. */\n throws?: ThrowDescriptor[];\n}\n\n/** Symbol the route metadata list is stored under on a controller class. Using\n * a symbol (not a string key) keeps it off the public structural surface and\n * avoids any chance of an authored property collision. */\nexport const ROUTES: unique symbol = Symbol.for(\"palbase.backend.routes\");\n\n/** Symbol the per-method buffered parameter metas are stored under while a class\n * is being decorated. Parameter decorators fire before the method decorator, so\n * they buffer here keyed by method name; the method decorator drains the buffer\n * into the route entry it creates. */\nconst PARAM_BUFFER: unique symbol = Symbol.for(\"palbase.backend.paramBuffer\");\n\n/** A room's own slots. Rooms are NOT routes — no verb, no path, no params — so\n * they get their own carrier slots instead of being squeezed into RouteMeta. */\nconst ROOM: unique symbol = Symbol.for(\"palbase.backend.room\");\nconst ROOM_HOOKS: unique symbol = Symbol.for(\"palbase.backend.roomHooks\");\n\n/** Symbol the per-method buffered return-type schemas are stored under while a\n * class's registry is being populated. The codegen-injected `recordReturn` call\n * can fire before OR after the method decorator; it buffers here keyed by method\n * name and `recordRoute` drains it into the route entry (and `recordReturn`\n * writes through if the route already exists). Buffering on BOTH sides means a\n * fully-formed route entry always carries its return schema — a raw-symbol\n * reader (the runtime) never has to re-merge. */\nconst RETURN_BUFFER: unique symbol = Symbol.for(\"palbase.backend.returnBuffer\");\n\n/** Symbol the per-method buffered throw descriptors are stored under while a\n * class's registry is being populated. The stager-injected `recordThrows` call\n * can fire before OR after the method decorator; it buffers here keyed by method\n * name and `recordRoute` drains it into the route entry (and `recordThrows`\n * writes through if the route already exists). Buffering on BOTH sides means a\n * fully-formed route entry always carries its throw descriptors — a raw-symbol\n * reader (the runtime) never has to re-merge. */\nconst THROWS_BUFFER: unique symbol = Symbol.for(\"palbase.backend.throwsBuffer\");\n\n/** A class constructor carrying the symbol-keyed registry slots. We type the\n * registry-bearing class as this so the decorators can read/write the slots\n * without `any` — a plain `Function` does not carry index signatures. */\ninterface RegistryCarrier {\n [ROUTES]?: RouteMeta[];\n [PARAM_BUFFER]?: Record<string, ParamMeta[]>;\n [ROOM]?: RoomMeta;\n [ROOM_HOOKS]?: RoomBuffer;\n [RETURN_BUFFER]?: Record<string, ZodTypeAny>;\n [THROWS_BUFFER]?: Record<string, ThrowDescriptor[]>;\n}\n\n/** Coerce a decorated target (class constructor or its prototype) into the\n * registry carrier that owns the slots. Method/param decorators receive the\n * PROTOTYPE as their target; the class decorator receives the constructor. We\n * always anchor the registry on the CONSTRUCTOR so `getRoutes(ctor)` finds it. */\nfunction carrierOf(target: object): RegistryCarrier {\n // For instance-member decorators, `target` is the prototype; its `.constructor`\n // is the class. For a static member or the class decorator, `target` is the\n // constructor already. Resolve to the constructor either way.\n const ctor =\n typeof target === \"function\"\n ? (target as unknown as RegistryCarrier)\n : (((target as { constructor?: unknown }).constructor ??\n target) as unknown as RegistryCarrier);\n return ctor;\n}\n\n/** Get (creating if absent) the own route list for a class constructor. Own —\n * not inherited — so a subclass does not mutate its base's routes. */\nfunction ownRoutes(carrier: RegistryCarrier): RouteMeta[] {\n if (!Object.prototype.hasOwnProperty.call(carrier, ROUTES)) {\n carrier[ROUTES] = [];\n }\n return carrier[ROUTES] as RouteMeta[];\n}\n\n/** Get (creating if absent) the own per-method param buffer for a class. */\nfunction ownParamBuffer(carrier: RegistryCarrier): Record<string, ParamMeta[]> {\n if (!Object.prototype.hasOwnProperty.call(carrier, PARAM_BUFFER)) {\n carrier[PARAM_BUFFER] = {};\n }\n return carrier[PARAM_BUFFER] as Record<string, ParamMeta[]>;\n}\n\n/** Record a route (called by the method decorators). Drains any parameter\n * metas already buffered for `fnName` into the new route entry, then sorts them\n * by parameter index so dispatch can inject positionally. */\nexport function recordRoute(\n target: object,\n fnName: string,\n method: HttpMethodUpper,\n subpath: string,\n options: RouteOptions,\n): void {\n const carrier = carrierOf(target);\n const routes = ownRoutes(carrier);\n const buffer = ownParamBuffer(carrier);\n const params = (buffer[fnName] ?? []).slice().sort((a, b) => a.index - b.index);\n const route: RouteMeta = { method, subpath, fnName, options, params };\n // Drain a buffered return schema (the recordReturn-ran-first ordering) so the\n // route entry is complete the moment it's created — a raw-symbol consumer\n // (the runtime extractor/worker) sees the return schema without re-merging.\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer && returnBuffer[fnName] !== undefined) {\n route.returnSchema = returnBuffer[fnName];\n }\n // Same drain for buffered throw descriptors (the recordThrows-ran-first\n // ordering) — the route entry is complete the moment it's created.\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer && throwsBuffer[fnName] !== undefined) {\n route.throws = throwsBuffer[fnName];\n }\n routes.push(route);\n}\n\n/** Record one parameter decorator (called by `@Body`/`@User`/…). Buffers per\n * method name; the method decorator merges the buffer into the route entry. If\n * the route already exists (method decorator ran first — TS does evaluate the\n * method decorator AFTER its parameter decorators, but we stay order-robust),\n * the meta is also appended directly so neither ordering loses it. */\nexport function recordParam(target: object, fnName: string, meta: ParamMeta): void {\n const carrier = carrierOf(target);\n const buffer = ownParamBuffer(carrier);\n (buffer[fnName] ??= []).push(meta);\n\n // Order-robust: if the route already exists, merge in place + keep sorted.\n const routes = carrier[ROUTES];\n if (routes) {\n const route = routes.find((r) => r.fnName === fnName);\n if (route) {\n route.params.push(meta);\n route.params.sort((a, b) => a.index - b.index);\n }\n }\n}\n\n/** Attach a return schema to the route for `fnName` (called by the codegen\n * injection that reads the method's return type). If the route does not exist\n * yet, the schema is buffered (RETURN_BUFFER) and drained into the route by\n * `recordRoute` when the method decorator runs. */\nexport function recordReturn(target: object, fnName: string, schema: ZodTypeAny): void {\n const carrier = carrierOf(target);\n const routes = carrier[ROUTES];\n const route = routes?.find((r) => r.fnName === fnName);\n if (route) {\n route.returnSchema = schema;\n return;\n }\n if (!Object.prototype.hasOwnProperty.call(carrier, RETURN_BUFFER)) {\n carrier[RETURN_BUFFER] = {};\n }\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer) returnBuffer[fnName] = schema;\n}\n\n/** Attach the inferred throw descriptors to the route for `fnName` (called by\n * the stager-injected IIFE that carries the throw analysis result — the\n * `recordReturn` twin). If the route does not exist yet, the descriptors are\n * buffered (THROWS_BUFFER) and drained into the route by `recordRoute` when the\n * method decorator runs. */\nexport function recordThrows(target: object, fnName: string, throws: ThrowDescriptor[]): void {\n const carrier = carrierOf(target);\n const routes = carrier[ROUTES];\n const route = routes?.find((r) => r.fnName === fnName);\n if (route) {\n route.throws = throws;\n return;\n }\n if (!Object.prototype.hasOwnProperty.call(carrier, THROWS_BUFFER)) {\n carrier[THROWS_BUFFER] = {};\n }\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer) throwsBuffer[fnName] = throws;\n}\n\n/** Read the route metadata for a controller class (the deploy/dispatch entry\n * point). Applies any buffered return schemas + throw descriptors (for the\n * recordReturn/recordThrows-runs-before orderings) and returns a defensive copy\n * so callers cannot mutate the registry.\n */\nexport function getRoutes(ctor: object): RouteMeta[] {\n const carrier = carrierOf(ctor);\n const routes = carrier[ROUTES] ?? [];\n const returnBuffer = carrier[RETURN_BUFFER];\n if (returnBuffer) {\n for (const route of routes) {\n const buffered = returnBuffer[route.fnName];\n if (buffered && route.returnSchema === undefined) {\n route.returnSchema = buffered;\n }\n }\n }\n const throwsBuffer = carrier[THROWS_BUFFER];\n if (throwsBuffer) {\n for (const route of routes) {\n const buffered = throwsBuffer[route.fnName];\n if (buffered && route.throws === undefined) {\n route.throws = buffered;\n }\n }\n }\n return routes.map((r) => ({\n ...r,\n params: r.params.slice(),\n ...(r.throws !== undefined ? { throws: r.throws.slice() } : {}),\n }));\n}\n\n// ── rooms ───────────────────────────────────────────────────────────────────\n\n/** Which lifecycle hook a method is bound to. */\nexport type RoomHook = \"authorize\" | \"first\" | \"join\" | \"leave\" | \"empty\";\n\nexport interface RoomMessageMeta {\n fnName: string;\n schema: ZodTypeAny;\n}\n\nexport interface RoomMeta {\n pattern: string;\n events: Record<string, ZodTypeAny>;\n graceMs: number;\n /** hook → the method name that implements it. */\n hooks: Partial<Record<RoomHook, string>>;\n /** inbound message name → its method and payload schema. */\n messages: Record<string, RoomMessageMeta>;\n}\n\ninterface RoomBuffer {\n hooks: Partial<Record<RoomHook, string>>;\n messages: Record<string, RoomMessageMeta>;\n}\n\n/** Get (creating if absent) the own hook buffer. Own — not inherited — so a\n * subclass never mutates its base's hooks. Member decorators fill this BEFORE\n * the class decorator runs; controller.ts:203 depends on the same ordering. */\nfunction ownRoomBuffer(carrier: RegistryCarrier): RoomBuffer {\n if (!Object.prototype.hasOwnProperty.call(carrier, ROOM_HOOKS)) {\n carrier[ROOM_HOOKS] = { hooks: {}, messages: {} };\n }\n return carrier[ROOM_HOOKS] as RoomBuffer;\n}\n\n/** Record a lifecycle hook. A second method for the same hook is refused: two\n * answers to \"who handles this\" cannot be resolved at dispatch, and silently\n * keeping one is how a hook stops running without anyone being told. */\nexport function recordRoomHook(target: object, hook: RoomHook, fnName: string): void {\n const buffer = ownRoomBuffer(carrierOf(target));\n const existing = buffer.hooks[hook];\n if (existing !== undefined && existing !== fnName) {\n const label = `On${hook.charAt(0).toUpperCase()}${hook.slice(1)}`;\n throw new Error(\n `@${label} is declared twice in one room (${existing} and ${fnName}). ` +\n `A room has one of each hook.`,\n );\n }\n buffer.hooks[hook] = fnName;\n}\n\n/** Record an inbound message handler. */\nexport function recordRoomMessage(\n target: object,\n name: string,\n fnName: string,\n schema: ZodTypeAny,\n): void {\n const buffer = ownRoomBuffer(carrierOf(target));\n const existing = buffer.messages[name];\n if (existing !== undefined && existing.fnName !== fnName) {\n throw new Error(\n `@OnMessage(\"${name}\") is declared twice in one room (${existing.fnName} and ${fnName}).`,\n );\n }\n buffer.messages[name] = { fnName, schema };\n}\n\n/** Record the room itself (called by the class decorator), draining the buffer\n * the member decorators already filled. */\nexport function recordRoom(\n ctor: object,\n meta: Omit<RoomMeta, \"hooks\" | \"messages\">,\n): void {\n const carrier = carrierOf(ctor);\n const buffer = ownRoomBuffer(carrier);\n carrier[ROOM] = { ...meta, hooks: buffer.hooks, messages: buffer.messages };\n}\n\n/** The room a class declares, or undefined. A class with no `@Room` is not a\n * room — the marker is the CONFIG's presence, never a name or a base class\n * (the rule upload.ts:13-16 states for uploads). */\nexport function getRoom(ctor: object): RoomMeta | undefined {\n const carrier = carrierOf(ctor);\n if (!Object.prototype.hasOwnProperty.call(carrier, ROOM)) return undefined;\n return carrier[ROOM] as RoomMeta;\n}\n","// `@Controller(basePath, options?)` — the class decorator that marks a class as\n// a Palbase backend controller. It stamps a non-enumerable `__palbase`\n// discriminant + the resolved controller metadata onto the class so the\n// deploy/dispatch pipeline (and `isController`/`resolveController`) can detect\n// and read it without `reflect-metadata`.\nimport type { AuthSpec } from \"../endpoint.js\";\nimport { getRoutes } from \"./registry.js\";\n\n/** The controller metadata stamped onto a `@Controller`-decorated class. The\n * default export of a `controllers/*.controller.ts` file resolves to this via\n * {@link resolveController}. */\nexport interface ControllerMeta {\n /** Discriminant the runtime + tooling read. */\n readonly __palbase: \"controller\";\n /** The base path every route in this controller mounts under (e.g. \"/todos\"). */\n basePath: string;\n /** Controller-level default auth, applied to routes that don't set their own\n * (`@Get(\"/x\", { auth })` overrides this). `undefined` ⇒ the application\n * default ({@link defineDefaultAuth}), and secure-by-default below that —\n * see {@link resolveEffectiveAuth} for the whole cascade. */\n defaultAuth?: AuthSpec;\n}\n\n/** Options accepted by `@Controller`. */\nexport interface ControllerOptions {\n /** Default auth for ALL routes in this controller (route-level overrides;\n * omitting it falls through to the application default declared with\n * {@link defineDefaultAuth}). */\n auth?: AuthSpec;\n}\n\n/** Symbol the controller metadata is stamped under. Symbol-keyed (not a string\n * property) so it never collides with an authored member and stays off the\n * structural surface. */\nexport const CONTROLLER_META: unique symbol = Symbol.for(\"palbase.backend.controllerMeta\");\n\n/**\n * Every class `@Controller` has decorated, in decoration order.\n *\n * This is what lets a controller file need no export at all: importing the file\n * runs the decorator, the decorator records the class here, and the runtime\n * reads the list. Without it the only handle on a class is its export name, so\n * every controller had to be exported AND named in a generated entry — the\n * ceremony NestJS still charges (`export class` PLUS\n * `@Module({controllers:[…]})`).\n *\n * Keyed on a well-known Symbol against globalThis rather than held in a module\n * variable, because a deployed bundle inlines its own copy of this package: two\n * copies would keep two lists, and the runtime would read the empty one. The\n * same hazard `runtimeHooks` exists for, closed the same way — one shared slot.\n */\nconst REGISTRY: unique symbol = Symbol.for(\"palbase.backend.allControllers\") as never;\n\nfunction registry(): unknown[] {\n const g = globalThis as unknown as Record<symbol, unknown[] | undefined>;\n const existing = g[REGISTRY];\n if (existing) return existing;\n const fresh: unknown[] = [];\n g[REGISTRY] = fresh;\n return fresh;\n}\n\n/**\n * The controller classes this process has loaded, in decoration order.\n *\n * Decoration order is import order, which the bundler fixes by sorting the\n * files it emits imports for — so two builds of one tree produce the same\n * route table, and route precedence is not a function of module-resolution\n * accidents.\n */\nexport function getRegisteredControllers(): readonly unknown[] {\n return registry().slice();\n}\n\n/** Empty the registry. For tests, which load controllers repeatedly. */\nexport function __resetRegisteredControllers(): void {\n registry().length = 0;\n}\n\n/**\n * The APPLICATION-level default auth.\n *\n * Held on globalThis under a well-known Symbol for exactly the reason\n * {@link REGISTRY} is: a deployed bundle inlines its own copy of this package,\n * and two copies keeping two defaults is how a security setting silently\n * becomes two different settings.\n */\nconst APP_DEFAULT_AUTH: unique symbol = Symbol.for(\"palbase.backend.appDefaultAuth\") as never;\n\nfunction appAuthSlot(): Record<symbol, AuthSpec | undefined> {\n return globalThis as unknown as Record<symbol, AuthSpec | undefined>;\n}\n\n/**\n * Declare the default auth for EVERY route in the application — the ring the\n * cascade consults when neither the route nor its controller says anything.\n *\n * The measured problem it removes: `auth: { verifiedEmail: true }` repeated by\n * hand on ten `@Controller`s. A security setting that must be repeated is a\n * security setting that will be forgotten — the eleventh controller opens the\n * door and nothing says so.\n *\n * Call it at MODULE SCOPE in a file the application imports (the controllers'\n * own barrel, or a module a controller imports). The cascade reads this slot\n * when the route table is built and when the spec is emitted — both of which\n * run after module loading — so declaration order does not matter, but being\n * imported at all does.\n *\n * @example\n * defineDefaultAuth({ verifiedEmail: true }); // every route, unless it says otherwise\n */\nexport function defineDefaultAuth(auth: AuthSpec): void {\n appAuthSlot()[APP_DEFAULT_AUTH] = auth;\n}\n\n/** The declared application default, or `undefined` when none was declared. */\nexport function getDefaultAuth(): AuthSpec | undefined {\n return appAuthSlot()[APP_DEFAULT_AUTH];\n}\n\n/** Clear the application default. For tests, which declare it repeatedly. */\nexport function __resetDefaultAuth(): void {\n delete appAuthSlot()[APP_DEFAULT_AUTH];\n}\n\n/**\n * THE auth cascade: route → controller → application → `true`.\n *\n * One function, every caller — the route table (`engine/router.ts`) and the\n * spec emitter (`openapi/controllers.ts`) ASK for the answer instead of\n * spelling the chain themselves. Two hand-written copies of a cascade is how\n * the build-time answer and the runtime answer come to disagree about who may\n * call an endpoint, and the disagreement shows up as an open door.\n *\n * The terminal `true` is secure-by-default and is load-bearing: a route that\n * declared nothing, under a controller that declared nothing, in an\n * application that declared nothing, is CLOSED.\n */\nexport function resolveEffectiveAuth(\n routeAuth: AuthSpec | undefined,\n controllerAuth: AuthSpec | undefined,\n): AuthSpec {\n return routeAuth ?? controllerAuth ?? getDefaultAuth() ?? true;\n}\n\n/** A class carrying the stamped controller metadata + discriminant. */\ninterface ControllerCarrier {\n __palbase?: \"controller\";\n [CONTROLLER_META]?: ControllerMeta;\n}\n\n/** The one path segment the platform owns. The isolate matches\n * `^/webhooks/([^/]+)$` on the raw request path BEFORE controller dispatch, so\n * anything a controller resolves to under it answers `404 webhook_not_found`\n * and never runs. */\nconst RESERVED_FIRST_SEGMENT = \"webhooks\";\n\n/**\n * Throw if `path` resolves under the reserved segment. Segments are compared the\n * way the isolate compares them — `split(\"/\").filter(Boolean)` — NOT by string\n * prefix, because empty segments collapse there: `@Controller(\"/\")` +\n * `@Post(\"/webhooks/x\")` composes to `//webhooks/x`, which the isolate serves as\n * `/webhooks/x`. A prefix check reads that as safe; the segment check does not.\n * `/webhooksy` stays allowed for the same reason — it is a different segment.\n *\n * Every verb is refused, not just the POST the isolate currently intercepts: the\n * reservation is of the URL namespace, so a `@Get(\"/webhooks/x\")` that happens\n * to work today would be silently shadowed the moment the isolate's method gate\n * widens. Refusing at build is recoverable; discovering it as a 404 is not.\n */\nfunction assertNotReserved(path: string, subject: string): void {\n const [first] = path.split(\"/\").filter(Boolean);\n if (first === RESERVED_FIRST_SEGMENT) {\n throw new Error(\n `${subject} resolves under the reserved /${RESERVED_FIRST_SEGMENT} path — ` +\n \"inbound webhooks are served there and would shadow this route\",\n );\n }\n}\n\n/**\n * Mark a class as a Palbase backend controller. `basePath` is the mount path\n * for every route the class declares; `options.auth` sets the controller-level\n * default auth (a route's own `auth` overrides it; absent ⇒ secure-by-default).\n *\n * @example\n * \\@Controller(\"/todos\", { auth: false })\n * export class TodosController {\n * \\@Get(\"\") list(\\@QueryParams(ListTodosQuery) q: ListTodosQuery): TodoSchema[] { … }\n * }\n */\nexport function Controller(basePath: string, options: ControllerOptions = {}) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n // /webhooks/* belongs to the platform: the isolate matches the inbound\n // webhook route before controller dispatch, so a controller mounted here\n // would never receive a request. Silent shadowing is the failure mode this\n // whole change exists to remove, so refuse it at build.\n //\n // The COMPOSED path is what gets shadowed, not the base path. `@Controller(\"\")`\n // and `@Controller(\"/\")` both pass a base-path-only check while a\n // `@Post(\"/webhooks/stripe\")` inside them resolves to exactly the path the\n // isolate intercepts. Method decorators run BEFORE the class decorator (TS\n // evaluates members first), so every route this class declares is already in\n // the registry here — which is why the composed check can live at this one\n // seam instead of on the dispatch read path. The `@Controller(\"\") +\n // @Post(\"/webhooks/stripe\")` test is the lock on that ordering: if it ever\n // stopped holding, that test goes red.\n assertNotReserved(basePath, `@Controller(\"${basePath}\")`);\n for (const route of getRoutes(ctor)) {\n assertNotReserved(\n `${basePath}${route.subpath}`,\n `@${route.method}(\"${route.subpath}\") in @Controller(\"${basePath}\")`,\n );\n }\n\n const carrier = ctor as unknown as ControllerCarrier;\n const meta: ControllerMeta = {\n __palbase: \"controller\",\n basePath,\n ...(options.auth !== undefined ? { defaultAuth: options.auth } : {}),\n };\n // Non-enumerable so it doesn't leak onto instances / structural checks.\n Object.defineProperty(carrier, CONTROLLER_META, {\n value: meta,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // The bare `__palbase` discriminant is the cheap detection marker the\n // runtime/extractor checks; keep it readable but non-enumerable.\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"controller\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // Record it, so importing the file is enough and exporting is optional.\n // Guarded against a double-decoration re-entering the same class twice.\n const all = registry();\n if (!all.includes(ctor)) all.push(ctor);\n return ctor;\n };\n}\n\n/** True when `value` is a `@Controller`-decorated class (cheap discriminant\n * check). Accepts the class constructor (the default export of a controller\n * file). */\nexport function isController(value: unknown): boolean {\n if (typeof value !== \"function\" && (typeof value !== \"object\" || value === null)) {\n return false;\n }\n const carrier = value as ControllerCarrier;\n return carrier.__palbase === \"controller\" && carrier[CONTROLLER_META] !== undefined;\n}\n\n/** Read the resolved controller metadata off a `@Controller`-decorated class.\n * Throws if the class was not decorated — callers should gate with\n * {@link isController} first (the loader does). */\nexport function resolveController(ctor: unknown): ControllerMeta {\n if (typeof ctor !== \"function\" && (typeof ctor !== \"object\" || ctor === null)) {\n throw new TypeError(\"resolveController: value is not a class\");\n }\n const meta = (ctor as ControllerCarrier)[CONTROLLER_META];\n if (!meta) {\n throw new TypeError(\n \"resolveController: class is not a @Controller — every controller file must `export default` a @Controller-decorated class\",\n );\n }\n return meta;\n}\n\n/**\n * A class the runtime constructs takes NO constructor parameters.\n *\n * ONE writer, four callers (controller, hook, job, webhook) and the build's own\n * check. Four hand-written copies of this message is how the four come to\n * disagree about what is refused — and the disagreement is silent, because a\n * class that slips past one of them still ends up with `undefined` fields.\n *\n * Why it is refused rather than injected: there is no container. The parameter\n * would arrive `undefined`, the code would compile, deploy, and fail at the\n * first request that touches the field — the most expensive place to learn it.\n */\nexport function assertZeroArgConstructor(Ctrl: unknown, kind: string): void {\n const arity = (Ctrl as { length?: number }).length ?? 0;\n if (arity === 0) return;\n const name = (Ctrl as { name?: string }).name ?? \"<anonymous>\";\n throw new Error(\n `${kind} ${name} declares a constructor with ${arity} parameter(s). ` +\n `A ${kind} is constructed by the runtime with a zero-argument constructor — ` +\n `there is no injector to supply them, so every parameter would arrive as ` +\n `undefined. Hold the dependency as a module-level singleton the ${kind} ` +\n \"imports (`const repo = makeRepo()` beside the class), and construct the \" +\n \"service directly in tests (e.g. `new TodoService(fakeDatabase().db)`).\",\n );\n}\n","// Method decorators: `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` /\n// `@Query` declare a route (verb + subpath + options) on a controller method. These are LEGACY\n// method decorators (`experimentalDecorators`), receiving\n// `(prototype, methodName, descriptor)`. They write into the per-class registry\n// (registry.ts). The success-response schema is NOT declared here: it is derived\n// from the method's RETURN TYPE by a codegen step and injected onto the route at\n// runtime via `recordReturn` (registry.ts).\nimport {\n recordRoute,\n type HttpMethodUpper,\n type RouteOptions,\n} from \"./registry.js\";\n\n/** A legacy method decorator. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** Build a method decorator for one HTTP verb. The decorated method's name is\n * the route `fnName` — and it is PUBLIC API, not authoring sugar: the runtime\n * derives the operationId as `<controllerName>.<fnName>` (the dotted namespace\n * the SDKs expose as `pb.todos.list()`), so renaming this method renames every\n * client call. The flat verb+path id is only the fallback for routes with no\n * controller metadata. See openapi/discover.ts. */\nfunction makeMethodDecorator(method: HttpMethodUpper) {\n return function (subpath: string, options: RouteOptions = {}): MethodDecorator {\n // Runtime guard for stale pre-9.0.0 code: `@Query(zodSchema)` used to be\n // the query-string PARAM decorator. Applied against this SDK it would\n // silently record a garbage route (schema-as-subpath) and fail the deploy\n // with a baffling self-conflict — fail loud and name the migration instead.\n if (typeof subpath !== \"string\") {\n throw new Error(\n `@${method[0]}${method.slice(1).toLowerCase()}(subpath) expects a string subpath, got ${typeof subpath}.` +\n (method === \"QUERY\"\n ? \" If this is a zod schema on a method parameter: the query-string param decorator was renamed @QueryParams(schema) in @palbase/backend 9.0.0.\"\n : \"\"),\n );\n }\n return function (target, propertyKey) {\n recordRoute(target, String(propertyKey), method, subpath, options);\n };\n };\n}\n\n/** `@Get(subpath, options?)` — declare a GET route. */\nexport const Get = makeMethodDecorator(\"GET\");\n/** `@Post(subpath, options?)` — declare a POST route. */\nexport const Post = makeMethodDecorator(\"POST\");\n/** `@Put(subpath, options?)` — declare a PUT route. */\nexport const Put = makeMethodDecorator(\"PUT\");\n/** `@Patch(subpath, options?)` — declare a PATCH route. */\nexport const Patch = makeMethodDecorator(\"PATCH\");\n/** `@Delete(subpath, options?)` — declare a DELETE route. */\nexport const Delete = makeMethodDecorator(\"DELETE\");\n/** `@Query(subpath, options?)` — declare an HTTP QUERY route (RFC 10008):\n * safe + idempotent like GET, body-carrying like POST. Input rides `@Body`. */\nexport const Query = makeMethodDecorator(\"QUERY\");\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Webhook / @On — the inbound-webhook half of the decorator surface.\n//\n// Mirrors decorators/controller.ts exactly: symbol-keyed, non-enumerable\n// metadata on the constructor plus a `__palbase` discriminant, read back by a\n// resolver. The resolver is the ONLY translation point — it returns the shape\n// the runtime already consumes, so the isolate's dispatch and the signature\n// engine's cross-binding golden are untouched by the authoring change.\nimport type { WebhookMeta, WebhookProvider } from \"../webhook.js\";\n\n/** A signature scheme spelled out, for a service with no preset. The presets\n * (`provider`) are named configurations of this same shape. */\nexport interface SignatureSpec {\n /** Header carrying the signature. */\n header: string;\n /** Stripped before comparison (e.g. `sha256=`). Omit when absent. */\n prefix?: string;\n algo: \"hmac-sha256\" | \"hmac-sha1\";\n encoding: \"hex\" | \"base64\";\n /** What the HMAC covers. Exactly two placeholders: `{body}` and `{ts}`.\n * Everything else is literal. `{ts}` requires `timestampHeader` and brings\n * the five-minute replay window with it. */\n signs: string;\n timestampHeader?: string;\n}\n\nexport interface WebhookOptions {\n provider?: WebhookProvider;\n signature?: SignatureSpec;\n /** Env-var REFERENCE for the signing secret — the platform never holds it. */\n secret: { env: string };\n}\n\nexport type WebhookEventHandler = (event: unknown, meta: WebhookMeta) => Promise<void>;\n\nexport interface ResolvedWebhook {\n provider?: WebhookProvider;\n signature?: SignatureSpec;\n secret: { env: string };\n events: Record<string, WebhookEventHandler>;\n}\n\nexport const WEBHOOK_META: unique symbol = Symbol.for(\"palbase.backend.webhookMeta\");\nexport const WEBHOOK_EVENTS: unique symbol = Symbol.for(\"palbase.backend.webhookEvents\");\n\ninterface EventEntry {\n event: string;\n fnName: string;\n}\n\ninterface WebhookCarrier {\n __palbase?: \"webhook\";\n [WEBHOOK_META]?: WebhookOptions;\n [WEBHOOK_EVENTS]?: EventEntry[];\n}\n\nfunction carrierOf(ctor: object): WebhookCarrier {\n return ctor as WebhookCarrier;\n}\n\n/** Mark a class as an inbound webhook. The mount name is the FILE name — there\n * is deliberately no `name` option, because the file name IS the public URL. */\nexport function Webhook(options: WebhookOptions) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n const carrier = carrierOf(ctor);\n Object.defineProperty(carrier, WEBHOOK_META, {\n value: options,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"webhook\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return ctor;\n };\n}\n\n/** Bind a method to one event name. Any string is valid: presets provide\n * autocomplete, never a constraint, because we do not carry provider catalogs. */\nexport function On(event: string) {\n return function (target: object, fnName: string | symbol): void {\n // Method decorators receive the PROTOTYPE; metadata belongs on the ctor.\n const carrier = carrierOf((target as { constructor: object }).constructor);\n const existing = carrier[WEBHOOK_EVENTS];\n const entries: EventEntry[] = existing ? [...existing] : [];\n entries.push({ event, fnName: String(fnName) });\n Object.defineProperty(carrier, WEBHOOK_EVENTS, {\n value: entries,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n };\n}\n\n/** Read a decorated class back as the resolved config the runtime consumes.\n * Every misuse throws HERE, at build time, rather than becoming a webhook that\n * answers 200 and does nothing.\n *\n * @throws when the class declares constructor parameters (FR-011) — nothing\n * here supplies them, so the field would be `undefined` on every delivery. */\nexport function getWebhookConfig(ctor: object): ResolvedWebhook {\n const carrier = carrierOf(ctor);\n const meta = carrier[WEBHOOK_META];\n const entries = carrier[WEBHOOK_EVENTS] ?? [];\n\n if (!meta) {\n throw new Error(\n `@On used on a class that is not decorated with @Webhook (${(ctor as { name?: string }).name ?? \"anonymous\"})`,\n );\n }\n if (!meta.provider && !meta.signature) {\n throw new Error(\n \"@Webhook requires either a `provider` preset or an explicit `signature` — \" +\n \"an endpoint with no verification would accept forged deliveries\",\n );\n }\n // EITHER, not both. The isolate picks `provider` when both are present and\n // never looks at `signature`, so a tenant that wrote both gets deliveries\n // verified against a scheme they did not choose — silently, and with no way to\n // tell from the outside which one ran. Ambiguity about WHICH signature check\n // guards an endpoint is not something to resolve by precedence.\n if (meta.provider && meta.signature) {\n throw new Error(\n \"@Webhook declares BOTH a `provider` preset and an explicit `signature` — \" +\n \"these are alternatives; keep the one that describes the sender, because only `provider` would be used\",\n );\n }\n if (meta.signature) {\n const sig = meta.signature;\n // Mirrors Go's NewTemplateVerifier (internal/webhook/verify.go). Both sides\n // reject the same specs; this one rejects at build, which is the only place\n // a tenant can still act on it.\n if (!sig.header) {\n throw new Error(\"@Webhook signature requires `header` — the header the signature arrives in\");\n }\n if (sig.algo !== \"hmac-sha256\" && sig.algo !== \"hmac-sha1\") {\n throw new Error(`@Webhook signature has an unsupported algo \"${sig.algo}\"`);\n }\n if (sig.encoding !== \"hex\" && sig.encoding !== \"base64\") {\n throw new Error(`@Webhook signature has an unsupported encoding \"${sig.encoding}\"`);\n }\n if (!sig.signs?.includes(\"{body}\")) {\n throw new Error(\"@Webhook signature `signs` must contain {body} — signing a constant is not a signature\");\n }\n if (sig.signs.includes(\"{ts}\") && !sig.timestampHeader) {\n throw new Error(\"@Webhook signature uses {ts} but declares no `timestampHeader` to read it from\");\n }\n }\n if (!meta.secret?.env) {\n throw new Error(\"@Webhook requires `secret: { env: \\\"VAR_NAME\\\" }`\");\n }\n if (entries.length === 0) {\n throw new Error(\"@Webhook requires at least one @On handler\");\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first delivery. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"webhook class\");\n\n const instance = new (ctor as new () => Record<string, WebhookEventHandler>)();\n // Object.create(null), not {} — event names are free-form, so `@On(\"constructor\")`\n // and `@On(\"toString\")` are legal. A plain literal inherits those keys from\n // Object.prototype, and the duplicate check below would reject the FIRST and\n // only handler for them as a redeclaration.\n const events: Record<string, WebhookEventHandler> = Object.create(null) as Record<string, WebhookEventHandler>;\n for (const entry of entries) {\n if (Object.prototype.hasOwnProperty.call(events, entry.event)) {\n throw new Error(`@On(\"${entry.event}\") declared twice on the same webhook`);\n }\n events[entry.event] = (event, metaArg) =>\n (instance[entry.fnName] as WebhookEventHandler).call(instance, event, metaArg);\n }\n\n return {\n ...(meta.provider ? { provider: meta.provider } : {}),\n ...(meta.signature ? { signature: meta.signature } : {}),\n secret: meta.secret,\n events,\n };\n}\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Hook — the BLOCKING half of the internal-event surface.\n//\n// Two axes decide which decorator a handler wants. Where does the event come\n// from, and can the handler stop it?\n//\n// @Webhook + @On an OUTSIDE service (Stripe, GitHub…) — cannot block\n// @Hook an event this stack raised — CAN block: `throw` cancels it\n// @On an event this stack raised — listens only, a monitor\n//\n// The blocking power lives in the NAME `@Hook`, not in the method decorator's\n// shape, which is why `@On` keeps meaning \"listener\" in both worlds and needs\n// no change. `@Upload` is the same pattern already shipped: the storage module\n// calls the tenant's method, and a method that answers 4xx discards the object\n// and hands its exact status, body and content-type back to the client.\n//\n// Mirrors decorators/webhook.ts: symbol-keyed, non-enumerable metadata on the\n// constructor, read back by one resolver. The resolver is the only translation\n// point, so the runtime consumes a shape the authoring surface never leaks.\nimport type { HookMeta } from \"../hooks.js\";\nimport { WEBHOOK_EVENTS } from \"./webhook.js\";\n\n/** A hook handler. Returning quietly ALLOWS; throwing DENIES (blocking hooks). */\nexport type HookFn = (event: unknown, meta: HookMeta) => Promise<unknown>;\n\nexport interface ResolvedHookClass {\n /** `@Hook` handlers, by event. A throw here cancels the operation. */\n blocking: Record<string, HookFn>;\n /** `@On` handlers, by event. A throw here reaches nobody but the log. */\n listeners: Record<string, HookFn>;\n}\n\n/** A hook's refusal, with the reason the caller will see.\n *\n * Any thrown error denies — this class exists so the REASON travels as a\n * deliberate message rather than as whatever a stray TypeError happened to say.\n * The engine is fail-closed by design (an unreachable hook denies), so a hook\n * body should stay narrow: an accidental throw refuses a real user. */\nexport class Deny extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"Deny\";\n }\n}\n\nexport const HOOK_BLOCKING: unique symbol = Symbol.for(\"palbase.backend.hookBlocking\");\n\ninterface EventEntry {\n event: string;\n fnName: string;\n}\n\n/** `@Hook(\"before.user.create\")` — a blocking handler for one stack event. */\nexport function Hook(event: string) {\n return function (target: object, fnName: string | symbol): void {\n const carrier = (target as { constructor: object }).constructor as Record<symbol, unknown>;\n const existing = carrier[HOOK_BLOCKING] as EventEntry[] | undefined;\n const entries: EventEntry[] = existing ? [...existing] : [];\n entries.push({ event, fnName: String(fnName) });\n Object.defineProperty(carrier, HOOK_BLOCKING, {\n value: entries,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n };\n}\n\n/** Binds one decorator's entries onto a single instance of the class.\n *\n * ONE instance for the whole class, built here rather than per call: a hook\n * that opens a client or reads a list in its constructor would otherwise pay\n * for it on every signup. */\nfunction bind(instance: Record<string, HookFn>, entries: EventEntry[], kind: string) {\n const out: Record<string, HookFn> = Object.create(null) as Record<string, HookFn>;\n for (const entry of entries) {\n if (Object.prototype.hasOwnProperty.call(out, entry.event)) {\n throw new Error(`${kind}(\"${entry.event}\") declared twice on the same hook class`);\n }\n // Resolved ONCE, here, so a decorator naming a method that does not exist\n // fails at build time with the name in the message — rather than at the\n // first signup, as \"instance[fnName] is not a function\".\n const fn = instance[entry.fnName];\n if (typeof fn !== \"function\") {\n throw new Error(`${kind}(\"${entry.event}\") names no method \"${entry.fnName}\" on the class`);\n }\n out[entry.event] = (event, meta) => fn.call(instance, event, meta);\n }\n return out;\n}\n\n/** Resolves a hook class into the two maps the runtime dispatches from.\n *\n * Every misuse throws HERE, at build time, rather than becoming a hook that is\n * silently never called — the failure mode this whole change exists to end.\n *\n * @throws when the class declares constructor parameters (FR-011) — nothing\n * here supplies them, so the field would be `undefined` on every event. */\nexport function getHookConfig(ctor: object): ResolvedHookClass {\n const carrier = ctor as Record<symbol, unknown>;\n const blockingEntries = (carrier[HOOK_BLOCKING] ?? []) as EventEntry[];\n const listenerEntries = (carrier[WEBHOOK_EVENTS] ?? []) as EventEntry[];\n\n if (blockingEntries.length === 0 && listenerEntries.length === 0) {\n throw new Error(\n `${(ctor as { name?: string }).name ?? \"a hook class\"} carries no handler — ` +\n \"a hook file must declare at least one @Hook (blocking) or @On (listener) method\",\n );\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first event. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"hook class\");\n\n const instance = new (ctor as new () => Record<string, HookFn>)();\n return {\n blocking: bind(instance, blockingEntries, \"@Hook\"),\n listeners: bind(instance, listenerEntries, \"@On\"),\n };\n}\n","// `@Upload` — the single-method direct-storage upload decorator, and its\n// `@UploadedObject` parameter companion + `UploadConfig`/`UploadedObject` types.\n//\n// Unlike `@Get`/`@Post`/… (where bytes flow THROUGH the br-pod), an `@Upload`\n// route never sees the file bytes: the client uploads DIRECTLY to storage via a\n// signed URL the br-pod mints in an authorize pre-flight. The decorated method\n// body is the COMPLETION handler — it runs once, after storage confirms the\n// object landed (via an HMAC-signed completion webhook), and returns the typed\n// result the client awaits. There is exactly one method: it is BOTH the\n// authorize gate (its uploadConfig drives the guard + signed-URL pinning) AND\n// the completion handler (its body).\n//\n// On the wire the authorize pre-flight is a POST; what marks a route as an\n// upload route through the whole pipeline (registry → flatten → openapi →\n// codegen) is the PRESENCE of `uploadConfig` on the route — never a special HTTP\n// verb. The `@Get`/`@Post`/… decorators never set it.\nimport { recordRoute, recordParam } from \"./registry.js\";\nimport type { RouteOptions } from \"./registry.js\";\nimport type { PalbaseBucketName } from \"../stack.js\";\n\n/** A legacy method decorator (`experimentalDecorators`): `(prototype, name,\n * descriptor)`. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** A legacy parameter decorator: `(prototype, name, paramIndex)`. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/**\n * Direct-storage upload settings for an `@Upload` route. The br-pod validates an\n * authorize request against these (size/type), then mints a signed upload URL\n * that PINS the limits so storage itself rejects an over-limit / wrong-type PUT\n * — the client cannot exceed what it declared.\n */\nexport interface UploadConfig {\n /**\n * Target bucket NAME — one the STACK holds.\n *\n * The union comes from the generated `palbase-stack.d.ts`, so a bucket the\n * stack does not carry is a compile error. It used to say \"MUST exist in\n * `config/storage.ts` defineStorage(...)\", and that invariant was carried by\n * this sentence plus a cross-check nothing called; it is carried by the type\n * now.\n *\n * The bucket is the SINGLE SOURCE OF TRUTH for the size limit + MIME allowlist:\n * `bucket({ fileSizeLimit, allowedMimeTypes })`. Storage enforces those at the\n * actual PUT (the only guard a client cannot skip), so `@Upload` deliberately\n * does NOT take its own `maxSize`/`allowedTypes` — duplicating them here would\n * let a route declare a tighter limit than its bucket that storage would not\n * enforce (a real bypass: declare 10 bytes at authorize, then PUT up to the\n * bucket ceiling straight at the signed URL). One bucket, one limit, enforced.\n */\n bucket: PalbaseBucketName;\n /**\n * SERVER-side object key template. The client NEVER chooses the path. Tokens:\n * `{userId}` (authenticated user id), `{uploadId}` (server-minted), and\n * `{filename}` (the client-declared filename, sanitized). e.g.\n * `\"{userId}/{uploadId}-{filename}\"`.\n */\n pathTemplate: string;\n}\n\n/**\n * The uploaded object, injected into an `@Upload` method body by\n * `@UploadedObject()` once storage confirms the upload. Bytes are NOT present\n * (they went straight to storage) — this is the metadata the completion handler\n * persists.\n */\nexport interface UploadedObject {\n /** Server-minted id correlating authorize ↔ completion (idempotency key). */\n uploadId: string;\n /** Final object key in the bucket (rendered from `pathTemplate`). */\n path: string;\n /** Bucket the object landed in. */\n bucket: string;\n /** Object size in bytes, as reported by storage. */\n size: number;\n /** Object MIME type, as reported by storage — detected from the BYTES, not\n * from the filename or from what the client claimed. */\n contentType: string;\n /** SHA-256 of the stored bytes, hex. The same value the object's ETag is\n * derived from, so a client that has it can tell whether it already holds\n * these bytes. */\n checksum: string;\n /** Pixel width, for an image. Absent otherwise — a PDF has no dimensions,\n * and reporting 0 would be a measurement rather than an absence. */\n width?: number;\n /** Pixel height, for an image. */\n height?: number;\n /**\n * A ~25-byte placeholder the client paints INSTANTLY while the real image\n * downloads — the thing that replaces a grey skeleton with something already\n * shaped like the picture. Absent for non-images.\n *\n * Persist it beside the object's path: it costs a column and saves a request\n * per picture on every gallery render.\n */\n thumbhash?: string;\n /**\n * The renditions the bucket declared, by name, as URLs ready to use.\n *\n * Present on the completion input so the handler that stores the row has\n * everything it needs in one place — asking for them afterwards would be a\n * second call per upload, and per picture on every read.\n */\n variants: Record<string, string>;\n}\n\n/**\n * `@Upload(subpath, config)` — declare a direct-storage upload route. The method\n * body is the completion handler; `config.uploadConfig` drives the authorize\n * guard + signed-URL pinning.\n *\n * @example\n * @Upload(\"/\", { bucket: \"docs\", pathTemplate: \"{userId}/{uploadId}-{filename}\" })\n * async upload(@UploadedObject() obj: UploadedObject, @User() user): Promise<DocResult> { ... }\n * // The size limit + MIME allowlist come from the \"docs\" bucket ON THE STACK\n * // — storage enforces them at the PUT.\n */\nexport function Upload(\n subpath: string,\n config: UploadConfig & Pick<RouteOptions, \"auth\" | \"rateLimit\">,\n): MethodDecorator {\n const { auth, rateLimit, ...uploadConfig } = config;\n validateUploadConfigShape(uploadConfig);\n const options: RouteOptions = {\n uploadConfig,\n ...(auth !== undefined ? { auth } : {}),\n ...(rateLimit !== undefined ? { rateLimit } : {}),\n };\n return function (target, propertyKey) {\n // On the wire the authorize pre-flight is a POST; `uploadConfig` is what\n // marks this as an upload route downstream.\n recordRoute(target, String(propertyKey), \"POST\", subpath, options);\n };\n}\n\n/**\n * `@UploadedObject()` — inject the uploaded object (`: UploadedObject`) into an\n * `@Upload` method body (the completion input). Only valid on an `@Upload`\n * route; the bytes are NOT present (they went directly to storage), this is the\n * confirmed object's metadata.\n *\n * Co-located with the {@link UploadedObject} TYPE so a single exported name\n * `UploadedObject` carries BOTH the decorator value and the type annotation.\n */\nexport function UploadedObject(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), {\n index: parameterIndex,\n kind: \"uploadedObject\",\n });\n };\n}\n\n/**\n * Shape-validate an UploadConfig at decoration time (author-time failure beats a\n * silent deploy bug). Does NOT check that the bucket EXISTS — the generated\n * `palbase-stack.d.ts` union does that, and it does it at compile time rather\n * than at deploy.\n */\nexport function validateUploadConfigShape(c: UploadConfig): void {\n if (c === null || typeof c !== \"object\") {\n throw new Error(\"@Upload config must be an object { bucket, pathTemplate, ... }\");\n }\n // Read the bucket through a WIDENED view on purpose. Its declared type is\n // `PalbaseBucketName`, which is `never` until the project generates\n // `palbase-stack.d.ts` — and `never.length` does not typecheck. This function\n // is a RUNTIME guard against a shape the compiler never saw (a plain-JS\n // caller, a bundle boundary), so the value arriving here is genuinely unknown\n // and reading it as such is the honest signature, not a cast to dodge an error.\n const bucket: unknown = (c as { bucket?: unknown }).bucket;\n if (typeof bucket !== \"string\" || bucket.length === 0) {\n throw new Error(\"@Upload config.bucket must be a non-empty bucket name\");\n }\n if (typeof c.pathTemplate !== \"string\" || c.pathTemplate.length === 0) {\n throw new Error(\"@Upload config.pathTemplate must be a non-empty key template\");\n }\n}\n\n","// `@Sse` — the streaming-response decorator, and its `@SseOut` / `@Signal`\n// parameter companions.\n//\n// Unlike `@Get`/`@Post`/… (where the handler's RETURN VALUE is serialised to\n// JSON), an `@Sse` route's method body WRITES frames as it goes and its return\n// value is discarded. The response is `text/event-stream` and stays open until\n// the body returns or the client disconnects.\n//\n// On the wire an `@Sse` route is a POST — a stream is started by a request that\n// carries input. What marks it as a streaming route through the whole pipeline\n// (registry → flatten → openapi → codegen) is the PRESENCE of `sseConfig` on the\n// route, NEVER the verb: an ordinary `@Post` route is also POST, so the verb\n// cannot carry the distinction. This is the same rule `@Upload` states, for the\n// same reason.\n//\n// The problem this solves: a provider on the server (an AI client, a job queue,\n// any long-running producer) streams from a session; while a client is connected\n// the frames reach it, and when the client disconnects the provider must stop\n// being pulled. That last half is what `@Signal()` exists for.\nimport { recordRoute, recordParam } from \"./registry.js\";\nimport type { RouteOptions } from \"./registry.js\";\nimport type { ZodTypeAny } from \"zod\";\n\n/** A legacy method decorator (`experimentalDecorators`): `(prototype, name,\n * descriptor)`. */\ntype MethodDecorator = (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n) => void;\n\n/** A legacy parameter decorator: `(prototype, name, paramIndex)`. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/**\n * Settings for an `@Sse` route.\n *\n * EMPTY in v1, and deliberately so: the pipeline keys off this object's\n * PRESENCE, not its contents (see the file header). Declaring the type now means\n * a later setting arrives as a field on an existing marker rather than as a\n * second marker nothing downstream reads.\n */\nexport interface SseConfig {\n /**\n * The shape of ONE frame — what a single `out.write(value)` carries.\n *\n * REQUIRED, not optional, and that is the whole point. An `@Sse` handler\n * returns `Promise<void>`, so the codegen-injected `recordReturn` has no type\n * to record and nothing downstream can infer what a frame is. A route without\n * this declares a stream whose element type is unknown, and every generated\n * client from that contract is opaque — which is precisely the failure\n * `x-palbase-sse` exists to prevent. Making it optional would have left that\n * failure one forgotten field away.\n *\n * Measured live on a real pushed stack (2026-08-29): the contract gate refused\n * the deploy with \"2 untyped response(s) — every generated client from it is\n * opaque\", naming both routes that omitted it.\n */\n frame: ZodTypeAny;\n}\n\n/**\n * The writer injected by `@SseOut()`. Each `write` emits ONE SSE `data:` frame\n * carrying `value` JSON-encoded.\n *\n * The FIRST `write` is load-bearing beyond its frame: it settles the request's\n * database transaction. A streaming response may run for minutes, and the\n * handler runs inside the request's transaction — holding one open for the life\n * of a stream exhausts the connection pool, a failure invisible to a unit test\n * that only dies under load. So the first frame is the point at which the\n * request phase is declared over, and database access after it is refused by\n * name rather than silently run against a settled transaction.\n *\n * The practical rule for a handler: do the database work BEFORE the first write.\n */\nexport interface SseWriter {\n write(value: unknown): void;\n}\n\n/**\n * `@Sse(subpath, config)` — declare a streaming route.\n *\n * @example\n * @Sse(\"/chat\", { frame: ChatFrame })\n * async chat(@Body() b: ChatInput, @SseOut() out: SseWriter, @Signal() signal: AbortSignal) {\n * const stream = await openai.chat.completions.create(\n * { model: \"gpt-5.6\", messages: b.messages, stream: true },\n * { signal },\n * );\n * for await (const chunk of stream) out.write(chunk);\n * }\n * // The client disconnects → `signal` aborts → the provider stops being pulled.\n * // The signal is a plain AbortSignal, so it goes wherever the provider takes\n * // one: `{ signal }` for the OpenAI and Anthropic SDKs, `abortSignal:` for the\n * // Vercel AI SDK, `fetch(url, { signal })` for a raw call.\n */\nexport function Sse(\n subpath = \"\",\n config: SseConfig & Pick<RouteOptions, \"auth\" | \"rateLimit\">,\n): MethodDecorator {\n const { auth, rateLimit, ...sseConfig } = config;\n const options: RouteOptions = {\n sseConfig,\n ...(auth !== undefined ? { auth } : {}),\n ...(rateLimit !== undefined ? { rateLimit } : {}),\n };\n return function (target, propertyKey) {\n recordRoute(target, String(propertyKey), \"POST\", subpath, options);\n };\n}\n\n/**\n * `@SseOut()` — inject the frame writer (`: SseWriter`) into an `@Sse` method\n * body. Only meaningful on an `@Sse` route.\n */\nexport function SseOut(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), { index: parameterIndex, kind: \"sseOut\" });\n };\n}\n\n/**\n * `@Signal()` — inject the request's `AbortSignal`, which enters the aborted\n * state when the client disconnects.\n *\n * NOT derivable from `@Req()`: `PBRequest` carries only request-scoped data —\n * the typed input, route/query params, headers, the authenticated user, calling\n * client metadata, trace ids, and the declared error throwers — and no signal\n * (endpoint.ts:358-363).\n *\n * Measured 2026-08-29 on Bun: an infinite producer guarded by this signal\n * stopped four frames after the client was killed, and the handler's `finally`\n * ran. It is the same mechanism a NestJS handler reaches through\n * `req.on(\"close\")`.\n */\nexport function Signal(): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), { index: parameterIndex, kind: \"signal\" });\n };\n}\n","// @Room — the realtime surface a backend can actually MANAGE.\n//\n// palbase's realtime lets a backend TALK (broadcast, state.set, push.send) and\n// lets it INTERCEPT a client's publish (defineChannels' handler). What it never\n// let a backend do is SEE the connection: who joined, who left, whether anyone\n// is still watching. A room is that missing half, in the shape this SDK already\n// uses for HTTP — a class with decorated methods.\n//\n// The cost of the gap was concrete: nothing could tell a project that the last\n// device left, so an expensive upstream (an AI session, a market feed, a game\n// loop) kept running and kept billing with nobody reading it. `@OnFirst` and\n// `@OnEmpty` exist for exactly that pair of moments.\n//\n// WHAT A ROOM IS NOT: it does not know where the room id came from, what the\n// history is, or what `@OnFirst` starts. All three belong to the project. The\n// primitive is infrastructure; it carries messages both ways and reports who is\n// present.\n\nimport type { ZodTypeAny } from \"zod\";\nimport {\n recordRoom,\n recordRoomHook,\n recordRoomMessage,\n type RoomHook,\n} from \"./registry.js\";\n\nexport interface RoomOptions {\n /**\n * The events this room sends to its clients, by name.\n *\n * Declared rather than inferred, because a room emits from anywhere in the\n * class — there is no return type to read. The map is the room's public\n * surface: it becomes a Swift enum and a TypeScript union in the generated\n * clients, so a device gets `case .tick(n:)` instead of an opaque bag.\n *\n * Per-event rather than one blob because realtime is event-ADDRESSED all the\n * way down (`Realtime.broadcast(channel, EVENT, payload)`).\n */\n events: Record<string, ZodTypeAny>;\n\n /**\n * How long a room is held after its last sign of life, in milliseconds.\n *\n * Default 60_000, and the floor is not a matter of taste: the decision must\n * survive the SLOWEST client's heartbeat gap twice over, and the web SDK\n * beats every 25 s (palbe/src/realtime/connection.ts:133) against iOS's 2 s\n * (RealtimeConnection.swift:162). A shorter default would declare healthy web\n * clients dead between two beats.\n *\n * Raise it for an upstream that is expensive to restart; lower it (never\n * below ~50 s while web beats at 25 s) for one that is cheap.\n */\n graceMs?: number;\n}\n\n/** Twice the slowest client heartbeat, plus margin. See RoomOptions.graceMs. */\nconst DEFAULT_GRACE_MS = 60_000;\n\n/**\n * A room pattern IS a channel pattern, so it obeys the channel matcher's rules.\n *\n * Both ends of the wire split on `:` — Go's `matchPattern`\n * (internal/modules/rt/channels.go) and this SDK's `matchDeclared` — so a\n * pattern written with slashes matches NO live topic. It fails silently: the\n * room compiles, ships, and simply never fires. Refused here, by name, at the\n * only moment a human is looking.\n *\n * The duplicate-param rule is carried over for the reason channels.ts states:\n * `dm:{uid}:{uid}` against `dm:victim:attacker` lets the last segment win, and\n * an owner check then compares the attacker's id with itself and passes.\n */\nfunction assertPattern(pattern: string): void {\n if (pattern.includes(\"/\")) {\n throw new Error(\n `@Room(\"${pattern}\"): channel patterns are colon-separated, not slash-separated. ` +\n `Write \"${pattern.replace(/\\//g, \":\")}\" — a slash matches no live topic.`,\n );\n }\n const segments = pattern.split(\":\");\n if (segments.some((s) => s === \"\")) {\n throw new Error(`@Room(\"${pattern}\"): empty segment — every segment must be non-empty.`);\n }\n const seen = new Set<string>();\n for (const s of segments) {\n if (!s.startsWith(\"{\") || !s.endsWith(\"}\")) continue;\n const name = s.slice(1, -1);\n if (name === \"\") throw new Error(`@Room(\"${pattern}\"): \"{}\" names no parameter.`);\n if (seen.has(name)) {\n throw new Error(`@Room(\"${pattern}\"): parameter \"{${name}}\" appears twice.`);\n }\n seen.add(name);\n }\n}\n\n/**\n * Declare a class as a room.\n *\n * ```ts\n * @Room(\"chat:{roomId}\", { events: { message: Message } })\n * class ChatRoom {\n * @OnAuthorize() can({ user, params }) { … }\n * @OnFirst() open(ctx) { … } // the room filled\n * @OnEmpty() close(ctx) { … } // nobody is watching any more\n * @OnMessage(\"say\", Say) say(ctx) { … }\n * }\n * ```\n *\n * The pattern is the topic: `chat:{roomId}` addresses `chat:42`. A room is\n * marked by the PRESENCE of this config — never by a name, a base class or a\n * naming convention.\n */\nexport function Room(pattern: string, options: RoomOptions) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n assertPattern(pattern);\n // Member decorators have already run (TypeScript evaluates members before\n // the class), so the hook buffer is complete here and `recordRoom` drains\n // it. controller.ts:203 documents and depends on the same ordering.\n recordRoom(ctor, {\n pattern,\n events: options.events,\n graceMs: options.graceMs ?? DEFAULT_GRACE_MS,\n });\n return ctor;\n };\n}\n\nfunction hookDecorator(hook: RoomHook): () => MethodDecorator {\n return () =>\n function (target: object, propertyKey: string | symbol): void {\n recordRoomHook(target, hook, String(propertyKey));\n };\n}\n\n/** Who may enter. Return a grant to admit, `null` to refuse. */\nexport const OnAuthorize = hookDecorator(\"authorize\");\n\n/**\n * The room is occupied and nobody owns it — start whatever the room needs.\n *\n * Deliberately a CONDITION rather than a 0→1 transition, and the difference is\n * load-bearing: a runtime restart, a deploy pointer swap (the previous release\n * is never torn down) and an owner that died all leave a full room with nobody\n * holding it. A transition would fire once and never again; a condition\n * recovers every time.\n *\n * Exactly one runtime in the cluster enters this hook for a given room, so\n * three devices never open three upstreams.\n */\nexport const OnFirst = hookDecorator(\"first\");\n\n/** A device arrived. Anything emitted here reaches ONLY that device. */\nexport const OnJoin = hookDecorator(\"join\");\n\n/** A device left. */\nexport const OnLeave = hookDecorator(\"leave\");\n\n/** Nobody is watching any more — stop whatever `@OnFirst` started. */\nexport const OnEmpty = hookDecorator(\"empty\");\n\n/**\n * A message from a client, validated against `schema` before the method runs.\n *\n * A payload that fails the schema never reaches the method: the client is told\n * why, and the room's code only ever sees the shape it declared.\n */\nexport function OnMessage(name: string, schema: ZodTypeAny): MethodDecorator {\n return function (target: object, propertyKey: string | symbol): void {\n recordRoomMessage(target, name, String(propertyKey), schema);\n };\n}\n","// Parameter decorators: `@Body` / `@QueryParams` / `@Param` / `@Headers` / `@User` /\n// `@OptionalUser` / `@Client` / `@RequestId` / `@TraceId` / `@Req`. Each records\n// `{ index, kind, schema?, name? }` into the per-class registry for the method\n// it decorates. These are LEGACY parameter decorators\n// (`experimentalDecorators`), receiving `(prototype, methodName, paramIndex)` —\n// esbuild/tsc preserve the param index at runtime (verified, design §0), which\n// is how dispatch injects positionally. No type reflection\n// (`emitDecoratorMetadata`) is used: validation comes from the zod schema, the\n// type annotation the developer writes is purely for autocomplete.\nimport type { ZodTypeAny } from \"zod\";\nimport { recordParam, type ParamKind } from \"./registry.js\";\n\n/** A legacy parameter decorator. */\ntype ParameterDecorator = (\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n) => void;\n\n/** Build a parameter decorator that records the given kind (+ optional schema /\n * name) at the decorated parameter's index. */\nfunction makeParamDecorator(\n kind: ParamKind,\n extra?: { schema?: ZodTypeAny; name?: string },\n): ParameterDecorator {\n return function (target, propertyKey, parameterIndex) {\n recordParam(target, String(propertyKey), {\n index: parameterIndex,\n kind,\n ...(extra?.schema !== undefined ? { schema: extra.schema } : {}),\n ...(extra?.name !== undefined ? { name: extra.name } : {}),\n });\n };\n}\n\n/** `@Body(schema)` — inject the request body, validated against `schema`. The\n * developer writes `: T` (= `z.infer<schema>`, same name) for autocomplete. */\nexport function Body(schema: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"body\", { schema });\n}\n\n/** `@QueryParams(schema)` — inject the parsed query params, validated against\n * `schema`. */\nexport function QueryParams(schema: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"query\", { schema });\n}\n\n/** `@Headers(schema?)` — inject the request headers (lowercase keys). With a\n * schema, headers are validated + the codegen emits header parameters. */\nexport function Headers(schema?: ZodTypeAny): ParameterDecorator {\n return makeParamDecorator(\"headers\", schema !== undefined ? { schema } : undefined);\n}\n\n/** `@Param(\"id\")` — inject one matched path param by name. */\nexport function Param(name: string): ParameterDecorator {\n return makeParamDecorator(\"param\", { name });\n}\n\n/** `@User()` — inject the authenticated user (`: User`, non-null for an\n * effective-required route). The runtime resolves the effective auth. */\nexport function User(): ParameterDecorator {\n return makeParamDecorator(\"user\");\n}\n\n/** `@OptionalUser()` — inject the user as `User | null` (for routes whose\n * effective auth is `false` / `{ required: false }`). */\nexport function OptionalUser(): ParameterDecorator {\n return makeParamDecorator(\"optionalUser\");\n}\n\n/** `@Client()` — inject the parsed calling-client metadata (`: ClientInfo`). */\nexport function Client(): ParameterDecorator {\n return makeParamDecorator(\"client\");\n}\n\n/** `@RequestId()` — inject the per-request id (`: string`). */\nexport function RequestId(): ParameterDecorator {\n return makeParamDecorator(\"requestId\");\n}\n\n/** `@TraceId()` — inject the W3C trace id (`: string`). */\nexport function TraceId(): ParameterDecorator {\n return makeParamDecorator(\"traceId\");\n}\n\n/** `@Req()` — inject the raw request object (escape hatch, `: PBRequest`). */\nexport function Req(): ParameterDecorator {\n return makeParamDecorator(\"req\");\n}\n\n// NOTE: `@UploadedObject()` lives in decorators/upload.ts (co-located with the\n// `UploadedObject` TYPE) so a single exported name carries both the value (the\n// decorator) and the type — TS can only merge value+type under one export name\n// when both are declared in the SAME module.\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients } from \"./endpoint.js\";\nimport type { User } from \"./types.js\";\n\n/** Middleware context — subset of EndpointContext without input (not yet validated). */\nexport interface MiddlewareContext extends PalbaseModuleClients {\n params: Record<string, string>;\n query: Record<string, string>;\n headers: Record<string, string>;\n user: User | null;\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n requestId: string;\n environmentId: string;\n}\n\n/** Middleware function signature — receives context and next function. */\nexport type MiddlewareHandler = (\n ctx: MiddlewareContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/**\n * Define a middleware function for use in the middleware/ directory or\n * as endpoint-specific middleware.\n *\n * Middleware runs before the handler. Call `next()` to pass control\n * to the next middleware or handler. If `next()` is not called, the\n * handler will not execute.\n *\n * Errors thrown in middleware are caught by the pipeline and returned\n * as error responses.\n */\nexport function defineMiddleware(fn: MiddlewareHandler): MiddlewareHandler {\n return fn;\n}\n","/**\n * The brand that identifies an HttpError ACROSS SDK instances.\n *\n * A process legitimately holds more than one copy of this SDK — the runtime\n * loads the engine from its own node_modules while the tenant's bundle carries\n * an inlined copy, which is why the controller registry and the error registry\n * are both anchored on `Symbol.for`. The one place that did not follow the\n * pattern was the engine's catch: `err instanceof HttpError` compares CLASS\n * IDENTITY, so a `throw new NotFound()` from the bundle's copy did not match\n * the engine's copy and every typed error in every deployed backend degraded to\n * `500 internal_error`. Measured through the edge on a real deploy: a route\n * throwing `NotFound` answered 500 while the runtime's own log printed the\n * error object with `status: 404` right beside it.\n *\n * `Symbol.for` puts this in the cross-realm registry, so every copy of the SDK\n * agrees on it by VALUE rather than by identity.\n */\nexport const HTTP_ERROR_BRAND: unique symbol = Symbol.for(\"palbase.backend.httpError\");\n\n/**\n * Set on an `HttpError` the ENGINE built out of a driver failure, as opposed to\n * one the author constructed to ANSWER a request.\n *\n * The distinction cannot be read off the status, and 409 is why. The scaffold\n * teaches `throw new Conflict(\"title already taken\")` as the way to answer\n * (template/AGENTS.md), and the engine raises `UniqueViolation` — also a 409 —\n * when a write hits a unique index. Logging by status therefore either loses the\n * engine's event or writes an \"unhandled\" line every time an author takes the\n * documented path. Measured: it did the second.\n *\n * `Symbol.for` so the mark survives the bundle/runtime SDK split, the same way\n * {@link HTTP_ERROR_BRAND} does.\n */\nexport const ENGINE_RAISED: unique symbol = Symbol.for(\"palbase.backend.engineRaised\") as never;\n\n/** Mark `e` as engine-raised and return it, so a conversion site reads as one expression. */\nexport function markEngineRaised<E extends object>(e: E): E {\n (e as Record<symbol, unknown>)[ENGINE_RAISED] = true;\n return e;\n}\n\n/** Whether the engine built this error, rather than the author throwing it to answer. */\nexport function isEngineRaised(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as Record<symbol, unknown>)[ENGINE_RAISED] === true;\n}\n\n/**\n * Whether a thrown value is an HttpError from ANY copy of this SDK.\n *\n * The shape is checked as well as the brand: the brand says \"this claims to be\n * one of ours\", the fields say the envelope can actually be built from it, and\n * a half-formed object must fall through to the 500 path rather than produce a\n * malformed response.\n */\nexport function isHttpError(err: unknown): err is HttpError {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as Record<PropertyKey, unknown>;\n return (\n e[HTTP_ERROR_BRAND] === true &&\n typeof e.status === \"number\" &&\n typeof e.error === \"string\" &&\n typeof e.errorDescription === \"string\"\n );\n}\n\n/** HTTP error with structured error response format.\n *\n * The base class for the throwable error classes (`PalError`, `Conflict`,\n * `NotFound`, …). Construct one directly with `throw new HttpError(404,\n * \"todo_not_found\", \"No such todo\")`, or throw a named subclass\n * (`throw new NotFound(\"todo not found\")`). The runtime catches any `HttpError`\n * and emits the standard envelope; on the wire (and to iOS) it surfaces as\n * `BackendError.server(code, status, message, requestId)`.\n *\n * The optional `data` field carries a structured payload alongside the\n * standard envelope — for errors that need to ship extra context\n * (e.g. `new Conflict(\"locked\", \"title_locked\", { retryAfter: 30 })`). It rides\n * through to the iOS typed enum's associated value.\n */\nexport class HttpError extends Error {\n public readonly status: number;\n public readonly error: string;\n public readonly errorDescription: string;\n public readonly data?: unknown;\n /** See {@link HTTP_ERROR_BRAND} — how the engine recognises this across SDK copies. */\n public readonly [HTTP_ERROR_BRAND] = true;\n\n constructor(status: number, error: string, errorDescription: string, data?: unknown) {\n super(errorDescription);\n this.name = \"HttpError\";\n this.status = status;\n this.error = error;\n this.errorDescription = errorDescription;\n if (data !== undefined) {\n this.data = data;\n }\n }\n\n /**\n * Serialize to the standard Palbase error response format.\n * The `requestId` is injected by the runtime layer from the request context.\n * When called without arguments (e.g. JSON.stringify), request_id is omitted.\n * When `data` is set, it is appended as a strict-superset field.\n */\n toJSON(requestId?: string): {\n error: string;\n error_description: string;\n status: number;\n request_id?: string;\n data?: unknown;\n } {\n const result: {\n error: string;\n error_description: string;\n status: number;\n request_id?: string;\n data?: unknown;\n } = {\n error: this.error,\n error_description: this.errorDescription,\n status: this.status,\n };\n if (requestId) {\n result.request_id = requestId;\n }\n if (this.data !== undefined) {\n result.data = this.data;\n }\n return result;\n }\n}\n\n/**\n * Throw with a custom HTTP status + wire code. The general-purpose escape hatch\n * when none of the named classes (`Conflict`/`NotFound`/…) fits.\n *\n * @example\n * throw new PalError(418, \"teapot\", \"I'm a teapot\");\n */\nexport class PalError extends HttpError {\n constructor(status: number, code: string, description: string, data?: unknown) {\n super(status, code, description, data);\n this.name = \"PalError\";\n }\n}\n\n/** Base for the named status classes. Each subclass fixes its HTTP status; the\n * `code` defaults to the class's canonical wire code (overridable), and the\n * `message` defaults to a human-readable label (overridable). */\nabstract class NamedHttpError extends HttpError {\n protected constructor(\n status: number,\n defaultCode: string,\n name: string,\n message?: string,\n code?: string,\n data?: unknown,\n ) {\n super(status, code ?? defaultCode, message ?? defaultMessage(name), data);\n this.name = name;\n }\n}\n\n/** Derive a default human-readable message from a class name\n * (\"NotFound\" → \"Not found\", \"TooManyRequests\" → \"Too many requests\"). */\nfunction defaultMessage(name: string): string {\n const spaced = name.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\");\n return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n}\n\n/**\n * 400 — the request was malformed or failed validation. Carries a fixed typed\n * payload: `new BadRequest({ fields: [{ field: \"email\", message: \"invalid\" }] })`.\n * The shape is declared once in the SDK so codegen surfaces `error.data.fields`\n * typed on the client.\n */\nexport class BadRequest extends NamedHttpError {\n public declare readonly data: BadRequestData;\n constructor(data: BadRequestData, message?: string) {\n super(400, \"bad_request\", \"BadRequest\", message, undefined, data);\n }\n}\n\n/** 401 — the caller is not authenticated. */\nexport class Unauthorized extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(401, \"unauthorized\", \"Unauthorized\", message, code, data);\n }\n}\n\n/** 403 — the caller is authenticated but not allowed. */\nexport class Forbidden extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(403, \"forbidden\", \"Forbidden\", message, code, data);\n }\n}\n\n/** 404 — the requested resource does not exist. */\nexport class NotFound extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(404, \"not_found\", \"NotFound\", message, code, data);\n }\n}\n\n/** 409 — the request conflicts with the current state. */\nexport class Conflict extends NamedHttpError {\n constructor(message?: string, code?: string, data?: unknown) {\n super(409, \"conflict\", \"Conflict\", message, code, data);\n }\n}\n\n/**\n * 409 — a write was refused because it would duplicate an existing row.\n * Carries the NAME of the unique constraint Postgres named (`users_email_key`).\n *\n * The engine produces it: a statement rejected with SQLSTATE `23505` is\n * converted here rather than surfacing as an opaque driver error (see\n * `engine/db.ts`, `diagnosingDriver`). What that removes is the string match —\n * before this, the only way to act on a duplicate was to test the driver\n * message for \"duplicate key value violates unique constraint\", a contract\n * nobody signed that breaks on a Postgres upgrade, a locale, or a constraint\n * rename, silently and in production.\n *\n * THE NAME IS A FIELD AND STAYS OUT OF THE DEFAULT MESSAGE. The two are not\n * the same audience. `constraint` is read by the code that catches this — the\n * developer, who already knows the schema. `errorDescription` is the HTTP\n * response body, and an UNCAUGHT duplicate puts it in front of the\n * application's end user: `users_email_key` there discloses how the schema is\n * built to whoever sent the request. The platform's own data API took the same\n * decision one surface over and wrote down why —\n * `v2/internal/modules/database/internal/handler/pgerror.go:83-87` collapses\n * every 23xxx to a generic conflict, \"never disclose the constraint/column\n * name\". A thrower who WANTS the name on the wire passes it deliberately\n * (`new UniqueViolation(c, \\`\\${c} already exists\\`)`, or through `data`).\n *\n * @example\n * try {\n * await Database.tables.users.insert({ email });\n * } catch (e) {\n * if (UniqueViolation.is(e) && e.constraint === \"users_email_key\") {\n * throw new Conflict(\"That email is taken\", \"email_taken\");\n * }\n * throw e;\n * }\n */\nexport class UniqueViolation extends Conflict {\n /**\n * Whether `e` is a unique violation — REGARDLESS of which copy of this SDK\n * constructed it.\n *\n * Use this instead of `instanceof`. Measured on a live stack: a controller\n * bundle INLINES its own copy of `@palbase/backend`, and the engine that\n * raises this error is the runtime's copy. Two copies, two class identities,\n * and `e instanceof UniqueViolation` is false in the one place a caller\n * writes it — a check that reads as correct and silently never matches.\n */\n static is(e: unknown): e is UniqueViolation {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { name?: unknown }).name === \"UniqueViolation\" &&\n typeof (e as { constraint?: unknown }).constraint === \"string\"\n );\n }\n\n /** The unique constraint the statement violated, as Postgres named it.\n * `\"\"` when the driver did not say which — see `engine/db.ts`. */\n public readonly constraint: string;\n\n constructor(constraint: string, message?: string, code?: string, data?: unknown) {\n super(message ?? \"Unique constraint violated\", code ?? \"unique_violation\", data);\n this.name = \"UniqueViolation\";\n this.constraint = constraint;\n }\n}\n\n/** A single field-level validation failure carried by {@link BadRequest}. */\nexport interface FieldError {\n /** The offending field's name (dotted path for nested fields). */\n field: string;\n /** Human-readable reason the field failed. */\n message: string;\n}\n\n/** The fixed, typed payload {@link BadRequest} ships. */\nexport interface BadRequestData {\n /** The fields that failed validation. */\n fields: FieldError[];\n}\n\n/** The fixed, typed payload {@link TooManyRequests} ships. */\nexport interface TooManyRequestsData {\n /** Seconds the caller should wait before retrying. */\n retryAfter: number;\n}\n\n/**\n * 429 — the caller has exceeded the rate limit. Carries a fixed typed payload:\n * `new TooManyRequests({ retryAfter: 30 })`. The shape is declared once in the\n * SDK (error-registry pre-seed) so codegen surfaces `error.data.retryAfter`\n * typed on the client — no per-project definition needed.\n */\nexport class TooManyRequests extends NamedHttpError {\n public declare readonly data: TooManyRequestsData;\n constructor(data: TooManyRequestsData, message?: string) {\n super(429, \"too_many_requests\", \"TooManyRequests\", message, undefined, data);\n }\n}\n","// defineError — project-defined typed error classes + the module-global error\n// registry the OpenAPI spec twins join against.\n//\n// `defineError(code, status, dataSchema?)` returns an `HttpError` subclass whose\n// constructor is typed by the zod schema (`new TodoLocked({ retryAfter: 30 })`).\n// Each call self-registers `{ code, status, className, dataSchema }` in a\n// registry anchored on `globalThis` under `Symbol.for(...)` — mirroring the\n// ROUTES pattern — so the deploy bundle's registrations land on the single SDK\n// instance the extractor `require()`s. The registry is pre-seeded with the named\n// built-in classes (`NotFound`, `Conflict`, …) so throw inference can resolve\n// ad-hoc `throw new NotFound(...)` sites by their canonical wire codes.\n//\n// Duplicate code with a DIFFERENT shape (status OR converted data schema) is a\n// hard error at registration time (deploy fails loudly — error codes are\n// project-unique); structurally-identical re-registration is idempotent (each\n// controller BUNDLE carries its own copy of a shared models/errors.ts, so the\n// same defineError line legitimately runs once per bundle in one process).\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z, type ZodTypeAny } from \"zod\";\nimport { HttpError } from \"./errors.js\";\n\nextendZodWithOpenApi(z);\n\n/** One registered error: the wire code, HTTP status, the class name the\n * analyzer sees, the optional data payload schema, and whether it is one of the\n * pre-seeded built-in named classes. */\nexport interface RegisteredError {\n code: string;\n status: number;\n className: string;\n dataSchema?: ZodTypeAny;\n /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec\n * twins would emit an identical `data` schema for this error. */\n dataDigest?: string;\n builtin: boolean;\n}\n\n/** The cross-module-instance registry anchor (the pinned contract symbol). */\nconst ERROR_REGISTRY: unique symbol = Symbol.for(\"palbase.backend.errorRegistry\");\n\ninterface RegistryCarrier {\n [ERROR_REGISTRY]?: Map<string, RegisteredError>;\n}\n\n/** Get (creating + pre-seeding if absent) the project-global error registry,\n * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a\n * process shares the one registry. */\n/** The fixed data schemas the built-in named errors ship. Declared HERE (not in\n * errors.ts, which stays zod-free) because this is where the registry converts\n * them to JSON-schema for the spec — keying codegen's typed `error.data`. Only\n * the errors that semantically carry a payload have a schema; the rest are\n * data-less. `.int()` is preserved so the wire/codegen sees an integer. */\nconst BUILTIN_DATA_SCHEMAS: Record<string, ZodTypeAny> = {\n bad_request: z.object({\n fields: z.array(z.object({ field: z.string(), message: z.string() })),\n }),\n too_many_requests: z.object({ retryAfter: z.number().int() }),\n};\n\nexport function getErrorRegistry(): Map<string, RegisteredError> {\n const g = globalThis as RegistryCarrier;\n if (!g[ERROR_REGISTRY]) {\n const m = new Map<string, RegisteredError>();\n for (const [code, status, className] of [\n [\"bad_request\", 400, \"BadRequest\"],\n [\"unauthorized\", 401, \"Unauthorized\"],\n [\"forbidden\", 403, \"Forbidden\"],\n [\"not_found\", 404, \"NotFound\"],\n [\"conflict\", 409, \"Conflict\"],\n // The engine's own 23505 conversion (engine/db.ts) throws this, and an\n // author may too. Registered like every other built-in so the spec\n // emitter resolves it — an unregistered code is SKIPPED silently there\n // (openapi/convert.ts) and would degrade to the client's `.other` case.\n [\"unique_violation\", 409, \"UniqueViolation\"],\n [\"too_many_requests\", 429, \"TooManyRequests\"],\n ] as const) {\n const dataSchema = BUILTIN_DATA_SCHEMAS[code];\n m.set(code, {\n code,\n status,\n className,\n builtin: true,\n ...(dataSchema ? { dataSchema, dataDigest: digestOf(code, dataSchema) } : {}),\n });\n }\n g[ERROR_REGISTRY] = m;\n }\n return g[ERROR_REGISTRY];\n}\n\n/** Class returned for schema-bearing errors: ctor(data, message?). */\nexport interface DefinedErrorWithData<S extends ZodTypeAny> {\n new (data: z.input<S>, message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/** Class returned for schema-less errors: ctor(message?). */\nexport interface DefinedError {\n new (message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/**\n * Define a project error class. MUST be called with literal args (string\n * literal `code`, numeric literal `status`) at module top level — the deploy\n * stager's static analyzer reads those literals to resolve throw sites.\n *\n * @example\n * // models/todos/errors.ts\n * export const TodoLocked = defineError(\"todo_locked\", 409, z.object({ retryAfter: z.number() }));\n * // services/todo.service.ts\n * throw new TodoLocked({ retryAfter: 30 });\n */\nexport function defineError<S extends ZodTypeAny>(\n code: string,\n status: number,\n dataSchema: S,\n): DefinedErrorWithData<S>;\nexport function defineError(code: string, status: number): DefinedError;\nexport function defineError(code: string, status: number, dataSchema?: ZodTypeAny): unknown {\n if (!Number.isInteger(status) || status < 400 || status > 599) {\n throw new Error(\n `defineError: status for \"${code}\" must be a 4xx/5xx integer, got ${status} — ` +\n `error responses must not clobber success responses in the project spec.`,\n );\n }\n const registry = getErrorRegistry();\n const existing = registry.get(code);\n const className = defaultClassName(code);\n const dataDigest = dataSchema ? digestOf(code, dataSchema) : undefined;\n if (existing) {\n const sameShape =\n existing.status === status && !existing.builtin && existing.dataDigest === dataDigest;\n if (!sameShape) {\n throw new Error(\n `defineError: duplicate error code \"${code}\" with a different shape ` +\n `(existing: status ${existing.status}${existing.builtin ? \", built-in\" : \"\"}` +\n `${existing.status === status && !existing.builtin ? \", different data schema\" : \"\"}). ` +\n `Error codes are project-unique.`,\n );\n }\n }\n // Local factories so the class-constructor closures capture a NON-optional\n // schema binding (narrowing does not flow into closures created in a branch).\n const makeWithData = (schema: ZodTypeAny) =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(data: unknown, message?: string) {\n super(status, code, message ?? humanize(code), schema.parse(data));\n this.name = className;\n }\n };\n const makeWithoutData = () =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(message?: string) {\n super(status, code, message ?? humanize(code));\n this.name = className;\n }\n };\n const cls = dataSchema ? makeWithData(dataSchema) : makeWithoutData();\n Object.defineProperty(cls, \"name\", { value: className });\n registry.set(code, {\n code,\n status,\n className,\n builtin: false,\n ...(dataSchema ? { dataSchema } : {}),\n ...(dataDigest !== undefined ? { dataDigest } : {}),\n });\n return cls;\n}\n\n/** Convert a data schema through the SAME library the spec twins use and\n * return its JSON-schema digest (the duplicate-shape comparison key). Doubles\n * as the self-containment guard: a schema carrying `.openapi(refId)` metadata\n * (top-level or nested) converts to `$ref` pointers into components the\n * project spec never emits — a dangling ref every spec consumer would choke\n * on — so it is rejected here, at the definition site, with a fixable message. */\nfunction digestOf(code: string, dataSchema: ZodTypeAny): string {\n const TMP_REF = \"__PalbaseErrorDataDigest\";\n const tmpRegistry = new OpenAPIRegistry();\n // Wrap the schema as a property — exactly how the envelope embeds it — so a\n // TOP-LEVEL .openapi(refId) is not masked by the registration refId and\n // surfaces as the same $ref the real emission would produce.\n tmpRegistry.register(TMP_REF, z.object({ data: dataSchema }).openapi(TMP_REF));\n const generated = new OpenApiGeneratorV31(tmpRegistry.definitions).generateComponents();\n const out = generated.components?.schemas?.[TMP_REF];\n const digest = JSON.stringify(out ?? null);\n if (digest.includes('\"$ref\"')) {\n throw new Error(\n `defineError: dataSchema for \"${code}\" carries .openapi(refId) metadata — ` +\n `it would emit dangling $ref pointers in the project spec. ` +\n `Use a plain zod schema (z.object({...})) without .openapi(...).`,\n );\n }\n return digest;\n}\n\n/** \"todo_locked\" → \"TodoLocked\" (used as Error.name; the source class NAME the\n * analyzer sees is whatever the user assigned the const to — they should match\n * by convention, and the descriptor carries the analyzed const name anyway). */\nfunction defaultClassName(code: string): string {\n return code\n .split(\"_\")\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n}\n\n/** \"todo_locked\" → \"Todo locked\" — the default human-readable message. */\nfunction humanize(code: string): string {\n const s = code.replace(/_/g, \" \");\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n","/** Non-service, per-invocation data for job handlers.\n * Services (Database, Log, …) are imported as singletons, not passed here. */\nexport interface JobMeta {\n /** Environment-scoped env vars. */\n env: Record<string, string>;\n /** The globally unique Environment runtime identifier. */\n environmentId: string;\n}\n\n/**\n * Cron expression validation.\n * Supports standard 5-field cron: minute hour day-of-month month day-of-week.\n * Each field allows: number, *, ranges (1-5), steps (star/2), lists (1,3,5).\n */\nexport function validateCronExpression(expression: string): string | null {\n const trimmed = expression.trim();\n if (trimmed === \"\") {\n return \"Cron expression is required\";\n }\n\n const parts = trimmed.split(/\\s+/);\n if (parts.length !== 5) {\n return `Invalid cron expression \"${trimmed}\": expected 5 fields (minute hour day month weekday), got ${parts.length}`;\n }\n\n const fieldNames = [\"minute\", \"hour\", \"day of month\", \"month\", \"day of week\"];\n const fieldRanges: [number, number][] = [\n [0, 59],\n [0, 23],\n [1, 31],\n [1, 12],\n [0, 7],\n ];\n\n for (let i = 0; i < 5; i++) {\n const field = parts[i]!;\n const name = fieldNames[i]!;\n const [min, max] = fieldRanges[i]!;\n\n const error = validateCronField(field, name, min, max);\n if (error !== null) {\n return error;\n }\n }\n\n return null;\n}\n\nfunction validateCronField(\n field: string,\n name: string,\n min: number,\n max: number,\n): string | null {\n // Split by comma for lists\n const listParts = field.split(\",\");\n for (const part of listParts) {\n // Check for step: */2, 1-5/2\n const stepParts = part.split(\"/\");\n if (stepParts.length > 2) {\n return `Invalid ${name} field: \"${field}\"`;\n }\n\n const base = stepParts[0]!;\n const step = stepParts[1];\n\n if (step !== undefined) {\n const stepNum = Number(step);\n if (!Number.isInteger(stepNum) || stepNum < 1) {\n return `Invalid step value in ${name} field: \"${field}\"`;\n }\n }\n\n if (base === \"*\") {\n continue;\n }\n\n // Check for range: 1-5\n if (base.includes(\"-\")) {\n const rangeParts = base.split(\"-\");\n if (rangeParts.length !== 2) {\n return `Invalid range in ${name} field: \"${field}\"`;\n }\n const rangeStart = Number(rangeParts[0]);\n const rangeEnd = Number(rangeParts[1]);\n if (\n !Number.isInteger(rangeStart) ||\n !Number.isInteger(rangeEnd) ||\n rangeStart < min ||\n rangeEnd > max ||\n rangeStart > rangeEnd\n ) {\n return `Invalid range in ${name} field: \"${field}\"`;\n }\n continue;\n }\n\n // Single number\n const num = Number(base);\n if (!Number.isInteger(num) || num < min || num > max) {\n return `Invalid value in ${name} field: \"${field}\"`;\n }\n }\n\n return null;\n}\n","import { assertZeroArgConstructor } from \"./controller.js\";\n// @Job — the cron half of the decorator surface. Same metadata mechanism as\n// @Webhook/@Controller. The job's NAME is not here on purpose: it is the file\n// name, which is also what the Temporal schedule id is built from. Two names\n// with nothing reconciling them is what this replaces.\nimport type { JobMeta } from \"../job.js\";\nimport { validateCronExpression } from \"../job.js\";\n\nexport interface JobOptions {\n /** Cron expression, five fields (e.g. \"0 3 * * *\"). */\n schedule: string;\n /** Execution timeout in seconds. Defaults to 30, ceiling 300 (sandbox limit). */\n timeout?: number;\n /**\n * How many times a FAILED run is retried before the run is recorded failed.\n * Defaults to 5, ceiling 10; 0 disables retrying entirely.\n *\n * Retries exist for the transient half of the failure space — the runtime\n * still waking, a network blip — not for a job that is wrong. A permanent\n * failure still lands in the run history, it just lands after the retries\n * are spent rather than instead of them.\n */\n retry?: number;\n}\n\nexport interface ResolvedJob {\n schedule: string;\n timeout: number;\n retry: number;\n handler: (meta: JobMeta) => Promise<void>;\n}\n\nconst DEFAULT_TIMEOUT_SECONDS = 30;\nconst MAX_TIMEOUT_SECONDS = 300;\nconst DEFAULT_RETRY = 5;\nconst MAX_RETRY = 10;\n\nexport const JOB_META: unique symbol = Symbol.for(\"palbase.backend.jobMeta\");\n\ninterface JobCarrier {\n __palbase?: \"job\";\n [JOB_META]?: JobOptions;\n}\n\nexport function Job(options: JobOptions) {\n return function <T extends abstract new (...args: never[]) => object>(ctor: T): T {\n const carrier = ctor as unknown as JobCarrier;\n Object.defineProperty(carrier, JOB_META, {\n value: options,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(carrier, \"__palbase\", {\n value: \"job\",\n enumerable: false,\n configurable: true,\n writable: false,\n });\n return ctor;\n };\n}\n\nexport function getJobConfig(ctor: object): ResolvedJob {\n const meta = (ctor as JobCarrier)[JOB_META];\n if (!meta) {\n throw new Error(\n `getJobConfig on a class with no @Job decorator (${(ctor as { name?: string }).name ?? \"anonymous\"})`,\n );\n }\n if (!meta.schedule || meta.schedule.trim() === \"\") {\n throw new Error(\"@Job requires a `schedule` cron expression\");\n }\n const cronError = validateCronExpression(meta.schedule);\n if (cronError) {\n throw new Error(`@Job has an invalid cron schedule: ${cronError}`);\n }\n\n const timeout = meta.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n if (!Number.isInteger(timeout) || timeout <= 0) {\n throw new Error(\"@Job `timeout` must be a positive whole number of seconds\");\n }\n if (timeout > MAX_TIMEOUT_SECONDS) {\n throw new Error(`@Job \\`timeout\\` exceeds the ${MAX_TIMEOUT_SECONDS}s sandbox ceiling`);\n }\n\n const retry = meta.retry ?? DEFAULT_RETRY;\n if (!Number.isInteger(retry) || retry < 0) {\n throw new Error(\"@Job `retry` must be a whole number of attempts, zero or more\");\n }\n if (retry > MAX_RETRY) {\n throw new Error(`@Job \\`retry\\` exceeds the ceiling of ${MAX_RETRY}`);\n }\n\n // The `new ()` in the cast below is a CLAIM — that the class is constructible\n // with no arguments — and this check is what makes it true. Without it the\n // cast quietly held for `constructor(dep: Repo)` too: the call compiled, it\n // deployed, and the field arrived as `undefined` at the first scheduled run. Same refusal\n // as the controller's (engine/router.ts, FR-010).\n assertZeroArgConstructor(ctor, \"job class\");\n\n const instance = new (ctor as new () => { run?: (meta: JobMeta) => Promise<void> })();\n if (typeof instance.run !== \"function\") {\n throw new Error(\"@Job class must declare an async run() method\");\n }\n const run = instance.run.bind(instance);\n\n return { schedule: meta.schedule, timeout, retry, handler: run };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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