@supacloud/js 0.38.0 → 0.39.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/PROCEDURES.md ADDED
@@ -0,0 +1,100 @@
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
+ Existing `createApiClient({ fetch: createSupaCloudApiFetch(...) })` initialization
32
+ remains supported and retains the original error classes. Switch initialization
33
+ to the facade when ready; successful values, route decoder overloads and
34
+ `.query/.mutate` argument types are unchanged. Existing `api.cases.detail(input)`
35
+ calls also work through the facade. The facade normalizes failures from routes,
36
+ procedures and `api.request`; `buildRouteUrl` stays synchronous.
37
+
38
+ Facade `.mutate` calls with required idempotency must supply an execution key.
39
+ Direct generated procedures may still satisfy the legacy runtime check with an
40
+ explicit `idempotency-key` request header. Legacy callable routes retain their old
41
+ header and argument conventions. Extra generated-client settings can still be applied with
42
+ `generated: config => createApiClient({ ...config, normalize: false })`.
43
+ Do not override `config.fetch` or introduce retrying interceptors in that factory.
44
+
45
+ The same procedures work with the optional
46
+ [`@supacloud/js/query`](./QUERY.md) adapter and ordinary Svelte/React Query bindings.
47
+ The facade does not create a cache or import a framework runtime.
48
+
49
+ ## Errors
50
+
51
+ `SupaCloudProcedureError` exposes:
52
+
53
+ - `code`: generated API or SupaCloud transport classification
54
+ - `status`: HTTP status, or `null` when no response was received
55
+ - `requestId`: bounded `x-request-id` (or the JSON body's `requestId`), or `null`
56
+ - `details`: the full JSON error body when available, including any domain `code`
57
+ - `response`: the original HTTP `Response` when available
58
+ - `cause`: the original Supabase `FunctionsHttpError`, fetch error or client error
59
+
60
+ ```ts
61
+ import { FunctionsHttpError } from "@supabase/supabase-js";
62
+ import { SupaCloudProcedureError } from "@supacloud/js";
63
+
64
+ try {
65
+ await api.cases.detail.query({ params: { id: "case-1" } });
66
+ } catch (error) {
67
+ if (!(error instanceof SupaCloudProcedureError)) throw error;
68
+ console.error(error.code, error.status, error.requestId);
69
+ if (error.cause instanceof FunctionsHttpError) {
70
+ // Identical to error.response; its body has not been consumed by the facade.
71
+ const body: unknown = await error.cause.context.json();
72
+ }
73
+ }
74
+ ```
75
+
76
+ HTTP failures use `API_HTTP_ERROR`; JSON/schema failures use
77
+ `API_RESPONSE_INVALID` and undeclared success statuses use
78
+ `API_RESPONSE_UNDECLARED`. Network and relay failures use
79
+ `SUPACLOUD_TRANSPORT_ERROR` and `SUPACLOUD_FUNCTIONS_ERROR`; other client failures
80
+ use `SUPACLOUD_CLIENT_ERROR`. Invalid idempotency uses `SUPACLOUD_EXECUTION_ERROR`.
81
+ Native `AbortError` cancellation remains unchanged.
82
+
83
+ Error-body inspection reads only a clone of JSON failures, at most 64 KiB and
84
+ 250 ms. Non-JSON, oversized, malformed or stalled bodies leave `details`
85
+ undefined without hiding the HTTP failure. Treat details as untrusted data.
86
+ `details`, `response` and `cause` are excluded from JSON serialization.
87
+ Successful response bodies may already be consumed when schema validation fails;
88
+ their status and headers remain available. If Supabase fails before returning a
89
+ response (including malformed success JSON), the original error is kept as
90
+ `cause`, but no HTTP status is fabricated.
91
+
92
+ ## Mutation Safety
93
+
94
+ Mutations are never retried by this facade. Commands that declare required
95
+ idempotency reject before dispatch unless an invocation supplies a valid
96
+ `idempotencyKey`. Declared non-2xx response schemas retain the generated
97
+ client's typed-value behavior instead of being reclassified as exceptions.
98
+ Reuse the key only for the same logical operation. A failed or cancelled request
99
+ does not prove that a write rolled back; resolve uncertain outcomes before retrying.
100
+ The facade does not implement server-side idempotency or durable command receipts.
package/QUERY.md CHANGED
@@ -23,13 +23,15 @@ until regenerated. Existing route calls, response validation, interceptors,
23
23
  `.query()` and `.mutate()` argument conventions are unchanged.
24
24
 
25
25
  ```ts
26
- import { createSupaCloudApiFetch } from "@supacloud/js";
26
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
27
27
  import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
28
28
  import { createApiClient } from "./generated/client";
29
29
 
30
30
  // Reuse the application's existing user-scoped Supabase client.
31
- const api = createApiClient({
32
- fetch: createSupaCloudApiFetch({ supabase, functionName: "app-api" }),
31
+ const api = createSupaCloudProcedureClient({
32
+ supabase,
33
+ functionName: "app-api",
34
+ generated: createApiClient,
33
35
  });
34
36
  const queries = createSupaCloudQueryAdapter({
35
37
  keyPrefix: [projectUrl, "app-api", tenantId, actorId],
@@ -39,6 +41,8 @@ const queries = createSupaCloudQueryAdapter({
39
41
  The Supabase client still owns session storage, refresh, auth headers, Database,
40
42
  Storage, Realtime and Functions. No second token store or fetch/auth protocol is
41
43
  introduced. This adapter works with other generated-client transports as well.
44
+ See [Procedure Facade](./PROCEDURES.md) for incremental migration and unified
45
+ errors. `createApiClient({ fetch: createSupaCloudApiFetch(...) })` remains supported.
42
46
 
43
47
  ## Query Options
44
48
 
@@ -68,7 +72,8 @@ are adapter-owned.
68
72
  Query cancellation forwards TanStack's signal into the generated client.
69
73
  No-content query results are normalized from `undefined` to `null`, because
70
74
  TanStack cannot cache `undefined`; direct procedure and mutation results remain
71
- unchanged. HTTP/validation errors retain the generated client's error metadata.
75
+ unchanged. With the facade, HTTP/validation failures use `SupaCloudProcedureError`;
76
+ direct generated clients retain their original error classes.
72
77
  Schema-declared non-2xx responses retain the generated client's typed-data
73
78
  semantics; this adapter does not reclassify them as exceptions.
74
79
 
@@ -141,6 +146,11 @@ Each invocation supplies `{ input, execution }`. A required command idempotency
141
146
  key is required both by TypeScript and at runtime. It belongs to the logical
142
147
  operation, not to the component or mutation-options factory. Reuse it only when
143
148
  reconciling/retrying the same operation, never for a different write.
149
+ The facade validates execution keys; direct generated procedures retain their
150
+ legacy header checks. With the facade, invalid mutation
151
+ execution settings reject with `SupaCloudProcedureError` and
152
+ `SUPACLOUD_EXECUTION_ERROR` before dispatch; direct generated clients retain their
153
+ original validation errors.
144
154
 
145
155
  Mutations set `retry: false`, including when QueryClient defaults enable retry.
146
156
  An unknown outcome is not permission to retry; first resolve the server outcome.
package/README.md CHANGED
@@ -60,6 +60,25 @@ 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
+ });
75
+
76
+ const detail = await api.cases.detail.query({ params: { id: "case-1" } });
77
+ ```
78
+
79
+ The facade preserves route overloads and adds `SupaCloudProcedureError`, original
80
+ Functions errors, and HTTP metadata. It does not replace Supabase JS or retry writes.
81
+
63
82
  For compiler-generated application procedures, the optional
64
83
  [`@supacloud/js/query`](./QUERY.md) entrypoint provides typed TanStack Query options,
65
84
  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,6 +74,7 @@ __export(exports_src, {
73
74
  createSupaCloudClient: () => createSupaCloudClient,
74
75
  createSupaCloudCommandFetch: () => createSupaCloudCommandFetch,
75
76
  createSupaCloudOAuthFetch: () => createSupaCloudOAuthFetch,
77
+ createSupaCloudProcedureClient: () => createSupaCloudProcedureClient,
76
78
  createSupaCloudTaskFetch: () => createSupaCloudTaskFetch,
77
79
  createSupaCloudWorkflowFetch: () => createSupaCloudWorkflowFetch
78
80
  });
@@ -2489,6 +2491,10 @@ function createSupaCloudArtifactFetch(options = {}) {
2489
2491
  return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
2490
2492
  }
2491
2493
  // src/api-fetch.ts
2494
+ var invocationErrors = new WeakMap;
2495
+ function getSupaCloudApiFetchError(response) {
2496
+ return invocationErrors.get(response);
2497
+ }
2492
2498
  function isRecord4(value) {
2493
2499
  return value !== null && typeof value === "object" && !Array.isArray(value);
2494
2500
  }
@@ -2569,6 +2575,7 @@ function createSupaCloudApiFetch(options) {
2569
2575
  delete headers[key];
2570
2576
  }
2571
2577
  }
