@supacloud/js 0.11.1 → 0.11.3
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/dist/index.d.ts +124 -0
- package/dist/index.js +274 -0
- package/package.json +13 -2
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
+
export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
|
|
3
|
+
export type SupaCloudTaskLogEntry = {
|
|
4
|
+
timestamp: string;
|
|
5
|
+
stream: "stdout" | "stderr";
|
|
6
|
+
level: string;
|
|
7
|
+
message: string;
|
|
8
|
+
};
|
|
9
|
+
export type SupaCloudTaskAttempt = {
|
|
10
|
+
attempt_no: number;
|
|
11
|
+
status: string;
|
|
12
|
+
started_at: string | null;
|
|
13
|
+
completed_at: string | null;
|
|
14
|
+
duration_ms: number | null;
|
|
15
|
+
response_status: number | null;
|
|
16
|
+
error: string | null;
|
|
17
|
+
logs: SupaCloudTaskLogEntry[];
|
|
18
|
+
};
|
|
19
|
+
export type SupaCloudTaskDetail = {
|
|
20
|
+
id: string;
|
|
21
|
+
status: SupaCloudTaskStatus | string;
|
|
22
|
+
function_slug?: string | null;
|
|
23
|
+
function_version?: string | null;
|
|
24
|
+
attempt?: number | null;
|
|
25
|
+
max_attempts?: number | null;
|
|
26
|
+
progress?: number | null;
|
|
27
|
+
error?: string | null;
|
|
28
|
+
error_message?: string | null;
|
|
29
|
+
result?: unknown;
|
|
30
|
+
payload?: Record<string, unknown>;
|
|
31
|
+
attempts?: SupaCloudTaskAttempt[];
|
|
32
|
+
latest_logs?: SupaCloudTaskLogEntry[];
|
|
33
|
+
updated_at?: string | null;
|
|
34
|
+
created_at?: string | null;
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
};
|
|
37
|
+
export type SupaCloudTaskSnapshot = {
|
|
38
|
+
id: string;
|
|
39
|
+
status: SupaCloudTaskStatus | string;
|
|
40
|
+
progress?: number | null;
|
|
41
|
+
error?: string | null;
|
|
42
|
+
updatedAt?: string | null;
|
|
43
|
+
raw: unknown;
|
|
44
|
+
};
|
|
45
|
+
export type SupaCloudTaskListFilters = {
|
|
46
|
+
status?: string | string[];
|
|
47
|
+
taskType?: string | string[];
|
|
48
|
+
functionSlug?: string;
|
|
49
|
+
dlq?: boolean;
|
|
50
|
+
limit?: number;
|
|
51
|
+
};
|
|
52
|
+
export type SupaCloudTaskSubmitOptions = {
|
|
53
|
+
body?: string | Blob | ArrayBuffer | FormData | File | ReadableStream<Uint8Array> | Record<string, unknown>;
|
|
54
|
+
headers?: Record<string, string>;
|
|
55
|
+
retries?: number;
|
|
56
|
+
timeoutSec?: number;
|
|
57
|
+
idempotencyKey?: string;
|
|
58
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
59
|
+
};
|
|
60
|
+
export type SupaCloudTaskWaitOptions = {
|
|
61
|
+
intervalMs?: number;
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
};
|
|
64
|
+
export type SupaCloudTaskSubscribeState = "connecting" | "realtime" | "polling" | "closed";
|
|
65
|
+
export type SupaCloudTaskSubscribeOptions = {
|
|
66
|
+
pollingIntervalMs?: number;
|
|
67
|
+
onUpdate: (task: SupaCloudTaskSnapshot) => void;
|
|
68
|
+
onStateChange?: (state: SupaCloudTaskSubscribeState, details?: {
|
|
69
|
+
error?: unknown;
|
|
70
|
+
}) => void;
|
|
71
|
+
onError?: (error: unknown) => void;
|
|
72
|
+
stopOnTerminal?: boolean;
|
|
73
|
+
};
|
|
74
|
+
export type SupaCloudTaskReceipt = {
|
|
75
|
+
taskId: string;
|
|
76
|
+
status: string;
|
|
77
|
+
get: () => Promise<SupaCloudTaskDetail>;
|
|
78
|
+
wait: (options?: SupaCloudTaskWaitOptions) => Promise<SupaCloudTaskDetail>;
|
|
79
|
+
cancel: () => Promise<SupaCloudTaskDetail>;
|
|
80
|
+
retry: () => Promise<SupaCloudTaskDetail>;
|
|
81
|
+
subscribe: (options: SupaCloudTaskSubscribeOptions) => {
|
|
82
|
+
connectionState: SupaCloudTaskSubscribeState;
|
|
83
|
+
unsubscribe: () => void;
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
export type SupaCloudClientOptions<TClient extends SupabaseClient = SupabaseClient> = {
|
|
87
|
+
supabase: TClient;
|
|
88
|
+
managementApiUrl: string;
|
|
89
|
+
projectRef: string;
|
|
90
|
+
getAccessToken?: () => Promise<string | null> | string | null;
|
|
91
|
+
pollingIntervalMs?: number;
|
|
92
|
+
};
|
|
93
|
+
export declare class SupaCloudTaskSubmitError extends Error {
|
|
94
|
+
readonly responseBody: unknown;
|
|
95
|
+
constructor(message: string, responseBody: unknown);
|
|
96
|
+
}
|
|
97
|
+
declare class SupaCloudTasksClient<TClient extends SupabaseClient = SupabaseClient> {
|
|
98
|
+
private readonly options;
|
|
99
|
+
constructor(options: Required<SupaCloudClientOptions<TClient>>);
|
|
100
|
+
private resolveAccessToken;
|
|
101
|
+
private request;
|
|
102
|
+
private createReceipt;
|
|
103
|
+
submit(functionName: string, options?: SupaCloudTaskSubmitOptions): Promise<SupaCloudTaskReceipt>;
|
|
104
|
+
get(taskId: string): Promise<SupaCloudTaskDetail>;
|
|
105
|
+
list(filters?: SupaCloudTaskListFilters): Promise<SupaCloudTaskDetail[]>;
|
|
106
|
+
cancel(taskId: string): Promise<SupaCloudTaskDetail>;
|
|
107
|
+
retry(taskId: string): Promise<SupaCloudTaskDetail>;
|
|
108
|
+
listDlq(limit?: number): Promise<SupaCloudTaskDetail[]>;
|
|
109
|
+
wait(taskId: string, options?: SupaCloudTaskWaitOptions): Promise<SupaCloudTaskDetail>;
|
|
110
|
+
subscribe(taskId: string, options: SupaCloudTaskSubscribeOptions): {
|
|
111
|
+
readonly connectionState: SupaCloudTaskSubscribeState;
|
|
112
|
+
unsubscribe(): void;
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
|
|
116
|
+
supabase: TClient;
|
|
117
|
+
projectRef: string;
|
|
118
|
+
managementApiUrl: string;
|
|
119
|
+
tasks: SupaCloudTasksClient<TClient>;
|
|
120
|
+
functions: {
|
|
121
|
+
invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt>;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
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: _retries, timeoutSec: _timeoutSec, idempotencyKey: _idempotencyKey, method } = options;
|
|
100
|
+
const { data, error } = await this.options.supabase.functions.invoke(functionName, {
|
|
101
|
+
body,
|
|
102
|
+
method,
|
|
103
|
+
headers
|
|
104
|
+
});
|
|
105
|
+
if (error)
|
|
106
|
+
throw error;
|
|
107
|
+
const payload = data ?? {};
|
|
108
|
+
const taskId = typeof payload.task_id === "string" ? payload.task_id : typeof payload.taskId === "string" ? payload.taskId : null;
|
|
109
|
+
if (!taskId) {
|
|
110
|
+
throw new SupaCloudTaskSubmitError("Background task was not enqueued", data);
|
|
111
|
+
}
|
|
112
|
+
return this.createReceipt(taskId, String(payload.status ?? "enqueued"));
|
|
113
|
+
}
|
|
114
|
+
async get(taskId) {
|
|
115
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}`, "GET");
|
|
116
|
+
}
|
|
117
|
+
async list(filters = {}) {
|
|
118
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET");
|
|
119
|
+
}
|
|
120
|
+
async cancel(taskId) {
|
|
121
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/cancel`, "POST");
|
|
122
|
+
}
|
|
123
|
+
async retry(taskId) {
|
|
124
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/retry`, "POST");
|
|
125
|
+
}
|
|
126
|
+
async listDlq(limit = 100) {
|
|
127
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/dlq?limit=${limit}`, "GET");
|
|
128
|
+
}
|
|
129
|
+
async wait(taskId, options = {}) {
|
|
130
|
+
const intervalMs = options.intervalMs ?? this.options.pollingIntervalMs;
|
|
131
|
+
while (true) {
|
|
132
|
+
if (options.signal?.aborted) {
|
|
133
|
+
throw options.signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
134
|
+
}
|
|
135
|
+
const task = await this.get(taskId);
|
|
136
|
+
if (TERMINAL_STATUSES.has(String(task.status)))
|
|
137
|
+
return task;
|
|
138
|
+
await new Promise((resolve, reject) => {
|
|
139
|
+
const timer = setTimeout(resolve, intervalMs);
|
|
140
|
+
if (options.signal) {
|
|
141
|
+
const onAbort = () => {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
144
|
+
reject(options.signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
145
|
+
};
|
|
146
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
subscribe(taskId, options) {
|
|
152
|
+
let closed = false;
|
|
153
|
+
let channel = null;
|
|
154
|
+
let pollTimer = null;
|
|
155
|
+
let mode = "connecting";
|
|
156
|
+
const pollingIntervalMs = options.pollingIntervalMs ?? this.options.pollingIntervalMs;
|
|
157
|
+
const stopOnTerminal = options.stopOnTerminal ?? true;
|
|
158
|
+
const setMode = (next, details) => {
|
|
159
|
+
if (closed || mode === next)
|
|
160
|
+
return;
|
|
161
|
+
mode = next;
|
|
162
|
+
options.onStateChange?.(next, details);
|
|
163
|
+
};
|
|
164
|
+
const stopPolling = () => {
|
|
165
|
+
if (pollTimer) {
|
|
166
|
+
clearTimeout(pollTimer);
|
|
167
|
+
pollTimer = null;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const teardownRealtime = async () => {
|
|
171
|
+
if (channel) {
|
|
172
|
+
const current = channel;
|
|
173
|
+
channel = null;
|
|
174
|
+
await this.options.supabase.removeChannel(current);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const close = async () => {
|
|
178
|
+
if (closed)
|
|
179
|
+
return;
|
|
180
|
+
stopPolling();
|
|
181
|
+
await teardownRealtime();
|
|
182
|
+
setMode("closed");
|
|
183
|
+
closed = true;
|
|
184
|
+
};
|
|
185
|
+
const emitTask = (task) => {
|
|
186
|
+
const snapshot = normalizeTaskSnapshot(task);
|
|
187
|
+
options.onUpdate(snapshot);
|
|
188
|
+
if (stopOnTerminal && TERMINAL_STATUSES.has(snapshot.status)) {
|
|
189
|
+
close();
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const pollOnce = async () => {
|
|
193
|
+
if (closed)
|
|
194
|
+
return;
|
|
195
|
+
try {
|
|
196
|
+
const task = await this.get(taskId);
|
|
197
|
+
emitTask(task);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
options.onError?.(error);
|
|
200
|
+
} finally {
|
|
201
|
+
if (!closed && mode === "polling") {
|
|
202
|
+
pollTimer = setTimeout(() => {
|
|
203
|
+
pollOnce();
|
|
204
|
+
}, pollingIntervalMs);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
const startPolling = (error) => {
|
|
209
|
+
if (closed)
|
|
210
|
+
return;
|
|
211
|
+
stopPolling();
|
|
212
|
+
setMode("polling", { error });
|
|
213
|
+
pollOnce();
|
|
214
|
+
};
|
|
215
|
+
channel = this.options.supabase.channel(`supacloud-task:${this.options.projectRef}:${taskId}`).on("postgres_changes", {
|
|
216
|
+
event: "*",
|
|
217
|
+
schema: "public",
|
|
218
|
+
table: "tasks",
|
|
219
|
+
filter: `id=eq.${taskId}`
|
|
220
|
+
}, (payload) => {
|
|
221
|
+
const next = payload.new && Object.keys(payload.new).length > 0 ? payload.new : payload.old;
|
|
222
|
+
if (next)
|
|
223
|
+
emitTask(next);
|
|
224
|
+
}).subscribe(async (status, error) => {
|
|
225
|
+
if (closed)
|
|
226
|
+
return;
|
|
227
|
+
if (status === "SUBSCRIBED") {
|
|
228
|
+
stopPolling();
|
|
229
|
+
setMode("realtime");
|
|
230
|
+
try {
|
|
231
|
+
emitTask(await this.get(taskId));
|
|
232
|
+
} catch (err) {
|
|
233
|
+
options.onError?.(err);
|
|
234
|
+
}
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (status === "TIMED_OUT" || status === "CHANNEL_ERROR" || status === "CLOSED") {
|
|
238
|
+
await teardownRealtime();
|
|
239
|
+
startPolling(error);
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
setMode("connecting");
|
|
243
|
+
return {
|
|
244
|
+
get connectionState() {
|
|
245
|
+
return mode;
|
|
246
|
+
},
|
|
247
|
+
unsubscribe() {
|
|
248
|
+
close();
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
function createSupaCloudClient(options) {
|
|
254
|
+
const normalized = {
|
|
255
|
+
...options,
|
|
256
|
+
managementApiUrl: normalizeBaseUrl(options.managementApiUrl),
|
|
257
|
+
pollingIntervalMs: options.pollingIntervalMs ?? 3000,
|
|
258
|
+
getAccessToken: options.getAccessToken ?? (() => defaultAccessTokenResolver(options.supabase))
|
|
259
|
+
};
|
|
260
|
+
const tasks = new SupaCloudTasksClient(normalized);
|
|
261
|
+
return {
|
|
262
|
+
supabase: options.supabase,
|
|
263
|
+
projectRef: normalized.projectRef,
|
|
264
|
+
managementApiUrl: normalized.managementApiUrl,
|
|
265
|
+
tasks,
|
|
266
|
+
functions: {
|
|
267
|
+
invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
export {
|
|
272
|
+
createSupaCloudClient,
|
|
273
|
+
SupaCloudTaskSubmitError
|
|
274
|
+
};
|
package/package.json
CHANGED
|
@@ -1,17 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/js",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.3",
|
|
4
4
|
"description": "Platform SDK for SupaCloud, built on top of supabase-js",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
9
16
|
"files": [
|
|
10
17
|
"dist",
|
|
11
18
|
"README.md"
|
|
12
19
|
],
|
|
13
20
|
"scripts": {
|
|
14
|
-
"build": "bun build
|
|
21
|
+
"build": "bun run clean && bun run build:js && bun run build:types",
|
|
22
|
+
"build:js": "bun build src/index.ts --outdir dist --target node",
|
|
23
|
+
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
24
|
+
"clean": "rm -rf dist",
|
|
25
|
+
"prepublishOnly": "bun run build",
|
|
15
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
16
27
|
"typecheck:test": "tsc -p tsconfig.test.json --noEmit"
|
|
17
28
|
},
|