@palbase/backend 5.2.0 → 7.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/index.d.cts CHANGED
@@ -1,10 +1,10 @@
1
- import { C as CacheClient, b as PalbaseDocsClient, c as PalbaseFlagsClient, L as Logger, d as PalbaseNotificationsClient, Q as QueueClient, D as DBClient, e as PalbaseStorageClient, A as AuthSpec, R as RateLimitConfig, U as User$1 } from './endpoint-B3uVK6OL.cjs';
2
- export { f as AuthConfig, B as BadRequest, g as ClientInfo, h as Conflict, i as DBOps, E as ErrorDef, j as ErrorMap, k as ErrorThrowers, F as FileContext, l as Forbidden, H as HttpError, m as HttpMethod, M as Middleware, n as MiddlewareContext, o as MiddlewareHandler, N as NotFound, P as PBRequest, p as PalError, q as PalbaseAnalyticsClient, r as PalbaseAnalyticsManagementNamespace, s as PalbaseAnalyticsProperties, t as PalbaseAnalyticsQueryNamespace, u as PalbaseAttestAndroidParams, v as PalbaseAttestAndroidResult, w as PalbaseAttestiOSParams, x as PalbaseAttestiOSResult, y as PalbaseAuthClient, z as PalbaseBatchOverrideOperation, G as PalbaseBatchSetOverridesResult, I as PalbaseBindDeviceParams, J as PalbaseBucketClient, K as PalbaseClearAllOverridesResult, O as PalbaseClearOverrideResult, S as PalbaseCmsClient, T as PalbaseCmsFindOneOptions, V as PalbaseCmsFindOptions, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, ag as PalbaseFunctionsClient, ah as PalbaseFunnelQueryInput, ai as PalbaseFunnelResult, aj as PalbaseIdentifyTraits, ak as PalbaseInboxClient, al as PalbaseInboxListOptions, am as PalbaseInboxListResult, an as PalbaseInboxMessage, ao as PalbaseInboxSendParams, ap as PalbaseInboxSendResponse, aq as PalbaseInitialLink, ar as PalbaseInvokeOptions, as as PalbaseLink, at as PalbaseLinkAnalytics, au as PalbaseLinkDetails, av as PalbaseLinksClient, aw as PalbaseListLinksOptions, ax as PalbaseListLinksResult, ay as PalbaseListOptions, az as PalbaseMatchParams, aA as PalbaseMultiChannelResponse, aB as PalbaseOverviewResult, aC as PalbasePreferences, aD as PalbasePreferencesClient, aE as PalbasePublicUrlResponse, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, aK as PalbaseRealtimeChannel, aL as PalbaseRealtimeClient, aM as PalbaseRealtimeMessage, aN as PalbaseRegisterDeviceParams, aO as PalbaseResult, aP as PalbaseRetentionQueryInput, aQ as PalbaseRetentionResult, aR as PalbaseSession, aS as PalbaseSetOverrideResult, aT as PalbaseSetOverridesResult, aU as PalbaseSignedUrlResponse, aV as PalbaseSmsClient, aW as PalbaseSmsSendParams, aX as PalbaseSmsSendResponse, aY as PalbaseTransformOptions, aZ as PalbaseUpdateLinkParams, a_ as PalbaseUploadOptions, a$ as PalbaseUser, b0 as PalbaseUserDetailResult, b1 as PalbaseUsersQueryInput, b2 as PalbaseUsersResult, b3 as PalbaseVerifyRequestSignatureParams, b4 as PalbaseWhereOperator, b5 as TooManyRequests, b6 as TxClient, b7 as Unauthorized, b8 as defineMiddleware } from './endpoint-B3uVK6OL.cjs';
1
+ import { C as CacheClient, b as PalbaseDocsClient, c as PalbaseFlagsClient, L as Logger, d as PalbaseNotificationsClient, Q as QueueClient, e as PalbaseRealtimeClient, D as DBClient, f as PalbaseStorageClient, A as AuthSpec, R as RateLimitConfig, H as HttpError, U as User$1 } from './endpoint-BFgsOTiL.cjs';
2
+ export { g as AuthConfig, B as BadRequest, h as ClientInfo, i as Conflict, j as DBOps, E as ErrorDef, k as ErrorMap, l as ErrorThrowers, F as FileContext, m as Forbidden, n as HttpMethod, M as Middleware, o as MiddlewareContext, p as MiddlewareHandler, N as NotFound, P as PBRequest, q as PalError, r as PalbaseAnalyticsClient, s as PalbaseAnalyticsManagementNamespace, t as PalbaseAnalyticsProperties, u as PalbaseAnalyticsQueryNamespace, v as PalbaseAttestAndroidParams, w as PalbaseAttestAndroidResult, x as PalbaseAttestiOSParams, y as PalbaseAttestiOSResult, z as PalbaseAuthClient, G as PalbaseBatchOverrideOperation, I as PalbaseBatchSetOverridesResult, J as PalbaseBindDeviceParams, K as PalbaseBucketClient, O as PalbaseClearAllOverridesResult, S as PalbaseClearOverrideResult, T as PalbaseCmsClient, V as PalbaseCmsFindOneOptions, W as PalbaseCmsFindOptions, X as PalbaseCohortQueryInput, Y as PalbaseCohortResult, Z as PalbaseCollectionRef, _ as PalbaseCountQueryInput, $ as PalbaseCountResult, a0 as PalbaseCreateLinkParams, a1 as PalbaseDeviceInfo, a2 as PalbaseDeviceTokenView, a3 as PalbaseDocumentRef, a4 as PalbaseDocumentSnapshot, a5 as PalbaseEmailClient, a6 as PalbaseEmailSendParams, a7 as PalbaseEmailSendResponse, a8 as PalbaseEventNamesResult, a9 as PalbaseEventsQueryInput, aa as PalbaseEventsResult, ab as PalbaseFileObject, ac as PalbaseFlag, ad as PalbaseFlagContext, ae as PalbaseFlagSource, af as PalbaseFlagValue, ag as PalbaseFlagVariant, ah as PalbaseFlagsServiceClient, ai as PalbaseFunctionsClient, aj as PalbaseFunnelQueryInput, ak as PalbaseFunnelResult, al as PalbaseIdentifyTraits, am as PalbaseInboxClient, an as PalbaseInboxListOptions, ao as PalbaseInboxListResult, ap as PalbaseInboxMessage, aq as PalbaseInboxSendParams, ar as PalbaseInboxSendResponse, as as PalbaseInitialLink, at as PalbaseInvokeOptions, au as PalbaseLink, av as PalbaseLinkAnalytics, aw as PalbaseLinkDetails, ax as PalbaseLinksClient, ay as PalbaseListLinksOptions, az as PalbaseListLinksResult, aA as PalbaseListOptions, aB as PalbaseMatchParams, aC as PalbaseMultiChannelResponse, aD as PalbaseOverviewResult, aE as PalbasePreferences, aF as PalbasePreferencesClient, aG as PalbasePublicUrlResponse, aH as PalbasePushClient, aI as PalbasePushSendParams, aJ as PalbasePushSendResponse, aK as PalbaseQrCodeOptions, aL as PalbaseQuerySnapshot, aM as PalbaseRegisterDeviceParams, aN as PalbaseResult, aO as PalbaseRetentionQueryInput, aP as PalbaseRetentionResult, aQ as PalbaseSession, aR as PalbaseSetOverrideResult, aS as PalbaseSetOverridesResult, aT as PalbaseSignedUrlResponse, aU as PalbaseSmsClient, aV as PalbaseSmsSendParams, aW as PalbaseSmsSendResponse, aX as PalbaseTransformOptions, aY as PalbaseUpdateLinkParams, aZ as PalbaseUploadOptions, a_ as PalbaseUser, a$ as PalbaseUserDetailResult, b0 as PalbaseUsersQueryInput, b1 as PalbaseUsersResult, b2 as PalbaseVerifyRequestSignatureParams, b3 as PalbaseWhereOperator, b4 as TooManyRequests, b5 as TxClient, b6 as Unauthorized, b7 as defineMiddleware } from './endpoint-BFgsOTiL.cjs';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
- import { E as EnvTypedDatabase, S as SchemaDef } from './index-BAEWl60b.cjs';
5
- export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, g as EnvTypedTable, h as EnvTypedTx, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TypedDB, q as TypedTable, r as TypedTx, s as boolean, t as defineSchema, u as enumType, v as integer, w as isPalbaseExtension, x as jsonb, y as makeTypedDB, z as policy, A as text, B as timestamp, D as uuid } from './index-BAEWl60b.cjs';
4
+ import { E as EnvTypedDatabase, S as SchemaDef } from './index-CE31P7Dt.cjs';
5
+ export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, g as EnvTypedTable, h as EnvTypedTx, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TypedDB, q as TypedTable, r as TypedTx, s as boolean, t as defineSchema, u as enumType, v as integer, w as isPalbaseExtension, x as jsonb, y as makeTypedDB, z as policy, A as text, B as timestamp, D as uuid } from './index-CE31P7Dt.cjs';
6
6
  export { TableTypes, Tables } from './db/env.cjs';
