@palbase/backend 0.1.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.
@@ -0,0 +1,381 @@
1
+ import { E as EndpointContext, D as DBClient, L as Logger, C as CacheClient, P as PalbaseBindings } from './endpoint-tZi55HU8.cjs';
2
+ export { A as AuthConfig, a as EndpointConfig, H as HttpMethod, M as Middleware, b as MiddlewareContext, c as MiddlewareHandler, R as RateLimitConfig, U as User, d as defineEndpoint, e as defineMiddleware } from './endpoint-tZi55HU8.cjs';
3
+ export { z } from 'zod';
4
+
5
+ /** HTTP error with structured error response format. */
6
+ declare class HttpError extends Error {
7
+ readonly status: number;
8
+ readonly error: string;
9
+ readonly errorDescription: string;
10
+ constructor(status: number, error: string, errorDescription: string);
11
+ /**
12
+ * Serialize to the standard Palbase error response format.
13
+ * The `requestId` is injected by the runtime layer from the request context.
14
+ * When called without arguments (e.g. JSON.stringify), request_id is omitted.
15
+ */
16
+ toJSON(requestId?: string): {
17
+ error: string;
18
+ error_description: string;
19
+ status: number;
20
+ request_id?: string;
21
+ };
22
+ }
23
+
24
+ /** Backoff strategy for worker retries. */
25
+ type BackoffStrategy = "exponential" | "linear" | "fixed";
26
+ /** Configuration for a background worker. */
27
+ interface WorkerConfig<TPayload = unknown> {
28
+ /** Worker name — must be unique across the project. */
29
+ name: string;
30
+ /** Maximum number of retries before sending to dead letter queue. Defaults to 3. */
31
+ retry?: number;
32
+ /** Execution timeout in seconds. Defaults to 30. */
33
+ timeout?: number;
34
+ /** Backoff strategy between retries. Defaults to "exponential". */
35
+ backoff?: BackoffStrategy;
36
+ /** Handler function that processes the job payload. */
37
+ handler: (ctx: Omit<EndpointContext<TPayload>, "input" | "params" | "query" | "headers">, payload: TPayload) => Promise<void>;
38
+ }
39
+ /** Resolved worker configuration with defaults applied. */
40
+ interface ResolvedWorkerConfig<TPayload = unknown> {
41
+ name: string;
42
+ retry: number;
43
+ timeout: number;
44
+ backoff: BackoffStrategy;
45
+ handler: (ctx: Omit<EndpointContext<TPayload>, "input" | "params" | "query" | "headers">, payload: TPayload) => Promise<void>;
46
+ }
47
+ /**
48
+ * Define a background worker that processes jobs from the queue.
49
+ *
50
+ * Workers are placed in the `workers/` directory and auto-discovered at deploy time.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * export default defineWorker({
55
+ * name: "send-email",
56
+ * retry: 5,
57
+ * timeout: 60,
58
+ * backoff: "exponential",
59
+ * handler: async (ctx, payload: { to: string; subject: string }) => {
60
+ * await sendEmail(payload.to, payload.subject);
61
+ * },
62
+ * });
63
+ * ```
64
+ */
65
+ declare function defineWorker<TPayload = unknown>(config: WorkerConfig<TPayload>): ResolvedWorkerConfig<TPayload>;
66
+
67
+ /** Context injected into job handlers — subset of EndpointContext without request-specific fields. */
68
+ interface JobContext {
69
+ db: DBClient;
70
+ env: Record<string, string>;
71
+ log: Logger;
72
+ cache: CacheClient;
73
+ queue: {
74
+ enqueue(workerName: string, payload: unknown): Promise<string>;
75
+ };
76
+ palbase: PalbaseBindings;
77
+ projectId: string;
78
+ environmentId: string;
79
+ }
80
+ /** Configuration for defining a scheduled job. */
81
+ interface JobConfig {
82
+ /** Unique job name — alphanumeric, underscore, hyphen only. */
83
+ name: string;
84
+ /** Cron expression (e.g., "0 3 * * *"). */
85
+ schedule: string;
86
+ /** Execution timeout in seconds. Defaults to 30. */
87
+ timeout?: number;
88
+ /** Job handler function. */
89
+ handler: (ctx: JobContext) => Promise<void>;
90
+ }
91
+ /** Resolved job configuration with defaults applied. */
92
+ interface ResolvedJobConfig {
93
+ name: string;
94
+ schedule: string;
95
+ timeout: number;
96
+ handler: (ctx: JobContext) => Promise<void>;
97
+ }
98
+ /**
99
+ * Define a scheduled cron job.
100
+ *
101
+ * Jobs are placed in the `jobs/` directory and auto-discovered at deploy time.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * export default defineJob({
106
+ * name: "cleanup-expired",
107
+ * schedule: "0 3 * * *", // every day at 3 AM
108
+ * timeout: 60,
109
+ * handler: async (ctx) => {
110
+ * await ctx.db.delete("sessions", "expired < NOW()");
111
+ * ctx.log.info("Cleaned up expired sessions");
112
+ * },
113
+ * });
114
+ * ```
115
+ */
116
+ declare function defineJob(config: JobConfig): ResolvedJobConfig;
117
+
118
+ /** Supported webhook provider types. */
119
+ type WebhookProvider = "stripe" | "github" | "twilio" | "sendgrid" | "slack" | "discord" | "livekit";
120
+ /** Context injected into webhook handlers — no user (webhooks are machine-to-machine). */
121
+ interface WebhookContext {
122
+ db: DBClient;
123
+ env: Record<string, string>;
124
+ log: Logger;
125
+ cache: CacheClient;
126
+ queue: {
127
+ enqueue(workerName: string, payload: unknown): Promise<string>;
128
+ };
129
+ palbase: PalbaseBindings;
130
+ projectId: string;
131
+ environmentId: string;
132
+ requestId: string;
133
+ }
134
+ /** Secret reference — resolves from environment variables at runtime. */
135
+ interface EnvSecretRef {
136
+ env: string;
137
+ }
138
+ /** Provider-specific event maps for type-safe event handlers. */
139
+ interface ProviderEventMap {
140
+ stripe: {
141
+ "checkout.session.completed": Record<string, unknown>;
142
+ "payment_intent.succeeded": Record<string, unknown>;
143
+ "payment_intent.payment_failed": Record<string, unknown>;
144
+ "customer.subscription.created": Record<string, unknown>;
145
+ "customer.subscription.updated": Record<string, unknown>;
146
+ "customer.subscription.deleted": Record<string, unknown>;
147
+ "invoice.paid": Record<string, unknown>;
148
+ "invoice.payment_failed": Record<string, unknown>;
149
+ [key: string]: Record<string, unknown>;
150
+ };
151
+ github: {
152
+ push: Record<string, unknown>;
153
+ pull_request: Record<string, unknown>;
154
+ issues: Record<string, unknown>;
155
+ "pull_request.opened": Record<string, unknown>;
156
+ "pull_request.closed": Record<string, unknown>;
157
+ "pull_request.merged": Record<string, unknown>;
158
+ [key: string]: Record<string, unknown>;
159
+ };
160
+ twilio: {
161
+ "message.received": Record<string, unknown>;
162
+ "message.sent": Record<string, unknown>;
163
+ "call.completed": Record<string, unknown>;
164
+ [key: string]: Record<string, unknown>;
165
+ };
166
+ sendgrid: {
167
+ delivered: Record<string, unknown>;
168
+ bounce: Record<string, unknown>;
169
+ open: Record<string, unknown>;
170
+ click: Record<string, unknown>;
171
+ [key: string]: Record<string, unknown>;
172
+ };
173
+ slack: {
174
+ url_verification: Record<string, unknown>;
175
+ event_callback: Record<string, unknown>;
176
+ [key: string]: Record<string, unknown>;
177
+ };
178
+ discord: {
179
+ PING: Record<string, unknown>;
180
+ MESSAGE_CREATE: Record<string, unknown>;
181
+ INTERACTION_CREATE: Record<string, unknown>;
182
+ [key: string]: Record<string, unknown>;
183
+ };
184
+ livekit: {
185
+ "room.started": Record<string, unknown>;
186
+ "room.finished": Record<string, unknown>;
187
+ "participant.joined": Record<string, unknown>;
188
+ "participant.left": Record<string, unknown>;
189
+ [key: string]: Record<string, unknown>;
190
+ };
191
+ }
192
+ /** Event handler function type. */
193
+ type WebhookEventHandler<TEvent = Record<string, unknown>> = (ctx: WebhookContext, event: TEvent) => Promise<void>;
194
+ /** Provider-based webhook configuration. */
195
+ interface ProviderWebhookConfig<P extends WebhookProvider = WebhookProvider> {
196
+ provider: P;
197
+ secret: EnvSecretRef;
198
+ events: {
199
+ [K in keyof ProviderEventMap[P]]?: WebhookEventHandler<ProviderEventMap[P][K]>;
200
+ };
201
+ }
202
+ /** Incoming request representation for custom verify functions. */
203
+ interface WebhookRequest {
204
+ headers: Record<string, string>;
205
+ body: string;
206
+ method: string;
207
+ url: string;
208
+ }
209
+ /** Custom webhook configuration. */
210
+ interface CustomWebhookConfig {
211
+ path: string;
212
+ verify?: (req: WebhookRequest) => Promise<boolean> | boolean;
213
+ handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;
214
+ }
215
+ /** Resolved provider webhook (internal). */
216
+ interface ResolvedProviderWebhook<P extends WebhookProvider = WebhookProvider> {
217
+ type: "provider";
218
+ provider: P;
219
+ secret: EnvSecretRef;
220
+ events: Record<string, WebhookEventHandler>;
221
+ }
222
+ /** Resolved custom webhook (internal). */
223
+ interface ResolvedCustomWebhook {
224
+ type: "custom";
225
+ path: string;
226
+ verify?: (req: WebhookRequest) => Promise<boolean> | boolean;
227
+ handler: (ctx: WebhookContext, payload: Record<string, unknown>) => Promise<void>;
228
+ }
229
+ /** Union of resolved webhook types. */
230
+ type ResolvedWebhookConfig = ResolvedProviderWebhook | ResolvedCustomWebhook;
231
+ /**
232
+ * Define a provider-based webhook.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * export default defineWebhook({
237
+ * provider: "stripe",
238
+ * secret: { env: "STRIPE_WEBHOOK_SECRET" },
239
+ * events: {
240
+ * "checkout.session.completed": async (ctx, event) => {
241
+ * await ctx.db.insert("orders", { status: "paid" });
242
+ * },
243
+ * },
244
+ * });
245
+ * ```
246
+ */
247
+ declare function defineWebhook<P extends WebhookProvider>(config: ProviderWebhookConfig<P>): ResolvedProviderWebhook<P>;
248
+ /**
249
+ * Define a custom webhook with optional verification.
250
+ *
251
+ * @example
252
+ * ```ts
253
+ * export default defineWebhook({
254
+ * path: "/webhooks/livekit",
255
+ * verify: async (req) => req.headers["x-api-key"] === "secret",
256
+ * handler: async (ctx, payload) => {
257
+ * ctx.log.info("Received webhook", payload);
258
+ * },
259
+ * });
260
+ * ```
261
+ */
262
+ declare function defineWebhook(config: CustomWebhookConfig): ResolvedCustomWebhook;
263
+
264
+ /** Context injected into hook handlers. */
265
+ interface HookContext {
266
+ db: DBClient;
267
+ env: Record<string, string>;
268
+ log: Logger;
269
+ cache: CacheClient;
270
+ queue: {
271
+ enqueue(workerName: string, payload: unknown): Promise<string>;
272
+ };
273
+ palbase: PalbaseBindings;
274
+ projectId: string;
275
+ environmentId: string;
276
+ }
277
+ /** Payload for auth.onUserCreated hook. */
278
+ interface UserCreatedEvent {
279
+ user: {
280
+ id: string;
281
+ email: string;
282
+ role: string;
283
+ metadata: Record<string, unknown>;
284
+ createdAt: string;
285
+ };
286
+ }
287
+ /** Payload for auth.onSignIn hook. */
288
+ interface SignInEvent {
289
+ user: {
290
+ id: string;
291
+ email: string;
292
+ role: string;
293
+ };
294
+ provider: string;
295
+ timestamp: string;
296
+ }
297
+ /** Payload for auth.onSignOut hook. */
298
+ interface SignOutEvent {
299
+ user: {
300
+ id: string;
301
+ email: string;
302
+ };
303
+ timestamp: string;
304
+ }
305
+ /** Payload for auth.onPasswordReset hook. */
306
+ interface PasswordResetEvent {
307
+ user: {
308
+ id: string;
309
+ email: string;
310
+ };
311
+ timestamp: string;
312
+ }
313
+ /** Payload for storage.onFileUploaded hook. */
314
+ interface FileUploadedEvent {
315
+ file: {
316
+ id: string;
317
+ name: string;
318
+ bucket: string;
319
+ path: string;
320
+ size: number;
321
+ contentType: string;
322
+ };
323
+ }
324
+ /** Payload for storage.onFileDeleted hook. */
325
+ interface FileDeletedEvent {
326
+ file: {
327
+ id: string;
328
+ name: string;
329
+ bucket: string;
330
+ path: string;
331
+ };
332
+ }
333
+ /** Payload for documents.onDocumentCreated hook. */
334
+ interface DocumentCreatedEvent {
335
+ document: {
336
+ id: string;
337
+ collection: string;
338
+ data: Record<string, unknown>;
339
+ };
340
+ }
341
+ /** Payload for documents.onDocumentUpdated hook. */
342
+ interface DocumentUpdatedEvent {
343
+ document: {
344
+ id: string;
345
+ collection: string;
346
+ data: Record<string, unknown>;
347
+ previousData: Record<string, unknown>;
348
+ };
349
+ }
350
+ /** Payload for documents.onDocumentDeleted hook. */
351
+ interface DocumentDeletedEvent {
352
+ document: {
353
+ id: string;
354
+ collection: string;
355
+ data: Record<string, unknown>;
356
+ };
357
+ }
358
+ type HookHandler<TEvent> = (ctx: HookContext, event: TEvent) => Promise<void>;
359
+ /** Resolved hook configuration (internal). */
360
+ interface ResolvedHook<TEvent = unknown> {
361
+ module: string;
362
+ event: string;
363
+ handler: HookHandler<TEvent>;
364
+ }
365
+ declare const auth: {
366
+ onUserCreated(handler: HookHandler<UserCreatedEvent>): ResolvedHook<UserCreatedEvent>;
367
+ onSignIn(handler: HookHandler<SignInEvent>): ResolvedHook<SignInEvent>;
368
+ onSignOut(handler: HookHandler<SignOutEvent>): ResolvedHook<SignOutEvent>;
369
+ onPasswordReset(handler: HookHandler<PasswordResetEvent>): ResolvedHook<PasswordResetEvent>;
370
+ };
371
+ declare const storage: {
372
+ onFileUploaded(handler: HookHandler<FileUploadedEvent>): ResolvedHook<FileUploadedEvent>;
373
+ onFileDeleted(handler: HookHandler<FileDeletedEvent>): ResolvedHook<FileDeletedEvent>;
374
+ };
375
+ declare const documents: {
376
+ onDocumentCreated(handler: HookHandler<DocumentCreatedEvent>): ResolvedHook<DocumentCreatedEvent>;
377
+ onDocumentUpdated(handler: HookHandler<DocumentUpdatedEvent>): ResolvedHook<DocumentUpdatedEvent>;
378
+ onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
379
+ };
380
+
381
+ export { type BackoffStrategy, CacheClient, type CustomWebhookConfig, DBClient, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, EndpointContext, type EnvSecretRef, type FileDeletedEvent, type FileUploadedEvent, type HookContext, type HookHandler, HttpError, type JobConfig, type JobContext, Logger, PalbaseBindings, type PasswordResetEvent, type ProviderEventMap, type ProviderWebhookConfig, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, type SignInEvent, type SignOutEvent, type UserCreatedEvent, type WebhookContext, type WebhookEventHandler, type WebhookProvider, type WebhookRequest, type WorkerConfig, auth, defineJob, defineWebhook, defineWorker, documents, storage };