@supacloud/js 0.10.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/README.md +66 -0
- package/dist/index.js +280 -0
- package/package.json +37 -0
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# `@supacloud/js`
|
|
2
|
+
|
|
3
|
+
`@supacloud/js` is the platform SDK for SupaCloud.
|
|
4
|
+
|
|
5
|
+
It does **not** replace [`@supabase/supabase-js`](https://www.npmjs.com/package/@supabase/supabase-js). Instead, it wraps a normal Supabase client and adds SupaCloud-specific capabilities such as:
|
|
6
|
+
|
|
7
|
+
- background task submission
|
|
8
|
+
- task detail and list APIs
|
|
9
|
+
- cancel / retry helpers
|
|
10
|
+
- Realtime subscription with polling fallback
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @supacloud/js @supabase/supabase-js
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createClient } from "@supabase/supabase-js";
|
|
22
|
+
import { createSupaCloudClient } from "@supacloud/js";
|
|
23
|
+
|
|
24
|
+
const supabase = createClient("https://api.example.com", "anon-key");
|
|
25
|
+
|
|
26
|
+
const supacloud = createSupaCloudClient({
|
|
27
|
+
supabase,
|
|
28
|
+
managementApiUrl: "https://admin.example.com",
|
|
29
|
+
projectRef: "abcd1234",
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const task = await supacloud.tasks.submit("aorist-ai/generate/crop", {
|
|
33
|
+
body: { image_id: "img_123" },
|
|
34
|
+
idempotencyKey: "crop-img_123-v1",
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const finalState = await task.wait();
|
|
38
|
+
console.log(finalState.status);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Design
|
|
42
|
+
|
|
43
|
+
This SDK is intentionally thin:
|
|
44
|
+
|
|
45
|
+
- `supabase-js` still owns auth, storage, database, Realtime transport, and plain function invokes
|
|
46
|
+
- `@supacloud/js` owns SupaCloud platform semantics layered on top of that transport
|
|
47
|
+
|
|
48
|
+
The current package focuses on:
|
|
49
|
+
|
|
50
|
+
- `tasks.submit`
|
|
51
|
+
- `tasks.get`
|
|
52
|
+
- `tasks.list`
|
|
53
|
+
- `tasks.listDlq`
|
|
54
|
+
- `tasks.cancel`
|
|
55
|
+
- `tasks.retry`
|
|
56
|
+
- `tasks.wait`
|
|
57
|
+
- `tasks.subscribe`
|
|
58
|
+
|
|
59
|
+
## Status Subscription
|
|
60
|
+
|
|
61
|
+
`tasks.subscribe()` uses this strategy:
|
|
62
|
+
|
|
63
|
+
1. try `postgres_changes` on `public.tasks`
|
|
64
|
+
2. if Realtime is unavailable, fall back to polling the management API
|
|
65
|
+
|
|
66
|
+
This lets apps degrade gracefully when websocket or channel health is transient.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
class SupaCloudTaskSubmitError extends Error {
|
|
3
|
+
responseBody;
|
|
4
|
+
constructor(message, responseBody) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "SupaCloudTaskSubmitError";
|
|
7
|
+
this.responseBody = responseBody;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
var TERMINAL_STATUSES = new Set([
|
|
11
|
+
"succeeded",
|
|
12
|
+
"failed",
|
|
13
|
+
"dead_lettered",
|
|
14
|
+
"cancelled",
|
|
15
|
+
"completed"
|
|
16
|
+
]);
|
|
17
|
+
function normalizeBaseUrl(url) {
|
|
18
|
+
return url.replace(/\/+$/, "");
|
|
19
|
+
}
|
|
20
|
+
function toArray(value) {
|
|
21
|
+
if (!value)
|
|
22
|
+
return;
|
|
23
|
+
return Array.isArray(value) ? value : [value];
|
|
24
|
+
}
|
|
25
|
+
function createQueryString(filters = {}) {
|
|
26
|
+
const params = new URLSearchParams;
|
|
27
|
+
const statuses = toArray(filters.status);
|
|
28
|
+
const taskTypes = toArray(filters.taskType);
|
|
29
|
+
if (statuses?.length)
|
|
30
|
+
params.set("status", statuses.join(","));
|
|
31
|
+
if (taskTypes?.length)
|
|
32
|
+
params.set("task_type", taskTypes.join(","));
|
|
33
|
+
if (filters.functionSlug)
|
|
34
|
+
params.set("function_slug", filters.functionSlug);
|
|
35
|
+
if (filters.dlq)
|
|
36
|
+
params.set("dlq", "true");
|
|
37
|
+
if (filters.limit !== undefined)
|
|
38
|
+
params.set("limit", String(filters.limit));
|
|
39
|
+
const query = params.toString();
|
|
40
|
+
return query.length > 0 ? `?${query}` : "";
|
|
41
|
+
}
|
|
42
|
+
async function defaultAccessTokenResolver(supabase) {
|
|
43
|
+
const { data, error } = await supabase.auth.getSession();
|
|
44
|
+
if (error)
|
|
45
|
+
throw error;
|
|
46
|
+
return data.session?.access_token ?? null;
|
|
47
|
+
}
|
|
48
|
+
function normalizeTaskSnapshot(task) {
|
|
49
|
+
const value = task ?? {};
|
|
50
|
+
return {
|
|
51
|
+
id: String(value.id ?? ""),
|
|
52
|
+
status: String(value.status ?? "unknown"),
|
|
53
|
+
progress: typeof value.progress === "number" ? value.progress : null,
|
|
54
|
+
error: typeof value.error === "string" ? value.error : typeof value.error_message === "string" ? value.error_message : null,
|
|
55
|
+
updatedAt: typeof value.updated_at === "string" ? value.updated_at : typeof value.updatedAt === "string" ? value.updatedAt : null,
|
|
56
|
+
raw: task
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
class SupaCloudTasksClient {
|
|
61
|
+
options;
|
|
62
|
+
constructor(options) {
|
|
63
|
+
this.options = options;
|
|
64
|
+
}
|
|
65
|
+
async resolveAccessToken() {
|
|
66
|
+
const token = await this.options.getAccessToken();
|
|
67
|
+
if (!token) {
|
|
68
|
+
throw new Error("No SupaCloud management API access token available. Pass getAccessToken() or ensure supabase.auth has an active session.");
|
|
69
|
+
}
|
|
70
|
+
return token;
|
|
71
|
+
}
|
|
72
|
+
async request(path, method, body) {
|
|
73
|
+
const accessToken = await this.resolveAccessToken();
|
|
74
|
+
const response = await fetch(`${this.options.managementApiUrl}${path}`, {
|
|
75
|
+
method,
|
|
76
|
+
headers: {
|
|
77
|
+
authorization: `Bearer ${accessToken}`,
|
|
78
|
+
...body !== undefined ? { "content-type": "application/json" } : {}
|
|
79
|
+
},
|
|
80
|
+
...body !== undefined ? { body: JSON.stringify(body) } : {}
|
|
81
|
+
});
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
throw new Error(`SupaCloud request failed (${response.status})`);
|
|
84
|
+
}
|
|
85
|
+
return await response.json();
|
|
86
|
+
}
|
|
87
|
+
createReceipt(taskId, status) {
|
|
88
|
+
return {
|
|
89
|
+
taskId,
|
|
90
|
+
status,
|
|
91
|
+
get: () => this.get(taskId),
|
|
92
|
+
wait: (options) => this.wait(taskId, options),
|
|
93
|
+
cancel: () => this.cancel(taskId),
|
|
94
|
+
retry: () => this.retry(taskId),
|
|
95
|
+
subscribe: (options) => this.subscribe(taskId, options)
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async submit(functionName, options = {}) {
|
|
99
|
+
const { body, headers = {}, retries, timeoutSec, idempotencyKey, method } = options;
|
|
100
|
+
const { data, error } = await this.options.supabase.functions.invoke(functionName, {
|
|
101
|
+
body,
|
|
102
|
+
method,
|
|
103
|
+
headers: {
|
|
104
|
+
...headers,
|
|
105
|
+
"x-supacloud-async": "true",
|
|
106
|
+
...retries !== undefined ? { "x-supacloud-retries": String(retries) } : {},
|
|
107
|
+
...timeoutSec !== undefined ? { "x-supacloud-timeout": String(timeoutSec) } : {},
|
|
108
|
+
...idempotencyKey ? { "x-supacloud-idempotency-key": idempotencyKey } : {}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
if (error)
|
|
112
|
+
throw error;
|
|
113
|
+
const payload = data ?? {};
|
|
114
|
+
const taskId = typeof payload.task_id === "string" ? payload.task_id : typeof payload.taskId === "string" ? payload.taskId : null;
|
|
115
|
+
if (!taskId) {
|
|
116
|
+
throw new SupaCloudTaskSubmitError("Background task was not enqueued", data);
|
|
117
|
+
}
|
|
118
|
+
return this.createReceipt(taskId, String(payload.status ?? "enqueued"));
|
|
119
|
+
}
|
|
120
|
+
async get(taskId) {
|
|
121
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}`, "GET");
|
|
122
|
+
}
|
|
123
|
+
async list(filters = {}) {
|
|
124
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET");
|
|
125
|
+
}
|
|
126
|
+
async cancel(taskId) {
|
|
127
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/cancel`, "POST");
|
|
128
|
+
}
|
|
129
|
+
async retry(taskId) {
|
|
130
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/retry`, "POST");
|
|
131
|
+
}
|
|
132
|
+
async listDlq(limit = 100) {
|
|
133
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/dlq?limit=${limit}`, "GET");
|
|
134
|
+
}
|
|
135
|
+
async wait(taskId, options = {}) {
|
|
136
|
+
const intervalMs = options.intervalMs ?? this.options.pollingIntervalMs;
|
|
137
|
+
while (true) {
|
|
138
|
+
if (options.signal?.aborted) {
|
|
139
|
+
throw options.signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
140
|
+
}
|
|
141
|
+
const task = await this.get(taskId);
|
|
142
|
+
if (TERMINAL_STATUSES.has(String(task.status)))
|
|
143
|
+
return task;
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
const timer = setTimeout(resolve, intervalMs);
|
|
146
|
+
if (options.signal) {
|
|
147
|
+
const onAbort = () => {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
150
|
+
reject(options.signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
151
|
+
};
|
|
152
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
subscribe(taskId, options) {
|
|
158
|
+
let closed = false;
|
|
159
|
+
let channel = null;
|
|
160
|
+
let pollTimer = null;
|
|
161
|
+
let mode = "connecting";
|
|
162
|
+
const pollingIntervalMs = options.pollingIntervalMs ?? this.options.pollingIntervalMs;
|
|
163
|
+
const stopOnTerminal = options.stopOnTerminal ?? true;
|
|
164
|
+
const setMode = (next, details) => {
|
|
165
|
+
if (closed || mode === next)
|
|
166
|
+
return;
|
|
167
|
+
mode = next;
|
|
168
|
+
options.onStateChange?.(next, details);
|
|
169
|
+
};
|
|
170
|
+
const stopPolling = () => {
|
|
171
|
+
if (pollTimer) {
|
|
172
|
+
clearTimeout(pollTimer);
|
|
173
|
+
pollTimer = null;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
const teardownRealtime = async () => {
|
|
177
|
+
if (channel) {
|
|
178
|
+
const current = channel;
|
|
179
|
+
channel = null;
|
|
180
|
+
await this.options.supabase.removeChannel(current);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const close = async () => {
|
|
184
|
+
if (closed)
|
|
185
|
+
return;
|
|
186
|
+
stopPolling();
|
|
187
|
+
await teardownRealtime();
|
|
188
|
+
setMode("closed");
|
|
189
|
+
closed = true;
|
|
190
|
+
};
|
|
191
|
+
const emitTask = (task) => {
|
|
192
|
+
const snapshot = normalizeTaskSnapshot(task);
|
|
193
|
+
options.onUpdate(snapshot);
|
|
194
|
+
if (stopOnTerminal && TERMINAL_STATUSES.has(snapshot.status)) {
|
|
195
|
+
close();
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
const pollOnce = async () => {
|
|
199
|
+
if (closed)
|
|
200
|
+
return;
|
|
201
|
+
try {
|
|
202
|
+
const task = await this.get(taskId);
|
|
203
|
+
emitTask(task);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
options.onError?.(error);
|
|
206
|
+
} finally {
|
|
207
|
+
if (!closed && mode === "polling") {
|
|
208
|
+
pollTimer = setTimeout(() => {
|
|
209
|
+
pollOnce();
|
|
210
|
+
}, pollingIntervalMs);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
const startPolling = (error) => {
|
|
215
|
+
if (closed)
|
|
216
|
+
return;
|
|
217
|
+
stopPolling();
|
|
218
|
+
setMode("polling", { error });
|
|
219
|
+
pollOnce();
|
|
220
|
+
};
|
|
221
|
+
channel = this.options.supabase.channel(`supacloud-task:${this.options.projectRef}:${taskId}`).on("postgres_changes", {
|
|
222
|
+
event: "*",
|
|
223
|
+
schema: "public",
|
|
224
|
+
table: "tasks",
|
|
225
|
+
filter: `id=eq.${taskId}`
|
|
226
|
+
}, (payload) => {
|
|
227
|
+
const next = payload.new && Object.keys(payload.new).length > 0 ? payload.new : payload.old;
|
|
228
|
+
if (next)
|
|
229
|
+
emitTask(next);
|
|
230
|
+
}).subscribe(async (status, error) => {
|
|
231
|
+
if (closed)
|
|
232
|
+
return;
|
|
233
|
+
if (status === "SUBSCRIBED") {
|
|
234
|
+
stopPolling();
|
|
235
|
+
setMode("realtime");
|
|
236
|
+
try {
|
|
237
|
+
emitTask(await this.get(taskId));
|
|
238
|
+
} catch (err) {
|
|
239
|
+
options.onError?.(err);
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (status === "TIMED_OUT" || status === "CHANNEL_ERROR" || status === "CLOSED") {
|
|
244
|
+
await teardownRealtime();
|
|
245
|
+
startPolling(error);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
setMode("connecting");
|
|
249
|
+
return {
|
|
250
|
+
get connectionState() {
|
|
251
|
+
return mode;
|
|
252
|
+
},
|
|
253
|
+
unsubscribe() {
|
|
254
|
+
close();
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function createSupaCloudClient(options) {
|
|
260
|
+
const normalized = {
|
|
261
|
+
...options,
|
|
262
|
+
managementApiUrl: normalizeBaseUrl(options.managementApiUrl),
|
|
263
|
+
pollingIntervalMs: options.pollingIntervalMs ?? 3000,
|
|
264
|
+
getAccessToken: options.getAccessToken ?? (() => defaultAccessTokenResolver(options.supabase))
|
|
265
|
+
};
|
|
266
|
+
const tasks = new SupaCloudTasksClient(normalized);
|
|
267
|
+
return {
|
|
268
|
+
supabase: options.supabase,
|
|
269
|
+
projectRef: normalized.projectRef,
|
|
270
|
+
managementApiUrl: normalized.managementApiUrl,
|
|
271
|
+
tasks,
|
|
272
|
+
functions: {
|
|
273
|
+
invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
export {
|
|
278
|
+
createSupaCloudClient,
|
|
279
|
+
SupaCloudTaskSubmitError
|
|
280
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@supacloud/js",
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"description": "Platform SDK for SupaCloud, built on top of supabase-js",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "bun build src/index.ts --outdir dist --target node",
|
|
15
|
+
"typecheck": "tsc --noEmit"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"supacloud",
|
|
19
|
+
"supabase",
|
|
20
|
+
"sdk",
|
|
21
|
+
"background-tasks",
|
|
22
|
+
"realtime"
|
|
23
|
+
],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://github.com/zuohuadong/supacloud.git",
|
|
28
|
+
"directory": "packages/supacloud-js"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@supabase/supabase-js": "^2.103.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@supabase/supabase-js": "^2.103.0",
|
|
35
|
+
"typescript": "^5.9.3"
|
|
36
|
+
}
|
|
37
|
+
}
|