7
- import { ZodTypeAny } from 'zod';
7
+ import { ZodTypeAny, z } from 'zod';
8
8
  export { z } from 'zod';
9
9
 
10
10
  /**
@@ -50,9 +50,12 @@ export { z } from 'zod';
50
50
 
51
51
  /** The set of live clients the runtime injects per request scope.
52
52
  *
53
- * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They
54
- * are not exposed as backend handler singletons (auth lives on the client SDK;
55
- * the rest are out of scope for backend endpoints). */
53
+ * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but
54
+ * cannot hold a subscription socket `subscribe()` lives on the client SDK).
55
+ *
56
+ * EXCLUDED on purpose: Functions, CMS, Links, Analytics, Auth. They are not
57
+ * exposed as backend handler singletons (auth lives on the client SDK; the rest
58
+ * are out of scope for backend endpoints). */
56
59
  interface RuntimeServices {
57
60
  Database: DBClient;
58
61
  Documents: PalbaseDocsClient;
@@ -62,6 +65,7 @@ interface RuntimeServices {
62
65
  Log: Logger;
63
66
  Notifications: PalbaseNotificationsClient;
64
67
  Flags: PalbaseFlagsClient;
68
+ Realtime: PalbaseRealtimeClient;
65
69
  }
66
70
  /**
67
71
  * Per-request store. The persistent runtime runs each request inside
@@ -125,8 +129,37 @@ declare const Queue: QueueClient;
125
129
  declare const Log: Logger;
126
130
  /** Push / email / SMS / in-app notifications. */
127
131
  declare const Notifications: PalbaseNotificationsClient;
128
- /** Feature flags. */
132
+ /**
133
+ * Feature flags.
134
+ *
135
+ * Mirrors the `Database` / `Database.asService()` model. The default surface is
136
+ * RLS-equivalent for flags: reads resolve against the CURRENT request user and
137
+ * `Flags.setOverride(key, value)` writes an override for that same signed-in
138
+ * user (no userId argument, no admin power). Cross-user admin writes
139
+ * (`setOverrideForUser`, …) live behind `Flags.asService()` — explicit and
140
+ * greppable, just like `Database.asService()`.
141
+ *
142
+ * @example
143
+ * import { Flags } from "@palbase/backend";
144
+ *
145
+ * if (await Flags.isEnabled("new_checkout")) { ... } // current user
146
+ * await Flags.setOverride("new_checkout", true); // current user
147
+ * await Flags.asService().setOverrideForUser("u_9", "x", true); // cross-user
148
+ */
129
149
  declare const Flags: PalbaseFlagsClient;
150
+ /**
151
+ * The Realtime broadcast singleton for the current request scope. Backend-side
152
+ * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —
153
+ * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:
154
+ * `broadcast` resolves once accepted (or with an `error`), never blocking the
155
+ * handler on subscribers.
156
+ *
157
+ * @example
158
+ * import { Realtime } from "@palbase/backend";
159
+ *
160
+ * await Realtime.broadcast("room:42", "message", { text, from: user.id });
161
+ */
162
+ declare const Realtime: PalbaseRealtimeClient;
130
163
 
131
164
  /**
132
165
  * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`
@@ -679,6 +712,20 @@ interface RouteOptions {
679
712
  /** Per-route rate limit. */
680
713
  rateLimit?: RateLimitConfig;
681
714
  }