2578
+ request.signal.throwIfAborted();
2572
2579
  const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
2573
2580
  ...body === undefined ? {} : { body },
2574
2581
  ...Object.keys(headers).length === 0 ? {} : { headers },
@@ -2576,8 +2583,10 @@ function createSupaCloudApiFetch(options) {
2576
2583
  signal: request.signal
2577
2584
  });
2578
2585
  if (invocation.error !== null && invocation.error !== undefined) {
2579
- if (invocation.response instanceof Response)
2586
+ if (invocation.response instanceof Response) {
2587
+ invocationErrors.set(invocation.response, invocation.error);
2580
2588
  return invocation.response;
2589
+ }
2581
2590
  if (invocation.error instanceof Error)
2582
2591
  throw invocation.error;
2583
2592
  throw new Error(errorMessage(invocation.error));
@@ -2585,6 +2594,187 @@ function createSupaCloudApiFetch(options) {
2585
2594
  return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
2586
2595
  };
2587
2596
  }
2597
+ // src/procedure-error.ts
2598
+ function procedureErrorIdentifier(value) {
2599
+ return typeof value === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value) ? value : undefined;
2600
+ }
2601
+
2602
+ class SupaCloudProcedureError extends Error {
2603
+ code;
2604
+ status;
2605
+ requestId;
2606
+ details;
2607
+ response;
2608
+ cause;
2609
+ constructor(message, options) {
2610
+ super(message, { cause: options.cause });
2611
+ this.name = "SupaCloudProcedureError";
2612
+ this.code = options.code;
2613
+ this.status = options.status ?? null;
2614
+ this.requestId = procedureErrorIdentifier(options.requestId) ?? null;
2615
+ this.details = options.details;
2616
+ this.response = options.response;
2617
+ this.cause = options.cause;
2618
+ Object.defineProperty(this, "response", { enumerable: false });
2619
+ Object.defineProperty(this, "cause", { enumerable: false });
2620
+ Object.defineProperty(this, "details", { enumerable: false });
2621
+ }
2622
+ }
2623
+
2624
+ // src/procedure-client.ts
2625
+ function isRecord5(value) {
2626
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2627
+ }
2628
+ function asGeneratedError(value) {
2629
+ if (!isRecord5(value))
2630
+ return;
2631
+ if (value.name !== "ApiClientError" || typeof value.code !== "string" || typeof value.status !== "number")
2632
+ return;
2633
+ return { code: value.code, status: value.status, requestId: value.requestId, response: value.response };
2634
+ }
2635
+ async function readErrorBody(response) {
2636
+ if (response === undefined || response.ok || response.bodyUsed || !response.body)
2637
+ return;
2638
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
2639
+ if (type !== "application/json" && !type?.endsWith("+json"))
2640
+ return;
2641
+ const maxBytes = 64 * 1024;
2642
+ const length = response.headers.get("content-length");
2643
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
2644
+ return;
2645
+ let reader;
2646
+ let timer;
2647
+ let finished = false;
2648
+ try {
2649
+ reader = response.clone().body?.getReader();
2650
+ if (!reader)
2651
+ return;
2652
+ const current = reader;
2653
+ const read = async () => {
2654
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2655
+ let bytes = 0;
2656
+ let text = "";
2657
+ while (!finished) {
2658
+ const chunk = await current.read();
2659
+ if (finished)
2660
+ return;
2661
+ if (chunk.done) {
2662
+ const body = JSON.parse(text + decoder.decode());
2663
+ return isRecord5(body) ? body : undefined;
2664
+ }
2665
+ bytes += chunk.value.byteLength;
2666
+ if (bytes > maxBytes)
2667
+ return;
2668
+ text += decoder.decode(chunk.value, { stream: true });
2669
+ }
2670
+ return;
2671
+ };
2672
+ return await Promise.race([
2673
+ read(),
2674
+ new Promise((resolve) => {
2675
+ timer = setTimeout(() => resolve(undefined), 250);
2676
+ })
2677
+ ]);
2678
+ } catch {
2679
+ return;
2680
+ } finally {
2681
+ finished = true;
2682
+ clearTimeout(timer);
2683
+ reader?.cancel().catch(() => {});
2684
+ }
2685
+ }
2686
+ function errorName(error) {
2687
+ return isRecord5(error) && typeof error.name === "string" ? error.name : undefined;
2688
+ }
2689
+ async function normalizeProcedureError(error, transport = false) {
2690
+ if (error instanceof SupaCloudProcedureError)
2691
+ return error;
2692
+ if (errorName(error) === "AbortError")
2693
+ return error;
2694
+ if (errorName(error) === "FunctionsFetchError" && isRecord5(error) && errorName(error.context) === "AbortError")
2695
+ return error.context;
2696
+ const generated = asGeneratedError(error);
2697
+ const response = generated?.response instanceof Response ? generated.response : isRecord5(error) && error.context instanceof Response ? error.context : undefined;
2698
+ const original = response === undefined ? undefined : getSupaCloudApiFetchError(response);
2699
+ const cause = original ?? error;
2700
+ const responseBody = await readErrorBody(response);
2701
+ const name = errorName(cause);
2702
+ const message = error instanceof Error ? error.message : "SupaCloud procedure failed";
2703
+ 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";
2704
+ const code = name === "FunctionsRelayError" ? fallback : generated?.code ?? fallback;
2705
+ return new SupaCloudProcedureError(message, {
2706
+ code,
2707
+ status: generated?.status ?? response?.status ?? null,
2708
+ requestId: procedureErrorIdentifier(generated?.requestId) ?? procedureErrorIdentifier(response?.headers.get("x-request-id")) ?? procedureErrorIdentifier(responseBody?.requestId) ?? null,
2709
+ details: responseBody,
2710
+ response,
2711
+ cause
2712
+ });
2713
+ }
2714
+ function validateProcedureExecution(procedure, args) {
2715
+ const metadata = Reflect.get(procedure, "__supacloudProcedure");
2716
+ if (!isRecord5(metadata))
2717
+ return;
2718
+ const [first, second] = args;
2719
+ const execution = second ?? (isRecord5(first) && (Object.hasOwn(first, "idempotencyKey") || Object.hasOwn(first, "signal")) ? first : undefined);
2720
+ const key = isRecord5(execution) ? execution.idempotencyKey : undefined;
2721
+ if (metadata.idempotency === "required" && key === undefined || key !== undefined && (typeof key !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(key))) {
2722
+ throw new SupaCloudProcedureError("This procedure requires a valid idempotencyKey", {
2723
+ code: "SUPACLOUD_EXECUTION_ERROR"
2724
+ });
2725
+ }
2726
+ }
2727
+ function wrapGeneratedClient(client) {
2728
+ const cache = new WeakMap;
2729
+ const wrap = (value, level) => {
2730
+ const cached = cache.get(value);
2731
+ if (cached !== undefined)
2732
+ return cached;
2733
+ const proxy = new Proxy(value, {
2734
+ async apply(current, thisArg, args) {
2735
+ try {
2736
+ validateProcedureExecution(current, args);
2737
+ return await Reflect.apply(current, thisArg, args);
2738
+ } catch (failure) {
2739
+ throw await normalizeProcedureError(failure);
2740
+ }
2741
+ },
2742
+ get(current, key, receiver) {
2743
+ const member = Reflect.get(current, key, receiver);
2744
+ if (!Object.hasOwn(current, key))
2745
+ return member;
2746
+ if (typeof member === "function" && (level === "controller" || level === "client" && key === "request" || level === "call" && (key === "query" || key === "mutate"))) {
2747
+ return wrap(member, "call");
2748
+ }
2749
+ if (level === "client" && isRecord5(member) && Object.getPrototypeOf(member) === Object.prototype) {
2750
+ return wrap(member, "controller");
2751
+ }
2752
+ return member;
2753
+ }
2754
+ });
2755
+ cache.set(value, proxy);
2756
+ return proxy;
2757
+ };
2758
+ return wrap(client, "client");
2759
+ }
2760
+ function createSupaCloudProcedureClient(options) {
2761
+ const transport = createSupaCloudApiFetch({
2762
+ supabase: options.supabase,
2763
+ functionName: options.functionName
2764
+ });
2765
+ const fetch2 = async (input, init) => {
2766
+ try {
2767
+ const response = await transport(input, init);
2768
+ const error = getSupaCloudApiFetchError(response);
2769
+ if (error !== undefined && (response.ok || errorName(error) === "FunctionsRelayError"))
2770
+ throw error;
2771
+ return response;
2772
+ } catch (error) {
2773
+ throw await normalizeProcedureError(error, true);
2774
+ }
2775
+ };
2776
+ return wrapGeneratedClient(options.generated({ fetch: fetch2 }));
2777
+ }
2588
2778
 
