@supacloud/js 0.38.0 → 0.39.1

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/PROCEDURES.md ADDED
@@ -0,0 +1,145 @@
1
+ # Generated Procedure Facade
2
+
3
+ The root `@supacloud/js` entrypoint provides a framework-neutral facade for
4
+ compiler-generated application clients:
5
+
6
+ ```ts
7
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
8
+ import { createApiClient } from "./generated/client";
9
+
10
+ const api = createSupaCloudProcedureClient({
11
+ supabase,
12
+ functionName: "app-api",
13
+ generated: createApiClient,
14
+ });
15
+
16
+ await api.cases.detail.query({ params: { id: "case-1" } });
17
+ await api.cases.accept.mutate(
18
+ { params: { id: "case-1" } },
19
+ { idempotencyKey: "case-1-accept-v1" },
20
+ );
21
+ ```
22
+
23
+ The facade creates no session, token store or second auth implementation.
24
+ `supabase-js` remains responsible for authentication, refresh, Functions,
25
+ Database, Storage and Realtime. The existing generated client transport and
26
+ callable route methods remain compatible, so migration can be incremental.
27
+
28
+ ## Migration
29
+
30
+ Upgrade the compiler and SDK together and regenerate the application `client.ts`.
31
+ The facade checks the generated `__supacloudClient.hooksVersion` capability and
32
+ rejects older generated files with a regeneration message. It returns the
33
+ generated client itself, without a Proxy.
34
+ Existing `createApiClient({ fetch: createSupaCloudApiFetch(...) })` initialization
35
+ remains supported and retains the original error classes. Switch initialization
36
+ to the facade when ready; successful values, route decoder overloads and
37
+ `.query/.mutate` argument types are unchanged. Existing `api.cases.detail(input)`
38
+ calls also work through the facade. The facade normalizes failures from routes,
39
+ procedures and `api.request`; `buildRouteUrl` stays synchronous.
40
+
41
+ All `.mutate` calls with required idempotency must supply an execution key,
42
+ including direct generated procedures. An `idempotency-key` request header
43
+ cannot satisfy this requirement. Legacy callable routes retain their old
44
+ header and argument conventions. Extra settings are inferred from the generated
45
+ factory's own configuration:
46
+
47
+ ```ts
48
+ const api = createSupaCloudProcedureClient({
49
+ supabase,
50
+ functionName: "app-api",
51
+ generated: createApiClient,
52
+ generatedConfig: {
53
+ normalize: false,
54
+ headers: () => ({ "x-tenant": tenantId }),
55
+ interceptors: [businessInterceptor],
56
+ },
57
+ });
58
+ ```
59
+
60
+ `fetch`, `errorMapper` and `procedureExecutionValidator` remain facade-owned,
61
+ including when configuration is supplied as an existing variable. Other
62
+ generated settings keep their original types and behavior. Custom factory
63
+ wrappers must forward these hooks; do not replace them or introduce retrying
64
+ interceptors. Supabase still owns authentication headers.
65
+
66
+ The same procedures work with the optional
67
+ [`@supacloud/js/query`](./QUERY.md) adapter and ordinary Svelte/React Query bindings.
68
+ The facade does not create a cache or import a framework runtime.
69
+
70
+ ## Errors
71
+
72
+ `SupaCloudProcedureError` exposes:
73
+
74
+ - `code`: the closed `SupaCloudProcedureErrorCode` classification
75
+ - `status`: HTTP status, or `null` when no response was received
76
+ - `requestId`: bounded `x-request-id` (or the JSON body's `requestId`), or `null`
77
+ - `upstreamCode`: bounded domain/server code (or an unknown future generated code), or `null`
78
+ - `details`: the full JSON error body when available, including any domain `code`
79
+ - `response`: the original HTTP `Response` when available
80
+ - `cause`: the original Supabase `FunctionsHttpError`, fetch error or client error
81
+
82
+ ```ts
83
+ import { FunctionsHttpError } from "@supabase/supabase-js";
84
+ import { isSupaCloudProcedureError } from "@supacloud/js";
85
+
86
+ try {
87
+ await api.cases.detail.query({ params: { id: "case-1" } });
88
+ } catch (error) {
89
+ if (!isSupaCloudProcedureError(error)) throw error;
90
+ console.error(error.code, error.status, error.requestId);
91
+ if (error.cause instanceof FunctionsHttpError) {
92
+ // Identical to error.response; its body has not been consumed by the facade.
93
+ const body: unknown = await error.cause.context.json();
94
+ }
95
+ }
96
+ ```
97
+
98
+ HTTP failures use `API_HTTP_ERROR`; JSON/schema failures use
99
+ `API_RESPONSE_INVALID` and undeclared success statuses use
100
+ `API_RESPONSE_UNDECLARED`. Network and relay failures use
101
+ `SUPACLOUD_TRANSPORT_ERROR` and `SUPACLOUD_FUNCTIONS_ERROR`. Unknown future generated
102
+ error codes use `SUPACLOUD_CLIENT_ERROR` with the original code in `upstreamCode`.
103
+ Invalid idempotency uses `SUPACLOUD_EXECUTION_ERROR`.
104
+ Unknown application, header-provider, interceptor and custom-decoder exceptions
105
+ remain unchanged, including `SyntaxError` and `TypeError`. Native `AbortError`
106
+ cancellation remains unchanged.
107
+
108
+ Use `isSupaCloudProcedureError` when catching errors across separately bundled
109
+ SDK entrypoints: their constructors need not have the same identity. This guard
110
+ checks the error's shape and known code, not its provenance; it is not an
111
+ authorization check or an error deserializer. Cross-realm errors are not
112
+ supported. `isSupaCloudProcedureHttpError` additionally narrows to a numeric
113
+ status and a `Response` (including contract failures on 2xx responses);
114
+ `isSupaCloudProcedureTransportError` narrows to network/relay codes.
115
+
116
+ Error-body inspection reads only a clone of JSON failures, at most 64 KiB and
117
+ 250 ms. Non-JSON, oversized, malformed or stalled bodies leave `details`
118
+ undefined without hiding the HTTP failure. Treat details as untrusted data.
119
+ `details`, `upstreamCode`, `response` and `cause` are excluded from JSON serialization.
120
+ Generated clients decode buffered responses from a clone when possible, including
121
+ successful responses that fail schema validation. If cloning is unavailable,
122
+ decoding falls back to the original body. Successful live streams are not cloned.
123
+ This preserves the response received by the generated client; Supabase may have
124
+ already decoded its own successful response before adapting it to Fetch.
125
+ If Supabase fails before returning a
126
+ response (including malformed success JSON), the original error is kept as
127
+ `cause`, but no HTTP status is fabricated.
128
+
129
+ ## Mutation Safety
130
+
131
+ Mutations are never retried by this facade. Commands that declare required
132
+ idempotency reject before dispatch unless an invocation supplies a valid
133
+ `idempotencyKey`. Declared non-2xx response schemas retain the generated
134
+ client's typed-value behavior instead of being reclassified as exceptions.
135
+ Reuse the key only for the same logical operation. A failed or cancelled request
136
+ does not prove that a write rolled back; resolve uncertain outcomes before retrying.
137
+ The facade does not implement server-side idempotency or durable command receipts.
138
+
139
+ The facade's generated execution hook and the Query adapter share the same
140
+ validator. Standalone generated procedures enforce the same execution rules with
141
+ native `TypeError` failures, without adding an SDK runtime dependency. An
142
+ `idempotency-key` in request input, global headers or interceptors never replaces
143
+ the execution key. The captured execution key wins over header overrides.
144
+ Existing header-only procedure calls must move the key to the execution argument
145
+ when regenerating; callable route methods retain their original conventions.
package/QUERY.md CHANGED
@@ -18,18 +18,23 @@ The adapter targets Query Core `^5.104.1`; the integration tests use Svelte Quer
18
18
  and the adapter has no runtime dependency on Supabase, Svelte or Query Core.
19
19
 
20
20
  Regenerate `client.ts` with a compiler that emits `__supacloudProcedure` metadata.
21
+ Procedures must be callable asynchronous functions; metadata-only objects and
22
+ synchronous functions are rejected by the type contract. Invalid runtime shapes
23
+ are rejected before creating query or mutation options.
21
24
  Earlier generated clients remain usable directly, but cannot use these options
22
25
  until regenerated. Existing route calls, response validation, interceptors,
23
26
  `.query()` and `.mutate()` argument conventions are unchanged.
24
27
 
25
28
  ```ts
26
- import { createSupaCloudApiFetch } from "@supacloud/js";
29
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
27
30
  import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
28
31
  import { createApiClient } from "./generated/client";
29
32
 
30
33
  // Reuse the application's existing user-scoped Supabase client.
31
- const api = createApiClient({
32
- fetch: createSupaCloudApiFetch({ supabase, functionName: "app-api" }),
34
+ const api = createSupaCloudProcedureClient({
35
+ supabase,
36
+ functionName: "app-api",
37
+ generated: createApiClient,
33
38
  });
34
39
  const queries = createSupaCloudQueryAdapter({
35
40
  keyPrefix: [projectUrl, "app-api", tenantId, actorId],
@@ -39,6 +44,8 @@ const queries = createSupaCloudQueryAdapter({
39
44
  The Supabase client still owns session storage, refresh, auth headers, Database,
40
45
  Storage, Realtime and Functions. No second token store or fetch/auth protocol is
41
46
  introduced. This adapter works with other generated-client transports as well.
47
+ See [Procedure Facade](./PROCEDURES.md) for incremental migration and unified
48
+ errors. `createApiClient({ fetch: createSupaCloudApiFetch(...) })` remains supported.
42
49
 
43
50
  ## Query Options
44
51
 
@@ -68,7 +75,8 @@ are adapter-owned.
68
75
  Query cancellation forwards TanStack's signal into the generated client.
69
76
  No-content query results are normalized from `undefined` to `null`, because
70
77
  TanStack cannot cache `undefined`; direct procedure and mutation results remain
71
- unchanged. HTTP/validation errors retain the generated client's error metadata.
78
+ unchanged. With the facade, HTTP/validation failures use `SupaCloudProcedureError`;
79
+ direct generated clients retain their original error classes.
72
80
  Schema-declared non-2xx responses retain the generated client's typed-data
73
81
  semantics; this adapter does not reclassify them as exceptions.
74
82
 
@@ -141,6 +149,16 @@ Each invocation supplies `{ input, execution }`. A required command idempotency
141
149
  key is required both by TypeScript and at runtime. It belongs to the logical
142
150
  operation, not to the component or mutation-options factory. Reuse it only when
143
151
  reconciling/retrying the same operation, never for a different write.
152
+ The adapter and facade share execution validation. Missing, empty, oversized and
153
+ invalid-character keys reject with `SupaCloudProcedureError` and
154
+ `SUPACLOUD_EXECUTION_ERROR` before dispatch, including when adapting direct
155
+ generated clients or custom procedures. An input `idempotency-key` header cannot
156
+ replace the per-invocation execution key. Standalone generated procedures enforce
157
+ the same execution rules with native `TypeError` failures; legacy callable routes
158
+ retain their original header conventions.
159
+
160
+ Use `isSupaCloudProcedureError` from `@supacloud/js` rather than relying on
161
+ constructor identity when catching errors from separately bundled entrypoints.
144
162
 
145
163
  Mutations set `retry: false`, including when QueryClient defaults enable retry.
146
164
  An unknown outcome is not permission to retry; first resolve the server outcome.
package/README.md CHANGED
@@ -60,6 +60,26 @@ peer range compatible with a newer SDK.
60
60
 
61
61
  ## Quick Start
62
62
 
63
+ Use [`createSupaCloudProcedureClient`](./PROCEDURES.md) to initialize a generated
64
+ application client with the existing Supabase session:
65
+
66
+ ```ts
67
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
68
+ import { createApiClient } from "./generated/client";
69
+
70
+ const api = createSupaCloudProcedureClient({
71
+ supabase,
72
+ functionName: "app-api",
73
+ generated: createApiClient,
74
+ generatedConfig: { normalize: false },
75
+ });
76
+
77
+ const detail = await api.cases.detail.query({ params: { id: "case-1" } });
78
+ ```
79
+
80
+ The facade preserves route overloads and adds `SupaCloudProcedureError`, original
81
+ Functions errors, and HTTP metadata. It does not replace Supabase JS or retry writes.
82
+
63
83
  For compiler-generated application procedures, the optional
64
84
  [`@supacloud/js/query`](./QUERY.md) entrypoint provides typed TanStack Query options,
65
85
  identity-scoped cache keys, cancellation and per-invocation mutation idempotency.
@@ -6,6 +6,8 @@ export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = Supab
6
6
  /** The deployed Edge Function name that hosts the generated application routes. */
7
7
  functionName: string;
8
8
  }
9
+ /** Returns the original Supabase Functions error associated with a response. */
10
+ export declare function getSupaCloudApiFetchError(response: Response): unknown | undefined;
9
11
  /**
10
12
  * Adapts the generated application client to the official Supabase Function
11
13
  * transport without creating a second auth/session implementation.
@@ -6,6 +6,8 @@ export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = Supab
6
6
  /** The deployed Edge Function name that hosts the generated application routes. */
7
7
  functionName: string;
8
8
  }
9
+ /** Returns the original Supabase Functions error associated with a response. */
10
+ export declare function getSupaCloudApiFetchError(response: Response): unknown | undefined;
9
11
  /**
10
12
  * Adapts the generated application client to the official Supabase Function
11
13
  * transport without creating a second auth/session implementation.
package/dist/index.cjs CHANGED
@@ -51,6 +51,7 @@ __export(exports_src, {
51
51
  SupaCloudOAuthClientsClient: () => SupaCloudOAuthClientsClient,
52
52
  SupaCloudOAuthServerClient: () => SupaCloudOAuthServerClient,
53
53
  SupaCloudOAuthServerError: () => SupaCloudOAuthServerError,
54
+ SupaCloudProcedureError: () => SupaCloudProcedureError,
54
55
  SupaCloudQueueError: () => SupaCloudQueueError,
55
56
  SupaCloudTaskAuthenticationError: () => SupaCloudTaskAuthenticationError,
56
57
  SupaCloudTaskDecodeError: () => SupaCloudTaskDecoderError,
@@ -73,11 +74,16 @@ __export(exports_src, {
73
74
  createSupaCloudClient: () => createSupaCloudClient,
74
75
  createSupaCloudCommandFetch: () => createSupaCloudCommandFetch,
75
76
  createSupaCloudOAuthFetch: () => createSupaCloudOAuthFetch,
77
+ createSupaCloudProcedureClient: () => createSupaCloudProcedureClient,
76
78
  createSupaCloudTaskFetch: () => createSupaCloudTaskFetch,
77
- createSupaCloudWorkflowFetch: () => createSupaCloudWorkflowFetch
79
+ createSupaCloudWorkflowFetch: () => createSupaCloudWorkflowFetch,
80
+ isSupaCloudProcedureError: () => isSupaCloudProcedureError,
81
+ isSupaCloudProcedureErrorCode: () => isSupaCloudProcedureErrorCode,
82
+ isSupaCloudProcedureHttpError: () => isSupaCloudProcedureHttpError,
83
+ isSupaCloudProcedureTransportError: () => isSupaCloudProcedureTransportError
78
84
  });
79
85
  module.exports = __toCommonJS(exports_src);
80
- var import_supabase_js = require("@supabase/supabase-js");
86
+ var import_supabase_js2 = require("@supabase/supabase-js");
81
87
 
82
88
  // src/workflow-rpc.ts
83
89
  function invokeWorkflowMutation(supabase, functionName, request, unconfirmed) {
@@ -2489,6 +2495,10 @@ function createSupaCloudArtifactFetch(options = {}) {
2489
2495
  return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
2490
2496
  }
2491
2497
  // src/api-fetch.ts
2498
+ var invocationErrors = new WeakMap;
2499
+ function getSupaCloudApiFetchError(response) {
2500
+ return invocationErrors.get(response);
2501
+ }
2492
2502
  function isRecord4(value) {
2493
2503
  return value !== null && typeof value === "object" && !Array.isArray(value);
2494
2504
  }
@@ -2569,6 +2579,7 @@ function createSupaCloudApiFetch(options) {
2569
2579
  delete headers[key];
2570
2580
  }
2571
2581
  }
2582
+ request.signal.throwIfAborted();
2572
2583
  const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
2573
2584
  ...body === undefined ? {} : { body },
2574
2585
  ...Object.keys(headers).length === 0 ? {} : { headers },
@@ -2576,8 +2587,10 @@ function createSupaCloudApiFetch(options) {
2576
2587
  signal: request.signal
2577
2588
  });
2578
2589
  if (invocation.error !== null && invocation.error !== undefined) {
2579
- if (invocation.response instanceof Response)
2590
+ if (invocation.response instanceof Response) {
2591
+ invocationErrors.set(invocation.response, invocation.error);
2580
2592
  return invocation.response;
2593
+ }
2581
2594
  if (invocation.error instanceof Error)
2582
2595
  throw invocation.error;
2583
2596
  throw new Error(errorMessage(invocation.error));
@@ -2585,6 +2598,213 @@ function createSupaCloudApiFetch(options) {
2585
2598
  return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
2586
2599
  };
2587
2600
  }
2601
+ // src/procedure-client.ts
2602
+ var import_supabase_js = require("@supabase/supabase-js");
2603
+
2604
+ // src/procedure-error.ts
2605
+ var procedureErrorCodes = new Set([
2606
+ "API_HTTP_ERROR",
2607
+ "API_RESPONSE_INVALID",
2608
+ "API_RESPONSE_UNDECLARED",
2609
+ "SUPACLOUD_EXECUTION_ERROR",
2610
+ "SUPACLOUD_FUNCTIONS_ERROR",
2611
+ "SUPACLOUD_TRANSPORT_ERROR",
2612
+ "SUPACLOUD_CLIENT_ERROR"
2613
+ ]);
2614
+ function isSupaCloudProcedureErrorCode(value) {
2615
+ return typeof value === "string" && procedureErrorCodes.has(value);
2616
+ }
2617
+ function procedureErrorIdentifier(value) {
2618
+ return typeof value === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value) ? value : undefined;
2619
+ }
2620
+
2621
+ class SupaCloudProcedureError extends Error {
2622
+ code;
2623
+ status;
2624
+ requestId;
2625
+ upstreamCode;
2626
+ details;
2627
+ response;
2628
+ cause;
2629
+ constructor(message, options) {
2630
+ super(message, { cause: options.cause });
2631
+ this.name = "SupaCloudProcedureError";
2632
+ this.code = options.code;
2633
+ this.status = options.status ?? null;
2634
+ this.requestId = procedureErrorIdentifier(options.requestId) ?? null;
2635
+ this.upstreamCode = procedureErrorIdentifier(options.upstreamCode) ?? null;
2636
+ this.details = options.details;
2637
+ this.response = options.response;
2638
+ this.cause = options.cause;
2639
+ Object.defineProperty(this, "response", { enumerable: false });
2640
+ Object.defineProperty(this, "cause", { enumerable: false });
2641
+ Object.defineProperty(this, "upstreamCode", { enumerable: false });
2642
+ Object.defineProperty(this, "details", { enumerable: false });
2643
+ }
2644
+ }
2645
+ function isSupaCloudProcedureError(value) {
2646
+ 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;
2647
+ }
2648
+ function isSupaCloudProcedureHttpError(value) {
2649
+ return isSupaCloudProcedureError(value) && typeof value.status === "number" && value.response instanceof Response;
2650
+ }
2651
+ function isSupaCloudProcedureTransportError(value) {
2652
+ return isSupaCloudProcedureError(value) && (value.code === "SUPACLOUD_FUNCTIONS_ERROR" || value.code === "SUPACLOUD_TRANSPORT_ERROR");
2653
+ }
2654
+
2655
+ // src/procedure-runtime.ts
2656
+ var idempotencyKeyPattern = /^[A-Za-z0-9._:-]{1,512}$/;
2657
+ function isValidSupaCloudIdempotencyKey(value) {
2658
+ return typeof value === "string" && idempotencyKeyPattern.test(value);
2659
+ }
2660
+ function isRecord5(value) {
2661
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2662
+ }
2663
+ function validateSupaCloudProcedureExecution(metadata, execution) {
2664
+ if (execution !== undefined && !isRecord5(execution)) {
2665
+ throw new SupaCloudProcedureError("Procedure execution must be an options object", {
2666
+ code: "SUPACLOUD_EXECUTION_ERROR"
2667
+ });
2668
+ }
2669
+ const signal = isRecord5(execution) ? execution.signal : undefined;
2670
+ if (signal !== undefined && (typeof AbortSignal === "undefined" || !(signal instanceof AbortSignal))) {
2671
+ throw new SupaCloudProcedureError("Procedure signal must be an AbortSignal", {
2672
+ code: "SUPACLOUD_EXECUTION_ERROR"
2673
+ });
2674
+ }
2675
+ const key = isRecord5(execution) ? execution.idempotencyKey : undefined;
2676
+ if (metadata.idempotency === "required" && key === undefined || key !== undefined && !isValidSupaCloudIdempotencyKey(key)) {
2677
+ throw new SupaCloudProcedureError("This procedure requires a valid idempotencyKey", {
2678
+ code: "SUPACLOUD_EXECUTION_ERROR"
2679
+ });
2680
+ }
2681
+ }
2682
+
2683
+ // src/procedure-client.ts
2684
+ function isRecord6(value) {
2685
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2686
+ }
2687
+ function asGeneratedError(value) {
2688
+ if (!isRecord6(value) || !(value instanceof Error))
2689
+ return;
2690
+ 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))
2691
+ return;
2692
+ return { code: value.code, status: value.status, requestId: value.requestId, response: value.response };
2693
+ }
2694
+ async function readErrorBody(response) {
2695
+ if (response === undefined || response.ok || response.bodyUsed || !response.body)
2696
+ return;
2697
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
2698
+ if (type !== "application/json" && !type?.endsWith("+json"))
2699
+ return;
2700
+ const maxBytes = 64 * 1024;
2701
+ const length = response.headers.get("content-length");
2702
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
2703
+ return;
2704
+ let reader;
2705
+ let timer;
2706
+ let finished = false;
2707
+ try {
2708
+ reader = response.clone().body?.getReader();
2709
+ if (!reader)
2710
+ return;
2711
+ const current = reader;
2712
+ const read = async () => {
2713
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2714
+ let bytes = 0;
2715
+ let text = "";
2716
+ while (!finished) {
2717
+ const chunk = await current.read();
2718
+ if (finished)
2719
+ return;
2720
+ if (chunk.done) {
2721
+ const body = JSON.parse(text + decoder.decode());
2722
+ return isRecord6(body) ? body : undefined;
2723
+ }
2724
+ bytes += chunk.value.byteLength;
2725
+ if (bytes > maxBytes)
2726
+ return;
2727
+ text += decoder.decode(chunk.value, { stream: true });
2728
+ }
2729
+ return;
2730
+ };
2731
+ return await Promise.race([
2732
+ read(),
2733
+ new Promise((resolve) => {
2734
+ timer = setTimeout(() => resolve(undefined), 250);
2735
+ })
2736
+ ]);
2737
+ } catch {
2738
+ return;
2739
+ } finally {
2740
+ finished = true;
2741
+ clearTimeout(timer);
2742
+ reader?.cancel().catch(() => {});
2743
+ }
2744
+ }
2745
+ function errorName(error) {
2746
+ return isRecord6(error) && typeof error.name === "string" ? error.name : undefined;
2747
+ }
2748
+ async function normalizeProcedureError(error, transport = false) {
2749
+ if (isSupaCloudProcedureError(error))
2750
+ return error;
2751
+ const generated = asGeneratedError(error);
2752
+ const knownTransportFailure = error instanceof import_supabase_js.FunctionsFetchError || error instanceof import_supabase_js.FunctionsRelayError || error instanceof import_supabase_js.FunctionsHttpError;
2753
+ if (generated === undefined && !knownTransportFailure && !transport)
2754
+ return error;
2755
+ if (errorName(error) === "AbortError")
2756
+ return error;
2757
+ if (errorName(error) === "FunctionsFetchError" && isRecord6(error) && errorName(error.context) === "AbortError")
2758
+ return error.context;
2759
+ const responseDecodeFailure = transport && error instanceof SyntaxError;
2760
+ const response = generated?.response instanceof Response ? generated.response : isRecord6(error) && error.context instanceof Response ? error.context : undefined;
2761
+ const original = response === undefined ? undefined : getSupaCloudApiFetchError(response);
2762
+ const cause = original ?? error;
2763
+ const responseBody = await readErrorBody(response);
2764
+ const name = errorName(cause);
2765
+ const message = error instanceof Error ? error.message : "SupaCloud procedure failed";
2766
+ 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";
2767
+ const code = name !== "FunctionsRelayError" && generated?.code && isSupaCloudProcedureErrorCode(generated.code) ? generated.code : fallback;
2768
+ const upstreamCode = procedureErrorIdentifier(responseBody?.code) ?? (generated && !isSupaCloudProcedureErrorCode(generated.code) ? procedureErrorIdentifier(generated.code) : undefined);
2769
+ return new SupaCloudProcedureError(message, {
2770
+ code,
2771
+ status: generated?.status ?? response?.status ?? null,
2772
+ requestId: procedureErrorIdentifier(generated?.requestId) ?? procedureErrorIdentifier(response?.headers.get("x-request-id")) ?? procedureErrorIdentifier(responseBody?.requestId) ?? null,
2773
+ upstreamCode: upstreamCode ?? null,
2774
+ details: responseBody,
2775
+ response,
2776
+ cause
2777
+ });
2778
+ }
2779
+ function createSupaCloudProcedureClient(options) {
2780
+ const transport = createSupaCloudApiFetch({
2781
+ supabase: options.supabase,
2782
+ functionName: options.functionName
2783
+ });
2784
+ const fetch2 = async (input, init) => {
2785
+ try {
2786
+ const response = await transport(input, init);
2787
+ const error = getSupaCloudApiFetchError(response);
2788
+ if (error !== undefined && (response.ok || errorName(error) === "FunctionsRelayError"))
2789
+ throw error;
2790
+ return response;
2791
+ } catch (error) {
2792
+ throw await normalizeProcedureError(error, true);
2793
+ }
2794
+ };
2795
+ const generatedConfig = {
2796
+ ...options.generatedConfig ?? {},
2797
+ fetch: fetch2,
2798
+ errorMapper: normalizeProcedureError,
2799
+ procedureExecutionValidator: validateSupaCloudProcedureExecution
2800
+ };
2801
+ const client = options.generated(generatedConfig);
2802
+ const capabilities = Reflect.get(client, "__supacloudClient");
2803
+ if (!isRecord6(capabilities) || capabilities.hooksVersion !== 1) {
2804
+ throw new TypeError("Regenerate the application client to enable procedure error and execution hooks");
2805
+ }
2806
+ return client;
2807
+ }
2588
2808
 
2589
2809
  // src/index.ts
2590
2810
  class SupaCloudTaskSubmitError extends Error {
@@ -3301,11 +3521,11 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
3301
3521
  const { data, error, response } = invocation;
3302
3522
  const boundedHttpFailure = response instanceof Response && boundedTaskHttpFailures.delete(response);
3303
3523
  if (error !== null && error !== undefined) {
3304
- if (error instanceof import_supabase_js.FunctionsHttpError && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
3524
+ if (error instanceof import_supabase_js2.FunctionsHttpError && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
3305
3525
  throw error;
3306
3526
  }
3307
3527
  if (boundedHttpFailure && response instanceof Response && !response.redirected && response.status >= 400 && response.status < 500 && matchesForeignTaskHttpError(error, response)) {
3308
- throw new import_supabase_js.FunctionsHttpError(response);
3528
+ throw new import_supabase_js2.FunctionsHttpError(response);
3309
3529
  }
3310
3530
  if (response instanceof Response)
3311
3531
  response.body?.cancel().catch(() => {});
package/dist/index.d.cts CHANGED
@@ -16,7 +16,8 @@ export * from "./workflows.cjs";
16
16
  export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from "./workflow-fetch.cjs";
17
17
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.cjs";
18
18
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.cjs";
19
- export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions } from "./api-fetch.cjs";
19
+ export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.cjs";
20
+ 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";
20
21
  export * from "./commands.cjs";
21
22
  export * from "./artifacts.cjs";
22
23
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
package/dist/index.d.mts CHANGED
@@ -16,7 +16,8 @@ export * from "./workflows.mjs";
16
16
  export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from "./workflow-fetch.mjs";
17
17
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.mjs";
18
18
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.mjs";
19
- export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions } from "./api-fetch.mjs";
19
+ export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.mjs";
20
+ 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";
20
21
  export * from "./commands.mjs";
21
22
  export * from "./artifacts.mjs";
22
23
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";