@palbase/backend 2.0.2 → 4.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-EG7TTYHY.js +235 -0
- package/dist/chunk-EG7TTYHY.js.map +1 -0
- package/dist/chunk-WUQO76NW.js +101 -0
- package/dist/chunk-WUQO76NW.js.map +1 -0
- package/dist/db/env.cjs +19 -0
- package/dist/db/env.cjs.map +1 -0
- package/dist/db/env.d.cts +45 -0
- package/dist/db/env.d.ts +45 -0
- package/dist/db/env.js +1 -0
- package/dist/db/env.js.map +1 -0
- package/dist/db/index.cjs +143 -231
- package/dist/db/index.cjs.map +1 -1
- package/dist/db/index.d.cts +4 -20
- package/dist/db/index.d.ts +4 -20
- package/dist/db/index.js +13 -233
- package/dist/db/index.js.map +1 -1
- package/dist/{endpoint-Djk5L6G2.d.ts → endpoint-2d_DpASt.d.cts} +94 -96
- package/dist/{endpoint-BlcY2xNA.d.cts → endpoint-2d_DpASt.d.ts} +94 -96
- package/dist/index-DZW9CjiY.d.ts +463 -0
- package/dist/index-DzRFS3Tl.d.cts +463 -0
- package/dist/index.cjs +557 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +278 -161
- package/dist/index.d.ts +278 -161
- package/dist/index.js +343 -12
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +57 -2
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +1 -2
- package/dist/test/index.d.ts +1 -2
- package/dist/test/index.js +10 -2
- package/dist/test/index.js.map +1 -1
- package/docs/README.md +33 -12
- package/docs/background.md +19 -13
- package/docs/database.md +70 -17
- package/docs/endpoints.md +103 -79
- package/docs/errors.md +37 -31
- package/docs/events.md +25 -17
- package/docs/getting-started.md +38 -18
- package/docs/llms-full.txt +758 -267
- package/docs/llms.txt +3 -1
- package/docs/migrations.md +98 -0
- package/docs/resources.md +94 -0
- package/docs/routing.md +54 -27
- package/docs/schema.md +163 -42
- package/docs/services.md +17 -14
- package/package.json +12 -2
- package/dist/chunk-4J3F32SH.js +0 -96
- package/dist/chunk-4J3F32SH.js.map +0 -1
- package/dist/chunk-L36JLUPO.js +0 -97
- package/dist/chunk-L36JLUPO.js.map +0 -1
- package/dist/schema-BqfEhIC0.d.cts +0 -133
- package/dist/schema-BqfEhIC0.d.ts +0 -133
package/dist/test/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { D as DBClient,
|
|
1
|
+
import { D as DBClient, P as PBRequest, a as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-2d_DpASt.js';
|
|
2
2
|
import 'zod';
|
|
3
|
-
import '../schema-BqfEhIC0.js';
|
|
4
3
|
|
|
5
4
|
/** Mock DB client with tracking and seed data support. */
|
|
6
5
|
interface MockDBClient extends DBClient {
|
package/dist/test/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
__setRuntime
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-WUQO76NW.js";
|
|
4
4
|
|
|
5
5
|
// src/test/mock-db.ts
|
|
6
6
|
function createMockDB() {
|
|
@@ -52,11 +52,18 @@ function createMockDB() {
|
|
|
52
52
|
);
|
|
53
53
|
}
|
|
54
54
|
};
|
|
55
|
-
|
|
55
|
+
const client = {
|
|
56
56
|
...ops,
|
|
57
57
|
transaction(fn) {
|
|
58
58
|
return fn(ops);
|
|
59
59
|
},
|
|
60
|
+
// In tests there is no real DB role; `asService()` returns the same
|
|
61
|
+
// in-memory client so RLS-bypass code paths still hit the same store and
|
|
62
|
+
// tracking maps. The omitted `asService` matches the contract (no
|
|
63
|
+
// double-bypass), so callers can't recurse.
|
|
64
|
+
asService() {
|
|
65
|
+
return client;
|
|
66
|
+
},
|
|
60
67
|
inserted(table) {
|
|
61
68
|
return tracked.inserted.get(table) ?? [];
|
|
62
69
|
},
|
|
@@ -70,6 +77,7 @@ function createMockDB() {
|
|
|
70
77
|
store.set(table, [...data]);
|
|
71
78
|
}
|
|
72
79
|
};
|
|
80
|
+
return client;
|
|
73
81
|
}
|
|
74
82
|
|
|
75
83
|
// src/test/context.ts
|
package/dist/test/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/mock-db.ts","../../src/test/context.ts"],"sourcesContent":["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":";;;;;AAsBO,SAAS,eAA6B;AAC3C,QAAM,QAAQ,oBAAI,IAAuC;AACzD,QAAM,UAA0B;AAAA,IAC9B,UAAU,oBAAI,IAAI;AAAA,IAClB,SAAS,oBAAI,IAAI;AAAA,IACjB,SAAS,oBAAI,IAAI;AA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AAA,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/mock-db.ts","../../src/test/context.ts"],"sourcesContent":["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 const client: MockDBClient = {\n ...ops,\n\n transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T> {\n return fn(ops);\n },\n\n // In tests there is no real DB role; `asService()` returns the same\n // in-memory client so RLS-bypass code paths still hit the same store and\n // tracking maps. The omitted `asService` matches the contract (no\n // double-bypass), so callers can't recurse.\n asService(): Omit<DBClient, \"asService\"> {\n return client;\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 return client;\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\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c;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":[]}
|
package/docs/README.md
CHANGED
|
@@ -7,25 +7,41 @@ This is **not** Express, Fastify, or a Supabase Edge Function. There is no
|
|
|
7
7
|
`app.get(...)`, no manual route registration, no `import express`. You export
|
|
8
8
|
definitions; the runtime wires them up.
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## Mental model (important)
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|------------------|------------------|--------------------|
|
|
14
|
-
| **Endpoints** (`endpoints/**`) | a single `req` ([PBRequest](./endpoints.md)) | imported singletons: `import { Database } from "@palbase/backend"` |
|
|
15
|
-
| **Workers, Jobs, Hooks, Webhooks** | a `ctx` object | `ctx.db`, `ctx.log`, `ctx.cache`, `ctx.queue` |
|
|
12
|
+
Every handler type imports service singletons the same way:
|
|
16
13
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
```ts
|
|
15
|
+
import { Database, Log, Cache, Queue } from "@palbase/backend";
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The **only difference** is the trigger argument:
|
|
19
|
+
|
|
20
|
+
| You are writing… | Handler signature | Trigger arg |
|
|
21
|
+
|------------------|-------------------|-------------|
|
|
22
|
+
| **Endpoints** (`controllers/` class controllers) | method `(…params)` | parameter decorators `@Body`/`@Query`/`@Param`/`@User`/… — [endpoints.md](./endpoints.md) |
|
|
23
|
+
| **Workers** (`workers/**`) | `(payload, meta)` | typed payload + `WorkerMeta` |
|
|
24
|
+
| **Jobs** (`jobs/**`) | `(meta)` | `JobMeta` |
|
|
25
|
+
| **Hooks** (`hooks/**`) | `(event, meta)` | typed event + `HookMeta` |
|
|
26
|
+
| **Webhooks** (`webhooks/**`) | `(event, meta)` | typed event + `WebhookMeta` |
|
|
27
|
+
| **Middleware** (`middleware/**`) | `(ctx, next)` | `MiddlewareContext` — the **one exception** |
|
|
28
|
+
|
|
29
|
+
`meta` carries non-service data: `env` (branch env vars), `projectId`,
|
|
30
|
+
`environmentId`, and for workers/webhooks `requestId`. Services always come from
|
|
31
|
+
the imported singletons — not from `ctx` or any argument.
|
|
20
32
|
|
|
21
33
|
## Project shape
|
|
22
34
|
|
|
23
35
|
```
|
|
24
36
|
my-backend/
|
|
25
37
|
├── package.json # depends on @palbase/backend
|
|
26
|
-
├──
|
|
27
|
-
│ └── hello
|
|
38
|
+
├── controllers/ # @Controller classes: @Get/@Post methods (mount the API)
|
|
39
|
+
│ └── hello.controller.ts # @Controller("/hello") + @Get example
|
|
40
|
+
├── models/<ctrl>/<ep>.ts # zod schemas, folder per controller, file per endpoint
|
|
41
|
+
│ └── hello/greet.ts # GreetQuery + HelloResponse (zod value + z.infer type)
|
|
42
|
+
├── services/ # plain classes/singletons your controllers call
|
|
28
43
|
├── db/schema.ts # table definitions (optional, enables typed DB)
|
|
44
|
+
├── db/migrations/ # explicit SQL migrations for type changes (optional)
|
|
29
45
|
├── workers/ # background job handlers (optional)
|
|
30
46
|
├── jobs/ # cron-scheduled jobs (optional)
|
|
31
47
|
├── hooks/ # auth/storage/document event hooks (optional)
|
|
@@ -33,15 +49,20 @@ my-backend/
|
|
|
33
49
|
└── middleware/ # cross-cutting request middleware (optional)
|
|
34
50
|
```
|
|
35
51
|
|
|
52
|
+
HTTP endpoints are **not** file-path routed. You author a class controller
|
|
53
|
+
(`@Controller("/base")` with `@Get`/`@Post`/… methods); putting it under
|
|
54
|
+
`controllers/` mounts it. See [routing.md](./routing.md).
|
|
55
|
+
|
|
36
56
|
## Documentation
|
|
37
57
|
|
|
38
58
|
| Topic | File |
|
|
39
59
|
|-------|------|
|
|
40
60
|
| Getting started | [getting-started.md](./getting-started.md) |
|
|
41
|
-
|
|
|
42
|
-
| Endpoints
|
|
61
|
+
| Routing (class controllers) | [routing.md](./routing.md) |
|
|
62
|
+
| Endpoints (decorators) | [endpoints.md](./endpoints.md) |
|
|
43
63
|
| Database & transactions | [database.md](./database.md) |
|
|
44
64
|
| Schema & typed DB | [schema.md](./schema.md) |
|
|
65
|
+
| Migrations (additive vs type-change + drift-gate) | [migrations.md](./migrations.md) |
|
|
45
66
|
| Services (Cache, Queue, Storage, …) | [services.md](./services.md) |
|
|
46
67
|
| Errors | [errors.md](./errors.md) |
|
|
47
68
|
| Workers & Jobs | [background.md](./background.md) |
|
package/docs/background.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# Workers & Jobs
|
|
2
2
|
|
|
3
|
-
Workers and jobs use the
|
|
4
|
-
|
|
5
|
-
**not** receive a `req
|
|
6
|
-
|
|
3
|
+
Workers and jobs use the **singleton model** — the same imported service
|
|
4
|
+
singletons as endpoints (`import { Database, Log } from "@palbase/backend"`).
|
|
5
|
+
They do **not** receive a `req`. Instead, a small `meta` argument carries the
|
|
6
|
+
non-service data (`env`, `user`, correlation ids).
|
|
7
7
|
|
|
8
8
|
## Workers (queue consumers)
|
|
9
9
|
|
|
@@ -12,7 +12,7 @@ A worker processes jobs pushed via `Queue.push(name, payload)`. File lives under
|
|
|
12
12
|
|
|
13
13
|
```ts
|
|
14
14
|
// workers/process-order.ts
|
|
15
|
-
import { defineWorker } from "@palbase/backend";
|
|
15
|
+
import { defineWorker, Database, Log } from "@palbase/backend";
|
|
16
16
|
|
|
17
17
|
interface OrderPayload { orderId: string; amount: number; }
|
|
18
18
|
|
|
@@ -21,13 +21,16 @@ export default defineWorker<OrderPayload>({
|
|
|
21
21
|
retry: 5, // optional, default 3
|
|
22
22
|
timeout: 60, // optional, seconds
|
|
23
23
|
backoff: "exponential", // "exponential" | "linear" | "fixed", default exponential
|
|
24
|
-
handler: async (
|
|
25
|
-
|
|
26
|
-
await
|
|
24
|
+
handler: async (payload, meta) => {
|
|
25
|
+
Log.info(`processing ${payload.orderId} (env ${meta.environmentId})`);
|
|
26
|
+
await Database.update("orders", payload.orderId, { status: "processed" });
|
|
27
27
|
},
|
|
28
28
|
});
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
+
`meta` shape: `{ env, user, requestId, projectId, environmentId }`. Branch env
|
|
32
|
+
vars are in `meta.env`; services come from the imported singletons.
|
|
33
|
+
|
|
31
34
|
Enqueue from an endpoint:
|
|
32
35
|
|
|
33
36
|
```ts
|
|
@@ -41,16 +44,19 @@ A job runs on a cron schedule. File lives under `jobs/`.
|
|
|
41
44
|
|
|
42
45
|
```ts
|
|
43
46
|
// jobs/cleanup.ts
|
|
44
|
-
import { defineJob } from "@palbase/backend";
|
|
47
|
+
import { defineJob, Database, Log } from "@palbase/backend";
|
|
45
48
|
|
|
46
49
|
export default defineJob({
|
|
47
50
|
name: "cleanup-expired",
|
|
48
51
|
schedule: "0 3 * * *", // standard cron
|
|
49
52
|
timeout: 120, // optional, seconds
|
|
50
|
-
handler: async (
|
|
51
|
-
const expired = await
|
|
52
|
-
for (const s of expired) await
|
|
53
|
-
|
|
53
|
+
handler: async (meta) => {
|
|
54
|
+
const expired = await Database.findMany("sessions", { expired: true });
|
|
55
|
+
for (const s of expired) await Database.delete("sessions", s.id as string);
|
|
56
|
+
Log.info(`cleaned ${expired.length} sessions in ${meta.projectId}`);
|
|
54
57
|
},
|
|
55
58
|
});
|
|
56
59
|
```
|
|
60
|
+
|
|
61
|
+
`meta` shape: `{ env, projectId, environmentId }`. No `user` (jobs are
|
|
62
|
+
system-initiated).
|
package/docs/database.md
CHANGED
|
@@ -1,16 +1,37 @@
|
|
|
1
1
|
# Database
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Import the `Database` singleton in every handler type — endpoints, workers,
|
|
4
|
+
jobs, hooks, and webhooks all use the same import:
|
|
4
5
|
|
|
5
6
|
```ts
|
|
6
7
|
import { Database } from "@palbase/backend";
|
|
7
8
|
```
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
[events.md](./events.md)).
|
|
10
|
+
Only **middleware** still uses `ctx.db` (see [background.md](./background.md)
|
|
11
|
+
and [events.md](./events.md) for worker/job/hook/webhook examples).
|
|
12
12
|
|
|
13
|
-
##
|
|
13
|
+
## Typed by default — `Database.tables`
|
|
14
|
+
|
|
15
|
+
When you declare `db/schema.ts`, `Database.tables.<name>` is typed everywhere
|
|
16
|
+
with no import and no generic. `insert` demands the right columns; rows come
|
|
17
|
+
back typed; nullable columns are `T | null`. This is the path you should use:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const todo = await Database.tables.todos.insert({ title: "buy milk" });
|
|
21
|
+
todo.id; // string ✓
|
|
22
|
+
todo.done; // boolean ✓
|
|
23
|
+
const open = await Database.tables.todos.findMany({ done: false });
|
|
24
|
+
await Database.tables.todos.update(todo.id, { done: true });
|
|
25
|
+
await Database.tables.todos.delete(todo.id);
|
|
26
|
+
// todo.nope ← compile error
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
See [schema.md](./schema.md) for the full typed-table surface.
|
|
30
|
+
|
|
31
|
+
## Raw string-keyed operations
|
|
32
|
+
|
|
33
|
+
For dynamic table names or read-only SQL, the string-keyed ops are still
|
|
34
|
+
available:
|
|
14
35
|
|
|
15
36
|
| Method | Returns |
|
|
16
37
|
|--------|---------|
|
|
@@ -22,14 +43,6 @@ reached via the context object (see [background.md](./background.md) and
|
|
|
22
43
|
| `Database.query(sql, params?)` | rows from a read-only SQL query (runs in a READ ONLY transaction) |
|
|
23
44
|
| `Database.transaction(fn)` | runs `fn(tx)` in a transaction |
|
|
24
45
|
|
|
25
|
-
```ts
|
|
26
|
-
const row = await Database.insert("todos", { title: "buy milk", done: false });
|
|
27
|
-
const one = await Database.findById("todos", row.id as string);
|
|
28
|
-
const open = await Database.findMany("todos", { done: false });
|
|
29
|
-
await Database.update("todos", row.id as string, { done: true });
|
|
30
|
-
await Database.delete("todos", row.id as string);
|
|
31
|
-
```
|
|
32
|
-
|
|
33
46
|
`findMany`'s `query` is an equality filter: keys are ANDed together. For
|
|
34
47
|
anything richer (ranges, ordering, joins) use `Database.query`.
|
|
35
48
|
|
|
@@ -50,11 +63,51 @@ transaction). Returning commits; throwing rolls back.
|
|
|
50
63
|
|
|
51
64
|
```ts
|
|
52
65
|
await Database.transaction(async (tx) => {
|
|
53
|
-
const order = await tx.insert(
|
|
54
|
-
await tx.insert(
|
|
66
|
+
const order = await tx.tables.orders.insert({ amount: 1000, status: "pending" });
|
|
67
|
+
await tx.tables.order_items.insert({ order_id: order.id, sku: "ABC" });
|
|
55
68
|
// throw here → both inserts roll back
|
|
56
69
|
});
|
|
57
70
|
```
|
|
58
71
|
|
|
59
|
-
|
|
60
|
-
[schema.md](./schema.md).
|
|
72
|
+
The `tx` carries the same typed `tx.tables.<name>` API as `Database.tables`
|
|
73
|
+
(no nested transaction). See [schema.md](./schema.md) for the full surface.
|
|
74
|
+
|
|
75
|
+
## Bypassing RLS — `Database.asService()`
|
|
76
|
+
|
|
77
|
+
When a table has [Row-Level Security](./schema.md#row-level-security-rls)
|
|
78
|
+
policies, every `Database.*` call runs as the request's verified user
|
|
79
|
+
(`authenticated`), so the database filters out rows the user's policies don't
|
|
80
|
+
allow. That is the secure default.
|
|
81
|
+
|
|
82
|
+
Sometimes you need to read or write **across all users** — an admin endpoint, a
|
|
83
|
+
background job that fans out notifications, a cleanup task. For that, call
|
|
84
|
+
`Database.asService()`. It returns a sibling client that runs as the
|
|
85
|
+
`service_role` (which has `BYPASSRLS`), exposing the exact same surface —
|
|
86
|
+
`tables`, the raw string ops, and `transaction`:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { Database } from "@palbase/backend";
|
|
90
|
+
|
|
91
|
+
// RLS-enforced (default): only the caller's own rows.
|
|
92
|
+
const mine = await Database.tables.todos.findMany({});
|
|
93
|
+
|
|
94
|
+
// Service-role bypass: every user's rows. Explicit and greppable.
|
|
95
|
+
const all = await Database.asService().tables.todos.findMany({});
|
|
96
|
+
const rows = await Database.asService().query("SELECT count(*) FROM todos");
|
|
97
|
+
|
|
98
|
+
// A service-role transaction (the role is fixed for the whole tx):
|
|
99
|
+
await Database.asService().transaction(async (tx) => {
|
|
100
|
+
await tx.tables.todos.update(id, { done: true });
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Guidelines:
|
|
105
|
+
|
|
106
|
+
- **Be explicit.** Prefer the default `Database.*` and reach for `asService()`
|
|
107
|
+
only where you genuinely need cross-user access. It is intentionally easy to
|
|
108
|
+
grep for in review.
|
|
109
|
+
- **No double-bypass / no nesting.** The sibling does not re-expose
|
|
110
|
+
`asService()`, and `tx` never exposes it — a transaction's role is fixed when
|
|
111
|
+
it begins. Use `Database.transaction(...)` for an authenticated tx and
|
|
112
|
+
`Database.asService().transaction(...)` for a service-role tx; you cannot mix
|
|
113
|
+
enforced and bypassed ops inside one interactive transaction.
|
package/docs/endpoints.md
CHANGED
|
@@ -1,86 +1,126 @@
|
|
|
1
1
|
# Endpoints
|
|
2
2
|
|
|
3
|
-
An endpoint is
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
An endpoint is a **method on a class controller** — a class decorated with
|
|
4
|
+
`@Controller(basePath)` whose methods are decorated with `@Get`/`@Post`/`@Put`/
|
|
5
|
+
`@Patch`/`@Delete`. Controller files live under `controllers/` and are mounted
|
|
6
|
+
automatically (see [routing.md](./routing.md)). Request input + context are
|
|
7
|
+
injected into the method via **parameter decorators** (`@Body`/`@Query`/`@Param`/
|
|
8
|
+
`@User`/…), each piece direct — no `req` god-object. Services are reached via the
|
|
9
|
+
imported singletons (see [services.md](./services.md)).
|
|
6
10
|
|
|
7
|
-
##
|
|
11
|
+
## A controller
|
|
8
12
|
|
|
9
13
|
```ts
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
// controllers/rooms.controller.ts
|
|
15
|
+
import { Controller, Get, Post, Returns, Body, Param, User, NotFound, Database } from "@palbase/backend";
|
|
16
|
+
import type { UserT } from "@palbase/backend";
|
|
17
|
+
import { CreateRoomBody } from "../models/rooms/create.js";
|
|
18
|
+
import { RoomSchema } from "../models/rooms/shared.js";
|
|
19
|
+
|
|
20
|
+
@Controller("/rooms")
|
|
21
|
+
export default class RoomsController {
|
|
22
|
+
@Post("")
|
|
23
|
+
@Returns(RoomSchema)
|
|
24
|
+
async create(@Body(CreateRoomBody) body: CreateRoomBody, @User() user: UserT): Promise<RoomSchema> {
|
|
25
|
+
const room = await Database.insert("rooms", { name: body.name, capacity: body.capacity ?? null });
|
|
26
|
+
return { id: room.id as string, name: room.name as string, capacity: (room.capacity as number) ?? null };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@Get("/{id}")
|
|
30
|
+
@Returns(RoomSchema)
|
|
31
|
+
async getOne(@Param("id") id: string): Promise<RoomSchema> {
|
|
32
|
+
const room = await Database.findById("rooms", id);
|
|
33
|
+
if (!room) throw new NotFound("Room does not exist", "room_not_found");
|
|
34
|
+
return { id: room.id as string, name: room.name as string, capacity: (room.capacity as number) ?? null };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Method decorators
|
|
40
|
+
|
|
41
|
+
`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete` take `(subpath, options?)`:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
interface RouteOptions {
|
|
45
|
+
auth?: boolean | { required?: boolean; role?: string }; // overrides controller default
|
|
46
|
+
rateLimit?: { max: number; window: number }; // optional, per route
|
|
47
|
+
}
|
|
20
48
|
```
|
|
21
49
|
|
|
22
|
-
|
|
50
|
+
Input and output are NOT method-decorator options: input comes from the
|
|
51
|
+
parameter decorators, output from the method's return type. The method decorator
|
|
52
|
+
only carries route concerns (path, auth, rateLimit).
|
|
53
|
+
|
|
54
|
+
## Parameter decorators
|
|
55
|
+
|
|
56
|
+
| Decorator | Injects | Typed by | OpenAPI |
|
|
57
|
+
|---|---|---|---|
|
|
58
|
+
| `@Body(schema)` | request body | `: T` (`z.infer<schema>`, same name) | requestBody |
|
|
59
|
+
| `@Query(schema)` | query params | `: T` | query parameters |
|
|
60
|
+
| `@Param("id")` | one path param | `: string` | path parameter |
|
|
61
|
+
| `@Headers(schema?)` | request headers | `Record<string,string>` (+ typed with schema) | header parameters |
|
|
62
|
+
| `@User()` | authenticated user | `: UserT` | — (from token) |
|
|
63
|
+
| `@OptionalUser()` | user, possibly anon | `: UserT \| null` | — |
|
|
64
|
+
| `@Client()` | parsed client info | `: ClientInfo` | — |
|
|
65
|
+
| `@RequestId()` / `@TraceId()` | correlation ids | `: string` | — |
|
|
66
|
+
| `@Req()` | raw request (escape hatch) | `: PBRequest` | — |
|
|
67
|
+
|
|
68
|
+
`@Body`/`@Query`/`@Headers` take a zod schema (validation + codegen source); the
|
|
69
|
+
developer writes the matching type annotation (same name). `UserT` is the
|
|
70
|
+
authenticated-user type (`{ id: string; email?: string; role: string; metadata:
|
|
71
|
+
Record<string, unknown> }`) — exported under the alias `UserT` because the value
|
|
72
|
+
name `User` is the `@User()` decorator.
|
|
23
73
|
|
|
24
|
-
|
|
25
|
-
|-------|------|-------|
|
|
26
|
-
| `req.input` | inferred from `input` schema | request body for POST/PUT/PATCH; `{}` otherwise |
|
|
27
|
-
| `req.params` | `Record<string,string>` | route params, e.g. `req.params.id` |
|
|
28
|
-
| `req.query` | `Record<string,string>` | parsed query string |
|
|
29
|
-
| `req.headers` | `Record<string,string>` | lowercase keys |
|
|
30
|
-
| `req.user` | `User` when authenticated; `User \| null` when `auth` is omitted or `required: false` | see Auth below |
|
|
31
|
-
| `req.client` | `ClientInfo` | calling SDK/app/platform/os version (all nullable) |
|
|
32
|
-
| `req.file` | `FileContext \| null` | uploaded file, if any |
|
|
33
|
-
| `req.method` | `string` | the HTTP method |
|
|
34
|
-
| `req.requestId` / `req.traceId` / `req.spanId` | `string` | correlation ids |
|
|
35
|
-
| `req.errors` | typed throwers | present when `errors` is declared (see errors.md) |
|
|
74
|
+
## Output = return type
|
|
36
75
|
|
|
37
|
-
|
|
76
|
+
The success response is the method's RETURN TYPE. Pair it with `@Returns(schema)`
|
|
77
|
+
so the zod value drives the OpenAPI 200 response (the type annotation drives
|
|
78
|
+
compile-time checking; the zod value is lossless for codegen). A method that
|
|
79
|
+
returns nothing annotates `: void`.
|
|
38
80
|
|
|
39
|
-
## Auth
|
|
81
|
+
## Auth — controller default + route override cascade
|
|
82
|
+
|
|
83
|
+
**Secure by default:** a route requires authentication UNLESS it explicitly opts
|
|
84
|
+
out. Resolution order (most specific wins):
|
|
85
|
+
|
|
86
|
+
1. Route-level `@Post("", { auth })` — wins if present.
|
|
87
|
+
2. Controller-level `@Controller("/x", { auth })` — applies to routes without
|
|
88
|
+
their own `auth`.
|
|
89
|
+
3. Default `true` (secure-by-default).
|
|
40
90
|
|
|
41
91
|
```ts
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
92
|
+
@Controller("/public", { auth: false }) // all routes default public
|
|
93
|
+
export default class PublicController {
|
|
94
|
+
@Get("/open") open(): Info { ... } // inherits → public
|
|
95
|
+
@Get("/secret", { auth: true }) // OVERRIDES → authed
|
|
96
|
+
secret(@User() u: UserT): Secret { ... }
|
|
97
|
+
}
|
|
46
98
|
```
|
|
47
99
|
|
|
48
|
-
|
|
49
|
-
|
|
100
|
+
| effective `auth` | `@User()` type to annotate |
|
|
101
|
+
|------------------|----------------------------|
|
|
102
|
+
| required (omitted / `true` / `{ required: true }` / role-only) | `@User() u: UserT` |
|
|
103
|
+
| public (`false` / `{ required: false }`) | `@OptionalUser() u: UserT \| null` |
|
|
50
104
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
| `true` | `User` |
|
|
55
|
-
| `false` | `User \| null` |
|
|
56
|
-
| `{ required: true }` | `User` |
|
|
57
|
-
| `{ required: false }` | `User \| null` |
|
|
58
|
-
| `{ role: "admin" }` (object, no `required`) | `User` |
|
|
105
|
+
The runtime always applies the resolved effective auth; the static type you
|
|
106
|
+
annotate is best-effort (a parameter decorator cannot see the controller default
|
|
107
|
+
at the type level).
|
|
59
108
|
|
|
60
|
-
|
|
61
|
-
object with a `role` but no `required` key is treated as authenticated. When
|
|
62
|
-
`auth` is omitted, the endpoint is public and `req.user` may be null.
|
|
109
|
+
## Errors — global throw classes
|
|
63
110
|
|
|
64
|
-
|
|
111
|
+
Throw an error class anywhere (controller OR service) — no `req`, no per-route
|
|
112
|
+
map. The runtime catches it and emits the standard envelope:
|
|
65
113
|
|
|
66
114
|
```ts
|
|
67
|
-
import {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
input: z.object({ name: z.string().min(1).max(100), capacity: z.number().int().positive().optional() }),
|
|
73
|
-
output: z.object({ id: z.string(), name: z.string(), capacity: z.number().nullable() }),
|
|
74
|
-
handler: async (req) => {
|
|
75
|
-
const room = await Database.insert("rooms", {
|
|
76
|
-
name: req.input.name,
|
|
77
|
-
capacity: req.input.capacity ?? null,
|
|
78
|
-
});
|
|
79
|
-
return { id: room.id as string, name: room.name as string, capacity: (room.capacity as number) ?? null };
|
|
80
|
-
},
|
|
81
|
-
});
|
|
115
|
+
import { Conflict, NotFound, BadRequest, Unauthorized, Forbidden, TooManyRequests, PalError } from "@palbase/backend";
|
|
116
|
+
|
|
117
|
+
throw new Conflict("title taken"); // → 409
|
|
118
|
+
throw new NotFound(); // → 404 ("Not found")
|
|
119
|
+
throw new PalError(418, "teapot", "custom"); // → custom status/code
|
|
82
120
|
```
|
|
83
121
|
|
|
122
|
+
See [errors.md](./errors.md) for the full set + the wire envelope shape.
|
|
123
|
+
|
|
84
124
|
## Middleware
|
|
85
125
|
|
|
86
126
|
A middleware wraps a request. Define one in `middleware/<name>.ts`:
|
|
@@ -97,20 +137,4 @@ export default defineMiddleware(async (ctx, next) => {
|
|
|
97
137
|
```
|
|
98
138
|
|
|
99
139
|
The middleware handler receives `(ctx, next)` — call `await next()` to run the
|
|
100
|
-
rest of the chain (other middleware, then the endpoint
|
|
101
|
-
the `ctx` model, not `req`.
|
|
102
|
-
|
|
103
|
-
To attach middleware to a specific endpoint, import it and list it in the
|
|
104
|
-
endpoint's `middleware` array:
|
|
105
|
-
|
|
106
|
-
```ts
|
|
107
|
-
import { defineEndpoint, z } from "@palbase/backend";
|
|
108
|
-
import logger from "../../middleware/logger.js";
|
|
109
|
-
|
|
110
|
-
export default defineEndpoint({
|
|
111
|
-
method: "GET",
|
|
112
|
-
middleware: [logger],
|
|
113
|
-
output: z.object({ ok: z.boolean() }),
|
|
114
|
-
handler: async (req) => ({ ok: true }),
|
|
115
|
-
});
|
|
116
|
-
```
|
|
140
|
+
rest of the chain (other middleware, then the endpoint method).
|