@palbase/backend 1.0.0 → 2.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.
- package/dist/{chunk-7N5ICXCB.js → chunk-L36JLUPO.js} +11 -2
- package/dist/chunk-L36JLUPO.js.map +1 -0
- package/dist/{endpoint-yn2xcrWu.d.cts → endpoint-BlcY2xNA.d.cts} +11 -11
- package/dist/{endpoint-knNIeovM.d.ts → endpoint-Djk5L6G2.d.ts} +11 -11
- package/dist/index.cjs +14 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +44 -16
- package/dist/index.d.ts +44 -16
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +5 -1
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +1 -1
- package/dist/test/index.d.ts +1 -1
- package/dist/test/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-7N5ICXCB.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { D as DBClient, C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, Q as QueueClient, c as PalbaseStorageClient, d as PalbaseModuleClients, U as User, E as ErrorThrowers } from './endpoint-
|
|
2
|
-
export { A as AuthConfig, e as ClientInfo, f as EndpointConfig, g as ErrorDef, h as ErrorMap, F as FileContext, H as HttpError, i as HttpMethod, M as Middleware, j as MiddlewareContext, k as MiddlewareHandler, l as PBRequest, m as PalbaseAnalyticsClient, n as PalbaseAnalyticsManagementNamespace, o as PalbaseAnalyticsProperties, p as PalbaseAnalyticsQueryNamespace, q as PalbaseAttestAndroidParams, r as PalbaseAttestAndroidResult, s as PalbaseAttestiOSParams, t as PalbaseAttestiOSResult, u as PalbaseAuthClient, v as PalbaseBindDeviceParams, w as PalbaseBucketClient, x as PalbaseCmsClient, y as PalbaseCmsFindOneOptions, z as PalbaseCmsFindOptions, B as PalbaseCohortQueryInput, G as PalbaseCohortResult, I as PalbaseCollectionRef, J as PalbaseCountQueryInput, K as PalbaseCountResult, N as PalbaseCreateLinkParams, O as PalbaseDeviceInfo, R as PalbaseDeviceTokenView, S as PalbaseDocumentRef, T as PalbaseDocumentSnapshot, V as PalbaseEmailClient, W as PalbaseEmailSendParams, X as PalbaseEmailSendResponse, Y as PalbaseEventNamesResult, Z as PalbaseEventsQueryInput, _ as PalbaseEventsResult, $ as PalbaseFileObject, a0 as PalbaseFlag, a1 as PalbaseFlagContext, a2 as PalbaseFlagVariant, a3 as PalbaseFunctionsClient, a4 as PalbaseFunnelQueryInput, a5 as PalbaseFunnelResult, a6 as PalbaseIdentifyTraits, a7 as PalbaseInboxClient, a8 as PalbaseInboxListOptions, a9 as PalbaseInboxListResult, aa as PalbaseInboxMessage, ab as PalbaseInboxSendParams, ac as PalbaseInboxSendResponse, ad as PalbaseInitialLink, ae as PalbaseInvokeOptions, af as PalbaseLink, ag as PalbaseLinkAnalytics, ah as PalbaseLinkDetails, ai as PalbaseLinksClient, aj as PalbaseListLinksOptions, ak as PalbaseListLinksResult, al as PalbaseListOptions, am as PalbaseMatchParams, an as PalbaseMultiChannelResponse, ao as PalbaseOverviewResult, ap as PalbasePreferences, aq as PalbasePreferencesClient, ar as PalbasePublicUrlResponse, as as PalbasePushClient, at as PalbasePushSendParams, au as PalbasePushSendResponse, av as PalbaseQrCodeOptions, aw as PalbaseQuerySnapshot, ax as PalbaseRealtimeChannel, ay as PalbaseRealtimeClient, az as PalbaseRealtimeMessage, aA as PalbaseRegisterDeviceParams, aB as PalbaseResult, aC as PalbaseRetentionQueryInput, aD as PalbaseRetentionResult, aE as PalbaseSession, aF as PalbaseSignedUrlResponse, aG as PalbaseSmsClient, aH as PalbaseSmsSendParams, aI as PalbaseSmsSendResponse, aJ as PalbaseTransformOptions, aK as PalbaseUpdateLinkParams, aL as PalbaseUploadOptions, aM as PalbaseUser, aN as PalbaseUserDetailResult, aO as PalbaseUsersQueryInput, aP as PalbaseUsersResult, aQ as PalbaseVerifyRequestSignatureParams, aR as PalbaseWhereOperator, aS as RateLimitConfig, aT as TxClient, aU as defineEndpoint, aV as defineMiddleware } from './endpoint-
|
|
1
|
+
import { D as DBClient, C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, Q as QueueClient, c as PalbaseStorageClient, d as PalbaseModuleClients, U as User, E as ErrorThrowers } from './endpoint-Djk5L6G2.js';
|
|
2
|
+
export { A as AuthConfig, e as ClientInfo, f as EndpointConfig, g as ErrorDef, h as ErrorMap, F as FileContext, H as HttpError, i as HttpMethod, M as Middleware, j as MiddlewareContext, k as MiddlewareHandler, l as PBRequest, m as PalbaseAnalyticsClient, n as PalbaseAnalyticsManagementNamespace, o as PalbaseAnalyticsProperties, p as PalbaseAnalyticsQueryNamespace, q as PalbaseAttestAndroidParams, r as PalbaseAttestAndroidResult, s as PalbaseAttestiOSParams, t as PalbaseAttestiOSResult, u as PalbaseAuthClient, v as PalbaseBindDeviceParams, w as PalbaseBucketClient, x as PalbaseCmsClient, y as PalbaseCmsFindOneOptions, z as PalbaseCmsFindOptions, B as PalbaseCohortQueryInput, G as PalbaseCohortResult, I as PalbaseCollectionRef, J as PalbaseCountQueryInput, K as PalbaseCountResult, N as PalbaseCreateLinkParams, O as PalbaseDeviceInfo, R as PalbaseDeviceTokenView, S as PalbaseDocumentRef, T as PalbaseDocumentSnapshot, V as PalbaseEmailClient, W as PalbaseEmailSendParams, X as PalbaseEmailSendResponse, Y as PalbaseEventNamesResult, Z as PalbaseEventsQueryInput, _ as PalbaseEventsResult, $ as PalbaseFileObject, a0 as PalbaseFlag, a1 as PalbaseFlagContext, a2 as PalbaseFlagVariant, a3 as PalbaseFunctionsClient, a4 as PalbaseFunnelQueryInput, a5 as PalbaseFunnelResult, a6 as PalbaseIdentifyTraits, a7 as PalbaseInboxClient, a8 as PalbaseInboxListOptions, a9 as PalbaseInboxListResult, aa as PalbaseInboxMessage, ab as PalbaseInboxSendParams, ac as PalbaseInboxSendResponse, ad as PalbaseInitialLink, ae as PalbaseInvokeOptions, af as PalbaseLink, ag as PalbaseLinkAnalytics, ah as PalbaseLinkDetails, ai as PalbaseLinksClient, aj as PalbaseListLinksOptions, ak as PalbaseListLinksResult, al as PalbaseListOptions, am as PalbaseMatchParams, an as PalbaseMultiChannelResponse, ao as PalbaseOverviewResult, ap as PalbasePreferences, aq as PalbasePreferencesClient, ar as PalbasePublicUrlResponse, as as PalbasePushClient, at as PalbasePushSendParams, au as PalbasePushSendResponse, av as PalbaseQrCodeOptions, aw as PalbaseQuerySnapshot, ax as PalbaseRealtimeChannel, ay as PalbaseRealtimeClient, az as PalbaseRealtimeMessage, aA as PalbaseRegisterDeviceParams, aB as PalbaseResult, aC as PalbaseRetentionQueryInput, aD as PalbaseRetentionResult, aE as PalbaseSession, aF as PalbaseSignedUrlResponse, aG as PalbaseSmsClient, aH as PalbaseSmsSendParams, aI as PalbaseSmsSendResponse, aJ as PalbaseTransformOptions, aK as PalbaseUpdateLinkParams, aL as PalbaseUploadOptions, aM as PalbaseUser, aN as PalbaseUserDetailResult, aO as PalbaseUsersQueryInput, aP as PalbaseUsersResult, aQ as PalbaseVerifyRequestSignatureParams, aR as PalbaseWhereOperator, aS as RateLimitConfig, aT as TxClient, aU as defineEndpoint, aV as defineMiddleware } from './endpoint-Djk5L6G2.js';
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
4
|
import { T as TableDef, C as ColIsOptionalOnInsert, a as ColValue, S as SchemaDef } from './schema-BqfEhIC0.js';
|
|
4
5
|
export { b as ColumnBuilder, c as ColumnDef, d as ColumnType, O as OnDeleteAction, e as boolean, f as defineSchema, g as enumType, i as integer, j as jsonb, t as table, h as text, k as timestamp, u as uuid } from './schema-BqfEhIC0.js';
|
|
5
6
|
export { z } from 'zod';
|
|
@@ -106,19 +107,29 @@ declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): Typ
|
|
|
106
107
|
* });
|
|
107
108
|
*
|
|
108
109
|
* The singletons are thin Proxies. Every property access forwards to the live
|
|
109
|
-
* client
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
110
|
+
* client for the CURRENT request scope, resolved through {@link __getRuntime}.
|
|
111
|
+
*
|
|
112
|
+
* # Request-scope resolution (persistent app-server)
|
|
113
|
+
*
|
|
114
|
+
* The runtime is a long-running Node process that serves many concurrent
|
|
115
|
+
* requests on one event loop (NOT a fresh subprocess per request). A single
|
|
116
|
+
* module-global slot would let one in-flight request's services bleed into
|
|
117
|
+
* another's. So the services are carried in an {@link AsyncLocalStorage} store
|
|
118
|
+
* ({@link __requestALS}) that the runtime sets per request with
|
|
119
|
+
* {@link __runWithRuntime}; every async continuation of that request reads its
|
|
120
|
+
* own store. `__getRuntime` reads the ALS store first; the module-global slot
|
|
121
|
+
* (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE
|
|
122
|
+
* an ALS scope (dev-server, unit tests, the legacy single-shot path). Because
|
|
123
|
+
* each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the
|
|
124
|
+
* ALS store is what prevents cross-REQUEST leakage within the shared process.
|
|
114
125
|
*
|
|
115
126
|
* The seam that makes `import { Database } from "@palbase/backend"` resolve to
|
|
116
127
|
* the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL
|
|
117
128
|
* when the tenant bundle is built, and the package is installed globally in the
|
|
118
129
|
* pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's
|
|
119
130
|
* `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared
|
|
120
|
-
* module instance —
|
|
121
|
-
* singletons the bundle imported.
|
|
131
|
+
* module instance — the ALS store and `__setRuntime` slot on that instance are
|
|
132
|
+
* visible to the singletons the bundle imported.
|
|
122
133
|
*/
|
|
123
134
|
|
|
124
135
|
/** The set of live clients the runtime injects per request scope.
|
|
@@ -136,17 +147,34 @@ interface RuntimeServices {
|
|
|
136
147
|
Notifications: PalbaseNotificationsClient;
|
|
137
148
|
Flags: PalbaseFlagsClient;
|
|
138
149
|
}
|
|
139
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* Per-request store. The persistent runtime runs each request inside
|
|
152
|
+
* {@link __runWithRuntime}, so every async continuation of that request reads
|
|
153
|
+
* its OWN `runtime` (and any other request-scoped fields the runtime adds).
|
|
140
154
|
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
155
|
+
* Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS
|
|
156
|
+
* instance across the one module instance — two ALS instances would silently
|
|
157
|
+
* not see each other's stores. NOT part of the public author-facing API.
|
|
144
158
|
*/
|
|
159
|
+
declare const __requestALS: AsyncLocalStorage<{
|
|
160
|
+
runtime: RuntimeServices;
|
|
161
|
+
}>;
|
|
162
|
+
/** Install the live clients in the process-global fallback slot.
|
|
163
|
+
*
|
|
164
|
+
* Persistent-server requests should use {@link __runWithRuntime} instead; this
|
|
165
|
+
* remains for dev-server / tests / the legacy single-shot path that run without
|
|
166
|
+
* an ALS scope. NOT part of the public author-facing API. */
|
|
145
167
|
declare function __setRuntime(services: RuntimeServices): void;
|
|
168
|
+
/** Run `fn` with `services` bound as the request-scoped runtime.
|
|
169
|
+
*
|
|
170
|
+
* The persistent worker calls this once per request so concurrent requests
|
|
171
|
+
* never share a services slot. NOT part of the public author-facing API. */
|
|
172
|
+
declare function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T;
|
|
146
173
|
/** Read the live clients, throwing if accessed outside a request scope.
|
|
147
174
|
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
175
|
+
* Resolves the ALS store first (persistent server, per-request), then the
|
|
176
|
+
* process-global fallback (dev-server / tests). NOT part of the public
|
|
177
|
+
* author-facing API — used by the runtime and the singleton Proxies. */
|
|
150
178
|
declare function __getRuntime(): RuntimeServices;
|
|
151
179
|
/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +
|
|
152
180
|
* `query`/`transaction`. For a typed `.tables.<name>` API, wrap with
|
|
@@ -543,4 +571,4 @@ declare const documents: {
|
|
|
543
571
|
onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
|
|
544
572
|
};
|
|
545
573
|
|
|
546
|
-
export { type BackoffStrategy, Cache, CacheClient, type CustomWebhookConfig, DBClient, Database, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, ErrorThrowers, type FileDeletedEvent, type FileUploadedEvent, Flags, type HookContext, type HookHandler, type InsertShape, type JobConfig, type JobContext, Log, Logger, Notifications, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, type PasswordResetEvent, type ProviderEventMap, type ProviderWebhookConfig, Queue, QueueClient, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, type RowShape, type RuntimeServices, SchemaDef, type SignInEvent, type SignOutEvent, Storage, TableDef, type TypedDB, type TypedTable, type TypedTx, User, type UserCreatedEvent, type WebhookContext, type WebhookEventHandler, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerContext, __getRuntime, __setRuntime, auth, defineJob, defineWebhook, defineWorker, documents, makeTypedDB, storage, typedDatabase };
|
|
574
|
+
export { type BackoffStrategy, Cache, CacheClient, type CustomWebhookConfig, DBClient, Database, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, ErrorThrowers, type FileDeletedEvent, type FileUploadedEvent, Flags, type HookContext, type HookHandler, type InsertShape, type JobConfig, type JobContext, Log, Logger, Notifications, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, type PasswordResetEvent, type ProviderEventMap, type ProviderWebhookConfig, Queue, QueueClient, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, type RowShape, type RuntimeServices, SchemaDef, type SignInEvent, type SignOutEvent, Storage, TableDef, type TypedDB, type TypedTable, type TypedTx, User, type UserCreatedEvent, type WebhookContext, type WebhookEventHandler, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerContext, __getRuntime, __requestALS, __runWithRuntime, __setRuntime, auth, defineJob, defineWebhook, defineWorker, documents, makeTypedDB, storage, typedDatabase };
|
package/dist/index.js
CHANGED
|
@@ -8,10 +8,12 @@ import {
|
|
|
8
8
|
Queue,
|
|
9
9
|
Storage,
|
|
10
10
|
__getRuntime,
|
|
11
|
+
__requestALS,
|
|
12
|
+
__runWithRuntime,
|
|
11
13
|
__setRuntime,
|
|
12
14
|
makeTypedDB,
|
|
13
15
|
typedDatabase
|
|
14
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-L36JLUPO.js";
|
|
15
17
|
import {
|
|
16
18
|
boolean,
|
|
17
19
|
defineSchema,
|
|
@@ -336,6 +338,8 @@ export {
|
|
|
336
338
|
Queue,
|
|
337
339
|
Storage,
|
|
338
340
|
__getRuntime,
|
|
341
|
+
__requestALS,
|
|
342
|
+
__runWithRuntime,
|
|
339
343
|
__setRuntime,
|
|
340
344
|
auth,
|
|
341
345
|
boolean,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/endpoint.ts","../src/middleware.ts","../src/errors.ts","../src/worker.ts","../src/job.ts","../src/webhook.ts","../src/hooks.ts","../src/index.ts"],"sourcesContent":["import type { ZodSchema, z } from \"zod\";\nimport type { AuthConfig, HttpMethod, User } from \"./types.js\";\nimport type { MiddlewareContext } from \"./middleware.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport { HttpError } from \"./errors.js\";\nimport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseFlagsClient,\n PalbaseNotificationsClient,\n PalbaseAnalyticsClient,\n PalbaseLinksClient,\n PalbaseCmsClient,\n} from \"./clients.js\";\n\n/** Uploaded file metadata injected into endpoint context when a file is present.\n * `data` is typed as `Uint8Array` for SDK portability (Buffer extends Uint8Array in Node).\n */\nexport interface FileContext {\n filename: string;\n contentType: string;\n size: number;\n data: Uint8Array;\n}\n\n/** Queue client for dispatching background jobs from within a handler. */\nexport interface QueueClient {\n /** Enqueue a job for the named worker. Returns the new job ID. */\n push(worker: string, payload: unknown): Promise<{ jobId: string }>;\n}\n\n/** Rate limit configuration for an endpoint. */\nexport interface RateLimitConfig {\n /** Maximum number of requests in the window. */\n max: number;\n /** Window duration in seconds. */\n window: number;\n}\n\n/** The transaction-scoped client passed to `db.transaction(fn)` — same DB ops, no nested transaction. */\nexport type TxClient = Omit<DBClient, \"transaction\">;\n\n/** Database client interface injected into endpoint context. */\nexport interface DBClient {\n /** Run a read-only SQL query (executes in a READ ONLY transaction). */\n query(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;\n insert(table: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;\n update(table: string, id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;\n delete(table: string, id: string): Promise<void>;\n findById(table: string, id: string): Promise<Record<string, unknown> | null>;\n findMany(table: string, query?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n /**\n * Run an interactive transaction. The callback receives a `tx` with the same\n * DB ops as this client; returning normally commits, throwing rolls back.\n * Nested transactions are not supported.\n */\n transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T>;\n}\n\n/** Logger interface injected into endpoint context. */\nexport interface Logger {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n debug(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Cache client interface injected into endpoint context.\n *\n * The cache is JSON-typed: values are serialized to/from JSON, so any JSON\n * value (objects, arrays, numbers, booleans, strings) round-trips. `get<T>`\n * therefore returns `T | null` rather than `string | null`.\n */\nexport interface CacheClient {\n /** Read a value. Returns `null` on a cache miss. */\n get<T = unknown>(key: string): Promise<T | null>;\n /** Write a JSON-serializable value with an optional TTL (seconds). */\n set(key: string, value: unknown, ttl?: number): Promise<void>;\n /** Delete a key. */\n del(key: string): Promise<void>;\n /** Atomically increment an integer counter, returning the new value. */\n incr(key: string): Promise<number>;\n /**\n * Stampede-safe read-through cache fill. On a hit, returns the cached value.\n * On a miss, a single caller (across all pod replicas, coordinated by a\n * distributed lock) runs `fn`, caches the result for `ttl` seconds, and\n * returns it; concurrent callers wait for that result instead of also\n * running `fn`. If no value lands within the lock's TTL, the call rejects —\n * it does NOT run `fn` on timeout (that would reintroduce the stampede).\n *\n * @param ttl value TTL in seconds.\n */\n getOrSet<T>(key: string, ttl: number, fn: () => Promise<T> | T): Promise<T>;\n}\n\n/** Result envelope used across the Palbase Server SDK clients. */\nexport interface PalbaseResult<T> {\n data: T | null;\n error: { message?: string; code?: string } | null;\n status?: number;\n}\n\n/** Document snapshot returned by docs.get(). */\nexport interface PalbaseDocumentSnapshot<T = Record<string, unknown>> {\n id: string;\n exists: boolean;\n data(): T | undefined;\n ref: { path: string };\n}\n\n/** Collection query snapshot returned by collection.get(). */\nexport interface PalbaseQuerySnapshot<T = Record<string, unknown>> {\n docs: PalbaseDocumentSnapshot<T>[];\n empty: boolean;\n size: number;\n}\n\n/** Comparison operators supported by docs.where(). */\nexport type PalbaseWhereOperator =\n | \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\";\n\n/** Document reference exposed by Documents.collection(...).doc(...). */\nexport interface PalbaseDocumentRef<T = Record<string, unknown>> {\n readonly path: string;\n set(data: T): Promise<PalbaseResult<void>>;\n get(): Promise<PalbaseResult<PalbaseDocumentSnapshot<T>>>;\n update(data: Partial<T>): Promise<PalbaseResult<void>>;\n delete(): Promise<PalbaseResult<void>>;\n}\n\n/** Collection reference exposed by Documents.collection(...). */\nexport interface PalbaseCollectionRef<T = Record<string, unknown>> {\n readonly path: string;\n doc(id: string): PalbaseDocumentRef<T>;\n add(data: T): Promise<PalbaseResult<PalbaseDocumentRef<T>>>;\n where(field: string, op: PalbaseWhereOperator, value: unknown): PalbaseCollectionRef<T>;\n orderBy(field: string, direction?: \"asc\" | \"desc\"): PalbaseCollectionRef<T>;\n limit(n: number): PalbaseCollectionRef<T>;\n get(): Promise<PalbaseResult<PalbaseQuerySnapshot<T>>>;\n}\n\n/** Docs client surface available on the Documents singleton. */\nexport interface PalbaseDocsClient {\n collection<T = Record<string, unknown>>(path: string): PalbaseCollectionRef<T>;\n doc<T = Record<string, unknown>>(path: string): PalbaseDocumentRef<T>;\n}\n\n/** Calling-client metadata, derived from request headers.\n *\n * Populated from the `X-Palbase-*-Version` / platform headers the client SDKs\n * send. All fields are nullable: a request may come from a non-SDK caller\n * (curl, server-to-server) that sends none of them. The semver comparison\n * helpers (`appVersionAtLeast`, …) arrive in Phase 2 — Phase 1 surfaces only\n * the raw data fields. */\nexport interface ClientInfo {\n /** Palbase SDK version (`X-Palbase-Sdk-Version`), or null. */\n sdkVersion: string | null;\n /** Calling app's own version (`X-Palbase-Client-Version`), or null. */\n appVersion: string | null;\n /** Platform identifier (e.g. \"ios\", \"android\", \"web\"), or null. */\n platform: string | null;\n /** OS version string, or null. */\n osVersion: string | null;\n}\n\n/** Palbase module clients, as a structural bundle.\n *\n * NOT part of the endpoint surface anymore — endpoint handlers reach services\n * via the PascalCase singletons (`Database`, `Documents`, …). This type is\n * retained as an INTERNAL shape for the sibling contexts that still carry a\n * `ctx` (middleware, jobs, workers, hooks, webhooks — out of Phase 1 scope).\n * It is intentionally not re-exported from `index.ts`.\n *\n * Structurally typed against the runtime's `ServerClient`; the runtime injects\n * the real client, so mismatched names would surface as `undefined is not a\n * function` at call time — keep these in sync with `ServerClient`. */\nexport interface PalbaseModuleClients {\n auth: PalbaseAuthClient;\n storage: PalbaseStorageClient;\n docs: PalbaseDocsClient;\n realtime: PalbaseRealtimeClient;\n functions: PalbaseFunctionsClient;\n flags: PalbaseFlagsClient;\n notifications: PalbaseNotificationsClient;\n analytics: PalbaseAnalyticsClient;\n links: PalbaseLinksClient;\n cms: PalbaseCmsClient;\n}\n\n/** Declared-error definition.\n *\n * `code` is the stable snake_case identifier that lands on the wire envelope's\n * `error` field. `status` is the HTTP status code returned. `data`, if set,\n * is a Zod schema whose value rides on the envelope's `data` field — the CLI\n * codegen lowers it to the typed enum's associated value on iOS.\n *\n * `description` is optional human-readable text; the OpenAPI generator uses it\n * for the response description and the iOS codegen surfaces it in the\n * generated method's doc-comment.\n */\nexport interface ErrorDef<TData extends ZodSchema = ZodSchema> {\n status: number;\n code: string;\n description?: string;\n data?: TData;\n}\n\n/** Map of declared errors keyed by their TypeScript-side names.\n *\n * Keys are the friendly names the handler uses (`req.errors.todoLocked`);\n * `code` on each value is the wire identifier. The TS name is what the iOS\n * codegen lowers to (camelCase enum cases), and the wire `code` is what the\n * envelope's `error` field carries.\n */\nexport type ErrorMap = Record<string, ErrorDef>;\n\n/** Throwable proxy projected onto `req.errors` when `errors` is declared.\n *\n * Each entry is a constructor: declared errors with a `data` schema demand\n * the payload as a required argument; declared errors without `data` take\n * none. Throwing the result emits the standard envelope (with `data` when\n * present).\n *\n * throw req.errors.todoNotFound();\n * throw req.errors.todoLocked({ retryAfter: 30 });\n */\nexport type ErrorThrowers<TErrors extends ErrorMap | undefined> =\n TErrors extends ErrorMap\n ? {\n [K in keyof TErrors]: TErrors[K][\"data\"] extends ZodSchema\n ? (data: z.infer<NonNullable<TErrors[K][\"data\"]>>) => HttpError\n : () => HttpError;\n }\n : Record<string, never>;\n\n/** The request-scoped object passed to every endpoint handler.\n *\n * Replaces the old `ctx` god-object. `PBRequest` carries ONLY request-scoped\n * data — the typed `input`, route/query params, headers, the authenticated\n * `user`, calling-client metadata, trace ids, and the endpoint's declared\n * error throwers. Services (`Database`, `Documents`, `Cache`, …) are NOT on\n * the request: import them directly from `@palbase/backend` as singletons.\n *\n * import { defineEndpoint, Database } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => Database.insert(\"todos\", { title: req.input.title }),\n * });\n *\n * Generic parameters:\n * - `TInput` — the validated `input` type (inferred from the `input` Zod\n * schema by `defineEndpoint`). The user-facing form is single-generic:\n * `PBRequest<TodoInput>`.\n * - `TAuthed` — whether `user` is non-null. DEFAULTS to `true` (the common\n * case; the auth pipeline returns 401 before the handler when auth is\n * required, so a non-null `user` is runtime-honest). `defineEndpoint` passes\n * `IsAuthed<TAuth>` here, so `auth: false` → `User | null`.\n * - `TErrors` — the declared `errors` map, typing `req.errors.<name>(...)`.\n */\nexport interface PBRequest<\n TInput = unknown,\n TAuthed extends boolean = true,\n TErrors extends ErrorMap | undefined = undefined,\n> {\n /** Validated request input (body for POST/PUT/PATCH; `{}` otherwise). */\n input: TInput;\n /** Matched route params (e.g. `{ id }` for `/todos/[id]`). */\n params: Record<string, string>;\n /** Parsed query-string params. */\n query: Record<string, string>;\n /** Request headers (lowercase keys). */\n headers: Record<string, string>;\n /** Authenticated user. Non-null (`User`) by default; `User | null` only when\n * the endpoint's `auth` config disables enforcement (driven by `TAuthed`,\n * which `defineEndpoint` computes from the `auth` literal via {@link IsAuthed}). */\n user: TAuthed extends true ? User : User | null;\n /** Calling-client metadata derived from request headers (all nullable). */\n client: ClientInfo;\n /** Uploaded file, or null when the request has no file part. */\n file: FileContext | null;\n /** HTTP method of the incoming request (e.g. \"GET\", \"POST\"). */\n method: string;\n /** Per-request id (`req_<…>`), preserved for back-compat correlation. */\n requestId: string;\n /** W3C trace id (primary correlation key across modules). */\n traceId: string;\n /** W3C span id for this handler invocation. */\n spanId: string;\n /** Typed throwers for the endpoint's declared errors. Empty when the\n * `errors` block is absent on `defineEndpoint`. */\n errors: ErrorThrowers<TErrors>;\n}\n\n/** Middleware function signature — uses MiddlewareContext (no input, not yet validated). */\nexport type Middleware = (\n ctx: MiddlewareContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/** The shape an endpoint's `auth` config may take.\n *\n * Either a bare boolean (`true`/`false`) or an object form (`{ required?,\n * role? }`). The object form is `Partial<AuthConfig>` so `required` may be\n * omitted — which the runtime treats as `required: true` (see {@link IsAuthed}).\n */\nexport type AuthSpec = boolean | Partial<AuthConfig>;\n\n/** Compute, at the type level, whether an endpoint authenticates its caller —\n * i.e. whether `req.user` should be `User` (non-null) instead of `User | null`.\n *\n * This mirrors the Go pipeline's enforcement exactly (extract_meta.js + auth.go):\n * a request is authenticated ⟺ `auth === true` OR (`auth` is an object whose\n * `required` is not explicitly `false`). So `req.user` stays nullable ONLY when\n * `auth` is absent (`undefined`), `auth === false`, or `auth: { required: false }`.\n *\n * | `TAuth` | `IsAuthed<TAuth>` |\n * |---------------------------------|-------------------|\n * | `undefined` | `false` |\n * | `true` | `true` |\n * | `false` | `false` |\n * | `{ required: true }` | `true` |\n * | `{ required: false }` | `false` |\n * | `{ role: 'admin' }` (no `required`) | `true` ⚠️ |\n *\n * Order matters: the `{ required: false }` branch is checked first so the\n * object case can't swallow it; `true` then `false` literals are handled\n * explicitly before the catch-all object branch (which encodes the\n * \"required omitted ⇒ required\" corner case).\n */\nexport type IsAuthed<TAuth> = TAuth extends { required: false }\n ? false\n : TAuth extends true\n ? true\n : TAuth extends false\n ? false\n : TAuth extends object\n ? true\n : false;\n\n/** Configuration for defining an endpoint.\n *\n * `TSchema` — optional `SchemaDef` carried on the `schema` field. The runtime\n * uses it to wire a typed `.tables.*` API; authors opt in per endpoint with\n * `typedDatabase(schema)` (see runtime.ts).\n *\n * `TAuth` — captures the literal type of the `auth` field (via the `const`\n * type parameter on `defineEndpoint`) so the handler's `req.user` can be\n * narrowed to non-null `User` when auth is required. See {@link IsAuthed}.\n *\n * `TErrors` — captures the literal `errors` map (via the `const` type\n * parameter on `defineEndpoint`) so `req.errors.<name>(...)` is typed per\n * declared entry. The OpenAPI generator emits each one as a discriminated\n * response under `responses[<status>]`, and the CLI codegen lowers them to\n * a typed `<Endpoint>.Error` enum on iOS.\n */\nexport interface EndpointConfig<\n TInputSchema extends ZodSchema = ZodSchema,\n TOutputSchema extends ZodSchema = ZodSchema,\n TSchema extends SchemaDef | undefined = undefined,\n TAuth extends AuthSpec | undefined = undefined,\n TErrors extends ErrorMap | undefined = undefined,\n> {\n method: HttpMethod;\n auth?: TAuth;\n rateLimit?: RateLimitConfig;\n input?: TInputSchema;\n output?: TOutputSchema;\n schema?: TSchema;\n errors?: TErrors;\n middleware?: Middleware[];\n handler: (\n req: PBRequest<z.infer<TInputSchema>, IsAuthed<TAuth>, TErrors>,\n ) => Promise<z.infer<TOutputSchema>>;\n}\n\n/** Define a type-safe endpoint. The input schema infers the `req.input` type.\n * Pass a `schema` (from `defineSchema`) and wrap `Database` with\n * `typedDatabase(schema)` in the handler for a typed `.tables.*` API.\n *\n * The `const TAuth` and `const TErrors` type parameters capture the `auth`\n * and `errors` fields as literals, so `req.user` narrows to non-null `User`\n * when auth is enforced and `req.errors.<name>(...)` is typed per declared\n * entry.\n */\nexport function defineEndpoint<\n TInputSchema extends ZodSchema,\n TOutputSchema extends ZodSchema,\n TSchema extends SchemaDef | undefined = undefined,\n const TAuth extends AuthSpec | undefined = undefined,\n const TErrors extends ErrorMap | undefined = undefined,\n>(\n config: EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors>,\n): EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors> {\n return config;\n}\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 projectId: 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","/** HTTP error with structured error response format.\n *\n * Two ways to construct one:\n *\n * 1. Directly: `throw new HttpError(404, \"todo_not_found\", \"No such todo\")`.\n * Surfaces on the wire (and to iOS) as `BackendError.server(code, status,\n * message, requestId)`.\n * 2. Via `ctx.errors.<name>(data?)` for declared errors — see\n * `EndpointConfig.errors`. The endpoint's OpenAPI spec describes each\n * one, and the CLI codegen emits a typed `<Endpoint>.Error` enum so iOS\n * callers can `catch <Endpoint>.Error.<case>` directly.\n *\n * The optional `data` field carries a structured payload alongside the\n * standard envelope — used by declared errors that need to ship extra context\n * (e.g. `todoLocked({ retryAfter: 30 })`). It rides through to the iOS typed\n * 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\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","import type {\n DBClient,\n Logger,\n CacheClient,\n QueueClient,\n PalbaseModuleClients,\n ErrorThrowers,\n} from \"./endpoint.js\";\nimport type { User } from \"./types.js\";\n\n/** Context injected into worker handlers — the non-request-scoped service\n * surface (db/log/cache/queue + module clients), plus correlation ids. Workers\n * are not part of the Phase 1 `ctx → PBRequest` redesign, so they keep their\n * own `ctx`; the job payload arrives as the handler's second argument. */\nexport interface WorkerContext extends PalbaseModuleClients {\n user: User | null;\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n errors: ErrorThrowers<undefined>;\n requestId: string;\n projectId: string;\n environmentId: string;\n}\n\n/** Backoff strategy for worker retries. */\nexport type BackoffStrategy = \"exponential\" | \"linear\" | \"fixed\";\n\n/** Configuration for a background worker. */\nexport interface WorkerConfig<TPayload = unknown> {\n /** Worker name — must be unique across the project. */\n name: string;\n /** Maximum number of retries before sending to dead letter queue. Defaults to 3. */\n retry?: number;\n /** Execution timeout in seconds. Defaults to 30. */\n timeout?: number;\n /** Backoff strategy between retries. Defaults to \"exponential\". */\n backoff?: BackoffStrategy;\n /** Handler function that processes the job payload. */\n handler: (\n ctx: WorkerContext,\n payload: TPayload,\n ) => Promise<void>;\n}\n\n/** Resolved worker configuration with defaults applied. */\nexport interface ResolvedWorkerConfig<TPayload = unknown> {\n name: string;\n retry: number;\n timeout: number;\n backoff: BackoffStrategy;\n handler: (\n ctx: WorkerContext,\n payload: TPayload,\n ) => Promise<void>;\n}\n\n/** Valid worker name pattern: alphanumeric, underscore, hyphen only.\n * Prevents Redis key injection via colons or path separators. */\nconst VALID_WORKER_NAME = /^[a-zA-Z0-9_-]+$/;\n\n/** Default values for worker configuration. */\nconst WORKER_DEFAULTS = {\n retry: 3,\n timeout: 30,\n backoff: \"exponential\" as BackoffStrategy,\n} as const;\n\n/**\n * Define a background worker that processes jobs from the queue.\n *\n * Workers are placed in the `workers/` directory and auto-discovered at deploy time.\n *\n * @example\n * ```ts\n * export default defineWorker({\n * name: \"send-email\",\n * retry: 5,\n * timeout: 60,\n * backoff: \"exponential\",\n * handler: async (ctx, payload: { to: string; subject: string }) => {\n * await sendEmail(payload.to, payload.subject);\n * },\n * });\n * ```\n */\nexport function defineWorker<TPayload = unknown>(\n config: WorkerConfig<TPayload>,\n): ResolvedWorkerConfig<TPayload> {\n if (!config.name || config.name.trim() === \"\") {\n throw new Error(\"Worker name is required\");\n }\n\n if (!VALID_WORKER_NAME.test(config.name)) {\n throw new Error(\n `Invalid worker name \"${config.name}\": must match [a-zA-Z0-9_-]+`,\n );\n }\n\n if (config.retry !== undefined && (config.retry < 0 || !Number.isInteger(config.retry))) {\n throw new Error(\"Worker retry must be a non-negative integer\");\n }\n\n if (config.timeout !== undefined && config.timeout <= 0) {\n throw new Error(\"Worker timeout must be a positive number\");\n }\n\n if (\n config.backoff !== undefined &&\n ![\"exponential\", \"linear\", \"fixed\"].includes(config.backoff)\n ) {\n throw new Error(`Invalid backoff strategy: ${config.backoff}`);\n }\n\n return {\n name: config.name,\n retry: config.retry ?? WORKER_DEFAULTS.retry,\n timeout: config.timeout ?? WORKER_DEFAULTS.timeout,\n backoff: config.backoff ?? WORKER_DEFAULTS.backoff,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Context injected into job handlers — subset of EndpointContext without request-specific fields. */\nexport interface JobContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n}\n\n/** Configuration for defining a scheduled job. */\nexport interface JobConfig {\n /** Unique job name — alphanumeric, underscore, hyphen only. */\n name: string;\n /** Cron expression (e.g., \"0 3 * * *\"). */\n schedule: string;\n /** Execution timeout in seconds. Defaults to 30. */\n timeout?: number;\n /** Job handler function. */\n handler: (ctx: JobContext) => Promise<void>;\n}\n\n/** Resolved job configuration with defaults applied. */\nexport interface ResolvedJobConfig {\n name: string;\n schedule: string;\n timeout: number;\n handler: (ctx: JobContext) => Promise<void>;\n}\n\n/** Valid job name pattern: alphanumeric, underscore, hyphen only. */\nconst VALID_JOB_NAME = /^[a-zA-Z0-9_-]+$/;\n\n/** Maximum allowed timeout in seconds (5 minutes, matching sandbox limits). */\nconst MAX_TIMEOUT_SECONDS = 300;\n\n/** Default values for job configuration. */\nconst JOB_DEFAULTS = {\n timeout: 30,\n} as const;\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 */\nfunction 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\n/**\n * Define a scheduled cron job.\n *\n * Jobs are placed in the `jobs/` directory and auto-discovered at deploy time.\n *\n * @example\n * ```ts\n * export default defineJob({\n * name: \"cleanup-expired\",\n * schedule: \"0 3 * * *\", // every day at 3 AM\n * timeout: 60,\n * handler: async (ctx) => {\n * await ctx.db.delete(\"sessions\", \"expired < NOW()\");\n * ctx.log.info(\"Cleaned up expired sessions\");\n * },\n * });\n * ```\n */\nexport function defineJob(config: JobConfig): ResolvedJobConfig {\n if (!config.name || config.name.trim() === \"\") {\n throw new Error(\"Job name is required\");\n }\n\n if (!VALID_JOB_NAME.test(config.name)) {\n throw new Error(\n `Invalid job name \"${config.name}\": must match [a-zA-Z0-9_-]+`,\n );\n }\n\n if (!config.schedule || config.schedule.trim() === \"\") {\n throw new Error(\"Job schedule is required\");\n }\n\n const cronError = validateCronExpression(config.schedule);\n if (cronError !== null) {\n throw new Error(cronError);\n }\n\n if (!config.handler) {\n throw new Error(\"Job handler is required\");\n }\n\n if (config.timeout !== undefined && config.timeout <= 0) {\n throw new Error(\"Job timeout must be a positive number\");\n }\n\n if (config.timeout !== undefined && !Number.isInteger(config.timeout)) {\n throw new Error(\"Job timeout must be an integer\");\n }\n\n if (config.timeout !== undefined && config.timeout > MAX_TIMEOUT_SECONDS) {\n throw new Error(\n `Job timeout ${config.timeout}s exceeds maximum ${MAX_TIMEOUT_SECONDS}s`,\n );\n }\n\n return {\n name: config.name,\n schedule: config.schedule.trim(),\n timeout: config.timeout ?? JOB_DEFAULTS.timeout,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Supported webhook provider types. */\nexport type WebhookProvider =\n | \"stripe\"\n | \"github\"\n | \"twilio\"\n | \"sendgrid\"\n | \"slack\"\n | \"discord\"\n | \"livekit\";\n\n/** Context injected into webhook handlers — no user (webhooks are machine-to-machine). */\nexport interface WebhookContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n requestId: string;\n}\n\n/** Secret reference — resolves from environment variables at runtime. */\nexport interface EnvSecretRef {\n env: string;\n}\n\n/** Provider-specific event maps for type-safe event handlers. */\nexport interface ProviderEventMap {\n stripe: {\n \"checkout.session.completed\": Record<string, unknown>;\n \"payment_intent.succeeded\": Record<string, unknown>;\n \"payment_intent.payment_failed\": Record<string, unknown>;\n \"customer.subscription.created\": Record<string, unknown>;\n \"customer.subscription.updated\": Record<string, unknown>;\n \"customer.subscription.deleted\": Record<string, unknown>;\n \"invoice.paid\": Record<string, unknown>;\n \"invoice.payment_failed\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n github: {\n push: Record<string, unknown>;\n pull_request: Record<string, unknown>;\n issues: Record<string, unknown>;\n \"pull_request.opened\": Record<string, unknown>;\n \"pull_request.closed\": Record<string, unknown>;\n \"pull_request.merged\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n twilio: {\n \"message.received\": Record<string, unknown>;\n \"message.sent\": Record<string, unknown>;\n \"call.completed\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n sendgrid: {\n delivered: Record<string, unknown>;\n bounce: Record<string, unknown>;\n open: Record<string, unknown>;\n click: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n slack: {\n url_verification: Record<string, unknown>;\n event_callback: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n discord: {\n PING: Record<string, unknown>;\n MESSAGE_CREATE: Record<string, unknown>;\n INTERACTION_CREATE: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n livekit: {\n \"room.started\": Record<string, unknown>;\n \"room.finished\": Record<string, unknown>;\n \"participant.joined\": Record<string, unknown>;\n \"participant.left\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n}\n\n/** Event handler function type. */\nexport type WebhookEventHandler<TEvent = Record<string, unknown>> = (\n ctx: WebhookContext,\n event: TEvent,\n) => Promise<void>;\n\n/** Provider-based webhook configuration. */\nexport interface ProviderWebhookConfig<P extends WebhookProvider = WebhookProvider> {\n provider: P;\n secret: EnvSecretRef;\n events: {\n [K in keyof ProviderEventMap[P]]?: WebhookEventHandler<ProviderEventMap[P][K]>;\n };\n}\n\n/** Incoming request representation for custom verify functions. */\nexport interface WebhookRequest {\n headers: Record<string, string>;\n body: string;\n method: string;\n url: string;\n}\n\n/** Custom webhook configuration. */\nexport interface CustomWebhookConfig {\n path: string;\n verify?: (req: WebhookRequest) => Promise<boolean> | boolean;\n handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;\n}\n\n/** Resolved provider webhook (internal). */\nexport interface ResolvedProviderWebhook<P extends WebhookProvider = WebhookProvider> {\n type: \"provider\";\n provider: P;\n secret: EnvSecretRef;\n events: Record<string, WebhookEventHandler>;\n}\n\n/** Resolved custom webhook (internal). */\nexport interface ResolvedCustomWebhook {\n type: \"custom\";\n path: string;\n verify?: (req: WebhookRequest) => Promise<boolean> | boolean;\n handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;\n}\n\n/** Union of resolved webhook types. */\nexport type ResolvedWebhookConfig = ResolvedProviderWebhook | ResolvedCustomWebhook;\n\n/** Valid webhook path pattern: starts with /, alphanumeric + hyphen + slash. */\nconst VALID_WEBHOOK_PATH = /^\\/[a-zA-Z0-9/_-]+$/;\n\n/**\n * Define a provider-based webhook.\n *\n * @example\n * ```ts\n * export default defineWebhook({\n * provider: \"stripe\",\n * secret: { env: \"STRIPE_WEBHOOK_SECRET\" },\n * events: {\n * \"checkout.session.completed\": async (ctx, event) => {\n * await ctx.db.insert(\"orders\", { status: \"paid\" });\n * },\n * },\n * });\n * ```\n */\nexport function defineWebhook<P extends WebhookProvider>(\n config: ProviderWebhookConfig<P>,\n): ResolvedProviderWebhook<P>;\n\n/**\n * Define a custom webhook with optional verification.\n *\n * @example\n * ```ts\n * export default defineWebhook({\n * path: \"/webhooks/livekit\",\n * verify: async (req) => req.headers[\"x-api-key\"] === \"secret\",\n * handler: async (ctx, payload) => {\n * ctx.log.info(\"Received webhook\", payload);\n * },\n * });\n * ```\n */\nexport function defineWebhook(config: CustomWebhookConfig): ResolvedCustomWebhook;\n\nexport function defineWebhook(\n config: ProviderWebhookConfig | CustomWebhookConfig,\n): ResolvedWebhookConfig {\n if (\"provider\" in config) {\n return validateProviderWebhook(config);\n }\n return validateCustomWebhook(config);\n}\n\nfunction validateProviderWebhook<P extends WebhookProvider>(\n config: ProviderWebhookConfig<P>,\n): ResolvedProviderWebhook<P> {\n if (!config.provider) {\n throw new Error(\"Webhook provider is required\");\n }\n\n const validProviders: WebhookProvider[] = [\n \"stripe\", \"github\", \"twilio\", \"sendgrid\", \"slack\", \"discord\", \"livekit\",\n ];\n if (!validProviders.includes(config.provider)) {\n throw new Error(\n `Invalid webhook provider \"${config.provider}\": must be one of ${validProviders.join(\", \")}`,\n );\n }\n\n if (!config.secret) {\n throw new Error(\"Webhook secret is required (use { env: \\\"SECRET_NAME\\\" })\");\n }\n\n if (typeof config.secret.env !== \"string\" || config.secret.env.trim() === \"\") {\n throw new Error(\"Webhook secret env name must be a non-empty string\");\n }\n\n if (!config.events || Object.keys(config.events).length === 0) {\n throw new Error(\"At least one event handler is required\");\n }\n\n for (const [eventName, handler] of Object.entries(config.events)) {\n if (typeof handler !== \"function\") {\n throw new Error(`Event handler for \"${eventName}\" must be a function`);\n }\n }\n\n return {\n type: \"provider\",\n provider: config.provider,\n secret: config.secret,\n events: config.events as Record<string, WebhookEventHandler>,\n };\n}\n\nfunction validateCustomWebhook(config: CustomWebhookConfig): ResolvedCustomWebhook {\n if (!config.path || config.path.trim() === \"\") {\n throw new Error(\"Webhook path is required\");\n }\n\n if (!VALID_WEBHOOK_PATH.test(config.path)) {\n throw new Error(\n `Invalid webhook path \"${config.path}\": must start with / and contain only alphanumeric, hyphen, underscore, slash`,\n );\n }\n\n if (!config.handler) {\n throw new Error(\"Webhook handler is required\");\n }\n\n if (typeof config.handler !== \"function\") {\n throw new Error(\"Webhook handler must be a function\");\n }\n\n if (config.verify !== undefined && typeof config.verify !== \"function\") {\n throw new Error(\"Webhook verify must be a function\");\n }\n\n return {\n type: \"custom\",\n path: config.path,\n verify: config.verify,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Context injected into hook handlers. */\nexport interface HookContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n}\n\n// --- Auth Event Payloads ---\n\n/** Payload for auth.onUserCreated hook. */\nexport interface UserCreatedEvent {\n user: {\n id: string;\n email: string;\n role: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n };\n}\n\n/** Payload for auth.onSignIn hook. */\nexport interface SignInEvent {\n user: {\n id: string;\n email: string;\n role: string;\n };\n provider: string;\n timestamp: string;\n}\n\n/** Payload for auth.onSignOut hook. */\nexport interface SignOutEvent {\n user: {\n id: string;\n email: string;\n };\n timestamp: string;\n}\n\n/** Payload for auth.onPasswordReset hook. */\nexport interface PasswordResetEvent {\n user: {\n id: string;\n email: string;\n };\n timestamp: string;\n}\n\n// --- Storage Event Payloads ---\n\n/** Payload for storage.onFileUploaded hook. */\nexport interface FileUploadedEvent {\n file: {\n id: string;\n name: string;\n bucket: string;\n path: string;\n size: number;\n contentType: string;\n };\n}\n\n/** Payload for storage.onFileDeleted hook. */\nexport interface FileDeletedEvent {\n file: {\n id: string;\n name: string;\n bucket: string;\n path: string;\n };\n}\n\n// --- Documents Event Payloads ---\n\n/** Payload for documents.onDocumentCreated hook. */\nexport interface DocumentCreatedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n };\n}\n\n/** Payload for documents.onDocumentUpdated hook. */\nexport interface DocumentUpdatedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n previousData: Record<string, unknown>;\n };\n}\n\n/** Payload for documents.onDocumentDeleted hook. */\nexport interface DocumentDeletedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n };\n}\n\n// --- Hook Handler Types ---\n\nexport type HookHandler<TEvent> = (ctx: HookContext, event: TEvent) => Promise<void>;\n\n/** Resolved hook configuration (internal). */\nexport interface ResolvedHook<TEvent = unknown> {\n module: string;\n event: string;\n handler: HookHandler<TEvent>;\n}\n\n// --- Auth Hooks ---\n\nexport const auth = {\n onUserCreated(handler: HookHandler<UserCreatedEvent>): ResolvedHook<UserCreatedEvent> {\n return { module: \"auth\", event: \"user.created\", handler };\n },\n\n onSignIn(handler: HookHandler<SignInEvent>): ResolvedHook<SignInEvent> {\n return { module: \"auth\", event: \"user.sign_in\", handler };\n },\n\n onSignOut(handler: HookHandler<SignOutEvent>): ResolvedHook<SignOutEvent> {\n return { module: \"auth\", event: \"user.sign_out\", handler };\n },\n\n onPasswordReset(handler: HookHandler<PasswordResetEvent>): ResolvedHook<PasswordResetEvent> {\n return { module: \"auth\", event: \"user.password_reset\", handler };\n },\n};\n\n// --- Storage Hooks ---\n\nexport const storage = {\n onFileUploaded(handler: HookHandler<FileUploadedEvent>): ResolvedHook<FileUploadedEvent> {\n return { module: \"storage\", event: \"file.uploaded\", handler };\n },\n\n onFileDeleted(handler: HookHandler<FileDeletedEvent>): ResolvedHook<FileDeletedEvent> {\n return { module: \"storage\", event: \"file.deleted\", handler };\n },\n};\n\n// --- Documents Hooks ---\n\nexport const documents = {\n onDocumentCreated(handler: HookHandler<DocumentCreatedEvent>): ResolvedHook<DocumentCreatedEvent> {\n return { module: \"documents\", event: \"document.created\", handler };\n },\n\n onDocumentUpdated(handler: HookHandler<DocumentUpdatedEvent>): ResolvedHook<DocumentUpdatedEvent> {\n return { module: \"documents\", event: \"document.updated\", handler };\n },\n\n onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent> {\n return { module: \"documents\", event: \"document.deleted\", handler };\n },\n};\n","export { defineEndpoint } from \"./endpoint.js\";\nexport type {\n EndpointConfig,\n PBRequest,\n ClientInfo,\n RateLimitConfig,\n DBClient,\n TxClient,\n FileContext,\n QueueClient,\n Logger,\n CacheClient,\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 Queue,\n Log,\n Notifications,\n Flags,\n typedDatabase,\n __setRuntime,\n __getRuntime,\n} from \"./runtime.js\";\nexport type { RuntimeServices } from \"./runtime.js\";\nexport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseRealtimeClient,\n PalbaseRealtimeChannel,\n PalbaseRealtimeMessage,\n PalbaseFunctionsClient,\n PalbaseInvokeOptions,\n PalbaseFlagsClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseNotificationsClient,\n PalbasePushClient,\n PalbaseEmailClient,\n PalbaseSmsClient,\n PalbaseInboxClient,\n PalbasePreferencesClient,\n PalbaseAnalyticsClient,\n PalbaseAnalyticsQueryNamespace,\n PalbaseAnalyticsManagementNamespace,\n PalbaseLinksClient,\n PalbaseCmsClient,\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 PalbasePublicUrlResponse,\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 PalbaseCmsFindOptions,\n PalbaseCmsFindOneOptions,\n} from \"./clients.js\";\nexport { defineSchema, table } from \"./db/schema.js\";\nexport type { SchemaDef, TableDef } from \"./db/schema.js\";\nexport { uuid, text, integer, boolean, timestamp, jsonb, enumType } from \"./db/columns.js\";\nexport type { ColumnBuilder, ColumnDef, ColumnType, OnDeleteAction } from \"./db/columns.js\";\nexport { makeTypedDB } from \"./db/typed-db.js\";\nexport type { TypedDB, TypedTx, TypedTable, InsertShape, RowShape } from \"./db/typed-db.js\";\nexport { defineMiddleware } from \"./middleware.js\";\nexport type { MiddlewareContext, MiddlewareHandler } from \"./middleware.js\";\nexport type { User, HttpMethod, AuthConfig } from \"./types.js\";\nexport { HttpError } from \"./errors.js\";\nexport { defineWorker } from \"./worker.js\";\nexport type {\n WorkerConfig,\n ResolvedWorkerConfig,\n WorkerContext,\n BackoffStrategy,\n} from \"./worker.js\";\nexport { defineJob } from \"./job.js\";\nexport type { JobConfig, ResolvedJobConfig, JobContext } from \"./job.js\";\nexport { defineWebhook } from \"./webhook.js\";\nexport type {\n WebhookProvider,\n WebhookContext,\n EnvSecretRef,\n ProviderWebhookConfig,\n CustomWebhookConfig,\n ResolvedProviderWebhook,\n ResolvedCustomWebhook,\n ResolvedWebhookConfig,\n WebhookEventHandler,\n WebhookRequest,\n ProviderEventMap,\n} from \"./webhook.js\";\nexport { auth, storage, documents } from \"./hooks.js\";\nexport type {\n HookContext,\n HookHandler,\n ResolvedHook,\n UserCreatedEvent,\n SignInEvent,\n SignOutEvent,\n PasswordResetEvent,\n FileUploadedEvent,\n FileDeletedEvent,\n DocumentCreatedEvent,\n DocumentUpdatedEvent,\n DocumentDeletedEvent,\n} from \"./hooks.js\";\nexport { z } from \"zod\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoYO,SAAS,eAOd,QACsE;AACtE,SAAO;AACT;;;AC3WO,SAAS,iBAAiB,IAA0C;AACzE,SAAO;AACT;;;ACpBO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,QAAgB,OAAe,kBAA0B,MAAgB;AACnF,UAAM,gBAAgB;AACtB,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,QAAQ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AAQ,QAAQ,OAAO,gBAAgB,QAAQ;AAAA,EAC1D;AAAA,EAEA,UAAU,SAAgE;AACxE,WAAO,EAAE,QAAQ,QAAQ,OAAO,iBAAiB,QAAQ;AAAA,EAC3D;AAAA,EAEA,gBAAgB,SAA4E;AAC1F,WAAO,EAAE,QAAQ,QAAQ,OAAO,uBAAuB,QAAQ;AAAA,EACjE;AACF;AAIO,IAAM,UAAU;AAAA,EACrB,eAAe,SAA0E;AACvF,WAAO,EAAE,QAAQ,WAAW,OAAO,iBAAiB,QAAQ;AAAA,EAC9D;AAAA,EAEA,cAAc,SAAwE;AACpF,WAAO,EAAE,QAAQ,WAAW,OAAO,gBAAgB,QAAQ;AAAA,EAC7D;AACF;AAIO,IAAM,YAAY;AAAA,EACvB,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AAAA,EAEA,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AAAA,EAEA,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AACF;;;ACKA,SAAS,SAAS;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/endpoint.ts","../src/middleware.ts","../src/errors.ts","../src/worker.ts","../src/job.ts","../src/webhook.ts","../src/hooks.ts","../src/index.ts"],"sourcesContent":["import type { ZodSchema, z } from \"zod\";\nimport type { AuthConfig, HttpMethod, User } from \"./types.js\";\nimport type { MiddlewareContext } from \"./middleware.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport { HttpError } from \"./errors.js\";\nimport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseFlagsClient,\n PalbaseNotificationsClient,\n PalbaseAnalyticsClient,\n PalbaseLinksClient,\n PalbaseCmsClient,\n} from \"./clients.js\";\n\n/** Uploaded file metadata injected into endpoint context when a file is present.\n * `data` is typed as `Uint8Array` for SDK portability (Buffer extends Uint8Array in Node).\n */\nexport interface FileContext {\n filename: string;\n contentType: string;\n size: number;\n data: Uint8Array;\n}\n\n/** Queue client for dispatching background jobs from within a handler. */\nexport interface QueueClient {\n /** Enqueue a job for the named worker. Returns the new job ID. */\n push(worker: string, payload: unknown): Promise<{ jobId: string }>;\n}\n\n/** Rate limit configuration for an endpoint. */\nexport interface RateLimitConfig {\n /** Maximum number of requests in the window. */\n max: number;\n /** Window duration in seconds. */\n window: number;\n}\n\n/** The transaction-scoped client passed to `db.transaction(fn)` — same DB ops, no nested transaction. */\nexport type TxClient = Omit<DBClient, \"transaction\">;\n\n/** Database client interface injected into endpoint context. */\nexport interface DBClient {\n /** Run a read-only SQL query (executes in a READ ONLY transaction). */\n query(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;\n insert(table: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;\n update(table: string, id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;\n delete(table: string, id: string): Promise<void>;\n findById(table: string, id: string): Promise<Record<string, unknown> | null>;\n findMany(table: string, query?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n /**\n * Run an interactive transaction. The callback receives a `tx` with the same\n * DB ops as this client; returning normally commits, throwing rolls back.\n * Nested transactions are not supported.\n */\n transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T>;\n}\n\n/** Logger interface injected into endpoint context. */\nexport interface Logger {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n debug(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Cache client interface injected into endpoint context.\n *\n * The cache is JSON-typed: values are serialized to/from JSON, so any JSON\n * value (objects, arrays, numbers, booleans, strings) round-trips. `get<T>`\n * therefore returns `T | null` rather than `string | null`.\n */\nexport interface CacheClient {\n /** Read a value. Returns `null` on a cache miss. */\n get<T = unknown>(key: string): Promise<T | null>;\n /** Write a JSON-serializable value with an optional TTL (seconds). */\n set(key: string, value: unknown, ttl?: number): Promise<void>;\n /** Delete a key. */\n del(key: string): Promise<void>;\n /** Atomically increment an integer counter, returning the new value. */\n incr(key: string): Promise<number>;\n /**\n * Stampede-safe read-through cache fill. On a hit, returns the cached value.\n * On a miss, a single caller (across all pod replicas, coordinated by a\n * distributed lock) runs `fn`, caches the result for `ttl` seconds, and\n * returns it; concurrent callers wait for that result instead of also\n * running `fn`. If no value lands within the lock's TTL, the call rejects —\n * it does NOT run `fn` on timeout (that would reintroduce the stampede).\n *\n * @param ttl value TTL in seconds.\n */\n getOrSet<T>(key: string, ttl: number, fn: () => Promise<T> | T): Promise<T>;\n}\n\n/** Result envelope used across the Palbase Server SDK clients. */\nexport interface PalbaseResult<T> {\n data: T | null;\n error: { message?: string; code?: string } | null;\n status?: number;\n}\n\n/** Document snapshot returned by docs.get(). */\nexport interface PalbaseDocumentSnapshot<T = Record<string, unknown>> {\n id: string;\n exists: boolean;\n data(): T | undefined;\n ref: { path: string };\n}\n\n/** Collection query snapshot returned by collection.get(). */\nexport interface PalbaseQuerySnapshot<T = Record<string, unknown>> {\n docs: PalbaseDocumentSnapshot<T>[];\n empty: boolean;\n size: number;\n}\n\n/** Comparison operators supported by docs.where(). */\nexport type PalbaseWhereOperator =\n | \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\";\n\n/** Document reference exposed by Documents.collection(...).doc(...). */\nexport interface PalbaseDocumentRef<T = Record<string, unknown>> {\n readonly path: string;\n set(data: T): Promise<PalbaseResult<void>>;\n get(): Promise<PalbaseResult<PalbaseDocumentSnapshot<T>>>;\n update(data: Partial<T>): Promise<PalbaseResult<void>>;\n delete(): Promise<PalbaseResult<void>>;\n}\n\n/** Collection reference exposed by Documents.collection(...). */\nexport interface PalbaseCollectionRef<T = Record<string, unknown>> {\n readonly path: string;\n doc(id: string): PalbaseDocumentRef<T>;\n add(data: T): Promise<PalbaseResult<PalbaseDocumentRef<T>>>;\n where(field: string, op: PalbaseWhereOperator, value: unknown): PalbaseCollectionRef<T>;\n orderBy(field: string, direction?: \"asc\" | \"desc\"): PalbaseCollectionRef<T>;\n limit(n: number): PalbaseCollectionRef<T>;\n get(): Promise<PalbaseResult<PalbaseQuerySnapshot<T>>>;\n}\n\n/** Docs client surface available on the Documents singleton. */\nexport interface PalbaseDocsClient {\n collection<T = Record<string, unknown>>(path: string): PalbaseCollectionRef<T>;\n doc<T = Record<string, unknown>>(path: string): PalbaseDocumentRef<T>;\n}\n\n/** Calling-client metadata, derived from request headers.\n *\n * Populated from the `X-Palbase-*-Version` / platform headers the client SDKs\n * send. All fields are nullable: a request may come from a non-SDK caller\n * (curl, server-to-server) that sends none of them. The semver comparison\n * helpers (`appVersionAtLeast`, …) arrive in Phase 2 — Phase 1 surfaces only\n * the raw data fields. */\nexport interface ClientInfo {\n /** Palbase SDK version (`X-Palbase-Sdk-Version`), or null. */\n sdkVersion: string | null;\n /** Calling app's own version (`X-Palbase-Client-Version`), or null. */\n appVersion: string | null;\n /** Platform identifier (e.g. \"ios\", \"android\", \"web\"), or null. */\n platform: string | null;\n /** OS version string, or null. */\n osVersion: string | null;\n}\n\n/** Palbase module clients, as a structural bundle.\n *\n * NOT part of the endpoint surface anymore — endpoint handlers reach services\n * via the PascalCase singletons (`Database`, `Documents`, …). This type is\n * retained as an INTERNAL shape for the sibling contexts that still carry a\n * `ctx` (middleware, jobs, workers, hooks, webhooks — out of Phase 1 scope).\n * It is intentionally not re-exported from `index.ts`.\n *\n * Structurally typed against the runtime's `ServerClient`; the runtime injects\n * the real client, so mismatched names would surface as `undefined is not a\n * function` at call time — keep these in sync with `ServerClient`. */\nexport interface PalbaseModuleClients {\n auth: PalbaseAuthClient;\n storage: PalbaseStorageClient;\n docs: PalbaseDocsClient;\n realtime: PalbaseRealtimeClient;\n functions: PalbaseFunctionsClient;\n flags: PalbaseFlagsClient;\n notifications: PalbaseNotificationsClient;\n analytics: PalbaseAnalyticsClient;\n links: PalbaseLinksClient;\n cms: PalbaseCmsClient;\n}\n\n/** Declared-error definition.\n *\n * `code` is the stable snake_case identifier that lands on the wire envelope's\n * `error` field. `status` is the HTTP status code returned. `data`, if set,\n * is a Zod schema whose value rides on the envelope's `data` field — the CLI\n * codegen lowers it to the typed enum's associated value on iOS.\n *\n * `description` is optional human-readable text; the OpenAPI generator uses it\n * for the response description and the iOS codegen surfaces it in the\n * generated method's doc-comment.\n */\nexport interface ErrorDef<TData extends ZodSchema = ZodSchema> {\n status: number;\n code: string;\n description?: string;\n data?: TData;\n}\n\n/** Map of declared errors keyed by their TypeScript-side names.\n *\n * Keys are the friendly names the handler uses (`req.errors.todoLocked`);\n * `code` on each value is the wire identifier. The TS name is what the iOS\n * codegen lowers to (camelCase enum cases), and the wire `code` is what the\n * envelope's `error` field carries.\n */\nexport type ErrorMap = Record<string, ErrorDef>;\n\n/** Throwable proxy projected onto `req.errors` when `errors` is declared.\n *\n * Each entry is a constructor: declared errors with a `data` schema demand\n * the payload as a required argument; declared errors without `data` take\n * none. Throwing the result emits the standard envelope (with `data` when\n * present).\n *\n * throw req.errors.todoNotFound();\n * throw req.errors.todoLocked({ retryAfter: 30 });\n */\nexport type ErrorThrowers<TErrors extends ErrorMap | undefined> =\n TErrors extends ErrorMap\n ? {\n [K in keyof TErrors]: TErrors[K][\"data\"] extends ZodSchema\n ? (data: z.infer<NonNullable<TErrors[K][\"data\"]>>) => HttpError\n : () => HttpError;\n }\n : Record<string, never>;\n\n/** The request-scoped object passed to every endpoint handler.\n *\n * Replaces the old `ctx` god-object. `PBRequest` carries ONLY request-scoped\n * data — the typed `input`, route/query params, headers, the authenticated\n * `user`, calling-client metadata, trace ids, and the endpoint's declared\n * error throwers. Services (`Database`, `Documents`, `Cache`, …) are NOT on\n * the request: import them directly from `@palbase/backend` as singletons.\n *\n * import { defineEndpoint, Database } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => Database.insert(\"todos\", { title: req.input.title }),\n * });\n *\n * Generic parameters:\n * - `TInput` — the validated `input` type (inferred from the `input` Zod\n * schema by `defineEndpoint`). The user-facing form is single-generic:\n * `PBRequest<TodoInput>`.\n * - `TAuthed` — whether `user` is non-null. DEFAULTS to `true` (the common\n * case; the auth pipeline returns 401 before the handler when auth is\n * required, so a non-null `user` is runtime-honest). `defineEndpoint` passes\n * `IsAuthed<TAuth>` here, so `auth: false` → `User | null`.\n * - `TErrors` — the declared `errors` map, typing `req.errors.<name>(...)`.\n */\nexport interface PBRequest<\n TInput = unknown,\n TAuthed extends boolean = true,\n TErrors extends ErrorMap | undefined = undefined,\n> {\n /** Validated request input (body for POST/PUT/PATCH; `{}` otherwise). */\n input: TInput;\n /** Matched route params (e.g. `{ id }` for `/todos/[id]`). */\n params: Record<string, string>;\n /** Parsed query-string params. */\n query: Record<string, string>;\n /** Request headers (lowercase keys). */\n headers: Record<string, string>;\n /** Authenticated user. Non-null (`User`) by default; `User | null` only when\n * the endpoint's `auth` config disables enforcement (driven by `TAuthed`,\n * which `defineEndpoint` computes from the `auth` literal via {@link IsAuthed}). */\n user: TAuthed extends true ? User : User | null;\n /** Calling-client metadata derived from request headers (all nullable). */\n client: ClientInfo;\n /** Uploaded file, or null when the request has no file part. */\n file: FileContext | null;\n /** HTTP method of the incoming request (e.g. \"GET\", \"POST\"). */\n method: string;\n /** Per-request id (`req_<…>`), preserved for back-compat correlation. */\n requestId: string;\n /** W3C trace id (primary correlation key across modules). */\n traceId: string;\n /** W3C span id for this handler invocation. */\n spanId: string;\n /** Typed throwers for the endpoint's declared errors. Empty when the\n * `errors` block is absent on `defineEndpoint`. */\n errors: ErrorThrowers<TErrors>;\n}\n\n/** Middleware function signature — uses MiddlewareContext (no input, not yet validated). */\nexport type Middleware = (\n ctx: MiddlewareContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/** The shape an endpoint's `auth` config may take.\n *\n * Either a bare boolean (`true`/`false`) or an object form (`{ required?,\n * role? }`). The object form is `Partial<AuthConfig>` so `required` may be\n * omitted — which the runtime treats as `required: true` (see {@link IsAuthed}).\n */\nexport type AuthSpec = boolean | Partial<AuthConfig>;\n\n/** Compute, at the type level, whether an endpoint authenticates its caller —\n * i.e. whether `req.user` should be `User` (non-null) instead of `User | null`.\n *\n * This mirrors the Go pipeline's enforcement exactly (extract_meta.js + auth.go):\n * a request is authenticated ⟺ `auth === true` OR (`auth` is an object whose\n * `required` is not explicitly `false`). So `req.user` stays nullable ONLY when\n * `auth` is absent (`undefined`), `auth === false`, or `auth: { required: false }`.\n *\n * | `TAuth` | `IsAuthed<TAuth>` |\n * |---------------------------------|-------------------|\n * | `undefined` | `false` |\n * | `true` | `true` |\n * | `false` | `false` |\n * | `{ required: true }` | `true` |\n * | `{ required: false }` | `false` |\n * | `{ role: 'admin' }` (no `required`) | `true` ⚠️ |\n *\n * Order matters: the `{ required: false }` branch is checked first so the\n * object case can't swallow it; `true` then `false` literals are handled\n * explicitly before the catch-all object branch (which encodes the\n * \"required omitted ⇒ required\" corner case).\n */\nexport type IsAuthed<TAuth> = TAuth extends { required: false }\n ? false\n : TAuth extends true\n ? true\n : TAuth extends false\n ? false\n : TAuth extends object\n ? true\n : false;\n\n/** Configuration for defining an endpoint.\n *\n * `TSchema` — optional `SchemaDef` carried on the `schema` field. The runtime\n * uses it to wire a typed `.tables.*` API; authors opt in per endpoint with\n * `typedDatabase(schema)` (see runtime.ts).\n *\n * `TAuth` — captures the literal type of the `auth` field (via the `const`\n * type parameter on `defineEndpoint`) so the handler's `req.user` can be\n * narrowed to non-null `User` when auth is required. See {@link IsAuthed}.\n *\n * `TErrors` — captures the literal `errors` map (via the `const` type\n * parameter on `defineEndpoint`) so `req.errors.<name>(...)` is typed per\n * declared entry. The OpenAPI generator emits each one as a discriminated\n * response under `responses[<status>]`, and the CLI codegen lowers them to\n * a typed `<Endpoint>.Error` enum on iOS.\n */\nexport interface EndpointConfig<\n TInputSchema extends ZodSchema = ZodSchema,\n TOutputSchema extends ZodSchema = ZodSchema,\n TSchema extends SchemaDef | undefined = undefined,\n TAuth extends AuthSpec | undefined = undefined,\n TErrors extends ErrorMap | undefined = undefined,\n> {\n method: HttpMethod;\n auth?: TAuth;\n rateLimit?: RateLimitConfig;\n input?: TInputSchema;\n output?: TOutputSchema;\n schema?: TSchema;\n errors?: TErrors;\n middleware?: Middleware[];\n handler: (\n req: PBRequest<z.infer<TInputSchema>, IsAuthed<TAuth>, TErrors>,\n ) => Promise<z.infer<TOutputSchema>>;\n}\n\n/** Define a type-safe endpoint. The input schema infers the `req.input` type.\n * Pass a `schema` (from `defineSchema`) and wrap `Database` with\n * `typedDatabase(schema)` in the handler for a typed `.tables.*` API.\n *\n * The `const TAuth` and `const TErrors` type parameters capture the `auth`\n * and `errors` fields as literals, so `req.user` narrows to non-null `User`\n * when auth is enforced and `req.errors.<name>(...)` is typed per declared\n * entry.\n */\nexport function defineEndpoint<\n TInputSchema extends ZodSchema,\n TOutputSchema extends ZodSchema,\n TSchema extends SchemaDef | undefined = undefined,\n const TAuth extends AuthSpec | undefined = undefined,\n const TErrors extends ErrorMap | undefined = undefined,\n>(\n config: EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors>,\n): EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors> {\n return config;\n}\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 projectId: 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","/** HTTP error with structured error response format.\n *\n * Two ways to construct one:\n *\n * 1. Directly: `throw new HttpError(404, \"todo_not_found\", \"No such todo\")`.\n * Surfaces on the wire (and to iOS) as `BackendError.server(code, status,\n * message, requestId)`.\n * 2. Via `ctx.errors.<name>(data?)` for declared errors — see\n * `EndpointConfig.errors`. The endpoint's OpenAPI spec describes each\n * one, and the CLI codegen emits a typed `<Endpoint>.Error` enum so iOS\n * callers can `catch <Endpoint>.Error.<case>` directly.\n *\n * The optional `data` field carries a structured payload alongside the\n * standard envelope — used by declared errors that need to ship extra context\n * (e.g. `todoLocked({ retryAfter: 30 })`). It rides through to the iOS typed\n * 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\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","import type {\n DBClient,\n Logger,\n CacheClient,\n QueueClient,\n PalbaseModuleClients,\n ErrorThrowers,\n} from \"./endpoint.js\";\nimport type { User } from \"./types.js\";\n\n/** Context injected into worker handlers — the non-request-scoped service\n * surface (db/log/cache/queue + module clients), plus correlation ids. Workers\n * are not part of the Phase 1 `ctx → PBRequest` redesign, so they keep their\n * own `ctx`; the job payload arrives as the handler's second argument. */\nexport interface WorkerContext extends PalbaseModuleClients {\n user: User | null;\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n errors: ErrorThrowers<undefined>;\n requestId: string;\n projectId: string;\n environmentId: string;\n}\n\n/** Backoff strategy for worker retries. */\nexport type BackoffStrategy = \"exponential\" | \"linear\" | \"fixed\";\n\n/** Configuration for a background worker. */\nexport interface WorkerConfig<TPayload = unknown> {\n /** Worker name — must be unique across the project. */\n name: string;\n /** Maximum number of retries before sending to dead letter queue. Defaults to 3. */\n retry?: number;\n /** Execution timeout in seconds. Defaults to 30. */\n timeout?: number;\n /** Backoff strategy between retries. Defaults to \"exponential\". */\n backoff?: BackoffStrategy;\n /** Handler function that processes the job payload. */\n handler: (\n ctx: WorkerContext,\n payload: TPayload,\n ) => Promise<void>;\n}\n\n/** Resolved worker configuration with defaults applied. */\nexport interface ResolvedWorkerConfig<TPayload = unknown> {\n name: string;\n retry: number;\n timeout: number;\n backoff: BackoffStrategy;\n handler: (\n ctx: WorkerContext,\n payload: TPayload,\n ) => Promise<void>;\n}\n\n/** Valid worker name pattern: alphanumeric, underscore, hyphen only.\n * Prevents Redis key injection via colons or path separators. */\nconst VALID_WORKER_NAME = /^[a-zA-Z0-9_-]+$/;\n\n/** Default values for worker configuration. */\nconst WORKER_DEFAULTS = {\n retry: 3,\n timeout: 30,\n backoff: \"exponential\" as BackoffStrategy,\n} as const;\n\n/**\n * Define a background worker that processes jobs from the queue.\n *\n * Workers are placed in the `workers/` directory and auto-discovered at deploy time.\n *\n * @example\n * ```ts\n * export default defineWorker({\n * name: \"send-email\",\n * retry: 5,\n * timeout: 60,\n * backoff: \"exponential\",\n * handler: async (ctx, payload: { to: string; subject: string }) => {\n * await sendEmail(payload.to, payload.subject);\n * },\n * });\n * ```\n */\nexport function defineWorker<TPayload = unknown>(\n config: WorkerConfig<TPayload>,\n): ResolvedWorkerConfig<TPayload> {\n if (!config.name || config.name.trim() === \"\") {\n throw new Error(\"Worker name is required\");\n }\n\n if (!VALID_WORKER_NAME.test(config.name)) {\n throw new Error(\n `Invalid worker name \"${config.name}\": must match [a-zA-Z0-9_-]+`,\n );\n }\n\n if (config.retry !== undefined && (config.retry < 0 || !Number.isInteger(config.retry))) {\n throw new Error(\"Worker retry must be a non-negative integer\");\n }\n\n if (config.timeout !== undefined && config.timeout <= 0) {\n throw new Error(\"Worker timeout must be a positive number\");\n }\n\n if (\n config.backoff !== undefined &&\n ![\"exponential\", \"linear\", \"fixed\"].includes(config.backoff)\n ) {\n throw new Error(`Invalid backoff strategy: ${config.backoff}`);\n }\n\n return {\n name: config.name,\n retry: config.retry ?? WORKER_DEFAULTS.retry,\n timeout: config.timeout ?? WORKER_DEFAULTS.timeout,\n backoff: config.backoff ?? WORKER_DEFAULTS.backoff,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Context injected into job handlers — subset of EndpointContext without request-specific fields. */\nexport interface JobContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n}\n\n/** Configuration for defining a scheduled job. */\nexport interface JobConfig {\n /** Unique job name — alphanumeric, underscore, hyphen only. */\n name: string;\n /** Cron expression (e.g., \"0 3 * * *\"). */\n schedule: string;\n /** Execution timeout in seconds. Defaults to 30. */\n timeout?: number;\n /** Job handler function. */\n handler: (ctx: JobContext) => Promise<void>;\n}\n\n/** Resolved job configuration with defaults applied. */\nexport interface ResolvedJobConfig {\n name: string;\n schedule: string;\n timeout: number;\n handler: (ctx: JobContext) => Promise<void>;\n}\n\n/** Valid job name pattern: alphanumeric, underscore, hyphen only. */\nconst VALID_JOB_NAME = /^[a-zA-Z0-9_-]+$/;\n\n/** Maximum allowed timeout in seconds (5 minutes, matching sandbox limits). */\nconst MAX_TIMEOUT_SECONDS = 300;\n\n/** Default values for job configuration. */\nconst JOB_DEFAULTS = {\n timeout: 30,\n} as const;\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 */\nfunction 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\n/**\n * Define a scheduled cron job.\n *\n * Jobs are placed in the `jobs/` directory and auto-discovered at deploy time.\n *\n * @example\n * ```ts\n * export default defineJob({\n * name: \"cleanup-expired\",\n * schedule: \"0 3 * * *\", // every day at 3 AM\n * timeout: 60,\n * handler: async (ctx) => {\n * await ctx.db.delete(\"sessions\", \"expired < NOW()\");\n * ctx.log.info(\"Cleaned up expired sessions\");\n * },\n * });\n * ```\n */\nexport function defineJob(config: JobConfig): ResolvedJobConfig {\n if (!config.name || config.name.trim() === \"\") {\n throw new Error(\"Job name is required\");\n }\n\n if (!VALID_JOB_NAME.test(config.name)) {\n throw new Error(\n `Invalid job name \"${config.name}\": must match [a-zA-Z0-9_-]+`,\n );\n }\n\n if (!config.schedule || config.schedule.trim() === \"\") {\n throw new Error(\"Job schedule is required\");\n }\n\n const cronError = validateCronExpression(config.schedule);\n if (cronError !== null) {\n throw new Error(cronError);\n }\n\n if (!config.handler) {\n throw new Error(\"Job handler is required\");\n }\n\n if (config.timeout !== undefined && config.timeout <= 0) {\n throw new Error(\"Job timeout must be a positive number\");\n }\n\n if (config.timeout !== undefined && !Number.isInteger(config.timeout)) {\n throw new Error(\"Job timeout must be an integer\");\n }\n\n if (config.timeout !== undefined && config.timeout > MAX_TIMEOUT_SECONDS) {\n throw new Error(\n `Job timeout ${config.timeout}s exceeds maximum ${MAX_TIMEOUT_SECONDS}s`,\n );\n }\n\n return {\n name: config.name,\n schedule: config.schedule.trim(),\n timeout: config.timeout ?? JOB_DEFAULTS.timeout,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Supported webhook provider types. */\nexport type WebhookProvider =\n | \"stripe\"\n | \"github\"\n | \"twilio\"\n | \"sendgrid\"\n | \"slack\"\n | \"discord\"\n | \"livekit\";\n\n/** Context injected into webhook handlers — no user (webhooks are machine-to-machine). */\nexport interface WebhookContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n requestId: string;\n}\n\n/** Secret reference — resolves from environment variables at runtime. */\nexport interface EnvSecretRef {\n env: string;\n}\n\n/** Provider-specific event maps for type-safe event handlers. */\nexport interface ProviderEventMap {\n stripe: {\n \"checkout.session.completed\": Record<string, unknown>;\n \"payment_intent.succeeded\": Record<string, unknown>;\n \"payment_intent.payment_failed\": Record<string, unknown>;\n \"customer.subscription.created\": Record<string, unknown>;\n \"customer.subscription.updated\": Record<string, unknown>;\n \"customer.subscription.deleted\": Record<string, unknown>;\n \"invoice.paid\": Record<string, unknown>;\n \"invoice.payment_failed\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n github: {\n push: Record<string, unknown>;\n pull_request: Record<string, unknown>;\n issues: Record<string, unknown>;\n \"pull_request.opened\": Record<string, unknown>;\n \"pull_request.closed\": Record<string, unknown>;\n \"pull_request.merged\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n twilio: {\n \"message.received\": Record<string, unknown>;\n \"message.sent\": Record<string, unknown>;\n \"call.completed\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n sendgrid: {\n delivered: Record<string, unknown>;\n bounce: Record<string, unknown>;\n open: Record<string, unknown>;\n click: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n slack: {\n url_verification: Record<string, unknown>;\n event_callback: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n discord: {\n PING: Record<string, unknown>;\n MESSAGE_CREATE: Record<string, unknown>;\n INTERACTION_CREATE: Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n livekit: {\n \"room.started\": Record<string, unknown>;\n \"room.finished\": Record<string, unknown>;\n \"participant.joined\": Record<string, unknown>;\n \"participant.left\": Record<string, unknown>;\n [key: string]: Record<string, unknown>;\n };\n}\n\n/** Event handler function type. */\nexport type WebhookEventHandler<TEvent = Record<string, unknown>> = (\n ctx: WebhookContext,\n event: TEvent,\n) => Promise<void>;\n\n/** Provider-based webhook configuration. */\nexport interface ProviderWebhookConfig<P extends WebhookProvider = WebhookProvider> {\n provider: P;\n secret: EnvSecretRef;\n events: {\n [K in keyof ProviderEventMap[P]]?: WebhookEventHandler<ProviderEventMap[P][K]>;\n };\n}\n\n/** Incoming request representation for custom verify functions. */\nexport interface WebhookRequest {\n headers: Record<string, string>;\n body: string;\n method: string;\n url: string;\n}\n\n/** Custom webhook configuration. */\nexport interface CustomWebhookConfig {\n path: string;\n verify?: (req: WebhookRequest) => Promise<boolean> | boolean;\n handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;\n}\n\n/** Resolved provider webhook (internal). */\nexport interface ResolvedProviderWebhook<P extends WebhookProvider = WebhookProvider> {\n type: \"provider\";\n provider: P;\n secret: EnvSecretRef;\n events: Record<string, WebhookEventHandler>;\n}\n\n/** Resolved custom webhook (internal). */\nexport interface ResolvedCustomWebhook {\n type: \"custom\";\n path: string;\n verify?: (req: WebhookRequest) => Promise<boolean> | boolean;\n handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;\n}\n\n/** Union of resolved webhook types. */\nexport type ResolvedWebhookConfig = ResolvedProviderWebhook | ResolvedCustomWebhook;\n\n/** Valid webhook path pattern: starts with /, alphanumeric + hyphen + slash. */\nconst VALID_WEBHOOK_PATH = /^\\/[a-zA-Z0-9/_-]+$/;\n\n/**\n * Define a provider-based webhook.\n *\n * @example\n * ```ts\n * export default defineWebhook({\n * provider: \"stripe\",\n * secret: { env: \"STRIPE_WEBHOOK_SECRET\" },\n * events: {\n * \"checkout.session.completed\": async (ctx, event) => {\n * await ctx.db.insert(\"orders\", { status: \"paid\" });\n * },\n * },\n * });\n * ```\n */\nexport function defineWebhook<P extends WebhookProvider>(\n config: ProviderWebhookConfig<P>,\n): ResolvedProviderWebhook<P>;\n\n/**\n * Define a custom webhook with optional verification.\n *\n * @example\n * ```ts\n * export default defineWebhook({\n * path: \"/webhooks/livekit\",\n * verify: async (req) => req.headers[\"x-api-key\"] === \"secret\",\n * handler: async (ctx, payload) => {\n * ctx.log.info(\"Received webhook\", payload);\n * },\n * });\n * ```\n */\nexport function defineWebhook(config: CustomWebhookConfig): ResolvedCustomWebhook;\n\nexport function defineWebhook(\n config: ProviderWebhookConfig | CustomWebhookConfig,\n): ResolvedWebhookConfig {\n if (\"provider\" in config) {\n return validateProviderWebhook(config);\n }\n return validateCustomWebhook(config);\n}\n\nfunction validateProviderWebhook<P extends WebhookProvider>(\n config: ProviderWebhookConfig<P>,\n): ResolvedProviderWebhook<P> {\n if (!config.provider) {\n throw new Error(\"Webhook provider is required\");\n }\n\n const validProviders: WebhookProvider[] = [\n \"stripe\", \"github\", \"twilio\", \"sendgrid\", \"slack\", \"discord\", \"livekit\",\n ];\n if (!validProviders.includes(config.provider)) {\n throw new Error(\n `Invalid webhook provider \"${config.provider}\": must be one of ${validProviders.join(\", \")}`,\n );\n }\n\n if (!config.secret) {\n throw new Error(\"Webhook secret is required (use { env: \\\"SECRET_NAME\\\" })\");\n }\n\n if (typeof config.secret.env !== \"string\" || config.secret.env.trim() === \"\") {\n throw new Error(\"Webhook secret env name must be a non-empty string\");\n }\n\n if (!config.events || Object.keys(config.events).length === 0) {\n throw new Error(\"At least one event handler is required\");\n }\n\n for (const [eventName, handler] of Object.entries(config.events)) {\n if (typeof handler !== \"function\") {\n throw new Error(`Event handler for \"${eventName}\" must be a function`);\n }\n }\n\n return {\n type: \"provider\",\n provider: config.provider,\n secret: config.secret,\n events: config.events as Record<string, WebhookEventHandler>,\n };\n}\n\nfunction validateCustomWebhook(config: CustomWebhookConfig): ResolvedCustomWebhook {\n if (!config.path || config.path.trim() === \"\") {\n throw new Error(\"Webhook path is required\");\n }\n\n if (!VALID_WEBHOOK_PATH.test(config.path)) {\n throw new Error(\n `Invalid webhook path \"${config.path}\": must start with / and contain only alphanumeric, hyphen, underscore, slash`,\n );\n }\n\n if (!config.handler) {\n throw new Error(\"Webhook handler is required\");\n }\n\n if (typeof config.handler !== \"function\") {\n throw new Error(\"Webhook handler must be a function\");\n }\n\n if (config.verify !== undefined && typeof config.verify !== \"function\") {\n throw new Error(\"Webhook verify must be a function\");\n }\n\n return {\n type: \"custom\",\n path: config.path,\n verify: config.verify,\n handler: config.handler,\n };\n}\n","import type { DBClient, Logger, CacheClient, PalbaseModuleClients, QueueClient } from \"./endpoint.js\";\n\n/** Context injected into hook handlers. */\nexport interface HookContext extends PalbaseModuleClients {\n db: DBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n projectId: string;\n environmentId: string;\n}\n\n// --- Auth Event Payloads ---\n\n/** Payload for auth.onUserCreated hook. */\nexport interface UserCreatedEvent {\n user: {\n id: string;\n email: string;\n role: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n };\n}\n\n/** Payload for auth.onSignIn hook. */\nexport interface SignInEvent {\n user: {\n id: string;\n email: string;\n role: string;\n };\n provider: string;\n timestamp: string;\n}\n\n/** Payload for auth.onSignOut hook. */\nexport interface SignOutEvent {\n user: {\n id: string;\n email: string;\n };\n timestamp: string;\n}\n\n/** Payload for auth.onPasswordReset hook. */\nexport interface PasswordResetEvent {\n user: {\n id: string;\n email: string;\n };\n timestamp: string;\n}\n\n// --- Storage Event Payloads ---\n\n/** Payload for storage.onFileUploaded hook. */\nexport interface FileUploadedEvent {\n file: {\n id: string;\n name: string;\n bucket: string;\n path: string;\n size: number;\n contentType: string;\n };\n}\n\n/** Payload for storage.onFileDeleted hook. */\nexport interface FileDeletedEvent {\n file: {\n id: string;\n name: string;\n bucket: string;\n path: string;\n };\n}\n\n// --- Documents Event Payloads ---\n\n/** Payload for documents.onDocumentCreated hook. */\nexport interface DocumentCreatedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n };\n}\n\n/** Payload for documents.onDocumentUpdated hook. */\nexport interface DocumentUpdatedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n previousData: Record<string, unknown>;\n };\n}\n\n/** Payload for documents.onDocumentDeleted hook. */\nexport interface DocumentDeletedEvent {\n document: {\n id: string;\n collection: string;\n data: Record<string, unknown>;\n };\n}\n\n// --- Hook Handler Types ---\n\nexport type HookHandler<TEvent> = (ctx: HookContext, event: TEvent) => Promise<void>;\n\n/** Resolved hook configuration (internal). */\nexport interface ResolvedHook<TEvent = unknown> {\n module: string;\n event: string;\n handler: HookHandler<TEvent>;\n}\n\n// --- Auth Hooks ---\n\nexport const auth = {\n onUserCreated(handler: HookHandler<UserCreatedEvent>): ResolvedHook<UserCreatedEvent> {\n return { module: \"auth\", event: \"user.created\", handler };\n },\n\n onSignIn(handler: HookHandler<SignInEvent>): ResolvedHook<SignInEvent> {\n return { module: \"auth\", event: \"user.sign_in\", handler };\n },\n\n onSignOut(handler: HookHandler<SignOutEvent>): ResolvedHook<SignOutEvent> {\n return { module: \"auth\", event: \"user.sign_out\", handler };\n },\n\n onPasswordReset(handler: HookHandler<PasswordResetEvent>): ResolvedHook<PasswordResetEvent> {\n return { module: \"auth\", event: \"user.password_reset\", handler };\n },\n};\n\n// --- Storage Hooks ---\n\nexport const storage = {\n onFileUploaded(handler: HookHandler<FileUploadedEvent>): ResolvedHook<FileUploadedEvent> {\n return { module: \"storage\", event: \"file.uploaded\", handler };\n },\n\n onFileDeleted(handler: HookHandler<FileDeletedEvent>): ResolvedHook<FileDeletedEvent> {\n return { module: \"storage\", event: \"file.deleted\", handler };\n },\n};\n\n// --- Documents Hooks ---\n\nexport const documents = {\n onDocumentCreated(handler: HookHandler<DocumentCreatedEvent>): ResolvedHook<DocumentCreatedEvent> {\n return { module: \"documents\", event: \"document.created\", handler };\n },\n\n onDocumentUpdated(handler: HookHandler<DocumentUpdatedEvent>): ResolvedHook<DocumentUpdatedEvent> {\n return { module: \"documents\", event: \"document.updated\", handler };\n },\n\n onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent> {\n return { module: \"documents\", event: \"document.deleted\", handler };\n },\n};\n","export { defineEndpoint } from \"./endpoint.js\";\nexport type {\n EndpointConfig,\n PBRequest,\n ClientInfo,\n RateLimitConfig,\n DBClient,\n TxClient,\n FileContext,\n QueueClient,\n Logger,\n CacheClient,\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 Queue,\n Log,\n Notifications,\n Flags,\n typedDatabase,\n __setRuntime,\n __runWithRuntime,\n __requestALS,\n __getRuntime,\n} from \"./runtime.js\";\nexport type { RuntimeServices } from \"./runtime.js\";\nexport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseRealtimeClient,\n PalbaseRealtimeChannel,\n PalbaseRealtimeMessage,\n PalbaseFunctionsClient,\n PalbaseInvokeOptions,\n PalbaseFlagsClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseNotificationsClient,\n PalbasePushClient,\n PalbaseEmailClient,\n PalbaseSmsClient,\n PalbaseInboxClient,\n PalbasePreferencesClient,\n PalbaseAnalyticsClient,\n PalbaseAnalyticsQueryNamespace,\n PalbaseAnalyticsManagementNamespace,\n PalbaseLinksClient,\n PalbaseCmsClient,\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 PalbasePublicUrlResponse,\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 PalbaseCmsFindOptions,\n PalbaseCmsFindOneOptions,\n} from \"./clients.js\";\nexport { defineSchema, table } from \"./db/schema.js\";\nexport type { SchemaDef, TableDef } from \"./db/schema.js\";\nexport { uuid, text, integer, boolean, timestamp, jsonb, enumType } from \"./db/columns.js\";\nexport type { ColumnBuilder, ColumnDef, ColumnType, OnDeleteAction } from \"./db/columns.js\";\nexport { makeTypedDB } from \"./db/typed-db.js\";\nexport type { TypedDB, TypedTx, TypedTable, InsertShape, RowShape } from \"./db/typed-db.js\";\nexport { defineMiddleware } from \"./middleware.js\";\nexport type { MiddlewareContext, MiddlewareHandler } from \"./middleware.js\";\nexport type { User, HttpMethod, AuthConfig } from \"./types.js\";\nexport { HttpError } from \"./errors.js\";\nexport { defineWorker } from \"./worker.js\";\nexport type {\n WorkerConfig,\n ResolvedWorkerConfig,\n WorkerContext,\n BackoffStrategy,\n} from \"./worker.js\";\nexport { defineJob } from \"./job.js\";\nexport type { JobConfig, ResolvedJobConfig, JobContext } from \"./job.js\";\nexport { defineWebhook } from \"./webhook.js\";\nexport type {\n WebhookProvider,\n WebhookContext,\n EnvSecretRef,\n ProviderWebhookConfig,\n CustomWebhookConfig,\n ResolvedProviderWebhook,\n ResolvedCustomWebhook,\n ResolvedWebhookConfig,\n WebhookEventHandler,\n WebhookRequest,\n ProviderEventMap,\n} from \"./webhook.js\";\nexport { auth, storage, documents } from \"./hooks.js\";\nexport type {\n HookContext,\n HookHandler,\n ResolvedHook,\n UserCreatedEvent,\n SignInEvent,\n SignOutEvent,\n PasswordResetEvent,\n FileUploadedEvent,\n FileDeletedEvent,\n DocumentCreatedEvent,\n DocumentUpdatedEvent,\n DocumentDeletedEvent,\n} from \"./hooks.js\";\nexport { z } from \"zod\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoYO,SAAS,eAOd,QACsE;AACtE,SAAO;AACT;;;AC3WO,SAAS,iBAAiB,IAA0C;AACzE,SAAO;AACT;;;ACpBO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,QAAgB,OAAe,kBAA0B,MAAgB;AACnF,UAAM,gBAAgB;AACtB,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,QAAQ;AACb,SAAK,mBAAmB;AACxB,QAAI,SAAS,QAAW;AACtB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AAA,EAEA,UAAU,SAAgE;AACxE,WAAO,EAAE,QAAQ,QAAQ,OAAO,iBAAiB,QAAQ;AAAA,EAC3D;AAAA,EAEA,gBAAgB,SAA4E;AAC1F,WAAO,EAAE,QAAQ,QAAQ,OAAO,uBAAuB,QAAQ;AAAA,EACjE;AACF;AAIO,IAAM,UAAU;AAAA,EACrB,eAAe,SAA0E;AACvF,WAAO,EAAE,QAAQ,WAAW,OAAO,iBAAiB,QAAQ;AAAA,EAC9D;AAAA,EAEA,cAAc,SAAwE;AACpF,WAAO,EAAE,QAAQ,WAAW,OAAO,gBAAgB,QAAQ;AAAA,EAC7D;AACF;AAIO,IAAM,YAAY;AAAA,EACvB,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AAAA,EAEA,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AAAA,EAEA,kBAAkB,SAAgF;AAChG,WAAO,EAAE,QAAQ,aAAa,OAAO,oBAAoB,QAAQ;AAAA,EACnE;AACF;;;ACOA,SAAS,SAAS;","names":[]}
|
package/dist/test/index.cjs
CHANGED
|
@@ -26,14 +26,18 @@ __export(test_exports, {
|
|
|
26
26
|
module.exports = __toCommonJS(test_exports);
|
|
27
27
|
|
|
28
28
|
// src/runtime.ts
|
|
29
|
+
var import_node_async_hooks = require("async_hooks");
|
|
30
|
+
var __requestALS = new import_node_async_hooks.AsyncLocalStorage();
|
|
29
31
|
var runtime = null;
|
|
30
32
|
function __setRuntime(services) {
|
|
31
33
|
runtime = services;
|
|
32
34
|
}
|
|
33
35
|
function __getRuntime() {
|
|
36
|
+
const scoped = __requestALS.getStore();
|
|
37
|
+
if (scoped) return scoped.runtime;
|
|
34
38
|
if (runtime === null) {
|
|
35
39
|
throw new Error(
|
|
36
|
-
"Palbase services accessed outside a request scope. The Database/Documents/\u2026 singletons are only available inside an endpoint handler (or after the runtime has called __setRuntime)."
|
|
40
|
+
"Palbase services accessed outside a request scope. The Database/Documents/\u2026 singletons are only available inside an endpoint handler (or after the runtime has called __runWithRuntime / __setRuntime)."
|
|
37
41
|
);
|
|
38
42
|
}
|
|
39
43
|
return runtime;
|
package/dist/test/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/index.ts","../../src/runtime.ts","../../src/test/mock-db.ts","../../src/test/context.ts"],"sourcesContent":["export { createTestContext } from \"./context.js\";\nexport type { TestContextOptions, TestContext, LogEntry } from \"./context.js\";\nexport { createMockDB } from \"./mock-db.js\";\nexport type { MockDBClient } from \"./mock-db.js\";\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, endpoint authors import PascalCase service singletons directly:\n *\n * import { Database, Documents, Cache } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => {\n * const row = await Database.insert(\"todos\", { title: req.input.title });\n * return row;\n * },\n * });\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client held in a per-process mutable slot, which the runtime sets with\n * {@link __setRuntime} BEFORE invoking the handler and (today) leaves in place\n * for the lifetime of that fresh Node subprocess. Because each `br-<ref>` pod\n * is single-tenant and every request runs in a fresh Node subprocess\n * (node_executor.go), there is no cross-tenant leakage risk.\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 — calling `__setRuntime` on that instance is visible to the\n * singletons the bundle imported.\n */\n\nimport type {\n DBClient,\n CacheClient,\n QueueClient,\n Logger,\n PalbaseDocsClient,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n} from \"./clients.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport type { TypedDB } from \"./db/typed-db.js\";\nimport { makeTypedDB } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They\n * are not exposed as backend handler singletons (auth lives on the client SDK;\n * the rest are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Queue: QueueClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n}\n\n/** Per-process slot holding the live clients for the current request scope. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients for the current request scope.\n *\n * Called by the Palbase runtime (worker.js / dev-server.js) immediately before\n * invoking a handler. NOT part of the public author-facing API — exported with\n * a `__` prefix so the runtime can reach it across the shared module instance.\n */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * NOT part of the public author-facing API — exported with a `__` prefix for\n * the runtime and the singleton Proxies. */\nexport function __getRuntime(): RuntimeServices {\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 __setRuntime).\",\n );\n }\n return runtime;\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/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +\n * `query`/`transaction`. For a typed `.tables.<name>` API, wrap with\n * {@link typedDatabase}. */\nexport const Database: DBClient = makeServiceProxy(\"Database\");\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/** Object storage client (buckets, signed URLs). */\nexport const Storage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n/** Background job queue. */\nexport const Queue: QueueClient = makeServiceProxy(\"Queue\");\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/** Feature flags. */\nexport const Flags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Type the `Database` singleton against a `defineSchema()` result, returning a\n * facade with a typed `.tables.<name>.insert(...)` API alongside the raw\n * `query`/`transaction` ops.\n *\n * const Db = typedDatabase(schema);\n * const todo = await Db.tables.todos.insert({ title: \"x\" });\n *\n * This is per-endpoint (not global module augmentation), so one endpoint's\n * tables never leak into another's `Database` type.\n */\nexport function typedDatabase<TSchema extends SchemaDef>(\n schema: TSchema,\n): TypedDB<TSchema> & DBClient {\n // makeTypedDB wraps the raw DBClient with the typed `.tables` facade (and a\n // typed `transaction`). The full `& DBClient` surface also needs the raw ops\n // (query/insert/update/delete/findById/findMany), which we delegate straight\n // to the `Database` singleton — every call goes through its runtime Proxy.\n const typed = makeTypedDB(schema, Database);\n const rawOps: DBClient = {\n query: (sql, params) => Database.query(sql, params),\n insert: (table, data) => Database.insert(table, data),\n update: (table, id, data) => Database.update(table, id, data),\n delete: (table, id) => Database.delete(table, id),\n findById: (table, id) => Database.findById(table, id),\n findMany: (table, q) => Database.findMany(table, q),\n transaction: (fn) => Database.transaction(fn),\n };\n // typed.transaction (typed-tx) intentionally overrides rawOps.transaction so\n // the callback sees the typed `.tables` API.\n return Object.assign(rawOps, typed);\n}\n","import type { DBClient, TxClient } from \"../endpoint.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n // Build the op surface first (TxClient = the five DB ops + query). The\n // transaction below reuses this same `ops` object as the tx-scoped client,\n // so writes inside a transaction land in the same in-memory store and\n // tracking maps — exactly the semantics a user endpoint test expects.\n const ops: TxClient = {\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, data: Record<string, unknown>) {\n const record = { id: crypto.randomUUID(), ...data };\n if (!store.has(table)) store.set(table, []);\n store.get(table)!.push(record);\n if (!tracked.inserted.has(table)) tracked.inserted.set(table, []);\n tracked.inserted.get(table)!.push(record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n const updated = idx >= 0\n ? { ...rows[idx], ...data }\n : { id, ...data };\n if (idx >= 0) {\n rows[idx] = updated;\n }\n if (!tracked.updated.has(table)) tracked.updated.set(table, []);\n tracked.updated.get(table)!.push(updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n if (idx >= 0) rows.splice(idx, 1);\n if (!tracked.deleted.has(table)) tracked.deleted.set(table, []);\n tracked.deleted.get(table)!.push(id);\n },\n\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n async findMany(table: string, query?: Record<string, unknown>) {\n const rows = store.get(table) ?? [];\n if (!query) return rows;\n return rows.filter((row) =>\n Object.entries(query).every(([key, val]) => row[key] === val),\n );\n },\n };\n\n return {\n ...ops,\n\n transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T> {\n return fn(ops);\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n}\n","import type {\n CacheClient,\n ClientInfo,\n Logger,\n PBRequest,\n PalbaseModuleClients,\n QueueClient,\n} from \"../endpoint.js\";\nimport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseFlagsClient,\n PalbaseNotificationsClient,\n PalbaseAnalyticsClient,\n PalbaseLinksClient,\n PalbaseCmsClient,\n} from \"../clients.js\";\nimport type { User } from \"../types.js\";\nimport { __setRuntime } from \"../runtime.js\";\nimport { createMockDB, type MockDBClient } from \"./mock-db.js\";\n\n/** Options for creating a test context. */\nexport interface TestContextOptions<TInput = unknown> {\n user?: User | null;\n input?: TInput;\n params?: Record<string, string>;\n query?: Record<string, string>;\n headers?: Record<string, string>;\n env?: Record<string, string>;\n db?: { seed?: Record<string, Record<string, unknown>[]> };\n}\n\n/** Log entry captured by the mock logger. */\nexport interface LogEntry {\n level: \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n args: unknown[];\n}\n\n/** Test context for exercising endpoint handlers.\n *\n * Handlers now receive a {@link PBRequest} (no services attached) and reach\n * services via the PascalCase singletons (`Database`, `Log`, …). So\n * `createTestContext` does two things:\n * 1. returns a `PBRequest` (the object you pass to `handler(...)`), and\n * 2. installs mock services into the runtime via `__setRuntime`, so the\n * singletons resolve to the same mocks while the handler runs.\n *\n * For assertions and for building sibling (worker/job/hook/webhook) contexts,\n * the mock service handles are also attached here (`db`, `log`, `cache`,\n * `queue`, `env`, plus the module clients and captured `logs`). The user\n * defaults to nullable in tests (`PBRequest<TInput, false>`) so test code can\n * pass any auth shape without a cast. */\nexport interface TestContext<TInput = unknown>\n extends PBRequest<TInput, false>,\n PalbaseModuleClients {\n db: MockDBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n /** Captured log entries. */\n logs: LogEntry[];\n}\n\n/** Create a mock logger that captures entries. */\nfunction createMockLogger(logs: LogEntry[]): Logger {\n return {\n info(message: string, ...args: unknown[]) {\n logs.push({ level: \"info\", message, args });\n },\n warn(message: string, ...args: unknown[]) {\n logs.push({ level: \"warn\", message, args });\n },\n error(message: string, ...args: unknown[]) {\n logs.push({ level: \"error\", message, args });\n },\n debug(message: string, ...args: unknown[]) {\n logs.push({ level: \"debug\", message, args });\n },\n };\n}\n\n/** Create a mock in-memory cache.\n *\n * Mirrors the runtime's JSON-typed semantics (values are arbitrary JSON, not\n * just strings). getOrSet is single-process here, so it does not need the\n * distributed lock the real runtime uses — it is just get-miss → fn → set.\n * The cross-replica stampede protection is covered by the worker.js tests.\n */\nfunction createMockCache(): CacheClient {\n const store = new Map<string, unknown>();\n\n const get = async <T = unknown>(key: string): Promise<T | null> => {\n return store.has(key) ? (store.get(key) as T) : null;\n };\n const set = async (key: string, value: unknown, _ttl?: number): Promise<void> => {\n store.set(key, value);\n };\n\n return {\n get,\n set,\n async del(key: string) {\n store.delete(key);\n },\n async incr(key: string) {\n const raw = store.get(key);\n const current = typeof raw === \"number\" ? raw : parseInt(String(raw ?? \"0\"), 10);\n const next = current + 1;\n store.set(key, next);\n return next;\n },\n async getOrSet<T>(key: string, ttl: number, fn: () => Promise<T> | T): Promise<T> {\n const hit = await get<T>(key);\n if (hit !== null) {\n return hit;\n }\n const value = await fn();\n await set(key, value, ttl);\n return value;\n },\n };\n}\n\n/** Create mock Palbase module clients (Documents, Storage, …).\n *\n * Every slot throws with a descriptive error so tests that access a module\n * client surface without configuring it fail loudly rather than silently\n * returning undefined. Override individual clients on the returned context for\n * tests that need them.\n */\nfunction createMockModuleClients(): PalbaseModuleClients {\n const notImpl = (label: string): never => {\n throw new Error(\n `${label} not configured in test mock — override the matching client on the returned context`,\n );\n };\n\n const docs: PalbaseModuleClients[\"docs\"] = {\n collection: () => notImpl(\"docs.collection\"),\n doc: () => notImpl(\"docs.doc\"),\n };\n\n const auth: PalbaseAuthClient = {\n verifyUserToken: () => notImpl(\"auth.verifyUserToken\"),\n getSession: () => notImpl(\"auth.getSession\"),\n mfa: {\n enroll: () => notImpl(\"auth.mfa.enroll\"),\n verifyEnrollment: () => notImpl(\"auth.mfa.verifyEnrollment\"),\n challenge: () => notImpl(\"auth.mfa.challenge\"),\n recovery: () => notImpl(\"auth.mfa.recovery\"),\n listFactors: () => notImpl(\"auth.mfa.listFactors\"),\n removeFactor: () => notImpl(\"auth.mfa.removeFactor\"),\n regenerateRecoveryCodes: () => notImpl(\"auth.mfa.regenerateRecoveryCodes\"),\n emailEnroll: () => notImpl(\"auth.mfa.emailEnroll\"),\n emailChallenge: () => notImpl(\"auth.mfa.emailChallenge\"),\n emailVerify: () => notImpl(\"auth.mfa.emailVerify\"),\n },\n device: {\n generateChallenge: () => notImpl(\"auth.device.generateChallenge\"),\n attestAndroid: () => notImpl(\"auth.device.attestAndroid\"),\n attestiOS: () => notImpl(\"auth.device.attestiOS\"),\n bind: () => notImpl(\"auth.device.bind\"),\n list: () => notImpl(\"auth.device.list\"),\n delete: () => notImpl(\"auth.device.delete\"),\n verifyRequestSignature: () => notImpl(\"auth.device.verifyRequestSignature\"),\n getToken: () => notImpl(\"auth.device.getToken\"),\n get isActive(): never {\n return notImpl(\"auth.device.isActive\");\n },\n setCachedToken: () => notImpl(\"auth.device.setCachedToken\"),\n dispose: () => notImpl(\"auth.device.dispose\"),\n },\n };\n\n const storage: PalbaseStorageClient = {\n bucket: () => notImpl(\"storage.bucket\"),\n };\n\n const realtime: PalbaseRealtimeClient = {\n channel: () => notImpl(\"realtime.channel\"),\n removeChannel: () => notImpl(\"realtime.removeChannel\"),\n removeAllChannels: () => notImpl(\"realtime.removeAllChannels\"),\n };\n\n const functions: PalbaseFunctionsClient = {\n invoke: () => notImpl(\"functions.invoke\"),\n };\n\n const flags: PalbaseFlagsClient = {\n isEnabled: () => notImpl(\"flags.isEnabled\"),\n getVariant: () => notImpl(\"flags.getVariant\"),\n getAll: () => notImpl(\"flags.getAll\"),\n };\n\n const notifications: PalbaseNotificationsClient = {\n push: { send: () => notImpl(\"notifications.push.send\") },\n email: { send: () => notImpl(\"notifications.email.send\") },\n sms: { send: () => notImpl(\"notifications.sms.send\") },\n inbox: {\n send: () => notImpl(\"notifications.inbox.send\"),\n list: () => notImpl(\"notifications.inbox.list\"),\n unreadCount: () => notImpl(\"notifications.inbox.unreadCount\"),\n markRead: () => notImpl(\"notifications.inbox.markRead\"),\n markAllRead: () => notImpl(\"notifications.inbox.markAllRead\"),\n archive: () => notImpl(\"notifications.inbox.archive\"),\n },\n preferences: {\n get: () => notImpl(\"notifications.preferences.get\"),\n update: () => notImpl(\"notifications.preferences.update\"),\n },\n templates: {\n email: {\n list: () => notImpl(\"notifications.templates.email.list\"),\n get: () => notImpl(\"notifications.templates.email.get\"),\n create: () => notImpl(\"notifications.templates.email.create\"),\n update: () => notImpl(\"notifications.templates.email.update\"),\n delete: () => notImpl(\"notifications.templates.email.delete\"),\n },\n sms: {\n list: () => notImpl(\"notifications.templates.sms.list\"),\n get: () => notImpl(\"notifications.templates.sms.get\"),\n create: () => notImpl(\"notifications.templates.sms.create\"),\n update: () => notImpl(\"notifications.templates.sms.update\"),\n delete: () => notImpl(\"notifications.templates.sms.delete\"),\n },\n },\n registerDevice: () => notImpl(\"notifications.registerDevice\"),\n unregisterDevice: () => notImpl(\"notifications.unregisterDevice\"),\n };\n\n const analytics: PalbaseAnalyticsClient = {\n capture: () => notImpl(\"analytics.capture\"),\n identify: () => notImpl(\"analytics.identify\"),\n screen: () => notImpl(\"analytics.screen\"),\n query: {\n count: () => notImpl(\"analytics.query.count\"),\n events: () => notImpl(\"analytics.query.events\"),\n properties: () => notImpl(\"analytics.query.properties\"),\n users: () => notImpl(\"analytics.query.users\"),\n funnel: () => notImpl(\"analytics.query.funnel\"),\n retention: () => notImpl(\"analytics.query.retention\"),\n cohort: () => notImpl(\"analytics.query.cohort\"),\n },\n management: {\n overview: () => notImpl(\"analytics.management.overview\"),\n eventNames: () => notImpl(\"analytics.management.eventNames\"),\n userDetail: () => notImpl(\"analytics.management.userDetail\"),\n deleteUser: () => notImpl(\"analytics.management.deleteUser\"),\n },\n };\n\n const links: PalbaseLinksClient = {\n create: () => notImpl(\"links.create\"),\n list: () => notImpl(\"links.list\"),\n get: () => notImpl(\"links.get\"),\n update: () => notImpl(\"links.update\"),\n delete: () => notImpl(\"links.delete\"),\n analytics: () => notImpl(\"links.analytics\"),\n qrCode: () => notImpl(\"links.qrCode\"),\n match: () => notImpl(\"links.match\"),\n };\n\n const cms: PalbaseCmsClient = {\n find: () => notImpl(\"cms.find\"),\n findOne: () => notImpl(\"cms.findOne\"),\n };\n\n return {\n auth,\n storage,\n docs,\n realtime,\n functions,\n flags,\n notifications,\n analytics,\n links,\n cms,\n };\n}\n\n/** Null-by-default calling-client metadata for tests. */\nconst NULL_CLIENT_INFO: ClientInfo = {\n sdkVersion: null,\n appVersion: null,\n platform: null,\n osVersion: null,\n};\n\n/** Create a fully mocked endpoint test context.\n *\n * Returns a `PBRequest` (pass it to `handler(...)`) with the mock service\n * handles attached for assertions, and installs those mocks into the runtime\n * via `__setRuntime` so the `Database`/`Log`/… singletons resolve to them\n * while the handler runs.\n */\nexport function createTestContext<TInput = unknown>(\n options: TestContextOptions<TInput> = {},\n): TestContext<TInput> {\n const logs: LogEntry[] = [];\n const db = createMockDB();\n\n // Seed data if provided\n if (options.db?.seed) {\n for (const [table, data] of Object.entries(options.db.seed)) {\n db.seed(table, data);\n }\n }\n\n const mockQueue: QueueClient = {\n push: async (_worker: string, _payload: unknown) => ({ jobId: \"\" }),\n };\n const log = createMockLogger(logs);\n const cache = createMockCache();\n const moduleClients = createMockModuleClients();\n\n // Install the mocks so the PascalCase singletons (Database, Log, …) resolve\n // to them while the handler under test runs.\n __setRuntime({\n Database: db,\n Documents: moduleClients.docs,\n Storage: moduleClients.storage,\n Cache: cache,\n Queue: mockQueue,\n Log: log,\n Notifications: moduleClients.notifications,\n Flags: moduleClients.flags,\n });\n\n const ctx: TestContext<TInput> = {\n input: (options.input ?? {}) as TInput,\n params: options.params ?? {},\n query: options.query ?? {},\n headers: options.headers ?? {},\n user: options.user ?? null,\n client: NULL_CLIENT_INFO,\n method: \"POST\",\n file: null,\n db,\n env: options.env ?? {},\n log,\n cache,\n queue: mockQueue,\n ...moduleClients,\n // Empty errors map in tests by default. Tests that exercise an endpoint's\n // declared errors construct their own throwers; this stub satisfies the\n // PBRequest shape without forcing every test to declare `errors:`.\n errors: {},\n requestId: \"req_test_000000000000\",\n traceId: \"0\".repeat(32),\n spanId: \"0\".repeat(16),\n logs,\n };\n\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiEA,IAAI,UAAkC;AAQ/B,SAAS,aAAa,UAAiC;AAC5D,YAAU;AACZ;A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C1B,QAAM,KAAK,aAAa;AAGxB,MAAI,QAAQ,IAAI,MAAM;AACpB,eAAW,CAAC,OAAO,IAAI,KAAK,OAAO,QAAQ,QAAQ,GAAG,IAAI,GAAG;AAC3D,SAAG,KAAK,OAAO,IAAI;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,YAAyB;AAAA,IAC7B,MAAM,OAAO,SAAiB,cAAuB,EAAE,OAAO,GAAG;AAAA,EACnE;AACA,QAAM,MAAM,iBAAiB,IAAI;AACjC,QAAM,QAAQ,gBAAgB;AAC9B,QAAM,gBAAgB,wBAAwB;AAI9C,eAAa;AAAA,IACX,UAAU;AAAA,IACV,WAAW,cAAc;AAAA,IACzB,SAAS,cAAc;AAAA,IACvB,OAAO;AAAA,IACP,OAAO;AAAA,IACP,KAAK;AAAA,IACL,eAAe,cAAc;AAAA,IAC7B,OAAO,cAAc;AAAA,EACvB,CAAC;AAED,QAAM,MAA2B;AAAA,IAC/B,OAAQ,QAAQ,SAAS,CAAC;AAAA,IAC1B,QAAQ,QAAQ,UAAU,CAAC;AAAA,IAC3B,OAAO,QAAQ,SAAS,CAAC;AAAA,IACzB,SAAS,QAAQ,WAAW,CAAC;AAAA,IAC7B,MAAM,QAAQ,QAAQ;AAAA,IACtB,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN;AAAA,IACA,KAAK,QAAQ,OAAO,CAAC;AAAA,IACrB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,GAAG;AAAA;AAAA;AAAA;AAAA,IAIH,QAAQ,CAAC;AAAA,IACT,WAAW;AAAA,IACX,SAAS,IAAI,OAAO,EAAE;AAAA,IACtB,QAAQ,IAAI,OAAO,EAAE;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/test/index.ts","../../src/runtime.ts","../../src/test/mock-db.ts","../../src/test/context.ts"],"sourcesContent":["export { createTestContext } from \"./context.js\";\nexport type { TestContextOptions, TestContext, LogEntry } from \"./context.js\";\nexport { createMockDB } from \"./mock-db.js\";\nexport type { MockDBClient } from \"./mock-db.js\";\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, endpoint authors import PascalCase service singletons directly:\n *\n * import { Database, Documents, Cache } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => {\n * const row = await Database.insert(\"todos\", { title: req.input.title });\n * return row;\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 { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n CacheClient,\n QueueClient,\n Logger,\n PalbaseDocsClient,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n} from \"./clients.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport type { TypedDB } from \"./db/typed-db.js\";\nimport { makeTypedDB } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They\n * are not exposed as backend handler singletons (auth lives on the client SDK;\n * the rest are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Queue: QueueClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\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<{ runtime: RuntimeServices }>();\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/**\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/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +\n * `query`/`transaction`. For a typed `.tables.<name>` API, wrap with\n * {@link typedDatabase}. */\nexport const Database: DBClient = makeServiceProxy(\"Database\");\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/** Object storage client (buckets, signed URLs). */\nexport const Storage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n/** Background job queue. */\nexport const Queue: QueueClient = makeServiceProxy(\"Queue\");\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/** Feature flags. */\nexport const Flags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Type the `Database` singleton against a `defineSchema()` result, returning a\n * facade with a typed `.tables.<name>.insert(...)` API alongside the raw\n * `query`/`transaction` ops.\n *\n * const Db = typedDatabase(schema);\n * const todo = await Db.tables.todos.insert({ title: \"x\" });\n *\n * This is per-endpoint (not global module augmentation), so one endpoint's\n * tables never leak into another's `Database` type.\n */\nexport function typedDatabase<TSchema extends SchemaDef>(\n schema: TSchema,\n): TypedDB<TSchema> & DBClient {\n // makeTypedDB wraps the raw DBClient with the typed `.tables` facade (and a\n // typed `transaction`). The full `& DBClient` surface also needs the raw ops\n // (query/insert/update/delete/findById/findMany), which we delegate straight\n // to the `Database` singleton — every call goes through its runtime Proxy.\n const typed = makeTypedDB(schema, Database);\n const rawOps: DBClient = {\n query: (sql, params) => Database.query(sql, params),\n insert: (table, data) => Database.insert(table, data),\n update: (table, id, data) => Database.update(table, id, data),\n delete: (table, id) => Database.delete(table, id),\n findById: (table, id) => Database.findById(table, id),\n findMany: (table, q) => Database.findMany(table, q),\n transaction: (fn) => Database.transaction(fn),\n };\n // typed.transaction (typed-tx) intentionally overrides rawOps.transaction so\n // the callback sees the typed `.tables` API.\n return Object.assign(rawOps, typed);\n}\n","import type { DBClient, TxClient } from \"../endpoint.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n // Build the op surface first (TxClient = the five DB ops + query). The\n // transaction below reuses this same `ops` object as the tx-scoped client,\n // so writes inside a transaction land in the same in-memory store and\n // tracking maps — exactly the semantics a user endpoint test expects.\n const ops: TxClient = {\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, data: Record<string, unknown>) {\n const record = { id: crypto.randomUUID(), ...data };\n if (!store.has(table)) store.set(table, []);\n store.get(table)!.push(record);\n if (!tracked.inserted.has(table)) tracked.inserted.set(table, []);\n tracked.inserted.get(table)!.push(record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n const updated = idx >= 0\n ? { ...rows[idx], ...data }\n : { id, ...data };\n if (idx >= 0) {\n rows[idx] = updated;\n }\n if (!tracked.updated.has(table)) tracked.updated.set(table, []);\n tracked.updated.get(table)!.push(updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n if (idx >= 0) rows.splice(idx, 1);\n if (!tracked.deleted.has(table)) tracked.deleted.set(table, []);\n tracked.deleted.get(table)!.push(id);\n },\n\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n async findMany(table: string, query?: Record<string, unknown>) {\n const rows = store.get(table) ?? [];\n if (!query) return rows;\n return rows.filter((row) =>\n Object.entries(query).every(([key, val]) => row[key] === val),\n );\n },\n };\n\n return {\n ...ops,\n\n transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T> {\n return fn(ops);\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n}\n","import type {\n CacheClient,\n ClientInfo,\n Logger,\n PBRequest,\n PalbaseModuleClients,\n QueueClient,\n} from \"../endpoint.js\";\nimport type {\n PalbaseAuthClient,\n PalbaseStorageClient,\n PalbaseRealtimeClient,\n PalbaseFunctionsClient,\n PalbaseFlagsClient,\n PalbaseNotificationsClient,\n PalbaseAnalyticsClient,\n PalbaseLinksClient,\n PalbaseCmsClient,\n} from \"../clients.js\";\nimport type { User } from \"../types.js\";\nimport { __setRuntime } from \"../runtime.js\";\nimport { createMockDB, type MockDBClient } from \"./mock-db.js\";\n\n/** Options for creating a test context. */\nexport interface TestContextOptions<TInput = unknown> {\n user?: User | null;\n input?: TInput;\n params?: Record<string, string>;\n query?: Record<string, string>;\n headers?: Record<string, string>;\n env?: Record<string, string>;\n db?: { seed?: Record<string, Record<string, unknown>[]> };\n}\n\n/** Log entry captured by the mock logger. */\nexport interface LogEntry {\n level: \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n args: unknown[];\n}\n\n/** Test context for exercising endpoint handlers.\n *\n * Handlers now receive a {@link PBRequest} (no services attached) and reach\n * services via the PascalCase singletons (`Database`, `Log`, …). So\n * `createTestContext` does two things:\n * 1. returns a `PBRequest` (the object you pass to `handler(...)`), and\n * 2. installs mock services into the runtime via `__setRuntime`, so the\n * singletons resolve to the same mocks while the handler runs.\n *\n * For assertions and for building sibling (worker/job/hook/webhook) contexts,\n * the mock service handles are also attached here (`db`, `log`, `cache`,\n * `queue`, `env`, plus the module clients and captured `logs`). The user\n * defaults to nullable in tests (`PBRequest<TInput, false>`) so test code can\n * pass any auth shape without a cast. */\nexport interface TestContext<TInput = unknown>\n extends PBRequest<TInput, false>,\n PalbaseModuleClients {\n db: MockDBClient;\n env: Record<string, string>;\n log: Logger;\n cache: CacheClient;\n queue: QueueClient;\n /** Captured log entries. */\n logs: LogEntry[];\n}\n\n/** Create a mock logger that captures entries. */\nfunction createMockLogger(logs: LogEntry[]): Logger {\n return {\n info(message: string, ...args: unknown[]) {\n logs.push({ level: \"info\", message, args });\n },\n warn(message: string, ...args: unknown[]) {\n logs.push({ level: \"warn\", message, args });\n },\n error(message: string, ...args: unknown[]) {\n logs.push({ level: \"error\", message, args });\n },\n debug(message: string, ...args: unknown[]) {\n logs.push({ level: \"debug\", message, args });\n },\n };\n}\n\n/** Create a mock in-memory cache.\n *\n * Mirrors the runtime's JSON-typed semantics (values are arbitrary JSON, not\n * just strings). getOrSet is single-process here, so it does not need the\n * distributed lock the real runtime uses — it is just get-miss → fn → set.\n * The cross-replica stampede protection is covered by the worker.js tests.\n */\nfunction createMockCache(): CacheClient {\n const store = new Map<string, unknown>();\n\n const get = async <T = unknown>(key: string): Promise<T | null> => {\n return store.has(key) ? (store.get(key) as T) : null;\n };\n const set = async (key: string, value: unknown, _ttl?: number): Promise<void> => {\n store.set(key, value);\n };\n\n return {\n get,\n set,\n async del(key: string) {\n store.delete(key);\n },\n async incr(key: string) {\n const raw = store.get(key);\n const current = typeof raw === \"number\" ? raw : parseInt(String(raw ?? \"0\"), 10);\n const next = current + 1;\n store.set(key, next);\n return next;\n },\n async getOrSet<T>(key: string, ttl: number, fn: () => Promise<T> | T): Promise<T> {\n const hit = await get<T>(key);\n if (hit !== null) {\n return hit;\n }\n const value = await fn();\n await set(key, value, ttl);\n return value;\n },\n };\n}\n\n/** Create mock Palbase module clients (Documents, Storage, …).\n *\n * Every slot throws with a descriptive error so tests that access a module\n * client surface without configuring it fail loudly rather than silently\n * returning undefined. Override individual clients on the returned context for\n * tests that need them.\n */\nfunction createMockModuleClients(): PalbaseModuleClients {\n const notImpl = (label: string): never => {\n throw new Error(\n `${label} not configured in test mock — override the matching client on the returned context`,\n );\n };\n\n const docs: PalbaseModuleClients[\"docs\"] = {\n collection: () => notImpl(\"docs.collection\"),\n doc: () => notImpl(\"docs.doc\"),\n };\n\n const auth: PalbaseAuthClient = {\n verifyUserToken: () => notImpl(\"auth.verifyUserToken\"),\n getSession: () => notImpl(\"auth.getSession\"),\n mfa: {\n enroll: () => notImpl(\"auth.mfa.enroll\"),\n verifyEnrollment: () => notImpl(\"auth.mfa.verifyEnrollment\"),\n challenge: () => notImpl(\"auth.mfa.challenge\"),\n recovery: () => notImpl(\"auth.mfa.recovery\"),\n listFactors: () => notImpl(\"auth.mfa.listFactors\"),\n removeFactor: () => notImpl(\"auth.mfa.removeFactor\"),\n regenerateRecoveryCodes: () => notImpl(\"auth.mfa.regenerateRecoveryCodes\"),\n emailEnroll: () => notImpl(\"auth.mfa.emailEnroll\"),\n emailChallenge: () => notImpl(\"auth.mfa.emailChallenge\"),\n emailVerify: () => notImpl(\"auth.mfa.emailVerify\"),\n },\n device: {\n generateChallenge: () => notImpl(\"auth.device.generateChallenge\"),\n attestAndroid: () => notImpl(\"auth.device.attestAndroid\"),\n attestiOS: () => notImpl(\"auth.device.attestiOS\"),\n bind: () => notImpl(\"auth.device.bind\"),\n list: () => notImpl(\"auth.device.list\"),\n delete: () => notImpl(\"auth.device.delete\"),\n verifyRequestSignature: () => notImpl(\"auth.device.verifyRequestSignature\"),\n getToken: () => notImpl(\"auth.device.getToken\"),\n get isActive(): never {\n return notImpl(\"auth.device.isActive\");\n },\n setCachedToken: () => notImpl(\"auth.device.setCachedToken\"),\n dispose: () => notImpl(\"auth.device.dispose\"),\n },\n };\n\n const storage: PalbaseStorageClient = {\n bucket: () => notImpl(\"storage.bucket\"),\n };\n\n const realtime: PalbaseRealtimeClient = {\n channel: () => notImpl(\"realtime.channel\"),\n removeChannel: () => notImpl(\"realtime.removeChannel\"),\n removeAllChannels: () => notImpl(\"realtime.removeAllChannels\"),\n };\n\n const functions: PalbaseFunctionsClient = {\n invoke: () => notImpl(\"functions.invoke\"),\n };\n\n const flags: PalbaseFlagsClient = {\n isEnabled: () => notImpl(\"flags.isEnabled\"),\n getVariant: () => notImpl(\"flags.getVariant\"),\n getAll: () => notImpl(\"flags.getAll\"),\n };\n\n const notifications: PalbaseNotificationsClient = {\n push: { send: () => notImpl(\"notifications.push.send\") },\n email: { send: () => notImpl(\"notifications.email.send\") },\n sms: { send: () => notImpl(\"notifications.sms.send\") },\n inbox: {\n send: () => notImpl(\"notifications.inbox.send\"),\n list: () => notImpl(\"notifications.inbox.list\"),\n unreadCount: () => notImpl(\"notifications.inbox.unreadCount\"),\n markRead: () => notImpl(\"notifications.inbox.markRead\"),\n markAllRead: () => notImpl(\"notifications.inbox.markAllRead\"),\n archive: () => notImpl(\"notifications.inbox.archive\"),\n },\n preferences: {\n get: () => notImpl(\"notifications.preferences.get\"),\n update: () => notImpl(\"notifications.preferences.update\"),\n },\n templates: {\n email: {\n list: () => notImpl(\"notifications.templates.email.list\"),\n get: () => notImpl(\"notifications.templates.email.get\"),\n create: () => notImpl(\"notifications.templates.email.create\"),\n update: () => notImpl(\"notifications.templates.email.update\"),\n delete: () => notImpl(\"notifications.templates.email.delete\"),\n },\n sms: {\n list: () => notImpl(\"notifications.templates.sms.list\"),\n get: () => notImpl(\"notifications.templates.sms.get\"),\n create: () => notImpl(\"notifications.templates.sms.create\"),\n update: () => notImpl(\"notifications.templates.sms.update\"),\n delete: () => notImpl(\"notifications.templates.sms.delete\"),\n },\n },\n registerDevice: () => notImpl(\"notifications.registerDevice\"),\n unregisterDevice: () => notImpl(\"notifications.unregisterDevice\"),\n };\n\n const analytics: PalbaseAnalyticsClient = {\n capture: () => notImpl(\"analytics.capture\"),\n identify: () => notImpl(\"analytics.identify\"),\n screen: () => notImpl(\"analytics.screen\"),\n query: {\n count: () => notImpl(\"analytics.query.count\"),\n events: () => notImpl(\"analytics.query.events\"),\n properties: () => notImpl(\"analytics.query.properties\"),\n users: () => notImpl(\"analytics.query.users\"),\n funnel: () => notImpl(\"analytics.query.funnel\"),\n retention: () => notImpl(\"analytics.query.retention\"),\n cohort: () => notImpl(\"analytics.query.cohort\"),\n },\n management: {\n overview: () => notImpl(\"analytics.management.overview\"),\n eventNames: () => notImpl(\"analytics.management.eventNames\"),\n userDetail: () => notImpl(\"analytics.management.userDetail\"),\n deleteUser: () => notImpl(\"analytics.management.deleteUser\"),\n },\n };\n\n const links: PalbaseLinksClient = {\n create: () => notImpl(\"links.create\"),\n list: () => notImpl(\"links.list\"),\n get: () => notImpl(\"links.get\"),\n update: () => notImpl(\"links.update\"),\n delete: () => notImpl(\"links.delete\"),\n analytics: () => notImpl(\"links.analytics\"),\n qrCode: () => notImpl(\"links.qrCode\"),\n match: () => notImpl(\"links.match\"),\n };\n\n const cms: PalbaseCmsClient = {\n find: () => notImpl(\"cms.find\"),\n findOne: () => notImpl(\"cms.findOne\"),\n };\n\n return {\n auth,\n storage,\n docs,\n realtime,\n functions,\n flags,\n notifications,\n analytics,\n links,\n cms,\n };\n}\n\n/** Null-by-default calling-client metadata for tests. */\nconst NULL_CLIENT_INFO: ClientInfo = {\n sdkVersion: null,\n appVersion: null,\n platform: null,\n osVersion: null,\n};\n\n/** Create a fully mocked endpoint test context.\n *\n * Returns a `PBRequest` (pass it to `handler(...)`) with the mock service\n * handles attached for assertions, and installs those mocks into the runtime\n * via `__setRuntime` so the `Database`/`Log`/… singletons resolve to them\n * while the handler runs.\n */\nexport function createTestContext<TInput = unknown>(\n options: TestContextOptions<TInput> = {},\n): TestContext<TInput> {\n const logs: LogEntry[] = [];\n const db = createMockDB();\n\n // Seed data if provided\n if (options.db?.seed) {\n for (const [table, data] of Object.entries(options.db.seed)) {\n db.seed(table, data);\n }\n }\n\n const mockQueue: QueueClient = {\n push: async (_worker: string, _payload: unknown) => ({ jobId: \"\" }),\n };\n const log = createMockLogger(logs);\n const cache = createMockCache();\n const moduleClients = createMockModuleClients();\n\n // Install the mocks so the PascalCase singletons (Database, Log, …) resolve\n // to them while the handler under test runs.\n __setRuntime({\n Database: db,\n Documents: moduleClients.docs,\n Storage: moduleClients.storage,\n Cache: cache,\n Queue: mockQueue,\n Log: log,\n Notifications: moduleClients.notifications,\n Flags: moduleClients.flags,\n });\n\n const ctx: TestContext<TInput> = {\n input: (options.input ?? {}) as TInput,\n params: options.params ?? {},\n query: options.query ?? {},\n headers: options.headers ?? {},\n user: options.user ?? null,\n client: NULL_CLIENT_INFO,\n method: \"POST\",\n file: null,\n db,\n env: options.env ?? {},\n log,\n cache,\n queue: mockQueue,\n ...moduleClients,\n // Empty errors map in tests by default. Tests that exercise an endpoint's\n // declared errors construct their own throwers; this stub satisfies the\n // PBRequest shape without forcing every test to declare `errors:`.\n errors: {},\n requestId: \"req_test_000000000000\",\n traceId: \"0\".repeat(32),\n spanId: \"0\".repeat(16),\n logs,\n };\n\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0CA,8BAAkC;AA2C3B,IAAM,eAAe,IAAI,0CAAgD;AAKhF,IAAI,UAAkC;AAO/B,SAAS,aAAa,UAAiC;AAC5D,YAAU;AACZ;AAeO,SAAS,eAAgC;AAC9C,QAAM,SAAS,aAAa,SAAS;AACrC,MAAI,OAAQ,QAAO,OAAO;AAC1B,MAAI,YAAY,MAAM;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AACA,SAAO;AACT;AAWA,SAAS,iBAAkD,KAA4B;AACrF,QAAM,UAA4C;AAAA,IAChD,IAAI,SAAS,MAAM,UAAU;AAC3B,YAAM,SAAS,aAAa,EAAE,GAAG;AACjC,YAAM,QAAQ,QAAQ,IAAI,QAAkB,MAAM,QAAQ;AAG1D,aAAO,OAAO,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI;AAAA,IAC5D;AAAA,EACF;AAGA,SAAO,IAAI,MAAM,CAAC,GAAyB,OAAO;AACpD;AAKO,IAAM,WAAqB,iBAAiB,UAAU;AAGtD,IAAM,YAA+B,iBAAiB,WAAW;AAGjE,IAAM,UAAgC,iBAAiB,SAAS;AAGhE,IAAM,QAAqB,iBAAiB,OAAO;AAGnD,I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AED,QAAM,MAA2B;AAAA,IAC/B,OAAQ,QAAQ,SAAS,CAAC;AAAA,IAC1B,QAAQ,QAAQ,UAAU,CAAC;AAAA,IAC3B,OAAO,QAAQ,SAAS,CAAC;AAAA,IACzB,SAAS,QAAQ,WAAW,CAAC;AAAA,IAC7B,MAAM,QAAQ,QAAQ;AAAA,IACtB,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN;AAAA,IACA,KAAK,QAAQ,OAAO,CAAC;AAAA,IACrB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,GAAG;AAAA;AAAA;AAAA;AAAA,IAIH,QAAQ,CAAC;AAAA,IACT,WAAW;AAAA,IACX,SAAS,IAAI,OAAO,EAAE;AAAA,IACtB,QAAQ,IAAI,OAAO,EAAE;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/dist/test/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DBClient, l as PBRequest, d as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-
|
|
1
|
+
import { D as DBClient, l as PBRequest, d as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-BlcY2xNA.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import '../schema-BqfEhIC0.cjs';
|
|
4
4
|
|