@supacloud/js 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -0
  2. package/package.json +5 -3
  3. package/dist/index.js +0 -280
package/README.md CHANGED
@@ -45,6 +45,9 @@ This SDK is intentionally thin:
45
45
  - `supabase-js` still owns auth, storage, database, Realtime transport, and plain function invokes
46
46
  - `@supacloud/js` owns SupaCloud platform semantics layered on top of that transport
47
47
 
48
+ `tasks.submit()` expects the target function path to be configured in `background_routes`.
49
+ That keeps frontend calls compatible with strict CORS deployments while preserving the same task receipt API.
50
+
48
51
  The current package focuses on:
49
52
 
50
53
  - `tasks.submit`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "scripts": {
14
14
  "build": "bun build src/index.ts --outdir dist --target node",
15
- "typecheck": "tsc --noEmit"
15
+ "typecheck": "tsc -p tsconfig.json --noEmit",
16
+ "typecheck:test": "tsc -p tsconfig.test.json --noEmit"
16
17
  },
17
18
  "keywords": [
18
19
  "supacloud",
@@ -31,7 +32,8 @@
31
32
  "@supabase/supabase-js": "^2.103.0"
32
33
  },
33
34
  "devDependencies": {
35
+ "@types/bun": "^1.3.9",
34
36
  "@supabase/supabase-js": "^2.103.0",
35
- "typescript": "^5.9.3"
37
+ "typescript": "^6.0.0"
36
38
  }
37
39
  }
package/dist/index.js DELETED
@@ -1,280 +0,0 @@
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
- };