715
+ /** One inferred throw site: the error CLASS name (e.g. "TodoLocked") and its
716
+ * wire code (e.g. "todo_locked"). `status`, `hasData`, and the data JSON schema
717
+ * are NOT carried here — they resolve from the error registry by `code` at
718
+ * extract/openapi time (single source of truth). */
719
+ interface ThrowDescriptor {
720
+ name: string;
721
+ code: string;
722
+ }
723
+ /** Attach the inferred throw descriptors to the route for `fnName` (called by
724
+ * the stager-injected IIFE that carries the throw analysis result — the
725
+ * `recordReturn` twin). If the route does not exist yet, the descriptors are
726
+ * buffered (THROWS_BUFFER) and drained into the route by `recordRoute` when the
727
+ * method decorator runs. */
728
+ declare function recordThrows(target: object, fnName: string, throws: ThrowDescriptor[]): void;
682
729
 
683
730
  /** A legacy method decorator. */
684
731
  type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
@@ -721,6 +768,49 @@ declare function TraceId(): ParameterDecorator;
721
768
  /** `@Req()` — inject the raw request object (escape hatch, `: PBRequest`). */
722
769
  declare function Req(): ParameterDecorator;
723
770
 
771
+ /** One registered error: the wire code, HTTP status, the class name the
772
+ * analyzer sees, the optional data payload schema, and whether it is one of the
773
+ * pre-seeded built-in named classes. */
774
+ interface RegisteredError {
775
+ code: string;
776
+ status: number;
777
+ className: string;
778
+ dataSchema?: ZodTypeAny;
779
+ /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec
780
+ * twins would emit an identical `data` schema for this error. */
781
+ dataDigest?: string;
782
+ builtin: boolean;
783
+ }
784
+ /** Get (creating + pre-seeding if absent) the project-global error registry,
785
+ * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a
786
+ * process shares the one registry. */
787
+ declare function getErrorRegistry(): Map<string, RegisteredError>;
788
+ /** Class returned for schema-bearing errors: ctor(data, message?). */
789
+ interface DefinedErrorWithData<S extends ZodTypeAny> {
790
+ new (data: z.input<S>, message?: string): HttpError;
791
+ readonly code: string;
792
+ readonly status: number;
793
+ }
794
+ /** Class returned for schema-less errors: ctor(message?). */
795
+ interface DefinedError {
796
+ new (message?: string): HttpError;
797
+ readonly code: string;
798
+ readonly status: number;
799
+ }
800
+ /**
801
+ * Define a project error class. MUST be called with literal args (string
802
+ * literal `code`, numeric literal `status`) at module top level — the deploy
803
+ * stager's static analyzer reads those literals to resolve throw sites.
804
+ *
805
+ * @example
806
+ * // models/todos/errors.ts
807
+ * export const TodoLocked = defineError("todo_locked", 409, z.object({ retryAfter: z.number() }));
808
+ * // services/todo.service.ts
809
+ * throw new TodoLocked({ retryAfter: 30 });
810
+ */
811
+ declare function defineError<S extends ZodTypeAny>(code: string, status: number, dataSchema: S): DefinedErrorWithData<S>;
812
+ declare function defineError(code: string, status: number): DefinedError;
813
+
724
814
  /** Non-service, per-invocation data for background worker handlers.
725
815
  * Services (Database, Log, …) are imported as singletons, not passed here. */