2589
2779
  // src/index.ts
2590
2780
  class SupaCloudTaskSubmitError extends Error {
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, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, 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, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, 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";
package/dist/index.mjs CHANGED
@@ -2411,6 +2411,10 @@ function createSupaCloudArtifactFetch(options = {}) {
2411
2411
  return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
2412
2412
  }
2413
2413
  // src/api-fetch.ts
2414
+ var invocationErrors = new WeakMap;
2415
+ function getSupaCloudApiFetchError(response) {
2416
+ return invocationErrors.get(response);
2417
+ }
2414
2418
  function isRecord4(value) {
2415
2419
  return value !== null && typeof value === "object" && !Array.isArray(value);
2416
2420
  }
@@ -2491,6 +2495,7 @@ function createSupaCloudApiFetch(options) {
2491
2495
  delete headers[key];
2492
2496
  }
2493
2497
  }
2498
+ request.signal.throwIfAborted();
2494
2499
  const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
2495
2500
  ...body === undefined ? {} : { body },
2496
2501
  ...Object.keys(headers).length === 0 ? {} : { headers },
@@ -2498,8 +2503,10 @@ function createSupaCloudApiFetch(options) {
2498
2503
  signal: request.signal
2499
2504
  });
2500
2505
  if (invocation.error !== null && invocation.error !== undefined) {
2501
- if (invocation.response instanceof Response)
2506
+ if (invocation.response instanceof Response) {
2507
+ invocationErrors.set(invocation.response, invocation.error);
2502
2508
  return invocation.response;
2509
+ }
2503
2510
  if (invocation.error instanceof Error)
2504
2511
  throw invocation.error;
2505
2512
  throw new Error(errorMessage(invocation.error));
@@ -2507,6 +2514,187 @@ function createSupaCloudApiFetch(options) {
2507
2514
  return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
2508
2515
  };
2509
2516
  }
