@supacloud/js 0.39.0 → 0.41.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
@@ -6,9 +6,11 @@ import { SupaCloudApiError } from "./api-error.cjs";
6
6
  import { type FetchTransport } from "./bounded-rpc-fetch.cjs";
7
7
  import { SupaCloudOAuthClientsClient } from "./oauth-clients.cjs";
8
8
  import { SupaCloudOAuthServerClient } from "./oauth-server.cjs";
9
- import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.cjs";
9
+ import { type ProcedureSource, type ProceduresOf, type QueryAdapterOptions } from "@supacloud/query";
10
+ export { createProcedureClient, createQueryAdapter, createQueryKey, invalidateByTags, type QueryAdapter, type QueryAdapterOptions, } from "@supacloud/query";
11
+ import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.cjs";
10
12
  export { SupaCloudApiError } from "./api-error.cjs";
11
- export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.cjs";
13
+ export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.cjs";
12
14
  export * from "./oauth-clients.cjs";
13
15
  export * from "./oauth-server.cjs";
14
16
  export { createSupaCloudOAuthFetch, type SupaCloudOAuthFetchOptions, } from "./auth-fetch.cjs";
@@ -17,7 +19,7 @@ export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from
17
19
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.cjs";
18
20
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.cjs";
19
21
  export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.cjs";