726
816
  interface WorkerMeta {
@@ -1173,4 +1263,4 @@ declare const documents: {
1173
1263
  onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
1174
1264
  };
1175
1265
 
1176
- export { type AcsOptions, type ApnsOptions, type BackoffStrategy, Body, type BucketDef, type BucketOptions, Cache, CacheClient, Client, Controller, type ControllerOptions, type CustomWebhookConfig, DBClient, Database, Delete, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, EnvTypedDatabase, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagOptions, type FlagType, type FlagValue, Flags, type FlagsConfig, type FlagsInput, Get, Headers, type HookHandler, type HookMeta, type HttpMethodUpper, type JobConfig, type JobMeta, Log, Logger, NOTIFICATIONS_CONFIG_KIND, Notifications, type NotificationsConfig, type NotificationsInput, OptionalUser, PROVIDER_CATALOG, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, Param, type PasswordResetEvent, Patch, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderEventMap, type ProviderName, type ProviderOptions, type ProviderWebhookConfig, Put, Query, Queue, QueueClient, RESERVED_SECRET_PREFIX, RateLimitConfig, Req, RequestId, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, Resource, type ResourceEnv, type RouteOptions, type RuntimeServices, STORAGE_CONFIG_KIND, SchemaDef, type SendgridOptions, type SesOptions, type SignInEvent, type SignOutEvent, type SmtpOptions, Storage, type StorageConfig, type StorageInput, TraceId, type TwilioOptions, User, type UserCreatedEvent, User$1 as UserT, type WebhookEventHandler, type WebhookMeta, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerMeta, __getRuntime, __registerResource, __requestALS, __runResourceBoot, __runWithRuntime, __setRuntime, __shutdownResources, auth, bucket, buildProvider, defineFlags, defineJob, defineNotifications, defineStorage, defineWebhook, defineWorker, documents, flag, makeEnvDts, parseFileSizeLimit, reservedSecretKey, storage };
1266
+ export { type AcsOptions, type ApnsOptions, type BackoffStrategy, Body, type BucketDef, type BucketOptions, Cache, CacheClient, Client, Controller, type ControllerOptions, type CustomWebhookConfig, DBClient, Database, type DefinedError, type DefinedErrorWithData, Delete, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, EnvTypedDatabase, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagOptions, type FlagType, type FlagValue, Flags, type FlagsConfig, type FlagsInput, Get, Headers, type HookHandler, type HookMeta, HttpError, type HttpMethodUpper, type JobConfig, type JobMeta, Log, Logger, NOTIFICATIONS_CONFIG_KIND, Notifications, type NotificationsConfig, type NotificationsInput, OptionalUser, PROVIDER_CATALOG, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseRealtimeClient, PalbaseStorageClient, Param, type PasswordResetEvent, Patch, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderEventMap, type ProviderName, type ProviderOptions, type ProviderWebhookConfig, Put, Query, Queue, QueueClient, RESERVED_SECRET_PREFIX, RateLimitConfig, Realtime, type RegisteredError, Req, RequestId, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, Resource, type ResourceEnv, type RouteOptions, type RuntimeServices, STORAGE_CONFIG_KIND, SchemaDef, type SendgridOptions, type SesOptions, type SignInEvent, type SignOutEvent, type SmtpOptions, Storage, type StorageConfig, type StorageInput, type ThrowDescriptor, TraceId, type TwilioOptions, User, type UserCreatedEvent, User$1 as UserT, type WebhookEventHandler, type WebhookMeta, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerMeta, __getRuntime, __registerResource, __requestALS, __runResourceBoot, __runWithRuntime, __setRuntime, __shutdownResources, auth, bucket, buildProvider, defineError, defineFlags, defineJob, defineNotifications, defineStorage, defineWebhook, defineWorker, documents, flag, getErrorRegistry, makeEnvDts, parseFileSizeLimit, recordThrows, reservedSecretKey, storage };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { C as CacheClient, b as PalbaseDocsClient, c as PalbaseFlagsClient, L as Logger, d as PalbaseNotificationsClient, Q as QueueClient, D as DBClient, e as PalbaseStorageClient, A as AuthSpec, R as RateLimitConfig, U as User$1 } from './endpoint-B3uVK6OL.js';
2
- export { f as AuthConfig, B as BadRequest, g as ClientInfo, h as Conflict, i as DBOps, E as ErrorDef, j as ErrorMap, k as ErrorThrowers, F as FileContext, l as Forbidden, H as HttpError, m as HttpMethod, M as Middleware, n as MiddlewareContext, o as MiddlewareHandler, N as NotFound, P as PBRequest, p as PalError, q as PalbaseAnalyticsClient, r as PalbaseAnalyticsManagementNamespace, s as PalbaseAnalyticsProperties, t as PalbaseAnalyticsQueryNamespace, u as PalbaseAttestAndroidParams, v as PalbaseAttestAndroidResult, w as PalbaseAttestiOSParams, x as PalbaseAttestiOSResult, y as PalbaseAuthClient, z as PalbaseBatchOverrideOperation, G as PalbaseBatchSetOverridesResult, I as PalbaseBindDeviceParams, J as PalbaseBucketClient, K as PalbaseClearAllOverridesResult, O as PalbaseClearOverrideResult, S as PalbaseCmsClient, T as PalbaseCmsFindOneOptions, V as PalbaseCmsFindOptions, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, ag as PalbaseFunctionsClient, ah as PalbaseFunnelQueryInput, ai as PalbaseFunnelResult, aj as PalbaseIdentifyTraits, ak as PalbaseInboxClient, al as PalbaseInboxListOptions, am as PalbaseInboxListResult, an as PalbaseInboxMessage, ao as PalbaseInboxSendParams, ap as PalbaseInboxSendResponse, aq as PalbaseInitialLink, ar as PalbaseInvokeOptions, as as PalbaseLink, at as PalbaseLinkAnalytics, au as PalbaseLinkDetails, av as PalbaseLinksClient, aw as PalbaseListLinksOptions, ax as PalbaseListLinksResult, ay as PalbaseListOptions, az as PalbaseMatchParams, aA as PalbaseMultiChannelResponse, aB as PalbaseOverviewResult, aC as PalbasePreferences, aD as PalbasePreferencesClient, aE as PalbasePublicUrlResponse, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, aK as PalbaseRealtimeChannel, aL as PalbaseRealtimeClient, aM as PalbaseRealtimeMessage, aN as PalbaseRegisterDeviceParams, aO as PalbaseResult, aP as PalbaseRetentionQueryInput, aQ as PalbaseRetentionResult, aR as PalbaseSession, aS as PalbaseSetOverrideResult, aT as PalbaseSetOverridesResult, aU as PalbaseSignedUrlResponse, aV as PalbaseSmsClient, aW as PalbaseSmsSendParams, aX as PalbaseSmsSendResponse, aY as PalbaseTransformOptions, aZ as PalbaseUpdateLinkParams, a_ as PalbaseUploadOptions, a$ as PalbaseUser, b0 as PalbaseUserDetailResult, b1 as PalbaseUsersQueryInput, b2 as PalbaseUsersResult, b3 as PalbaseVerifyRequestSignatureParams, b4 as PalbaseWhereOperator, b5 as TooManyRequests, b6 as TxClient, b7 as Unauthorized, b8 as defineMiddleware } from './endpoint-B3uVK6OL.js';
1
+ import { C as CacheClient, b as PalbaseDocsClient, c as PalbaseFlagsClient, L as Logger, d as PalbaseNotificationsClient, Q as QueueClient, e as PalbaseRealtimeClient, D as DBClient, f as PalbaseStorageClient, A as AuthSpec, R as RateLimitConfig, H as HttpError, U as User$1 } from './endpoint-BFgsOTiL.js';
2
+ export { g as AuthConfig, B as BadRequest, h as ClientInfo, i as Conflict, j as DBOps, E as ErrorDef, k as ErrorMap, l as ErrorThrowers, F as FileContext, m as Forbidden, n as HttpMethod, M as Middleware, o as MiddlewareContext, p as MiddlewareHandler, N as NotFound, P as PBRequest, q as PalError, r as PalbaseAnalyticsClient, s as PalbaseAnalyticsManagementNamespace, t as PalbaseAnalyticsProperties, u as PalbaseAnalyticsQueryNamespace, v as PalbaseAttestAndroidParams, w as PalbaseAttestAndroidResult, x as PalbaseAttestiOSParams, y as PalbaseAttestiOSResult, z as PalbaseAuthClient, G as PalbaseBatchOverrideOperation, I as PalbaseBatchSetOverridesResult, J as PalbaseBindDeviceParams, K as PalbaseBucketClient, O as PalbaseClearAllOverridesResult, S as PalbaseClearOverrideResult, T as PalbaseCmsClient, V as PalbaseCmsFindOneOptions, W as PalbaseCmsFindOptions, X as PalbaseCohortQueryInput, Y as PalbaseCohortResult, Z as PalbaseCollectionRef, _ as PalbaseCountQueryInput, $ as PalbaseCountResult, a0 as PalbaseCreateLinkParams, a1 as PalbaseDeviceInfo, a2 as PalbaseDeviceTokenView, a3 as PalbaseDocumentRef, a4 as PalbaseDocumentSnapshot, a5 as PalbaseEmailClient, a6 as PalbaseEmailSendParams, a7 as PalbaseEmailSendResponse, a8 as PalbaseEventNamesResult, a9 as PalbaseEventsQueryInput, aa as PalbaseEventsResult, ab as PalbaseFileObject, ac as PalbaseFlag, ad as PalbaseFlagContext, ae as PalbaseFlagSource, af as PalbaseFlagValue, ag as PalbaseFlagVariant, ah as PalbaseFlagsServiceClient, ai as PalbaseFunctionsClient, aj as PalbaseFunnelQueryInput, ak as PalbaseFunnelResult, al as PalbaseIdentifyTraits, am as PalbaseInboxClient, an as PalbaseInboxListOptions, ao as PalbaseInboxListResult, ap as PalbaseInboxMessage, aq as PalbaseInboxSendParams, ar as PalbaseInboxSendResponse, as as PalbaseInitialLink, at as PalbaseInvokeOptions, au as PalbaseLink, av as PalbaseLinkAnalytics, aw as PalbaseLinkDetails, ax as PalbaseLinksClient, ay as PalbaseListLinksOptions, az as PalbaseListLinksResult, aA as PalbaseListOptions, aB as PalbaseMatchParams, aC as PalbaseMultiChannelResponse, aD as PalbaseOverviewResult, aE as PalbasePreferences, aF as PalbasePreferencesClient, aG as PalbasePublicUrlResponse, aH as PalbasePushClient, aI as PalbasePushSendParams, aJ as PalbasePushSendResponse, aK as PalbaseQrCodeOptions, aL as PalbaseQuerySnapshot, aM as PalbaseRegisterDeviceParams, aN as PalbaseResult, aO as PalbaseRetentionQueryInput, aP as PalbaseRetentionResult, aQ as PalbaseSession, aR as PalbaseSetOverrideResult, aS as PalbaseSetOverridesResult, aT as PalbaseSignedUrlResponse, aU as PalbaseSmsClient, aV as PalbaseSmsSendParams, aW as PalbaseSmsSendResponse, aX as PalbaseTransformOptions, aY as PalbaseUpdateLinkParams, aZ as PalbaseUploadOptions, a_ as PalbaseUser, a$ as PalbaseUserDetailResult, b0 as PalbaseUsersQueryInput, b1 as PalbaseUsersResult, b2 as PalbaseVerifyRequestSignatureParams, b3 as PalbaseWhereOperator, b4 as TooManyRequests, b5 as TxClient, b6 as Unauthorized, b7 as defineMiddleware } from './endpoint-BFgsOTiL.js';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
- import { E as EnvTypedDatabase, S as SchemaDef } from './index-D9uLjEhB.js';
5
- export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, g as EnvTypedTable, h as EnvTypedTx, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TypedDB, q as TypedTable, r as TypedTx, s as boolean, t as defineSchema, u as enumType, v as integer, w as isPalbaseExtension, x as jsonb, y as makeTypedDB, z as policy, A as text, B as timestamp, D as uuid } from './index-D9uLjEhB.js';
4
+ import { E as EnvTypedDatabase, S as SchemaDef } from './index-E7CMoir3.js';
5
+ export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, g as EnvTypedTable, h as EnvTypedTx, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TypedDB, q as TypedTable, r as TypedTx, s as boolean, t as defineSchema, u as enumType, v as integer, w as isPalbaseExtension, x as jsonb, y as makeTypedDB, z as policy, A as text, B as timestamp, D as uuid } from './index-E7CMoir3.js';
6
6
  export { TableTypes, Tables } from './db/env.js';