2517
+ // src/procedure-error.ts
2518
+ function procedureErrorIdentifier(value) {
2519
+ return typeof value === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value) ? value : undefined;
2520
+ }
2521
+
2522
+ class SupaCloudProcedureError extends Error {
2523
+ code;
2524
+ status;
2525
+ requestId;
2526
+ details;
2527
+ response;
2528
+ cause;
2529
+ constructor(message, options) {
2530
+ super(message, { cause: options.cause });
2531
+ this.name = "SupaCloudProcedureError";
2532
+ this.code = options.code;
2533
+ this.status = options.status ?? null;
2534
+ this.requestId = procedureErrorIdentifier(options.requestId) ?? null;
2535
+ this.details = options.details;
2536
+ this.response = options.response;
2537
+ this.cause = options.cause;
2538
+ Object.defineProperty(this, "response", { enumerable: false });
2539
+ Object.defineProperty(this, "cause", { enumerable: false });
2540
+ Object.defineProperty(this, "details", { enumerable: false });
2541
+ }
2542
+ }
2543
+
2544
+ // src/procedure-client.ts
2545
+ function isRecord5(value) {
2546
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2547
+ }
2548
+ function asGeneratedError(value) {
2549
+ if (!isRecord5(value))
2550
+ return;
2551
+ if (value.name !== "ApiClientError" || typeof value.code !== "string" || typeof value.status !== "number")
2552
+ return;
2553
+ return { code: value.code, status: value.status, requestId: value.requestId, response: value.response };
2554
+ }
2555
+ async function readErrorBody(response) {
2556
+ if (response === undefined || response.ok || response.bodyUsed || !response.body)
2557
+ return;
2558
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
2559
+ if (type !== "application/json" && !type?.endsWith("+json"))
2560
+ return;
2561
+ const maxBytes = 64 * 1024;
2562
+ const length = response.headers.get("content-length");
2563
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
2564
+ return;
2565
+ let reader;
2566
+ let timer;
2567
+ let finished = false;
2568
+ try {
2569
+ reader = response.clone().body?.getReader();
2570
+ if (!reader)
2571
+ return;
2572
+ const current = reader;
2573
+ const read = async () => {
2574
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2575
+ let bytes = 0;
2576
+ let text = "";
2577
+ while (!finished) {
2578
+ const chunk = await current.read();
2579
+ if (finished)
2580
+ return;
2581
+ if (chunk.done) {
2582
+ const body = JSON.parse(text + decoder.decode());
2583
+ return isRecord5(body) ? body : undefined;
2584
+ }
2585
+ bytes += chunk.value.byteLength;
2586
+ if (bytes > maxBytes)
2587
+ return;
2588
+ text += decoder.decode(chunk.value, { stream: true });
2589
+ }
2590
+ return;
2591
+ };
2592
+ return await Promise.race([
2593
+ read(),
2594
+ new Promise((resolve) => {
2595
+ timer = setTimeout(() => resolve(undefined), 250);
2596
+ })
2597
+ ]);
2598
+ } catch {
2599
+ return;
2600
+ } finally {
2601
+ finished = true;
2602
+ clearTimeout(timer);
2603
+ reader?.cancel().catch(() => {});
2604
+ }
2605
+ }
2606
+ function errorName(error) {
2607
+ return isRecord5(error) && typeof error.name === "string" ? error.name : undefined;
2608
+ }
2609
+ async function normalizeProcedureError(error, transport = false) {
2610
+ if (error instanceof SupaCloudProcedureError)
2611
+ return error;
2612
+ if (errorName(error) === "AbortError")
2613
+ return error;
2614
+ if (errorName(error) === "FunctionsFetchError" && isRecord5(error) && errorName(error.context) === "AbortError")
2615
+ 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;
2618
+ const original = response === undefined ? undefined : getSupaCloudApiFetchError(response);
2619
+ const cause = original ?? error;
2620
+ const responseBody = await readErrorBody(response);
2621
+ const name = errorName(cause);
2622
+ 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;
2625
+ return new SupaCloudProcedureError(message, {
2626
+ code,
2627
+ status: generated?.status ?? response?.status ?? null,
2628
+ requestId: procedureErrorIdentifier(generated?.requestId) ?? procedureErrorIdentifier(response?.headers.get("x-request-id")) ?? procedureErrorIdentifier(responseBody?.requestId) ?? null,
2629
+ details: responseBody,
2630
+ response,
2631
+ cause
2632
+ });
2633
+ }
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
+ function createSupaCloudProcedureClient(options) {
2681
+ const transport = createSupaCloudApiFetch({
2682
+ supabase: options.supabase,
2683
+ functionName: options.functionName
2684
+ });
2685
+ const fetch2 = async (input, init) => {
2686
+ try {
2687
+ const response = await transport(input, init);
2688
+ const error = getSupaCloudApiFetchError(response);
2689
+ if (error !== undefined && (response.ok || errorName(error) === "FunctionsRelayError"))
2690
+ throw error;
2691
+ return response;
2692
+ } catch (error) {
2693
+ throw await normalizeProcedureError(error, true);
2694
+ }
2695
+ };
2696
+ return wrapGeneratedClient(options.generated({ fetch: fetch2 }));
2697
+ }
2510
2698
 