20
- export { createSupaCloudProcedureClient, SupaCloudProcedureError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.cjs";
22
+ export { createSupaCloudProcedureClient, SupaCloudProcedureError, isSupaCloudProcedureError, isSupaCloudProcedureErrorCode, isSupaCloudProcedureHttpError, isSupaCloudProcedureTransportError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudGeneratedClientOptions, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.cjs";
21
23
  export * from "./commands.cjs";
22
24
  export * from "./artifacts.cjs";
23
25
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
@@ -305,6 +307,11 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
305
307
  private get encodedName();
306
308
  private rpc;
307
309
  send(payload?: SupaCloudQueueJson, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult>;
310
+ /**
311
+ * Additive SupaCloud extension backed by a tenant-local unique job key.
312
+ * The official pgmq_public.send contract remains unchanged.
313
+ */
314
+ sendIdempotent(payload: SupaCloudQueueJson | undefined, jobKey: string, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueIdempotentSendResult>;
308
315
  sendBatch(messages: SupaCloudQueueJson[], options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult[]>;
309
316
  read(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage[]>;
310
317
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
@@ -342,7 +349,9 @@ declare class SupaCloudQueuesClient<TClient extends SupabaseClient = SupabaseCli
342
349
  create(queueName: string, options?: SupaCloudQueueCreateOptions): Promise<SupaCloudQueueInfo>;
343
350
  drop(queueName: string): Promise<void>;
344
351
  }
345
- export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
352
+ export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient, TApiClient extends ProcedureSource | undefined = undefined>(options: SupaCloudClientOptions<TClient> & {
353
+ apiClient?: TApiClient;
354
+ }): {
346
355
  supabase: TClient;
347
356
  projectRef: string;
348
357
  managementApiUrl: string;
@@ -359,4 +368,27 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
359
368
  functions: {
360
369
  invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
361
370
  };
371
+ procedures: TApiClient extends ProcedureSource ? ProceduresOf<TApiClient> : undefined;
372
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<TApiClient & {}>;
373
+ withClient: <T extends ProcedureSource>(apiClient: T) => {
374
+ supabase: TClient;
375
+ projectRef: string;
376
+ managementApiUrl: string;
377
+ auth: {
378
+ oauthServer: SupaCloudOAuthServerClient;
379
+ oauthClients: SupaCloudOAuthClientsClient;
380
+ };
381
+ tasks: SupaCloudTasksClient<TClient>;
382
+ workflows: SupaCloudWorkflowsClient<TClient>;
383
+ commands: SupaCloudCommandsClient<TClient>;
384
+ artifacts: SupaCloudArtifactsClient<TClient>;
385
+ queues: SupaCloudQueuesClient<TClient>;
386
+ queue: (name: string) => SupaCloudQueueClient<TClient>;
387
+ functions: {
388
+ invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
389
+ };
390
+ procedures: ProceduresOf<T>;
391
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<T>;
392
+ withClient: /*elided*/ any;
393
+ };
362
394
  };
package/dist/index.d.mts CHANGED
@@ -6,9 +6,11 @@ import { SupaCloudApiError } from "./api-error.mjs";
6
6
  import { type FetchTransport } from "./bounded-rpc-fetch.mjs";
7
7
  import { SupaCloudOAuthClientsClient } from "./oauth-clients.mjs";
8
8
  import { SupaCloudOAuthServerClient } from "./oauth-server.mjs";
9
- import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.mjs";
9
+ import { type ProcedureSource, type ProceduresOf, type QueryAdapterOptions } from "@supacloud/query";
10
+ export { createProcedureClient, createQueryAdapter, createQueryKey, invalidateByTags, type QueryAdapter, type QueryAdapterOptions, } from "@supacloud/query";
11
+ import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.mjs";
10
12
  export { SupaCloudApiError } from "./api-error.mjs";
11
- export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.mjs";
13
+ export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.mjs";
12
14
  export * from "./oauth-clients.mjs";
13
15
  export * from "./oauth-server.mjs";
14
16
  export { createSupaCloudOAuthFetch, type SupaCloudOAuthFetchOptions, } from "./auth-fetch.mjs";
@@ -17,7 +19,7 @@ export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from
17
19
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.mjs";
18
20
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.mjs";
19
21
  export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.mjs";
20
- export { createSupaCloudProcedureClient, SupaCloudProcedureError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.mjs";
22
+ export { createSupaCloudProcedureClient, SupaCloudProcedureError, isSupaCloudProcedureError, isSupaCloudProcedureErrorCode, isSupaCloudProcedureHttpError, isSupaCloudProcedureTransportError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudGeneratedClientOptions, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.mjs";
21
23
  export * from "./commands.mjs";
22
24
  export * from "./artifacts.mjs";
23
25
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
@@ -305,6 +307,11 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
305
307
  private get encodedName();
306
308
  private rpc;
307
309
  send(payload?: SupaCloudQueueJson, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult>;
310
+ /**
311
+ * Additive SupaCloud extension backed by a tenant-local unique job key.
312
+ * The official pgmq_public.send contract remains unchanged.
313
+ */
314
+ sendIdempotent(payload: SupaCloudQueueJson | undefined, jobKey: string, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueIdempotentSendResult>;
308
315
  sendBatch(messages: SupaCloudQueueJson[], options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult[]>;
309
316
  read(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage[]>;
310
317
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
@@ -342,7 +349,9 @@ declare class SupaCloudQueuesClient<TClient extends SupabaseClient = SupabaseCli
342
349
  create(queueName: string, options?: SupaCloudQueueCreateOptions): Promise<SupaCloudQueueInfo>;
343
350
  drop(queueName: string): Promise<void>;
344
351
  }
345
- export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
352
+ export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient, TApiClient extends ProcedureSource | undefined = undefined>(options: SupaCloudClientOptions<TClient> & {
353
+ apiClient?: TApiClient;
354
+ }): {
346
355
  supabase: TClient;
347
356
  projectRef: string;
348
357
  managementApiUrl: string;
@@ -359,4 +368,27 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
359
368
  functions: {
360
369
  invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
361
370
  };
371
+ procedures: TApiClient extends ProcedureSource ? ProceduresOf<TApiClient> : undefined;
372
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<TApiClient & {}>;
373
+ withClient: <T extends ProcedureSource>(apiClient: T) => {
374
+ supabase: TClient;
375
+ projectRef: string;
376
+ managementApiUrl: string;
377
+ auth: {
378
+ oauthServer: SupaCloudOAuthServerClient;
379
+ oauthClients: SupaCloudOAuthClientsClient;
380
+ };
381
+ tasks: SupaCloudTasksClient<TClient>;
382
+ workflows: SupaCloudWorkflowsClient<TClient>;
383
+ commands: SupaCloudCommandsClient<TClient>;
384
+ artifacts: SupaCloudArtifactsClient<TClient>;
385
+ queues: SupaCloudQueuesClient<TClient>;
386
+ queue: (name: string) => SupaCloudQueueClient<TClient>;
387
+ functions: {
388
+ invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
389
+ };
390
+ procedures: ProceduresOf<T>;
391
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<T>;
392
+ withClient: /*elided*/ any;
393
+ };
362
394
  };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { FunctionsHttpError } from "@supabase/supabase-js";
2
+ import { FunctionsHttpError as FunctionsHttpError2 } from "@supabase/supabase-js";
3
3
 
4
4
  // src/workflow-rpc.ts
5
5
  function invokeWorkflowMutation(supabase, functionName, request, unconfirmed) {
@@ -2308,6 +2308,142 @@ class SupaCloudOAuthServerClient {
2308
2308
  });
2309
2309
  }
2310
2310
  }
2311
+
2312
+ // node_modules/@supacloud/query/dist/index.js
2313
+ async function invalidateByTags(queryClient, tags, keyPrefix) {
2314
+ const targetTags = Array.isArray(tags) ? tags : [tags];
2315
+ if (targetTags.length === 0)
2316
+ return;
2317
+ await queryClient.invalidateQueries({
2318
+ ...keyPrefix ? { queryKey: keyPrefix } : {},
2319
+ predicate: (query) => {
2320
+ const queryTags = query.meta?.tags;
2321
+ if (!Array.isArray(queryTags))
2322
+ return false;
2323
+ return targetTags.some((tag) => queryTags.includes(tag));
2324
+ }
2325
+ });
2326
+ }
2327
+ function snapshot(value, ancestors = new Set) {
2328
+ if (value === null || value === undefined || typeof value === "string" || typeof value === "boolean")
2329
+ return value;
2330
+ if (typeof value === "number" && Number.isFinite(value))
2331
+ return value;
2332
+ if (typeof value !== "object" || ancestors.has(value))
2333
+ throw new TypeError("Input must be acyclic JSON data");
2334
+ const prototype = Object.getPrototypeOf(value);
2335
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
2336
+ throw new TypeError("Input must be JSON data");
2337
+ ancestors.add(value);
2338
+ try {
2339
+ if (Array.isArray(value))
2340
+ return Object.freeze(value.map((item) => snapshot(item, ancestors) ?? null));
2341
+ return Object.freeze(Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, snapshot(item, ancestors)])));
2342
+ } finally {
2343
+ ancestors.delete(value);
2344
+ }
2345
+ }
2346
+ function identityPrefix(prefix) {
2347
+ if (!Array.isArray(prefix) || prefix.length === 0 || prefix.some((part) => typeof part !== "string" || !part.trim())) {
2348
+ throw new TypeError("keyPrefix must contain nonempty identity values");
2349
+ }
2350
+ return Object.freeze(["supacloud", ...prefix]);
2351
+ }
2352
+ function createQueryKey(operationId, input, keyPrefix) {
2353
+ return Object.freeze([...identityPrefix(keyPrefix), operationId, snapshot(input)]);
2354
+ }
2355
+ function createProcedureClient(client) {
2356
+ const candidate = Object.hasOwn(client, "procedureClient") ? client.procedureClient : undefined;
2357
+ return candidate !== undefined ? candidate : client;
2358
+ }
2359
+ function call(procedure, input, execution) {
2360
+ if (!execution || typeof execution !== "object" || Array.isArray(execution))
2361
+ throw new TypeError("Invalid execution options");
2362
+ const { signal, idempotencyKey } = execution;
2363
+ if (signal !== undefined && !(signal instanceof AbortSignal))
2364
+ throw new TypeError("Invalid AbortSignal");
2365
+ if (procedure.__supacloudProcedure.idempotency === "required" && idempotencyKey === undefined || idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(idempotencyKey))) {
2366
+ throw new TypeError("A valid idempotencyKey is required");
2367
+ }
2368
+ const captured = Object.freeze({ ...execution });
2369
+ const invoke = procedure;
2370
+ return new Promise((resolve, reject) => {
2371
+ const abort = () => reject(signal?.reason ?? new DOMException("Procedure cancelled", "AbortError"));
2372
+ if (signal?.aborted) {
2373
+ abort();
2374
+ return;
2375
+ }
2376
+ signal?.addEventListener("abort", abort, { once: true });
2377
+ Promise.resolve().then(() => {
2378
+ signal?.throwIfAborted();
2379
+ return invoke(input, captured);
2380
+ }).then(resolve, reject).finally(() => signal?.removeEventListener("abort", abort));
2381
+ });
2382
+ }
2383
+ function createQueryAdapter(client, options) {
2384
+ const prefix = identityPrefix(options.keyPrefix);
2385
+ const source = createProcedureClient(client);
2386
+ const result = Object.create(null);
2387
+ for (const [controller, handlers] of Object.entries(source)) {
2388
+ if (controller === "invalidateByTags")
2389
+ throw new TypeError("Reserved controller name: invalidateByTags");
2390
+ const mapped = Object.create(null);
2391
+ result[controller] = mapped;
2392
+ for (const [name, member] of Object.entries(handlers)) {
2393
+ const procedure = "query" in member ? member.query : member.mutate;
2394
+ if (procedure === undefined)
2395
+ throw new TypeError("Expected a generated procedure");
2396
+ const metadata = procedure.__supacloudProcedure;
2397
+ if (typeof procedure !== "function" || !metadata || metadata.kind !== ("query" in member ? "query" : "mutation") || typeof metadata.key !== "string" || typeof metadata.method !== "string" || typeof metadata.path !== "string" || !["none", "required"].includes(metadata.idempotency)) {
2398
+ throw new TypeError("Expected a generated procedure");
2399
+ }
2400
+ const key = Object.freeze([...prefix, metadata.kind, metadata.method, metadata.path]);
2401
+ if ("query" in member) {
2402
+ const proc = member.query;
2403
+ mapped[name] = {
2404
+ queryKey: (...args) => args.length ? Object.freeze([...key, snapshot(args[0] ?? {})]) : key,
2405
+ queryOptions: (input, opts) => {
2406
+ const captured = snapshot(input ?? {});
2407
+ return {
2408
+ queryKey: Object.freeze([...key, captured]),
2409
+ queryFn: async ({ signal }) => await call(proc, captured, { signal }) ?? null,
2410
+ meta: { ...opts?.meta, tags: Object.freeze([...opts?.tags ?? []]) }
2411
+ };
2412
+ }
2413
+ };
2414
+ } else {
2415
+ const proc = member.mutate;
2416
+ if (proc === undefined)
2417
+ throw new TypeError("Expected a generated mutation");
2418
+ mapped[name] = {
2419
+ mutationKey: () => key,
2420
+ mutationOptions: (opts) => ({
2421
+ mutationKey: key,
2422
+ retry: false,
2423
+ mutationFn: async (variables) => call(proc, variables.input, variables.execution === undefined ? {} : variables.execution),
2424
+ meta: { ...opts?.meta },
2425
+ onSuccess: async (data, variables, context) => {
2426
+ const target = opts?.queryClient ?? options.queryClient;
2427
+ if (opts?.invalidateTags?.length && target === undefined)
2428
+ throw new Error("No QueryClient provided for invalidation");
2429
+ if (target !== undefined && opts?.invalidateTags?.length)
2430
+ await invalidateByTags(target, opts.invalidateTags, prefix);
2431
+ return opts?.onSuccess?.(data, variables, context);
2432
+ }
2433
+ })
2434
+ };
2435
+ }
2436
+ }
2437
+ }
2438
+ return Object.assign(result, {
2439
+ invalidateByTags: (tags, clientForInvalidation) => {
2440
+ const target = clientForInvalidation ?? options.queryClient;
2441
+ if (target === undefined)
2442
+ throw new Error("No QueryClient provided for invalidateByTags");
2443
+ return invalidateByTags(target, tags, prefix);
2444
+ }
2445
+ });
2446
+ }
2311
2447
  // src/auth-fetch.ts
2312
2448
  function requestMethod(input, init) {
2313
2449
  return (init?.method || (input instanceof Request ? input.method : "GET")).toUpperCase();
@@ -2514,7 +2650,22 @@ function createSupaCloudApiFetch(options) {
2514
2650
  return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
2515
2651
  };
2516
2652
  }
2653
+ // src/procedure-client.ts
2654
+ import { FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from "@supabase/supabase-js";
2655
+
2517
2656
  // src/procedure-error.ts
2657
+ var procedureErrorCodes = new Set([
2658
+ "API_HTTP_ERROR",
2659
+ "API_RESPONSE_INVALID",
2660
+ "API_RESPONSE_UNDECLARED",
2661
+ "SUPACLOUD_EXECUTION_ERROR",
2662
+ "SUPACLOUD_FUNCTIONS_ERROR",
2663
+ "SUPACLOUD_TRANSPORT_ERROR",
2664
+ "SUPACLOUD_CLIENT_ERROR"
2665
+ ]);
2666
+ function isSupaCloudProcedureErrorCode(value) {
2667
+ return typeof value === "string" && procedureErrorCodes.has(value);
2668
+ }
2518
2669
  function procedureErrorIdentifier(value) {
2519
2670
  return typeof value === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value) ? value : undefined;
2520
2671
  }
@@ -2523,6 +2674,7 @@ class SupaCloudProcedureError extends Error {
2523
2674
  code;
2524
2675
  status;
2525
2676
  requestId;
2677
+ upstreamCode;
2526
2678
  details;
2527
2679
  response;
2528
2680
  cause;
@@ -2532,23 +2684,62 @@ class SupaCloudProcedureError extends Error {
2532
2684
  this.code = options.code;
2533
2685
  this.status = options.status ?? null;
2534
2686
  this.requestId = procedureErrorIdentifier(options.requestId) ?? null;
2687
+ this.upstreamCode = procedureErrorIdentifier(options.upstreamCode) ?? null;
2535
2688
  this.details = options.details;
2536
2689
  this.response = options.response;
2537
2690
  this.cause = options.cause;
2538
2691
  Object.defineProperty(this, "response", { enumerable: false });
2539
2692
  Object.defineProperty(this, "cause", { enumerable: false });
2693
+ Object.defineProperty(this, "upstreamCode", { enumerable: false });
2540
2694
  Object.defineProperty(this, "details", { enumerable: false });
2541
2695
  }
2542
2696
  }
2697
+ function isSupaCloudProcedureError(value) {
2698
+ return value instanceof Error && value.name === "SupaCloudProcedureError" && "code" in value && isSupaCloudProcedureErrorCode(value.code) && "status" in value && (value.status === null || typeof value.status === "number" && Number.isInteger(value.status) && value.status >= 0 && value.status <= 599) && "requestId" in value && (value.requestId === null || procedureErrorIdentifier(value.requestId) !== undefined) && "upstreamCode" in value && (value.upstreamCode === null || procedureErrorIdentifier(value.upstreamCode) !== undefined) && "response" in value && (value.response === undefined || value.response instanceof Response) && "details" in value && "cause" in value;
2699
+ }
2700
+ function isSupaCloudProcedureHttpError(value) {
2701
+ return isSupaCloudProcedureError(value) && typeof value.status === "number" && value.response instanceof Response;
2702
+ }
2703
+ function isSupaCloudProcedureTransportError(value) {
2704
+ return isSupaCloudProcedureError(value) && (value.code === "SUPACLOUD_FUNCTIONS_ERROR" || value.code === "SUPACLOUD_TRANSPORT_ERROR");
2705
+ }
2543
2706
 
2544
- // src/procedure-client.ts
2707
+ // src/procedure-runtime.ts
2708
+ var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2709
+ function isValidSupaCloudIdempotencyKey(value) {
2710
+ return typeof value === "string" && idempotencyKeyPattern.test(value);
2711
+ }
2545
2712
  function isRecord5(value) {
2546
2713
  return value !== null && typeof value === "object" && !Array.isArray(value);
2547
2714
  }
2715
+ function validateSupaCloudProcedureExecution(metadata, execution) {
2716
+ if (execution !== undefined && !isRecord5(execution)) {
2717
+ throw new SupaCloudProcedureError("Procedure execution must be an options object", {
2718
+ code: "SUPACLOUD_EXECUTION_ERROR"
2719
+ });
2720
+ }
2721
+ const signal = isRecord5(execution) ? execution.signal : undefined;
2722
+ if (signal !== undefined && (typeof AbortSignal === "undefined" || !(signal instanceof AbortSignal))) {
2723
+ throw new SupaCloudProcedureError("Procedure signal must be an AbortSignal", {
2724
+ code: "SUPACLOUD_EXECUTION_ERROR"
2725
+ });
2726
+ }
2727
+ const key = isRecord5(execution) ? execution.idempotencyKey : undefined;
2728
+ if (metadata.idempotency === "required" && key === undefined || key !== undefined && !isValidSupaCloudIdempotencyKey(key)) {
2729
+ throw new SupaCloudProcedureError("This procedure requires a valid idempotencyKey", {
2730
+ code: "SUPACLOUD_EXECUTION_ERROR"
2731
+ });
2732
+ }
2733
+ }
2734
+
2735
+ // src/procedure-client.ts
2736
+ function isRecord6(value) {
2737
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2738
+ }
2548
2739
  function asGeneratedError(value) {
2549
- if (!isRecord5(value))
2740
+ if (!isRecord6(value) || !(value instanceof Error))
2550
2741
  return;
2551
- if (value.name !== "ApiClientError" || typeof value.code !== "string" || typeof value.status !== "number")
2742
+ if (value.name !== "ApiClientError" || typeof value.code !== "string" || typeof value.status !== "number" || !Number.isInteger(value.status) || value.status < 0 || value.status > 599 || typeof value.method !== "string" || typeof value.path !== "string" || !("response" in value) || value.response !== undefined && !(value.response instanceof Response))
2552
2743
  return;
2553
2744
  return { code: value.code, status: value.status, requestId: value.requestId, response: value.response };
2554
2745
  }
@@ -2580,7 +2771,7 @@ async function readErrorBody(response) {
2580
2771
  return;
2581
2772
  if (chunk.done) {
2582
2773
  const body = JSON.parse(text + decoder.decode());
2583
- return isRecord5(body) ? body : undefined;
2774
+ return isRecord6(body) ? body : undefined;
2584
2775
  }
2585
2776
  bytes += chunk.value.byteLength;
2586
2777
  if (bytes > maxBytes)
@@ -2604,79 +2795,39 @@ async function readErrorBody(response) {
2604
2795
  }
2605
2796
  }
2606
2797
  function errorName(error) {
2607
- return isRecord5(error) && typeof error.name === "string" ? error.name : undefined;
2798
+ return isRecord6(error) && typeof error.name === "string" ? error.name : undefined;
2608
2799
  }
2609
2800
  async function normalizeProcedureError(error, transport = false) {
2610
- if (error instanceof SupaCloudProcedureError)
2801
+ if (isSupaCloudProcedureError(error))
2802
+ return error;
2803
+ const generated = asGeneratedError(error);
2804
+ const knownTransportFailure = error instanceof FunctionsFetchError || error instanceof FunctionsRelayError || error instanceof FunctionsHttpError;
2805
+ if (generated === undefined && !knownTransportFailure && !transport)
2611
2806
  return error;
2612
2807
  if (errorName(error) === "AbortError")
2613
2808
  return error;
2614
- if (errorName(error) === "FunctionsFetchError" && isRecord5(error) && errorName(error.context) === "AbortError")
2809
+ if (errorName(error) === "FunctionsFetchError" && isRecord6(error) && errorName(error.context) === "AbortError")
2615
2810
  return error.context;
2616
- const generated = asGeneratedError(error);
2617
- const response = generated?.response instanceof Response ? generated.response : isRecord5(error) && error.context instanceof Response ? error.context : undefined;
2811
+ const responseDecodeFailure = transport && error instanceof SyntaxError;
2812
+ const response = generated?.response instanceof Response ? generated.response : isRecord6(error) && error.context instanceof Response ? error.context : undefined;
2618
2813
  const original = response === undefined ? undefined : getSupaCloudApiFetchError(response);
2619
2814
  const cause = original ?? error;
2620
2815
  const responseBody = await readErrorBody(response);
2621
2816
  const name = errorName(cause);
2622
2817
  const message = error instanceof Error ? error.message : "SupaCloud procedure failed";
2623
- const fallback = name === "FunctionsFetchError" ? "SUPACLOUD_TRANSPORT_ERROR" : name === "FunctionsRelayError" ? "SUPACLOUD_FUNCTIONS_ERROR" : name === "FunctionsHttpError" ? "API_HTTP_ERROR" : error instanceof SyntaxError ? "API_RESPONSE_INVALID" : transport ? "SUPACLOUD_TRANSPORT_ERROR" : "SUPACLOUD_CLIENT_ERROR";
2624
- const code = name === "FunctionsRelayError" ? fallback : generated?.code ?? fallback;
2818
+ const fallback = name === "FunctionsFetchError" ? "SUPACLOUD_TRANSPORT_ERROR" : name === "FunctionsRelayError" ? "SUPACLOUD_FUNCTIONS_ERROR" : name === "FunctionsHttpError" ? "API_HTTP_ERROR" : responseDecodeFailure ? "API_RESPONSE_INVALID" : transport ? "SUPACLOUD_TRANSPORT_ERROR" : "SUPACLOUD_CLIENT_ERROR";
2819
+ const code = name !== "FunctionsRelayError" && generated?.code && isSupaCloudProcedureErrorCode(generated.code) ? generated.code : fallback;
2820
+ const upstreamCode = procedureErrorIdentifier(responseBody?.code) ?? (generated && !isSupaCloudProcedureErrorCode(generated.code) ? procedureErrorIdentifier(generated.code) : undefined);
2625
2821
  return new SupaCloudProcedureError(message, {
2626
2822
  code,
2627
2823
  status: generated?.status ?? response?.status ?? null,
2628
2824
  requestId: procedureErrorIdentifier(generated?.requestId) ?? procedureErrorIdentifier(response?.headers.get("x-request-id")) ?? procedureErrorIdentifier(responseBody?.requestId) ?? null,
2825
+ upstreamCode: upstreamCode ?? null,
2629
2826
  details: responseBody,
2630
2827
  response,
2631
2828
  cause
2632
2829
  });
2633
2830
  }
2634
- function validateProcedureExecution(procedure, args) {
2635
- const metadata = Reflect.get(procedure, "__supacloudProcedure");
2636
- if (!isRecord5(metadata))
2637
- return;
2638
- const [first, second] = args;
2639
- const execution = second ?? (isRecord5(first) && (Object.hasOwn(first, "idempotencyKey") || Object.hasOwn(first, "signal")) ? first : undefined);
2640
- const key = isRecord5(execution) ? execution.idempotencyKey : undefined;
2641
- if (metadata.idempotency === "required" && key === undefined || key !== undefined && (typeof key !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(key))) {
2642
- throw new SupaCloudProcedureError("This procedure requires a valid idempotencyKey", {
2643
- code: "SUPACLOUD_EXECUTION_ERROR"
2644
- });
2645
- }
2646
- }
2647
- function wrapGeneratedClient(client) {
2648
- const cache = new WeakMap;
2649
- const wrap = (value, level) => {
2650
- const cached = cache.get(value);
2651
- if (cached !== undefined)
2652
- return cached;
2653
- const proxy = new Proxy(value, {
2654
- async apply(current, thisArg, args) {
2655
- try {
2656
- validateProcedureExecution(current, args);
2657
- return await Reflect.apply(current, thisArg, args);
2658
- } catch (failure) {
2659
- throw await normalizeProcedureError(failure);
2660
- }
2661
- },
2662
- get(current, key, receiver) {
2663
- const member = Reflect.get(current, key, receiver);
2664
- if (!Object.hasOwn(current, key))
2665
- return member;
2666
- if (typeof member === "function" && (level === "controller" || level === "client" && key === "request" || level === "call" && (key === "query" || key === "mutate"))) {
2667
- return wrap(member, "call");
2668
- }
2669
- if (level === "client" && isRecord5(member) && Object.getPrototypeOf(member) === Object.prototype) {
2670
- return wrap(member, "controller");
2671
- }
2672
- return member;
2673
- }
2674
- });
2675
- cache.set(value, proxy);
2676
- return proxy;
2677
- };
2678
- return wrap(client, "client");
2679
- }
2680
2831
  function createSupaCloudProcedureClient(options) {
2681
2832
  const transport = createSupaCloudApiFetch({
2682
2833
  supabase: options.supabase,
@@ -2693,7 +2844,18 @@ function createSupaCloudProcedureClient(options) {
2693
2844
  throw await normalizeProcedureError(error, true);
2694
2845
  }
2695
2846
  };
2696
- return wrapGeneratedClient(options.generated({ fetch: fetch2 }));
2847
+ const generatedConfig = {
2848
+ ...options.generatedConfig ?? {},
2849
+ fetch: fetch2,
2850
+ errorMapper: normalizeProcedureError,
2851
+ procedureExecutionValidator: validateSupaCloudProcedureExecution
2852
+ };
2853
+ const client = options.generated(generatedConfig);
2854
+ const capabilities = Reflect.get(client, "__supacloudClient");
2855
+ if (!isRecord6(capabilities) || capabilities.hooksVersion !== 1) {
2856
+ throw new TypeError("Regenerate the application client to enable procedure error and execution hooks");
2857
+ }
2858
+ return client;
2697
2859
  }
2698
2860
 
2699
2861
  // src/index.ts
@@ -3411,11 +3573,11 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
3411
3573
  const { data, error, response } = invocation;
3412
3574
  const boundedHttpFailure = response instanceof Response && boundedTaskHttpFailures.delete(response);
3413
3575
  if (error !== null && error !== undefined) {
3414
- if (error instanceof FunctionsHttpError && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
3576
+ if (error instanceof FunctionsHttpError2 && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
3415
3577
  throw error;
3416
3578
  }
3417
3579
  if (boundedHttpFailure && response instanceof Response && !response.redirected && response.status >= 400 && response.status < 500 && matchesForeignTaskHttpError(error, response)) {
3418
- throw new FunctionsHttpError(response);
3580
+ throw new FunctionsHttpError2(response);
3419
3581
  }
3420
3582
  if (response instanceof Response)
3421
3583
  response.body?.cancel().catch(() => {});
@@ -3789,6 +3951,34 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
3789
3951
  payload: captured
3790
3952
  };
3791
3953
  }
3954
+ async sendIdempotent(payload = {}, jobKey, options = {}) {
3955
+ const captured = queueJsonSnapshot(payload);
3956
+ if (typeof jobKey !== "string" || jobKey.trim() !== jobKey || !/^[A-Za-z0-9_.:@/-]{1,200}$/.test(jobKey)) {
3957
+ throw new SupaCloudQueueError(false, "QUEUE_JOB_KEY_INVALID");
3958
+ }
3959
+ const result = await this.rpc("send_idempotent", {
3960
+ queue_name: this.name,
3961
+ message: captured,
3962
+ p_job_key: jobKey,
3963
+ sleep_seconds: normalizeSecondsFromOptions(options)
3964
+ }, (value) => {
3965
+ if (!Array.isArray(value) || value.length !== 1 || !value[0] || Array.isArray(value[0]) || typeof value[0] !== "object") {
3966
+ throw new SupaCloudQueueError;
3967
+ }
3968
+ const row = value[0];
3969
+ if (typeof row.created !== "boolean")
3970
+ throw new SupaCloudQueueError;
3971
+ return { msgId: queueMessageId(row.msg_id), created: row.created === true };
3972
+ });
3973
+ return {
3974
+ id: result.msgId,
3975
+ msg_id: result.msgId,
3976
+ queue_name: this.name,
3977
+ status: result.created ? "pending" : "deduplicated",
3978
+ payload: captured,
3979
+ deduplicated: !result.created
3980
+ };
3981
+ }
3792
3982
  async sendBatch(messages, options = {}) {
3793
3983
  if (!Array.isArray(messages) || messages.length === 0 || messages.length > 1e4)
3794
3984
  throw new SupaCloudQueueError;
@@ -3919,7 +4109,7 @@ function createSupaCloudClient(options) {
3919
4109
  const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
3920
4110
  const commands2 = new SupaCloudCommandsClient(options.supabase);
3921
4111
  const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
3922
- return {
4112
+ const instance = {
3923
4113
  supabase: options.supabase,
3924
4114
  projectRef: normalized.projectRef,
3925
4115
  managementApiUrl: normalized.managementApiUrl,
@@ -3937,6 +4127,24 @@ function createSupaCloudClient(options) {
3937
4127
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
3938
4128
  }
3939
4129
  };
4130
+ function withClient(apiClient) {
4131
+ return {
4132
+ ...instance,
4133
+ procedures: createProcedureClient(apiClient),
4134
+ queryAdapter: (adapterOptions) => createQueryAdapter(apiClient, adapterOptions),
4135
+ withClient
4136
+ };
4137
+ }
4138
+ return {
4139
+ ...instance,
4140
+ procedures: options.apiClient === undefined ? undefined : createProcedureClient(options.apiClient),
4141
+ queryAdapter: (adapterOptions) => {
4142
+ if (options.apiClient === undefined)
4143
+ throw new Error("No procedure client attached");
4144
+ return createQueryAdapter(options.apiClient, adapterOptions);
4145
+ },
4146
+ withClient
4147
+ };
3940
4148
  }
3941
4149
  export {
3942
4150
  SupaCloudApiError,
@@ -3969,6 +4177,9 @@ export {
3969
4177
  SupaCloudWorkflowRetryError,
3970
4178
  SupaCloudWorkflowStartError,
3971
4179
  SupaCloudWorkflowsClient,
4180
+ createProcedureClient,
4181
+ createQueryAdapter,
4182
+ createQueryKey,
3972
4183
  createSupaCloudApiFetch,
3973
4184
  createSupaCloudArtifactFetch,
3974
4185
  createSupaCloudClient,
@@ -3976,5 +4187,10 @@ export {
3976
4187
  createSupaCloudOAuthFetch,
3977
4188
  createSupaCloudProcedureClient,
3978
4189
  createSupaCloudTaskFetch,
3979
- createSupaCloudWorkflowFetch
4190
+ createSupaCloudWorkflowFetch,
4191
+ invalidateByTags,
4192
+ isSupaCloudProcedureError,
4193
+ isSupaCloudProcedureErrorCode,
4194
+ isSupaCloudProcedureHttpError,
4195
+ isSupaCloudProcedureTransportError
3980
4196
  };
@@ -1,10 +1,18 @@
1
1
  import type { SupabaseClient } from "./supabase-types.cjs";
2
2
  import type { FetchTransport } from "./bounded-rpc-fetch.cjs";
3
- export { SupaCloudProcedureError, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-error.cjs";
3
+ import { type SupaCloudProcedureExecution, type SupaCloudProcedureMetadata } from "./procedure-runtime.cjs";
4
+ export { SupaCloudProcedureError, isSupaCloudProcedureError, isSupaCloudProcedureErrorCode, isSupaCloudProcedureHttpError, isSupaCloudProcedureTransportError, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-error.cjs";
4
5
  export interface SupaCloudGeneratedClientConfig {
5
6
  fetch: FetchTransport;
7
+ errorMapper?: (error: unknown) => unknown | Promise<unknown>;
8
+ procedureExecutionValidator?: (metadata: SupaCloudProcedureMetadata, execution?: SupaCloudProcedureExecution) => void;
6
9
  }
7
10
  export type SupaCloudGeneratedClientFactory<TClient extends object = object> = (config: SupaCloudGeneratedClientConfig) => TClient;
11
+ export type SupaCloudGeneratedClientOptions<TFactory extends SupaCloudGeneratedClientFactory> = Omit<NonNullable<Parameters<TFactory>[0]>, keyof SupaCloudGeneratedClientConfig> & {
12
+ fetch?: never;
13
+ errorMapper?: never;
14
+ procedureExecutionValidator?: never;
15
+ };
8
16
  export interface SupaCloudProcedureClientOptions<TClient extends SupabaseClient, TFactory extends SupaCloudGeneratedClientFactory> {
9
17
  /** The existing user-scoped Supabase client; it owns auth and session refresh. */
10
18
  supabase: TClient;
@@ -12,6 +20,8 @@ export interface SupaCloudProcedureClientOptions<TClient extends SupabaseClient,
12
20
  functionName: string;
13
21
  /** The generated createApiClient factory for the application contract. */
14
22
  generated: TFactory;
23
+ /** Additional generated-client settings; transport and facade policies are owned by this wrapper. */
24
+ generatedConfig?: SupaCloudGeneratedClientOptions<NoInfer<TFactory>>;
15
25
  }
16
26
  export type SupaCloudProcedureClient<TFactory extends SupaCloudGeneratedClientFactory> = ReturnType<TFactory>;
17
27
  /**