7
- import { ZodTypeAny } from 'zod';
7
+ import { ZodTypeAny, z } from 'zod';
8
8
  export { z } from 'zod';
9
9
 
10
10
  /**
@@ -50,9 +50,12 @@ export { z } from 'zod';
50
50
 
51
51
  /** The set of live clients the runtime injects per request scope.
52
52
  *
53
- * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They
54
- * are not exposed as backend handler singletons (auth lives on the client SDK;
55
- * the rest are out of scope for backend endpoints). */
53
+ * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but
54
+ * cannot hold a subscription socket `subscribe()` lives on the client SDK).
55
+ *
56
+ * EXCLUDED on purpose: Functions, CMS, Links, Analytics, Auth. They are not
57
+ * exposed as backend handler singletons (auth lives on the client SDK; the rest
58
+ * are out of scope for backend endpoints). */
56
59
  interface RuntimeServices {
57
60
  Database: DBClient;
58
61
  Documents: PalbaseDocsClient;
@@ -62,6 +65,7 @@ interface RuntimeServices {
62
65
  Log: Logger;
63
66
  Notifications: PalbaseNotificationsClient;
64
67
  Flags: PalbaseFlagsClient;
68
+ Realtime: PalbaseRealtimeClient;
65
69
  }
66
70
  /**
67
71
  * Per-request store. The persistent runtime runs each request inside
@@ -125,8 +129,37 @@ declare const Queue: QueueClient;
125
129
  declare const Log: Logger;
126
130
  /** Push / email / SMS / in-app notifications. */
127
131
  declare const Notifications: PalbaseNotificationsClient;
128
- /** Feature flags. */
132
+ /**
133
+ * Feature flags.
134
+ *
135
+ * Mirrors the `Database` / `Database.asService()` model. The default surface is
136
+ * RLS-equivalent for flags: reads resolve against the CURRENT request user and
137
+ * `Flags.setOverride(key, value)` writes an override for that same signed-in
138
+ * user (no userId argument, no admin power). Cross-user admin writes
139
+ * (`setOverrideForUser`, …) live behind `Flags.asService()` — explicit and
140
+ * greppable, just like `Database.asService()`.
141
+ *
142
+ * @example
143
+ * import { Flags } from "@palbase/backend";
144
+ *
145
+ * if (await Flags.isEnabled("new_checkout")) { ... } // current user
146
+ * await Flags.setOverride("new_checkout", true); // current user
147
+ * await Flags.asService().setOverrideForUser("u_9", "x", true); // cross-user
148
+ */
129
149
  declare const Flags: PalbaseFlagsClient;
150
+ /**
151
+ * The Realtime broadcast singleton for the current request scope. Backend-side
152
+ * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —
153
+ * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:
154
+ * `broadcast` resolves once accepted (or with an `error`), never blocking the
155
+ * handler on subscribers.
156
+ *
157
+ * @example
158
+ * import { Realtime } from "@palbase/backend";
159
+ *
160
+ * await Realtime.broadcast("room:42", "message", { text, from: user.id });
161
+ */
162
+ declare const Realtime: PalbaseRealtimeClient;
130
163
 
131
164
  /**
132
165
  * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`
@@ -679,6 +712,20 @@ interface RouteOptions {
679
712
  /** Per-route rate limit. */
680
713
  rateLimit?: RateLimitConfig;
681
714
  }
