@supacloud/js 0.36.1 → 0.38.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/QUERY.md +163 -0
- package/README.md +6 -0
- package/dist/api-fetch.d.cts +13 -0
- package/dist/api-fetch.d.mts +13 -0
- package/dist/index.cjs +98 -0
- package/dist/index.d.cts +1 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +98 -0
- package/dist/query.cjs +145 -0
- package/dist/query.d.cts +62 -0
- package/dist/query.d.mts +62 -0
- package/dist/query.mjs +105 -0
- package/package.json +26 -5
package/QUERY.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# TanStack Query Adapter
|
|
2
|
+
|
|
3
|
+
`@supacloud/js/query` adds framework-neutral options for compiler-generated
|
|
4
|
+
`.query` and `.mutate` procedures. Use the host's existing TanStack binding and
|
|
5
|
+
QueryClient; this entrypoint creates neither a cache nor an authentication store.
|
|
6
|
+
No Svelte-specific SDK entrypoint is needed.
|
|
7
|
+
|
|
8
|
+
## Installation And Migration
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @supacloud/js @supabase/supabase-js @tanstack/query-core
|
|
12
|
+
# Svelte applications also use their normal framework binding:
|
|
13
|
+
npm install @tanstack/svelte-query svelte
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The adapter targets Query Core `^5.104.1`; the integration tests use Svelte Query
|
|
17
|
+
`6.3.1`. Query Core is an optional peer. The root SDK does not import this adapter,
|
|
18
|
+
and the adapter has no runtime dependency on Supabase, Svelte or Query Core.
|
|
19
|
+
|
|
20
|
+
Regenerate `client.ts` with a compiler that emits `__supacloudProcedure` metadata.
|
|
21
|
+
Earlier generated clients remain usable directly, but cannot use these options
|
|
22
|
+
until regenerated. Existing route calls, response validation, interceptors,
|
|
23
|
+
`.query()` and `.mutate()` argument conventions are unchanged.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createSupaCloudApiFetch } from "@supacloud/js";
|
|
27
|
+
import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
|
|
28
|
+
import { createApiClient } from "./generated/client";
|
|
29
|
+
|
|
30
|
+
// Reuse the application's existing user-scoped Supabase client.
|
|
31
|
+
const api = createApiClient({
|
|
32
|
+
fetch: createSupaCloudApiFetch({ supabase, functionName: "app-api" }),
|
|
33
|
+
});
|
|
34
|
+
const queries = createSupaCloudQueryAdapter({
|
|
35
|
+
keyPrefix: [projectUrl, "app-api", tenantId, actorId],
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The Supabase client still owns session storage, refresh, auth headers, Database,
|
|
40
|
+
Storage, Realtime and Functions. No second token store or fetch/auth protocol is
|
|
41
|
+
introduced. This adapter works with other generated-client transports as well.
|
|
42
|
+
|
|
43
|
+
## Query Options
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
const input = { params: { id: "item-1" } };
|
|
47
|
+
const options = queries.queryOptions(api.items.detail.query, input, {
|
|
48
|
+
staleTime: 30_000,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// Works with QueryClient and the host's framework query hook.
|
|
52
|
+
const item = await queryClient.fetchQuery(options);
|
|
53
|
+
const cached = queryClient.getQueryData(options.queryKey);
|
|
54
|
+
|
|
55
|
+
// One exact input, or every input for this procedure in the same identity scope.
|
|
56
|
+
await queryClient.invalidateQueries({ queryKey: queries.queryKey(api.items.detail.query, input), exact: true });
|
|
57
|
+
await queryClient.invalidateQueries({ queryKey: queries.queryKey(api.items.detail.query) });
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Keys include the explicit namespace, query/mutation kind, HTTP method, route
|
|
61
|
+
template, and query input. Query inputs are immutable JSON snapshots: mutating an
|
|
62
|
+
input after building options cannot change the request under an old key. Cycles,
|
|
63
|
+
binary objects, functions and non-finite numbers are rejected for cached queries.
|
|
64
|
+
Pass `undefined` for a query with no required input. `select`, `enabled`, staleness
|
|
65
|
+
and other observer options remain TanStack options. Keys and request functions
|
|
66
|
+
are adapter-owned.
|
|
67
|
+
|
|
68
|
+
Query cancellation forwards TanStack's signal into the generated client.
|
|
69
|
+
No-content query results are normalized from `undefined` to `null`, because
|
|
70
|
+
TanStack cannot cache `undefined`; direct procedure and mutation results remain
|
|
71
|
+
unchanged. HTTP/validation errors retain the generated client's error metadata.
|
|
72
|
+
Schema-declared non-2xx responses retain the generated client's typed-data
|
|
73
|
+
semantics; this adapter does not reclassify them as exceptions.
|
|
74
|
+
|
|
75
|
+
The namespace is mandatory and must include all non-secret identities that
|
|
76
|
+
affect authorization and the target application/function. Recreate the adapter
|
|
77
|
+
on project, tenant or actor changes. Cancel/remove old scoped queries on logout;
|
|
78
|
+
do not preserve previous data across authorization boundaries. Use one QueryClient
|
|
79
|
+
per SSR request. Do not put tokens or session cookies in keys, request input,
|
|
80
|
+
metadata or persisted caches; use the existing Supabase session for auth.
|
|
81
|
+
|
|
82
|
+
## Svelte
|
|
83
|
+
|
|
84
|
+
Call the normal Svelte Query hooks inside a component under its existing
|
|
85
|
+
`QueryClientProvider`. Build options in their reactive accessors:
|
|
86
|
+
|
|
87
|
+
```svelte
|
|
88
|
+
<script lang="ts">
|
|
89
|
+
import { createQuery, createMutation, useQueryClient } from "@tanstack/svelte-query";
|
|
90
|
+
import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
|
|
91
|
+
import { createSvelteCommandScope } from "@supacloud/app-svelte";
|
|
92
|
+
import { toStore } from "svelte/store";
|
|
93
|
+
import { api } from "./api";
|
|
94
|
+
|
|
95
|
+
let { projectUrl, tenantId, actorId, itemId } = $props<{
|
|
96
|
+
projectUrl: string; tenantId: string; actorId: string; itemId: string;
|
|
97
|
+
}>();
|
|
98
|
+
const queryClient = useQueryClient();
|
|
99
|
+
const queries = $derived(createSupaCloudQueryAdapter({
|
|
100
|
+
keyPrefix: [projectUrl, "app-api", tenantId, actorId],
|
|
101
|
+
}));
|
|
102
|
+
const scope = createSvelteCommandScope({
|
|
103
|
+
target: toStore(() => JSON.stringify([projectUrl, tenantId, actorId, itemId])),
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const detail = createQuery(() => queries.queryOptions(
|
|
107
|
+
api.items.detail.query, { params: { id: itemId } },
|
|
108
|
+
));
|
|
109
|
+
const save = createMutation(() => queries.mutationOptions(api.items.save.mutate));
|
|
110
|
+
|
|
111
|
+
async function submit(name: string, operationId: string) {
|
|
112
|
+
const capturedQueries = queries;
|
|
113
|
+
const input = { params: { id: itemId }, body: { name } };
|
|
114
|
+
const attempt = scope.begin(operationId);
|
|
115
|
+
try {
|
|
116
|
+
await save.mutateAsync({
|
|
117
|
+
input,
|
|
118
|
+
execution: { idempotencyKey: operationId, signal: attempt.signal },
|
|
119
|
+
});
|
|
120
|
+
if (attempt.isCurrent()) {
|
|
121
|
+
await queryClient.invalidateQueries({
|
|
122
|
+
queryKey: capturedQueries.queryKey(api.items.detail.query, { params: input.params }),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (attempt.isCurrent()) throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
</script>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`detail.data`, `detail.isPending`, `detail.error` and `save.mutateAsync` are typed
|
|
133
|
+
by the generated schemas. React and other bindings consume the same ordinary
|
|
134
|
+
options through their own query/mutation hooks; no framework runtime is imported
|
|
135
|
+
by this adapter. The focused tests cover Query Core runtime behavior and Svelte
|
|
136
|
+
type integration, not a browser-rendered application.
|
|
137
|
+
|
|
138
|
+
## Mutation Safety
|
|
139
|
+
|
|
140
|
+
Each invocation supplies `{ input, execution }`. A required command idempotency
|
|
141
|
+
key is required both by TypeScript and at runtime. It belongs to the logical
|
|
142
|
+
operation, not to the component or mutation-options factory. Reuse it only when
|
|
143
|
+
reconciling/retrying the same operation, never for a different write.
|
|
144
|
+
|
|
145
|
+
Mutations set `retry: false`, including when QueryClient defaults enable retry.
|
|
146
|
+
An unknown outcome is not permission to retry; first resolve the server outcome.
|
|
147
|
+
If the procedure has no required input or execution settings, use
|
|
148
|
+
`mutation.mutateAsync({})`. Mutation inputs are passed through, including binary
|
|
149
|
+
or multipart bodies supported by the generated client.
|
|
150
|
+
|
|
151
|
+
Capture `scope.begin(operationId).signal` when the user starts an operation and
|
|
152
|
+
pass it in `execution`. The existing `@supacloud/app-svelte` scope invalidates it
|
|
153
|
+
on target/navigation changes and destruction. An already-aborted signal prevents
|
|
154
|
+
dispatch; aborting in-flight work rejects waiting and ignores late completion.
|
|
155
|
+
This never proves a server write rolled back and never releases persistent locks.
|
|
156
|
+
Use `attempt.isCurrent()`/`attempt.commit()` for component effects and guard custom
|
|
157
|
+
error/settled callbacks, including callbacks already running at cancellation time.
|
|
158
|
+
TanStack's native mutation `scope` still means serial scheduling, not component
|
|
159
|
+
lifetime.
|
|
160
|
+
|
|
161
|
+
This first adapter does not add batching, subscriptions, infinite-query builders,
|
|
162
|
+
automatic mutation-to-query dependency inference or a new durable-command engine.
|
|
163
|
+
Invalidation and optimistic updates remain explicit TanStack behavior.
|
package/README.md
CHANGED
|
@@ -60,6 +60,12 @@ peer range compatible with a newer SDK.
|
|
|
60
60
|
|
|
61
61
|
## Quick Start
|
|
62
62
|
|
|
63
|
+
For compiler-generated application procedures, the optional
|
|
64
|
+
[`@supacloud/js/query`](./QUERY.md) entrypoint provides typed TanStack Query options,
|
|
65
|
+
identity-scoped cache keys, cancellation and per-invocation mutation idempotency.
|
|
66
|
+
Use the existing Svelte/React Query binding and Supabase session; no additional
|
|
67
|
+
framework-specific SupaCloud query package is required.
|
|
68
|
+
|
|
63
69
|
```ts
|
|
64
70
|
import { createClient } from "@supabase/supabase-js";
|
|
65
71
|
import { createSupaCloudClient, createSupaCloudTaskFetch } from "@supacloud/js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { SupabaseClient } from "./supabase-types.cjs";
|
|
2
|
+
import type { FetchTransport } from "./bounded-rpc-fetch.cjs";
|
|
3
|
+
export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = SupabaseClient> {
|
|
4
|
+
/** The existing user-scoped Supabase client. It owns auth, apikey and session refresh. */
|
|
5
|
+
supabase: TClient;
|
|
6
|
+
/** The deployed Edge Function name that hosts the generated application routes. */
|
|
7
|
+
functionName: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Adapts the generated application client to the official Supabase Function
|
|
11
|
+
* transport without creating a second auth/session implementation.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createSupaCloudApiFetch<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudApiFetchOptions<TClient>): FetchTransport;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { SupabaseClient } from "./supabase-types.mjs";
|
|
2
|
+
import type { FetchTransport } from "./bounded-rpc-fetch.mjs";
|
|
3
|
+
export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = SupabaseClient> {
|
|
4
|
+
/** The existing user-scoped Supabase client. It owns auth, apikey and session refresh. */
|
|
5
|
+
supabase: TClient;
|
|
6
|
+
/** The deployed Edge Function name that hosts the generated application routes. */
|
|
7
|
+
functionName: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Adapts the generated application client to the official Supabase Function
|
|
11
|
+
* transport without creating a second auth/session implementation.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createSupaCloudApiFetch<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudApiFetchOptions<TClient>): FetchTransport;
|
package/dist/index.cjs
CHANGED
|
@@ -68,6 +68,7 @@ __export(exports_src, {
|
|
|
68
68
|
SupaCloudWorkflowRetryError: () => SupaCloudWorkflowRetryError,
|
|
69
69
|
SupaCloudWorkflowStartError: () => SupaCloudWorkflowStartError,
|
|
70
70
|
SupaCloudWorkflowsClient: () => SupaCloudWorkflowsClient,
|
|
71
|
+
createSupaCloudApiFetch: () => createSupaCloudApiFetch,
|
|
71
72
|
createSupaCloudArtifactFetch: () => createSupaCloudArtifactFetch,
|
|
72
73
|
createSupaCloudClient: () => createSupaCloudClient,
|
|
73
74
|
createSupaCloudCommandFetch: () => createSupaCloudCommandFetch,
|
|
@@ -2487,6 +2488,103 @@ var artifactPath2 = /\/rpc\/supacloud_artifact_(?:register|get|link)$/;
|
|
|
2487
2488
|
function createSupaCloudArtifactFetch(options = {}) {
|
|
2488
2489
|
return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
|
|
2489
2490
|
}
|
|
2491
|
+
// src/api-fetch.ts
|
|
2492
|
+
function isRecord4(value) {
|
|
2493
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2494
|
+
}
|
|
2495
|
+
function errorMessage(error) {
|
|
2496
|
+
return isRecord4(error) && typeof error.message === "string" ? error.message : "Supabase Function invocation failed";
|
|
2497
|
+
}
|
|
2498
|
+
async function readRequestBody(request) {
|
|
2499
|
+
if (request.body === null)
|
|
2500
|
+
return;
|
|
2501
|
+
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
2502
|
+
if (contentType.includes("multipart/form-data"))
|
|
2503
|
+
return request.formData();
|
|
2504
|
+
if (!contentType.startsWith("text/") && !contentType.includes("application/json") && !contentType.includes("+json") && !contentType.includes("application/x-www-form-urlencoded")) {
|
|
2505
|
+
return request.blob();
|
|
2506
|
+
}
|
|
2507
|
+
const text = await request.text();
|
|
2508
|
+
if (text.length === 0)
|
|
2509
|
+
return;
|
|
2510
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) {
|
|
2511
|
+
try {
|
|
2512
|
+
return JSON.parse(text);
|
|
2513
|
+
} catch {
|
|
2514
|
+
return text;
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
return text;
|
|
2518
|
+
}
|
|
2519
|
+
function responseFromData(data, source) {
|
|
2520
|
+
if (data instanceof Response)
|
|
2521
|
+
return data;
|
|
2522
|
+
const status = source?.status ?? (data === undefined ? 204 : 200);
|
|
2523
|
+
const headers = source?.headers;
|
|
2524
|
+
const init = {
|
|
2525
|
+
status,
|
|
2526
|
+
...source?.statusText === undefined ? {} : { statusText: source.statusText },
|
|
2527
|
+
...headers === undefined ? {} : { headers }
|
|
2528
|
+
};
|
|
2529
|
+
if ([204, 205, 304].includes(status))
|
|
2530
|
+
return new Response(null, init);
|
|
2531
|
+
if (data === undefined)
|
|
2532
|
+
return new Response(null, init);
|
|
2533
|
+
if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || data instanceof ReadableStream || data instanceof FormData || typeof data === "string") {
|
|
2534
|
+
return new Response(data, init);
|
|
2535
|
+
}
|
|
2536
|
+
if (headers?.get("content-type")?.includes("json")) {
|
|
2537
|
+
return new Response(JSON.stringify(data), init);
|
|
2538
|
+
}
|
|
2539
|
+
return new Response(JSON.stringify(data), {
|
|
2540
|
+
...init,
|
|
2541
|
+
headers: headers ?? { "content-type": "application/json" }
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
function createSupaCloudApiFetch(options) {
|
|
2545
|
+
const functionName = options.functionName.trim();
|
|
2546
|
+
if (!/^[A-Za-z0-9._-]+$/.test(functionName)) {
|
|
2547
|
+
throw new TypeError("functionName must be a single Supabase Function name");
|
|
2548
|
+
}
|
|
2549
|
+
const invoke = options.supabase.functions.invoke.bind(options.supabase.functions);
|
|
2550
|
+
return async (input, init) => {
|
|
2551
|
+
const rawInput = input instanceof Request ? input.url : input.toString();
|
|
2552
|
+
const url = new URL(rawInput, "http://supacloud.local");
|
|
2553
|
+
const request = new Request(url, init);
|
|
2554
|
+
const method = request.method;
|
|
2555
|
+
if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
|
2556
|
+
throw new TypeError(`Supabase Function transport does not support ${request.method}`);
|
|
2557
|
+
}
|
|
2558
|
+
const headers = {};
|
|
2559
|
+
request.headers.forEach((value, key) => {
|
|
2560
|
+
const normalized = key.toLowerCase();
|
|
2561
|
+
if (normalized !== "authorization" && normalized !== "apikey" && normalized !== "content-length") {
|
|
2562
|
+
headers[key] = value;
|
|
2563
|
+
}
|
|
2564
|
+
});
|
|
2565
|
+
const body = method === "GET" ? undefined : await readRequestBody(request);
|
|
2566
|
+
if ((request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) {
|
|
2567
|
+
for (const key of Object.keys(headers)) {
|
|
2568
|
+
if (key.toLowerCase() === "content-type")
|
|
2569
|
+
delete headers[key];
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
|
|
2573
|
+
...body === undefined ? {} : { body },
|
|
2574
|
+
...Object.keys(headers).length === 0 ? {} : { headers },
|
|
2575
|
+
method,
|
|
2576
|
+
signal: request.signal
|
|
2577
|
+
});
|
|
2578
|
+
if (invocation.error !== null && invocation.error !== undefined) {
|
|
2579
|
+
if (invocation.response instanceof Response)
|
|
2580
|
+
return invocation.response;
|
|
2581
|
+
if (invocation.error instanceof Error)
|
|
2582
|
+
throw invocation.error;
|
|
2583
|
+
throw new Error(errorMessage(invocation.error));
|
|
2584
|
+
}
|
|
2585
|
+
return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
|
|
2586
|
+
};
|
|
2587
|
+
}
|
|
2490
2588
|
|
|
2491
2589
|
// src/index.ts
|
|
2492
2590
|
class SupaCloudTaskSubmitError extends Error {
|
package/dist/index.d.cts
CHANGED
|
@@ -16,6 +16,7 @@ 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
20
|
export * from "./commands.cjs";
|
|
20
21
|
export * from "./artifacts.cjs";
|
|
21
22
|
export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
|
package/dist/index.d.mts
CHANGED
|
@@ -16,6 +16,7 @@ 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
20
|
export * from "./commands.mjs";
|
|
20
21
|
export * from "./artifacts.mjs";
|
|
21
22
|
export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
|
package/dist/index.mjs
CHANGED
|
@@ -2410,6 +2410,103 @@ var artifactPath2 = /\/rpc\/supacloud_artifact_(?:register|get|link)$/;
|
|
|
2410
2410
|
function createSupaCloudArtifactFetch(options = {}) {
|
|
2411
2411
|
return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
|
|
2412
2412
|
}
|
|
2413
|
+
// src/api-fetch.ts
|
|
2414
|
+
function isRecord4(value) {
|
|
2415
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2416
|
+
}
|
|
2417
|
+
function errorMessage(error) {
|
|
2418
|
+
return isRecord4(error) && typeof error.message === "string" ? error.message : "Supabase Function invocation failed";
|
|
2419
|
+
}
|
|
2420
|
+
async function readRequestBody(request) {
|
|
2421
|
+
if (request.body === null)
|
|
2422
|
+
return;
|
|
2423
|
+
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
2424
|
+
if (contentType.includes("multipart/form-data"))
|
|
2425
|
+
return request.formData();
|
|
2426
|
+
if (!contentType.startsWith("text/") && !contentType.includes("application/json") && !contentType.includes("+json") && !contentType.includes("application/x-www-form-urlencoded")) {
|
|
2427
|
+
return request.blob();
|
|
2428
|
+
}
|
|
2429
|
+
const text = await request.text();
|
|
2430
|
+
if (text.length === 0)
|
|
2431
|
+
return;
|
|
2432
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) {
|
|
2433
|
+
try {
|
|
2434
|
+
return JSON.parse(text);
|
|
2435
|
+
} catch {
|
|
2436
|
+
return text;
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
return text;
|
|
2440
|
+
}
|
|
2441
|
+
function responseFromData(data, source) {
|
|
2442
|
+
if (data instanceof Response)
|
|
2443
|
+
return data;
|
|
2444
|
+
const status = source?.status ?? (data === undefined ? 204 : 200);
|
|
2445
|
+
const headers = source?.headers;
|
|
2446
|
+
const init = {
|
|
2447
|
+
status,
|
|
2448
|
+
...source?.statusText === undefined ? {} : { statusText: source.statusText },
|
|
2449
|
+
...headers === undefined ? {} : { headers }
|
|
2450
|
+
};
|
|
2451
|
+
if ([204, 205, 304].includes(status))
|
|
2452
|
+
return new Response(null, init);
|
|
2453
|
+
if (data === undefined)
|
|
2454
|
+
return new Response(null, init);
|
|
2455
|
+
if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || data instanceof ReadableStream || data instanceof FormData || typeof data === "string") {
|
|
2456
|
+
return new Response(data, init);
|
|
2457
|
+
}
|
|
2458
|
+
if (headers?.get("content-type")?.includes("json")) {
|
|
2459
|
+
return new Response(JSON.stringify(data), init);
|
|
2460
|
+
}
|
|
2461
|
+
return new Response(JSON.stringify(data), {
|
|
2462
|
+
...init,
|
|
2463
|
+
headers: headers ?? { "content-type": "application/json" }
|
|
2464
|
+
});
|
|
2465
|
+
}
|
|
2466
|
+
function createSupaCloudApiFetch(options) {
|
|
2467
|
+
const functionName = options.functionName.trim();
|
|
2468
|
+
if (!/^[A-Za-z0-9._-]+$/.test(functionName)) {
|
|
2469
|
+
throw new TypeError("functionName must be a single Supabase Function name");
|
|
2470
|
+
}
|
|
2471
|
+
const invoke = options.supabase.functions.invoke.bind(options.supabase.functions);
|
|
2472
|
+
return async (input, init) => {
|
|
2473
|
+
const rawInput = input instanceof Request ? input.url : input.toString();
|
|
2474
|
+
const url = new URL(rawInput, "http://supacloud.local");
|
|
2475
|
+
const request = new Request(url, init);
|
|
2476
|
+
const method = request.method;
|
|
2477
|
+
if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
|
2478
|
+
throw new TypeError(`Supabase Function transport does not support ${request.method}`);
|
|
2479
|
+
}
|
|
2480
|
+
const headers = {};
|
|
2481
|
+
request.headers.forEach((value, key) => {
|
|
2482
|
+
const normalized = key.toLowerCase();
|
|
2483
|
+
if (normalized !== "authorization" && normalized !== "apikey" && normalized !== "content-length") {
|
|
2484
|
+
headers[key] = value;
|
|
2485
|
+
}
|
|
2486
|
+
});
|
|
2487
|
+
const body = method === "GET" ? undefined : await readRequestBody(request);
|
|
2488
|
+
if ((request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) {
|
|
2489
|
+
for (const key of Object.keys(headers)) {
|
|
2490
|
+
if (key.toLowerCase() === "content-type")
|
|
2491
|
+
delete headers[key];
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
|
|
2495
|
+
...body === undefined ? {} : { body },
|
|
2496
|
+
...Object.keys(headers).length === 0 ? {} : { headers },
|
|
2497
|
+
method,
|
|
2498
|
+
signal: request.signal
|
|
2499
|
+
});
|
|
2500
|
+
if (invocation.error !== null && invocation.error !== undefined) {
|
|
2501
|
+
if (invocation.response instanceof Response)
|
|
2502
|
+
return invocation.response;
|
|
2503
|
+
if (invocation.error instanceof Error)
|
|
2504
|
+
throw invocation.error;
|
|
2505
|
+
throw new Error(errorMessage(invocation.error));
|
|
2506
|
+
}
|
|
2507
|
+
return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2413
2510
|
|
|
2414
2511
|
// src/index.ts
|
|
2415
2512
|
class SupaCloudTaskSubmitError extends Error {
|
|
@@ -3683,6 +3780,7 @@ export {
|
|
|
3683
3780
|
SupaCloudWorkflowRetryError,
|
|
3684
3781
|
SupaCloudWorkflowStartError,
|
|
3685
3782
|
SupaCloudWorkflowsClient,
|
|
3783
|
+
createSupaCloudApiFetch,
|
|
3686
3784
|
createSupaCloudArtifactFetch,
|
|
3687
3785
|
createSupaCloudClient,
|
|
3688
3786
|
createSupaCloudCommandFetch,
|
package/dist/query.cjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
function __accessProp(key) {
|
|
6
|
+
return this[key];
|
|
7
|
+
}
|
|
8
|
+
var __toCommonJS = (from) => {
|
|
9
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
10
|
+
if (entry)
|
|
11
|
+
return entry;
|
|
12
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (var key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(entry, key))
|
|
16
|
+
__defProp(entry, key, {
|
|
17
|
+
get: __accessProp.bind(from, key),
|
|
18
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
__moduleCache.set(from, entry);
|
|
22
|
+
return entry;
|
|
23
|
+
};
|
|
24
|
+
var __moduleCache;
|
|
25
|
+
var __returnValue = (v) => v;
|
|
26
|
+
function __exportSetter(name, newValue) {
|
|
27
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
28
|
+
}
|
|
29
|
+
var __export = (target, all) => {
|
|
30
|
+
for (var name in all)
|
|
31
|
+
__defProp(target, name, {
|
|
32
|
+
get: all[name],
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: true,
|
|
35
|
+
set: __exportSetter.bind(all, name)
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/query.ts
|
|
40
|
+
var exports_query = {};
|
|
41
|
+
__export(exports_query, {
|
|
42
|
+
createSupaCloudQueryAdapter: () => createSupaCloudQueryAdapter
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(exports_query);
|
|
45
|
+
function metadataOf(procedure, kind) {
|
|
46
|
+
const metadata = procedure.__supacloudProcedure;
|
|
47
|
+
if (!metadata || metadata.kind !== kind || typeof metadata.method !== "string" || typeof metadata.path !== "string" || !["none", "required"].includes(metadata.idempotency)) {
|
|
48
|
+
throw new TypeError(`Expected a generated ${kind} procedure; regenerate the application client`);
|
|
49
|
+
}
|
|
50
|
+
return metadata;
|
|
51
|
+
}
|
|
52
|
+
function snapshot(value, ancestors = new Set) {
|
|
53
|
+
if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean")
|
|
54
|
+
return value;
|
|
55
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
56
|
+
return value;
|
|
57
|
+
if (typeof value !== "object" || ancestors.has(value)) {
|
|
58
|
+
throw new TypeError("Procedure input must be acyclic JSON data");
|
|
59
|
+
}
|
|
60
|
+
const prototype = Object.getPrototypeOf(value);
|
|
61
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
|
|
62
|
+
throw new TypeError("Procedure input must be JSON data");
|
|
63
|
+
}
|
|
64
|
+
ancestors.add(value);
|
|
65
|
+
try {
|
|
66
|
+
if (Array.isArray(value)) {
|
|
67
|
+
return Object.freeze(value.map((item) => snapshot(item, ancestors) ?? null));
|
|
68
|
+
}
|
|
69
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).map(([key, item]) => [key, snapshot(item, ancestors)])));
|
|
70
|
+
} finally {
|
|
71
|
+
ancestors.delete(value);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function callProcedure(procedure, input, execution) {
|
|
75
|
+
const call = procedure;
|
|
76
|
+
const signal = execution.signal;
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
const onAbort = () => reject(signal?.reason ?? new DOMException("Procedure cancelled", "AbortError"));
|
|
79
|
+
if (signal?.aborted) {
|
|
80
|
+
onAbort();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
84
|
+
Promise.resolve().then(() => {
|
|
85
|
+
signal?.throwIfAborted();
|
|
86
|
+
return call(input, execution);
|
|
87
|
+
}).then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function createSupaCloudQueryAdapter({
|
|
91
|
+
keyPrefix
|
|
92
|
+
}) {
|
|
93
|
+
if (!Array.isArray(keyPrefix) || keyPrefix.length === 0 || keyPrefix.some((part) => typeof part !== "string" || !part.trim())) {
|
|
94
|
+
throw new TypeError("keyPrefix must contain nonempty identity values");
|
|
95
|
+
}
|
|
96
|
+
const prefix = Object.freeze(["supacloud", ...keyPrefix]);
|
|
97
|
+
function procedureKey(procedure, kind) {
|
|
98
|
+
const metadata = metadataOf(procedure, kind);
|
|
99
|
+
return Object.freeze([...prefix, kind, metadata.method, metadata.path]);
|
|
100
|
+
}
|
|
101
|
+
function queryKey(procedure, ...args) {
|
|
102
|
+
if (args.length === 0)
|
|
103
|
+
return procedureKey(procedure, "query");
|
|
104
|
+
return Object.freeze([
|
|
105
|
+
...procedureKey(procedure, "query"),
|
|
106
|
+
snapshot(args[0] ?? {})
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
function queryOptions(procedure, input, options) {
|
|
110
|
+
const capturedInput = snapshot(input ?? {});
|
|
111
|
+
return {
|
|
112
|
+
...options,
|
|
113
|
+
queryKey: Object.freeze([
|
|
114
|
+
...procedureKey(procedure, "query"),
|
|
115
|
+
capturedInput
|
|
116
|
+
]),
|
|
117
|
+
queryFn: async ({ signal }) => {
|
|
118
|
+
const result = await callProcedure(procedure, capturedInput, { signal });
|
|
119
|
+
return result === undefined ? null : result;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function mutationOptions(procedure, options) {
|
|
124
|
+
const metadata = metadataOf(procedure, "mutation");
|
|
125
|
+
return {
|
|
126
|
+
...options,
|
|
127
|
+
mutationKey: procedureKey(procedure, "mutation"),
|
|
128
|
+
retry: false,
|
|
129
|
+
mutationFn: async (variables) => {
|
|
130
|
+
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
|
+
return callProcedure(procedure, variables.input, execution);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
queryKey,
|
|
141
|
+
queryOptions,
|
|
142
|
+
mutationKey: (procedure) => procedureKey(procedure, "mutation"),
|
|
143
|
+
mutationOptions
|
|
144
|
+
};
|
|
145
|
+
}
|
package/dist/query.d.cts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { DataTag, DefaultError, MutationKey, MutationObserverOptions, QueryFunctionContext, QueryKey, QueryObserverOptions } from "@tanstack/query-core";
|
|
2
|
+
type Procedure<Kind extends "query" | "mutation"> = {
|
|
3
|
+
readonly __supacloudProcedure: {
|
|
4
|
+
readonly key: string;
|
|
5
|
+
readonly method: string;
|
|
6
|
+
readonly path: string;
|
|
7
|
+
readonly kind: Kind;
|
|
8
|
+
readonly idempotency: "none" | "required";
|
|
9
|
+
};
|
|
10
|
+
readonly __supacloudInput?: unknown;
|
|
11
|
+
};
|
|
12
|
+
export type SupaCloudProcedureInput<TProcedure> = TProcedure extends {
|
|
13
|
+
readonly __supacloudInput?: infer TInput;
|
|
14
|
+
} ? TInput : never;
|
|
15
|
+
export type SupaCloudProcedureResult<TProcedure> = TProcedure extends (...args: infer _Args) => Promise<infer TResult> ? TResult : unknown;
|
|
16
|
+
type ProcedureInput<TProcedure> = {} extends SupaCloudProcedureInput<TProcedure> ? SupaCloudProcedureInput<TProcedure> | undefined : SupaCloudProcedureInput<TProcedure>;
|
|
17
|
+
type QueryResult<TProcedure> = Exclude<SupaCloudProcedureResult<TProcedure>, undefined | void> | (undefined extends SupaCloudProcedureResult<TProcedure> ? null : never);
|
|
18
|
+
type TaggedQueryKey<TProcedure, TError = DefaultError> = DataTag<QueryKey, QueryResult<TProcedure>, TError>;
|
|
19
|
+
export interface SupaCloudProcedureExecutionOptions {
|
|
20
|
+
idempotencyKey?: string;
|
|
21
|
+
/** Pass an existing CommandAttempt signal to bind a mutation to component lifetime. */
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
export type SupaCloudMutationVariables<TProcedure extends Procedure<"mutation">> = ({} extends SupaCloudProcedureInput<TProcedure> ? {
|
|
25
|
+
input?: SupaCloudProcedureInput<TProcedure>;
|
|
26
|
+
} : {
|
|
27
|
+
input: SupaCloudProcedureInput<TProcedure>;
|
|
28
|
+
}) & (TProcedure["__supacloudProcedure"]["idempotency"] extends "required" ? {
|
|
29
|
+
execution: SupaCloudProcedureExecutionOptions & {
|
|
30
|
+
idempotencyKey: string;
|
|
31
|
+
};
|
|
32
|
+
} : {
|
|
33
|
+
execution?: SupaCloudProcedureExecutionOptions;
|
|
34
|
+
});
|
|
35
|
+
export type SupaCloudQueryOptions<TProcedure extends Procedure<"query">, TError = DefaultError, TData = QueryResult<TProcedure>> = Omit<QueryObserverOptions<QueryResult<TProcedure>, TError, TData, QueryResult<TProcedure>, QueryKey>, "queryKey" | "queryFn" | "queryHash" | "queryKeyHashFn">;
|
|
36
|
+
export type SupaCloudMutationOptions<TProcedure extends Procedure<"mutation">, TError = DefaultError, TContext = unknown> = Omit<MutationObserverOptions<SupaCloudProcedureResult<TProcedure>, TError, SupaCloudMutationVariables<TProcedure>, TContext>, "mutationKey" | "mutationFn" | "retry">;
|
|
37
|
+
export type SupaCloudQueryOptionsResult<TProcedure extends Procedure<"query">, TError = DefaultError, TData = QueryResult<TProcedure>> = SupaCloudQueryOptions<TProcedure, TError, TData> & {
|
|
38
|
+
queryKey: TaggedQueryKey<TProcedure, TError>;
|
|
39
|
+
queryFn(context: QueryFunctionContext<QueryKey>): Promise<QueryResult<TProcedure>>;
|
|
40
|
+
};
|
|
41
|
+
export type SupaCloudMutationOptionsResult<TProcedure extends Procedure<"mutation">, TError = DefaultError, TContext = unknown> = SupaCloudMutationOptions<TProcedure, TError, TContext> & {
|
|
42
|
+
mutationKey: MutationKey;
|
|
43
|
+
mutationFn(variables: SupaCloudMutationVariables<TProcedure>): Promise<SupaCloudProcedureResult<TProcedure>>;
|
|
44
|
+
retry: false;
|
|
45
|
+
};
|
|
46
|
+
export interface SupaCloudQueryAdapterOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Include project, tenant and actor identity. Recreate the adapter when any
|
|
49
|
+
* of those identities change so old cache entries cannot be reused.
|
|
50
|
+
*/
|
|
51
|
+
keyPrefix: readonly [string, ...string[]];
|
|
52
|
+
}
|
|
53
|
+
export declare function createSupaCloudQueryAdapter({ keyPrefix, }: SupaCloudQueryAdapterOptions): {
|
|
54
|
+
queryKey: {
|
|
55
|
+
<TProcedure extends Procedure<"query">>(procedure: TProcedure): QueryKey;
|
|
56
|
+
<TProcedure extends Procedure<"query">>(procedure: TProcedure, input: NoInfer<ProcedureInput<TProcedure>>): TaggedQueryKey<TProcedure>;
|
|
57
|
+
};
|
|
58
|
+
queryOptions: <TProcedure extends Procedure<"query">, TError = Error, TData = QueryResult<TProcedure>>(procedure: TProcedure, input: NoInfer<ProcedureInput<TProcedure>>, options?: SupaCloudQueryOptions<NoInfer<TProcedure>, TError, TData>) => SupaCloudQueryOptionsResult<TProcedure, TError, TData>;
|
|
59
|
+
mutationKey: (procedure: Procedure<"mutation">) => readonly unknown[];
|
|
60
|
+
mutationOptions: <TProcedure extends Procedure<"mutation">, TError = Error, TContext = unknown>(procedure: TProcedure, options?: SupaCloudMutationOptions<NoInfer<TProcedure>, TError, TContext>) => SupaCloudMutationOptionsResult<TProcedure, TError, TContext>;
|
|
61
|
+
};
|
|
62
|
+
export {};
|
package/dist/query.d.mts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { DataTag, DefaultError, MutationKey, MutationObserverOptions, QueryFunctionContext, QueryKey, QueryObserverOptions } from "@tanstack/query-core";
|
|
2
|
+
type Procedure<Kind extends "query" | "mutation"> = {
|
|
3
|
+
readonly __supacloudProcedure: {
|
|
4
|
+
readonly key: string;
|
|
5
|
+
readonly method: string;
|
|
6
|
+
readonly path: string;
|
|
7
|
+
readonly kind: Kind;
|
|
8
|
+
readonly idempotency: "none" | "required";
|
|
9
|
+
};
|
|
10
|
+
readonly __supacloudInput?: unknown;
|
|
11
|
+
};
|
|
12
|
+
export type SupaCloudProcedureInput<TProcedure> = TProcedure extends {
|
|
13
|
+
readonly __supacloudInput?: infer TInput;
|
|
14
|
+
} ? TInput : never;
|
|
15
|
+
export type SupaCloudProcedureResult<TProcedure> = TProcedure extends (...args: infer _Args) => Promise<infer TResult> ? TResult : unknown;
|
|
16
|
+
type ProcedureInput<TProcedure> = {} extends SupaCloudProcedureInput<TProcedure> ? SupaCloudProcedureInput<TProcedure> | undefined : SupaCloudProcedureInput<TProcedure>;
|
|
17
|
+
type QueryResult<TProcedure> = Exclude<SupaCloudProcedureResult<TProcedure>, undefined | void> | (undefined extends SupaCloudProcedureResult<TProcedure> ? null : never);
|
|
18
|
+
type TaggedQueryKey<TProcedure, TError = DefaultError> = DataTag<QueryKey, QueryResult<TProcedure>, TError>;
|
|
19
|
+
export interface SupaCloudProcedureExecutionOptions {
|
|
20
|
+
idempotencyKey?: string;
|
|
21
|
+
/** Pass an existing CommandAttempt signal to bind a mutation to component lifetime. */
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
export type SupaCloudMutationVariables<TProcedure extends Procedure<"mutation">> = ({} extends SupaCloudProcedureInput<TProcedure> ? {
|
|
25
|
+
input?: SupaCloudProcedureInput<TProcedure>;
|
|
26
|
+
} : {
|
|
27
|
+
input: SupaCloudProcedureInput<TProcedure>;
|
|
28
|
+
}) & (TProcedure["__supacloudProcedure"]["idempotency"] extends "required" ? {
|
|
29
|
+
execution: SupaCloudProcedureExecutionOptions & {
|
|
30
|
+
idempotencyKey: string;
|
|
31
|
+
};
|
|
32
|
+
} : {
|
|
33
|
+
execution?: SupaCloudProcedureExecutionOptions;
|
|
34
|
+
});
|
|
35
|
+
export type SupaCloudQueryOptions<TProcedure extends Procedure<"query">, TError = DefaultError, TData = QueryResult<TProcedure>> = Omit<QueryObserverOptions<QueryResult<TProcedure>, TError, TData, QueryResult<TProcedure>, QueryKey>, "queryKey" | "queryFn" | "queryHash" | "queryKeyHashFn">;
|
|
36
|
+
export type SupaCloudMutationOptions<TProcedure extends Procedure<"mutation">, TError = DefaultError, TContext = unknown> = Omit<MutationObserverOptions<SupaCloudProcedureResult<TProcedure>, TError, SupaCloudMutationVariables<TProcedure>, TContext>, "mutationKey" | "mutationFn" | "retry">;
|
|
37
|
+
export type SupaCloudQueryOptionsResult<TProcedure extends Procedure<"query">, TError = DefaultError, TData = QueryResult<TProcedure>> = SupaCloudQueryOptions<TProcedure, TError, TData> & {
|
|
38
|
+
queryKey: TaggedQueryKey<TProcedure, TError>;
|
|
39
|
+
queryFn(context: QueryFunctionContext<QueryKey>): Promise<QueryResult<TProcedure>>;
|
|
40
|
+
};
|
|
41
|
+
export type SupaCloudMutationOptionsResult<TProcedure extends Procedure<"mutation">, TError = DefaultError, TContext = unknown> = SupaCloudMutationOptions<TProcedure, TError, TContext> & {
|
|
42
|
+
mutationKey: MutationKey;
|
|
43
|
+
mutationFn(variables: SupaCloudMutationVariables<TProcedure>): Promise<SupaCloudProcedureResult<TProcedure>>;
|
|
44
|
+
retry: false;
|
|
45
|
+
};
|
|
46
|
+
export interface SupaCloudQueryAdapterOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Include project, tenant and actor identity. Recreate the adapter when any
|
|
49
|
+
* of those identities change so old cache entries cannot be reused.
|
|
50
|
+
*/
|
|
51
|
+
keyPrefix: readonly [string, ...string[]];
|
|
52
|
+
}
|
|
53
|
+
export declare function createSupaCloudQueryAdapter({ keyPrefix, }: SupaCloudQueryAdapterOptions): {
|
|
54
|
+
queryKey: {
|
|
55
|
+
<TProcedure extends Procedure<"query">>(procedure: TProcedure): QueryKey;
|
|
56
|
+
<TProcedure extends Procedure<"query">>(procedure: TProcedure, input: NoInfer<ProcedureInput<TProcedure>>): TaggedQueryKey<TProcedure>;
|
|
57
|
+
};
|
|
58
|
+
queryOptions: <TProcedure extends Procedure<"query">, TError = Error, TData = QueryResult<TProcedure>>(procedure: TProcedure, input: NoInfer<ProcedureInput<TProcedure>>, options?: SupaCloudQueryOptions<NoInfer<TProcedure>, TError, TData>) => SupaCloudQueryOptionsResult<TProcedure, TError, TData>;
|
|
59
|
+
mutationKey: (procedure: Procedure<"mutation">) => readonly unknown[];
|
|
60
|
+
mutationOptions: <TProcedure extends Procedure<"mutation">, TError = Error, TContext = unknown>(procedure: TProcedure, options?: SupaCloudMutationOptions<NoInfer<TProcedure>, TError, TContext>) => SupaCloudMutationOptionsResult<TProcedure, TError, TContext>;
|
|
61
|
+
};
|
|
62
|
+
export {};
|
package/dist/query.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// src/query.ts
|
|
2
|
+
function metadataOf(procedure, kind) {
|
|
3
|
+
const metadata = procedure.__supacloudProcedure;
|
|
4
|
+
if (!metadata || metadata.kind !== kind || typeof metadata.method !== "string" || typeof metadata.path !== "string" || !["none", "required"].includes(metadata.idempotency)) {
|
|
5
|
+
throw new TypeError(`Expected a generated ${kind} procedure; regenerate the application client`);
|
|
6
|
+
}
|
|
7
|
+
return metadata;
|
|
8
|
+
}
|
|
9
|
+
function snapshot(value, ancestors = new Set) {
|
|
10
|
+
if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean")
|
|
11
|
+
return value;
|
|
12
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
13
|
+
return value;
|
|
14
|
+
if (typeof value !== "object" || ancestors.has(value)) {
|
|
15
|
+
throw new TypeError("Procedure input must be acyclic JSON data");
|
|
16
|
+
}
|
|
17
|
+
const prototype = Object.getPrototypeOf(value);
|
|
18
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
|
|
19
|
+
throw new TypeError("Procedure input must be JSON data");
|
|
20
|
+
}
|
|
21
|
+
ancestors.add(value);
|
|
22
|
+
try {
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
return Object.freeze(value.map((item) => snapshot(item, ancestors) ?? null));
|
|
25
|
+
}
|
|
26
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).map(([key, item]) => [key, snapshot(item, ancestors)])));
|
|
27
|
+
} finally {
|
|
28
|
+
ancestors.delete(value);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function callProcedure(procedure, input, execution) {
|
|
32
|
+
const call = procedure;
|
|
33
|
+
const signal = execution.signal;
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
const onAbort = () => reject(signal?.reason ?? new DOMException("Procedure cancelled", "AbortError"));
|
|
36
|
+
if (signal?.aborted) {
|
|
37
|
+
onAbort();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
41
|
+
Promise.resolve().then(() => {
|
|
42
|
+
signal?.throwIfAborted();
|
|
43
|
+
return call(input, execution);
|
|
44
|
+
}).then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function createSupaCloudQueryAdapter({
|
|
48
|
+
keyPrefix
|
|
49
|
+
}) {
|
|
50
|
+
if (!Array.isArray(keyPrefix) || keyPrefix.length === 0 || keyPrefix.some((part) => typeof part !== "string" || !part.trim())) {
|
|
51
|
+
throw new TypeError("keyPrefix must contain nonempty identity values");
|
|
52
|
+
}
|
|
53
|
+
const prefix = Object.freeze(["supacloud", ...keyPrefix]);
|
|
54
|
+
function procedureKey(procedure, kind) {
|
|
55
|
+
const metadata = metadataOf(procedure, kind);
|
|
56
|
+
return Object.freeze([...prefix, kind, metadata.method, metadata.path]);
|
|
57
|
+
}
|
|
58
|
+
function queryKey(procedure, ...args) {
|
|
59
|
+
if (args.length === 0)
|
|
60
|
+
return procedureKey(procedure, "query");
|
|
61
|
+
return Object.freeze([
|
|
62
|
+
...procedureKey(procedure, "query"),
|
|
63
|
+
snapshot(args[0] ?? {})
|
|
64
|
+
]);
|
|
65
|
+
}
|
|
66
|
+
function queryOptions(procedure, input, options) {
|
|
67
|
+
const capturedInput = snapshot(input ?? {});
|
|
68
|
+
return {
|
|
69
|
+
...options,
|
|
70
|
+
queryKey: Object.freeze([
|
|
71
|
+
...procedureKey(procedure, "query"),
|
|
72
|
+
capturedInput
|
|
73
|
+
]),
|
|
74
|
+
queryFn: async ({ signal }) => {
|
|
75
|
+
const result = await callProcedure(procedure, capturedInput, { signal });
|
|
76
|
+
return result === undefined ? null : result;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function mutationOptions(procedure, options) {
|
|
81
|
+
const metadata = metadataOf(procedure, "mutation");
|
|
82
|
+
return {
|
|
83
|
+
...options,
|
|
84
|
+
mutationKey: procedureKey(procedure, "mutation"),
|
|
85
|
+
retry: false,
|
|
86
|
+
mutationFn: async (variables) => {
|
|
87
|
+
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
|
+
return callProcedure(procedure, variables.input, execution);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
queryKey,
|
|
98
|
+
queryOptions,
|
|
99
|
+
mutationKey: (procedure) => procedureKey(procedure, "mutation"),
|
|
100
|
+
mutationOptions
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export {
|
|
104
|
+
createSupaCloudQueryAdapter
|
|
105
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/js",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.0",
|
|
4
4
|
"description": "Platform SDK for SupaCloud, built on top of supabase-js",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -46,6 +46,16 @@
|
|
|
46
46
|
"types": "./dist/reactive.d.cts",
|
|
47
47
|
"default": "./dist/reactive.cjs"
|
|
48
48
|
}
|
|
49
|
+
},
|
|
50
|
+
"./query": {
|
|
51
|
+
"import": {
|
|
52
|
+
"types": "./dist/query.d.mts",
|
|
53
|
+
"default": "./dist/query.mjs"
|
|
54
|
+
},
|
|
55
|
+
"require": {
|
|
56
|
+
"types": "./dist/query.d.cts",
|
|
57
|
+
"default": "./dist/query.cjs"
|
|
58
|
+
}
|
|
49
59
|
}
|
|
50
60
|
},
|
|
51
61
|
"files": [
|
|
@@ -54,6 +64,7 @@
|
|
|
54
64
|
"dist",
|
|
55
65
|
"README.md",
|
|
56
66
|
"COMPATIBILITY.md",
|
|
67
|
+
"QUERY.md",
|
|
57
68
|
"REACTIVE.md"
|
|
58
69
|
],
|
|
59
70
|
"scripts": {
|
|
@@ -67,8 +78,8 @@
|
|
|
67
78
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
68
79
|
"typecheck:test": "tsc -p tsconfig.test.json --noEmit",
|
|
69
80
|
"check:package": "node ../../.github/scripts/esm-package-policy.mjs --pack .",
|
|
70
|
-
"build:js:esm": "bun build src/index.ts src/task-events.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target node --external @supabase/supabase-js --external @supacloud/contracts && bun build src/contracts.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target browser --external @supacloud/contracts && bun build src/reactive.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target browser --external rxjs",
|
|
71
|
-
"build:js:cjs": "bun build src/index.ts src/task-events.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target node --external @supabase/supabase-js --external @supacloud/contracts && bun build src/contracts.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target browser --external @supacloud/contracts && bun build src/reactive.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target browser --external rxjs"
|
|
81
|
+
"build:js:esm": "bun build src/index.ts src/task-events.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target node --external @supabase/supabase-js --external @supacloud/contracts && bun build src/contracts.ts src/query.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target browser --external @supacloud/contracts --external @tanstack/query-core && bun build src/reactive.ts --outdir dist --format esm --entry-naming \"[name].mjs\" --chunk-naming \"[name]-[hash].mjs\" --target browser --external rxjs",
|
|
82
|
+
"build:js:cjs": "bun build src/index.ts src/task-events.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target node --external @supabase/supabase-js --external @supacloud/contracts && bun build src/contracts.ts src/query.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target browser --external @supacloud/contracts --external @tanstack/query-core && bun build src/reactive.ts --outdir dist --format cjs --entry-naming \"[name].cjs\" --chunk-naming \"[name]-[hash].cjs\" --target browser --external rxjs"
|
|
72
83
|
},
|
|
73
84
|
"keywords": [
|
|
74
85
|
"supacloud",
|
|
@@ -84,7 +95,13 @@
|
|
|
84
95
|
"directory": "packages/supacloud-js"
|
|
85
96
|
},
|
|
86
97
|
"peerDependencies": {
|
|
87
|
-
"@supabase/supabase-js": "^2.115.0"
|
|
98
|
+
"@supabase/supabase-js": "^2.115.0",
|
|
99
|
+
"@tanstack/query-core": "^5.104.1"
|
|
100
|
+
},
|
|
101
|
+
"peerDependenciesMeta": {
|
|
102
|
+
"@tanstack/query-core": {
|
|
103
|
+
"optional": true
|
|
104
|
+
}
|
|
88
105
|
},
|
|
89
106
|
"dependencies": {
|
|
90
107
|
"@supacloud/contracts": "0.8.0",
|
|
@@ -93,7 +110,11 @@
|
|
|
93
110
|
"devDependencies": {
|
|
94
111
|
"@types/bun": "^1.4.2",
|
|
95
112
|
"@supabase/supabase-js": "^2.115.0",
|
|
96
|
-
"typescript": "^7.0.2"
|
|
113
|
+
"typescript": "^7.0.2",
|
|
114
|
+
"@tanstack/query-core": "5.104.1",
|
|
115
|
+
"@tanstack/svelte-query": "6.3.1",
|
|
116
|
+
"typebox": "1.3.34",
|
|
117
|
+
"svelte": "5.57.1"
|
|
97
118
|
},
|
|
98
119
|
"engines": {
|
|
99
120
|
"node": ">=22.12.0"
|