2511
2699
  // src/index.ts
2512
2700
  class SupaCloudTaskSubmitError extends Error {
@@ -3763,6 +3951,7 @@ export {
3763
3951
  SupaCloudOAuthClientsClient,
3764
3952
  SupaCloudOAuthServerClient,
3765
3953
  SupaCloudOAuthServerError,
3954
+ SupaCloudProcedureError,
3766
3955
  SupaCloudQueueError,
3767
3956
  SupaCloudTaskAuthenticationError,
3768
3957
  SupaCloudTaskDecoderError as SupaCloudTaskDecodeError,
@@ -3785,6 +3974,7 @@ export {
3785
3974
  createSupaCloudClient,
3786
3975
  createSupaCloudCommandFetch,
3787
3976
  createSupaCloudOAuthFetch,
3977
+ createSupaCloudProcedureClient,
3788
3978
  createSupaCloudTaskFetch,
3789
3979
  createSupaCloudWorkflowFetch
3790
3980
  };
@@ -0,0 +1,21 @@
1
+ import type { SupabaseClient } from "./supabase-types.cjs";
2
+ import type { FetchTransport } from "./bounded-rpc-fetch.cjs";
3
+ export { SupaCloudProcedureError, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-error.cjs";
4
+ export interface SupaCloudGeneratedClientConfig {
5
+ fetch: FetchTransport;
6
+ }
7
+ export type SupaCloudGeneratedClientFactory<TClient extends object = object> = (config: SupaCloudGeneratedClientConfig) => TClient;
8
+ export interface SupaCloudProcedureClientOptions<TClient extends SupabaseClient, TFactory extends SupaCloudGeneratedClientFactory> {
9
+ /** The existing user-scoped Supabase client; it owns auth and session refresh. */
10
+ supabase: TClient;
11
+ /** The deployed Edge Function name hosting the generated application routes. */
12
+ functionName: string;
13
+ /** The generated createApiClient factory for the application contract. */
14
+ generated: TFactory;
15
+ }
16
+ export type SupaCloudProcedureClient<TFactory extends SupaCloudGeneratedClientFactory> = ReturnType<TFactory>;
17
+ /**
18
+ * Creates a typed procedure facade over a compiler-generated client while
19
+ * reusing Supabase JS for auth, refresh and Functions transport.
20
+ */
21
+ export declare function createSupaCloudProcedureClient<TFactory extends SupaCloudGeneratedClientFactory, TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudProcedureClientOptions<TClient, TFactory>): SupaCloudProcedureClient<TFactory>;
@@ -0,0 +1,21 @@
1
+ import type { SupabaseClient } from "./supabase-types.mjs";
2
+ import type { FetchTransport } from "./bounded-rpc-fetch.mjs";
3
+ export { SupaCloudProcedureError, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-error.mjs";
4
+ export interface SupaCloudGeneratedClientConfig {
5
+ fetch: FetchTransport;
6
+ }
7
+ export type SupaCloudGeneratedClientFactory<TClient extends object = object> = (config: SupaCloudGeneratedClientConfig) => TClient;
8
+ export interface SupaCloudProcedureClientOptions<TClient extends SupabaseClient, TFactory extends SupaCloudGeneratedClientFactory> {
9
+ /** The existing user-scoped Supabase client; it owns auth and session refresh. */
10
+ supabase: TClient;
11
+ /** The deployed Edge Function name hosting the generated application routes. */
12
+ functionName: string;
13
+ /** The generated createApiClient factory for the application contract. */
14
+ generated: TFactory;
15
+ }
16
+ export type SupaCloudProcedureClient<TFactory extends SupaCloudGeneratedClientFactory> = ReturnType<TFactory>;
17
+ /**
18
+ * Creates a typed procedure facade over a compiler-generated client while
19
+ * reusing Supabase JS for auth, refresh and Functions transport.
20
+ */
21
+ export declare function createSupaCloudProcedureClient<TFactory extends SupaCloudGeneratedClientFactory, TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudProcedureClientOptions<TClient, TFactory>): SupaCloudProcedureClient<TFactory>;
@@ -0,0 +1,21 @@
1
+ export type SupaCloudProcedureErrorCode = "API_HTTP_ERROR" | "API_RESPONSE_INVALID" | "API_RESPONSE_UNDECLARED" | "SUPACLOUD_EXECUTION_ERROR" | "SUPACLOUD_FUNCTIONS_ERROR" | "SUPACLOUD_TRANSPORT_ERROR" | "SUPACLOUD_CLIENT_ERROR";
2
+ export interface SupaCloudProcedureErrorOptions {
3
+ code: string;
4
+ status?: number | null;
5
+ requestId?: string | null;
6
+ details?: unknown;
7
+ response?: Response | undefined;
8
+ cause?: unknown;
9
+ }
10
+ /** Internal validation shared by error construction and response inspection. */
11
+ export declare function procedureErrorIdentifier(value: unknown): string | undefined;
12
+ /** Failure metadata is not proof that a server-side mutation rolled back. */
13
+ export declare class SupaCloudProcedureError extends Error {
14
+ readonly code: string;
15
+ readonly status: number | null;
16
+ readonly requestId: string | null;
17
+ readonly details: unknown;
18
+ readonly response: Response | undefined;
19
+ readonly cause: unknown;
20
+ constructor(message: string, options: SupaCloudProcedureErrorOptions);
21
+ }
@@ -0,0 +1,21 @@
1
+ export type SupaCloudProcedureErrorCode = "API_HTTP_ERROR" | "API_RESPONSE_INVALID" | "API_RESPONSE_UNDECLARED" | "SUPACLOUD_EXECUTION_ERROR" | "SUPACLOUD_FUNCTIONS_ERROR" | "SUPACLOUD_TRANSPORT_ERROR" | "SUPACLOUD_CLIENT_ERROR";
2
+ export interface SupaCloudProcedureErrorOptions {
3
+ code: string;
4
+ status?: number | null;
5
+ requestId?: string | null;
6
+ details?: unknown;
7
+ response?: Response | undefined;
8
+ cause?: unknown;
9
+ }
10
+ /** Internal validation shared by error construction and response inspection. */
11
+ export declare function procedureErrorIdentifier(value: unknown): string | undefined;
12
+ /** Failure metadata is not proof that a server-side mutation rolled back. */
13
+ export declare class SupaCloudProcedureError extends Error {
14
+ readonly code: string;
15
+ readonly status: number | null;
16
+ readonly requestId: string | null;
17
+ readonly details: unknown;
18
+ readonly response: Response | undefined;
19
+ readonly cause: unknown;
20
+ constructor(message: string, options: SupaCloudProcedureErrorOptions);
21
+ }
package/dist/query.cjs CHANGED
@@ -121,17 +121,12 @@ function createSupaCloudQueryAdapter({
121
121
  };
122
122
  }
123
123
  function mutationOptions(procedure, options) {
124
- const metadata = metadataOf(procedure, "mutation");
125
124
  return {
126
125
  ...options,
127
126
  mutationKey: procedureKey(procedure, "mutation"),
128
127
  retry: false,
129
128
  mutationFn: async (variables) => {
130
129
  const execution = variables.execution ?? {};
131
- const key = execution.idempotencyKey;
132
- if (metadata.idempotency === "required" && key === undefined || key !== undefined && (typeof key !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(key))) {
133
- throw new TypeError("This mutation requires a valid idempotencyKey");
134
- }
135
130
  return callProcedure(procedure, variables.input, execution);
136
131
  }
137
132
  };
package/dist/query.mjs CHANGED
@@ -78,17 +78,12 @@ function createSupaCloudQueryAdapter({
78
78
  };
79
79
  }
80
80
  function mutationOptions(procedure, options) {
81
- const metadata = metadataOf(procedure, "mutation");
82
81
  return {
83
82
  ...options,
84
83
  mutationKey: procedureKey(procedure, "mutation"),
85
84
  retry: false,
86
85
  mutationFn: async (variables) => {
87
86
  const execution = variables.execution ?? {};
88
- const key = execution.idempotencyKey;
89
- if (metadata.idempotency === "required" && key === undefined || key !== undefined && (typeof key !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(key))) {
90
- throw new TypeError("This mutation requires a valid idempotencyKey");
91
- }
92
87
  return callProcedure(procedure, variables.input, execution);
93
88
  }
94
89
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -64,6 +64,7 @@
64
64
  "dist",
65
65
  "README.md",
66
66
  "COMPATIBILITY.md",
67
+ "PROCEDURES.md",
67
68
  "QUERY.md",
68
69
  "REACTIVE.md"
69
70
  ],