@palbase/backend 0.9.0 → 1.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 +88 -0
- package/dist/chunk-7N5ICXCB.js.map +1 -0
- package/dist/db/index.d.cts +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/{endpoint-DysSe3SI.d.ts → endpoint-knNIeovM.d.ts} +290 -119
- package/dist/{endpoint-_1Qq8AFz.d.cts → endpoint-yn2xcrWu.d.cts} +290 -119
- package/dist/index.cjs +104 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +195 -22
- package/dist/index.d.ts +195 -22
- package/dist/index.js +34 -22
- package/dist/index.js.map +1 -1
- package/dist/{schema-zk-a0Dv7.d.cts → schema-BqfEhIC0.d.cts} +1 -1
- package/dist/{schema-zk-a0Dv7.d.ts → schema-BqfEhIC0.d.ts} +1 -1
- package/dist/test/index.cjs +85 -8
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +28 -5
- package/dist/test/index.d.ts +28 -5
- package/dist/test/index.js +57 -8
- package/dist/test/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ZodSchema, z } from 'zod';
|
|
2
|
-
import { S as SchemaDef
|
|
2
|
+
import { S as SchemaDef } from './schema-BqfEhIC0.js';
|
|
3
3
|
|
|
4
4
|
/** Supported HTTP methods for endpoints. */
|
|
5
5
|
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
@@ -47,77 +47,43 @@ type MiddlewareHandler = (ctx: MiddlewareContext, next: () => Promise<void>) =>
|
|
|
47
47
|
*/
|
|
48
48
|
declare function defineMiddleware(fn: MiddlewareHandler): MiddlewareHandler;
|
|
49
49
|
|
|
50
|
-
/**
|
|
51
|
-
* typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.
|
|
50
|
+
/** HTTP error with structured error response format.
|
|
52
51
|
*
|
|
53
|
-
*
|
|
54
|
-
* and wraps the untyped runtime `DBClient` with a typed facade.
|
|
52
|
+
* Two ways to construct one:
|
|
55
53
|
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* to the precise shape that the schema declared.
|
|
64
|
-
* Both casts are narrowing only (not widening) and correctness is guaranteed
|
|
65
|
-
* by the schema the caller provides.
|
|
66
|
-
*/
|
|
67
|
-
|
|
68
|
-
/** Keys of C whose columns are required on INSERT (not nullable, no default). */
|
|
69
|
-
type RequiredKeys<C> = {
|
|
70
|
-
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;
|
|
71
|
-
}[keyof C];
|
|
72
|
-
/** Keys of C whose columns are optional on INSERT (nullable or has a default). */
|
|
73
|
-
type OptionalKeys<C> = {
|
|
74
|
-
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;
|
|
75
|
-
}[keyof C];
|
|
76
|
-
/**
|
|
77
|
-
* The TypeScript type for an INSERT payload for table `T`.
|
|
78
|
-
* - Required: columns that are NOT NULL and have no DB-level default.
|
|
79
|
-
* - Optional: columns that are nullable or carry a default.
|
|
54
|
+
* 1. Directly: `throw new HttpError(404, "todo_not_found", "No such todo")`.
|
|
55
|
+
* Surfaces on the wire (and to iOS) as `BackendError.server(code, status,
|
|
56
|
+
* message, requestId)`.
|
|
57
|
+
* 2. Via `ctx.errors.<name>(data?)` for declared errors — see
|
|
58
|
+
* `EndpointConfig.errors`. The endpoint's OpenAPI spec describes each
|
|
59
|
+
* one, and the CLI codegen emits a typed `<Endpoint>.Error` enum so iOS
|
|
60
|
+
* callers can `catch <Endpoint>.Error.<case>` directly.
|
|
80
61
|
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
[K in RequiredKeys<T["columns"]>]: ColValue<T["columns"][K]>;
|
|
86
|
-
} & {
|
|
87
|
-
[K in OptionalKeys<T["columns"]>]?: ColValue<T["columns"][K]>;
|
|
88
|
-
};
|
|
89
|
-
/**
|
|
90
|
-
* The TypeScript type for a full row returned by the DB for table `T`.
|
|
91
|
-
* Every column is present; nullable columns resolve to `T | null`.
|
|
62
|
+
* The optional `data` field carries a structured payload alongside the
|
|
63
|
+
* standard envelope — used by declared errors that need to ship extra context
|
|
64
|
+
* (e.g. `todoLocked({ retryAfter: 30 })`). It rides through to the iOS typed
|
|
65
|
+
* enum's associated value.
|
|
92
66
|
*/
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
67
|
+
declare class HttpError extends Error {
|
|
68
|
+
readonly status: number;
|
|
69
|
+
readonly error: string;
|
|
70
|
+
readonly errorDescription: string;
|
|
71
|
+
readonly data?: unknown;
|
|
72
|
+
constructor(status: number, error: string, errorDescription: string, data?: unknown);
|
|
73
|
+
/**
|
|
74
|
+
* Serialize to the standard Palbase error response format.
|
|
75
|
+
* The `requestId` is injected by the runtime layer from the request context.
|
|
76
|
+
* When called without arguments (e.g. JSON.stringify), request_id is omitted.
|
|
77
|
+
* When `data` is set, it is appended as a strict-superset field.
|
|
78
|
+
*/
|
|
79
|
+
toJSON(requestId?: string): {
|
|
80
|
+
error: string;
|
|
81
|
+
error_description: string;
|
|
82
|
+
status: number;
|
|
83
|
+
request_id?: string;
|
|
84
|
+
data?: unknown;
|
|
108
85
|
};
|
|
109
86
|
}
|
|
110
|
-
/**
|
|
111
|
-
* Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from
|
|
112
|
-
* the provided schema. No behavior change — all calls delegate to `raw` with
|
|
113
|
-
* the table name as a plain string.
|
|
114
|
-
*
|
|
115
|
-
* The `satisfies` check verifies the built object is structurally compatible
|
|
116
|
-
* before we present it as `TypedDB<S>`. The final `as TypedDB<S>` is a
|
|
117
|
-
* single structural narrowing from the dynamically-built type to the precise
|
|
118
|
-
* mapped type (TS cannot infer through `Object.keys` iteration).
|
|
119
|
-
*/
|
|
120
|
-
declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): TypedDB<S>;
|
|
121
87
|
|
|
122
88
|
/**
|
|
123
89
|
* Local typed interfaces for the 9 Palbase module clients injected into
|
|
@@ -331,7 +297,18 @@ interface PalbasePushSendResponse {
|
|
|
331
297
|
interface PalbaseEmailSendParams {
|
|
332
298
|
to: string | string[];
|
|
333
299
|
subject?: string;
|
|
300
|
+
/**
|
|
301
|
+
* @deprecated The server reads `template_slug`, not `template` — this
|
|
302
|
+
* field is forwarded as-is and ignored by palnotify. Use `templateSlug`
|
|
303
|
+
* instead. Retained for source-compat with older callers.
|
|
304
|
+
*/
|
|
334
305
|
template?: string;
|
|
306
|
+
/**
|
|
307
|
+
* Server email-template slug. The notifications client maps this to the
|
|
308
|
+
* wire field `template_slug` (mutually exclusive with `subject` + body
|
|
309
|
+
* fields when not overriding template output).
|
|
310
|
+
*/
|
|
311
|
+
templateSlug?: string;
|
|
335
312
|
variables?: Record<string, unknown>;
|
|
336
313
|
html?: string;
|
|
337
314
|
text?: string;
|
|
@@ -350,7 +327,18 @@ interface PalbaseEmailSendResponse {
|
|
|
350
327
|
/** SMS send params. */
|
|
351
328
|
interface PalbaseSmsSendParams {
|
|
352
329
|
to: string | string[];
|
|
353
|
-
|
|
330
|
+
/**
|
|
331
|
+
* SMS body text. Either `body` OR `templateSlug` must be supplied —
|
|
332
|
+
* the two are mutually exclusive at the server.
|
|
333
|
+
*/
|
|
334
|
+
body?: string;
|
|
335
|
+
/**
|
|
336
|
+
* Server SMS-template slug. The notifications client maps this to the
|
|
337
|
+
* wire field `template_slug`. When provided, palnotify renders the
|
|
338
|
+
* template with `variables` and uses the result as the SMS body.
|
|
339
|
+
*/
|
|
340
|
+
templateSlug?: string;
|
|
341
|
+
variables?: Record<string, unknown>;
|
|
354
342
|
category?: string;
|
|
355
343
|
}
|
|
356
344
|
/** SMS send response. */
|
|
@@ -422,6 +410,56 @@ interface PalbaseRegisterDeviceParams {
|
|
|
422
410
|
app_version?: string;
|
|
423
411
|
locale?: string;
|
|
424
412
|
}
|
|
413
|
+
/** Email template view (camelCase). */
|
|
414
|
+
interface PalbaseEmailTemplate {
|
|
415
|
+
id: string;
|
|
416
|
+
projectId: string;
|
|
417
|
+
slug: string;
|
|
418
|
+
subject: string;
|
|
419
|
+
htmlBody: string;
|
|
420
|
+
textBody?: string;
|
|
421
|
+
variables: string[];
|
|
422
|
+
isDefault: boolean;
|
|
423
|
+
createdAt: string;
|
|
424
|
+
updatedAt: string;
|
|
425
|
+
}
|
|
426
|
+
/** Payload for templates.email.create. */
|
|
427
|
+
interface PalbaseCreateEmailTemplateInput {
|
|
428
|
+
slug: string;
|
|
429
|
+
subject: string;
|
|
430
|
+
htmlBody: string;
|
|
431
|
+
textBody?: string;
|
|
432
|
+
variables?: string[];
|
|
433
|
+
}
|
|
434
|
+
/** Payload for templates.email.update — patch semantics. */
|
|
435
|
+
interface PalbaseUpdateEmailTemplateInput {
|
|
436
|
+
subject?: string;
|
|
437
|
+
htmlBody?: string;
|
|
438
|
+
textBody?: string;
|
|
439
|
+
variables?: string[];
|
|
440
|
+
}
|
|
441
|
+
/** SMS template view (camelCase). No subject / html / text distinction. */
|
|
442
|
+
interface PalbaseSMSTemplate {
|
|
443
|
+
id: string;
|
|
444
|
+
projectId: string;
|
|
445
|
+
slug: string;
|
|
446
|
+
body: string;
|
|
447
|
+
variables: string[];
|
|
448
|
+
isDefault: boolean;
|
|
449
|
+
createdAt: string;
|
|
450
|
+
updatedAt: string;
|
|
451
|
+
}
|
|
452
|
+
/** Payload for templates.sms.create. */
|
|
453
|
+
interface PalbaseCreateSMSTemplateInput {
|
|
454
|
+
slug: string;
|
|
455
|
+
body: string;
|
|
456
|
+
variables?: string[];
|
|
457
|
+
}
|
|
458
|
+
/** Payload for templates.sms.update — patch semantics. */
|
|
459
|
+
interface PalbaseUpdateSMSTemplateInput {
|
|
460
|
+
body?: string;
|
|
461
|
+
variables?: string[];
|
|
462
|
+
}
|
|
425
463
|
/** Analytics event properties. */
|
|
426
464
|
type PalbaseAnalyticsProperties = Record<string, unknown>;
|
|
427
465
|
/** Analytics identify traits. */
|
|
@@ -952,6 +990,47 @@ interface PalbasePreferencesClient {
|
|
|
952
990
|
/** Update notification preferences. */
|
|
953
991
|
update(params: PalbasePreferences): Promise<PalbaseResult<PalbasePreferences>>;
|
|
954
992
|
}
|
|
993
|
+
/**
|
|
994
|
+
* Email-template CRUD sub-client (service-role gated server-side).
|
|
995
|
+
*/
|
|
996
|
+
interface PalbaseEmailTemplatesClient {
|
|
997
|
+
/** List all email templates. */
|
|
998
|
+
list(): Promise<PalbaseResult<PalbaseEmailTemplate[]>>;
|
|
999
|
+
/** Get one email template by ID. */
|
|
1000
|
+
get(id: string): Promise<PalbaseResult<PalbaseEmailTemplate>>;
|
|
1001
|
+
/** Create an email template. */
|
|
1002
|
+
create(input: PalbaseCreateEmailTemplateInput): Promise<PalbaseResult<PalbaseEmailTemplate>>;
|
|
1003
|
+
/** Update an email template (patch semantics). */
|
|
1004
|
+
update(id: string, input: PalbaseUpdateEmailTemplateInput): Promise<PalbaseResult<PalbaseEmailTemplate>>;
|
|
1005
|
+
/** Delete an email template. */
|
|
1006
|
+
delete(id: string): Promise<PalbaseResult<void>>;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* SMS-template CRUD sub-client (service-role gated server-side).
|
|
1010
|
+
*/
|
|
1011
|
+
interface PalbaseSMSTemplatesClient {
|
|
1012
|
+
/** List all SMS templates. */
|
|
1013
|
+
list(): Promise<PalbaseResult<PalbaseSMSTemplate[]>>;
|
|
1014
|
+
/** Get one SMS template by ID. */
|
|
1015
|
+
get(id: string): Promise<PalbaseResult<PalbaseSMSTemplate>>;
|
|
1016
|
+
/** Create an SMS template. */
|
|
1017
|
+
create(input: PalbaseCreateSMSTemplateInput): Promise<PalbaseResult<PalbaseSMSTemplate>>;
|
|
1018
|
+
/** Update an SMS template (patch semantics). */
|
|
1019
|
+
update(id: string, input: PalbaseUpdateSMSTemplateInput): Promise<PalbaseResult<PalbaseSMSTemplate>>;
|
|
1020
|
+
/** Delete an SMS template. */
|
|
1021
|
+
delete(id: string): Promise<PalbaseResult<void>>;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Templates sub-client — parallel CRUD for email and SMS templates.
|
|
1025
|
+
* Service-role gated server-side; both surfaces map TS camelCase to
|
|
1026
|
+
* wire snake_case in the runtime client.
|
|
1027
|
+
*/
|
|
1028
|
+
interface PalbaseTemplatesClient {
|
|
1029
|
+
/** Email template CRUD. */
|
|
1030
|
+
email: PalbaseEmailTemplatesClient;
|
|
1031
|
+
/** SMS template CRUD. */
|
|
1032
|
+
sms: PalbaseSMSTemplatesClient;
|
|
1033
|
+
}
|
|
955
1034
|
/**
|
|
956
1035
|
* Notifications client available on `ctx.notifications`.
|
|
957
1036
|
* Service-role: all send operations require privileged access.
|
|
@@ -968,6 +1047,8 @@ interface PalbaseNotificationsClient {
|
|
|
968
1047
|
inbox: PalbaseInboxClient;
|
|
969
1048
|
/** Notification preferences manager. */
|
|
970
1049
|
preferences: PalbasePreferencesClient;
|
|
1050
|
+
/** Email + SMS template CRUD (service-role). */
|
|
1051
|
+
templates: PalbaseTemplatesClient;
|
|
971
1052
|
/** Register a device for push notifications. */
|
|
972
1053
|
registerDevice(params: PalbaseRegisterDeviceParams): Promise<PalbaseResult<PalbaseDeviceTokenView>>;
|
|
973
1054
|
/** Remove a device registration. */
|
|
@@ -1080,6 +1161,8 @@ interface RateLimitConfig {
|
|
|
1080
1161
|
/** Window duration in seconds. */
|
|
1081
1162
|
window: number;
|
|
1082
1163
|
}
|
|
1164
|
+
/** The transaction-scoped client passed to `db.transaction(fn)` — same DB ops, no nested transaction. */
|
|
1165
|
+
type TxClient = Omit<DBClient, "transaction">;
|
|
1083
1166
|
/** Database client interface injected into endpoint context. */
|
|
1084
1167
|
interface DBClient {
|
|
1085
1168
|
/** Run a read-only SQL query (executes in a READ ONLY transaction). */
|
|
@@ -1089,6 +1172,12 @@ interface DBClient {
|
|
|
1089
1172
|
delete(table: string, id: string): Promise<void>;
|
|
1090
1173
|
findById(table: string, id: string): Promise<Record<string, unknown> | null>;
|
|
1091
1174
|
findMany(table: string, query?: Record<string, unknown>): Promise<Record<string, unknown>[]>;
|
|
1175
|
+
/**
|
|
1176
|
+
* Run an interactive transaction. The callback receives a `tx` with the same
|
|
1177
|
+
* DB ops as this client; returning normally commits, throwing rolls back.
|
|
1178
|
+
* Nested transactions are not supported.
|
|
1179
|
+
*/
|
|
1180
|
+
transaction<T>(fn: (tx: TxClient) => Promise<T>): Promise<T>;
|
|
1092
1181
|
}
|
|
1093
1182
|
/** Logger interface injected into endpoint context. */
|
|
1094
1183
|
interface Logger {
|
|
@@ -1151,7 +1240,7 @@ interface PalbaseQuerySnapshot<T = Record<string, unknown>> {
|
|
|
1151
1240
|
}
|
|
1152
1241
|
/** Comparison operators supported by docs.where(). */
|
|
1153
1242
|
type PalbaseWhereOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "array-contains";
|
|
1154
|
-
/** Document reference exposed by
|
|
1243
|
+
/** Document reference exposed by Documents.collection(...).doc(...). */
|
|
1155
1244
|
interface PalbaseDocumentRef<T = Record<string, unknown>> {
|
|
1156
1245
|
readonly path: string;
|
|
1157
1246
|
set(data: T): Promise<PalbaseResult<void>>;
|
|
@@ -1159,7 +1248,7 @@ interface PalbaseDocumentRef<T = Record<string, unknown>> {
|
|
|
1159
1248
|
update(data: Partial<T>): Promise<PalbaseResult<void>>;
|
|
1160
1249
|
delete(): Promise<PalbaseResult<void>>;
|
|
1161
1250
|
}
|
|
1162
|
-
/** Collection reference exposed by
|
|
1251
|
+
/** Collection reference exposed by Documents.collection(...). */
|
|
1163
1252
|
interface PalbaseCollectionRef<T = Record<string, unknown>> {
|
|
1164
1253
|
readonly path: string;
|
|
1165
1254
|
doc(id: string): PalbaseDocumentRef<T>;
|
|
@@ -1169,23 +1258,39 @@ interface PalbaseCollectionRef<T = Record<string, unknown>> {
|
|
|
1169
1258
|
limit(n: number): PalbaseCollectionRef<T>;
|
|
1170
1259
|
get(): Promise<PalbaseResult<PalbaseQuerySnapshot<T>>>;
|
|
1171
1260
|
}
|
|
1172
|
-
/** Docs client surface available on
|
|
1261
|
+
/** Docs client surface available on the Documents singleton. */
|
|
1173
1262
|
interface PalbaseDocsClient {
|
|
1174
1263
|
collection<T = Record<string, unknown>>(path: string): PalbaseCollectionRef<T>;
|
|
1175
1264
|
doc<T = Record<string, unknown>>(path: string): PalbaseDocumentRef<T>;
|
|
1176
1265
|
}
|
|
1177
|
-
/**
|
|
1266
|
+
/** Calling-client metadata, derived from request headers.
|
|
1178
1267
|
*
|
|
1179
|
-
*
|
|
1180
|
-
*
|
|
1181
|
-
*
|
|
1182
|
-
*
|
|
1268
|
+
* Populated from the `X-Palbase-*-Version` / platform headers the client SDKs
|
|
1269
|
+
* send. All fields are nullable: a request may come from a non-SDK caller
|
|
1270
|
+
* (curl, server-to-server) that sends none of them. The semver comparison
|
|
1271
|
+
* helpers (`appVersionAtLeast`, …) arrive in Phase 2 — Phase 1 surfaces only
|
|
1272
|
+
* the raw data fields. */
|
|
1273
|
+
interface ClientInfo {
|
|
1274
|
+
/** Palbase SDK version (`X-Palbase-Sdk-Version`), or null. */
|
|
1275
|
+
sdkVersion: string | null;
|
|
1276
|
+
/** Calling app's own version (`X-Palbase-Client-Version`), or null. */
|
|
1277
|
+
appVersion: string | null;
|
|
1278
|
+
/** Platform identifier (e.g. "ios", "android", "web"), or null. */
|
|
1279
|
+
platform: string | null;
|
|
1280
|
+
/** OS version string, or null. */
|
|
1281
|
+
osVersion: string | null;
|
|
1282
|
+
}
|
|
1283
|
+
/** Palbase module clients, as a structural bundle.
|
|
1183
1284
|
*
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
* as
|
|
1187
|
-
*
|
|
1188
|
-
|
|
1285
|
+
* NOT part of the endpoint surface anymore — endpoint handlers reach services
|
|
1286
|
+
* via the PascalCase singletons (`Database`, `Documents`, …). This type is
|
|
1287
|
+
* retained as an INTERNAL shape for the sibling contexts that still carry a
|
|
1288
|
+
* `ctx` (middleware, jobs, workers, hooks, webhooks — out of Phase 1 scope).
|
|
1289
|
+
* It is intentionally not re-exported from `index.ts`.
|
|
1290
|
+
*
|
|
1291
|
+
* Structurally typed against the runtime's `ServerClient`; the runtime injects
|
|
1292
|
+
* the real client, so mismatched names would surface as `undefined is not a
|
|
1293
|
+
* function` at call time — keep these in sync with `ServerClient`. */
|
|
1189
1294
|
interface PalbaseModuleClients {
|
|
1190
1295
|
auth: PalbaseAuthClient;
|
|
1191
1296
|
storage: PalbaseStorageClient;
|
|
@@ -1198,40 +1303,97 @@ interface PalbaseModuleClients {
|
|
|
1198
1303
|
links: PalbaseLinksClient;
|
|
1199
1304
|
cms: PalbaseCmsClient;
|
|
1200
1305
|
}
|
|
1201
|
-
/**
|
|
1202
|
-
*
|
|
1203
|
-
*
|
|
1306
|
+
/** Declared-error definition.
|
|
1307
|
+
*
|
|
1308
|
+
* `code` is the stable snake_case identifier that lands on the wire envelope's
|
|
1309
|
+
* `error` field. `status` is the HTTP status code returned. `data`, if set,
|
|
1310
|
+
* is a Zod schema whose value rides on the envelope's `data` field — the CLI
|
|
1311
|
+
* codegen lowers it to the typed enum's associated value on iOS.
|
|
1312
|
+
*
|
|
1313
|
+
* `description` is optional human-readable text; the OpenAPI generator uses it
|
|
1314
|
+
* for the response description and the iOS codegen surfaces it in the
|
|
1315
|
+
* generated method's doc-comment.
|
|
1316
|
+
*/
|
|
1317
|
+
interface ErrorDef<TData extends ZodSchema = ZodSchema> {
|
|
1318
|
+
status: number;
|
|
1319
|
+
code: string;
|
|
1320
|
+
description?: string;
|
|
1321
|
+
data?: TData;
|
|
1322
|
+
}
|
|
1323
|
+
/** Map of declared errors keyed by their TypeScript-side names.
|
|
1324
|
+
*
|
|
1325
|
+
* Keys are the friendly names the handler uses (`req.errors.todoLocked`);
|
|
1326
|
+
* `code` on each value is the wire identifier. The TS name is what the iOS
|
|
1327
|
+
* codegen lowers to (camelCase enum cases), and the wire `code` is what the
|
|
1328
|
+
* envelope's `error` field carries.
|
|
1329
|
+
*/
|
|
1330
|
+
type ErrorMap = Record<string, ErrorDef>;
|
|
1331
|
+
/** Throwable proxy projected onto `req.errors` when `errors` is declared.
|
|
1332
|
+
*
|
|
1333
|
+
* Each entry is a constructor: declared errors with a `data` schema demand
|
|
1334
|
+
* the payload as a required argument; declared errors without `data` take
|
|
1335
|
+
* none. Throwing the result emits the standard envelope (with `data` when
|
|
1336
|
+
* present).
|
|
1337
|
+
*
|
|
1338
|
+
* throw req.errors.todoNotFound();
|
|
1339
|
+
* throw req.errors.todoLocked({ retryAfter: 30 });
|
|
1340
|
+
*/
|
|
1341
|
+
type ErrorThrowers<TErrors extends ErrorMap | undefined> = TErrors extends ErrorMap ? {
|
|
1342
|
+
[K in keyof TErrors]: TErrors[K]["data"] extends ZodSchema ? (data: z.infer<NonNullable<TErrors[K]["data"]>>) => HttpError : () => HttpError;
|
|
1343
|
+
} : Record<string, never>;
|
|
1344
|
+
/** The request-scoped object passed to every endpoint handler.
|
|
1345
|
+
*
|
|
1346
|
+
* Replaces the old `ctx` god-object. `PBRequest` carries ONLY request-scoped
|
|
1347
|
+
* data — the typed `input`, route/query params, headers, the authenticated
|
|
1348
|
+
* `user`, calling-client metadata, trace ids, and the endpoint's declared
|
|
1349
|
+
* error throwers. Services (`Database`, `Documents`, `Cache`, …) are NOT on
|
|
1350
|
+
* the request: import them directly from `@palbase/backend` as singletons.
|
|
1351
|
+
*
|
|
1352
|
+
* import { defineEndpoint, Database } from "@palbase/backend";
|
|
1204
1353
|
*
|
|
1205
|
-
*
|
|
1206
|
-
*
|
|
1207
|
-
*
|
|
1208
|
-
*
|
|
1354
|
+
* export default defineEndpoint({
|
|
1355
|
+
* method: "POST",
|
|
1356
|
+
* handler: async (req) => Database.insert("todos", { title: req.input.title }),
|
|
1357
|
+
* });
|
|
1358
|
+
*
|
|
1359
|
+
* Generic parameters:
|
|
1360
|
+
* - `TInput` — the validated `input` type (inferred from the `input` Zod
|
|
1361
|
+
* schema by `defineEndpoint`). The user-facing form is single-generic:
|
|
1362
|
+
* `PBRequest<TodoInput>`.
|
|
1363
|
+
* - `TAuthed` — whether `user` is non-null. DEFAULTS to `true` (the common
|
|
1364
|
+
* case; the auth pipeline returns 401 before the handler when auth is
|
|
1365
|
+
* required, so a non-null `user` is runtime-honest). `defineEndpoint` passes
|
|
1366
|
+
* `IsAuthed<TAuth>` here, so `auth: false` → `User | null`.
|
|
1367
|
+
* - `TErrors` — the declared `errors` map, typing `req.errors.<name>(...)`.
|
|
1209
1368
|
*/
|
|
1210
|
-
interface
|
|
1369
|
+
interface PBRequest<TInput = unknown, TAuthed extends boolean = true, TErrors extends ErrorMap | undefined = undefined> {
|
|
1370
|
+
/** Validated request input (body for POST/PUT/PATCH; `{}` otherwise). */
|
|
1211
1371
|
input: TInput;
|
|
1372
|
+
/** Matched route params (e.g. `{ id }` for `/todos/[id]`). */
|
|
1212
1373
|
params: Record<string, string>;
|
|
1374
|
+
/** Parsed query-string params. */
|
|
1213
1375
|
query: Record<string, string>;
|
|
1376
|
+
/** Request headers (lowercase keys). */
|
|
1214
1377
|
headers: Record<string, string>;
|
|
1215
|
-
/** Authenticated user. Non-null (`User`)
|
|
1216
|
-
*
|
|
1217
|
-
*
|
|
1218
|
-
* `auth` literal via {@link IsAuthed}. */
|
|
1378
|
+
/** Authenticated user. Non-null (`User`) by default; `User | null` only when
|
|
1379
|
+
* the endpoint's `auth` config disables enforcement (driven by `TAuthed`,
|
|
1380
|
+
* which `defineEndpoint` computes from the `auth` literal via {@link IsAuthed}). */
|
|
1219
1381
|
user: TAuthed extends true ? User : User | null;
|
|
1220
|
-
/**
|
|
1221
|
-
|
|
1222
|
-
/** Matched endpoint path (e.g. "/todos/create"). */
|
|
1223
|
-
endpointPath: string;
|
|
1382
|
+
/** Calling-client metadata derived from request headers (all nullable). */
|
|
1383
|
+
client: ClientInfo;
|
|
1224
1384
|
/** Uploaded file, or null when the request has no file part. */
|
|
1225
1385
|
file: FileContext | null;
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
cache: CacheClient;
|
|
1230
|
-
/** Queue client for dispatching background jobs. */
|
|
1231
|
-
queue: QueueClient;
|
|
1386
|
+
/** HTTP method of the incoming request (e.g. "GET", "POST"). */
|
|
1387
|
+
method: string;
|
|
1388
|
+
/** Per-request id (`req_<…>`), preserved for back-compat correlation. */
|
|
1232
1389
|
requestId: string;
|
|
1233
|
-
|
|
1234
|
-
|
|
1390
|
+
/** W3C trace id (primary correlation key across modules). */
|
|
1391
|
+
traceId: string;
|
|
1392
|
+
/** W3C span id for this handler invocation. */
|
|
1393
|
+
spanId: string;
|
|
1394
|
+
/** Typed throwers for the endpoint's declared errors. Empty when the
|
|
1395
|
+
* `errors` block is absent on `defineEndpoint`. */
|
|
1396
|
+
errors: ErrorThrowers<TErrors>;
|
|
1235
1397
|
}
|
|
1236
1398
|
/** Middleware function signature — uses MiddlewareContext (no input, not yet validated). */
|
|
1237
1399
|
type Middleware = (ctx: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
|
|
@@ -1243,11 +1405,11 @@ type Middleware = (ctx: MiddlewareContext, next: () => Promise<void>) => Promise
|
|
|
1243
1405
|
*/
|
|
1244
1406
|
type AuthSpec = boolean | Partial<AuthConfig>;
|
|
1245
1407
|
/** Compute, at the type level, whether an endpoint authenticates its caller —
|
|
1246
|
-
* i.e. whether `
|
|
1408
|
+
* i.e. whether `req.user` should be `User` (non-null) instead of `User | null`.
|
|
1247
1409
|
*
|
|
1248
1410
|
* This mirrors the Go pipeline's enforcement exactly (extract_meta.js + auth.go):
|
|
1249
1411
|
* a request is authenticated ⟺ `auth === true` OR (`auth` is an object whose
|
|
1250
|
-
* `required` is not explicitly `false`). So `
|
|
1412
|
+
* `required` is not explicitly `false`). So `req.user` stays nullable ONLY when
|
|
1251
1413
|
* `auth` is absent (`undefined`), `auth === false`, or `auth: { required: false }`.
|
|
1252
1414
|
*
|
|
1253
1415
|
* | `TAuth` | `IsAuthed<TAuth>` |
|
|
@@ -1269,31 +1431,40 @@ type IsAuthed<TAuth> = TAuth extends {
|
|
|
1269
1431
|
} ? false : TAuth extends true ? true : TAuth extends false ? false : TAuth extends object ? true : false;
|
|
1270
1432
|
/** Configuration for defining an endpoint.
|
|
1271
1433
|
*
|
|
1272
|
-
* `TSchema` — optional `SchemaDef`
|
|
1273
|
-
*
|
|
1274
|
-
*
|
|
1434
|
+
* `TSchema` — optional `SchemaDef` carried on the `schema` field. The runtime
|
|
1435
|
+
* uses it to wire a typed `.tables.*` API; authors opt in per endpoint with
|
|
1436
|
+
* `typedDatabase(schema)` (see runtime.ts).
|
|
1275
1437
|
*
|
|
1276
1438
|
* `TAuth` — captures the literal type of the `auth` field (via the `const`
|
|
1277
|
-
* type parameter on `defineEndpoint`) so the handler's `
|
|
1439
|
+
* type parameter on `defineEndpoint`) so the handler's `req.user` can be
|
|
1278
1440
|
* narrowed to non-null `User` when auth is required. See {@link IsAuthed}.
|
|
1441
|
+
*
|
|
1442
|
+
* `TErrors` — captures the literal `errors` map (via the `const` type
|
|
1443
|
+
* parameter on `defineEndpoint`) so `req.errors.<name>(...)` is typed per
|
|
1444
|
+
* declared entry. The OpenAPI generator emits each one as a discriminated
|
|
1445
|
+
* response under `responses[<status>]`, and the CLI codegen lowers them to
|
|
1446
|
+
* a typed `<Endpoint>.Error` enum on iOS.
|
|
1279
1447
|
*/
|
|
1280
|
-
interface EndpointConfig<TInputSchema extends ZodSchema = ZodSchema, TOutputSchema extends ZodSchema = ZodSchema, TSchema extends SchemaDef | undefined = undefined, TAuth extends AuthSpec | undefined = undefined> {
|
|
1448
|
+
interface EndpointConfig<TInputSchema extends ZodSchema = ZodSchema, TOutputSchema extends ZodSchema = ZodSchema, TSchema extends SchemaDef | undefined = undefined, TAuth extends AuthSpec | undefined = undefined, TErrors extends ErrorMap | undefined = undefined> {
|
|
1281
1449
|
method: HttpMethod;
|
|
1282
1450
|
auth?: TAuth;
|
|
1283
1451
|
rateLimit?: RateLimitConfig;
|
|
1284
1452
|
input?: TInputSchema;
|
|
1285
1453
|
output?: TOutputSchema;
|
|
1286
1454
|
schema?: TSchema;
|
|
1455
|
+
errors?: TErrors;
|
|
1287
1456
|
middleware?: Middleware[];
|
|
1288
|
-
handler: (
|
|
1457
|
+
handler: (req: PBRequest<z.infer<TInputSchema>, IsAuthed<TAuth>, TErrors>) => Promise<z.infer<TOutputSchema>>;
|
|
1289
1458
|
}
|
|
1290
|
-
/** Define a type-safe endpoint.
|
|
1291
|
-
* Pass a `schema` (from `defineSchema`)
|
|
1459
|
+
/** Define a type-safe endpoint. The input schema infers the `req.input` type.
|
|
1460
|
+
* Pass a `schema` (from `defineSchema`) and wrap `Database` with
|
|
1461
|
+
* `typedDatabase(schema)` in the handler for a typed `.tables.*` API.
|
|
1292
1462
|
*
|
|
1293
|
-
* The `const TAuth` type
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
1463
|
+
* The `const TAuth` and `const TErrors` type parameters capture the `auth`
|
|
1464
|
+
* and `errors` fields as literals, so `req.user` narrows to non-null `User`
|
|
1465
|
+
* when auth is enforced and `req.errors.<name>(...)` is typed per declared
|
|
1466
|
+
* entry.
|
|
1296
1467
|
*/
|
|
1297
|
-
declare function defineEndpoint<TInputSchema extends ZodSchema, TOutputSchema extends ZodSchema, TSchema extends SchemaDef | undefined = undefined, const TAuth extends AuthSpec | undefined = undefined>(config: EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth>): EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth>;
|
|
1468
|
+
declare function defineEndpoint<TInputSchema extends ZodSchema, TOutputSchema extends ZodSchema, TSchema extends SchemaDef | undefined = undefined, const TAuth extends AuthSpec | undefined = undefined, const TErrors extends ErrorMap | undefined = undefined>(config: EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors>): EndpointConfig<TInputSchema, TOutputSchema, TSchema, TAuth, TErrors>;
|
|
1298
1469
|
|
|
1299
|
-
export { type
|
|
1470
|
+
export { type PalbaseFileObject as $, type AuthConfig as A, type PalbaseCohortQueryInput as B, type CacheClient as C, type DBClient as D, type ErrorThrowers as E, type FileContext as F, type PalbaseCohortResult as G, HttpError as H, type PalbaseCollectionRef as I, type PalbaseCountQueryInput as J, type PalbaseCountResult as K, type Logger as L, type Middleware as M, type PalbaseCreateLinkParams as N, type PalbaseDeviceInfo as O, type PalbaseDocsClient as P, type QueueClient as Q, type PalbaseDeviceTokenView as R, type PalbaseDocumentRef as S, type PalbaseDocumentSnapshot as T, type User as U, type PalbaseEmailClient as V, type PalbaseEmailSendParams as W, type PalbaseEmailSendResponse as X, type PalbaseEventNamesResult as Y, type PalbaseEventsQueryInput as Z, type PalbaseEventsResult as _, type PalbaseFlagsClient as a, type PalbaseFlag as a0, type PalbaseFlagContext as a1, type PalbaseFlagVariant as a2, type PalbaseFunctionsClient as a3, type PalbaseFunnelQueryInput as a4, type PalbaseFunnelResult as a5, type PalbaseIdentifyTraits as a6, type PalbaseInboxClient as a7, type PalbaseInboxListOptions as a8, type PalbaseInboxListResult as a9, type PalbaseRegisterDeviceParams as aA, type PalbaseResult as aB, type PalbaseRetentionQueryInput as aC, type PalbaseRetentionResult as aD, type PalbaseSession as aE, type PalbaseSignedUrlResponse as aF, type PalbaseSmsClient as aG, type PalbaseSmsSendParams as aH, type PalbaseSmsSendResponse as aI, type PalbaseTransformOptions as aJ, type PalbaseUpdateLinkParams as aK, type PalbaseUploadOptions as aL, type PalbaseUser as aM, type PalbaseUserDetailResult as aN, type PalbaseUsersQueryInput as aO, type PalbaseUsersResult as aP, type PalbaseVerifyRequestSignatureParams as aQ, type PalbaseWhereOperator as aR, type RateLimitConfig as aS, type TxClient as aT, defineEndpoint as aU, defineMiddleware as aV, type PalbaseInboxMessage as aa, type PalbaseInboxSendParams as ab, type PalbaseInboxSendResponse as ac, type PalbaseInitialLink as ad, type PalbaseInvokeOptions as ae, type PalbaseLink as af, type PalbaseLinkAnalytics as ag, type PalbaseLinkDetails as ah, type PalbaseLinksClient as ai, type PalbaseListLinksOptions as aj, type PalbaseListLinksResult as ak, type PalbaseListOptions as al, type PalbaseMatchParams as am, type PalbaseMultiChannelResponse as an, type PalbaseOverviewResult as ao, type PalbasePreferences as ap, type PalbasePreferencesClient as aq, type PalbasePublicUrlResponse as ar, type PalbasePushClient as as, type PalbasePushSendParams as at, type PalbasePushSendResponse as au, type PalbaseQrCodeOptions as av, type PalbaseQuerySnapshot as aw, type PalbaseRealtimeChannel as ax, type PalbaseRealtimeClient as ay, type PalbaseRealtimeMessage as az, type PalbaseNotificationsClient as b, type PalbaseStorageClient as c, type PalbaseModuleClients as d, type ClientInfo as e, type EndpointConfig as f, type ErrorDef as g, type ErrorMap as h, type HttpMethod as i, type MiddlewareContext as j, type MiddlewareHandler as k, type PBRequest as l, type PalbaseAnalyticsClient as m, type PalbaseAnalyticsManagementNamespace as n, type PalbaseAnalyticsProperties as o, type PalbaseAnalyticsQueryNamespace as p, type PalbaseAttestAndroidParams as q, type PalbaseAttestAndroidResult as r, type PalbaseAttestiOSParams as s, type PalbaseAttestiOSResult as t, type PalbaseAuthClient as u, type PalbaseBindDeviceParams as v, type PalbaseBucketClient as w, type PalbaseCmsClient as x, type PalbaseCmsFindOneOptions as y, type PalbaseCmsFindOptions as z };
|