@supacloud/js 0.37.0 → 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/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";
|
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"
|