715
+ /** One inferred throw site: the error CLASS name (e.g. "TodoLocked") and its
716
+ * wire code (e.g. "todo_locked"). `status`, `hasData`, and the data JSON schema
717
+ * are NOT carried here — they resolve from the error registry by `code` at
718
+ * extract/openapi time (single source of truth). */
719
+ interface ThrowDescriptor {
720
+ name: string;
721
+ code: string;
722
+ }
723
+ /** Attach the inferred throw descriptors to the route for `fnName` (called by
724
+ * the stager-injected IIFE that carries the throw analysis result — the
725
+ * `recordReturn` twin). If the route does not exist yet, the descriptors are
726
+ * buffered (THROWS_BUFFER) and drained into the route by `recordRoute` when the
727
+ * method decorator runs. */
728
+ declare function recordThrows(target: object, fnName: string, throws: ThrowDescriptor[]): void;
682
729
 
683
730
  /** A legacy method decorator. */
684
731
  type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
@@ -721,6 +768,49 @@ declare function TraceId(): ParameterDecorator;
721
768
  /** `@Req()` — inject the raw request object (escape hatch, `: PBRequest`). */
722
769
  declare function Req(): ParameterDecorator;
723
770
 
771
+ /** One registered error: the wire code, HTTP status, the class name the
772
+ * analyzer sees, the optional data payload schema, and whether it is one of the
773
+ * pre-seeded built-in named classes. */
774
+ interface RegisteredError {
775
+ code: string;
776
+ status: number;
777
+ className: string;
778
+ dataSchema?: ZodTypeAny;
779
+ /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec
780
+ * twins would emit an identical `data` schema for this error. */
781
+ dataDigest?: string;
782
+ builtin: boolean;
783
+ }
784
+ /** Get (creating + pre-seeding if absent) the project-global error registry,
785
+ * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a
786
+ * process shares the one registry. */
787
+ declare function getErrorRegistry(): Map<string, RegisteredError>;
788
+ /** Class returned for schema-bearing errors: ctor(data, message?). */
789
+ interface DefinedErrorWithData<S extends ZodTypeAny> {
790
+ new (data: z.input<S>, message?: string): HttpError;
791
+ readonly code: string;
792
+ readonly status: number;
793
+ }
794
+ /** Class returned for schema-less errors: ctor(message?). */
795
+ interface DefinedError {
796
+ new (message?: string): HttpError;
797
+ readonly code: string;
798
+ readonly status: number;
799
+ }
800
+ /**
801
+ * Define a project error class. MUST be called with literal args (string
802
+ * literal `code`, numeric literal `status`) at module top level — the deploy
803
+ * stager's static analyzer reads those literals to resolve throw sites.
804
+ *
805
+ * @example
806
+ * // models/todos/errors.ts
807
+ * export const TodoLocked = defineError("todo_locked", 409, z.object({ retryAfter: z.number() }));
808
+ * // services/todo.service.ts
809
+ * throw new TodoLocked({ retryAfter: 30 });
810
+ */
811
+ declare function defineError<S extends ZodTypeAny>(code: string, status: number, dataSchema: S): DefinedErrorWithData<S>;
812
+ declare function defineError(code: string, status: number): DefinedError;
813
+
724
814
  /** Non-service, per-invocation data for background worker handlers.
725
815
  * Services (Database, Log, …) are imported as singletons, not passed here. */
