@supacloud/js 0.25.0 → 0.30.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 +387 -56
- package/dist/api-error.d.ts +6 -0
- package/dist/artifact-fetch.d.ts +6 -0
- package/dist/artifact-link.d.ts +8 -0
- package/dist/artifact-read.d.ts +13 -0
- package/dist/artifact-register.d.ts +14 -0
- package/dist/artifact-rpc.d.ts +2 -0
- package/dist/artifacts.d.ts +3 -0
- package/dist/auth-fetch.d.ts +4 -2
- package/dist/bounded-rpc-fetch.d.ts +2 -0
- package/dist/command-fetch.d.ts +6 -0
- package/dist/commands.d.ts +27 -16
- package/dist/index.d.ts +104 -225
- package/dist/index.js +3027 -456
- package/dist/oauth-clients.d.ts +95 -0
- package/dist/oauth-server.d.ts +104 -0
- package/dist/queue-rpc.d.ts +54 -0
- package/dist/workflow-advance.d.ts +8 -0
- package/dist/workflow-attempt.d.ts +4 -0
- package/dist/workflow-cancel.d.ts +14 -0
- package/dist/workflow-claim.d.ts +12 -0
- package/dist/workflow-complete.d.ts +8 -0
- package/dist/workflow-events.d.ts +14 -0
- package/dist/workflow-fail.d.ts +8 -0
- package/dist/workflow-fetch.d.ts +9 -0
- package/dist/workflow-json.d.ts +2 -0
- package/dist/workflow-retry.d.ts +8 -0
- package/dist/workflow-rpc.d.ts +6 -0
- package/dist/workflow-run.d.ts +8 -0
- package/dist/workflow-start.d.ts +8 -0
- package/dist/workflow-timestamp.d.ts +1 -0
- package/dist/workflows.d.ts +9 -0
- package/package.json +6 -3
package/dist/index.js
CHANGED
|
@@ -1,66 +1,1388 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { FunctionsHttpError } from "@supabase/supabase-js";
|
|
3
|
+
|
|
4
|
+
// src/workflow-rpc.ts
|
|
5
|
+
function invokeWorkflowMutation(supabase, functionName, request, unconfirmed) {
|
|
6
|
+
return invokeWorkflowRpc(supabase, functionName, request, unconfirmed);
|
|
7
|
+
}
|
|
8
|
+
function invokeWorkflowRead(supabase, functionName, request, invalid) {
|
|
9
|
+
return invokeWorkflowRpc(supabase, functionName, request, invalid);
|
|
10
|
+
}
|
|
11
|
+
async function invokeWorkflowRpc(supabase, functionName, request, failure) {
|
|
12
|
+
const controller = new AbortController;
|
|
13
|
+
let timer;
|
|
14
|
+
const deadline = new Promise((_, reject) => {
|
|
15
|
+
timer = setTimeout(() => {
|
|
16
|
+
reject(failure());
|
|
17
|
+
controller.abort();
|
|
18
|
+
}, 15000);
|
|
19
|
+
});
|
|
20
|
+
let result;
|
|
21
|
+
try {
|
|
22
|
+
const pending = supabase.rpc(functionName, { request }).retry(false).abortSignal(controller.signal);
|
|
23
|
+
result = await Promise.race([pending, deadline]);
|
|
24
|
+
} catch {
|
|
25
|
+
throw failure();
|
|
26
|
+
} finally {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
}
|
|
29
|
+
if (result.error && result.status >= 400 && result.status < 500)
|
|
30
|
+
throw result.error;
|
|
31
|
+
if (result.error || result.status !== 200)
|
|
32
|
+
throw failure();
|
|
33
|
+
return result.data;
|
|
8
34
|
}
|
|
9
35
|
|
|
10
|
-
// src/
|
|
11
|
-
class
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
36
|
+
// src/api-error.ts
|
|
37
|
+
class SupaCloudApiError extends Error {
|
|
38
|
+
status;
|
|
39
|
+
code;
|
|
40
|
+
responseBody;
|
|
41
|
+
constructor(message, status, responseBody) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = "SupaCloudApiError";
|
|
44
|
+
this.status = status;
|
|
45
|
+
this.responseBody = responseBody;
|
|
46
|
+
this.code = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) && Object.hasOwn(responseBody, "code") && "code" in responseBody && typeof responseBody.code === "string" ? responseBody.code : null;
|
|
15
47
|
}
|
|
16
|
-
|
|
17
|
-
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/queue-rpc.ts
|
|
51
|
+
class SupaCloudQueueError extends SupaCloudApiError {
|
|
52
|
+
mutationMayHaveApplied;
|
|
53
|
+
constructor(mutationMayHaveApplied = false, code = "QUEUE_CONTRACT_INVALID") {
|
|
54
|
+
super("Queue input or response could not be validated", 0, {
|
|
55
|
+
code,
|
|
56
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
57
|
+
});
|
|
58
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
59
|
+
this.name = "SupaCloudQueueError";
|
|
18
60
|
}
|
|
19
|
-
|
|
20
|
-
|
|
61
|
+
}
|
|
62
|
+
function invalid() {
|
|
63
|
+
throw new SupaCloudQueueError;
|
|
64
|
+
}
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function record(value) {
|
|
69
|
+
return isRecord(value) ? value : invalid();
|
|
70
|
+
}
|
|
71
|
+
function queueMessageId(value) {
|
|
72
|
+
if (typeof value === "number") {
|
|
73
|
+
return Number.isSafeInteger(value) && value > 0 ? String(value) : invalid();
|
|
21
74
|
}
|
|
22
|
-
|
|
23
|
-
return
|
|
75
|
+
if (typeof value !== "string" || !/^[1-9][0-9]{0,18}$/.test(value) || BigInt(value) > 9223372036854775807n)
|
|
76
|
+
return invalid();
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
function queueInteger(value, min, max = 2147483647) {
|
|
80
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid();
|
|
81
|
+
}
|
|
82
|
+
function queueSeconds(options) {
|
|
83
|
+
record(options);
|
|
84
|
+
const candidates = [];
|
|
85
|
+
for (const value of [options.sleepSeconds, options.sleep_seconds, options.visibilityTimeoutSec]) {
|
|
86
|
+
if (value !== undefined)
|
|
87
|
+
candidates.push(queueInteger(value, 0));
|
|
88
|
+
}
|
|
89
|
+
if (options.delayMs !== undefined) {
|
|
90
|
+
candidates.push(Math.floor(queueInteger(options.delayMs, 0, 2147483647 * 1000) / 1000));
|
|
91
|
+
}
|
|
92
|
+
const first = candidates[0] ?? 0;
|
|
93
|
+
if (candidates.some((value) => value !== first))
|
|
94
|
+
return invalid();
|
|
95
|
+
return first;
|
|
96
|
+
}
|
|
97
|
+
function queueReadCount(options, single = false) {
|
|
98
|
+
const data = record(options);
|
|
99
|
+
const n = data.n === undefined ? undefined : queueInteger(data.n, 1, 1e4);
|
|
100
|
+
const count = data.count === undefined ? undefined : queueInteger(data.count, 1, 1e4);
|
|
101
|
+
if (n !== undefined && count !== undefined && n !== count)
|
|
102
|
+
return invalid();
|
|
103
|
+
const result = n ?? count ?? 1;
|
|
104
|
+
return !single || result === 1 ? result : invalid();
|
|
105
|
+
}
|
|
106
|
+
function queueJsonSnapshot(value) {
|
|
107
|
+
const ancestors = new Set;
|
|
108
|
+
let nodes = 0, characters = 0;
|
|
109
|
+
function visit(input, depth) {
|
|
110
|
+
if (++nodes > 1e4 || depth > 64)
|
|
111
|
+
return invalid();
|
|
112
|
+
if (input === null || typeof input === "boolean")
|
|
113
|
+
return input;
|
|
114
|
+
if (typeof input === "number")
|
|
115
|
+
return Number.isFinite(input) ? input : invalid();
|
|
116
|
+
if (typeof input === "string") {
|
|
117
|
+
characters += input.length;
|
|
118
|
+
return characters <= 1048576 ? input : invalid();
|
|
119
|
+
}
|
|
120
|
+
if (typeof input !== "object" || ancestors.has(input))
|
|
121
|
+
return invalid();
|
|
122
|
+
if (!Array.isArray(input) && Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
|
|
123
|
+
return invalid();
|
|
124
|
+
ancestors.add(input);
|
|
125
|
+
try {
|
|
126
|
+
let property = function(key) {
|
|
127
|
+
const descriptor = properties[key];
|
|
128
|
+
if (!descriptor || !("value" in descriptor))
|
|
129
|
+
return invalid();
|
|
130
|
+
const item = descriptor.value;
|
|
131
|
+
return visit(item, depth + 1);
|
|
132
|
+
};
|
|
133
|
+
if (Object.getOwnPropertySymbols(input).length !== 0)
|
|
134
|
+
return invalid();
|
|
135
|
+
const properties = Object.getOwnPropertyDescriptors(input);
|
|
136
|
+
if (Array.isArray(input)) {
|
|
137
|
+
if (input.length > 1e4 || Object.keys(input).length !== input.length)
|
|
138
|
+
return invalid();
|
|
139
|
+
return Array.from({ length: input.length }, (_, index) => property(String(index)));
|
|
140
|
+
}
|
|
141
|
+
return Object.fromEntries(Object.keys(input).map((key) => {
|
|
142
|
+
characters += key.length;
|
|
143
|
+
if (characters > 1048576)
|
|
144
|
+
return invalid();
|
|
145
|
+
return [key, property(key)];
|
|
146
|
+
}));
|
|
147
|
+
} finally {
|
|
148
|
+
ancestors.delete(input);
|
|
149
|
+
}
|
|
24
150
|
}
|
|
25
|
-
|
|
26
|
-
|
|
151
|
+
return visit(value, 0);
|
|
152
|
+
}
|
|
153
|
+
function queueRpcIds(value, expected) {
|
|
154
|
+
if (!Array.isArray(value) || value.length !== expected)
|
|
155
|
+
return invalid();
|
|
156
|
+
const ids = value.map((id) => queueMessageId(id));
|
|
157
|
+
return new Set(ids).size === ids.length ? ids : invalid();
|
|
158
|
+
}
|
|
159
|
+
function queueRpcId(value) {
|
|
160
|
+
const id = queueRpcIds(value, 1)[0];
|
|
161
|
+
return id === undefined ? invalid() : id;
|
|
162
|
+
}
|
|
163
|
+
function queueRpcBoolean(value) {
|
|
164
|
+
return typeof value === "boolean" ? value : invalid();
|
|
165
|
+
}
|
|
166
|
+
function optionalText(value) {
|
|
167
|
+
return typeof value === "string" && value.length > 0 && value.length <= 4096 ? value : invalid();
|
|
168
|
+
}
|
|
169
|
+
function jsonEqual(left, right) {
|
|
170
|
+
if (left === right)
|
|
171
|
+
return true;
|
|
172
|
+
if (Array.isArray(left)) {
|
|
173
|
+
return Array.isArray(right) && left.length === right.length && left.every((item, index) => right[index] !== undefined && jsonEqual(item, right[index]));
|
|
174
|
+
}
|
|
175
|
+
if (left === null || right === null || typeof left !== "object" || typeof right !== "object" || Array.isArray(right))
|
|
176
|
+
return false;
|
|
177
|
+
const entries = Object.entries(left);
|
|
178
|
+
return entries.length === Object.keys(right).length && entries.every(([key, value]) => Object.hasOwn(right, key) && right[key] !== undefined && jsonEqual(value, right[key]));
|
|
179
|
+
}
|
|
180
|
+
function queueMessage(value, expected = {}) {
|
|
181
|
+
const data = record(value);
|
|
182
|
+
const id = queueMessageId(data.msg_id);
|
|
183
|
+
if (expected.messageId !== undefined && expected.messageId !== id || data.id !== undefined && queueMessageId(data.id) !== id)
|
|
184
|
+
return invalid();
|
|
185
|
+
const hasMessage = Object.hasOwn(data, "message");
|
|
186
|
+
const hasPayload = Object.hasOwn(data, "payload");
|
|
187
|
+
if (!hasMessage && (!hasPayload || expected.rpc))
|
|
188
|
+
return invalid();
|
|
189
|
+
const message = queueJsonSnapshot(hasMessage ? data.message : data.payload);
|
|
190
|
+
if (hasMessage && hasPayload && !jsonEqual(message, queueJsonSnapshot(data.payload)))
|
|
191
|
+
return invalid();
|
|
192
|
+
const result = { id, msg_id: id, message, payload: message };
|
|
193
|
+
if (data.read_ct !== undefined || expected.rpc)
|
|
194
|
+
result.read_ct = queueInteger(data.read_ct, 0);
|
|
195
|
+
for (const field of ["enqueued_at", "vt"]) {
|
|
196
|
+
if (data[field] === undefined && !expected.rpc)
|
|
197
|
+
continue;
|
|
198
|
+
const timestamp = data[field];
|
|
199
|
+
if (timestamp === null && !expected.rpc) {
|
|
200
|
+
result[field] = null;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const text = optionalText(timestamp);
|
|
204
|
+
if (!Number.isFinite(Date.parse(text)))
|
|
205
|
+
return invalid();
|
|
206
|
+
result[field] = text;
|
|
207
|
+
}
|
|
208
|
+
for (const field of ["status", "queue_name", "task_type"]) {
|
|
209
|
+
if (data[field] !== undefined)
|
|
210
|
+
result[field] = optionalText(data[field]);
|
|
211
|
+
}
|
|
212
|
+
if (expected.queueName !== undefined) {
|
|
213
|
+
if (result.queue_name !== undefined && result.queue_name !== expected.queueName || result.task_type !== undefined && result.task_type !== `queue:${expected.queueName}`)
|
|
214
|
+
return invalid();
|
|
215
|
+
result.queue_name = expected.queueName;
|
|
216
|
+
result.task_type = `queue:${expected.queueName}`;
|
|
217
|
+
}
|
|
218
|
+
if (expected.status !== undefined) {
|
|
219
|
+
if (result.status !== undefined && result.status !== expected.status)
|
|
220
|
+
return invalid();
|
|
221
|
+
result.status = expected.status;
|
|
222
|
+
}
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
function queueRpcMessages(queueName, value, max, status) {
|
|
226
|
+
if (!Array.isArray(value) || value.length > max)
|
|
227
|
+
return invalid();
|
|
228
|
+
const result = value.map((row) => queueMessage(row, { queueName, status, rpc: true }));
|
|
229
|
+
return new Set(result.map((row) => row.id)).size === result.length ? result : invalid();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/workflow-claim.ts
|
|
233
|
+
class SupaCloudWorkflowClaimInputError extends SupaCloudApiError {
|
|
234
|
+
mutationMayHaveApplied = false;
|
|
235
|
+
constructor() {
|
|
236
|
+
super("Workflow claim request could not be validated", 0, {
|
|
237
|
+
code: "WORKFLOW_CLAIM_INPUT_INVALID",
|
|
238
|
+
mutation_may_have_applied: false
|
|
239
|
+
});
|
|
240
|
+
this.name = "SupaCloudWorkflowClaimInputError";
|
|
27
241
|
}
|
|
28
|
-
|
|
29
|
-
|
|
242
|
+
}
|
|
243
|
+
function captureWorkflowClaimRequest(value) {
|
|
244
|
+
const fail = () => {
|
|
245
|
+
throw new SupaCloudWorkflowClaimInputError;
|
|
246
|
+
};
|
|
247
|
+
try {
|
|
248
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
249
|
+
return fail();
|
|
250
|
+
const properties = Object.getOwnPropertyDescriptors(value);
|
|
251
|
+
for (const name of Object.keys(properties)) {
|
|
252
|
+
const descriptor = properties[name];
|
|
253
|
+
if (name !== "workerId" && name !== "visibilityTimeoutSeconds" || !descriptor || !descriptor.enumerable || !("value" in descriptor))
|
|
254
|
+
return fail();
|
|
255
|
+
}
|
|
256
|
+
const worker = properties.workerId?.value;
|
|
257
|
+
const timeout = properties.visibilityTimeoutSeconds?.value;
|
|
258
|
+
if (typeof worker !== "string")
|
|
259
|
+
return fail();
|
|
260
|
+
const workerId = worker.replace(/^ +| +$/g, "");
|
|
261
|
+
let characters = 0;
|
|
262
|
+
for (const character of workerId) {
|
|
263
|
+
const point = character.codePointAt(0);
|
|
264
|
+
if (++characters > 200 || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
265
|
+
return fail();
|
|
266
|
+
}
|
|
267
|
+
if (characters === 0)
|
|
268
|
+
return fail();
|
|
269
|
+
const visibilityTimeoutSeconds = timeout === undefined ? 300 : timeout;
|
|
270
|
+
if (typeof visibilityTimeoutSeconds !== "number" || !Number.isSafeInteger(visibilityTimeoutSeconds) || visibilityTimeoutSeconds < 15 || visibilityTimeoutSeconds > 3600)
|
|
271
|
+
return fail();
|
|
272
|
+
return { workerId, visibilityTimeoutSeconds };
|
|
273
|
+
} catch {
|
|
274
|
+
return fail();
|
|
30
275
|
}
|
|
31
|
-
|
|
32
|
-
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
class SupaCloudWorkflowClaimError extends SupaCloudApiError {
|
|
279
|
+
mutationMayHaveApplied = true;
|
|
280
|
+
constructor() {
|
|
281
|
+
super("Workflow claim response could not be validated", 0, {
|
|
282
|
+
code: "WORKFLOW_CLAIM_UNCONFIRMED",
|
|
283
|
+
mutation_may_have_applied: true
|
|
284
|
+
});
|
|
285
|
+
this.name = "SupaCloudWorkflowClaimError";
|
|
33
286
|
}
|
|
34
|
-
|
|
35
|
-
|
|
287
|
+
}
|
|
288
|
+
function invalid2() {
|
|
289
|
+
throw new SupaCloudWorkflowClaimError;
|
|
290
|
+
}
|
|
291
|
+
function record2(value) {
|
|
292
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : invalid2();
|
|
293
|
+
}
|
|
294
|
+
function text(value) {
|
|
295
|
+
return typeof value === "string" && value.length > 0 ? value : invalid2();
|
|
296
|
+
}
|
|
297
|
+
function key(value) {
|
|
298
|
+
const result = text(value);
|
|
299
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : invalid2();
|
|
300
|
+
}
|
|
301
|
+
function version(value) {
|
|
302
|
+
const result = text(value);
|
|
303
|
+
let characters = 0;
|
|
304
|
+
for (const character of result) {
|
|
305
|
+
const point = character.codePointAt(0);
|
|
306
|
+
if (++characters > 80 || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
307
|
+
return invalid2();
|
|
308
|
+
}
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
311
|
+
function uuid(value) {
|
|
312
|
+
const result = text(value);
|
|
313
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result) ? result : invalid2();
|
|
314
|
+
}
|
|
315
|
+
function id(value) {
|
|
316
|
+
return typeof value === "string" && /^[1-9][0-9]{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n ? value : invalid2();
|
|
317
|
+
}
|
|
318
|
+
function positiveInteger(value) {
|
|
319
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= 2147483647 ? value : invalid2();
|
|
320
|
+
}
|
|
321
|
+
function decodeWorkflowClaim(value, expectedWorkerId) {
|
|
322
|
+
if (value === null)
|
|
323
|
+
return null;
|
|
324
|
+
try {
|
|
325
|
+
const data = record2(queueJsonSnapshot(value));
|
|
326
|
+
const messageId = id(data.messageId);
|
|
327
|
+
if (data.status === "discarded") {
|
|
328
|
+
const reason = text(data.reason);
|
|
329
|
+
return {
|
|
330
|
+
status: "discarded",
|
|
331
|
+
reason,
|
|
332
|
+
messageId,
|
|
333
|
+
...data.runId === undefined ? {} : { runId: uuid(data.runId) },
|
|
334
|
+
...data.stepId === undefined ? {} : { stepId: uuid(data.stepId) }
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const runId = uuid(data.runId);
|
|
338
|
+
const stepId = uuid(data.stepId);
|
|
339
|
+
const stepKey = key(data.stepKey);
|
|
340
|
+
const attempt = positiveInteger(data.attempt);
|
|
341
|
+
const maxAttempts = positiveInteger(data.maxAttempts);
|
|
342
|
+
if (maxAttempts > 100)
|
|
343
|
+
return invalid2();
|
|
344
|
+
if (data.status === "dead_lettered" && attempt > maxAttempts) {
|
|
345
|
+
return { status: "dead_lettered", runId, stepId, stepKey, messageId, attempt, maxAttempts };
|
|
346
|
+
}
|
|
347
|
+
if (data.status !== "claimed" || attempt > maxAttempts || data.workerId !== expectedWorkerId)
|
|
348
|
+
return invalid2();
|
|
349
|
+
return {
|
|
350
|
+
status: "claimed",
|
|
36
351
|
runId,
|
|
37
|
-
|
|
352
|
+
stepId,
|
|
353
|
+
stepKey,
|
|
354
|
+
messageId,
|
|
355
|
+
attempt,
|
|
356
|
+
maxAttempts,
|
|
357
|
+
workflowName: key(data.workflowName),
|
|
358
|
+
workflowVersion: version(data.workflowVersion),
|
|
359
|
+
workerId: text(data.workerId),
|
|
360
|
+
input: record2(data.input)
|
|
361
|
+
};
|
|
362
|
+
} catch {
|
|
363
|
+
return invalid2();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// src/workflow-timestamp.ts
|
|
368
|
+
function isWorkflowTimestamp(value) {
|
|
369
|
+
if (typeof value !== "string" || value.length > 40 || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.test(value))
|
|
370
|
+
return false;
|
|
371
|
+
const year = Number(value.slice(0, 4));
|
|
372
|
+
const month = Number(value.slice(5, 7));
|
|
373
|
+
const day = Number(value.slice(8, 10));
|
|
374
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
375
|
+
const days = month === 2 ? leap ? 29 : 28 : [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
376
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= days && Number(value.slice(11, 13)) <= 23 && Number(value.slice(14, 16)) <= 59 && Number(value.slice(17, 19)) <= 59 && Number.isFinite(Date.parse(value));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/workflow-run.ts
|
|
380
|
+
class SupaCloudWorkflowReadError extends SupaCloudApiError {
|
|
381
|
+
mutationMayHaveApplied = false;
|
|
382
|
+
constructor(code = "WORKFLOW_READ_INVALID") {
|
|
383
|
+
super("Workflow read could not be validated", 0, {
|
|
384
|
+
code,
|
|
385
|
+
mutation_may_have_applied: false
|
|
38
386
|
});
|
|
387
|
+
this.name = "SupaCloudWorkflowReadError";
|
|
39
388
|
}
|
|
40
|
-
|
|
41
|
-
|
|
389
|
+
}
|
|
390
|
+
function invalid3() {
|
|
391
|
+
throw new SupaCloudWorkflowReadError;
|
|
392
|
+
}
|
|
393
|
+
var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
394
|
+
function captureWorkflowRunId(value) {
|
|
395
|
+
if (typeof value !== "string" || !uuidPattern.test(value.toLowerCase())) {
|
|
396
|
+
throw new SupaCloudWorkflowReadError("WORKFLOW_READ_INPUT_INVALID");
|
|
42
397
|
}
|
|
43
|
-
|
|
44
|
-
|
|
398
|
+
return value.toLowerCase();
|
|
399
|
+
}
|
|
400
|
+
function uuid2(value) {
|
|
401
|
+
return typeof value === "string" && uuidPattern.test(value) ? value : invalid3();
|
|
402
|
+
}
|
|
403
|
+
function record3(value) {
|
|
404
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
405
|
+
return value;
|
|
406
|
+
return invalid3();
|
|
407
|
+
}
|
|
408
|
+
function text2(value, min = 0, max = 4000) {
|
|
409
|
+
if (typeof value !== "string")
|
|
410
|
+
return invalid3();
|
|
411
|
+
let count = 0;
|
|
412
|
+
for (const character of value) {
|
|
413
|
+
const point = character.codePointAt(0);
|
|
414
|
+
if (++count > max || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
415
|
+
return invalid3();
|
|
416
|
+
}
|
|
417
|
+
return count >= min ? value : invalid3();
|
|
418
|
+
}
|
|
419
|
+
function key2(value) {
|
|
420
|
+
const result = text2(value, 1, 120);
|
|
421
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : invalid3();
|
|
422
|
+
}
|
|
423
|
+
function id2(value) {
|
|
424
|
+
return typeof value === "string" && /^[1-9][0-9]{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n ? value : invalid3();
|
|
425
|
+
}
|
|
426
|
+
function integer(value, min, max = 2147483647) {
|
|
427
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid3();
|
|
428
|
+
}
|
|
429
|
+
function timestamp(value) {
|
|
430
|
+
return isWorkflowTimestamp(value) ? value : invalid3();
|
|
431
|
+
}
|
|
432
|
+
function nullable(value, decode) {
|
|
433
|
+
return value === null ? null : decode(value);
|
|
434
|
+
}
|
|
435
|
+
function state(value, values) {
|
|
436
|
+
for (const candidate of values)
|
|
437
|
+
if (candidate === value)
|
|
438
|
+
return candidate;
|
|
439
|
+
return invalid3();
|
|
440
|
+
}
|
|
441
|
+
function step(value) {
|
|
442
|
+
const data = record3(value);
|
|
443
|
+
return {
|
|
444
|
+
stepId: uuid2(data.stepId),
|
|
445
|
+
stepKey: key2(data.stepKey),
|
|
446
|
+
status: state(data.status, ["queued", "running", "completed", "failed", "dead_lettered", "cancelled"]),
|
|
447
|
+
input: record3(data.input),
|
|
448
|
+
output: record3(data.output),
|
|
449
|
+
errorMessage: text2(data.errorMessage),
|
|
450
|
+
attempts: integer(data.attempts, 0),
|
|
451
|
+
maxAttempts: integer(data.maxAttempts, 1, 100),
|
|
452
|
+
retryDelaySeconds: integer(data.retryDelaySeconds, 0, 86400),
|
|
453
|
+
queueMessageId: id2(data.queueMessageId),
|
|
454
|
+
claimedBy: nullable(data.claimedBy, (value) => text2(value, 1, 200)),
|
|
455
|
+
claimedAt: nullable(data.claimedAt, timestamp),
|
|
456
|
+
completedAt: nullable(data.completedAt, timestamp),
|
|
457
|
+
nextStepKey: nullable(data.nextStepKey, key2),
|
|
458
|
+
createdAt: timestamp(data.createdAt),
|
|
459
|
+
updatedAt: timestamp(data.updatedAt)
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function validateStepSuccessors(steps) {
|
|
463
|
+
if (steps.length === 0)
|
|
464
|
+
return invalid3();
|
|
465
|
+
const byKey = new Map(steps.map((item) => [item.stepKey, item]));
|
|
466
|
+
const successors = new Set;
|
|
467
|
+
for (const item of steps) {
|
|
468
|
+
if (item.nextStepKey !== null) {
|
|
469
|
+
if (item.status !== "completed" || item.completedAt === null || !byKey.has(item.nextStepKey) || successors.has(item.nextStepKey))
|
|
470
|
+
return invalid3();
|
|
471
|
+
successors.add(item.nextStepKey);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const roots = steps.filter((item) => !successors.has(item.stepKey));
|
|
475
|
+
if (roots.length !== 1)
|
|
476
|
+
return invalid3();
|
|
477
|
+
const visited = new Set;
|
|
478
|
+
let current = roots[0];
|
|
479
|
+
while (current) {
|
|
480
|
+
if (visited.has(current.stepKey))
|
|
481
|
+
return invalid3();
|
|
482
|
+
visited.add(current.stepKey);
|
|
483
|
+
current = current.nextStepKey === null ? undefined : byKey.get(current.nextStepKey);
|
|
484
|
+
}
|
|
485
|
+
if (visited.size !== steps.length)
|
|
486
|
+
return invalid3();
|
|
487
|
+
}
|
|
488
|
+
function validateLifecycle(run) {
|
|
489
|
+
const active = run.status === "queued" || run.status === "running";
|
|
490
|
+
if (active !== (run.completedAt === null))
|
|
491
|
+
return invalid3();
|
|
492
|
+
if ((run.status === "running" || run.status === "completed") && run.startedAt === null)
|
|
493
|
+
return invalid3();
|
|
494
|
+
if (run.status === "queued" && (run.startedAt !== null || run.steps.length !== 1 || run.steps[0]?.status !== "queued" || run.steps[0]?.attempts !== 0))
|
|
495
|
+
return invalid3();
|
|
496
|
+
if ((active || run.status === "completed") && run.errorMessage !== "")
|
|
497
|
+
return invalid3();
|
|
498
|
+
let activeSteps = 0;
|
|
499
|
+
let terminalSteps = 0;
|
|
500
|
+
for (const item of run.steps) {
|
|
501
|
+
const stepActive = item.status === "queued" || item.status === "running";
|
|
502
|
+
if (stepActive)
|
|
503
|
+
activeSteps++;
|
|
504
|
+
if (stepActive !== (item.completedAt === null))
|
|
505
|
+
return invalid3();
|
|
506
|
+
if (item.claimedBy === null !== (item.claimedAt === null))
|
|
507
|
+
return invalid3();
|
|
508
|
+
if (item.claimedBy !== null && (item.attempts === 0 || run.startedAt === null))
|
|
509
|
+
return invalid3();
|
|
510
|
+
if (item.status === "dead_lettered") {
|
|
511
|
+
if (item.attempts < item.maxAttempts || item.claimedBy === null && item.attempts === item.maxAttempts)
|
|
512
|
+
return invalid3();
|
|
513
|
+
} else if (item.attempts > item.maxAttempts || item.attempts > 0 && item.claimedBy === null)
|
|
514
|
+
return invalid3();
|
|
515
|
+
if (item.status === "queued" && item.attempts >= item.maxAttempts)
|
|
516
|
+
return invalid3();
|
|
517
|
+
if (["running", "completed", "failed"].includes(item.status) && (item.attempts === 0 || item.retryDelaySeconds !== 0))
|
|
518
|
+
return invalid3();
|
|
519
|
+
if (item.attempts === 0 && item.retryDelaySeconds !== 0)
|
|
520
|
+
return invalid3();
|
|
521
|
+
if (item.status === "completed" && item.errorMessage !== "")
|
|
522
|
+
return invalid3();
|
|
523
|
+
if (item.status === "failed" || item.status === "dead_lettered" || item.status === "cancelled") {
|
|
524
|
+
terminalSteps++;
|
|
525
|
+
const expected = item.status === "cancelled" ? "cancelled" : "failed";
|
|
526
|
+
if (run.status !== expected || item.errorMessage === "" || item.errorMessage !== run.errorMessage)
|
|
527
|
+
return invalid3();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (activeSteps !== (active ? 1 : 0))
|
|
531
|
+
return invalid3();
|
|
532
|
+
if (terminalSteps !== (run.status === "failed" || run.status === "cancelled" ? 1 : 0))
|
|
533
|
+
return invalid3();
|
|
534
|
+
}
|
|
535
|
+
function decodeWorkflowRun(value, expectedRunId, allowIdempotent = false) {
|
|
536
|
+
if (value === null)
|
|
537
|
+
return null;
|
|
538
|
+
try {
|
|
539
|
+
const data = record3(queueJsonSnapshot(value));
|
|
540
|
+
const runId = uuid2(data.runId);
|
|
541
|
+
if (runId !== expectedRunId || typeof data.idempotent !== "boolean" || !allowIdempotent && data.idempotent || !Array.isArray(data.steps))
|
|
542
|
+
return invalid3();
|
|
543
|
+
const steps = data.steps.map(step);
|
|
544
|
+
for (const field of ["stepId", "stepKey", "queueMessageId"]) {
|
|
545
|
+
if (new Set(steps.map((item) => item[field])).size !== steps.length)
|
|
546
|
+
return invalid3();
|
|
547
|
+
}
|
|
548
|
+
validateStepSuccessors(steps);
|
|
549
|
+
const run = {
|
|
45
550
|
runId,
|
|
46
|
-
|
|
551
|
+
workflowName: key2(data.workflowName),
|
|
552
|
+
workflowVersion: text2(data.workflowVersion, 1, 80),
|
|
553
|
+
status: state(data.status, ["queued", "running", "completed", "failed", "cancelled"]),
|
|
554
|
+
input: record3(data.input),
|
|
555
|
+
output: record3(data.output),
|
|
556
|
+
errorMessage: text2(data.errorMessage),
|
|
557
|
+
rowVersion: id2(data.rowVersion),
|
|
558
|
+
createdAt: timestamp(data.createdAt),
|
|
559
|
+
startedAt: nullable(data.startedAt, timestamp),
|
|
560
|
+
completedAt: nullable(data.completedAt, timestamp),
|
|
561
|
+
updatedAt: timestamp(data.updatedAt),
|
|
562
|
+
idempotent: data.idempotent,
|
|
563
|
+
steps
|
|
564
|
+
};
|
|
565
|
+
validateLifecycle(run);
|
|
566
|
+
return run;
|
|
567
|
+
} catch {
|
|
568
|
+
return invalid3();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// src/workflow-json.ts
|
|
573
|
+
function workflowJsonObject(value) {
|
|
574
|
+
const captured = queueJsonSnapshot(value === undefined ? {} : value);
|
|
575
|
+
if (captured === null || typeof captured !== "object" || Array.isArray(captured))
|
|
576
|
+
throw new Error;
|
|
577
|
+
return captured;
|
|
578
|
+
}
|
|
579
|
+
function workflowJsonEqual(left, right) {
|
|
580
|
+
if (left === right)
|
|
581
|
+
return true;
|
|
582
|
+
if (left === null || right === null || typeof left !== "object" || typeof right !== "object")
|
|
583
|
+
return false;
|
|
584
|
+
if (Array.isArray(left)) {
|
|
585
|
+
return Array.isArray(right) && left.length === right.length && left.every((item, index) => workflowJsonEqual(item, right[index]));
|
|
586
|
+
}
|
|
587
|
+
if (Array.isArray(right))
|
|
588
|
+
return false;
|
|
589
|
+
const a = Object.entries(left);
|
|
590
|
+
const b = Object.entries(right);
|
|
591
|
+
const values = new Map(b);
|
|
592
|
+
return a.length === b.length && a.every(([name, value]) => values.has(name) && workflowJsonEqual(value, values.get(name)));
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// src/workflow-start.ts
|
|
596
|
+
class SupaCloudWorkflowStartError extends SupaCloudApiError {
|
|
597
|
+
mutationMayHaveApplied;
|
|
598
|
+
constructor(mutationMayHaveApplied = false) {
|
|
599
|
+
super("Workflow start could not be validated", 0, {
|
|
600
|
+
code: mutationMayHaveApplied ? "WORKFLOW_START_UNCONFIRMED" : "WORKFLOW_START_INPUT_INVALID",
|
|
601
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
47
602
|
});
|
|
603
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
604
|
+
this.name = "SupaCloudWorkflowStartError";
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function fail() {
|
|
608
|
+
throw new SupaCloudWorkflowStartError;
|
|
609
|
+
}
|
|
610
|
+
function normalized(value, max) {
|
|
611
|
+
if (typeof value !== "string")
|
|
612
|
+
return fail();
|
|
613
|
+
const result = value.replace(/^ +| +$/g, "");
|
|
614
|
+
let count = 0;
|
|
615
|
+
for (const character of result) {
|
|
616
|
+
const code = character.codePointAt(0);
|
|
617
|
+
if (++count > max || code === 0 || code !== undefined && code >= 55296 && code <= 57343)
|
|
618
|
+
return fail();
|
|
619
|
+
}
|
|
620
|
+
return count > 0 ? result : fail();
|
|
621
|
+
}
|
|
622
|
+
function key3(value) {
|
|
623
|
+
const result = normalized(value, 120);
|
|
624
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : fail();
|
|
625
|
+
}
|
|
626
|
+
function captureWorkflowStart(value) {
|
|
627
|
+
try {
|
|
628
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
629
|
+
return fail();
|
|
630
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
631
|
+
for (const name of Object.keys(fields)) {
|
|
632
|
+
const field = fields[name];
|
|
633
|
+
if (!["runId", "workflowName", "workflowVersion", "firstStepKey", "input", "maxAttempts"].includes(name) || !field || !field.enumerable || !("value" in field))
|
|
634
|
+
return fail();
|
|
635
|
+
}
|
|
636
|
+
const get = (name) => fields[name]?.value;
|
|
637
|
+
const input = queueJsonSnapshot(get("input") === undefined ? {} : get("input"));
|
|
638
|
+
if (input === null || typeof input !== "object" || Array.isArray(input))
|
|
639
|
+
return fail();
|
|
640
|
+
const maxAttempts = get("maxAttempts") === undefined ? 3 : get("maxAttempts");
|
|
641
|
+
if (typeof maxAttempts !== "number" || !Number.isSafeInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 100)
|
|
642
|
+
return fail();
|
|
643
|
+
return {
|
|
644
|
+
runId: captureWorkflowRunId(get("runId")),
|
|
645
|
+
workflowName: key3(get("workflowName")),
|
|
646
|
+
workflowVersion: normalized(get("workflowVersion"), 80),
|
|
647
|
+
firstStepKey: key3(get("firstStepKey")),
|
|
648
|
+
input,
|
|
649
|
+
maxAttempts
|
|
650
|
+
};
|
|
651
|
+
} catch {
|
|
652
|
+
return fail();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function decodeWorkflowStart(value, request) {
|
|
656
|
+
try {
|
|
657
|
+
const run = decodeWorkflowRun(value, request.runId, true);
|
|
658
|
+
const successors = new Set(run?.steps.map((step) => step.nextStepKey));
|
|
659
|
+
const first = run?.steps.find((step) => !successors.has(step.stepKey));
|
|
660
|
+
if (!run || !first || run.workflowName !== request.workflowName || run.workflowVersion !== request.workflowVersion || first.stepKey !== request.firstStepKey || first.maxAttempts !== request.maxAttempts || !workflowJsonEqual(run.input, request.input) || !workflowJsonEqual(first.input, request.input))
|
|
661
|
+
throw new Error;
|
|
662
|
+
if (!run.idempotent && (run.status !== "queued" || run.steps.length !== 1 || first.status !== "queued" || first.attempts !== 0 || run.rowVersion !== "1"))
|
|
663
|
+
throw new Error;
|
|
664
|
+
return run;
|
|
665
|
+
} catch {
|
|
666
|
+
throw new SupaCloudWorkflowStartError(true);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/workflow-cancel.ts
|
|
671
|
+
class SupaCloudWorkflowCancelError extends SupaCloudApiError {
|
|
672
|
+
mutationMayHaveApplied;
|
|
673
|
+
constructor(mutationMayHaveApplied = false) {
|
|
674
|
+
super("Workflow cancellation could not be validated", 0, {
|
|
675
|
+
code: mutationMayHaveApplied ? "WORKFLOW_CANCEL_UNCONFIRMED" : "WORKFLOW_CANCEL_INPUT_INVALID",
|
|
676
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
677
|
+
});
|
|
678
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
679
|
+
this.name = "SupaCloudWorkflowCancelError";
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function captureWorkflowCancel(runId, reason) {
|
|
683
|
+
try {
|
|
684
|
+
const capturedId = captureWorkflowRunId(runId);
|
|
685
|
+
if (typeof reason !== "string")
|
|
686
|
+
throw new Error;
|
|
687
|
+
const capturedReason = reason.replace(/^ +| +$/g, "");
|
|
688
|
+
let length = 0;
|
|
689
|
+
for (const character of capturedReason) {
|
|
690
|
+
const point = character.codePointAt(0);
|
|
691
|
+
if (++length > 4000 || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
692
|
+
throw new Error;
|
|
693
|
+
}
|
|
694
|
+
if (length === 0)
|
|
695
|
+
throw new Error;
|
|
696
|
+
return { runId: capturedId, reason: capturedReason };
|
|
697
|
+
} catch {
|
|
698
|
+
throw new SupaCloudWorkflowCancelError;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function decodeWorkflowCancel(value, request) {
|
|
702
|
+
try {
|
|
703
|
+
const run = decodeWorkflowRun(value, request.runId, true);
|
|
704
|
+
if (!run || run.status !== "cancelled" || run.errorMessage !== request.reason || run.completedAt === null)
|
|
705
|
+
throw new Error;
|
|
706
|
+
for (const step of run.steps) {
|
|
707
|
+
if (step.status === "queued" || step.status === "running" || step.status === "cancelled" && (step.errorMessage !== request.reason || step.completedAt === null)) {
|
|
708
|
+
throw new Error;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
return run;
|
|
712
|
+
} catch {
|
|
713
|
+
throw new SupaCloudWorkflowCancelError(true);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// src/workflow-attempt.ts
|
|
718
|
+
function workflowRequestFields(value, names) {
|
|
719
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
720
|
+
throw new Error;
|
|
721
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
722
|
+
const entries = [];
|
|
723
|
+
for (const name of Object.keys(fields)) {
|
|
724
|
+
const field = fields[name];
|
|
725
|
+
if (!names.includes(name) || !field || !field.enumerable || !("value" in field))
|
|
726
|
+
throw new Error;
|
|
727
|
+
entries.push([name, field.value]);
|
|
728
|
+
}
|
|
729
|
+
return Object.fromEntries(entries);
|
|
730
|
+
}
|
|
731
|
+
function captureWorkflowAttempt(fields) {
|
|
732
|
+
const { messageId, attempt } = fields;
|
|
733
|
+
if (typeof messageId !== "string" || typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 1 || attempt > 2147483647)
|
|
734
|
+
throw new Error;
|
|
735
|
+
return {
|
|
736
|
+
stepId: captureWorkflowRunId(fields.stepId),
|
|
737
|
+
messageId: queueMessageId(messageId),
|
|
738
|
+
attempt,
|
|
739
|
+
workerId: captureWorkflowClaimRequest({ workerId: fields.workerId }).workerId
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
function captureWorkflowErrorMessage(value) {
|
|
743
|
+
if (typeof value !== "string")
|
|
744
|
+
throw new Error;
|
|
745
|
+
const errorMessage = value.replace(/^ +| +$/g, "");
|
|
746
|
+
let length = 0;
|
|
747
|
+
for (const character of errorMessage) {
|
|
748
|
+
const point = character.codePointAt(0);
|
|
749
|
+
if (++length > 4000 || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
750
|
+
throw new Error;
|
|
751
|
+
}
|
|
752
|
+
if (length === 0)
|
|
753
|
+
throw new Error;
|
|
754
|
+
return errorMessage;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/workflow-complete.ts
|
|
758
|
+
class SupaCloudWorkflowCompleteError extends SupaCloudApiError {
|
|
759
|
+
mutationMayHaveApplied;
|
|
760
|
+
constructor(mutationMayHaveApplied = false) {
|
|
761
|
+
super("Workflow completion could not be validated", 0, {
|
|
762
|
+
code: mutationMayHaveApplied ? "WORKFLOW_COMPLETE_UNCONFIRMED" : "WORKFLOW_COMPLETE_INPUT_INVALID",
|
|
763
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
764
|
+
});
|
|
765
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
766
|
+
this.name = "SupaCloudWorkflowCompleteError";
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
function captureWorkflowComplete(value) {
|
|
770
|
+
try {
|
|
771
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "stepOutput", "runOutput"]);
|
|
772
|
+
return {
|
|
773
|
+
...captureWorkflowAttempt(fields),
|
|
774
|
+
stepOutput: workflowJsonObject(fields.stepOutput),
|
|
775
|
+
runOutput: workflowJsonObject(fields.runOutput)
|
|
776
|
+
};
|
|
777
|
+
} catch {
|
|
778
|
+
throw new SupaCloudWorkflowCompleteError;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function decodeWorkflowComplete(value, request) {
|
|
782
|
+
try {
|
|
783
|
+
const snapshot = queueJsonSnapshot(value);
|
|
784
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
785
|
+
throw new Error;
|
|
786
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
787
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
788
|
+
if (!run || !step || run.status !== "completed" || run.errorMessage !== "" || run.completedAt === null || step.status !== "completed" || step.queueMessageId !== request.messageId || step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.completedAt === null || step.nextStepKey !== null || step.errorMessage !== "" || !workflowJsonEqual(step.output, request.stepOutput) || !workflowJsonEqual(run.output, request.runOutput) || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
789
|
+
throw new Error;
|
|
790
|
+
return run;
|
|
791
|
+
} catch {
|
|
792
|
+
throw new SupaCloudWorkflowCompleteError(true);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// src/workflow-fail.ts
|
|
797
|
+
class SupaCloudWorkflowFailError extends SupaCloudApiError {
|
|
798
|
+
mutationMayHaveApplied;
|
|
799
|
+
constructor(mutationMayHaveApplied = false) {
|
|
800
|
+
super("Workflow failure transition could not be validated", 0, {
|
|
801
|
+
code: mutationMayHaveApplied ? "WORKFLOW_FAIL_UNCONFIRMED" : "WORKFLOW_FAIL_INPUT_INVALID",
|
|
802
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
803
|
+
});
|
|
804
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
805
|
+
this.name = "SupaCloudWorkflowFailError";
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function captureWorkflowFail(value) {
|
|
809
|
+
try {
|
|
810
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "errorMessage"]);
|
|
811
|
+
return { ...captureWorkflowAttempt(fields), errorMessage: captureWorkflowErrorMessage(fields.errorMessage) };
|
|
812
|
+
} catch {
|
|
813
|
+
throw new SupaCloudWorkflowFailError;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function decodeWorkflowFail(value, request) {
|
|
817
|
+
try {
|
|
818
|
+
const snapshot = queueJsonSnapshot(value);
|
|
819
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
820
|
+
throw new Error;
|
|
821
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
822
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
823
|
+
if (!run || !step || run.status !== "failed" || run.errorMessage !== request.errorMessage || run.completedAt === null || step.status !== "failed" || step.queueMessageId !== request.messageId || step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.completedAt === null || step.errorMessage !== request.errorMessage || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
824
|
+
throw new Error;
|
|
825
|
+
return run;
|
|
826
|
+
} catch {
|
|
827
|
+
throw new SupaCloudWorkflowFailError(true);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// src/workflow-advance.ts
|
|
832
|
+
class SupaCloudWorkflowAdvanceError extends SupaCloudApiError {
|
|
833
|
+
mutationMayHaveApplied;
|
|
834
|
+
constructor(mutationMayHaveApplied = false) {
|
|
835
|
+
super("Workflow advancement could not be validated", 0, {
|
|
836
|
+
code: mutationMayHaveApplied ? "WORKFLOW_ADVANCE_UNCONFIRMED" : "WORKFLOW_ADVANCE_INPUT_INVALID",
|
|
837
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
838
|
+
});
|
|
839
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
840
|
+
this.name = "SupaCloudWorkflowAdvanceError";
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
function captureWorkflowAdvance(value) {
|
|
844
|
+
try {
|
|
845
|
+
const fields = workflowRequestFields(value, [
|
|
846
|
+
"stepId",
|
|
847
|
+
"messageId",
|
|
848
|
+
"attempt",
|
|
849
|
+
"workerId",
|
|
850
|
+
"output",
|
|
851
|
+
"nextStepKey",
|
|
852
|
+
"nextInput",
|
|
853
|
+
"nextMaxAttempts"
|
|
854
|
+
]);
|
|
855
|
+
if (typeof fields.nextStepKey !== "string")
|
|
856
|
+
throw new Error;
|
|
857
|
+
const nextStepKey = fields.nextStepKey.replace(/^ +| +$/g, "");
|
|
858
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(nextStepKey))
|
|
859
|
+
throw new Error;
|
|
860
|
+
const nextMaxAttempts = fields.nextMaxAttempts === undefined ? 3 : fields.nextMaxAttempts;
|
|
861
|
+
if (typeof nextMaxAttempts !== "number" || !Number.isSafeInteger(nextMaxAttempts) || nextMaxAttempts < 1 || nextMaxAttempts > 100)
|
|
862
|
+
throw new Error;
|
|
863
|
+
return {
|
|
864
|
+
...captureWorkflowAttempt(fields),
|
|
865
|
+
nextStepKey,
|
|
866
|
+
nextMaxAttempts,
|
|
867
|
+
output: workflowJsonObject(fields.output),
|
|
868
|
+
nextInput: workflowJsonObject(fields.nextInput)
|
|
869
|
+
};
|
|
870
|
+
} catch {
|
|
871
|
+
throw new SupaCloudWorkflowAdvanceError;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
function decodeWorkflowAdvance(value, request) {
|
|
875
|
+
try {
|
|
876
|
+
const snapshot = queueJsonSnapshot(value);
|
|
877
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
878
|
+
throw new Error;
|
|
879
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
880
|
+
const current = run?.steps.find((step) => step.stepId === request.stepId);
|
|
881
|
+
const next = run?.steps.find((step) => step.stepKey === request.nextStepKey);
|
|
882
|
+
if (!run || !current || !next || current.stepId === next.stepId || current.status !== "completed" || current.queueMessageId !== request.messageId || current.attempts !== request.attempt || current.claimedBy !== request.workerId || current.completedAt === null || current.errorMessage !== "" || current.nextStepKey !== request.nextStepKey || next.maxAttempts !== request.nextMaxAttempts || !workflowJsonEqual(current.output, request.output) || !workflowJsonEqual(next.input, request.nextInput)) {
|
|
883
|
+
throw new Error;
|
|
884
|
+
}
|
|
885
|
+
if (!run.idempotent && (run.status !== "running" || next.status !== "queued" || next.attempts !== 0))
|
|
886
|
+
throw new Error;
|
|
887
|
+
return run;
|
|
888
|
+
} catch {
|
|
889
|
+
throw new SupaCloudWorkflowAdvanceError(true);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// src/workflow-retry.ts
|
|
894
|
+
class SupaCloudWorkflowRetryError extends SupaCloudApiError {
|
|
895
|
+
mutationMayHaveApplied;
|
|
896
|
+
constructor(mutationMayHaveApplied = false) {
|
|
897
|
+
super("Workflow retry could not be validated", 0, {
|
|
898
|
+
code: mutationMayHaveApplied ? "WORKFLOW_RETRY_UNCONFIRMED" : "WORKFLOW_RETRY_INPUT_INVALID",
|
|
899
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
900
|
+
});
|
|
901
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
902
|
+
this.name = "SupaCloudWorkflowRetryError";
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
function captureWorkflowRetry(value) {
|
|
906
|
+
try {
|
|
907
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "errorMessage", "delaySeconds"]);
|
|
908
|
+
const delaySeconds = fields.delaySeconds === undefined ? 0 : fields.delaySeconds;
|
|
909
|
+
if (typeof delaySeconds !== "number" || !Number.isSafeInteger(delaySeconds) || delaySeconds < 0 || delaySeconds > 86400)
|
|
910
|
+
throw new Error;
|
|
911
|
+
return {
|
|
912
|
+
...captureWorkflowAttempt(fields),
|
|
913
|
+
errorMessage: captureWorkflowErrorMessage(fields.errorMessage),
|
|
914
|
+
delaySeconds
|
|
915
|
+
};
|
|
916
|
+
} catch {
|
|
917
|
+
throw new SupaCloudWorkflowRetryError;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function decodeWorkflowRetry(value, request) {
|
|
921
|
+
try {
|
|
922
|
+
const snapshot = queueJsonSnapshot(value);
|
|
923
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
924
|
+
throw new Error;
|
|
925
|
+
const receipt = snapshot.retryReceipt;
|
|
926
|
+
if (receipt === null || typeof receipt !== "object" || Array.isArray(receipt) || receipt.operation !== "retry" || receipt.stepId !== request.stepId || receipt.messageId !== request.messageId || receipt.attempt !== request.attempt || receipt.workerId !== request.workerId || receipt.errorMessage !== request.errorMessage || receipt.delaySeconds !== request.delaySeconds)
|
|
927
|
+
throw new Error;
|
|
928
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
929
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
930
|
+
if (!run || !step || step.queueMessageId !== request.messageId || step.attempts < request.attempt)
|
|
931
|
+
throw new Error;
|
|
932
|
+
if (run.idempotent)
|
|
933
|
+
return run;
|
|
934
|
+
if (step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.errorMessage !== request.errorMessage)
|
|
935
|
+
throw new Error;
|
|
936
|
+
if (request.attempt >= step.maxAttempts) {
|
|
937
|
+
if (step.status !== "dead_lettered" || run.status !== "failed" || run.errorMessage !== request.errorMessage || step.completedAt === null || run.completedAt === null || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
938
|
+
throw new Error;
|
|
939
|
+
} else if (step.status !== "queued" || run.status !== "running" || step.completedAt !== null || step.retryDelaySeconds !== request.delaySeconds)
|
|
940
|
+
throw new Error;
|
|
941
|
+
return run;
|
|
942
|
+
} catch {
|
|
943
|
+
throw new SupaCloudWorkflowRetryError(true);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// src/workflow-events.ts
|
|
948
|
+
class SupaCloudWorkflowEventsError extends SupaCloudApiError {
|
|
949
|
+
mutationMayHaveApplied = false;
|
|
950
|
+
constructor(input = false) {
|
|
951
|
+
super("Workflow events could not be validated", 0, {
|
|
952
|
+
code: input ? "WORKFLOW_EVENTS_INPUT_INVALID" : "WORKFLOW_EVENTS_INVALID",
|
|
953
|
+
mutation_may_have_applied: false
|
|
954
|
+
});
|
|
955
|
+
this.name = "SupaCloudWorkflowEventsError";
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
function captureWorkflowEvents(runId, options) {
|
|
959
|
+
try {
|
|
960
|
+
const fields = workflowRequestFields(options, ["afterEventId", "limit"]);
|
|
961
|
+
const afterEventId = fields.afterEventId === undefined ? "0" : fields.afterEventId;
|
|
962
|
+
const limit = fields.limit === undefined ? 100 : fields.limit;
|
|
963
|
+
if (typeof afterEventId !== "string" || afterEventId !== "0" && queueMessageId(afterEventId) !== afterEventId || typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
964
|
+
throw new Error;
|
|
965
|
+
return { runId: captureWorkflowRunId(runId), afterEventId, limit };
|
|
966
|
+
} catch {
|
|
967
|
+
throw new SupaCloudWorkflowEventsError(true);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
function decodeWorkflowEvents(value, request) {
|
|
971
|
+
try {
|
|
972
|
+
const snapshot = queueJsonSnapshot(value);
|
|
973
|
+
if (!Array.isArray(snapshot) || snapshot.length > request.limit)
|
|
974
|
+
throw new Error;
|
|
975
|
+
let previous = BigInt(request.afterEventId);
|
|
976
|
+
return snapshot.map((item) => {
|
|
977
|
+
if (item === null || typeof item !== "object" || Array.isArray(item))
|
|
978
|
+
throw new Error;
|
|
979
|
+
const { eventId, runId, stepId, eventType, attempt, details, createdAt } = item;
|
|
980
|
+
if (typeof eventId !== "string" || queueMessageId(eventId) !== eventId || BigInt(eventId) <= previous || runId !== request.runId || stepId !== null && (typeof stepId !== "string" || captureWorkflowRunId(stepId) !== stepId) || typeof eventType !== "string" || ![
|
|
981
|
+
"run_started",
|
|
982
|
+
"step_claimed",
|
|
983
|
+
"step_retried",
|
|
984
|
+
"step_completed",
|
|
985
|
+
"step_failed",
|
|
986
|
+
"step_dead_lettered",
|
|
987
|
+
"run_completed",
|
|
988
|
+
"run_cancelled"
|
|
989
|
+
].includes(eventType) || attempt !== null && (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 1 || attempt > 2147483647) || details === null || typeof details !== "object" || Array.isArray(details) || !isWorkflowTimestamp(createdAt))
|
|
990
|
+
throw new Error;
|
|
991
|
+
previous = BigInt(eventId);
|
|
992
|
+
return { eventId, runId, stepId, eventType, attempt, details, createdAt };
|
|
993
|
+
});
|
|
994
|
+
} catch {
|
|
995
|
+
throw new SupaCloudWorkflowEventsError;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/workflows.ts
|
|
1000
|
+
class SupaCloudWorkflowsClient {
|
|
1001
|
+
supabase;
|
|
1002
|
+
constructor(supabase) {
|
|
1003
|
+
this.supabase = supabase;
|
|
1004
|
+
}
|
|
1005
|
+
async start(request) {
|
|
1006
|
+
const captured = captureWorkflowStart(request);
|
|
1007
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_start", captured, () => new SupaCloudWorkflowStartError(true));
|
|
1008
|
+
return decodeWorkflowStart(result, captured);
|
|
1009
|
+
}
|
|
1010
|
+
async claim(request) {
|
|
1011
|
+
const captured = captureWorkflowClaimRequest(request);
|
|
1012
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_claim", captured, () => new SupaCloudWorkflowClaimError);
|
|
1013
|
+
return decodeWorkflowClaim(result, captured.workerId);
|
|
1014
|
+
}
|
|
1015
|
+
async advance(request) {
|
|
1016
|
+
const captured = captureWorkflowAdvance(request);
|
|
1017
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_advance", captured, () => new SupaCloudWorkflowAdvanceError(true));
|
|
1018
|
+
return decodeWorkflowAdvance(result, captured);
|
|
1019
|
+
}
|
|
1020
|
+
async complete(request) {
|
|
1021
|
+
const captured = captureWorkflowComplete(request);
|
|
1022
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_complete", captured, () => new SupaCloudWorkflowCompleteError(true));
|
|
1023
|
+
return decodeWorkflowComplete(result, captured);
|
|
1024
|
+
}
|
|
1025
|
+
async retry(request) {
|
|
1026
|
+
const captured = captureWorkflowRetry(request);
|
|
1027
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_retry", captured, () => new SupaCloudWorkflowRetryError(true));
|
|
1028
|
+
return decodeWorkflowRetry(result, captured);
|
|
1029
|
+
}
|
|
1030
|
+
async fail(request) {
|
|
1031
|
+
const captured = captureWorkflowFail(request);
|
|
1032
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_fail", captured, () => new SupaCloudWorkflowFailError(true));
|
|
1033
|
+
return decodeWorkflowFail(result, captured);
|
|
1034
|
+
}
|
|
1035
|
+
async cancel(runId, reason) {
|
|
1036
|
+
const captured = captureWorkflowCancel(runId, reason);
|
|
1037
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_cancel", captured, () => new SupaCloudWorkflowCancelError(true));
|
|
1038
|
+
return decodeWorkflowCancel(result, captured);
|
|
1039
|
+
}
|
|
1040
|
+
async get(runId) {
|
|
1041
|
+
const captured = captureWorkflowRunId(runId);
|
|
1042
|
+
const result = await invokeWorkflowRead(this.supabase, "supacloud_workflow_get", { runId: captured }, () => new SupaCloudWorkflowReadError);
|
|
1043
|
+
return decodeWorkflowRun(result, captured);
|
|
1044
|
+
}
|
|
1045
|
+
async events(runId, options = {}) {
|
|
1046
|
+
const captured = captureWorkflowEvents(runId, options);
|
|
1047
|
+
const result = await invokeWorkflowRead(this.supabase, "supacloud_workflow_events", captured, () => new SupaCloudWorkflowEventsError);
|
|
1048
|
+
return decodeWorkflowEvents(result, captured);
|
|
48
1049
|
}
|
|
49
1050
|
}
|
|
50
1051
|
|
|
51
1052
|
// src/commands.ts
|
|
1053
|
+
import { decodeCommandStatus } from "@supacloud/contracts";
|
|
1054
|
+
class SupaCloudCommandReadError extends SupaCloudApiError {
|
|
1055
|
+
mutationMayHaveApplied = false;
|
|
1056
|
+
constructor() {
|
|
1057
|
+
super("Command read could not be validated", 0, {
|
|
1058
|
+
code: "COMMAND_READ_INVALID",
|
|
1059
|
+
mutation_may_have_applied: false
|
|
1060
|
+
});
|
|
1061
|
+
this.name = "SupaCloudCommandReadError";
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
class SupaCloudCommandSubmitError extends SupaCloudApiError {
|
|
1066
|
+
mutationMayHaveApplied;
|
|
1067
|
+
constructor(mutationMayHaveApplied = true) {
|
|
1068
|
+
super("Command submission could not be validated", 0, {
|
|
1069
|
+
code: "COMMAND_SUBMIT_UNCONFIRMED",
|
|
1070
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
1071
|
+
});
|
|
1072
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1073
|
+
this.name = "SupaCloudCommandSubmitError";
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
52
1077
|
class SupaCloudCommandsClient {
|
|
53
1078
|
supabase;
|
|
54
1079
|
constructor(supabase) {
|
|
55
1080
|
this.supabase = supabase;
|
|
56
1081
|
}
|
|
57
|
-
submit(request) {
|
|
58
|
-
|
|
1082
|
+
async submit(request) {
|
|
1083
|
+
const raw = await this.request("supacloud_command_submit", request, () => new SupaCloudCommandSubmitError);
|
|
1084
|
+
const status = decodeCommandStatus(raw);
|
|
1085
|
+
if (status.commandId !== request.commandId.toLowerCase())
|
|
1086
|
+
throw new TypeError("Invalid command submission");
|
|
1087
|
+
return status;
|
|
1088
|
+
}
|
|
1089
|
+
async get(lookup) {
|
|
1090
|
+
const request = typeof lookup === "string" ? { commandId: lookup } : { ...lookup };
|
|
1091
|
+
const raw = await this.request("supacloud_command_get", request, () => new SupaCloudCommandReadError);
|
|
1092
|
+
if (raw === null)
|
|
1093
|
+
return null;
|
|
1094
|
+
const status = decodeCommandStatus(raw);
|
|
1095
|
+
if ("commandId" in request) {
|
|
1096
|
+
if (status.commandId !== request.commandId.toLowerCase())
|
|
1097
|
+
throw new TypeError("Mismatched command status");
|
|
1098
|
+
} else {
|
|
1099
|
+
if (status.kind !== "execution")
|
|
1100
|
+
throw new TypeError("Missing command execution");
|
|
1101
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
1102
|
+
if (status.execution[key] !== request[key])
|
|
1103
|
+
throw new TypeError("Mismatched command reference");
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
return status;
|
|
1107
|
+
}
|
|
1108
|
+
async request(functionName, request, failure) {
|
|
1109
|
+
let result;
|
|
1110
|
+
try {
|
|
1111
|
+
result = await this.supabase.rpc(functionName, { request });
|
|
1112
|
+
} catch {
|
|
1113
|
+
throw failure();
|
|
1114
|
+
}
|
|
1115
|
+
if (result.error) {
|
|
1116
|
+
const error = result.error;
|
|
1117
|
+
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : null;
|
|
1118
|
+
if (result.status === 0 || result.status === undefined && !code)
|
|
1119
|
+
throw failure();
|
|
1120
|
+
throw error;
|
|
1121
|
+
}
|
|
1122
|
+
return result.data;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// src/artifact-read.ts
|
|
1127
|
+
class SupaCloudArtifactReadError extends SupaCloudApiError {
|
|
1128
|
+
mutationMayHaveApplied = false;
|
|
1129
|
+
constructor(input = false) {
|
|
1130
|
+
super("Artifact read could not be validated", 0, {
|
|
1131
|
+
code: input ? "ARTIFACT_READ_INPUT_INVALID" : "ARTIFACT_READ_INVALID",
|
|
1132
|
+
mutation_may_have_applied: false
|
|
1133
|
+
});
|
|
1134
|
+
this.name = "SupaCloudArtifactReadError";
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
function uuid3(value) {
|
|
1138
|
+
if (typeof value !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value))
|
|
1139
|
+
throw new Error;
|
|
1140
|
+
return value;
|
|
1141
|
+
}
|
|
1142
|
+
function captureArtifactId(value) {
|
|
1143
|
+
try {
|
|
1144
|
+
if (typeof value !== "string")
|
|
1145
|
+
throw new Error;
|
|
1146
|
+
return uuid3(value.toLowerCase());
|
|
1147
|
+
} catch {
|
|
1148
|
+
throw new SupaCloudArtifactReadError(true);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
function record4(value) {
|
|
1152
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
1153
|
+
throw new Error;
|
|
1154
|
+
return value;
|
|
1155
|
+
}
|
|
1156
|
+
function artifactText(value, min = 0, max = 1048576) {
|
|
1157
|
+
if (typeof value !== "string")
|
|
1158
|
+
throw new Error;
|
|
1159
|
+
let count = 0;
|
|
1160
|
+
for (const character of value) {
|
|
1161
|
+
const point = character.codePointAt(0);
|
|
1162
|
+
if (++count > max || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
1163
|
+
throw new Error;
|
|
1164
|
+
}
|
|
1165
|
+
if (count < min)
|
|
1166
|
+
throw new Error;
|
|
1167
|
+
return value;
|
|
1168
|
+
}
|
|
1169
|
+
function artifactKey(value) {
|
|
1170
|
+
const result = artifactText(value, 1, 120);
|
|
1171
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result))
|
|
1172
|
+
throw new Error;
|
|
1173
|
+
return result;
|
|
1174
|
+
}
|
|
1175
|
+
function timestamp2(value) {
|
|
1176
|
+
if (!isWorkflowTimestamp(value))
|
|
1177
|
+
throw new Error;
|
|
1178
|
+
return value;
|
|
1179
|
+
}
|
|
1180
|
+
function artifactTimestampMicros(value) {
|
|
1181
|
+
timestamp2(value);
|
|
1182
|
+
const fraction = /\.(\d{1,6})/.exec(value)?.[1] ?? "";
|
|
1183
|
+
return BigInt(Date.parse(value)) * 1000n + BigInt(fraction.padEnd(6, "0").slice(3));
|
|
1184
|
+
}
|
|
1185
|
+
function artifactSize(value) {
|
|
1186
|
+
if (typeof value !== "string" || !/^(?:0|[1-9][0-9]{0,18})$/.test(value) || BigInt(value) > 9223372036854775807n)
|
|
1187
|
+
throw new Error;
|
|
1188
|
+
return value;
|
|
1189
|
+
}
|
|
1190
|
+
function artifactPath(value) {
|
|
1191
|
+
const result = artifactText(value, 1);
|
|
1192
|
+
if (result.startsWith("/") || result.includes("\\") || /(^|\/)\.\.?(\/|$)/.test(result))
|
|
1193
|
+
throw new Error;
|
|
1194
|
+
return result;
|
|
1195
|
+
}
|
|
1196
|
+
function decodeArtifactRead(value, artifactId, allowIdempotent = false) {
|
|
1197
|
+
if (value === null)
|
|
1198
|
+
return null;
|
|
1199
|
+
try {
|
|
1200
|
+
const data = record4(queueJsonSnapshot(value));
|
|
1201
|
+
if (uuid3(data.artifactId) !== artifactId || typeof data.idempotent !== "boolean" || !allowIdempotent && data.idempotent)
|
|
1202
|
+
throw new Error;
|
|
1203
|
+
const sizeBytes = artifactSize(data.sizeBytes);
|
|
1204
|
+
const sha256 = data.sha256;
|
|
1205
|
+
if (typeof sha256 !== "string" || !/^[0-9a-f]{64}$/.test(sha256))
|
|
1206
|
+
throw new Error;
|
|
1207
|
+
const objectPath = artifactPath(data.objectPath);
|
|
1208
|
+
const createdAt = timestamp2(data.createdAt);
|
|
1209
|
+
const retentionUntil = data.retentionUntil === null ? null : timestamp2(data.retentionUntil);
|
|
1210
|
+
if (retentionUntil !== null && artifactTimestampMicros(retentionUntil) < artifactTimestampMicros(createdAt))
|
|
1211
|
+
throw new Error;
|
|
1212
|
+
if (!Array.isArray(data.parents))
|
|
1213
|
+
throw new Error;
|
|
1214
|
+
const seen = new Set;
|
|
1215
|
+
const parents = data.parents.map((value) => {
|
|
1216
|
+
const parent = record4(value);
|
|
1217
|
+
const parentId = uuid3(parent.artifactId), relationType = artifactKey(parent.relationType);
|
|
1218
|
+
const identity = `${parentId}:${relationType}`;
|
|
1219
|
+
if (parentId === artifactId || seen.has(identity))
|
|
1220
|
+
throw new Error;
|
|
1221
|
+
seen.add(identity);
|
|
1222
|
+
return {
|
|
1223
|
+
artifactId: parentId,
|
|
1224
|
+
relationType,
|
|
1225
|
+
metadata: record4(parent.metadata),
|
|
1226
|
+
createdAt: timestamp2(parent.createdAt)
|
|
1227
|
+
};
|
|
1228
|
+
});
|
|
1229
|
+
return {
|
|
1230
|
+
artifactId,
|
|
1231
|
+
bucketId: artifactText(data.bucketId, 1),
|
|
1232
|
+
objectPath,
|
|
1233
|
+
objectVersion: artifactText(data.objectVersion),
|
|
1234
|
+
artifactType: artifactKey(data.artifactType),
|
|
1235
|
+
sha256,
|
|
1236
|
+
sizeBytes,
|
|
1237
|
+
mimeType: artifactText(data.mimeType, 1, 255),
|
|
1238
|
+
metadata: record4(data.metadata),
|
|
1239
|
+
retentionUntil,
|
|
1240
|
+
createdBy: data.createdBy === null ? null : uuid3(data.createdBy),
|
|
1241
|
+
createdAt,
|
|
1242
|
+
idempotent: data.idempotent,
|
|
1243
|
+
parents
|
|
1244
|
+
};
|
|
1245
|
+
} catch {
|
|
1246
|
+
throw new SupaCloudArtifactReadError;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// src/artifact-register.ts
|
|
1251
|
+
class SupaCloudArtifactRegisterError extends SupaCloudApiError {
|
|
1252
|
+
mutationMayHaveApplied;
|
|
1253
|
+
constructor(mutationMayHaveApplied = false) {
|
|
1254
|
+
super("Artifact registration could not be validated", 0, {
|
|
1255
|
+
code: mutationMayHaveApplied ? "ARTIFACT_REGISTER_UNCONFIRMED" : "ARTIFACT_REGISTER_INPUT_INVALID",
|
|
1256
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
1257
|
+
});
|
|
1258
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1259
|
+
this.name = "SupaCloudArtifactRegisterError";
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
function trim(value) {
|
|
1263
|
+
return artifactText(value).replace(/^ +| +$/g, "");
|
|
1264
|
+
}
|
|
1265
|
+
function captureArtifactRegister(value) {
|
|
1266
|
+
try {
|
|
1267
|
+
const fields = workflowRequestFields(value, [
|
|
1268
|
+
"artifactId",
|
|
1269
|
+
"bucketId",
|
|
1270
|
+
"objectPath",
|
|
1271
|
+
"artifactType",
|
|
1272
|
+
"sha256",
|
|
1273
|
+
"sizeBytes",
|
|
1274
|
+
"mimeType",
|
|
1275
|
+
"metadata",
|
|
1276
|
+
"retentionUntil",
|
|
1277
|
+
"createdBy"
|
|
1278
|
+
]);
|
|
1279
|
+
let size = fields.sizeBytes;
|
|
1280
|
+
if (typeof size === "number") {
|
|
1281
|
+
if (!Number.isSafeInteger(size) || size < 0)
|
|
1282
|
+
throw new Error;
|
|
1283
|
+
size = String(size);
|
|
1284
|
+
}
|
|
1285
|
+
const sha256 = trim(fields.sha256).toLowerCase();
|
|
1286
|
+
if (!/^[0-9a-f]{64}$/.test(sha256))
|
|
1287
|
+
throw new Error;
|
|
1288
|
+
const retentionUntil = fields.retentionUntil === undefined ? null : artifactText(fields.retentionUntil, 1, 40);
|
|
1289
|
+
if (retentionUntil !== null)
|
|
1290
|
+
artifactTimestampMicros(retentionUntil);
|
|
1291
|
+
return {
|
|
1292
|
+
artifactId: captureArtifactId(fields.artifactId),
|
|
1293
|
+
bucketId: artifactText(trim(fields.bucketId), 1),
|
|
1294
|
+
objectPath: artifactPath(trim(fields.objectPath)),
|
|
1295
|
+
artifactType: artifactKey(trim(fields.artifactType)),
|
|
1296
|
+
sha256,
|
|
1297
|
+
sizeBytes: artifactSize(size),
|
|
1298
|
+
mimeType: artifactText(trim(fields.mimeType).toLowerCase(), 1, 255),
|
|
1299
|
+
metadata: workflowJsonObject(fields.metadata),
|
|
1300
|
+
retentionUntil,
|
|
1301
|
+
createdBy: fields.createdBy === undefined ? null : captureArtifactId(fields.createdBy)
|
|
1302
|
+
};
|
|
1303
|
+
} catch {
|
|
1304
|
+
throw new SupaCloudArtifactRegisterError;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
function decodeArtifactRegister(value, request) {
|
|
1308
|
+
try {
|
|
1309
|
+
const receipt = decodeArtifactRead(value, request.artifactId, true);
|
|
1310
|
+
if (!receipt || receipt.bucketId !== request.bucketId || receipt.objectPath !== request.objectPath || receipt.artifactType !== request.artifactType || receipt.sha256 !== request.sha256 || receipt.sizeBytes !== request.sizeBytes || receipt.mimeType !== request.mimeType || receipt.createdBy !== request.createdBy || !workflowJsonEqual(receipt.metadata, request.metadata))
|
|
1311
|
+
throw new Error;
|
|
1312
|
+
if (request.retentionUntil === null ? receipt.retentionUntil !== null : receipt.retentionUntil === null || artifactTimestampMicros(receipt.retentionUntil) !== artifactTimestampMicros(request.retentionUntil))
|
|
1313
|
+
throw new Error;
|
|
1314
|
+
if (!receipt.idempotent && receipt.parents.length !== 0)
|
|
1315
|
+
throw new Error;
|
|
1316
|
+
return receipt;
|
|
1317
|
+
} catch {
|
|
1318
|
+
throw new SupaCloudArtifactRegisterError(true);
|
|
59
1319
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// src/artifact-rpc.ts
|
|
1323
|
+
async function invokeArtifactRpc(supabase, name, request, failure) {
|
|
1324
|
+
const controller = new AbortController;
|
|
1325
|
+
let timer;
|
|
1326
|
+
const deadline = new Promise((_, reject) => {
|
|
1327
|
+
timer = setTimeout(() => {
|
|
1328
|
+
reject(failure());
|
|
1329
|
+
controller.abort();
|
|
1330
|
+
}, 15000);
|
|
1331
|
+
});
|
|
1332
|
+
let result;
|
|
1333
|
+
try {
|
|
1334
|
+
const pending = supabase.rpc(name, { request }).retry(false).abortSignal(controller.signal);
|
|
1335
|
+
result = await Promise.race([pending, deadline]);
|
|
1336
|
+
} catch {
|
|
1337
|
+
throw failure();
|
|
1338
|
+
} finally {
|
|
1339
|
+
clearTimeout(timer);
|
|
1340
|
+
}
|
|
1341
|
+
if (result.error && result.status >= 400 && result.status < 500)
|
|
1342
|
+
throw result.error;
|
|
1343
|
+
if (result.error || result.status !== 200)
|
|
1344
|
+
throw failure();
|
|
1345
|
+
return result.data;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// src/artifact-link.ts
|
|
1349
|
+
class SupaCloudArtifactLinkError extends SupaCloudApiError {
|
|
1350
|
+
mutationMayHaveApplied;
|
|
1351
|
+
constructor(mutationMayHaveApplied = false) {
|
|
1352
|
+
super("Artifact link could not be validated", 0, {
|
|
1353
|
+
code: mutationMayHaveApplied ? "ARTIFACT_LINK_UNCONFIRMED" : "ARTIFACT_LINK_INPUT_INVALID",
|
|
1354
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
63
1355
|
});
|
|
1356
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1357
|
+
this.name = "SupaCloudArtifactLinkError";
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
function captureArtifactLink(value) {
|
|
1361
|
+
try {
|
|
1362
|
+
const fields = workflowRequestFields(value, ["parentArtifactId", "childArtifactId", "relationType", "metadata"]);
|
|
1363
|
+
const parentArtifactId = captureArtifactId(fields.parentArtifactId);
|
|
1364
|
+
const childArtifactId = captureArtifactId(fields.childArtifactId);
|
|
1365
|
+
if (parentArtifactId === childArtifactId)
|
|
1366
|
+
throw new Error;
|
|
1367
|
+
return {
|
|
1368
|
+
parentArtifactId,
|
|
1369
|
+
childArtifactId,
|
|
1370
|
+
relationType: artifactKey(artifactText(fields.relationType).replace(/^ +| +$/g, "")),
|
|
1371
|
+
metadata: workflowJsonObject(fields.metadata)
|
|
1372
|
+
};
|
|
1373
|
+
} catch {
|
|
1374
|
+
throw new SupaCloudArtifactLinkError;
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
function decodeArtifactLink(value, request) {
|
|
1378
|
+
try {
|
|
1379
|
+
const receipt = decodeArtifactRead(value, request.childArtifactId, true);
|
|
1380
|
+
const edge = receipt?.parents.find((parent) => parent.artifactId === request.parentArtifactId && parent.relationType === request.relationType);
|
|
1381
|
+
if (!receipt || !edge || !workflowJsonEqual(edge.metadata, request.metadata))
|
|
1382
|
+
throw new Error;
|
|
1383
|
+
return receipt;
|
|
1384
|
+
} catch {
|
|
1385
|
+
throw new SupaCloudArtifactLinkError(true);
|
|
64
1386
|
}
|
|
65
1387
|
}
|
|
66
1388
|
|
|
@@ -70,19 +1392,922 @@ class SupaCloudArtifactsClient {
|
|
|
70
1392
|
constructor(supabase) {
|
|
71
1393
|
this.supabase = supabase;
|
|
72
1394
|
}
|
|
73
|
-
register(request) {
|
|
74
|
-
|
|
1395
|
+
async register(request) {
|
|
1396
|
+
const captured = captureArtifactRegister(request);
|
|
1397
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_register", captured, () => new SupaCloudArtifactRegisterError(true));
|
|
1398
|
+
return decodeArtifactRegister(result, captured);
|
|
1399
|
+
}
|
|
1400
|
+
async get(artifactId) {
|
|
1401
|
+
const captured = captureArtifactId(artifactId);
|
|
1402
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_get", {
|
|
1403
|
+
artifactId: captured
|
|
1404
|
+
}, () => new SupaCloudArtifactReadError);
|
|
1405
|
+
return decodeArtifactRead(result, captured);
|
|
75
1406
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
1407
|
+
async link(request) {
|
|
1408
|
+
const captured = captureArtifactLink(request);
|
|
1409
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_link", captured, () => new SupaCloudArtifactLinkError(true));
|
|
1410
|
+
return decodeArtifactLink(result, captured);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// src/bounded-rpc-fetch.ts
|
|
1415
|
+
var maxBytes = 1024 * 1024;
|
|
1416
|
+
function createBoundedRpcFetch(path, failure, fetchImpl = globalThis.fetch.bind(globalThis)) {
|
|
1417
|
+
return async (input, init) => {
|
|
1418
|
+
const url = new URL(input instanceof Request ? input.url : input.toString());
|
|
1419
|
+
if (!path.test(url.pathname))
|
|
1420
|
+
return fetchImpl(input, init);
|
|
1421
|
+
const request = new Request(input, init);
|
|
1422
|
+
if (request.signal.aborted)
|
|
1423
|
+
throw failure();
|
|
1424
|
+
const controller = new AbortController;
|
|
1425
|
+
const cancel = () => controller.abort();
|
|
1426
|
+
request.signal.addEventListener("abort", cancel, { once: true });
|
|
1427
|
+
let reader;
|
|
1428
|
+
const abortRead = () => {
|
|
1429
|
+
reader?.cancel().catch(() => {});
|
|
1430
|
+
};
|
|
1431
|
+
let rejectAbort = () => {};
|
|
1432
|
+
const aborted = new Promise((_, reject) => {
|
|
1433
|
+
rejectAbort = () => {
|
|
1434
|
+
abortRead();
|
|
1435
|
+
reject(failure());
|
|
1436
|
+
};
|
|
1437
|
+
controller.signal.addEventListener("abort", rejectAbort, { once: true });
|
|
79
1438
|
});
|
|
1439
|
+
const timer = setTimeout(cancel, 15000);
|
|
1440
|
+
const read = async () => {
|
|
1441
|
+
const response = await fetchImpl(new Request(request, {
|
|
1442
|
+
signal: controller.signal,
|
|
1443
|
+
redirect: "error",
|
|
1444
|
+
cache: "no-store"
|
|
1445
|
+
}));
|
|
1446
|
+
if (controller.signal.aborted) {
|
|
1447
|
+
response.body?.cancel().catch(() => {});
|
|
1448
|
+
throw failure();
|
|
1449
|
+
}
|
|
1450
|
+
try {
|
|
1451
|
+
if (response.redirected || response.status >= 300 && response.status < 400 || !response.body)
|
|
1452
|
+
throw failure();
|
|
1453
|
+
const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
1454
|
+
const length = response.headers.get("content-length");
|
|
1455
|
+
if (mediaType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
|
|
1456
|
+
throw failure();
|
|
1457
|
+
reader = response.body.getReader();
|
|
1458
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1459
|
+
let bytes = 0;
|
|
1460
|
+
let content = "";
|
|
1461
|
+
while (true) {
|
|
1462
|
+
controller.signal.throwIfAborted();
|
|
1463
|
+
const chunk = await reader.read();
|
|
1464
|
+
controller.signal.throwIfAborted();
|
|
1465
|
+
if (chunk.done)
|
|
1466
|
+
break;
|
|
1467
|
+
bytes += chunk.value.byteLength;
|
|
1468
|
+
if (bytes > maxBytes)
|
|
1469
|
+
throw failure();
|
|
1470
|
+
content += decoder.decode(chunk.value, { stream: true });
|
|
1471
|
+
}
|
|
1472
|
+
content += decoder.decode();
|
|
1473
|
+
const headers = new Headers(response.headers);
|
|
1474
|
+
headers.delete("content-length");
|
|
1475
|
+
headers.delete("content-encoding");
|
|
1476
|
+
return new Response(content, { status: response.status, statusText: response.statusText, headers });
|
|
1477
|
+
} finally {
|
|
1478
|
+
if (reader) {
|
|
1479
|
+
abortRead();
|
|
1480
|
+
reader.releaseLock();
|
|
1481
|
+
} else {
|
|
1482
|
+
response.body?.cancel().catch(() => {});
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
try {
|
|
1487
|
+
return await Promise.race([read(), aborted]);
|
|
1488
|
+
} catch {
|
|
1489
|
+
throw failure();
|
|
1490
|
+
} finally {
|
|
1491
|
+
clearTimeout(timer);
|
|
1492
|
+
controller.abort();
|
|
1493
|
+
request.signal.removeEventListener("abort", cancel);
|
|
1494
|
+
controller.signal.removeEventListener("abort", rejectAbort);
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// src/oauth-clients.ts
|
|
1500
|
+
class SupaCloudOAuthClientError extends SupaCloudApiError {
|
|
1501
|
+
mutationMayHaveApplied;
|
|
1502
|
+
constructor(code, status = 0, mutationMayHaveApplied = false) {
|
|
1503
|
+
super("OAuth client operation failed", status, { code, mutation_may_have_applied: mutationMayHaveApplied });
|
|
1504
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1505
|
+
this.name = "SupaCloudOAuthClientError";
|
|
80
1506
|
}
|
|
81
|
-
|
|
82
|
-
|
|
1507
|
+
}
|
|
1508
|
+
function invalid4() {
|
|
1509
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_RESPONSE");
|
|
1510
|
+
}
|
|
1511
|
+
function isRecord2(value) {
|
|
1512
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1513
|
+
}
|
|
1514
|
+
function record5(value) {
|
|
1515
|
+
return isRecord2(value) ? value : invalid4();
|
|
1516
|
+
}
|
|
1517
|
+
function text3(value, max = 2048) {
|
|
1518
|
+
if (typeof value !== "string" || new TextEncoder().encode(value).length > max || /[\u0000-\u001f\u007f]/.test(value))
|
|
1519
|
+
return invalid4();
|
|
1520
|
+
return value;
|
|
1521
|
+
}
|
|
1522
|
+
function id3(value) {
|
|
1523
|
+
const valueId = text3(value, 36);
|
|
1524
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(valueId) ? valueId : invalid4();
|
|
1525
|
+
}
|
|
1526
|
+
function uri(value, redirect = false) {
|
|
1527
|
+
const input = text3(value);
|
|
1528
|
+
if (!input && !redirect)
|
|
1529
|
+
return input;
|
|
1530
|
+
if (!input || /[\s\\#]/.test(input))
|
|
1531
|
+
return invalid4();
|
|
1532
|
+
let url;
|
|
1533
|
+
try {
|
|
1534
|
+
url = new URL(input);
|
|
1535
|
+
} catch {
|
|
1536
|
+
return invalid4();
|
|
1537
|
+
}
|
|
1538
|
+
if (url.username || url.password || (redirect ? /^(javascript|data|blob|file|about):$/.test(url.protocol) : !/^https?:$/.test(url.protocol)))
|
|
1539
|
+
return invalid4();
|
|
1540
|
+
return input;
|
|
1541
|
+
}
|
|
1542
|
+
function array(value, decode, max) {
|
|
1543
|
+
if (!Array.isArray(value) || !value.length || value.length > max)
|
|
1544
|
+
return invalid4();
|
|
1545
|
+
const result = value.map((value) => decode(value));
|
|
1546
|
+
if (new Set(result).size !== result.length)
|
|
1547
|
+
return invalid4();
|
|
1548
|
+
return result;
|
|
1549
|
+
}
|
|
1550
|
+
function method(value) {
|
|
1551
|
+
return value === "none" || value === "client_secret_basic" || value === "client_secret_post" ? value : invalid4();
|
|
1552
|
+
}
|
|
1553
|
+
function date(value) {
|
|
1554
|
+
const input = text3(value, 64);
|
|
1555
|
+
const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(input);
|
|
1556
|
+
if (!parts)
|
|
1557
|
+
return invalid4();
|
|
1558
|
+
const year = Number(parts[1]), month = Number(parts[2]), day = Number(parts[3]);
|
|
1559
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
1560
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
1561
|
+
if (month < 1 || month > 12 || day < 1 || day > (days[month - 1] ?? 0) || Number(parts[4]) > 23 || Number(parts[5]) > 59 || Number(parts[6]) > 59 || Number(parts[7] ?? 0) > 23 || Number(parts[8] ?? 0) > 59 || !Number.isFinite(Date.parse(input)))
|
|
1562
|
+
return invalid4();
|
|
1563
|
+
return input;
|
|
1564
|
+
}
|
|
1565
|
+
function fields(data) {
|
|
1566
|
+
const result = {};
|
|
1567
|
+
if (data.client_name !== undefined)
|
|
1568
|
+
result.client_name = text3(data.client_name, 1024);
|
|
1569
|
+
if (data.redirect_uris !== undefined)
|
|
1570
|
+
result.redirect_uris = array(data.redirect_uris, (value) => uri(value, true), 100);
|
|
1571
|
+
if (data.token_endpoint_auth_method !== undefined)
|
|
1572
|
+
result.token_endpoint_auth_method = method(data.token_endpoint_auth_method);
|
|
1573
|
+
if (data.grant_types !== undefined) {
|
|
1574
|
+
result.grant_types = array(data.grant_types, (value) => value === "authorization_code" || value === "refresh_token" ? value : invalid4(), 2);
|
|
1575
|
+
}
|
|
1576
|
+
if (data.client_uri !== undefined)
|
|
1577
|
+
result.client_uri = uri(data.client_uri);
|
|
1578
|
+
if (data.logo_uri !== undefined)
|
|
1579
|
+
result.logo_uri = uri(data.logo_uri);
|
|
1580
|
+
return result;
|
|
1581
|
+
}
|
|
1582
|
+
function decodeClient(value, secret = false) {
|
|
1583
|
+
const data = record5(value);
|
|
1584
|
+
const { token_endpoint_auth_method: authMethod, ...optional } = fields(data);
|
|
1585
|
+
const metadata = { ...optional, client_id: id3(data.client_id) };
|
|
1586
|
+
if (data.response_types !== undefined)
|
|
1587
|
+
metadata.response_types = array(data.response_types, (value) => value === "code" ? value : invalid4(), 1);
|
|
1588
|
+
if (data.registration_type !== undefined) {
|
|
1589
|
+
if (data.registration_type !== "manual" && data.registration_type !== "dynamic")
|
|
1590
|
+
return invalid4();
|
|
1591
|
+
metadata.registration_type = data.registration_type;
|
|
1592
|
+
}
|
|
1593
|
+
if (data.created_at !== undefined)
|
|
1594
|
+
metadata.created_at = date(data.created_at);
|
|
1595
|
+
if (data.updated_at !== undefined)
|
|
1596
|
+
metadata.updated_at = date(data.updated_at);
|
|
1597
|
+
if (data.client_type === "public") {
|
|
1598
|
+
if (data.client_secret !== undefined || authMethod !== undefined && authMethod !== "none")
|
|
1599
|
+
return invalid4();
|
|
1600
|
+
return { ...metadata, client_type: "public", ...authMethod === undefined ? {} : { token_endpoint_auth_method: "none" } };
|
|
1601
|
+
}
|
|
1602
|
+
if (data.client_type !== "confidential" || authMethod === "none")
|
|
1603
|
+
return invalid4();
|
|
1604
|
+
const result = {
|
|
1605
|
+
...metadata,
|
|
1606
|
+
client_type: "confidential",
|
|
1607
|
+
...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod }
|
|
1608
|
+
};
|
|
1609
|
+
if (!secret && data.client_secret !== undefined)
|
|
1610
|
+
return invalid4();
|
|
1611
|
+
if (secret) {
|
|
1612
|
+
const clientSecret = text3(data.client_secret, 4096);
|
|
1613
|
+
if (!clientSecret || clientSecret !== clientSecret.trim())
|
|
1614
|
+
return invalid4();
|
|
1615
|
+
result.client_secret = clientSecret;
|
|
1616
|
+
}
|
|
1617
|
+
return result;
|
|
1618
|
+
}
|
|
1619
|
+
function decodeCreated(value) {
|
|
1620
|
+
const client = decodeClient(value, true);
|
|
1621
|
+
if (client.client_type === "public")
|
|
1622
|
+
return client;
|
|
1623
|
+
if (!client.client_secret)
|
|
1624
|
+
return invalid4();
|
|
1625
|
+
return { ...client, client_secret: client.client_secret };
|
|
1626
|
+
}
|
|
1627
|
+
function decodeList(value) {
|
|
1628
|
+
const data = record5(value);
|
|
1629
|
+
if (!Array.isArray(data.clients) || data.clients.length > 5000)
|
|
1630
|
+
return invalid4();
|
|
1631
|
+
const clients = data.clients.map((value) => decodeClient(value));
|
|
1632
|
+
if (new Set(clients.map((client) => client.client_id)).size !== clients.length)
|
|
1633
|
+
return invalid4();
|
|
1634
|
+
return { clients };
|
|
1635
|
+
}
|
|
1636
|
+
function updateInput(value, create = false) {
|
|
1637
|
+
const data = record5(value);
|
|
1638
|
+
const allowed = ["client_name", "redirect_uris", "token_endpoint_auth_method", "grant_types", "client_uri", "logo_uri"];
|
|
1639
|
+
if (create)
|
|
1640
|
+
allowed.push("client_type");
|
|
1641
|
+
if (Object.keys(data).some((key) => !allowed.includes(key)))
|
|
1642
|
+
return invalid4();
|
|
1643
|
+
const result = fields(data);
|
|
1644
|
+
if (!create && !Object.keys(result).length)
|
|
1645
|
+
return invalid4();
|
|
1646
|
+
return result;
|
|
1647
|
+
}
|
|
1648
|
+
function createInput(value) {
|
|
1649
|
+
const data = record5(value);
|
|
1650
|
+
const { token_endpoint_auth_method: authMethod, ...rest } = updateInput(value, true);
|
|
1651
|
+
if (!rest.redirect_uris)
|
|
1652
|
+
return invalid4();
|
|
1653
|
+
const common = { ...rest, redirect_uris: rest.redirect_uris };
|
|
1654
|
+
if (data.client_type === "public") {
|
|
1655
|
+
if (authMethod !== undefined && authMethod !== "none")
|
|
1656
|
+
return invalid4();
|
|
1657
|
+
return { ...common, client_type: "public", ...authMethod === undefined ? {} : { token_endpoint_auth_method: "none" } };
|
|
1658
|
+
}
|
|
1659
|
+
if (data.client_type === "confidential") {
|
|
1660
|
+
if (authMethod === "none")
|
|
1661
|
+
return invalid4();
|
|
1662
|
+
return { ...common, client_type: "confidential", ...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod } };
|
|
1663
|
+
}
|
|
1664
|
+
if (data.client_type !== undefined)
|
|
1665
|
+
return invalid4();
|
|
1666
|
+
return { ...common, ...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod } };
|
|
1667
|
+
}
|
|
1668
|
+
function validateInput(decode) {
|
|
1669
|
+
try {
|
|
1670
|
+
return decode();
|
|
1671
|
+
} catch {
|
|
1672
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
function matches(client, input) {
|
|
1676
|
+
for (const key of ["client_name", "client_uri", "logo_uri"]) {
|
|
1677
|
+
if (input[key] !== undefined && input[key] !== (client[key] ?? ""))
|
|
1678
|
+
return invalid4();
|
|
1679
|
+
}
|
|
1680
|
+
if (input.token_endpoint_auth_method !== undefined && input.token_endpoint_auth_method !== client.token_endpoint_auth_method)
|
|
1681
|
+
return invalid4();
|
|
1682
|
+
for (const key of ["redirect_uris", "grant_types"]) {
|
|
1683
|
+
const expected = input[key], actual = client[key];
|
|
1684
|
+
const expectedValues = new Set(expected);
|
|
1685
|
+
if (expected && (!actual || actual.length !== expected.length || actual.some((value) => !expectedValues.has(value))))
|
|
1686
|
+
return invalid4();
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
function baseUrl(value, session) {
|
|
1690
|
+
if (/[\s\\?#]/.test(value))
|
|
1691
|
+
return invalid4();
|
|
1692
|
+
if (session && value === "")
|
|
1693
|
+
return "";
|
|
1694
|
+
let url;
|
|
1695
|
+
try {
|
|
1696
|
+
url = new URL(value);
|
|
1697
|
+
} catch {
|
|
1698
|
+
return invalid4();
|
|
1699
|
+
}
|
|
1700
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash || url.href.replace(/\/$/, "") !== value.replace(/\/$/, ""))
|
|
1701
|
+
return invalid4();
|
|
1702
|
+
if (session)
|
|
1703
|
+
return invalid4();
|
|
1704
|
+
return url.href.replace(/\/$/, "");
|
|
1705
|
+
}
|
|
1706
|
+
async function readText(response, signal, max) {
|
|
1707
|
+
if (!response.body)
|
|
1708
|
+
return "";
|
|
1709
|
+
const reader = response.body.getReader();
|
|
1710
|
+
const abort = () => {
|
|
1711
|
+
reader.cancel().catch(() => {});
|
|
1712
|
+
};
|
|
1713
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1714
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1715
|
+
let size = 0, text = "";
|
|
1716
|
+
try {
|
|
1717
|
+
signal.throwIfAborted();
|
|
1718
|
+
for (;; ) {
|
|
1719
|
+
const part = await reader.read();
|
|
1720
|
+
signal.throwIfAborted();
|
|
1721
|
+
if (part.done)
|
|
1722
|
+
break;
|
|
1723
|
+
size += part.value.byteLength;
|
|
1724
|
+
if (size > max)
|
|
1725
|
+
return invalid4();
|
|
1726
|
+
text += decoder.decode(part.value, { stream: true });
|
|
1727
|
+
}
|
|
1728
|
+
return text + decoder.decode();
|
|
1729
|
+
} finally {
|
|
1730
|
+
signal.removeEventListener("abort", abort);
|
|
1731
|
+
reader.cancel().catch(() => {});
|
|
1732
|
+
reader.releaseLock();
|
|
83
1733
|
}
|
|
84
1734
|
}
|
|
85
1735
|
|
|
1736
|
+
class SupaCloudOAuthClientsClient {
|
|
1737
|
+
base;
|
|
1738
|
+
send;
|
|
1739
|
+
token;
|
|
1740
|
+
constructor(options) {
|
|
1741
|
+
this.base = validateInput(() => {
|
|
1742
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(options.projectRef))
|
|
1743
|
+
return invalid4();
|
|
1744
|
+
return `${baseUrl(options.managementApiUrl, options.sessionRequest !== undefined)}/v1/projects/${options.projectRef}/auth/oauth-clients`;
|
|
1745
|
+
});
|
|
1746
|
+
if (options.sessionRequest !== undefined) {
|
|
1747
|
+
if (typeof options.sessionRequest !== "function" || options.getAccessToken !== undefined || options.request !== undefined) {
|
|
1748
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1749
|
+
}
|
|
1750
|
+
this.send = options.sessionRequest;
|
|
1751
|
+
this.token = null;
|
|
1752
|
+
} else {
|
|
1753
|
+
if (typeof options.getAccessToken !== "function" || options.request !== undefined && typeof options.request !== "function") {
|
|
1754
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1755
|
+
}
|
|
1756
|
+
this.send = options.request ?? ((url, options) => fetch(url, options));
|
|
1757
|
+
this.token = options.getAccessToken;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
async request(suffix, method, body, status, decode, options) {
|
|
1761
|
+
const signal = options.signal, timeoutMs = options.timeoutMs ?? 15000;
|
|
1762
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) {
|
|
1763
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1764
|
+
}
|
|
1765
|
+
const encoded = body === undefined ? undefined : JSON.stringify(body);
|
|
1766
|
+
const controller = new AbortController;
|
|
1767
|
+
let rejectStopped = () => {};
|
|
1768
|
+
const stopped = new Promise((_, reject) => {
|
|
1769
|
+
rejectStopped = reject;
|
|
1770
|
+
});
|
|
1771
|
+
const mutation = method !== "GET";
|
|
1772
|
+
let sent = false;
|
|
1773
|
+
const stop = (code) => {
|
|
1774
|
+
controller.abort();
|
|
1775
|
+
rejectStopped(new SupaCloudOAuthClientError(code, 0, sent && mutation));
|
|
1776
|
+
};
|
|
1777
|
+
const abort = () => stop("OAUTH_CLIENT_REQUEST_CANCELLED");
|
|
1778
|
+
if (signal?.aborted)
|
|
1779
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_REQUEST_CANCELLED");
|
|
1780
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1781
|
+
const timer = setTimeout(() => stop("OAUTH_CLIENT_REQUEST_TIMED_OUT"), timeoutMs);
|
|
1782
|
+
const work = async () => {
|
|
1783
|
+
const headers = new Headers({ accept: "application/json" });
|
|
1784
|
+
if (this.token) {
|
|
1785
|
+
const token = await this.token();
|
|
1786
|
+
controller.signal.throwIfAborted();
|
|
1787
|
+
if (typeof token !== "string" || !token || /[\s\u0000-\u001f\u007f]/.test(token)) {
|
|
1788
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_TOKEN_UNAVAILABLE");
|
|
1789
|
+
}
|
|
1790
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
1791
|
+
}
|
|
1792
|
+
if (encoded !== undefined)
|
|
1793
|
+
headers.set("content-type", "application/json");
|
|
1794
|
+
controller.signal.throwIfAborted();
|
|
1795
|
+
sent = true;
|
|
1796
|
+
const response = await this.send(`${this.base}${suffix}`, {
|
|
1797
|
+
method,
|
|
1798
|
+
headers,
|
|
1799
|
+
...encoded === undefined ? {} : { body: encoded },
|
|
1800
|
+
signal: controller.signal,
|
|
1801
|
+
redirect: "error",
|
|
1802
|
+
cache: "no-store",
|
|
1803
|
+
credentials: this.token ? "omit" : "same-origin"
|
|
1804
|
+
});
|
|
1805
|
+
try {
|
|
1806
|
+
controller.signal.throwIfAborted();
|
|
1807
|
+
if (response.redirected || response.status >= 300 && response.status < 400)
|
|
1808
|
+
return invalid4();
|
|
1809
|
+
if (response.status === 204 && status === 204) {
|
|
1810
|
+
if (await readText(response, controller.signal, 0) !== "")
|
|
1811
|
+
return invalid4();
|
|
1812
|
+
return decode(undefined);
|
|
1813
|
+
}
|
|
1814
|
+
if (!/^application\/(?:json|[a-z0-9.+-]+\+json)(?:;|$)/i.test(response.headers.get("content-type") ?? ""))
|
|
1815
|
+
return invalid4();
|
|
1816
|
+
const value = JSON.parse(await readText(response, controller.signal, response.ok && suffix === "" && method === "GET" ? 1024 * 1024 : 64 * 1024));
|
|
1817
|
+
if (!response.ok) {
|
|
1818
|
+
const data = record5(value);
|
|
1819
|
+
if (data.mutation_may_have_applied !== undefined && typeof data.mutation_may_have_applied !== "boolean")
|
|
1820
|
+
return invalid4();
|
|
1821
|
+
const code = typeof data.code === "string" && /^[A-Z0-9_]{1,80}$/.test(data.code) ? data.code : "OAUTH_CLIENT_REQUEST_FAILED";
|
|
1822
|
+
throw new SupaCloudOAuthClientError(code, response.status, mutation && (data.mutation_may_have_applied === true || response.status >= 500));
|
|
1823
|
+
}
|
|
1824
|
+
if (response.status !== status)
|
|
1825
|
+
return invalid4();
|
|
1826
|
+
return decode(value);
|
|
1827
|
+
} finally {
|
|
1828
|
+
response.body?.cancel().catch(() => {});
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
try {
|
|
1832
|
+
return await Promise.race([work(), stopped]);
|
|
1833
|
+
} catch (error) {
|
|
1834
|
+
if (error instanceof SupaCloudOAuthClientError) {
|
|
1835
|
+
if (error.code === "INVALID_OAUTH_CLIENT_RESPONSE") {
|
|
1836
|
+
throw new SupaCloudOAuthClientError(error.code, error.status, sent && mutation);
|
|
1837
|
+
}
|
|
1838
|
+
throw error;
|
|
1839
|
+
}
|
|
1840
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_REQUEST_FAILED", 0, sent && mutation);
|
|
1841
|
+
} finally {
|
|
1842
|
+
clearTimeout(timer);
|
|
1843
|
+
signal?.removeEventListener("abort", abort);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
list(options = {}) {
|
|
1847
|
+
return this.request("", "GET", undefined, 200, decodeList, options);
|
|
1848
|
+
}
|
|
1849
|
+
async get(clientId, options = {}) {
|
|
1850
|
+
const target = validateInput(() => id3(clientId));
|
|
1851
|
+
return this.request(`/${target}`, "GET", undefined, 200, (value) => {
|
|
1852
|
+
const client = decodeClient(value);
|
|
1853
|
+
if (client.client_id !== target)
|
|
1854
|
+
return invalid4();
|
|
1855
|
+
return client;
|
|
1856
|
+
}, options);
|
|
1857
|
+
}
|
|
1858
|
+
async create(input, options = {}) {
|
|
1859
|
+
const submitted = validateInput(() => createInput(input));
|
|
1860
|
+
return this.request("", "POST", submitted, 201, (value) => {
|
|
1861
|
+
const client = decodeCreated(value);
|
|
1862
|
+
matches(client, submitted);
|
|
1863
|
+
const expectedType = submitted.client_type ?? (submitted.token_endpoint_auth_method === "none" ? "public" : "confidential");
|
|
1864
|
+
if (client.client_type !== expectedType || client.registration_type !== "manual")
|
|
1865
|
+
return invalid4();
|
|
1866
|
+
return client;
|
|
1867
|
+
}, options);
|
|
1868
|
+
}
|
|
1869
|
+
async update(clientId, input, options = {}) {
|
|
1870
|
+
const target = validateInput(() => id3(clientId)), submitted = validateInput(() => updateInput(input));
|
|
1871
|
+
return this.request(`/${target}`, "PUT", submitted, 200, (value) => {
|
|
1872
|
+
const client = decodeClient(value);
|
|
1873
|
+
if (client.client_id !== target)
|
|
1874
|
+
return invalid4();
|
|
1875
|
+
matches(client, submitted);
|
|
1876
|
+
return client;
|
|
1877
|
+
}, options);
|
|
1878
|
+
}
|
|
1879
|
+
async delete(clientId, options = {}) {
|
|
1880
|
+
const target = validateInput(() => id3(clientId));
|
|
1881
|
+
return this.request(`/${target}`, "DELETE", undefined, 204, (value) => {
|
|
1882
|
+
if (value !== undefined)
|
|
1883
|
+
return invalid4();
|
|
1884
|
+
}, options);
|
|
1885
|
+
}
|
|
1886
|
+
async regenerateSecret(clientId, options = {}) {
|
|
1887
|
+
const target = validateInput(() => id3(clientId));
|
|
1888
|
+
return this.request(`/${target}/regenerate-secret`, "POST", undefined, 200, (value) => {
|
|
1889
|
+
const client = decodeCreated(value);
|
|
1890
|
+
if (client.client_id !== target || client.client_type !== "confidential")
|
|
1891
|
+
return invalid4();
|
|
1892
|
+
return client;
|
|
1893
|
+
}, options);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
// src/oauth-server.ts
|
|
1898
|
+
class SupaCloudOAuthServerError extends SupaCloudApiError {
|
|
1899
|
+
code;
|
|
1900
|
+
mutationMayHaveApplied;
|
|
1901
|
+
constructor(message, code, mutationMayHaveApplied = false, status = 0) {
|
|
1902
|
+
super(message, status, { code, mutation_may_have_applied: mutationMayHaveApplied });
|
|
1903
|
+
this.code = code;
|
|
1904
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1905
|
+
this.name = "SupaCloudOAuthServerError";
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
function invalid5(field = "payload") {
|
|
1909
|
+
throw new SupaCloudOAuthServerError(`Invalid OAuth Server response: ${field}`, "OAUTH_SERVER_INVALID");
|
|
1910
|
+
}
|
|
1911
|
+
function isRecord3(value) {
|
|
1912
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1913
|
+
}
|
|
1914
|
+
function record6(value) {
|
|
1915
|
+
return isRecord3(value) ? value : invalid5();
|
|
1916
|
+
}
|
|
1917
|
+
function text4(value, field, max = 4096) {
|
|
1918
|
+
return typeof value === "string" && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value) ? value : invalid5(field);
|
|
1919
|
+
}
|
|
1920
|
+
function flag(value, field) {
|
|
1921
|
+
return typeof value === "boolean" ? value : invalid5(field);
|
|
1922
|
+
}
|
|
1923
|
+
function strings(value, field) {
|
|
1924
|
+
if (!Array.isArray(value) || value.length > 64)
|
|
1925
|
+
return invalid5(field);
|
|
1926
|
+
const result = value.map((item) => text4(item, field));
|
|
1927
|
+
return new Set(result).size === result.length ? result : invalid5(field);
|
|
1928
|
+
}
|
|
1929
|
+
function httpUrl(value, field) {
|
|
1930
|
+
const input = text4(value, field);
|
|
1931
|
+
let parsed;
|
|
1932
|
+
try {
|
|
1933
|
+
parsed = new URL(input);
|
|
1934
|
+
} catch {
|
|
1935
|
+
return invalid5(field);
|
|
1936
|
+
}
|
|
1937
|
+
if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || /[\s\\?#]/.test(input) || parsed.href.replace(/\/$/, "") !== input.replace(/\/$/, ""))
|
|
1938
|
+
return invalid5(field);
|
|
1939
|
+
return input;
|
|
1940
|
+
}
|
|
1941
|
+
function authorizationPath(value) {
|
|
1942
|
+
const input = text4(value, "authorization_path");
|
|
1943
|
+
let decoded;
|
|
1944
|
+
try {
|
|
1945
|
+
decoded = decodeURIComponent(input);
|
|
1946
|
+
} catch {
|
|
1947
|
+
return invalid5("authorization_path");
|
|
1948
|
+
}
|
|
1949
|
+
if (!input.startsWith("/") || [input, decoded].some((part) => /[\\?#\u0000-\u001f\u007f]/.test(part) || part.includes("//") || part.split("/").some((segment) => segment === "." || segment === ".."))) {
|
|
1950
|
+
return invalid5("authorization_path");
|
|
1951
|
+
}
|
|
1952
|
+
return input;
|
|
1953
|
+
}
|
|
1954
|
+
function decodeStatus(value, projectRef) {
|
|
1955
|
+
const data = record6(value);
|
|
1956
|
+
if (data.project_ref !== projectRef)
|
|
1957
|
+
return invalid5("project_ref does not match request");
|
|
1958
|
+
if (data.account_isolated !== true)
|
|
1959
|
+
return invalid5("account_isolated");
|
|
1960
|
+
if (data.state_source !== "configuration")
|
|
1961
|
+
return invalid5("state_source");
|
|
1962
|
+
if (data.runtime_verified !== false)
|
|
1963
|
+
return invalid5("runtime_verified");
|
|
1964
|
+
const issuer = httpUrl(data.issuer, "issuer");
|
|
1965
|
+
if (issuer.endsWith("/"))
|
|
1966
|
+
return invalid5("issuer");
|
|
1967
|
+
function endpoint(field, suffix) {
|
|
1968
|
+
return data[field] === `${issuer}${suffix}` ? httpUrl(data[field], field) : invalid5(field);
|
|
1969
|
+
}
|
|
1970
|
+
const metadata = httpUrl(data.oauth_authorization_server_metadata_url, "oauth_authorization_server_metadata_url");
|
|
1971
|
+
if (!new URL(metadata).pathname.endsWith("/.well-known/oauth-authorization-server/auth/v1")) {
|
|
1972
|
+
return invalid5("oauth_authorization_server_metadata_url");
|
|
1973
|
+
}
|
|
1974
|
+
const common = {
|
|
1975
|
+
project_ref: projectRef,
|
|
1976
|
+
organization_id: data.organization_id === null ? null : text4(data.organization_id, "organization_id", 128),
|
|
1977
|
+
account_isolated: true,
|
|
1978
|
+
state_source: "configuration",
|
|
1979
|
+
runtime_verified: false,
|
|
1980
|
+
enabled: flag(data.enabled, "enabled"),
|
|
1981
|
+
allow_dynamic_registration: flag(data.allow_dynamic_registration, "allow_dynamic_registration"),
|
|
1982
|
+
issuer,
|
|
1983
|
+
authorization_path: authorizationPath(data.authorization_path),
|
|
1984
|
+
discovery_url: endpoint("discovery_url", "/.well-known/openid-configuration"),
|
|
1985
|
+
oauth_authorization_server_metadata_url: metadata,
|
|
1986
|
+
jwks_url: endpoint("jwks_url", "/.well-known/jwks.json"),
|
|
1987
|
+
authorization_endpoint: endpoint("authorization_endpoint", "/oauth/authorize"),
|
|
1988
|
+
token_endpoint: endpoint("token_endpoint", "/oauth/token"),
|
|
1989
|
+
userinfo_endpoint: endpoint("userinfo_endpoint", "/oauth/userinfo"),
|
|
1990
|
+
registration_endpoint: endpoint("registration_endpoint", "/oauth/clients/register"),
|
|
1991
|
+
warnings: strings(data.warnings, "warnings")
|
|
1992
|
+
};
|
|
1993
|
+
if (data.signing_alg === "not_migrated") {
|
|
1994
|
+
if (data.key_id !== undefined)
|
|
1995
|
+
return invalid5("key_id");
|
|
1996
|
+
if (data.oidc_id_token_ready !== false)
|
|
1997
|
+
return invalid5("oidc_id_token_ready");
|
|
1998
|
+
if (data.migration_status !== "not_migrated")
|
|
1999
|
+
return invalid5("migration_status");
|
|
2000
|
+
return { ...common, signing_alg: "not_migrated", oidc_id_token_ready: false, migration_status: "not_migrated" };
|
|
2001
|
+
}
|
|
2002
|
+
if (data.signing_alg !== "ES256" && data.signing_alg !== "RS256")
|
|
2003
|
+
return invalid5("signing_alg");
|
|
2004
|
+
if (data.oidc_id_token_ready !== true)
|
|
2005
|
+
return invalid5("oidc_id_token_ready");
|
|
2006
|
+
const key_id = text4(data.key_id, "key_id", 256);
|
|
2007
|
+
if (data.signing_alg === "ES256") {
|
|
2008
|
+
if (data.migration_status !== "oidc_es256_migrated")
|
|
2009
|
+
return invalid5("migration_status");
|
|
2010
|
+
return { ...common, signing_alg: "ES256", key_id, oidc_id_token_ready: true, migration_status: "oidc_es256_migrated" };
|
|
2011
|
+
}
|
|
2012
|
+
if (data.migration_status !== "oidc_rs256_migrated")
|
|
2013
|
+
return invalid5("migration_status");
|
|
2014
|
+
return { ...common, signing_alg: "RS256", key_id, oidc_id_token_ready: true, migration_status: "oidc_rs256_migrated" };
|
|
2015
|
+
}
|
|
2016
|
+
function decodeDiscovery(value, status) {
|
|
2017
|
+
const data = record6(value);
|
|
2018
|
+
for (const [key, expected] of [
|
|
2019
|
+
["issuer", status.issuer],
|
|
2020
|
+
["authorization_endpoint", status.authorization_endpoint],
|
|
2021
|
+
["token_endpoint", status.token_endpoint],
|
|
2022
|
+
["jwks_uri", status.jwks_url]
|
|
2023
|
+
])
|
|
2024
|
+
if (data[key] !== expected)
|
|
2025
|
+
return invalid5(`discovery.${key}`);
|
|
2026
|
+
const responseTypes = strings(data.response_types_supported, "response_types_supported");
|
|
2027
|
+
const subjects = strings(data.subject_types_supported, "subject_types_supported");
|
|
2028
|
+
const algorithms = strings(data.id_token_signing_alg_values_supported, "id_token_signing_alg_values_supported");
|
|
2029
|
+
if (!responseTypes.includes("code") || subjects.length === 0 || subjects.some((subject) => subject !== "public" && subject !== "pairwise") || !algorithms.includes(status.signing_alg))
|
|
2030
|
+
return invalid5("discovery capabilities");
|
|
2031
|
+
const result = {
|
|
2032
|
+
issuer: status.issuer,
|
|
2033
|
+
authorization_endpoint: status.authorization_endpoint,
|
|
2034
|
+
token_endpoint: status.token_endpoint,
|
|
2035
|
+
jwks_uri: status.jwks_url,
|
|
2036
|
+
response_types_supported: responseTypes,
|
|
2037
|
+
subject_types_supported: subjects,
|
|
2038
|
+
id_token_signing_alg_values_supported: algorithms
|
|
2039
|
+
};
|
|
2040
|
+
for (const field of ["userinfo_endpoint", "registration_endpoint"]) {
|
|
2041
|
+
if (data[field] === undefined)
|
|
2042
|
+
continue;
|
|
2043
|
+
if (data[field] !== status[field])
|
|
2044
|
+
return invalid5(`discovery.${field}`);
|
|
2045
|
+
result[field] = status[field];
|
|
2046
|
+
}
|
|
2047
|
+
return result;
|
|
2048
|
+
}
|
|
2049
|
+
function base64url(value, field) {
|
|
2050
|
+
const encoded = text4(value, field, 2048);
|
|
2051
|
+
if (!/^[A-Za-z0-9_-]+$/.test(encoded))
|
|
2052
|
+
return invalid5(field);
|
|
2053
|
+
let binary;
|
|
2054
|
+
try {
|
|
2055
|
+
binary = atob(encoded.replace(/-/g, "+").replace(/_/g, "/"));
|
|
2056
|
+
} catch {
|
|
2057
|
+
return invalid5(field);
|
|
2058
|
+
}
|
|
2059
|
+
if (btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") !== encoded)
|
|
2060
|
+
return invalid5(field);
|
|
2061
|
+
return { encoded, bytes: Uint8Array.from(binary, (char) => char.charCodeAt(0)) };
|
|
2062
|
+
}
|
|
2063
|
+
async function decodeJwks(value, status) {
|
|
2064
|
+
const input = record6(value).keys;
|
|
2065
|
+
if (!Array.isArray(input) || input.length === 0 || input.length > 16)
|
|
2066
|
+
return invalid5("jwks.keys");
|
|
2067
|
+
const keys = [];
|
|
2068
|
+
const ids = new Set;
|
|
2069
|
+
for (const item of input) {
|
|
2070
|
+
const data = record6(item);
|
|
2071
|
+
if (["d", "p", "q", "dp", "dq", "qi", "oth", "k"].some((field) => (field in data)))
|
|
2072
|
+
return invalid5("private JWK");
|
|
2073
|
+
const kid = text4(data.kid, "kid", 256);
|
|
2074
|
+
if (ids.has(kid))
|
|
2075
|
+
return invalid5("duplicate kid");
|
|
2076
|
+
ids.add(kid);
|
|
2077
|
+
if (data.use !== undefined && data.use !== "sig")
|
|
2078
|
+
return invalid5("JWK use");
|
|
2079
|
+
if (data.key_ops !== undefined && strings(data.key_ops, "key_ops").join(",") !== "verify")
|
|
2080
|
+
return invalid5("key_ops");
|
|
2081
|
+
let key;
|
|
2082
|
+
if (data.kty === "EC") {
|
|
2083
|
+
if (data.crv !== "P-256" || data.alg !== "ES256")
|
|
2084
|
+
return invalid5("EC algorithm");
|
|
2085
|
+
const x = base64url(data.x, "x"), y = base64url(data.y, "y");
|
|
2086
|
+
if (x.bytes.length !== 32 || y.bytes.length !== 32)
|
|
2087
|
+
return invalid5("EC coordinates");
|
|
2088
|
+
key = { kty: "EC", crv: "P-256", x: x.encoded, y: y.encoded, alg: "ES256", kid, use: "sig" };
|
|
2089
|
+
} else if (data.kty === "RSA") {
|
|
2090
|
+
if (data.alg !== "RS256")
|
|
2091
|
+
return invalid5("RSA algorithm");
|
|
2092
|
+
const n = base64url(data.n, "n"), e = base64url(data.e, "e");
|
|
2093
|
+
const first = n.bytes[0];
|
|
2094
|
+
if (first === undefined || first === 0 || n.bytes.length > 1024 || (n.bytes.length - 1) * 8 + (32 - Math.clz32(first)) < 2048 || e.bytes.length === 0 || e.bytes.length > 4 || e.bytes[0] === 0)
|
|
2095
|
+
return invalid5("RSA parameters");
|
|
2096
|
+
const exponent = e.bytes.reduce((result, byte) => result * 256 + byte, 0);
|
|
2097
|
+
if (exponent < 3 || exponent % 2 === 0)
|
|
2098
|
+
return invalid5("RSA exponent");
|
|
2099
|
+
key = { kty: "RSA", n: n.encoded, e: e.encoded, alg: "RS256", kid, use: "sig" };
|
|
2100
|
+
} else
|
|
2101
|
+
return invalid5("JWK kty");
|
|
2102
|
+
try {
|
|
2103
|
+
await crypto.subtle.importKey("jwk", key, key.kty === "EC" ? { name: "ECDSA", namedCurve: "P-256" } : { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
|
2104
|
+
} catch {
|
|
2105
|
+
return invalid5("JWK public material");
|
|
2106
|
+
}
|
|
2107
|
+
keys.push(key);
|
|
2108
|
+
}
|
|
2109
|
+
if (!keys.some((key) => key.kid === status.key_id && key.alg === status.signing_alg))
|
|
2110
|
+
return invalid5("configured JWK");
|
|
2111
|
+
return { keys };
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
class Operation {
|
|
2115
|
+
controller = new AbortController;
|
|
2116
|
+
mutationStarted = false;
|
|
2117
|
+
bodies = new Set;
|
|
2118
|
+
async run(work) {
|
|
2119
|
+
let timer;
|
|
2120
|
+
const timeout = new Promise((_, reject) => {
|
|
2121
|
+
timer = setTimeout(() => {
|
|
2122
|
+
this.controller.abort();
|
|
2123
|
+
reject(new SupaCloudOAuthServerError("OAuth Server request timed out", "OAUTH_SERVER_TIMEOUT", this.mutationStarted));
|
|
2124
|
+
}, 15000);
|
|
2125
|
+
});
|
|
2126
|
+
try {
|
|
2127
|
+
return await Promise.race([work(), timeout]);
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
if (error instanceof SupaCloudOAuthServerError) {
|
|
2130
|
+
throw new SupaCloudOAuthServerError(error.message, error.code, error.mutationMayHaveApplied || this.mutationStarted, error.status);
|
|
2131
|
+
}
|
|
2132
|
+
throw new SupaCloudOAuthServerError("OAuth Server request failed", "OAUTH_SERVER_REQUEST_FAILED", this.mutationStarted);
|
|
2133
|
+
} finally {
|
|
2134
|
+
clearTimeout(timer);
|
|
2135
|
+
this.controller.abort();
|
|
2136
|
+
for (const body of this.bodies)
|
|
2137
|
+
body.cancel().catch(() => {});
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
async json(url, init = {}) {
|
|
2141
|
+
this.controller.signal.throwIfAborted();
|
|
2142
|
+
const response = await fetch(url, {
|
|
2143
|
+
...init,
|
|
2144
|
+
redirect: "error",
|
|
2145
|
+
credentials: "omit",
|
|
2146
|
+
cache: "no-store",
|
|
2147
|
+
signal: this.controller.signal
|
|
2148
|
+
});
|
|
2149
|
+
if (this.controller.signal.aborted) {
|
|
2150
|
+
response.body?.cancel().catch(() => {});
|
|
2151
|
+
this.controller.signal.throwIfAborted();
|
|
2152
|
+
}
|
|
2153
|
+
const body = response.body;
|
|
2154
|
+
if (body)
|
|
2155
|
+
this.bodies.add(body);
|
|
2156
|
+
if (response.redirected || response.status >= 300 && response.status < 400) {
|
|
2157
|
+
throw new SupaCloudOAuthServerError("OAuth Server returned an unsuccessful response", "OAUTH_SERVER_HTTP_ERROR", this.mutationStarted, response.status);
|
|
2158
|
+
}
|
|
2159
|
+
if (!body)
|
|
2160
|
+
return invalid5("empty body");
|
|
2161
|
+
const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
2162
|
+
if (type !== "application/json" && type !== "application/jwk-set+json")
|
|
2163
|
+
return invalid5("content-type");
|
|
2164
|
+
const length = response.headers.get("content-length");
|
|
2165
|
+
if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
|
|
2166
|
+
return invalid5("body size");
|
|
2167
|
+
const reader = body.getReader();
|
|
2168
|
+
const abort = () => {
|
|
2169
|
+
reader.cancel().catch(() => {});
|
|
2170
|
+
};
|
|
2171
|
+
this.controller.signal.addEventListener("abort", abort, { once: true });
|
|
2172
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
2173
|
+
let size = 0, content = "";
|
|
2174
|
+
try {
|
|
2175
|
+
while (true) {
|
|
2176
|
+
this.controller.signal.throwIfAborted();
|
|
2177
|
+
const chunk = await reader.read();
|
|
2178
|
+
this.controller.signal.throwIfAborted();
|
|
2179
|
+
if (chunk.done)
|
|
2180
|
+
break;
|
|
2181
|
+
size += chunk.value.byteLength;
|
|
2182
|
+
if (size > 65536)
|
|
2183
|
+
return invalid5("body size");
|
|
2184
|
+
content += decoder.decode(chunk.value, { stream: true });
|
|
2185
|
+
}
|
|
2186
|
+
content += decoder.decode();
|
|
2187
|
+
const value = JSON.parse(content);
|
|
2188
|
+
if (response.status !== 200) {
|
|
2189
|
+
const data = record6(value);
|
|
2190
|
+
const code = response.status === 503 && data.code === "SUPAUTH_DEPENDENT_REFRESH_FAILED" ? "SUPAUTH_DEPENDENT_REFRESH_FAILED" : "OAUTH_SERVER_HTTP_ERROR";
|
|
2191
|
+
throw new SupaCloudOAuthServerError("OAuth Server returned an unsuccessful response", code, this.mutationStarted, response.status);
|
|
2192
|
+
}
|
|
2193
|
+
return value;
|
|
2194
|
+
} finally {
|
|
2195
|
+
this.controller.signal.removeEventListener("abort", abort);
|
|
2196
|
+
reader.cancel().catch(() => {});
|
|
2197
|
+
reader.releaseLock();
|
|
2198
|
+
this.bodies.delete(body);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
class SupaCloudOAuthServerClient {
|
|
2204
|
+
base;
|
|
2205
|
+
projectRef;
|
|
2206
|
+
getAccessToken;
|
|
2207
|
+
constructor(options) {
|
|
2208
|
+
if (typeof options.projectRef !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(options.projectRef))
|
|
2209
|
+
invalid5("project_ref");
|
|
2210
|
+
this.projectRef = options.projectRef;
|
|
2211
|
+
this.base = httpUrl(options.managementApiUrl, "managementApiUrl").replace(/\/$/, "") + `/v1/projects/${this.projectRef}/auth/oauth-server`;
|
|
2212
|
+
this.getAccessToken = options.getAccessToken;
|
|
2213
|
+
}
|
|
2214
|
+
async status(operation) {
|
|
2215
|
+
const token = text4(await this.getAccessToken(), "access token", 16384);
|
|
2216
|
+
return decodeStatus(await operation.json(this.base, {
|
|
2217
|
+
method: "GET",
|
|
2218
|
+
headers: { authorization: `Bearer ${token}` }
|
|
2219
|
+
}), this.projectRef);
|
|
2220
|
+
}
|
|
2221
|
+
getStatus() {
|
|
2222
|
+
const operation = new Operation;
|
|
2223
|
+
return operation.run(() => this.status(operation));
|
|
2224
|
+
}
|
|
2225
|
+
migrateToOidc(options = {}) {
|
|
2226
|
+
const operation = new Operation;
|
|
2227
|
+
return operation.run(async () => {
|
|
2228
|
+
const input = record6(options);
|
|
2229
|
+
const allow = input.allowDynamicRegistration === undefined ? false : flag(input.allowDynamicRegistration, "allowDynamicRegistration");
|
|
2230
|
+
const path = input.authorizationPath === undefined ? undefined : authorizationPath(input.authorizationPath);
|
|
2231
|
+
const before = await this.status(operation);
|
|
2232
|
+
const token = text4(await this.getAccessToken(), "access token", 16384);
|
|
2233
|
+
operation.controller.signal.throwIfAborted();
|
|
2234
|
+
operation.mutationStarted = true;
|
|
2235
|
+
const after = decodeStatus(await operation.json(`${this.base}/migrate`, {
|
|
2236
|
+
method: "POST",
|
|
2237
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
2238
|
+
body: JSON.stringify({ allow_dynamic_registration: allow, ...path === undefined ? {} : { authorization_path: path } })
|
|
2239
|
+
}), this.projectRef);
|
|
2240
|
+
if (!after.enabled || !after.oidc_id_token_ready || after.allow_dynamic_registration !== allow || after.authorization_path !== (path ?? before.authorization_path) || after.issuer !== before.issuer || after.organization_id !== before.organization_id || after.signing_alg !== (before.signing_alg === "not_migrated" ? "ES256" : before.signing_alg) || before.key_id !== undefined && after.key_id !== before.key_id)
|
|
2241
|
+
return invalid5("migration receipt");
|
|
2242
|
+
return after;
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
publicDocument(field, decode) {
|
|
2246
|
+
const operation = new Operation;
|
|
2247
|
+
return operation.run(async () => {
|
|
2248
|
+
const status = await this.status(operation);
|
|
2249
|
+
if (!status.enabled || !status.oidc_id_token_ready)
|
|
2250
|
+
return invalid5("OAuth Server not configured");
|
|
2251
|
+
const value = await decode(await operation.json(status[field]), status);
|
|
2252
|
+
const after = await this.status(operation);
|
|
2253
|
+
if (JSON.stringify(status) !== JSON.stringify(after))
|
|
2254
|
+
return invalid5("configuration changed during public read");
|
|
2255
|
+
return value;
|
|
2256
|
+
});
|
|
2257
|
+
}
|
|
2258
|
+
getDiscovery() {
|
|
2259
|
+
return this.publicDocument("discovery_url", decodeDiscovery);
|
|
2260
|
+
}
|
|
2261
|
+
getJwks() {
|
|
2262
|
+
return this.publicDocument("jwks_url", decodeJwks);
|
|
2263
|
+
}
|
|
2264
|
+
buildAuthorizeUrl(options) {
|
|
2265
|
+
const operation = new Operation;
|
|
2266
|
+
return operation.run(async () => {
|
|
2267
|
+
const input = record6(options);
|
|
2268
|
+
const params = new URLSearchParams;
|
|
2269
|
+
params.set("client_id", text4(input.clientId, "clientId", 256));
|
|
2270
|
+
const redirect = text4(input.redirectUri, "redirectUri");
|
|
2271
|
+
let parsed;
|
|
2272
|
+
try {
|
|
2273
|
+
parsed = new URL(redirect);
|
|
2274
|
+
} catch {
|
|
2275
|
+
return invalid5("redirectUri");
|
|
2276
|
+
}
|
|
2277
|
+
if (!/^https?:$/.test(parsed.protocol) && !/^[a-z][a-z0-9+.-]*:$/.test(parsed.protocol) || /^(javascript|data|file|vbscript):$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.hash || /[\s\\]/.test(redirect))
|
|
2278
|
+
return invalid5("redirectUri");
|
|
2279
|
+
params.set("redirect_uri", redirect);
|
|
2280
|
+
if (input.responseType !== undefined && input.responseType !== "code")
|
|
2281
|
+
return invalid5("responseType");
|
|
2282
|
+
params.set("response_type", "code");
|
|
2283
|
+
if (input.scope !== undefined) {
|
|
2284
|
+
const scope = Array.isArray(input.scope) ? strings(input.scope, "scope").join(" ") : text4(input.scope, "scope");
|
|
2285
|
+
if (!/^[\x21\x23-\x5b\x5d-\x7e]+(?: [\x21\x23-\x5b\x5d-\x7e]+)*$/.test(scope))
|
|
2286
|
+
return invalid5("scope");
|
|
2287
|
+
params.set("scope", scope);
|
|
2288
|
+
}
|
|
2289
|
+
for (const field of ["state", "nonce"])
|
|
2290
|
+
if (input[field] !== undefined)
|
|
2291
|
+
params.set(field, text4(input[field], field));
|
|
2292
|
+
if (input.resource !== undefined)
|
|
2293
|
+
params.set("resource", httpUrl(input.resource, "resource"));
|
|
2294
|
+
if (input.codeChallenge !== undefined || input.codeChallengeMethod !== undefined) {
|
|
2295
|
+
const challenge = text4(input.codeChallenge, "codeChallenge", 128);
|
|
2296
|
+
const method = input.codeChallengeMethod;
|
|
2297
|
+
if (method !== "S256" && method !== "plain")
|
|
2298
|
+
return invalid5("codeChallengeMethod");
|
|
2299
|
+
if (method === "S256" ? base64url(challenge, "codeChallenge").bytes.length !== 32 : !/^[A-Za-z0-9._~-]{43,128}$/.test(challenge))
|
|
2300
|
+
return invalid5("codeChallenge");
|
|
2301
|
+
params.set("code_challenge", challenge);
|
|
2302
|
+
params.set("code_challenge_method", method);
|
|
2303
|
+
}
|
|
2304
|
+
const status = await this.status(operation);
|
|
2305
|
+
if (!status.enabled)
|
|
2306
|
+
return invalid5("OAuth Server disabled");
|
|
2307
|
+
return `${status.authorization_endpoint}?${params}`;
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
86
2311
|
// src/auth-fetch.ts
|
|
87
2312
|
function requestMethod(input, init) {
|
|
88
2313
|
return (init?.method || (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
@@ -106,12 +2331,12 @@ function parseRefreshBody(body, contentType) {
|
|
|
106
2331
|
const refreshToken = typeof record.refresh_token === "string" ? record.refresh_token.trim() : "";
|
|
107
2332
|
if (!refreshToken)
|
|
108
2333
|
return null;
|
|
109
|
-
const
|
|
2334
|
+
const params = new URLSearchParams;
|
|
110
2335
|
for (const [key, item] of Object.entries(record)) {
|
|
111
2336
|
if (typeof item === "string")
|
|
112
|
-
|
|
2337
|
+
params.set(key, item);
|
|
113
2338
|
}
|
|
114
|
-
return
|
|
2339
|
+
return params;
|
|
115
2340
|
}
|
|
116
2341
|
const params = new URLSearchParams(body);
|
|
117
2342
|
return params.get("refresh_token")?.trim() ? params : null;
|
|
@@ -170,9 +2395,26 @@ function createSupaCloudOAuthFetch(options = {}) {
|
|
|
170
2395
|
return fetchImpl(replacementRequest(request, endpoint, body));
|
|
171
2396
|
};
|
|
172
2397
|
}
|
|
2398
|
+
// src/workflow-fetch.ts
|
|
2399
|
+
var workflowPath = /\/rpc\/supacloud_workflow_(?:start|claim|advance|complete|retry|fail|cancel|get|events)$/;
|
|
2400
|
+
function createSupaCloudWorkflowFetch(options = {}) {
|
|
2401
|
+
return createBoundedRpcFetch(workflowPath, () => new Error("Workflow HTTP response could not be validated"), options.fetch);
|
|
2402
|
+
}
|
|
2403
|
+
// src/command-fetch.ts
|
|
2404
|
+
var commandPath = /\/rpc\/supacloud_command_(?:submit|get)$/;
|
|
2405
|
+
function createSupaCloudCommandFetch(options = {}) {
|
|
2406
|
+
return createBoundedRpcFetch(commandPath, () => new Error("Command HTTP response could not be validated"), options.fetch);
|
|
2407
|
+
}
|
|
2408
|
+
// src/artifact-fetch.ts
|
|
2409
|
+
var artifactPath2 = /\/rpc\/supacloud_artifact_(?:register|get|link)$/;
|
|
2410
|
+
function createSupaCloudArtifactFetch(options = {}) {
|
|
2411
|
+
return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
|
|
2412
|
+
}
|
|
173
2413
|
|
|
174
2414
|
// src/index.ts
|
|
175
2415
|
class SupaCloudTaskSubmitError extends Error {
|
|
2416
|
+
code = "TASK_SUBMIT_UNCONFIRMED";
|
|
2417
|
+
mutationMayHaveApplied = true;
|
|
176
2418
|
responseBody;
|
|
177
2419
|
constructor(message, responseBody) {
|
|
178
2420
|
super(message);
|
|
@@ -180,19 +2422,46 @@ class SupaCloudTaskSubmitError extends Error {
|
|
|
180
2422
|
this.responseBody = responseBody;
|
|
181
2423
|
}
|
|
182
2424
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
super(message);
|
|
190
|
-
this.name = "SupaCloudApiError";
|
|
191
|
-
this.status = status;
|
|
192
|
-
this.responseBody = responseBody;
|
|
193
|
-
this.code = extractErrorCode(responseBody);
|
|
2425
|
+
var boundedTaskHttpFailures = new WeakSet;
|
|
2426
|
+
function matchesForeignTaskHttpError(error, response) {
|
|
2427
|
+
try {
|
|
2428
|
+
return error instanceof Error && Object.getOwnPropertyDescriptor(error, "name")?.value === "FunctionsHttpError" && Object.getOwnPropertyDescriptor(error, "context")?.value === response;
|
|
2429
|
+
} catch {
|
|
2430
|
+
return false;
|
|
194
2431
|
}
|
|
195
2432
|
}
|
|
2433
|
+
function createSupaCloudTaskFetch(options) {
|
|
2434
|
+
const captured = queueJsonSnapshot(options.functionUrls);
|
|
2435
|
+
if (!Array.isArray(captured) || captured.length === 0)
|
|
2436
|
+
throw new Error("Invalid task function URLs");
|
|
2437
|
+
const urls = new Set(captured.map((value) => {
|
|
2438
|
+
if (typeof value !== "string" || value.trim() !== value || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
2439
|
+
throw new Error("Invalid task function URLs");
|
|
2440
|
+
}
|
|
2441
|
+
let url;
|
|
2442
|
+
try {
|
|
2443
|
+
url = new URL(value);
|
|
2444
|
+
} catch {
|
|
2445
|
+
throw new Error("Invalid task function URLs");
|
|
2446
|
+
}
|
|
2447
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
2448
|
+
throw new Error("Invalid task function URLs");
|
|
2449
|
+
}
|
|
2450
|
+
return url.origin + url.pathname;
|
|
2451
|
+
}));
|
|
2452
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
2453
|
+
const bounded = createBoundedRpcFetch(/./, () => new SupaCloudTaskSubmitError("Background task submission could not be confirmed", undefined), fetchImpl);
|
|
2454
|
+
return async (input, init) => {
|
|
2455
|
+
const url = new URL(input instanceof Request ? input.url : input.toString());
|
|
2456
|
+
if (!urls.has(url.origin + url.pathname))
|
|
2457
|
+
return fetchImpl(input, init);
|
|
2458
|
+
const response = await bounded(input, init);
|
|
2459
|
+
if (response.status >= 400 && response.status < 500 && response.headers.get("x-relay-error") !== "true") {
|
|
2460
|
+
boundedTaskHttpFailures.add(response);
|
|
2461
|
+
}
|
|
2462
|
+
return response;
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
196
2465
|
var TERMINAL_STATUSES = new Set([
|
|
197
2466
|
"succeeded",
|
|
198
2467
|
"failed",
|
|
@@ -212,7 +2481,7 @@ function waitForPollingInterval(intervalMs, signal) {
|
|
|
212
2481
|
settle();
|
|
213
2482
|
};
|
|
214
2483
|
const onAbort = () => finish(() => {
|
|
215
|
-
reject(signal
|
|
2484
|
+
reject(signal ? signal.reason : new DOMException("Aborted", "AbortError"));
|
|
216
2485
|
});
|
|
217
2486
|
const timer = setTimeout(() => finish(resolve), intervalMs);
|
|
218
2487
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -229,19 +2498,51 @@ function toArray(value) {
|
|
|
229
2498
|
return Array.isArray(value) ? value : [value];
|
|
230
2499
|
}
|
|
231
2500
|
function createQueryString(filters = {}) {
|
|
2501
|
+
let captured;
|
|
2502
|
+
try {
|
|
2503
|
+
captured = responseRecord(queueJsonSnapshot(filters), "task filters");
|
|
2504
|
+
} catch {
|
|
2505
|
+
throw new Error("Invalid task list filters");
|
|
2506
|
+
}
|
|
2507
|
+
if (Object.keys(captured).some((key) => !["status", "taskType", "functionSlug", "dlq", "limit"].includes(key))) {
|
|
2508
|
+
throw new Error("Invalid task list filters");
|
|
2509
|
+
}
|
|
2510
|
+
const text = (value, commaAllowed = false) => {
|
|
2511
|
+
if (typeof value !== "string" || !value || value.trim() !== value || /[\u0000-\u001f\u007f]/.test(value) || !commaAllowed && value.includes(",")) {
|
|
2512
|
+
throw new Error("Invalid task list filters");
|
|
2513
|
+
}
|
|
2514
|
+
try {
|
|
2515
|
+
encodeURIComponent(value);
|
|
2516
|
+
} catch {
|
|
2517
|
+
throw new Error("Invalid task list filters");
|
|
2518
|
+
}
|
|
2519
|
+
return value;
|
|
2520
|
+
};
|
|
2521
|
+
const values = (value) => {
|
|
2522
|
+
const items = Array.isArray(value) ? value : [value];
|
|
2523
|
+
if (items.length === 0)
|
|
2524
|
+
throw new Error("Invalid task list filters");
|
|
2525
|
+
return items.map((item) => text(item));
|
|
2526
|
+
};
|
|
232
2527
|
const params = new URLSearchParams;
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (
|
|
236
|
-
params.set("
|
|
237
|
-
if (
|
|
238
|
-
params.set("
|
|
239
|
-
if (
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
2528
|
+
if (Object.hasOwn(captured, "status"))
|
|
2529
|
+
params.set("status", values(captured.status).join(","));
|
|
2530
|
+
if (Object.hasOwn(captured, "taskType"))
|
|
2531
|
+
params.set("task_type", values(captured.taskType).join(","));
|
|
2532
|
+
if (Object.hasOwn(captured, "functionSlug"))
|
|
2533
|
+
params.set("function_slug", text(captured.functionSlug, true));
|
|
2534
|
+
if (Object.hasOwn(captured, "dlq")) {
|
|
2535
|
+
if (typeof captured.dlq !== "boolean")
|
|
2536
|
+
throw new Error("Invalid task list filters");
|
|
2537
|
+
if (captured.dlq)
|
|
2538
|
+
params.set("dlq", "true");
|
|
2539
|
+
}
|
|
2540
|
+
if (Object.hasOwn(captured, "limit")) {
|
|
2541
|
+
if (typeof captured.limit !== "number" || !Number.isSafeInteger(captured.limit) || captured.limit < 1) {
|
|
2542
|
+
throw new Error("Invalid task list filters");
|
|
2543
|
+
}
|
|
2544
|
+
params.set("limit", String(captured.limit));
|
|
2545
|
+
}
|
|
245
2546
|
const query = params.toString();
|
|
246
2547
|
return query.length > 0 ? `?${query}` : "";
|
|
247
2548
|
}
|
|
@@ -260,25 +2561,7 @@ function createQueueQueryString(filters = {}) {
|
|
|
260
2561
|
return query.length > 0 ? `?${query}` : "";
|
|
261
2562
|
}
|
|
262
2563
|
function normalizeSecondsFromOptions(options = {}) {
|
|
263
|
-
|
|
264
|
-
return Math.max(0, Math.floor(options.sleepSeconds));
|
|
265
|
-
if (typeof options.sleep_seconds === "number")
|
|
266
|
-
return Math.max(0, Math.floor(options.sleep_seconds));
|
|
267
|
-
if (typeof options.visibilityTimeoutSec === "number")
|
|
268
|
-
return Math.max(0, Math.floor(options.visibilityTimeoutSec));
|
|
269
|
-
if (typeof options.delayMs === "number")
|
|
270
|
-
return Math.max(0, Math.floor(options.delayMs / 1000));
|
|
271
|
-
return 0;
|
|
272
|
-
}
|
|
273
|
-
function normalizeMessageId(value) {
|
|
274
|
-
const parsed = Number(value);
|
|
275
|
-
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
|
|
276
|
-
}
|
|
277
|
-
function firstRpcValue(value) {
|
|
278
|
-
return isUnknownArray(value) ? value[0] : value;
|
|
279
|
-
}
|
|
280
|
-
function isUnknownArray(value) {
|
|
281
|
-
return Array.isArray(value);
|
|
2564
|
+
return queueSeconds(options);
|
|
282
2565
|
}
|
|
283
2566
|
function valueRecord2(value) {
|
|
284
2567
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
@@ -308,23 +2591,82 @@ function responseNumber(record, key, label) {
|
|
|
308
2591
|
}
|
|
309
2592
|
return value;
|
|
310
2593
|
}
|
|
311
|
-
function responseBoolean(record, key, label) {
|
|
312
|
-
const value = record[key];
|
|
313
|
-
if (typeof value !== "boolean") {
|
|
314
|
-
throw new Error(`Invalid ${label} response: ${key} is required`);
|
|
315
|
-
}
|
|
316
|
-
return value;
|
|
317
|
-
}
|
|
318
2594
|
function decodeVoid(value) {
|
|
319
2595
|
if (value !== undefined)
|
|
320
2596
|
throw new Error("Expected an empty response");
|
|
321
2597
|
}
|
|
2598
|
+
function taskText(value) {
|
|
2599
|
+
if (typeof value !== "string")
|
|
2600
|
+
throw new Error("Invalid task response: expected text");
|
|
2601
|
+
return value;
|
|
2602
|
+
}
|
|
2603
|
+
function taskNumber(value) {
|
|
2604
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
2605
|
+
throw new Error("Invalid task response: expected number");
|
|
2606
|
+
return value;
|
|
2607
|
+
}
|
|
2608
|
+
function taskNullable(value, decode) {
|
|
2609
|
+
return value === null ? null : decode(value);
|
|
2610
|
+
}
|
|
2611
|
+
function taskArray(value, decode) {
|
|
2612
|
+
if (!Array.isArray(value))
|
|
2613
|
+
throw new Error("Invalid task response: expected array");
|
|
2614
|
+
return value.map(decode);
|
|
2615
|
+
}
|
|
2616
|
+
function decodeTaskLog(value) {
|
|
2617
|
+
const data = responseRecord(value, "task log");
|
|
2618
|
+
if (data.stream !== "stdout" && data.stream !== "stderr")
|
|
2619
|
+
throw new Error("Invalid task log response: stream");
|
|
2620
|
+
return {
|
|
2621
|
+
timestamp: taskText(data.timestamp),
|
|
2622
|
+
stream: data.stream,
|
|
2623
|
+
level: taskText(data.level),
|
|
2624
|
+
message: taskText(data.message)
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
function decodeTaskAttempt(value) {
|
|
2628
|
+
const data = responseRecord(value, "task attempt");
|
|
2629
|
+
return {
|
|
2630
|
+
attempt_no: taskNumber(data.attempt_no),
|
|
2631
|
+
status: taskText(data.status),
|
|
2632
|
+
started_at: taskNullable(data.started_at, taskText),
|
|
2633
|
+
completed_at: taskNullable(data.completed_at, taskText),
|
|
2634
|
+
duration_ms: taskNullable(data.duration_ms, taskNumber),
|
|
2635
|
+
response_status: taskNullable(data.response_status, taskNumber),
|
|
2636
|
+
error: taskNullable(data.error, taskText),
|
|
2637
|
+
logs: taskArray(data.logs, decodeTaskLog)
|
|
2638
|
+
};
|
|
2639
|
+
}
|
|
322
2640
|
function decodeTaskDetail(value) {
|
|
323
2641
|
const record = responseRecord(value, "task");
|
|
2642
|
+
for (const key of [
|
|
2643
|
+
"function_slug",
|
|
2644
|
+
"function_version",
|
|
2645
|
+
"error",
|
|
2646
|
+
"error_message",
|
|
2647
|
+
"correlation_id",
|
|
2648
|
+
"business_task_id",
|
|
2649
|
+
"updated_at",
|
|
2650
|
+
"created_at"
|
|
2651
|
+
]) {
|
|
2652
|
+
if (Object.hasOwn(record, key))
|
|
2653
|
+
taskNullable(record[key], taskText);
|
|
2654
|
+
}
|
|
2655
|
+
for (const key of ["attempt", "max_attempts", "progress"]) {
|
|
2656
|
+
if (Object.hasOwn(record, key))
|
|
2657
|
+
taskNullable(record[key], taskNumber);
|
|
2658
|
+
}
|
|
2659
|
+
if (Object.hasOwn(record, "payload"))
|
|
2660
|
+
responseRecord(record.payload, "task payload");
|
|
2661
|
+
if (Object.hasOwn(record, "metadata") && record.metadata !== null)
|
|
2662
|
+
responseRecord(record.metadata, "task metadata");
|
|
324
2663
|
return {
|
|
325
2664
|
...record,
|
|
326
2665
|
id: responseString(record, "id", "task"),
|
|
327
|
-
|
|
2666
|
+
project_ref: responseString(record, "project_ref", "task"),
|
|
2667
|
+
status: responseString(record, "status", "task"),
|
|
2668
|
+
...Object.hasOwn(record, "attempts") ? { attempts: taskArray(record.attempts, decodeTaskAttempt) } : {},
|
|
2669
|
+
...Object.hasOwn(record, "latest_logs") ? { latest_logs: taskArray(record.latest_logs, decodeTaskLog) } : {}
|
|
328
2670
|
};
|
|
329
2671
|
}
|
|
330
2672
|
function decodeTaskDetails(value) {
|
|
@@ -332,22 +2674,95 @@ function decodeTaskDetails(value) {
|
|
|
332
2674
|
throw new Error("Invalid task list response");
|
|
333
2675
|
return value.map(decodeTaskDetail);
|
|
334
2676
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
2677
|
+
|
|
2678
|
+
class SupaCloudTaskResponseError extends SupaCloudApiError {
|
|
2679
|
+
mutationMayHaveApplied;
|
|
2680
|
+
constructor(operation) {
|
|
2681
|
+
const mutation = operation !== "get";
|
|
2682
|
+
super("Invalid task response: could not validate the requested task", 0, {
|
|
2683
|
+
code: operation === "get" ? "TASK_READ_INVALID" : `TASK_${operation.toUpperCase()}_UNCONFIRMED`,
|
|
2684
|
+
mutation_may_have_applied: mutation
|
|
2685
|
+
});
|
|
2686
|
+
this.name = "SupaCloudTaskResponseError";
|
|
2687
|
+
this.mutationMayHaveApplied = mutation;
|
|
2688
|
+
}
|
|
346
2689
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
2690
|
+
|
|
2691
|
+
class SupaCloudTaskDecoderError extends SupaCloudApiError {
|
|
2692
|
+
operation;
|
|
2693
|
+
code = "TASK_RESULT_INVALID";
|
|
2694
|
+
mutationMayHaveApplied;
|
|
2695
|
+
constructor(operation) {
|
|
2696
|
+
const mutation = operation === "cancel" || operation === "retry";
|
|
2697
|
+
super("Task result could not be decoded", 0, {
|
|
2698
|
+
code: "TASK_RESULT_INVALID",
|
|
2699
|
+
mutation_may_have_applied: mutation
|
|
2700
|
+
});
|
|
2701
|
+
this.operation = operation;
|
|
2702
|
+
this.name = "SupaCloudTaskDecoderError";
|
|
2703
|
+
this.mutationMayHaveApplied = mutation;
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
class SupaCloudTaskAuthenticationError extends SupaCloudApiError {
|
|
2707
|
+
mutationMayHaveApplied = false;
|
|
2708
|
+
constructor(code = "TASK_AUTH_INVALID") {
|
|
2709
|
+
super("Task authentication could not be validated", 0, {
|
|
2710
|
+
code,
|
|
2711
|
+
mutation_may_have_applied: false
|
|
2712
|
+
});
|
|
2713
|
+
this.name = "SupaCloudTaskAuthenticationError";
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
function captureTaskId(value) {
|
|
2717
|
+
if (typeof value !== "string" || value.length === 0 || value.trim() !== value || value === "." || value === ".." || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
2718
|
+
throw new Error("Invalid task ID");
|
|
2719
|
+
}
|
|
2720
|
+
try {
|
|
2721
|
+
encodeURIComponent(value);
|
|
2722
|
+
} catch {
|
|
2723
|
+
throw new Error("Invalid task ID");
|
|
2724
|
+
}
|
|
2725
|
+
const candidate = value.startsWith("{") && value.endsWith("}") ? value.slice(1, -1) : value;
|
|
2726
|
+
if (!/^[0-9a-f]{4}(?:-?[0-9a-f]{4}){7}$/i.test(candidate))
|
|
2727
|
+
return value;
|
|
2728
|
+
const hex = candidate.replaceAll("-", "").toLowerCase();
|
|
2729
|
+
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join("-");
|
|
2730
|
+
}
|
|
2731
|
+
function captureTaskDecoder(value) {
|
|
2732
|
+
if (typeof value !== "function")
|
|
2733
|
+
throw new TypeError("Invalid task result decoder");
|
|
2734
|
+
return value;
|
|
2735
|
+
}
|
|
2736
|
+
function decodeTaskResult(task, decoder, operation) {
|
|
2737
|
+
if (!Object.hasOwn(task, "result"))
|
|
2738
|
+
return task;
|
|
2739
|
+
try {
|
|
2740
|
+
const input = task.result === undefined ? undefined : queueJsonSnapshot(task.result);
|
|
2741
|
+
return { ...task, result: decoder(input) };
|
|
2742
|
+
} catch {
|
|
2743
|
+
throw new SupaCloudTaskDecoderError(operation);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
function decodeTaskDetailsWithResult(value, decoder) {
|
|
2747
|
+
return decodeTaskDetails(value).map((task) => decodeTaskResult(task, decoder, "list"));
|
|
2748
|
+
}
|
|
2749
|
+
function decodeBoundTask(value, taskId, operation) {
|
|
2750
|
+
try {
|
|
2751
|
+
const task = decodeTaskDetail(value);
|
|
2752
|
+
if (task.id !== taskId)
|
|
2753
|
+
throw new Error("Mismatched task ID");
|
|
2754
|
+
return task;
|
|
2755
|
+
} catch {
|
|
2756
|
+
throw new SupaCloudTaskResponseError(operation);
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
function decodeQueueMessages(value, queueName) {
|
|
2760
|
+
if (!Array.isArray(value) || value.length > 1e4)
|
|
2761
|
+
throw new SupaCloudQueueError;
|
|
2762
|
+
const messages = value.map((row) => queueMessage(row, { queueName }));
|
|
2763
|
+
if (new Set(messages.map((row) => row.id)).size !== messages.length)
|
|
2764
|
+
throw new SupaCloudQueueError;
|
|
2765
|
+
return messages;
|
|
351
2766
|
}
|
|
352
2767
|
function decodeQueueStats(value) {
|
|
353
2768
|
const record = responseRecord(value, "queue stats");
|
|
@@ -382,116 +2797,6 @@ function decodeQueueInfos(value) {
|
|
|
382
2797
|
throw new Error("Invalid queue info list response");
|
|
383
2798
|
return value.map(decodeQueueInfo);
|
|
384
2799
|
}
|
|
385
|
-
function decodeOAuthServerStatus(value) {
|
|
386
|
-
const record = responseRecord(value, "OAuth Server");
|
|
387
|
-
return {
|
|
388
|
-
...record,
|
|
389
|
-
project_ref: responseString(record, "project_ref", "OAuth Server"),
|
|
390
|
-
account_isolated: responseBoolean(record, "account_isolated", "OAuth Server"),
|
|
391
|
-
enabled: responseBoolean(record, "enabled", "OAuth Server"),
|
|
392
|
-
allow_dynamic_registration: responseBoolean(record, "allow_dynamic_registration", "OAuth Server"),
|
|
393
|
-
issuer: responseString(record, "issuer", "OAuth Server"),
|
|
394
|
-
discovery_url: responseString(record, "discovery_url", "OAuth Server"),
|
|
395
|
-
jwks_url: responseString(record, "jwks_url", "OAuth Server"),
|
|
396
|
-
authorization_endpoint: responseString(record, "authorization_endpoint", "OAuth Server"),
|
|
397
|
-
token_endpoint: responseString(record, "token_endpoint", "OAuth Server")
|
|
398
|
-
};
|
|
399
|
-
}
|
|
400
|
-
function decodeOAuthClient(value) {
|
|
401
|
-
const record = responseRecord(value, "OAuth client");
|
|
402
|
-
return {
|
|
403
|
-
...record,
|
|
404
|
-
client_id: responseString(record, "client_id", "OAuth client")
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
function decodeOAuthClientList(value) {
|
|
408
|
-
const record = responseRecord(value, "OAuth client list");
|
|
409
|
-
const clients = record.clients;
|
|
410
|
-
if (clients === undefined)
|
|
411
|
-
return record;
|
|
412
|
-
if (!Array.isArray(clients))
|
|
413
|
-
throw new Error("Invalid OAuth client list response");
|
|
414
|
-
return { ...record, clients: clients.map(decodeOAuthClient) };
|
|
415
|
-
}
|
|
416
|
-
function decodeSupAuthStepResult(value) {
|
|
417
|
-
const record = responseRecord(value, "SupAuth step");
|
|
418
|
-
return {
|
|
419
|
-
...record,
|
|
420
|
-
step: responseString(record, "step", "SupAuth step"),
|
|
421
|
-
status: responseString(record, "status", "SupAuth step")
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
function decodeSupAuthProvisionResult(value) {
|
|
425
|
-
const record = responseRecord(value, "SupAuth provision");
|
|
426
|
-
const steps = record.steps;
|
|
427
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
428
|
-
throw new Error("Invalid SupAuth provision response");
|
|
429
|
-
}
|
|
430
|
-
return {
|
|
431
|
-
...record,
|
|
432
|
-
projectRef: responseString(record, "projectRef", "SupAuth provision"),
|
|
433
|
-
status: responseString(record, "status", "SupAuth provision"),
|
|
434
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
function decodeSupAuthReconcileResult(value) {
|
|
438
|
-
const record = responseRecord(value, "SupAuth reconcile");
|
|
439
|
-
const steps = record.steps;
|
|
440
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
441
|
-
throw new Error("Invalid SupAuth reconcile response");
|
|
442
|
-
}
|
|
443
|
-
return {
|
|
444
|
-
...record,
|
|
445
|
-
projectRef: responseString(record, "projectRef", "SupAuth reconcile"),
|
|
446
|
-
changed: responseBoolean(record, "changed", "SupAuth reconcile"),
|
|
447
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
function decodeSupAuthRollbackResult(value) {
|
|
451
|
-
const record = responseRecord(value, "SupAuth rollback");
|
|
452
|
-
const steps = record.steps;
|
|
453
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
454
|
-
throw new Error("Invalid SupAuth rollback response");
|
|
455
|
-
}
|
|
456
|
-
return {
|
|
457
|
-
...record,
|
|
458
|
-
projectRef: responseString(record, "projectRef", "SupAuth rollback"),
|
|
459
|
-
status: responseString(record, "status", "SupAuth rollback"),
|
|
460
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
function decodeSupAuthClientConfig(value) {
|
|
464
|
-
const record = responseRecord(value, "SupAuth client config");
|
|
465
|
-
return {
|
|
466
|
-
...record,
|
|
467
|
-
projectRef: responseString(record, "projectRef", "SupAuth client config"),
|
|
468
|
-
supabaseUrl: responseString(record, "supabaseUrl", "SupAuth client config"),
|
|
469
|
-
authUrl: responseString(record, "authUrl", "SupAuth client config"),
|
|
470
|
-
restUrl: responseString(record, "restUrl", "SupAuth client config"),
|
|
471
|
-
storageUrl: responseString(record, "storageUrl", "SupAuth client config"),
|
|
472
|
-
realtimeUrl: responseString(record, "realtimeUrl", "SupAuth client config"),
|
|
473
|
-
functionsUrl: responseString(record, "functionsUrl", "SupAuth client config")
|
|
474
|
-
};
|
|
475
|
-
}
|
|
476
|
-
function decodeSupAuthVerification(value) {
|
|
477
|
-
const record = responseRecord(value, "SupAuth verification");
|
|
478
|
-
const checks = record.checks;
|
|
479
|
-
if (!isUnknownArray(checks))
|
|
480
|
-
throw new Error("Invalid SupAuth verification response");
|
|
481
|
-
return {
|
|
482
|
-
...record,
|
|
483
|
-
projectRef: responseString(record, "projectRef", "SupAuth verification"),
|
|
484
|
-
healthy: responseBoolean(record, "healthy", "SupAuth verification"),
|
|
485
|
-
checks: checks.map((check) => {
|
|
486
|
-
const record2 = responseRecord(check, "SupAuth check");
|
|
487
|
-
return {
|
|
488
|
-
...record2,
|
|
489
|
-
name: responseString(record2, "name", "SupAuth check"),
|
|
490
|
-
status: responseString(record2, "status", "SupAuth check")
|
|
491
|
-
};
|
|
492
|
-
})
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
2800
|
function decodePurgeResult(value) {
|
|
496
2801
|
const record = responseRecord(value, "queue purge");
|
|
497
2802
|
return {
|
|
@@ -499,46 +2804,6 @@ function decodePurgeResult(value) {
|
|
|
499
2804
|
purged: responseNumber(record, "purged", "queue purge")
|
|
500
2805
|
};
|
|
501
2806
|
}
|
|
502
|
-
function normalizeRpcMessage(queueName, value, status) {
|
|
503
|
-
const row = firstRpcValue(value);
|
|
504
|
-
if (!row || typeof row !== "object")
|
|
505
|
-
return null;
|
|
506
|
-
const record = valueRecord2(row);
|
|
507
|
-
const message = record.message && typeof record.message === "object" && !Array.isArray(record.message) ? valueRecord2(record.message) : {};
|
|
508
|
-
const msgId = normalizeMessageId(record.msg_id ?? record.id);
|
|
509
|
-
return {
|
|
510
|
-
...record,
|
|
511
|
-
id: String(msgId),
|
|
512
|
-
msg_id: msgId,
|
|
513
|
-
message,
|
|
514
|
-
payload: message,
|
|
515
|
-
status,
|
|
516
|
-
queue_name: queueName,
|
|
517
|
-
task_type: `queue:${queueName}`
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
function normalizeRpcMessages(queueName, value, status) {
|
|
521
|
-
const rows = isUnknownArray(value) ? value : value == null ? [] : [value];
|
|
522
|
-
return rows.map((row) => normalizeRpcMessage(queueName, row, status)).filter((row) => Boolean(row));
|
|
523
|
-
}
|
|
524
|
-
function normalizeRpcMessageId(value) {
|
|
525
|
-
const row = firstRpcValue(value);
|
|
526
|
-
if (row && typeof row === "object") {
|
|
527
|
-
const record = valueRecord2(row);
|
|
528
|
-
return normalizeMessageId(record.msg_id ?? record.send ?? record.send_batch ?? record.id);
|
|
529
|
-
}
|
|
530
|
-
return normalizeMessageId(row);
|
|
531
|
-
}
|
|
532
|
-
function normalizeRpcMessageIds(value) {
|
|
533
|
-
const rows = isUnknownArray(value) ? value : value == null ? [] : [value];
|
|
534
|
-
return rows.map((row) => normalizeRpcMessageId(row)).filter((id) => id > 0);
|
|
535
|
-
}
|
|
536
|
-
function extractErrorCode(body) {
|
|
537
|
-
if (!body || typeof body !== "object")
|
|
538
|
-
return null;
|
|
539
|
-
const code = valueRecord2(body).code;
|
|
540
|
-
return typeof code === "string" ? code : null;
|
|
541
|
-
}
|
|
542
2807
|
async function readResponseBody(response) {
|
|
543
2808
|
const text = await response.text();
|
|
544
2809
|
if (!text)
|
|
@@ -556,15 +2821,111 @@ async function defaultAccessTokenResolver(supabase) {
|
|
|
556
2821
|
throw error;
|
|
557
2822
|
return data.session?.access_token ?? null;
|
|
558
2823
|
}
|
|
559
|
-
function
|
|
560
|
-
|
|
2824
|
+
function validateTaskProject(record, projectRef) {
|
|
2825
|
+
if (!Object.hasOwn(record, "project_ref") || record.project_ref !== projectRef) {
|
|
2826
|
+
throw new Error("Invalid task response project");
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
var MAX_TASK_TIMER_MS = 2147483647;
|
|
2830
|
+
function taskTimerMs(value, allowZero = false) {
|
|
2831
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < (allowZero ? 0 : 1) || value > MAX_TASK_TIMER_MS) {
|
|
2832
|
+
throw new Error("Invalid task timer interval");
|
|
2833
|
+
}
|
|
2834
|
+
return value;
|
|
2835
|
+
}
|
|
2836
|
+
function captureTaskWaitOptions(options) {
|
|
2837
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
2838
|
+
throw new Error("Invalid task wait options");
|
|
2839
|
+
}
|
|
2840
|
+
const prototype = Object.getPrototypeOf(options);
|
|
2841
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
2842
|
+
throw new Error("Invalid task wait options");
|
|
2843
|
+
let intervalMs;
|
|
2844
|
+
let signal;
|
|
2845
|
+
for (const key of Reflect.ownKeys(options)) {
|
|
2846
|
+
const property = Object.getOwnPropertyDescriptor(options, key);
|
|
2847
|
+
if (key !== "intervalMs" && key !== "signal" || !property || !("value" in property)) {
|
|
2848
|
+
throw new Error("Invalid task wait options");
|
|
2849
|
+
}
|
|
2850
|
+
const value = property.value;
|
|
2851
|
+
if (value === undefined)
|
|
2852
|
+
continue;
|
|
2853
|
+
if (key === "intervalMs")
|
|
2854
|
+
intervalMs = taskTimerMs(value);
|
|
2855
|
+
else {
|
|
2856
|
+
if (!(value instanceof AbortSignal))
|
|
2857
|
+
throw new Error("Invalid task wait options");
|
|
2858
|
+
signal = value;
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
return {
|
|
2862
|
+
...intervalMs === undefined ? {} : { intervalMs },
|
|
2863
|
+
...signal === undefined ? {} : { signal }
|
|
2864
|
+
};
|
|
2865
|
+
}
|
|
2866
|
+
function captureTaskRealtimeSource(value) {
|
|
2867
|
+
if (value === undefined)
|
|
2868
|
+
return null;
|
|
2869
|
+
try {
|
|
2870
|
+
const source = responseRecord(queueJsonSnapshot(value), "task Realtime source");
|
|
2871
|
+
if (Object.keys(source).some((key) => key !== "schema" && key !== "table"))
|
|
2872
|
+
throw new Error;
|
|
2873
|
+
const schema = responseString(source, "schema", "task Realtime source");
|
|
2874
|
+
const table = responseString(source, "table", "task Realtime source");
|
|
2875
|
+
if (![schema, table].every((name) => /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)))
|
|
2876
|
+
throw new Error;
|
|
2877
|
+
return { schema, table };
|
|
2878
|
+
} catch {
|
|
2879
|
+
throw new Error("Invalid task Realtime source");
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
function captureTaskSubscribeOptions(options) {
|
|
2883
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || Object.getPrototypeOf(options) !== Object.prototype && Object.getPrototypeOf(options) !== null) {
|
|
2884
|
+
throw new Error("Invalid task subscription options");
|
|
2885
|
+
}
|
|
2886
|
+
const allowed = new Set([
|
|
2887
|
+
"realtime",
|
|
2888
|
+
"pollingIntervalMs",
|
|
2889
|
+
"realtimeTimeoutMs",
|
|
2890
|
+
"reconcileIntervalMs",
|
|
2891
|
+
"onUpdate",
|
|
2892
|
+
"onStateChange",
|
|
2893
|
+
"onError",
|
|
2894
|
+
"stopOnTerminal"
|
|
2895
|
+
]);
|
|
2896
|
+
for (const key of Reflect.ownKeys(options)) {
|
|
2897
|
+
const property = Object.getOwnPropertyDescriptor(options, key);
|
|
2898
|
+
if (typeof key !== "string" || !allowed.has(key) || !property || !("value" in property)) {
|
|
2899
|
+
throw new Error("Invalid task subscription options");
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
const captured = { ...options };
|
|
2903
|
+
if (typeof captured.onUpdate !== "function" || captured.onStateChange !== undefined && typeof captured.onStateChange !== "function" || captured.onError !== undefined && typeof captured.onError !== "function" || captured.stopOnTerminal !== undefined && typeof captured.stopOnTerminal !== "boolean") {
|
|
2904
|
+
throw new Error("Invalid task subscription options");
|
|
2905
|
+
}
|
|
2906
|
+
const realtime = captureTaskRealtimeSource(captured.realtime);
|
|
2907
|
+
if (realtime)
|
|
2908
|
+
captured.realtime = realtime;
|
|
2909
|
+
return captured;
|
|
2910
|
+
}
|
|
2911
|
+
function normalizeTaskSnapshot(task, taskId, projectRef, decoder) {
|
|
2912
|
+
let value;
|
|
2913
|
+
try {
|
|
2914
|
+
value = decodeBoundTask(queueJsonSnapshot(task), taskId, "get");
|
|
2915
|
+
validateTaskProject(value, projectRef);
|
|
2916
|
+
if (Object.hasOwn(value, "updatedAt"))
|
|
2917
|
+
taskNullable(value.updatedAt, taskText);
|
|
2918
|
+
} catch {
|
|
2919
|
+
throw new SupaCloudTaskResponseError("get");
|
|
2920
|
+
}
|
|
2921
|
+
const decoded = decoder === undefined ? value : decodeTaskResult(value, decoder, "subscribe");
|
|
561
2922
|
return {
|
|
562
|
-
id:
|
|
563
|
-
status:
|
|
564
|
-
progress: typeof
|
|
565
|
-
error: typeof
|
|
566
|
-
updatedAt: typeof
|
|
567
|
-
raw:
|
|
2923
|
+
id: decoded.id,
|
|
2924
|
+
status: decoded.status,
|
|
2925
|
+
progress: typeof decoded.progress === "number" ? decoded.progress : null,
|
|
2926
|
+
error: typeof decoded.error === "string" ? decoded.error : typeof decoded.error_message === "string" ? decoded.error_message : null,
|
|
2927
|
+
updatedAt: typeof decoded.updated_at === "string" ? decoded.updated_at : typeof decoded.updatedAt === "string" ? decoded.updatedAt : null,
|
|
2928
|
+
raw: decoded
|
|
568
2929
|
};
|
|
569
2930
|
}
|
|
570
2931
|
|
|
@@ -573,29 +2934,32 @@ class SupaCloudManagementClient {
|
|
|
573
2934
|
constructor(options) {
|
|
574
2935
|
this.options = options;
|
|
575
2936
|
}
|
|
576
|
-
async resolveAccessToken() {
|
|
2937
|
+
async resolveAccessToken(_signal) {
|
|
577
2938
|
const token = await this.options.getAccessToken();
|
|
578
2939
|
if (!token) {
|
|
579
2940
|
throw new Error("No SupaCloud management API access token available. Pass getAccessToken() or ensure supabase.auth has an active session.");
|
|
580
2941
|
}
|
|
581
2942
|
return token;
|
|
582
2943
|
}
|
|
583
|
-
async request(path, method, body, decode) {
|
|
584
|
-
|
|
585
|
-
const
|
|
2944
|
+
async request(path, method, body, decode, transport = globalThis.fetch.bind(globalThis), signal) {
|
|
2945
|
+
signal?.throwIfAborted();
|
|
2946
|
+
const accessToken = await this.resolveAccessToken(signal);
|
|
2947
|
+
signal?.throwIfAborted();
|
|
2948
|
+
const response = await transport(`${this.options.managementApiUrl}${path}`, {
|
|
586
2949
|
method,
|
|
587
2950
|
headers: {
|
|
588
2951
|
authorization: `Bearer ${accessToken}`,
|
|
589
2952
|
...body !== undefined ? { "content-type": "application/json" } : {}
|
|
590
2953
|
},
|
|
591
|
-
...body !== undefined ? { body: JSON.stringify(body) } : {}
|
|
2954
|
+
...body !== undefined ? { body: JSON.stringify(body) } : {},
|
|
2955
|
+
...signal === undefined ? {} : { signal }
|
|
592
2956
|
});
|
|
593
2957
|
if (response.status === 204)
|
|
594
2958
|
return decode(undefined);
|
|
595
2959
|
const responseBody = await readResponseBody(response);
|
|
596
2960
|
if (!response.ok) {
|
|
597
|
-
const
|
|
598
|
-
const message = typeof
|
|
2961
|
+
const responseRecord = valueRecord2(responseBody);
|
|
2962
|
+
const message = typeof responseRecord.message === "string" ? responseRecord.message : `SupaCloud request failed (${response.status})`;
|
|
599
2963
|
throw new SupaCloudApiError(message, response.status, responseBody);
|
|
600
2964
|
}
|
|
601
2965
|
return decode(responseBody);
|
|
@@ -603,6 +2967,67 @@ class SupaCloudManagementClient {
|
|
|
603
2967
|
}
|
|
604
2968
|
|
|
605
2969
|
class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
2970
|
+
async resolveAccessToken(signal) {
|
|
2971
|
+
signal?.throwIfAborted();
|
|
2972
|
+
let timer;
|
|
2973
|
+
let onAbort = () => {};
|
|
2974
|
+
const aborted = new Promise((_, reject) => {
|
|
2975
|
+
onAbort = () => reject(signal?.reason);
|
|
2976
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2977
|
+
});
|
|
2978
|
+
const timeoutError = new SupaCloudTaskAuthenticationError("TASK_AUTH_TIMEOUT");
|
|
2979
|
+
const deadline = new Promise((_, reject) => {
|
|
2980
|
+
timer = setTimeout(() => reject(timeoutError), 15000);
|
|
2981
|
+
});
|
|
2982
|
+
try {
|
|
2983
|
+
const token = await Promise.race([super.resolveAccessToken(), deadline, aborted]);
|
|
2984
|
+
signal?.throwIfAborted();
|
|
2985
|
+
if (typeof token !== "string" || !/^[\x21-\x7e]+$/.test(token)) {
|
|
2986
|
+
throw new SupaCloudTaskAuthenticationError;
|
|
2987
|
+
}
|
|
2988
|
+
return token;
|
|
2989
|
+
} catch (error) {
|
|
2990
|
+
signal?.throwIfAborted();
|
|
2991
|
+
if (error === timeoutError)
|
|
2992
|
+
throw timeoutError;
|
|
2993
|
+
throw new SupaCloudTaskAuthenticationError;
|
|
2994
|
+
} finally {
|
|
2995
|
+
clearTimeout(timer);
|
|
2996
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
request(path, method, body, decode, _transport, signal) {
|
|
3000
|
+
const operation = method === "POST" ? path.endsWith("/cancel") ? "cancel" : "retry" : "get";
|
|
3001
|
+
const projectRef = this.options.projectRef;
|
|
3002
|
+
const failure = () => new SupaCloudTaskResponseError(operation);
|
|
3003
|
+
const bounded = createBoundedRpcFetch(/./, failure);
|
|
3004
|
+
const transport = async (input, init) => {
|
|
3005
|
+
const response = await bounded(input, init);
|
|
3006
|
+
if (response.status >= 500 || response.ok && response.status !== 200)
|
|
3007
|
+
throw failure();
|
|
3008
|
+
return response;
|
|
3009
|
+
};
|
|
3010
|
+
return super.request(path, method, body, (value) => {
|
|
3011
|
+
try {
|
|
3012
|
+
const rows = Array.isArray(value) ? value : [value];
|
|
3013
|
+
for (const task of rows) {
|
|
3014
|
+
const record = responseRecord(task, "task");
|
|
3015
|
+
validateTaskProject(record, projectRef);
|
|
3016
|
+
}
|
|
3017
|
+
return decode(value);
|
|
3018
|
+
} catch (error) {
|
|
3019
|
+
if (error instanceof SupaCloudTaskDecoderError)
|
|
3020
|
+
throw error;
|
|
3021
|
+
throw failure();
|
|
3022
|
+
}
|
|
3023
|
+
}, transport, signal).then((value) => {
|
|
3024
|
+
signal?.throwIfAborted();
|
|
3025
|
+
return value;
|
|
3026
|
+
}, (error) => {
|
|
3027
|
+
signal?.throwIfAborted();
|
|
3028
|
+
throw error;
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
606
3031
|
createReceipt(taskId, status) {
|
|
607
3032
|
return {
|
|
608
3033
|
taskId,
|
|
@@ -614,8 +3039,20 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
614
3039
|
subscribe: (options) => this.subscribe(taskId, options)
|
|
615
3040
|
};
|
|
616
3041
|
}
|
|
617
|
-
|
|
618
|
-
|
|
3042
|
+
createTypedReceipt(taskId, status, decoder) {
|
|
3043
|
+
return {
|
|
3044
|
+
taskId,
|
|
3045
|
+
status,
|
|
3046
|
+
get: () => this.getTyped(taskId, decoder),
|
|
3047
|
+
wait: (options) => this.waitTyped(taskId, decoder, options),
|
|
3048
|
+
cancel: () => this.cancelTyped(taskId, decoder),
|
|
3049
|
+
retry: () => this.retryTyped(taskId, decoder),
|
|
3050
|
+
subscribe: (options) => this.subscribeTypedInternal(taskId, options, decoder)
|
|
3051
|
+
};
|
|
3052
|
+
}
|
|
3053
|
+
async submitInternal(functionName, options = {}, decoder) {
|
|
3054
|
+
const projectRef = this.options.projectRef;
|
|
3055
|
+
const { body, headers = {}, idempotencyKey, method } = options;
|
|
619
3056
|
const invokeHeaders = {
|
|
620
3057
|
...headers,
|
|
621
3058
|
...idempotencyKey ? { "x-supacloud-idempotency-key": idempotencyKey } : {},
|
|
@@ -623,64 +3060,209 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
623
3060
|
...options.businessTaskId ? { "x-supacloud-business-task-id": options.businessTaskId } : {},
|
|
624
3061
|
...options.metadata ? { "x-supacloud-task-metadata": JSON.stringify(options.metadata) } : {}
|
|
625
3062
|
};
|
|
626
|
-
const
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
3063
|
+
const controller = new AbortController;
|
|
3064
|
+
const failure = () => new SupaCloudTaskSubmitError("Background task submission could not be confirmed", undefined);
|
|
3065
|
+
const timeoutError = new SupaCloudTaskSubmitError("Background task submission timed out; outcome is unconfirmed", undefined);
|
|
3066
|
+
let timer;
|
|
3067
|
+
const deadline = new Promise((_, reject) => {
|
|
3068
|
+
timer = setTimeout(() => {
|
|
3069
|
+
reject(timeoutError);
|
|
3070
|
+
controller.abort(timeoutError);
|
|
3071
|
+
}, 15000);
|
|
630
3072
|
});
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
3073
|
+
let invocation;
|
|
3074
|
+
try {
|
|
3075
|
+
invocation = await Promise.race([
|
|
3076
|
+
this.options.supabase.functions.invoke(functionName, {
|
|
3077
|
+
...body === undefined ? {} : { body },
|
|
3078
|
+
...method === undefined ? {} : { method },
|
|
3079
|
+
headers: invokeHeaders,
|
|
3080
|
+
signal: controller.signal
|
|
3081
|
+
}),
|
|
3082
|
+
deadline
|
|
3083
|
+
]);
|
|
3084
|
+
} catch (error) {
|
|
3085
|
+
if (error === timeoutError)
|
|
3086
|
+
throw timeoutError;
|
|
3087
|
+
throw failure();
|
|
3088
|
+
} finally {
|
|
3089
|
+
clearTimeout(timer);
|
|
3090
|
+
}
|
|
3091
|
+
const { data, error, response } = invocation;
|
|
3092
|
+
const boundedHttpFailure = response instanceof Response && boundedTaskHttpFailures.delete(response);
|
|
3093
|
+
if (error !== null && error !== undefined) {
|
|
3094
|
+
if (error instanceof FunctionsHttpError && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
|
|
3095
|
+
throw error;
|
|
3096
|
+
}
|
|
3097
|
+
if (boundedHttpFailure && response instanceof Response && !response.redirected && response.status >= 400 && response.status < 500 && matchesForeignTaskHttpError(error, response)) {
|
|
3098
|
+
throw new FunctionsHttpError(response);
|
|
3099
|
+
}
|
|
3100
|
+
if (response instanceof Response)
|
|
3101
|
+
response.body?.cancel().catch(() => {});
|
|
3102
|
+
throw failure();
|
|
3103
|
+
}
|
|
3104
|
+
if (!(response instanceof Response) || response.status !== 202 || response.redirected) {
|
|
3105
|
+
if (response instanceof Response)
|
|
3106
|
+
response.body?.cancel().catch(() => {});
|
|
3107
|
+
throw failure();
|
|
3108
|
+
}
|
|
3109
|
+
try {
|
|
3110
|
+
const payload = responseRecord(queueJsonSnapshot(data), "task submission");
|
|
3111
|
+
validateTaskProject(payload, projectRef);
|
|
3112
|
+
const snakeId = Object.hasOwn(payload, "task_id") ? captureTaskId(payload.task_id) : undefined;
|
|
3113
|
+
const camelId = Object.hasOwn(payload, "taskId") ? captureTaskId(payload.taskId) : undefined;
|
|
3114
|
+
const taskId = snakeId ?? camelId;
|
|
3115
|
+
if (taskId === undefined || snakeId !== undefined && camelId !== undefined && snakeId !== camelId) {
|
|
3116
|
+
throw new Error("Invalid task receipt identity");
|
|
3117
|
+
}
|
|
3118
|
+
const status = responseString(payload, "status", "task submission");
|
|
3119
|
+
if (status.trim() !== status || /[\u0000-\u001f\u007f]/.test(status)) {
|
|
3120
|
+
throw new Error("Invalid task receipt status");
|
|
3121
|
+
}
|
|
3122
|
+
return decoder === undefined ? this.createReceipt(taskId, status) : this.createTypedReceipt(taskId, status, decoder);
|
|
3123
|
+
} catch {
|
|
3124
|
+
throw new SupaCloudTaskSubmitError("Background task submission could not be confirmed", data);
|
|
638
3125
|
}
|
|
639
|
-
return this.createReceipt(taskId, String(payload.status ?? "enqueued"));
|
|
640
3126
|
}
|
|
641
|
-
async
|
|
642
|
-
return this.
|
|
3127
|
+
async submit(functionName, options = {}) {
|
|
3128
|
+
return this.submitInternal(functionName, options);
|
|
3129
|
+
}
|
|
3130
|
+
async submitTyped(functionName, decoderOrOptions, optionsOrDecoder) {
|
|
3131
|
+
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
3132
|
+
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder ?? {} : decoderOrOptions;
|
|
3133
|
+
return this.submitInternal(functionName, options, decoder);
|
|
3134
|
+
}
|
|
3135
|
+
getInternal(taskId, decoder, signal) {
|
|
3136
|
+
const captured = captureTaskId(taskId);
|
|
3137
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}`, "GET", undefined, (value) => {
|
|
3138
|
+
const task = decodeBoundTask(value, captured, "get");
|
|
3139
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "get");
|
|
3140
|
+
}, undefined, signal);
|
|
3141
|
+
}
|
|
3142
|
+
async get(taskId, signal) {
|
|
3143
|
+
return this.getInternal(taskId, undefined, signal);
|
|
3144
|
+
}
|
|
3145
|
+
async getTyped(taskId, decoderOrSignal, signalOrDecoder) {
|
|
3146
|
+
const decoder = typeof decoderOrSignal === "function" ? captureTaskDecoder(decoderOrSignal) : captureTaskDecoder(signalOrDecoder);
|
|
3147
|
+
const signal = typeof decoderOrSignal === "function" ? signalOrDecoder : decoderOrSignal;
|
|
3148
|
+
return this.getInternal(taskId, decoder, signal);
|
|
643
3149
|
}
|
|
644
3150
|
async list(filters = {}) {
|
|
645
3151
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET", undefined, decodeTaskDetails);
|
|
646
3152
|
}
|
|
3153
|
+
async listTyped(decoderOrFilters, filtersOrDecoder) {
|
|
3154
|
+
const decoder = typeof decoderOrFilters === "function" ? captureTaskDecoder(decoderOrFilters) : captureTaskDecoder(filtersOrDecoder);
|
|
3155
|
+
const filters = typeof decoderOrFilters === "function" ? filtersOrDecoder : decoderOrFilters;
|
|
3156
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET", undefined, (value) => decodeTaskDetailsWithResult(value, decoder));
|
|
3157
|
+
}
|
|
3158
|
+
cancelInternal(taskId, decoder) {
|
|
3159
|
+
const captured = captureTaskId(taskId);
|
|
3160
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}/cancel`, "POST", undefined, (value) => {
|
|
3161
|
+
const task = decodeBoundTask(value, captured, "cancel");
|
|
3162
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "cancel");
|
|
3163
|
+
});
|
|
3164
|
+
}
|
|
647
3165
|
async cancel(taskId) {
|
|
648
|
-
return this.
|
|
3166
|
+
return this.cancelInternal(taskId);
|
|
3167
|
+
}
|
|
3168
|
+
async cancelTyped(taskId, decoder) {
|
|
3169
|
+
return this.cancelInternal(taskId, captureTaskDecoder(decoder));
|
|
3170
|
+
}
|
|
3171
|
+
retryInternal(taskId, decoder) {
|
|
3172
|
+
const captured = captureTaskId(taskId);
|
|
3173
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}/retry`, "POST", undefined, (value) => {
|
|
3174
|
+
const task = decodeBoundTask(value, captured, "retry");
|
|
3175
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "retry");
|
|
3176
|
+
});
|
|
649
3177
|
}
|
|
650
3178
|
async retry(taskId) {
|
|
651
|
-
return this.
|
|
3179
|
+
return this.retryInternal(taskId);
|
|
3180
|
+
}
|
|
3181
|
+
async retryTyped(taskId, decoder) {
|
|
3182
|
+
return this.retryInternal(taskId, captureTaskDecoder(decoder));
|
|
652
3183
|
}
|
|
653
3184
|
async listDlq(limit = 100) {
|
|
654
|
-
return this.
|
|
3185
|
+
return this.list({ dlq: true, limit });
|
|
655
3186
|
}
|
|
656
|
-
async
|
|
657
|
-
|
|
3187
|
+
async listDlqTyped(decoder, limit = 100) {
|
|
3188
|
+
return this.listTyped({ dlq: true, limit }, captureTaskDecoder(decoder));
|
|
3189
|
+
}
|
|
3190
|
+
async waitInternal(taskId, decoder, options = {}) {
|
|
3191
|
+
options = captureTaskWaitOptions(options);
|
|
3192
|
+
const { signal } = options;
|
|
3193
|
+
const intervalMs = taskTimerMs(options.intervalMs === undefined ? this.options.pollingIntervalMs : options.intervalMs);
|
|
658
3194
|
while (true) {
|
|
659
|
-
if (
|
|
660
|
-
throw
|
|
3195
|
+
if (signal?.aborted) {
|
|
3196
|
+
throw signal.reason;
|
|
661
3197
|
}
|
|
662
|
-
const task = await this.get(taskId);
|
|
663
|
-
if (TERMINAL_STATUSES.has(
|
|
3198
|
+
const task = decoder === undefined ? await this.get(taskId, signal) : await this.getTyped(taskId, decoder, signal);
|
|
3199
|
+
if (TERMINAL_STATUSES.has(task.status))
|
|
664
3200
|
return task;
|
|
665
|
-
await waitForPollingInterval(intervalMs,
|
|
3201
|
+
await waitForPollingInterval(intervalMs, signal);
|
|
666
3202
|
}
|
|
667
3203
|
}
|
|
3204
|
+
async wait(taskId, options = {}) {
|
|
3205
|
+
return this.waitInternal(taskId, undefined, options);
|
|
3206
|
+
}
|
|
3207
|
+
async waitTyped(taskId, decoderOrOptions, optionsOrDecoder) {
|
|
3208
|
+
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
3209
|
+
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
|
|
3210
|
+
return this.waitInternal(taskId, decoder, options);
|
|
3211
|
+
}
|
|
668
3212
|
subscribe(taskId, options) {
|
|
3213
|
+
return this.subscribeInternal(taskId, options);
|
|
3214
|
+
}
|
|
3215
|
+
subscribeTyped(taskId, decoderOrOptions, optionsOrDecoder) {
|
|
3216
|
+
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
3217
|
+
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
|
|
3218
|
+
return this.subscribeTypedInternal(taskId, options, decoder);
|
|
3219
|
+
}
|
|
3220
|
+
subscribeTypedInternal(taskId, options, decoder) {
|
|
3221
|
+
return this.subscribeInternal(taskId, options, decoder);
|
|
3222
|
+
}
|
|
3223
|
+
subscribeInternal(taskId, options, decoder) {
|
|
3224
|
+
taskId = captureTaskId(taskId);
|
|
3225
|
+
options = captureTaskSubscribeOptions(options);
|
|
3226
|
+
const realtime = captureTaskRealtimeSource(options.realtime);
|
|
3227
|
+
const projectRef = this.options.projectRef;
|
|
669
3228
|
let closed = false;
|
|
670
3229
|
let channel = null;
|
|
671
3230
|
let pollTimer = null;
|
|
672
3231
|
let realtimeTimeoutTimer = null;
|
|
673
3232
|
let reconcileTimer = null;
|
|
674
3233
|
let mode = "connecting";
|
|
675
|
-
const pollingIntervalMs = options.pollingIntervalMs
|
|
676
|
-
const realtimeTimeoutMs = options.realtimeTimeoutMs
|
|
677
|
-
const reconcileIntervalMs = options.reconcileIntervalMs
|
|
3234
|
+
const pollingIntervalMs = taskTimerMs(options.pollingIntervalMs === undefined ? this.options.pollingIntervalMs : options.pollingIntervalMs);
|
|
3235
|
+
const realtimeTimeoutMs = taskTimerMs(options.realtimeTimeoutMs === undefined ? 1e4 : options.realtimeTimeoutMs, true);
|
|
3236
|
+
const reconcileIntervalMs = taskTimerMs(options.reconcileIntervalMs === undefined ? Math.min(MAX_TASK_TIMER_MS, Math.max(30000, pollingIntervalMs * 10)) : options.reconcileIntervalMs, true);
|
|
678
3237
|
const stopOnTerminal = options.stopOnTerminal ?? true;
|
|
3238
|
+
const readController = new AbortController;
|
|
3239
|
+
const readTask = async (signal) => decoder === undefined ? await this.get(taskId, signal) : await this.getTyped(taskId, decoder, signal);
|
|
3240
|
+
let callbackFailed = false;
|
|
3241
|
+
const callCallback = (callback, onFailure) => {
|
|
3242
|
+
try {
|
|
3243
|
+
const result = callback();
|
|
3244
|
+
if (result !== undefined)
|
|
3245
|
+
Promise.resolve(result).catch(onFailure);
|
|
3246
|
+
} catch (error) {
|
|
3247
|
+
onFailure(error);
|
|
3248
|
+
}
|
|
3249
|
+
};
|
|
3250
|
+
const handleCallbackFailure = (error, report = true) => {
|
|
3251
|
+
if (callbackFailed)
|
|
3252
|
+
return;
|
|
3253
|
+
callbackFailed = true;
|
|
3254
|
+
close();
|
|
3255
|
+
if (report)
|
|
3256
|
+
reportError(error);
|
|
3257
|
+
};
|
|
3258
|
+
const reportError = (error) => {
|
|
3259
|
+
callCallback(() => options.onError?.(error), (cause) => handleCallbackFailure(cause, false));
|
|
3260
|
+
};
|
|
679
3261
|
const setMode = (next, details) => {
|
|
680
|
-
if (closed || mode === next)
|
|
3262
|
+
if (closed && next !== "closed" || mode === next)
|
|
681
3263
|
return;
|
|
682
3264
|
mode = next;
|
|
683
|
-
options.onStateChange?.(next, details);
|
|
3265
|
+
callCallback(() => options.onStateChange?.(next, details), handleCallbackFailure);
|
|
684
3266
|
};
|
|
685
3267
|
const stopPolling = () => {
|
|
686
3268
|
if (pollTimer) {
|
|
@@ -704,22 +3286,38 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
704
3286
|
if (channel) {
|
|
705
3287
|
const current = channel;
|
|
706
3288
|
channel = null;
|
|
707
|
-
|
|
3289
|
+
try {
|
|
3290
|
+
await this.options.supabase.removeChannel(current);
|
|
3291
|
+
} catch (error) {
|
|
3292
|
+
reportError(error);
|
|
3293
|
+
}
|
|
708
3294
|
}
|
|
709
3295
|
};
|
|
710
3296
|
const close = async () => {
|
|
711
3297
|
if (closed)
|
|
712
3298
|
return;
|
|
3299
|
+
closed = true;
|
|
3300
|
+
readController.abort();
|
|
713
3301
|
stopPolling();
|
|
714
3302
|
stopRealtimeTimeout();
|
|
715
3303
|
stopReconcile();
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
3304
|
+
try {
|
|
3305
|
+
await teardownRealtime();
|
|
3306
|
+
} finally {
|
|
3307
|
+
setMode("closed");
|
|
3308
|
+
}
|
|
719
3309
|
};
|
|
720
3310
|
const emitTask = (task) => {
|
|
721
|
-
|
|
722
|
-
|
|
3311
|
+
if (closed)
|
|
3312
|
+
return;
|
|
3313
|
+
let snapshot;
|
|
3314
|
+
try {
|
|
3315
|
+
snapshot = normalizeTaskSnapshot(task, taskId, projectRef, decoder);
|
|
3316
|
+
} catch (error) {
|
|
3317
|
+
reportError(error);
|
|
3318
|
+
return;
|
|
3319
|
+
}
|
|
3320
|
+
callCallback(() => options.onUpdate(snapshot), handleCallbackFailure);
|
|
723
3321
|
if (stopOnTerminal && TERMINAL_STATUSES.has(snapshot.status)) {
|
|
724
3322
|
close();
|
|
725
3323
|
}
|
|
@@ -728,10 +3326,11 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
728
3326
|
if (closed)
|
|
729
3327
|
return;
|
|
730
3328
|
try {
|
|
731
|
-
const task = await
|
|
3329
|
+
const task = await readTask(readController.signal);
|
|
732
3330
|
emitTask(task);
|
|
733
3331
|
} catch (error) {
|
|
734
|
-
|
|
3332
|
+
if (!closed)
|
|
3333
|
+
reportError(error);
|
|
735
3334
|
} finally {
|
|
736
3335
|
if (!closed && mode === "polling") {
|
|
737
3336
|
pollTimer = setTimeout(() => {
|
|
@@ -744,9 +3343,10 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
744
3343
|
if (closed || mode !== "realtime")
|
|
745
3344
|
return;
|
|
746
3345
|
try {
|
|
747
|
-
emitTask(await
|
|
3346
|
+
emitTask(await readTask(readController.signal));
|
|
748
3347
|
} catch (error) {
|
|
749
|
-
|
|
3348
|
+
if (!closed)
|
|
3349
|
+
reportError(error);
|
|
750
3350
|
} finally {
|
|
751
3351
|
if (!closed && mode === "realtime") {
|
|
752
3352
|
reconcileTimer = setTimeout(() => {
|
|
@@ -772,26 +3372,42 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
772
3372
|
setMode("polling", { error });
|
|
773
3373
|
pollOnce();
|
|
774
3374
|
};
|
|
3375
|
+
const subscription = {
|
|
3376
|
+
get connectionState() {
|
|
3377
|
+
return mode;
|
|
3378
|
+
},
|
|
3379
|
+
unsubscribe() {
|
|
3380
|
+
close();
|
|
3381
|
+
}
|
|
3382
|
+
};
|
|
3383
|
+
if (!realtime) {
|
|
3384
|
+
startPolling();
|
|
3385
|
+
return subscription;
|
|
3386
|
+
}
|
|
775
3387
|
channel = this.options.supabase.channel(`supacloud-task:${this.options.projectRef}:${taskId}`).on("postgres_changes", {
|
|
776
3388
|
event: "*",
|
|
777
|
-
schema:
|
|
778
|
-
table:
|
|
3389
|
+
schema: realtime.schema,
|
|
3390
|
+
table: realtime.table,
|
|
779
3391
|
filter: `id=eq.${taskId}`
|
|
780
3392
|
}, (payload) => {
|
|
781
3393
|
const next = payload.new && Object.keys(payload.new).length > 0 ? payload.new : payload.old;
|
|
782
3394
|
if (next)
|
|
783
3395
|
emitTask(next);
|
|
784
|
-
})
|
|
3396
|
+
});
|
|
3397
|
+
channel.subscribe(async (status, error) => {
|
|
785
3398
|
if (closed)
|
|
786
3399
|
return;
|
|
787
3400
|
if (status === "SUBSCRIBED") {
|
|
788
3401
|
stopPolling();
|
|
789
3402
|
stopRealtimeTimeout();
|
|
790
3403
|
setMode("realtime");
|
|
3404
|
+
if (closed)
|
|
3405
|
+
return;
|
|
791
3406
|
try {
|
|
792
|
-
emitTask(await
|
|
3407
|
+
emitTask(await readTask(readController.signal));
|
|
793
3408
|
} catch (err) {
|
|
794
|
-
|
|
3409
|
+
if (!closed)
|
|
3410
|
+
reportError(err);
|
|
795
3411
|
}
|
|
796
3412
|
startReconcile();
|
|
797
3413
|
return;
|
|
@@ -801,7 +3417,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
801
3417
|
startPolling(error);
|
|
802
3418
|
}
|
|
803
3419
|
});
|
|
804
|
-
if (realtimeTimeoutMs > 0) {
|
|
3420
|
+
if (!closed && realtimeTimeoutMs > 0) {
|
|
805
3421
|
realtimeTimeoutTimer = setTimeout(() => {
|
|
806
3422
|
if (!closed && mode === "connecting") {
|
|
807
3423
|
teardownRealtime().finally(() => {
|
|
@@ -811,14 +3427,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
811
3427
|
}, realtimeTimeoutMs);
|
|
812
3428
|
}
|
|
813
3429
|
setMode("connecting");
|
|
814
|
-
return
|
|
815
|
-
get connectionState() {
|
|
816
|
-
return mode;
|
|
817
|
-
},
|
|
818
|
-
unsubscribe() {
|
|
819
|
-
close();
|
|
820
|
-
}
|
|
821
|
-
};
|
|
3430
|
+
return subscription;
|
|
822
3431
|
}
|
|
823
3432
|
}
|
|
824
3433
|
|
|
@@ -827,62 +3436,81 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
827
3436
|
constructor(options, name) {
|
|
828
3437
|
super(options);
|
|
829
3438
|
this.name = name;
|
|
3439
|
+
if (typeof name !== "string" || !/^[a-z0-9][a-z0-9_-]{0,127}$/.test(name) || name.startsWith("supacloud_internal_"))
|
|
3440
|
+
throw new SupaCloudQueueError;
|
|
830
3441
|
}
|
|
831
3442
|
get encodedName() {
|
|
832
3443
|
return encodeURIComponent(this.name);
|
|
833
3444
|
}
|
|
834
3445
|
async rpc(fn, params, decode) {
|
|
835
3446
|
const scopedClient = this.options.supabase.schema("pgmq_public");
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
3447
|
+
try {
|
|
3448
|
+
const rpcResult = await scopedClient.rpc(fn, params).retry(false);
|
|
3449
|
+
const { data, error } = rpcResult;
|
|
3450
|
+
if (error)
|
|
3451
|
+
throw new SupaCloudQueueError(true, "QUEUE_RPC_FAILED");
|
|
3452
|
+
return decode(data);
|
|
3453
|
+
} catch (error) {
|
|
3454
|
+
throw new SupaCloudQueueError(true, error instanceof SupaCloudQueueError ? error.code ?? "QUEUE_CONTRACT_INVALID" : "QUEUE_RPC_FAILED");
|
|
3455
|
+
}
|
|
841
3456
|
}
|
|
842
3457
|
async send(payload = {}, options = {}) {
|
|
3458
|
+
const captured = queueJsonSnapshot(payload);
|
|
843
3459
|
const msgId = await this.rpc("send", {
|
|
844
3460
|
queue_name: this.name,
|
|
845
|
-
message:
|
|
3461
|
+
message: captured,
|
|
846
3462
|
sleep_seconds: normalizeSecondsFromOptions(options)
|
|
847
|
-
},
|
|
3463
|
+
}, queueRpcId);
|
|
848
3464
|
return {
|
|
849
3465
|
id: String(msgId),
|
|
850
3466
|
msg_id: msgId,
|
|
851
3467
|
queue_name: this.name,
|
|
852
3468
|
status: "pending",
|
|
853
|
-
payload
|
|
3469
|
+
payload: captured
|
|
854
3470
|
};
|
|
855
3471
|
}
|
|
856
3472
|
async sendBatch(messages, options = {}) {
|
|
3473
|
+
if (!Array.isArray(messages) || messages.length === 0 || messages.length > 1e4)
|
|
3474
|
+
throw new SupaCloudQueueError;
|
|
3475
|
+
const captured = queueJsonSnapshot(messages);
|
|
3476
|
+
if (!Array.isArray(captured))
|
|
3477
|
+
throw new SupaCloudQueueError;
|
|
857
3478
|
const ids = await this.rpc("send_batch", {
|
|
858
3479
|
queue_name: this.name,
|
|
859
|
-
messages,
|
|
3480
|
+
messages: captured,
|
|
860
3481
|
sleep_seconds: normalizeSecondsFromOptions(options)
|
|
861
|
-
},
|
|
862
|
-
return ids.map((msgId, index) =>
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
3482
|
+
}, (value) => queueRpcIds(value, captured.length));
|
|
3483
|
+
return ids.map((msgId, index) => {
|
|
3484
|
+
const payload = captured[index];
|
|
3485
|
+
if (payload === undefined)
|
|
3486
|
+
throw new SupaCloudQueueError(true);
|
|
3487
|
+
return {
|
|
3488
|
+
id: msgId,
|
|
3489
|
+
msg_id: msgId,
|
|
3490
|
+
queue_name: this.name,
|
|
3491
|
+
status: "pending",
|
|
3492
|
+
payload
|
|
3493
|
+
};
|
|
3494
|
+
});
|
|
869
3495
|
}
|
|
870
3496
|
async read(options = {}) {
|
|
3497
|
+
const count = queueReadCount(options);
|
|
871
3498
|
return this.rpc("read", {
|
|
872
3499
|
queue_name: this.name,
|
|
873
3500
|
sleep_seconds: normalizeSecondsFromOptions(options),
|
|
874
|
-
n:
|
|
875
|
-
}, (value) =>
|
|
3501
|
+
n: count
|
|
3502
|
+
}, (value) => queueRpcMessages(this.name, value, count, "leased"));
|
|
876
3503
|
}
|
|
877
3504
|
async receive(options = {}) {
|
|
3505
|
+
queueReadCount(options, true);
|
|
878
3506
|
const messages = await this.read({ ...options, n: 1 });
|
|
879
3507
|
return messages[0] ?? null;
|
|
880
3508
|
}
|
|
881
3509
|
async pop() {
|
|
882
|
-
return this.rpc("pop", { queue_name: this.name }, (value) =>
|
|
3510
|
+
return this.rpc("pop", { queue_name: this.name }, (value) => queueRpcMessages(this.name, value, 1, "deleted")[0] ?? null);
|
|
883
3511
|
}
|
|
884
3512
|
async list(filters = {}) {
|
|
885
|
-
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages${createQueueQueryString(filters)}`, "GET", undefined, decodeQueueMessages);
|
|
3513
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages${createQueueQueryString(filters)}`, "GET", undefined, (value) => decodeQueueMessages(value, this.name));
|
|
886
3514
|
}
|
|
887
3515
|
async listFailed(limit = 100) {
|
|
888
3516
|
return this.list({ archived: true, dlq: true, limit });
|
|
@@ -900,29 +3528,35 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
900
3528
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/settings`, "PATCH", settings, decodeQueueSettings);
|
|
901
3529
|
}
|
|
902
3530
|
async archive(messageId) {
|
|
903
|
-
const msgId =
|
|
3531
|
+
const msgId = queueMessageId(messageId);
|
|
904
3532
|
const success = await this.rpc("archive", {
|
|
905
3533
|
queue_name: this.name,
|
|
906
3534
|
message_id: msgId
|
|
907
|
-
},
|
|
3535
|
+
}, queueRpcBoolean);
|
|
908
3536
|
return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "archived", success };
|
|
909
3537
|
}
|
|
910
3538
|
async ack(messageId) {
|
|
911
3539
|
return this.archive(messageId);
|
|
912
3540
|
}
|
|
913
3541
|
async delete(messageId) {
|
|
914
|
-
const msgId =
|
|
3542
|
+
const msgId = queueMessageId(messageId);
|
|
915
3543
|
const success = await this.rpc("delete", {
|
|
916
3544
|
queue_name: this.name,
|
|
917
3545
|
message_id: msgId
|
|
918
|
-
},
|
|
3546
|
+
}, queueRpcBoolean);
|
|
919
3547
|
return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "deleted", success };
|
|
920
3548
|
}
|
|
921
3549
|
async release(messageId, options = {}) {
|
|
922
|
-
|
|
3550
|
+
const msgId = queueMessageId(messageId);
|
|
3551
|
+
const body = {
|
|
923
3552
|
sleep_seconds: normalizeSecondsFromOptions(options),
|
|
924
3553
|
...options.error ? { error: options.error } : {}
|
|
925
|
-
}
|
|
3554
|
+
};
|
|
3555
|
+
try {
|
|
3556
|
+
return await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}/release`, "POST", body, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
3557
|
+
} catch {
|
|
3558
|
+
throw new SupaCloudQueueError(true, "QUEUE_MANAGEMENT_FAILED");
|
|
3559
|
+
}
|
|
926
3560
|
}
|
|
927
3561
|
async purge() {
|
|
928
3562
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/purge`, "POST", undefined, decodePurgeResult);
|
|
@@ -931,10 +3565,12 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
931
3565
|
return this.archive(messageId);
|
|
932
3566
|
}
|
|
933
3567
|
async get(messageId) {
|
|
934
|
-
|
|
3568
|
+
const msgId = queueMessageId(messageId);
|
|
3569
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}`, "GET", undefined, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
935
3570
|
}
|
|
936
3571
|
async retry(messageId) {
|
|
937
|
-
|
|
3572
|
+
const msgId = queueMessageId(messageId);
|
|
3573
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}/retry`, "POST", undefined, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
938
3574
|
}
|
|
939
3575
|
}
|
|
940
3576
|
|
|
@@ -949,97 +3585,6 @@ class SupaCloudQueuesClient extends SupaCloudManagementClient {
|
|
|
949
3585
|
await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${encodeURIComponent(queueName)}`, "DELETE", undefined, decodeVoid);
|
|
950
3586
|
}
|
|
951
3587
|
}
|
|
952
|
-
|
|
953
|
-
class SupaCloudOAuthServerClient extends SupaCloudManagementClient {
|
|
954
|
-
async getStatus() {
|
|
955
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-server`, "GET", undefined, decodeOAuthServerStatus);
|
|
956
|
-
}
|
|
957
|
-
async migrateToOidc(options = {}) {
|
|
958
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-server/migrate`, "POST", {
|
|
959
|
-
allow_dynamic_registration: options.allowDynamicRegistration === true,
|
|
960
|
-
...options.authorizationPath === undefined ? {} : { authorization_path: options.authorizationPath }
|
|
961
|
-
}, decodeOAuthServerStatus);
|
|
962
|
-
}
|
|
963
|
-
async getDiscovery() {
|
|
964
|
-
const status = await this.getStatus();
|
|
965
|
-
const response = await fetch(status.discovery_url);
|
|
966
|
-
if (!response.ok)
|
|
967
|
-
throw new Error(`SupaCloud OIDC discovery failed (${response.status})`);
|
|
968
|
-
const payload = await response.json();
|
|
969
|
-
return valueRecord2(payload);
|
|
970
|
-
}
|
|
971
|
-
async getJwks() {
|
|
972
|
-
const status = await this.getStatus();
|
|
973
|
-
const response = await fetch(status.jwks_url);
|
|
974
|
-
if (!response.ok)
|
|
975
|
-
throw new Error(`SupaCloud JWKS fetch failed (${response.status})`);
|
|
976
|
-
const payload = await response.json();
|
|
977
|
-
return valueRecord2(payload);
|
|
978
|
-
}
|
|
979
|
-
async buildAuthorizeUrl(options) {
|
|
980
|
-
const status = await this.getStatus();
|
|
981
|
-
const url = new URL(status.authorization_endpoint);
|
|
982
|
-
url.searchParams.set("client_id", options.clientId);
|
|
983
|
-
url.searchParams.set("redirect_uri", options.redirectUri);
|
|
984
|
-
url.searchParams.set("response_type", options.responseType ?? "code");
|
|
985
|
-
const scope = Array.isArray(options.scope) ? options.scope.join(" ") : options.scope;
|
|
986
|
-
if (scope)
|
|
987
|
-
url.searchParams.set("scope", scope);
|
|
988
|
-
if (options.state)
|
|
989
|
-
url.searchParams.set("state", options.state);
|
|
990
|
-
if (options.codeChallenge)
|
|
991
|
-
url.searchParams.set("code_challenge", options.codeChallenge);
|
|
992
|
-
if (options.codeChallengeMethod)
|
|
993
|
-
url.searchParams.set("code_challenge_method", options.codeChallengeMethod);
|
|
994
|
-
if (options.nonce)
|
|
995
|
-
url.searchParams.set("nonce", options.nonce);
|
|
996
|
-
if (options.resource)
|
|
997
|
-
url.searchParams.set("resource", options.resource);
|
|
998
|
-
return url.toString();
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
class SupaCloudOAuthClientsClient extends SupaCloudManagementClient {
|
|
1003
|
-
async list() {
|
|
1004
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients`, "GET", undefined, decodeOAuthClientList);
|
|
1005
|
-
}
|
|
1006
|
-
async create(input) {
|
|
1007
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients`, "POST", input, decodeOAuthClient);
|
|
1008
|
-
}
|
|
1009
|
-
async get(clientId) {
|
|
1010
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "GET", undefined, decodeOAuthClient);
|
|
1011
|
-
}
|
|
1012
|
-
async update(clientId, patch) {
|
|
1013
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "PUT", patch, decodeOAuthClient);
|
|
1014
|
-
}
|
|
1015
|
-
async delete(clientId) {
|
|
1016
|
-
await this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "DELETE", undefined, decodeVoid);
|
|
1017
|
-
}
|
|
1018
|
-
async regenerateSecret(clientId) {
|
|
1019
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}/regenerate-secret`, "POST", undefined, decodeOAuthClient);
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
class SupaCloudSupAuthClient extends SupaCloudManagementClient {
|
|
1024
|
-
get basePath() {
|
|
1025
|
-
return `/v1/projects/${this.options.projectRef}/supauth`;
|
|
1026
|
-
}
|
|
1027
|
-
async provision(options = {}) {
|
|
1028
|
-
return this.request(`${this.basePath}/provision`, "POST", options, decodeSupAuthProvisionResult);
|
|
1029
|
-
}
|
|
1030
|
-
async reconcile(options = {}) {
|
|
1031
|
-
return this.request(`${this.basePath}/reconcile`, "POST", options, decodeSupAuthReconcileResult);
|
|
1032
|
-
}
|
|
1033
|
-
async rollback() {
|
|
1034
|
-
return this.request(`${this.basePath}/rollback`, "POST", undefined, decodeSupAuthRollbackResult);
|
|
1035
|
-
}
|
|
1036
|
-
async getClientConfig() {
|
|
1037
|
-
return this.request(`${this.basePath}/client-config`, "GET", undefined, decodeSupAuthClientConfig);
|
|
1038
|
-
}
|
|
1039
|
-
async verify() {
|
|
1040
|
-
return this.request(`${this.basePath}/verify`, "GET", undefined, decodeSupAuthVerification);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
3588
|
function createSupaCloudClient(options) {
|
|
1044
3589
|
const normalized = {
|
|
1045
3590
|
...options,
|
|
@@ -1050,7 +3595,6 @@ function createSupaCloudClient(options) {
|
|
|
1050
3595
|
const tasks = new SupaCloudTasksClient(normalized);
|
|
1051
3596
|
const oauthServer = new SupaCloudOAuthServerClient(normalized);
|
|
1052
3597
|
const oauthClients = new SupaCloudOAuthClientsClient(normalized);
|
|
1053
|
-
const supauth = new SupaCloudSupAuthClient(normalized);
|
|
1054
3598
|
const queues = new SupaCloudQueuesClient(normalized);
|
|
1055
3599
|
const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
|
|
1056
3600
|
const commands2 = new SupaCloudCommandsClient(options.supabase);
|
|
@@ -1067,7 +3611,6 @@ function createSupaCloudClient(options) {
|
|
|
1067
3611
|
workflows: workflows2,
|
|
1068
3612
|
commands: commands2,
|
|
1069
3613
|
artifacts: artifacts2,
|
|
1070
|
-
supauth,
|
|
1071
3614
|
queues,
|
|
1072
3615
|
queue: (name) => new SupaCloudQueueClient(normalized, name),
|
|
1073
3616
|
functions: {
|
|
@@ -1077,10 +3620,38 @@ function createSupaCloudClient(options) {
|
|
|
1077
3620
|
}
|
|
1078
3621
|
export {
|
|
1079
3622
|
SupaCloudApiError,
|
|
3623
|
+
SupaCloudArtifactLinkError,
|
|
3624
|
+
SupaCloudArtifactReadError,
|
|
3625
|
+
SupaCloudArtifactRegisterError,
|
|
1080
3626
|
SupaCloudArtifactsClient,
|
|
3627
|
+
SupaCloudCommandReadError,
|
|
3628
|
+
SupaCloudCommandSubmitError,
|
|
1081
3629
|
SupaCloudCommandsClient,
|
|
3630
|
+
SupaCloudOAuthClientError,
|
|
3631
|
+
SupaCloudOAuthClientsClient,
|
|
3632
|
+
SupaCloudOAuthServerClient,
|
|
3633
|
+
SupaCloudOAuthServerError,
|
|
3634
|
+
SupaCloudQueueError,
|
|
3635
|
+
SupaCloudTaskAuthenticationError,
|
|
3636
|
+
SupaCloudTaskDecoderError as SupaCloudTaskDecodeError,
|
|
3637
|
+
SupaCloudTaskDecoderError,
|
|
3638
|
+
SupaCloudTaskResponseError,
|
|
1082
3639
|
SupaCloudTaskSubmitError,
|
|
3640
|
+
SupaCloudWorkflowAdvanceError,
|
|
3641
|
+
SupaCloudWorkflowCancelError,
|
|
3642
|
+
SupaCloudWorkflowClaimError,
|
|
3643
|
+
SupaCloudWorkflowClaimInputError,
|
|
3644
|
+
SupaCloudWorkflowCompleteError,
|
|
3645
|
+
SupaCloudWorkflowEventsError,
|
|
3646
|
+
SupaCloudWorkflowFailError,
|
|
3647
|
+
SupaCloudWorkflowReadError,
|
|
3648
|
+
SupaCloudWorkflowRetryError,
|
|
3649
|
+
SupaCloudWorkflowStartError,
|
|
1083
3650
|
SupaCloudWorkflowsClient,
|
|
3651
|
+
createSupaCloudArtifactFetch,
|
|
1084
3652
|
createSupaCloudClient,
|
|
1085
|
-
|
|
3653
|
+
createSupaCloudCommandFetch,
|
|
3654
|
+
createSupaCloudOAuthFetch,
|
|
3655
|
+
createSupaCloudTaskFetch,
|
|
3656
|
+
createSupaCloudWorkflowFetch
|
|
1086
3657
|
};
|