726
816
  interface WorkerMeta {
@@ -1173,4 +1263,4 @@ declare const documents: {
1173
1263
  onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
1174
1264
  };
1175
1265
 
1176
- export { type AcsOptions, type ApnsOptions, type BackoffStrategy, Body, type BucketDef, type BucketOptions, Cache, CacheClient, Client, Controller, type ControllerOptions, type CustomWebhookConfig, DBClient, Database, Delete, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, EnvTypedDatabase, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagOptions, type FlagType, type FlagValue, Flags, type FlagsConfig, type FlagsInput, Get, Headers, type HookHandler, type HookMeta, type HttpMethodUpper, type JobConfig, type JobMeta, Log, Logger, NOTIFICATIONS_CONFIG_KIND, Notifications, type NotificationsConfig, type NotificationsInput, OptionalUser, PROVIDER_CATALOG, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, Param, type PasswordResetEvent, Patch, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderEventMap, type ProviderName, type ProviderOptions, type ProviderWebhookConfig, Put, Query, Queue, QueueClient, RESERVED_SECRET_PREFIX, RateLimitConfig, Req, RequestId, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, Resource, type ResourceEnv, type RouteOptions, type RuntimeServices, STORAGE_CONFIG_KIND, SchemaDef, type SendgridOptions, type SesOptions, type SignInEvent, type SignOutEvent, type SmtpOptions, Storage, type StorageConfig, type StorageInput, TraceId, type TwilioOptions, User, type UserCreatedEvent, User$1 as UserT, type WebhookEventHandler, type WebhookMeta, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerMeta, __getRuntime, __registerResource, __requestALS, __runResourceBoot, __runWithRuntime, __setRuntime, __shutdownResources, auth, bucket, buildProvider, defineFlags, defineJob, defineNotifications, defineStorage, defineWebhook, defineWorker, documents, flag, makeEnvDts, parseFileSizeLimit, reservedSecretKey, storage };
1266
+ export { type AcsOptions, type ApnsOptions, type BackoffStrategy, Body, type BucketDef, type BucketOptions, Cache, CacheClient, Client, Controller, type ControllerOptions, type CustomWebhookConfig, DBClient, Database, type DefinedError, type DefinedErrorWithData, Delete, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, EnvTypedDatabase, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagOptions, type FlagType, type FlagValue, Flags, type FlagsConfig, type FlagsInput, Get, Headers, type HookHandler, type HookMeta, HttpError, type HttpMethodUpper, type JobConfig, type JobMeta, Log, Logger, NOTIFICATIONS_CONFIG_KIND, Notifications, type NotificationsConfig, type NotificationsInput, OptionalUser, PROVIDER_CATALOG, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseRealtimeClient, PalbaseStorageClient, Param, type PasswordResetEvent, Patch, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderEventMap, type ProviderName, type ProviderOptions, type ProviderWebhookConfig, Put, Query, Queue, QueueClient, RESERVED_SECRET_PREFIX, RateLimitConfig, Realtime, type RegisteredError, Req, RequestId, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, Resource, type ResourceEnv, type RouteOptions, type RuntimeServices, STORAGE_CONFIG_KIND, SchemaDef, type SendgridOptions, type SesOptions, type SignInEvent, type SignOutEvent, type SmtpOptions, Storage, type StorageConfig, type StorageInput, type ThrowDescriptor, TraceId, type TwilioOptions, User, type UserCreatedEvent, User$1 as UserT, type WebhookEventHandler, type WebhookMeta, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerMeta, __getRuntime, __registerResource, __requestALS, __runResourceBoot, __runWithRuntime, __setRuntime, __shutdownResources, auth, bucket, buildProvider, defineError, defineFlags, defineJob, defineNotifications, defineStorage, defineWebhook, defineWorker, documents, flag, getErrorRegistry, makeEnvDts, parseFileSizeLimit, recordThrows, reservedSecretKey, storage };
package/dist/index.js CHANGED
@@ -6,12 +6,13 @@ import {
6
6
  Log,
7
7
  Notifications,
8
8
  Queue,
9
+ Realtime,
9
10
  Storage,
10
11
  __getRuntime,
11
12
  __requestALS,
12
13
  __runWithRuntime,
13
14
  __setRuntime
14
- } from "./chunk-WUQO76NW.js";
15
+ } from "./chunk-SWT2QR5F.js";
15
16
  import {
16
17
  EXTENSION_DEPENDENCIES,
17
18
  PALBASE_EXTENSIONS,
@@ -399,6 +400,7 @@ function Controller(basePath, options = {}) {
399
400
  var ROUTES = /* @__PURE__ */ Symbol.for("palbase.backend.routes");
400
401
  var PARAM_BUFFER = /* @__PURE__ */ Symbol.for("palbase.backend.paramBuffer");
401
402
  var RETURN_BUFFER = /* @__PURE__ */ Symbol.for("palbase.backend.returnBuffer");
403
+ var THROWS_BUFFER = /* @__PURE__ */ Symbol.for("palbase.backend.throwsBuffer");
402
404
  function carrierOf(target) {
403
405
  const ctor = typeof target === "function" ? target : target.constructor ?? target;
404
406
  return ctor;
@@ -425,6 +427,10 @@ function recordRoute(target, fnName, method, subpath, options) {
425
427
  if (returnBuffer && returnBuffer[fnName] !== void 0) {
426
428
  route.returnSchema = returnBuffer[fnName];
427
429
  }
430
+ const throwsBuffer = carrier[THROWS_BUFFER];
431
+ if (throwsBuffer && throwsBuffer[fnName] !== void 0) {
432
+ route.throws = throwsBuffer[fnName];
433
+ }
428
434
  routes.push(route);
429
435
  }
430
436
  function recordParam(target, fnName, meta) {
@@ -440,6 +446,20 @@ function recordParam(target, fnName, meta) {
440
446
  }
441
447
  }
442
448
  }
449
+ function recordThrows(target, fnName, throws) {
450
+ const carrier = carrierOf(target);
451
+ const routes = carrier[ROUTES];
452
+ const route = routes?.find((r) => r.fnName === fnName);
453
+ if (route) {
454
+ route.throws = throws;
455
+ return;
456
+ }
457
+ if (!Object.prototype.hasOwnProperty.call(carrier, THROWS_BUFFER)) {
458
+ carrier[THROWS_BUFFER] = {};
459
+ }
460
+ const throwsBuffer = carrier[THROWS_BUFFER];
461
+ if (throwsBuffer) throwsBuffer[fnName] = throws;
462
+ }
443
463
 
444
464
  // src/decorators/methods.ts
445
465
  function makeMethodDecorator(method) {
@@ -586,6 +606,101 @@ var TooManyRequests = class extends NamedHttpError {
586
606
  }
587
607
  };
588
608
 
609
+ // src/error-registry.ts
610
+ import {
611
+ OpenAPIRegistry,
612
+ OpenApiGeneratorV31,
613
+ extendZodWithOpenApi
614
+ } from "@asteasolutions/zod-to-openapi";
615
+ import { z } from "zod";
616
+ extendZodWithOpenApi(z);
617
+ var ERROR_REGISTRY = /* @__PURE__ */ Symbol.for("palbase.backend.errorRegistry");
618
+ function getErrorRegistry() {
619
+ const g = globalThis;
620
+ if (!g[ERROR_REGISTRY]) {
621
+ const m = /* @__PURE__ */ new Map();
622
+ for (const [code, status, className] of [
623
+ ["bad_request", 400, "BadRequest"],
624
+ ["unauthorized", 401, "Unauthorized"],
625
+ ["forbidden", 403, "Forbidden"],
626
+ ["not_found", 404, "NotFound"],
627
+ ["conflict", 409, "Conflict"],
628
+ ["too_many_requests", 429, "TooManyRequests"]
629
+ ]) {
630
+ m.set(code, { code, status, className, builtin: true });
631
+ }
632
+ g[ERROR_REGISTRY] = m;
633
+ }
634
+ return g[ERROR_REGISTRY];
635
+ }
636
+ function defineError(code, status, dataSchema) {
637
+ if (!Number.isInteger(status) || status < 400 || status > 599) {
638
+ throw new Error(
639
+ `defineError: status for "${code}" must be a 4xx/5xx integer, got ${status} \u2014 error responses must not clobber success responses in the project spec.`
640
+ );
641
+ }
642
+ const registry2 = getErrorRegistry();
643
+ const existing = registry2.get(code);
644
+ const className = defaultClassName(code);
645
+ const dataDigest = dataSchema ? digestOf(code, dataSchema) : void 0;
646
+ if (existing) {
647
+ const sameShape = existing.status === status && !existing.builtin && existing.dataDigest === dataDigest;
648
+ if (!sameShape) {
649
+ throw new Error(
650
+ `defineError: duplicate error code "${code}" with a different shape (existing: status ${existing.status}${existing.builtin ? ", built-in" : ""}${existing.status === status && !existing.builtin ? ", different data schema" : ""}). Error codes are project-unique.`
651
+ );
652
+ }
653
+ }
654
+ const makeWithData = (schema) => class extends HttpError {
655
+ static code = code;
656
+ static status = status;
657
+ constructor(data, message) {
658
+ super(status, code, message ?? humanize(code), schema.parse(data));
659
+ this.name = className;
660
+ }
661
+ };
662
+ const makeWithoutData = () => class extends HttpError {
663
+ static code = code;
664
+ static status = status;
665
+ constructor(message) {
666
+ super(status, code, message ?? humanize(code));
667
+ this.name = className;
668
+ }
669
+ };
670
+ const cls = dataSchema ? makeWithData(dataSchema) : makeWithoutData();
671
+ Object.defineProperty(cls, "name", { value: className });
672
+ registry2.set(code, {
673
+ code,
674
+ status,
675
+ className,
676
+ builtin: false,
677
+ ...dataSchema ? { dataSchema } : {},
678
+ ...dataDigest !== void 0 ? { dataDigest } : {}
679
+ });
680
+ return cls;
681
+ }
682
+ function digestOf(code, dataSchema) {
683
+ const TMP_REF = "__PalbaseErrorDataDigest";
684
+ const tmpRegistry = new OpenAPIRegistry();
685
+ tmpRegistry.register(TMP_REF, z.object({ data: dataSchema }).openapi(TMP_REF));
686
+ const generated = new OpenApiGeneratorV31(tmpRegistry.definitions).generateComponents();
687
+ const out = generated.components?.schemas?.[TMP_REF];
688
+ const digest = JSON.stringify(out ?? null);
689
+ if (digest.includes('"$ref"')) {
690
+ throw new Error(
691
+ `defineError: dataSchema for "${code}" carries .openapi(refId) metadata \u2014 it would emit dangling $ref pointers in the project spec. Use a plain zod schema (z.object({...})) without .openapi(...).`
692
+ );
693
+ }
694
+ return digest;
695
+ }
696
+ function defaultClassName(code) {
697
+ return code.split("_").map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
698
+ }
699
+ function humanize(code) {
700
+ const s = code.replace(/_/g, " ");
701
+ return s.charAt(0).toUpperCase() + s.slice(1);
702
+ }
703
+
589
704
  // src/worker.ts
590
705
  var VALID_WORKER_NAME = /^[a-zA-Z0-9_-]+$/;
591
706
  var WORKER_DEFAULTS = {
@@ -884,7 +999,7 @@ var documents = {
884
999
  };
885
1000
 
886
1001
  // src/index.ts
887
- import { z } from "zod";
1002
+ import { z as z2 } from "zod";
888
1003
  export {
889
1004
  BadRequest,
890
1005
  Body,
@@ -918,6 +1033,7 @@ export {
918
1033
  Query,
919
1034
  Queue,
920
1035
  RESERVED_SECRET_PREFIX,
1036
+ Realtime,
921
1037
  Req,
922
1038
  RequestId,
923
1039
  Resource,
@@ -938,6 +1054,7 @@ export {
938
1054
  boolean,
939
1055
  bucket,
940
1056
  buildProvider,
1057
+ defineError,
941
1058
  defineFlags,
942
1059
  defineJob,
943
1060
  defineMiddleware,
@@ -949,6 +1066,7 @@ export {
949
1066
  documents,
950
1067
  enumType,
951
1068
  flag,
1069
+ getErrorRegistry,
952
1070
  integer,
953
1071
  isPalbaseExtension,
954
1072
  jsonb,
@@ -956,11 +1074,12 @@ export {
956
1074
  makeTypedDB,
957
1075
  parseFileSizeLimit,
958
1076
  policy,
1077
+ recordThrows,
959
1078
  reservedSecretKey,
960
1079
  storage,
961
1080
  text,
962
1081
  timestamp,
963
1082
  uuid,
964
- z
1083
+ z2 as z
965
1084
  };
966
1085
  //# sourceMappingURL=index.js.map