@sylphx/sdk 0.19.2 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tasks.mjs ADDED
@@ -0,0 +1,1895 @@
1
+ // src/connection-url.ts
2
+ var SYLPHX_PROTOCOL = "sylphx:";
3
+ var DEFAULT_VERSION = "v1";
4
+ var CREDENTIAL_REGEX = /^(pk|sk)_(dev|stg|prod|prev)(?:_[a-z0-9]{12})?_[a-f0-9]{32,64}$/;
5
+ var VERSION_REGEX = /^v[0-9]+$/;
6
+ var SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
7
+ var InvalidConnectionUrlError = class _InvalidConnectionUrlError extends Error {
8
+ code = "INVALID_CONNECTION_URL";
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "InvalidConnectionUrlError";
12
+ Object.setPrototypeOf(this, _InvalidConnectionUrlError.prototype);
13
+ }
14
+ };
15
+ function fail(reason) {
16
+ throw new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`);
17
+ }
18
+ function parseCredential(raw) {
19
+ const match = CREDENTIAL_REGEX.exec(raw);
20
+ if (!match) {
21
+ fail(`credential must match (pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}, got "${raw}"`);
22
+ }
23
+ return {
24
+ credentialType: match[1],
25
+ env: match[2]
26
+ };
27
+ }
28
+ function validateSlug(candidate) {
29
+ if (!candidate || candidate.length > 63 || !SLUG_REGEX.test(candidate)) {
30
+ fail(`slug "${candidate}" is not a valid DNS label (lowercase alnum + hyphens, 1-63 chars)`);
31
+ }
32
+ return candidate;
33
+ }
34
+ function parseConnectionUrl(url) {
35
+ if (typeof url !== "string" || url.length === 0) {
36
+ fail("url must be a non-empty string");
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = new URL(url);
41
+ } catch {
42
+ fail(`not a valid URL: "${url}"`);
43
+ }
44
+ if (parsed.protocol !== SYLPHX_PROTOCOL) {
45
+ fail(`protocol must be "sylphx:", got "${parsed.protocol}"`);
46
+ }
47
+ const credential = decodeURIComponent(parsed.username);
48
+ if (!credential) {
49
+ fail("missing credential (expected `sylphx://<credential>@<host>`)");
50
+ }
51
+ if (parsed.password) {
52
+ fail("connection URL must not contain a password component");
53
+ }
54
+ const { credentialType, env } = parseCredential(credential);
55
+ const host = parsed.host;
56
+ if (!host) {
57
+ fail("missing host");
58
+ }
59
+ const hostname = parsed.hostname;
60
+ const firstDot = hostname.indexOf(".");
61
+ if (firstDot <= 0) {
62
+ fail(`host "${hostname}" must contain at least one dot (slug.domain)`);
63
+ }
64
+ const slugCandidate = hostname.slice(0, firstDot);
65
+ const domainSuffix = hostname.slice(firstDot + 1);
66
+ if (!domainSuffix) {
67
+ fail(`host "${hostname}" has empty domain suffix`);
68
+ }
69
+ const slug = validateSlug(slugCandidate);
70
+ const rawPath = parsed.pathname.replace(/^\/+/, "").replace(/\/+$/, "");
71
+ let version = DEFAULT_VERSION;
72
+ if (rawPath !== "") {
73
+ if (!VERSION_REGEX.test(rawPath)) {
74
+ fail(`path "${parsed.pathname}" must be empty or match /v{N}`);
75
+ }
76
+ version = rawPath;
77
+ }
78
+ if (parsed.search) {
79
+ fail("connection URL must not contain a query string");
80
+ }
81
+ if (parsed.hash) {
82
+ fail("connection URL must not contain a fragment");
83
+ }
84
+ const apiBaseUrl = `https://${host}/${version}`;
85
+ return {
86
+ credential,
87
+ credentialType,
88
+ env,
89
+ slug,
90
+ host,
91
+ apiBaseUrl
92
+ };
93
+ }
94
+
95
+ // src/constants.ts
96
+ var ENV_SECRET_URL = "SYLPHX_SECRET_URL";
97
+ var DEFAULT_SDK_API_HOST = "api.sylphx.com";
98
+ function detectSdkPlatform() {
99
+ if (typeof window !== "undefined") return "browser";
100
+ const runtimeGlobal = globalThis;
101
+ if (typeof runtimeGlobal.EdgeRuntime !== "undefined") return "edge";
102
+ return "node";
103
+ }
104
+ var SDK_PLATFORM = detectSdkPlatform();
105
+ var DEFAULT_TIMEOUT_MS = 3e4;
106
+ var SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
107
+ var SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
108
+ var REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
109
+ var FLAGS_CACHE_TTL_MS = 5 * 60 * 1e3;
110
+ var FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1e3;
111
+ var MAX_RETRY_DELAY_MS = 3e4;
112
+ var BASE_RETRY_DELAY_MS = 1e3;
113
+ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
114
+ var WEBHOOK_MAX_AGE_MS = 5 * 60 * 1e3;
115
+ var WEBHOOK_CLOCK_SKEW_MS = 30 * 1e3;
116
+ var PKCE_CODE_TTL_MS = 10 * 60 * 1e3;
117
+ var JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
118
+ var SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1e3;
119
+ var FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1e3;
120
+ var DEFAULT_RETRY_DELAYS_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
121
+ var JOB_DEFAULT_TIMEOUT_MS = 6e4;
122
+ var CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1e3;
123
+ var STALE_TIME_FREQUENT_MS = 60 * 1e3;
124
+ var STALE_TIME_MODERATE_MS = 2 * 60 * 1e3;
125
+ var STALE_TIME_STABLE_MS = 5 * 60 * 1e3;
126
+ var STALE_TIME_STATS_MS = 30 * 1e3;
127
+ var NEW_USER_THRESHOLD_MS = 60 * 1e3;
128
+ var STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024;
129
+ var STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024;
130
+ var STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024;
131
+ var STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
132
+ var JWK_CACHE_TTL_MS = 60 * 60 * 1e3;
133
+ var ETAG_CACHE_TTL_MS = 5 * 60 * 1e3;
134
+
135
+ // src/errors.ts
136
+ var ERROR_CODE_STATUS = {
137
+ BAD_REQUEST: 400,
138
+ UNAUTHORIZED: 401,
139
+ FORBIDDEN: 403,
140
+ NOT_FOUND: 404,
141
+ CONFLICT: 409,
142
+ PAYLOAD_TOO_LARGE: 413,
143
+ UNPROCESSABLE_ENTITY: 422,
144
+ TOO_MANY_REQUESTS: 429,
145
+ QUOTA_EXCEEDED: 402,
146
+ INTERNAL_SERVER_ERROR: 500,
147
+ NOT_IMPLEMENTED: 501,
148
+ BAD_GATEWAY: 502,
149
+ SERVICE_UNAVAILABLE: 503,
150
+ GATEWAY_TIMEOUT: 504,
151
+ NETWORK_ERROR: 0,
152
+ TIMEOUT: 0,
153
+ ABORTED: 0,
154
+ PARSE_ERROR: 0,
155
+ UNKNOWN: 0
156
+ };
157
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set([
158
+ "NETWORK_ERROR",
159
+ "TIMEOUT",
160
+ "BAD_GATEWAY",
161
+ "SERVICE_UNAVAILABLE",
162
+ "GATEWAY_TIMEOUT",
163
+ "TOO_MANY_REQUESTS",
164
+ // With backoff
165
+ "INTERNAL_SERVER_ERROR"
166
+ // Sometimes transient
167
+ ]);
168
+ var SylphxError = class _SylphxError extends Error {
169
+ /** Error code for programmatic handling */
170
+ code;
171
+ /** HTTP status code */
172
+ status;
173
+ /** Additional context data */
174
+ data;
175
+ /** Whether this error is safe to retry */
176
+ isRetryable;
177
+ /** Retry-After value in seconds (for rate limiting) */
178
+ retryAfter;
179
+ /** Timestamp when error occurred */
180
+ timestamp;
181
+ constructor(message, options = {}) {
182
+ super(message, { cause: options.cause });
183
+ this.name = "SylphxError";
184
+ this.code = options.code ?? "UNKNOWN";
185
+ this.status = options.status ?? ERROR_CODE_STATUS[this.code];
186
+ this.data = options.data;
187
+ this.isRetryable = RETRYABLE_CODES.has(this.code);
188
+ this.retryAfter = options.retryAfter;
189
+ this.timestamp = /* @__PURE__ */ new Date();
190
+ if (Error.captureStackTrace) {
191
+ Error.captureStackTrace(this, _SylphxError);
192
+ }
193
+ }
194
+ // ============================================================================
195
+ // Static Type Guards (DX helpers)
196
+ // ============================================================================
197
+ /**
198
+ * Check if error is a rate-limit error (429 Too Many Requests)
199
+ */
200
+ static isRateLimited(err) {
201
+ return err instanceof _SylphxError && err.code === "TOO_MANY_REQUESTS";
202
+ }
203
+ /**
204
+ * Check if error is an account lockout error (too many failed login attempts).
205
+ * When true, `error.data?.lockoutUntil` contains the ISO 8601 timestamp when the lockout expires.
206
+ */
207
+ static isAccountLocked(err) {
208
+ return err instanceof _SylphxError && err.code === "TOO_MANY_REQUESTS" && err.data?.code === "ACCOUNT_LOCKED";
209
+ }
210
+ /**
211
+ * Check if error is a quota exceeded error (plan limit reached)
212
+ */
213
+ static isQuotaExceeded(err) {
214
+ return err instanceof _SylphxError && err.code === "QUOTA_EXCEEDED";
215
+ }
216
+ /**
217
+ * Check if error is an authentication error (401 Unauthorized)
218
+ */
219
+ static isUnauthorized(err) {
220
+ return err instanceof _SylphxError && err.code === "UNAUTHORIZED";
221
+ }
222
+ /**
223
+ * Check if error is a not-found error (404 Not Found)
224
+ */
225
+ static isNotFound(err) {
226
+ return err instanceof _SylphxError && err.code === "NOT_FOUND";
227
+ }
228
+ /**
229
+ * Check if error is an authorization error (403 Forbidden)
230
+ */
231
+ static isForbidden(err) {
232
+ return err instanceof _SylphxError && err.code === "FORBIDDEN";
233
+ }
234
+ /**
235
+ * Check if error is a validation error (422 Unprocessable Entity)
236
+ */
237
+ static isValidationError(err) {
238
+ return err instanceof _SylphxError && err.code === "UNPROCESSABLE_ENTITY";
239
+ }
240
+ /**
241
+ * Check if error is a network error (no response received)
242
+ */
243
+ static isNetworkError(err) {
244
+ return err instanceof _SylphxError && err.code === "NETWORK_ERROR";
245
+ }
246
+ /**
247
+ * Check if error is an upstream/gateway error (502/504)
248
+ */
249
+ static isUpstreamError(err) {
250
+ return err instanceof _SylphxError && (err.code === "BAD_GATEWAY" || err.code === "GATEWAY_TIMEOUT" || err.code === "SERVICE_UNAVAILABLE");
251
+ }
252
+ /**
253
+ * Convert to JSON-serializable object
254
+ */
255
+ toJSON() {
256
+ return {
257
+ name: this.name,
258
+ message: this.message,
259
+ code: this.code,
260
+ status: this.status,
261
+ data: this.data,
262
+ isRetryable: this.isRetryable,
263
+ retryAfter: this.retryAfter,
264
+ timestamp: this.timestamp.toISOString()
265
+ };
266
+ }
267
+ };
268
+ var NetworkError = class extends SylphxError {
269
+ constructor(message = "Network request failed", options) {
270
+ super(message, { ...options, code: "NETWORK_ERROR" });
271
+ this.name = "NetworkError";
272
+ }
273
+ };
274
+ var TimeoutError = class extends SylphxError {
275
+ /** Timeout duration in milliseconds */
276
+ timeout;
277
+ constructor(timeout, options) {
278
+ super(`Request timed out after ${timeout}ms`, {
279
+ ...options,
280
+ code: "TIMEOUT"
281
+ });
282
+ this.name = "TimeoutError";
283
+ this.timeout = timeout;
284
+ }
285
+ };
286
+ var RateLimitError = class extends SylphxError {
287
+ /** Maximum requests allowed in window */
288
+ limit;
289
+ /** Remaining requests in current window */
290
+ remaining;
291
+ /** Unix timestamp (seconds) when limit resets */
292
+ resetAt;
293
+ constructor(message = "Too many requests", options) {
294
+ super(message, { ...options, code: "TOO_MANY_REQUESTS" });
295
+ this.name = "RateLimitError";
296
+ this.limit = options?.limit;
297
+ this.remaining = options?.remaining;
298
+ this.resetAt = options?.resetAt;
299
+ }
300
+ /**
301
+ * Get Date when rate limit resets
302
+ */
303
+ getResetDate() {
304
+ return this.resetAt ? new Date(this.resetAt * 1e3) : void 0;
305
+ }
306
+ /**
307
+ * Get human-readable retry message
308
+ */
309
+ getRetryMessage() {
310
+ if (this.retryAfter) {
311
+ return `Please retry after ${this.retryAfter} seconds`;
312
+ }
313
+ if (this.resetAt) {
314
+ const seconds = Math.max(0, this.resetAt - Math.floor(Date.now() / 1e3));
315
+ return `Rate limit resets in ${seconds} seconds`;
316
+ }
317
+ return "Please wait before retrying";
318
+ }
319
+ };
320
+
321
+ // src/config.ts
322
+ var LEGACY_EMBEDDED_REF_PATTERN = /^(pk|sk)_(dev|stg|prod|prev)_[a-z0-9]{12}_[a-f0-9]+$/;
323
+ var LEGACY_APP_KEY_PATTERN = /^app_(dev|stg|prod|prev)_/;
324
+ var MIGRATION_MESSAGE = "API key format has changed. Use a sylphx:// connection URL instead.\n\nNew format: sylphx://pk_prod_{ref?}_{hex}@your-slug.api.sylphx.com\n\nGenerate new credentials from the Sylphx Console \u2192 Your App \u2192 Environments.\nSee https://docs.sylphx.com/migration for details.";
325
+ function rejectLegacyKeyFormat(input) {
326
+ const trimmed = input.trim().toLowerCase();
327
+ if (LEGACY_APP_KEY_PATTERN.test(trimmed)) {
328
+ throw new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: "BAD_REQUEST" });
329
+ }
330
+ if (LEGACY_EMBEDDED_REF_PATTERN.test(trimmed)) {
331
+ throw new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: "BAD_REQUEST" });
332
+ }
333
+ }
334
+ function freezeConfig(opts) {
335
+ return Object.freeze({
336
+ credential: opts.credential,
337
+ credentialType: opts.credentialType,
338
+ env: opts.env,
339
+ slug: opts.slug,
340
+ baseUrl: opts.baseUrl,
341
+ accessToken: opts.accessToken,
342
+ // Backward-compat aliases
343
+ secretKey: opts.credentialType === "sk" ? opts.credential : void 0,
344
+ publicKey: opts.credentialType === "pk" ? opts.credential : void 0,
345
+ ref: opts.slug
346
+ });
347
+ }
348
+ function createClient(input) {
349
+ if (typeof input === "string") {
350
+ return createConfigFromUrl(input);
351
+ }
352
+ return createConfigFromComponents(input);
353
+ }
354
+ function createServerClient(input) {
355
+ const config = createClient(input);
356
+ if (config.credentialType !== "sk") {
357
+ throw new SylphxError(
358
+ "[Sylphx] createServerClient() requires a secret key (sk_*). Use a SYLPHX_SECRET_URL with an sk_ credential, or pass { secretKey } in the components object.",
359
+ { code: "BAD_REQUEST" }
360
+ );
361
+ }
362
+ return config;
363
+ }
364
+ function createConfigFromUrl(url) {
365
+ if (!url || typeof url !== "string") {
366
+ throw new SylphxError(
367
+ "[Sylphx] Connection URL is required. Set SYLPHX_URL or NEXT_PUBLIC_SYLPHX_URL environment variable.\n\nFormat: sylphx://pk_prod_{hex}@your-slug.api.sylphx.com",
368
+ { code: "BAD_REQUEST" }
369
+ );
370
+ }
371
+ const trimmed = url.trim();
372
+ rejectLegacyKeyFormat(trimmed);
373
+ if (!trimmed.startsWith("sylphx://")) {
374
+ if (CREDENTIAL_REGEX.test(trimmed)) {
375
+ throw new SylphxError(
376
+ "[Sylphx] Received a bare credential instead of a connection URL.\n\nWrap it in a connection URL: sylphx://<credential>@<slug>.api.sylphx.com\nOr use createClient({ slug, publicKey }) for explicit components.",
377
+ { code: "BAD_REQUEST" }
378
+ );
379
+ }
380
+ throw new SylphxError(
381
+ `[Sylphx] Invalid connection URL \u2014 must start with "sylphx://". Got: "${trimmed.slice(0, 30)}..."`,
382
+ { code: "BAD_REQUEST" }
383
+ );
384
+ }
385
+ let parsed;
386
+ try {
387
+ parsed = parseConnectionUrl(trimmed);
388
+ } catch (err) {
389
+ if (err instanceof InvalidConnectionUrlError) {
390
+ throw new SylphxError(err.message, { code: "BAD_REQUEST", cause: err });
391
+ }
392
+ throw err;
393
+ }
394
+ return freezeConfig({
395
+ credential: parsed.credential,
396
+ credentialType: parsed.credentialType,
397
+ env: parsed.env,
398
+ slug: parsed.slug,
399
+ baseUrl: parsed.apiBaseUrl
400
+ });
401
+ }
402
+ function createConfigFromComponents(input) {
403
+ const credential = input.secretKey || input.publicKey;
404
+ if (!credential) {
405
+ throw new SylphxError("[Sylphx] Either publicKey or secretKey must be provided.", {
406
+ code: "BAD_REQUEST"
407
+ });
408
+ }
409
+ const resolvedSlug = input.slug || input.ref;
410
+ if (!resolvedSlug) {
411
+ throw new SylphxError("[Sylphx] slug is required when using explicit components.", {
412
+ code: "BAD_REQUEST"
413
+ });
414
+ }
415
+ const trimmedCred = credential.trim().toLowerCase();
416
+ if (CREDENTIAL_REGEX.test(trimmedCred)) {
417
+ const match = CREDENTIAL_REGEX.exec(trimmedCred);
418
+ const credentialType = match[1];
419
+ const env = match[2];
420
+ const slug = resolvedSlug.trim().toLowerCase();
421
+ const domain = input.domain?.trim() || DEFAULT_SDK_API_HOST;
422
+ const baseUrl = `https://${slug}.${domain}/v1`;
423
+ return freezeConfig({
424
+ credential: trimmedCred,
425
+ credentialType,
426
+ env,
427
+ slug,
428
+ baseUrl,
429
+ accessToken: input.accessToken
430
+ });
431
+ }
432
+ const parts = trimmedCred.split("_");
433
+ const prefix = parts[0];
434
+ if ((prefix === "pk" || prefix === "sk") && parts.length >= 3) {
435
+ const envSegment = parts[1];
436
+ const validEnvs = ["dev", "stg", "prod", "prev"];
437
+ const env = validEnvs.includes(envSegment) ? envSegment : "prod";
438
+ const slug = resolvedSlug.trim().toLowerCase();
439
+ let baseUrl;
440
+ if (input.platformUrl) {
441
+ const platform = input.platformUrl.trim().replace(/\/$/, "");
442
+ baseUrl = platform.includes("/v1") ? platform : `${platform}/v1`;
443
+ } else {
444
+ const domain = input.domain?.trim() || DEFAULT_SDK_API_HOST;
445
+ baseUrl = `https://${slug}.${domain}/v1`;
446
+ }
447
+ return freezeConfig({
448
+ credential: trimmedCred,
449
+ credentialType: prefix,
450
+ env,
451
+ slug,
452
+ baseUrl,
453
+ accessToken: input.accessToken
454
+ });
455
+ }
456
+ throw new SylphxError(
457
+ `[Sylphx] Invalid credential format. Expected (pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}. Got: "${trimmedCred.slice(0, 30)}..."`,
458
+ { code: "BAD_REQUEST" }
459
+ );
460
+ }
461
+ function httpStatusToErrorCode(status) {
462
+ switch (status) {
463
+ case 400:
464
+ return "BAD_REQUEST";
465
+ case 401:
466
+ return "UNAUTHORIZED";
467
+ case 403:
468
+ return "FORBIDDEN";
469
+ case 404:
470
+ return "NOT_FOUND";
471
+ case 409:
472
+ return "CONFLICT";
473
+ case 413:
474
+ return "PAYLOAD_TOO_LARGE";
475
+ case 422:
476
+ return "UNPROCESSABLE_ENTITY";
477
+ case 429:
478
+ return "TOO_MANY_REQUESTS";
479
+ case 500:
480
+ return "INTERNAL_SERVER_ERROR";
481
+ case 501:
482
+ return "NOT_IMPLEMENTED";
483
+ case 502:
484
+ return "BAD_GATEWAY";
485
+ case 503:
486
+ return "SERVICE_UNAVAILABLE";
487
+ case 504:
488
+ return "GATEWAY_TIMEOUT";
489
+ default:
490
+ return status >= 500 ? "INTERNAL_SERVER_ERROR" : "BAD_REQUEST";
491
+ }
492
+ }
493
+ function buildHeaders(config) {
494
+ const headers = {
495
+ "Content-Type": "application/json"
496
+ };
497
+ if (config.credential) {
498
+ headers["x-app-secret"] = config.credential;
499
+ }
500
+ if (config.accessToken) {
501
+ headers.Authorization = `Bearer ${config.accessToken}`;
502
+ }
503
+ return headers;
504
+ }
505
+ function buildApiUrl(config, path) {
506
+ const base = config.baseUrl.replace(/\/$/, "");
507
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
508
+ return `${base}${cleanPath}`;
509
+ }
510
+ async function callApi(config, path, options = {}) {
511
+ const {
512
+ method = "GET",
513
+ body,
514
+ query,
515
+ timeout = DEFAULT_TIMEOUT_MS,
516
+ signal,
517
+ idempotencyKey,
518
+ headers: extraHeaders
519
+ } = options;
520
+ let url = buildApiUrl(config, path);
521
+ if (query) {
522
+ const params = new URLSearchParams();
523
+ for (const [key, value] of Object.entries(query)) {
524
+ if (value !== void 0) {
525
+ params.set(key, String(value));
526
+ }
527
+ }
528
+ const queryString = params.toString();
529
+ if (queryString) {
530
+ url += `?${queryString}`;
531
+ }
532
+ }
533
+ const controller = new AbortController();
534
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
535
+ const combinedSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
536
+ const headers = buildHeaders(config);
537
+ if (idempotencyKey) {
538
+ headers["Idempotency-Key"] = idempotencyKey;
539
+ }
540
+ if (extraHeaders) {
541
+ for (const [k, v] of Object.entries(extraHeaders)) {
542
+ headers[k] = v;
543
+ }
544
+ }
545
+ const fetchOptions = {
546
+ method,
547
+ headers,
548
+ signal: combinedSignal
549
+ };
550
+ if (body) {
551
+ fetchOptions.body = JSON.stringify(body);
552
+ }
553
+ let response;
554
+ try {
555
+ response = await fetch(url, fetchOptions);
556
+ } catch (error) {
557
+ clearTimeout(timeoutId);
558
+ if (error instanceof Error) {
559
+ if (error.name === "AbortError") {
560
+ if (controller.signal.aborted && !signal?.aborted) {
561
+ throw new TimeoutError(timeout);
562
+ }
563
+ throw new SylphxError("Request aborted", {
564
+ code: "ABORTED",
565
+ cause: error
566
+ });
567
+ }
568
+ throw new NetworkError(error.message, { cause: error });
569
+ }
570
+ throw new NetworkError("Network request failed");
571
+ } finally {
572
+ clearTimeout(timeoutId);
573
+ }
574
+ if (!response.ok) {
575
+ const errorBody = await response.text().catch(() => "");
576
+ let errorMessage = "Request failed";
577
+ let errorData;
578
+ if (errorBody) {
579
+ try {
580
+ const parsed = JSON.parse(errorBody);
581
+ errorMessage = parsed.error?.message ?? parsed.message ?? errorMessage;
582
+ errorData = parsed.error;
583
+ } catch {
584
+ errorMessage = response.statusText || errorMessage;
585
+ }
586
+ }
587
+ const errorCode = httpStatusToErrorCode(response.status);
588
+ const retryAfterHeader = response.headers.get("Retry-After");
589
+ const rateLimitLimit = response.headers.get("X-RateLimit-Limit");
590
+ const rateLimitRemaining = response.headers.get("X-RateLimit-Remaining");
591
+ const rateLimitReset = response.headers.get("X-RateLimit-Reset");
592
+ const retryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : void 0;
593
+ if (response.status === 429) {
594
+ throw new RateLimitError(errorMessage || "Too many requests", {
595
+ status: response.status,
596
+ data: errorData,
597
+ retryAfter,
598
+ limit: rateLimitLimit ? Number.parseInt(rateLimitLimit, 10) : void 0,
599
+ remaining: rateLimitRemaining ? Number.parseInt(rateLimitRemaining, 10) : void 0,
600
+ resetAt: rateLimitReset ? Number.parseInt(rateLimitReset, 10) : void 0
601
+ });
602
+ }
603
+ throw new SylphxError(errorMessage, {
604
+ code: errorCode,
605
+ status: response.status,
606
+ data: errorData,
607
+ retryAfter
608
+ });
609
+ }
610
+ const text = await response.text();
611
+ if (!text) {
612
+ return {};
613
+ }
614
+ try {
615
+ return JSON.parse(text);
616
+ } catch (error) {
617
+ throw new SylphxError("Failed to parse response", {
618
+ code: "PARSE_ERROR",
619
+ cause: error instanceof Error ? error : void 0,
620
+ data: { body: text.slice(0, 200) }
621
+ });
622
+ }
623
+ }
624
+
625
+ // src/lib/triggers/index.ts
626
+ async function createTrigger(config, options) {
627
+ return callApi(config, "/triggers", {
628
+ method: "POST",
629
+ body: options
630
+ });
631
+ }
632
+ async function listTriggers(config) {
633
+ return callApi(config, "/triggers");
634
+ }
635
+ async function getTrigger(config, triggerId) {
636
+ return callApi(config, `/triggers/${triggerId}`);
637
+ }
638
+ async function updateTrigger(config, triggerId, options) {
639
+ return callApi(config, `/triggers/${triggerId}`, {
640
+ method: "PATCH",
641
+ body: options
642
+ });
643
+ }
644
+ async function deleteTrigger(config, triggerId) {
645
+ return callApi(config, `/triggers/${triggerId}`, { method: "DELETE" });
646
+ }
647
+ async function pauseTrigger(config, triggerId) {
648
+ return callApi(config, `/triggers/${triggerId}/pause`, { method: "POST" });
649
+ }
650
+ async function resumeTrigger(config, triggerId) {
651
+ return callApi(config, `/triggers/${triggerId}/resume`, { method: "POST" });
652
+ }
653
+ async function fireTrigger(config, triggerId) {
654
+ return callApi(config, `/triggers/${triggerId}/fire`, {
655
+ method: "POST"
656
+ });
657
+ }
658
+ async function publishEvent(config, eventName, payload) {
659
+ return callApi(config, "/triggers/events", {
660
+ method: "POST",
661
+ body: { eventName, payload: payload ?? {} }
662
+ });
663
+ }
664
+ var TriggersClient = {
665
+ create: createTrigger,
666
+ list: listTriggers,
667
+ get: getTrigger,
668
+ update: updateTrigger,
669
+ delete: deleteTrigger,
670
+ pause: pauseTrigger,
671
+ resume: resumeTrigger,
672
+ fire: fireTrigger,
673
+ publishEvent
674
+ };
675
+
676
+ // src/lib/tasks/connection.ts
677
+ function resolveTaskServerConnectionUrl(options = {}) {
678
+ const explicit = options.explicitConnectionUrl?.trim();
679
+ if (explicit) return explicit;
680
+ if (typeof process === "undefined") return null;
681
+ return process.env[ENV_SECRET_URL]?.trim() || null;
682
+ }
683
+ function requireTaskServerConnectionUrl(options = {}) {
684
+ const connectionUrl = resolveTaskServerConnectionUrl(options);
685
+ if (!connectionUrl) {
686
+ throw new Error(
687
+ `[sylphx/tasks] No server connection URL found. Set ${ENV_SECRET_URL} env var or pass config to trigger options.`
688
+ );
689
+ }
690
+ return connectionUrl;
691
+ }
692
+
693
+ // src/lib/tasks/handler.ts
694
+ import { createHmac, timingSafeEqual } from "crypto";
695
+ var StepCompleteSignal = class {
696
+ constructor(stepName, result) {
697
+ this.stepName = stepName;
698
+ this.result = result;
699
+ }
700
+ _isStepCompleteSignal = true;
701
+ };
702
+ var StepSideEffectStartSignal = class {
703
+ constructor(stepName, effectKey, externalService) {
704
+ this.stepName = stepName;
705
+ this.effectKey = effectKey;
706
+ this.externalService = externalService;
707
+ }
708
+ _isStepSideEffectStartSignal = true;
709
+ };
710
+ var StepSideEffectCompleteSignal = class {
711
+ constructor(stepName, effectKey, handle, result) {
712
+ this.stepName = stepName;
713
+ this.effectKey = effectKey;
714
+ this.handle = handle;
715
+ this.result = result;
716
+ }
717
+ _isStepSideEffectCompleteSignal = true;
718
+ };
719
+ var StepSleepSignal = class {
720
+ constructor(stepName, duration) {
721
+ this.stepName = stepName;
722
+ this.duration = duration;
723
+ }
724
+ _isStepSleepSignal = true;
725
+ };
726
+ var StepWaitEventSignal = class {
727
+ constructor(stepName, eventName, options = {}) {
728
+ this.stepName = stepName;
729
+ this.eventName = eventName;
730
+ this.options = options;
731
+ }
732
+ _isStepWaitEventSignal = true;
733
+ };
734
+ function createStepContext(completedSteps, resolvedWaits, sideEffectReceipts = /* @__PURE__ */ new Map()) {
735
+ return {
736
+ /**
737
+ * Execute a named step.
738
+ *
739
+ * - If cached: return the cached value immediately (replay).
740
+ * - If not cached: execute fn, then throw StepCompleteSignal with the result.
741
+ */
742
+ async run(name, fn) {
743
+ if (completedSteps.has(name)) {
744
+ return completedSteps.get(name);
745
+ }
746
+ const result = await fn();
747
+ throw new StepCompleteSignal(name, result);
748
+ },
749
+ async sideEffect(stepName, effectKey, externalService, fn) {
750
+ const receipt = sideEffectReceipts.get(sideEffectReceiptKey(stepName, effectKey));
751
+ if (!receipt) {
752
+ throw new StepSideEffectStartSignal(stepName, effectKey, externalService);
753
+ }
754
+ if (receipt.externalService !== externalService) {
755
+ throw new Error(
756
+ `Side-effect external service mismatch for ${stepName}/${effectKey}: receipt=${receipt.externalService} handler=${externalService}`
757
+ );
758
+ }
759
+ if (receipt.completedAt) {
760
+ return receipt.result;
761
+ }
762
+ const outcome = await fn(receipt.idempotencyKey);
763
+ throw new StepSideEffectCompleteSignal(
764
+ stepName,
765
+ effectKey,
766
+ normalizeOptionalStepKey(outcome.handle),
767
+ outcome.result
768
+ );
769
+ },
770
+ /**
771
+ * Sleep for the given duration.
772
+ *
773
+ * - If resolved (platform woke us up): return immediately.
774
+ * - If not resolved: throw StepSleepSignal to pause execution.
775
+ */
776
+ async sleep(name, duration) {
777
+ if (resolvedWaits.has(name)) {
778
+ return;
779
+ }
780
+ throw new StepSleepSignal(name, duration);
781
+ },
782
+ /**
783
+ * Pause execution until a named event is published via TriggersClient.publishEvent().
784
+ *
785
+ * - If event already arrived (platform re-dispatched with result): return event payload.
786
+ * - If not yet arrived: throw StepWaitEventSignal to pause execution.
787
+ *
788
+ * @param name Step identifier (unique within handler).
789
+ * @param eventName The event name to listen for (e.g. 'user.approved').
790
+ * @param options Optional timeout ('24h', '7d') and payload filter.
791
+ *
792
+ * @example Human-in-the-loop approval
793
+ * ```typescript
794
+ * const approval = await step.waitForEvent('wait-approval', 'order.approved', {
795
+ * timeout: '48h',
796
+ * filter: { orderId: payload.orderId },
797
+ * })
798
+ * if (!approval) throw new Error('Approval timed out')
799
+ * await sendConfirmation(approval.approvedBy)
800
+ * ```
801
+ */
802
+ async waitForEvent(name, eventName, options = {}) {
803
+ if (resolvedWaits.has(name)) {
804
+ return resolvedWaits.get(name) ?? null;
805
+ }
806
+ throw new StepWaitEventSignal(name, eventName, options);
807
+ }
808
+ };
809
+ }
810
+ function normalizeOptionalStepKey(value) {
811
+ const trimmed = value?.trim();
812
+ return trimmed ? trimmed.slice(0, 500) : void 0;
813
+ }
814
+ function sideEffectReceiptKey(stepName, effectKey) {
815
+ return `${stepName}\0${effectKey}`;
816
+ }
817
+ function verifySignature(body, signature, secret) {
818
+ try {
819
+ const hmac = createHmac("sha256", secret).update(body, "utf8").digest("hex");
820
+ const normalised = signature.replace(/^sha256=/, "");
821
+ const expected = Buffer.from(hmac, "hex");
822
+ const provided = Buffer.from(normalised, "hex");
823
+ if (expected.length !== provided.length) return false;
824
+ return timingSafeEqual(expected, provided);
825
+ } catch {
826
+ return false;
827
+ }
828
+ }
829
+ function createTasksHandler(taskDefs, options = {}) {
830
+ const taskMap = /* @__PURE__ */ new Map();
831
+ for (const def of taskDefs) {
832
+ taskMap.set(def.name, def);
833
+ }
834
+ const GET = async (_req) => {
835
+ return Response.json({
836
+ ok: true,
837
+ tasks: Array.from(taskMap.keys())
838
+ });
839
+ };
840
+ const POST = async (req) => {
841
+ let rawBody;
842
+ try {
843
+ rawBody = await req.text();
844
+ } catch {
845
+ return Response.json(
846
+ { status: "error", message: "Failed to read request body" },
847
+ { status: 400 }
848
+ );
849
+ }
850
+ const signingSecret = options.signingSecret ?? process.env.SYLPHX_SIGNING_SECRET ?? "";
851
+ if (signingSecret) {
852
+ const signature = req.headers.get("x-sylphx-signature") ?? "";
853
+ if (!signature) {
854
+ return Response.json(
855
+ { status: "error", message: "Missing X-Sylphx-Signature header" },
856
+ { status: 401 }
857
+ );
858
+ }
859
+ if (!verifySignature(rawBody, signature, signingSecret)) {
860
+ return Response.json({ status: "error", message: "Invalid signature" }, { status: 401 });
861
+ }
862
+ }
863
+ let dispatch;
864
+ try {
865
+ dispatch = JSON.parse(rawBody);
866
+ } catch {
867
+ return Response.json(
868
+ { status: "error", message: "Request body is not valid JSON" },
869
+ { status: 400 }
870
+ );
871
+ }
872
+ const { taskName, payload, context } = dispatch;
873
+ if (!taskName || typeof taskName !== "string") {
874
+ return Response.json(
875
+ { status: "error", message: 'Missing or invalid "taskName" field' },
876
+ { status: 400 }
877
+ );
878
+ }
879
+ const taskDef = taskMap.get(taskName);
880
+ if (!taskDef) {
881
+ return Response.json(
882
+ {
883
+ status: "error",
884
+ message: `Task "${taskName}" not found. Registered tasks: ${Array.from(taskMap.keys()).join(", ")}`
885
+ },
886
+ { status: 404 }
887
+ );
888
+ }
889
+ const completedSteps = /* @__PURE__ */ new Map();
890
+ for (const step of context?.steps ?? []) {
891
+ completedSteps.set(step.name, step.result);
892
+ }
893
+ const resolvedWaits = /* @__PURE__ */ new Map();
894
+ for (const wait2 of context?.waits ?? []) {
895
+ resolvedWaits.set(wait2.name, wait2.result ?? void 0);
896
+ }
897
+ const sideEffectReceipts = /* @__PURE__ */ new Map();
898
+ for (const receipt of context?.sideEffects ?? []) {
899
+ sideEffectReceipts.set(sideEffectReceiptKey(receipt.stepName, receipt.effectKey), receipt);
900
+ }
901
+ const stepCtx = createStepContext(completedSteps, resolvedWaits, sideEffectReceipts);
902
+ try {
903
+ const result = await taskDef.handler(payload, { step: stepCtx });
904
+ return Response.json({ status: "complete", result });
905
+ } catch (err) {
906
+ if (err instanceof StepCompleteSignal || err?._isStepCompleteSignal) {
907
+ const signal = err;
908
+ return Response.json({
909
+ status: "step_complete",
910
+ stepName: signal.stepName,
911
+ result: signal.result
912
+ });
913
+ }
914
+ if (err instanceof StepSideEffectStartSignal || err?._isStepSideEffectStartSignal) {
915
+ const signal = err;
916
+ return Response.json({
917
+ status: "side_effect_start",
918
+ stepName: signal.stepName,
919
+ effectKey: signal.effectKey,
920
+ externalService: signal.externalService
921
+ });
922
+ }
923
+ if (err instanceof StepSideEffectCompleteSignal || err?._isStepSideEffectCompleteSignal) {
924
+ const signal = err;
925
+ return Response.json({
926
+ status: "side_effect_complete",
927
+ stepName: signal.stepName,
928
+ effectKey: signal.effectKey,
929
+ handle: signal.handle ?? null,
930
+ result: signal.result
931
+ });
932
+ }
933
+ if (err instanceof StepSleepSignal || err?._isStepSleepSignal) {
934
+ const signal = err;
935
+ return Response.json({
936
+ status: "step_sleep",
937
+ stepName: signal.stepName,
938
+ duration: signal.duration
939
+ });
940
+ }
941
+ if (err instanceof StepWaitEventSignal || err?._isStepWaitEventSignal) {
942
+ const signal = err;
943
+ return Response.json({
944
+ status: "step_wait_event",
945
+ stepName: signal.stepName,
946
+ eventName: signal.eventName,
947
+ timeout: signal.options.timeout ?? null,
948
+ filter: signal.options.filter ?? null
949
+ });
950
+ }
951
+ const message = err instanceof Error ? err.message : String(err);
952
+ console.error(`[sylphx/tasks] Task "${taskName}" threw an error:`, err);
953
+ return Response.json(
954
+ {
955
+ status: "error",
956
+ message,
957
+ retriable: true
958
+ },
959
+ { status: 500 }
960
+ );
961
+ }
962
+ };
963
+ return { GET, POST };
964
+ }
965
+
966
+ // src/lib/tasks/serve.ts
967
+ var triggerSyncDone = false;
968
+ var triggerSyncPromise = null;
969
+ async function syncTriggers(tasks, options) {
970
+ const connectionUrl = resolveTaskServerConnectionUrl({
971
+ explicitConnectionUrl: options.connectionUrl
972
+ });
973
+ if (!connectionUrl) {
974
+ return;
975
+ }
976
+ const tasksWithTriggers = tasks.filter((t) => t._trigger);
977
+ if (tasksWithTriggers.length === 0) return;
978
+ const config = createServerClient(connectionUrl);
979
+ const results = await Promise.allSettled(
980
+ tasksWithTriggers.flatMap((t) => {
981
+ const promises = [];
982
+ if (t._trigger?.cron) {
983
+ promises.push(
984
+ TriggersClient.create(config, {
985
+ name: `${t.id}:cron`,
986
+ source: { type: "cron", expression: t._trigger.cron },
987
+ target: { type: "task", taskName: t.id },
988
+ idempotencyKey: `task:${t.id}:cron:${t._trigger.cron}`
989
+ }).catch((err) => {
990
+ if (err?.status === 409 || err?.message?.includes("already exists")) return;
991
+ throw err;
992
+ })
993
+ );
994
+ }
995
+ if (t._trigger?.event) {
996
+ promises.push(
997
+ TriggersClient.create(config, {
998
+ name: `${t.id}:event:${t._trigger.event}`,
999
+ source: { type: "event", eventName: t._trigger.event },
1000
+ target: { type: "task", taskName: t.id },
1001
+ idempotencyKey: `task:${t.id}:event:${t._trigger.event}`
1002
+ }).catch((err) => {
1003
+ if (err?.status === 409 || err?.message?.includes("already exists")) return;
1004
+ throw err;
1005
+ })
1006
+ );
1007
+ }
1008
+ return promises;
1009
+ })
1010
+ );
1011
+ for (const result of results) {
1012
+ if (result.status === "rejected") {
1013
+ console.warn("[sylphx/tasks] Warning: trigger sync failed", result.reason);
1014
+ }
1015
+ }
1016
+ }
1017
+ function serve(options) {
1018
+ const functionModeTasks = options.tasks.filter((t) => !t._machine && t._run != null);
1019
+ const defs = functionModeTasks.map((t) => ({
1020
+ name: t.id,
1021
+ handler: t._run
1022
+ }));
1023
+ const handlerOptions = {
1024
+ signingSecret: options.signingSecret
1025
+ };
1026
+ const { GET: baseGET, POST: basePOST } = createTasksHandler(defs, handlerOptions);
1027
+ function ensureTriggerSync() {
1028
+ if (triggerSyncDone || triggerSyncPromise) return;
1029
+ triggerSyncPromise = syncTriggers(options.tasks, options).then(() => {
1030
+ triggerSyncDone = true;
1031
+ }).catch((err) => {
1032
+ triggerSyncPromise = null;
1033
+ console.warn("[sylphx/tasks] Trigger sync error:", err);
1034
+ });
1035
+ }
1036
+ return {
1037
+ async GET(req) {
1038
+ ensureTriggerSync();
1039
+ return baseGET(req);
1040
+ },
1041
+ async POST(req) {
1042
+ ensureTriggerSync();
1043
+ return basePOST(req);
1044
+ }
1045
+ };
1046
+ }
1047
+
1048
+ // src/lib/tasks/task.ts
1049
+ function resolveConfig(options) {
1050
+ if (options?.config) return options.config;
1051
+ const connectionUrl = requireTaskServerConnectionUrl();
1052
+ return createServerClient(connectionUrl);
1053
+ }
1054
+ async function pollUntilComplete(config, taskRunId, timeoutMs) {
1055
+ const deadline = Date.now() + timeoutMs;
1056
+ let delay2 = 500;
1057
+ while (Date.now() < deadline) {
1058
+ const run = await callApi(
1059
+ config,
1060
+ `/tasks/${taskRunId}`,
1061
+ { method: "GET" }
1062
+ );
1063
+ if (run.status === "completed") return run.result;
1064
+ if (run.status === "failed" || run.status === "cancelled") {
1065
+ throw new Error(run.error ?? `Task run ${taskRunId} ${run.status}`);
1066
+ }
1067
+ await new Promise((r) => setTimeout(r, delay2));
1068
+ delay2 = Math.min(delay2 * 1.5, 5e3);
1069
+ }
1070
+ throw new Error(`Task run ${taskRunId} timed out after ${timeoutMs}ms`);
1071
+ }
1072
+ async function dispatchTask(id, payload, machine, options) {
1073
+ const config = resolveConfig(options);
1074
+ const body = {
1075
+ taskName: id,
1076
+ payload
1077
+ };
1078
+ if (options?.idempotencyKey) body.idempotencyKey = options.idempotencyKey;
1079
+ if (options?.delay) body.delay = options.delay;
1080
+ if (options?.scheduledFor) body.scheduledFor = options.scheduledFor.toISOString();
1081
+ if (options?.maxAttempts) body.maxAttempts = options.maxAttempts;
1082
+ if (options?.queue) body.queue = options.queue;
1083
+ if (machine) body.machine = machine;
1084
+ const result = await callApi(config, "/tasks/trigger", {
1085
+ method: "POST",
1086
+ body
1087
+ });
1088
+ const runId = result.taskRunId;
1089
+ const defaultTimeoutMs = machine ? 24 * 3600 * 1e3 : 3e5;
1090
+ return {
1091
+ id: runId,
1092
+ status: result.status,
1093
+ waitForCompletion(waitOptions) {
1094
+ return pollUntilComplete(config, runId, waitOptions?.timeoutMs ?? defaultTimeoutMs);
1095
+ },
1096
+ async cancel() {
1097
+ const cancelled = await callApi(config, `/tasks/${runId}/cancel`, {
1098
+ method: "POST"
1099
+ });
1100
+ return cancelled.success;
1101
+ }
1102
+ };
1103
+ }
1104
+ function task(config) {
1105
+ return {
1106
+ id: config.id,
1107
+ _trigger: config.trigger,
1108
+ _machine: config.machine,
1109
+ _run: config.run,
1110
+ async trigger(payload, options) {
1111
+ return dispatchTask(config.id, payload, config.machine, options);
1112
+ },
1113
+ async triggerAndWait(payload, options) {
1114
+ const handle = await dispatchTask(
1115
+ config.id,
1116
+ payload,
1117
+ config.machine,
1118
+ options
1119
+ );
1120
+ return handle.waitForCompletion();
1121
+ },
1122
+ async batchTrigger(payloads, options) {
1123
+ const handles = await Promise.all(
1124
+ payloads.map((p) => dispatchTask(config.id, p, config.machine, options))
1125
+ );
1126
+ return { runs: handles };
1127
+ }
1128
+ };
1129
+ }
1130
+ function taskStub(id) {
1131
+ return {
1132
+ id,
1133
+ _machine: void 0,
1134
+ _run: void 0,
1135
+ async trigger(payload, options) {
1136
+ return dispatchTask(id, payload, void 0, options);
1137
+ },
1138
+ async triggerAndWait(payload, options) {
1139
+ const handle = await dispatchTask(id, payload, void 0, options);
1140
+ return handle.waitForCompletion();
1141
+ },
1142
+ async batchTrigger(payloads, options) {
1143
+ const handles = await Promise.all(
1144
+ payloads.map((p) => dispatchTask(id, p, void 0, options))
1145
+ );
1146
+ return { runs: handles };
1147
+ }
1148
+ };
1149
+ }
1150
+
1151
+ // src/lib/tasks/api-functions.ts
1152
+ async function scheduleTask(config, input) {
1153
+ return callApi(config, "/tasks/schedule", {
1154
+ method: "POST",
1155
+ body: input
1156
+ });
1157
+ }
1158
+ async function getTask(config, taskId) {
1159
+ return callApi(config, `/tasks/${taskId}`, { method: "GET" });
1160
+ }
1161
+ async function getTaskRun(config, runId) {
1162
+ return callApi(config, `/tasks/${runId}`, { method: "GET" });
1163
+ }
1164
+ async function cancelTask(config, taskId) {
1165
+ const result = await callApi(config, `/tasks/${taskId}/cancel`, {
1166
+ method: "POST"
1167
+ });
1168
+ return result.success;
1169
+ }
1170
+ async function listTaskRunDlq(config, options) {
1171
+ return callApi(config, "/tasks/dlq", {
1172
+ method: "GET",
1173
+ query: options
1174
+ });
1175
+ }
1176
+ async function replayTaskRun(config, taskId, input) {
1177
+ return callApi(config, `/tasks/${taskId}/replay`, {
1178
+ method: "POST",
1179
+ body: input
1180
+ });
1181
+ }
1182
+ async function listTasks(config, options) {
1183
+ return callApi(config, "/tasks", {
1184
+ method: "GET",
1185
+ query: options
1186
+ });
1187
+ }
1188
+ async function createCron(config, input) {
1189
+ return callApi(config, "/tasks/cron", {
1190
+ method: "POST",
1191
+ body: input
1192
+ });
1193
+ }
1194
+ async function pauseCron(config, scheduleId) {
1195
+ const result = await callApi(config, `/tasks/cron/${scheduleId}/pause`, {
1196
+ method: "POST"
1197
+ });
1198
+ return result.success;
1199
+ }
1200
+ async function resumeCron(config, scheduleId) {
1201
+ const result = await callApi(config, `/tasks/cron/${scheduleId}/resume`, {
1202
+ method: "POST"
1203
+ });
1204
+ return result.success;
1205
+ }
1206
+ async function deleteCron(config, scheduleId) {
1207
+ const result = await callApi(config, `/tasks/cron/${scheduleId}`, {
1208
+ method: "DELETE"
1209
+ });
1210
+ return result.success;
1211
+ }
1212
+
1213
+ // src/lib/tasks/types.ts
1214
+ var DEFAULT_JOBS_CONFIG = {
1215
+ defaultOptions: {
1216
+ priority: "normal",
1217
+ maxRetries: 3,
1218
+ retryDelay: {
1219
+ type: "exponential",
1220
+ base: BASE_RETRY_DELAY_MS,
1221
+ maxDelay: MAX_RETRY_DELAY_MS
1222
+ },
1223
+ timeout: JOB_DEFAULT_TIMEOUT_MS,
1224
+ dlq: {
1225
+ enabled: true,
1226
+ maxAge: JOBS_DLQ_MAX_AGE_MS
1227
+ // 7 days
1228
+ }
1229
+ },
1230
+ debug: false
1231
+ };
1232
+ var DEFAULT_RETRY_DELAYS = DEFAULT_RETRY_DELAYS_MS;
1233
+
1234
+ // src/lib/tasks/legacy.ts
1235
+ var TasksClient = class {
1236
+ config;
1237
+ eventHandlers = { job: [], workflow: [] };
1238
+ constructor(config) {
1239
+ this.config = {
1240
+ ...config,
1241
+ defaultOptions: {
1242
+ ...DEFAULT_JOBS_CONFIG.defaultOptions,
1243
+ ...config.defaultOptions
1244
+ }
1245
+ };
1246
+ if (config.onTaskEvent) {
1247
+ this.eventHandlers.job.push(config.onTaskEvent);
1248
+ }
1249
+ if (config.onWorkflowEvent) {
1250
+ this.eventHandlers.workflow.push(config.onWorkflowEvent);
1251
+ }
1252
+ }
1253
+ // =========================================================================
1254
+ // Job Scheduling
1255
+ // =========================================================================
1256
+ /**
1257
+ * Schedule a job for execution
1258
+ */
1259
+ async schedule(type, payload, options) {
1260
+ const response = await this.fetch("/jobs", {
1261
+ method: "POST",
1262
+ body: JSON.stringify({
1263
+ type,
1264
+ payload,
1265
+ options: {
1266
+ ...this.config.defaultOptions,
1267
+ ...options
1268
+ }
1269
+ })
1270
+ });
1271
+ return response.job;
1272
+ }
1273
+ /**
1274
+ * Schedule a job with delay
1275
+ */
1276
+ async scheduleDelayed(type, payload, delay2, options) {
1277
+ return this.schedule(type, payload, {
1278
+ ...options,
1279
+ delay: delay2 instanceof Date ? delay2.getTime() - Date.now() : delay2
1280
+ });
1281
+ }
1282
+ /**
1283
+ * Schedule a recurring job (cron)
1284
+ */
1285
+ async scheduleCron(type, payload, cron, options) {
1286
+ const response = await this.fetch("/jobs/scheduled", {
1287
+ method: "POST",
1288
+ body: JSON.stringify({
1289
+ type,
1290
+ payload,
1291
+ cron: typeof cron === "string" ? { expression: cron } : cron,
1292
+ options: {
1293
+ ...this.config.defaultOptions,
1294
+ ...options
1295
+ }
1296
+ })
1297
+ });
1298
+ return response.scheduled;
1299
+ }
1300
+ // =========================================================================
1301
+ // Job Management
1302
+ // =========================================================================
1303
+ /**
1304
+ * Get a job by ID
1305
+ */
1306
+ async getJob(jobId) {
1307
+ const response = await this.fetch(`/jobs/${jobId}`);
1308
+ return response.job;
1309
+ }
1310
+ /**
1311
+ * Cancel a job
1312
+ */
1313
+ async cancelJob(jobId) {
1314
+ const response = await this.fetch(`/jobs/${jobId}/cancel`, {
1315
+ method: "POST"
1316
+ });
1317
+ return response.cancelled;
1318
+ }
1319
+ /**
1320
+ * Retry a failed job
1321
+ */
1322
+ async retryJob(jobId) {
1323
+ const response = await this.fetch(`/jobs/${jobId}/retry`, {
1324
+ method: "POST"
1325
+ });
1326
+ return response.job;
1327
+ }
1328
+ /**
1329
+ * List jobs with filters
1330
+ */
1331
+ async listJobs(options) {
1332
+ const params = new URLSearchParams();
1333
+ if (options?.type) params.set("type", options.type);
1334
+ if (options?.status) params.set("status", options.status);
1335
+ if (options?.limit) params.set("limit", String(options.limit));
1336
+ if (options?.offset) params.set("offset", String(options.offset));
1337
+ const response = await this.fetch(`/jobs?${params.toString()}`);
1338
+ return { jobs: response.jobs, total: response.total };
1339
+ }
1340
+ // =========================================================================
1341
+ // Dead Letter Queue
1342
+ // =========================================================================
1343
+ /**
1344
+ * List DLQ entries
1345
+ */
1346
+ async listDLQ(options) {
1347
+ const params = new URLSearchParams();
1348
+ if (options?.limit) params.set("limit", String(options.limit));
1349
+ if (options?.offset) params.set("offset", String(options.offset));
1350
+ const response = await this.fetch(
1351
+ `/jobs/dlq?${params.toString()}`
1352
+ );
1353
+ return { entries: response.entries, total: response.total };
1354
+ }
1355
+ /**
1356
+ * Retry a DLQ entry
1357
+ */
1358
+ async retryDLQEntry(entryId) {
1359
+ const response = await this.fetch(`/jobs/dlq/${entryId}/retry`, {
1360
+ method: "POST"
1361
+ });
1362
+ return response.job;
1363
+ }
1364
+ /**
1365
+ * Discard a DLQ entry
1366
+ */
1367
+ async discardDLQEntry(entryId) {
1368
+ const response = await this.fetch(`/jobs/dlq/${entryId}`, {
1369
+ method: "DELETE"
1370
+ });
1371
+ return response.discarded;
1372
+ }
1373
+ // =========================================================================
1374
+ // Workflows
1375
+ // =========================================================================
1376
+ /**
1377
+ * Start a workflow
1378
+ */
1379
+ async startWorkflow(workflow, input, options) {
1380
+ const response = await this.fetch("/workflows", {
1381
+ method: "POST",
1382
+ body: JSON.stringify({
1383
+ workflow,
1384
+ input,
1385
+ options: {
1386
+ ...this.config.defaultOptions,
1387
+ ...options
1388
+ }
1389
+ })
1390
+ });
1391
+ return response.workflow;
1392
+ }
1393
+ /**
1394
+ * Get a workflow by ID
1395
+ */
1396
+ async getWorkflow(workflowId) {
1397
+ const response = await this.fetch(
1398
+ `/workflows/${workflowId}`
1399
+ );
1400
+ return response.workflow;
1401
+ }
1402
+ /**
1403
+ * Cancel a workflow
1404
+ */
1405
+ async cancelWorkflow(workflowId) {
1406
+ const response = await this.fetch(`/workflows/${workflowId}/cancel`, {
1407
+ method: "POST"
1408
+ });
1409
+ return response.cancelled;
1410
+ }
1411
+ /**
1412
+ * List workflows
1413
+ */
1414
+ async listWorkflows(options) {
1415
+ const params = new URLSearchParams();
1416
+ if (options?.type) params.set("type", options.type);
1417
+ if (options?.status) params.set("status", options.status);
1418
+ if (options?.limit) params.set("limit", String(options.limit));
1419
+ if (options?.offset) params.set("offset", String(options.offset));
1420
+ const response = await this.fetch(
1421
+ `/workflows?${params.toString()}`
1422
+ );
1423
+ return { workflows: response.workflows, total: response.total };
1424
+ }
1425
+ // =========================================================================
1426
+ // Scheduled Jobs
1427
+ // =========================================================================
1428
+ /**
1429
+ * List scheduled jobs
1430
+ */
1431
+ async listScheduledJobs(options) {
1432
+ const params = new URLSearchParams();
1433
+ if (options?.status) params.set("status", options.status);
1434
+ if (options?.limit) params.set("limit", String(options.limit));
1435
+ if (options?.offset) params.set("offset", String(options.offset));
1436
+ const response = await this.fetch(
1437
+ `/jobs/scheduled?${params.toString()}`
1438
+ );
1439
+ return { scheduled: response.scheduled, total: response.total };
1440
+ }
1441
+ /**
1442
+ * Pause a scheduled job
1443
+ */
1444
+ async pauseScheduledJob(scheduleId) {
1445
+ const response = await this.fetch(
1446
+ `/jobs/scheduled/${scheduleId}/pause`,
1447
+ {
1448
+ method: "POST"
1449
+ }
1450
+ );
1451
+ return response.scheduled;
1452
+ }
1453
+ /**
1454
+ * Resume a scheduled job
1455
+ */
1456
+ async resumeScheduledJob(scheduleId) {
1457
+ const response = await this.fetch(
1458
+ `/jobs/scheduled/${scheduleId}/resume`,
1459
+ {
1460
+ method: "POST"
1461
+ }
1462
+ );
1463
+ return response.scheduled;
1464
+ }
1465
+ /**
1466
+ * Delete a scheduled job
1467
+ */
1468
+ async deleteScheduledJob(scheduleId) {
1469
+ const response = await this.fetch(`/jobs/scheduled/${scheduleId}`, {
1470
+ method: "DELETE"
1471
+ });
1472
+ return response.deleted;
1473
+ }
1474
+ // =========================================================================
1475
+ // Events
1476
+ // =========================================================================
1477
+ /**
1478
+ * Subscribe to job events
1479
+ */
1480
+ onJobEvent(handler) {
1481
+ this.eventHandlers.job.push(handler);
1482
+ return () => {
1483
+ const index = this.eventHandlers.job.indexOf(handler);
1484
+ if (index !== -1) {
1485
+ this.eventHandlers.job.splice(index, 1);
1486
+ }
1487
+ };
1488
+ }
1489
+ /**
1490
+ * Subscribe to workflow events
1491
+ */
1492
+ onWorkflowEvent(handler) {
1493
+ this.eventHandlers.workflow.push(handler);
1494
+ return () => {
1495
+ const index = this.eventHandlers.workflow.indexOf(handler);
1496
+ if (index !== -1) {
1497
+ this.eventHandlers.workflow.splice(index, 1);
1498
+ }
1499
+ };
1500
+ }
1501
+ // =========================================================================
1502
+ // Internal
1503
+ // =========================================================================
1504
+ async fetch(path, options) {
1505
+ const url = `${this.config.apiEndpoint}${path}`;
1506
+ const response = await fetch(url, {
1507
+ ...options,
1508
+ headers: {
1509
+ "Content-Type": "application/json",
1510
+ ...this.config.apiKey && {
1511
+ Authorization: `Bearer ${this.config.apiKey}`
1512
+ },
1513
+ ...options?.headers
1514
+ }
1515
+ });
1516
+ if (!response.ok) {
1517
+ const errorPayload = await response.json().catch(() => ({ message: response.statusText }));
1518
+ const message = typeof errorPayload === "object" && errorPayload !== null && "message" in errorPayload && typeof errorPayload.message === "string" ? errorPayload.message : response.statusText;
1519
+ throw new Error(message || `HTTP ${response.status}`);
1520
+ }
1521
+ const payload = await response.json();
1522
+ return payload;
1523
+ }
1524
+ // =========================================================================
1525
+ // Native Task Engine — Handler API
1526
+ // =========================================================================
1527
+ /**
1528
+ * Define a named task handler.
1529
+ *
1530
+ * Returns a TaskDefinition that can be passed to tasks.handler([...]).
1531
+ * The handler runs with stateless-replay semantics — each dispatch
1532
+ * replays from the beginning with completed steps injected from cache.
1533
+ *
1534
+ * @example
1535
+ * ```typescript
1536
+ * const sendEmail = sylphx.tasks.define('send-email', async (payload, { step }) => {
1537
+ * const validated = await step.run('validate', () => validate(payload.to))
1538
+ * await step.sleep('cool-down', '5 minutes')
1539
+ * return step.run('send', () => send(validated))
1540
+ * })
1541
+ * ```
1542
+ */
1543
+ define(name, fn, options) {
1544
+ return { name, handler: fn, options };
1545
+ }
1546
+ /**
1547
+ * Create a Next.js / Web-API-compatible route handler for a set of task definitions.
1548
+ *
1549
+ * @example
1550
+ * ```typescript
1551
+ * // app/api/tasks/route.ts
1552
+ * export const { GET, POST } = sylphx.tasks.handler([sendEmail, processOrder])
1553
+ * ```
1554
+ */
1555
+ handler(tasks, handlerOptions) {
1556
+ return createTasksHandler(tasks, handlerOptions);
1557
+ }
1558
+ /**
1559
+ * Trigger a task run on the Sylphx platform.
1560
+ *
1561
+ * The platform will dispatch the task to the app's handler endpoint.
1562
+ * Returns the taskRunId which can be used to poll status.
1563
+ */
1564
+ async trigger(taskName, payload, options) {
1565
+ const response = await this.fetch(
1566
+ "/tasks/trigger",
1567
+ {
1568
+ method: "POST",
1569
+ body: JSON.stringify({
1570
+ taskName,
1571
+ payload,
1572
+ delay: options?.delay,
1573
+ scheduledFor: options?.scheduledFor?.toISOString(),
1574
+ idempotencyKey: options?.idempotencyKey,
1575
+ maxAttempts: options?.maxAttempts
1576
+ })
1577
+ }
1578
+ );
1579
+ return response;
1580
+ }
1581
+ /**
1582
+ * Fetch the current status of a task run.
1583
+ */
1584
+ async getTaskRun(taskRunId) {
1585
+ return this.fetch(`/tasks/${taskRunId}`);
1586
+ }
1587
+ /**
1588
+ * Cancel a pending, running, waiting, or failed task run.
1589
+ */
1590
+ async cancelTaskRun(taskRunId) {
1591
+ const response = await this.fetch(`/tasks/${taskRunId}/cancel`, {
1592
+ method: "POST"
1593
+ });
1594
+ return response.success;
1595
+ }
1596
+ /**
1597
+ * List task runs for the current project/environment.
1598
+ */
1599
+ async listTaskRuns(options) {
1600
+ const params = new URLSearchParams();
1601
+ if (options?.taskName) params.set("taskName", options.taskName);
1602
+ if (options?.status) params.set("status", options.status);
1603
+ if (options?.limit) params.set("limit", String(options.limit));
1604
+ if (options?.offset) params.set("offset", String(options.offset));
1605
+ return this.fetch(`/tasks?${params.toString()}`);
1606
+ }
1607
+ };
1608
+ function createTasksClient(config) {
1609
+ return new TasksClient(config);
1610
+ }
1611
+ var JobsClient = class extends TasksClient {
1612
+ };
1613
+ var createJobsClient = createTasksClient;
1614
+
1615
+ // src/lib/tasks/workflow-builder.ts
1616
+ function createWorkflow(type) {
1617
+ return new WorkflowBuilder(type);
1618
+ }
1619
+ var WorkflowBuilder = class {
1620
+ definition = {};
1621
+ _steps = [];
1622
+ constructor(type) {
1623
+ this.definition.type = type;
1624
+ }
1625
+ /**
1626
+ * Set workflow name
1627
+ */
1628
+ name(name) {
1629
+ this.definition.name = name;
1630
+ return this;
1631
+ }
1632
+ /**
1633
+ * Set workflow description
1634
+ */
1635
+ description(description) {
1636
+ this.definition.description = description;
1637
+ return this;
1638
+ }
1639
+ /**
1640
+ * Set default options
1641
+ */
1642
+ defaults(options) {
1643
+ this.definition.defaults = options;
1644
+ return this;
1645
+ }
1646
+ /**
1647
+ * Add a step to the workflow
1648
+ */
1649
+ step(name, step) {
1650
+ const namedStep = { ...step, name };
1651
+ this._steps.push(namedStep);
1652
+ return this;
1653
+ }
1654
+ /**
1655
+ * Add multiple steps
1656
+ */
1657
+ steps(...steps) {
1658
+ for (const [name, step] of steps) {
1659
+ this.step(name, step);
1660
+ }
1661
+ return this;
1662
+ }
1663
+ /**
1664
+ * Add on complete callback
1665
+ */
1666
+ onComplete(callback) {
1667
+ this.definition.onComplete = callback;
1668
+ return this;
1669
+ }
1670
+ /**
1671
+ * Add on error callback
1672
+ */
1673
+ onError(callback) {
1674
+ this.definition.onError = callback;
1675
+ return this;
1676
+ }
1677
+ /**
1678
+ * Build the workflow definition
1679
+ */
1680
+ build() {
1681
+ return {
1682
+ type: this.definition.type,
1683
+ name: this.definition.name,
1684
+ description: this.definition.description,
1685
+ steps: this._steps,
1686
+ defaults: this.definition.defaults,
1687
+ onComplete: this.definition.onComplete,
1688
+ onError: this.definition.onError
1689
+ };
1690
+ }
1691
+ };
1692
+ function task2(taskType, payload, options) {
1693
+ return {
1694
+ type: "job",
1695
+ name: taskType,
1696
+ jobType: taskType,
1697
+ payload: typeof payload === "function" ? payload : payload ? () => payload : void 0,
1698
+ options
1699
+ };
1700
+ }
1701
+ function conditional(condition, thenSteps, elseSteps) {
1702
+ return {
1703
+ type: "conditional",
1704
+ name: "conditional",
1705
+ condition,
1706
+ // biome-ignore lint/suspicious/noThenProperty: workflow step field name
1707
+ then: thenSteps,
1708
+ else: elseSteps
1709
+ };
1710
+ }
1711
+ function parallel(steps, options) {
1712
+ return {
1713
+ type: "parallel",
1714
+ name: "parallel",
1715
+ steps,
1716
+ waitFor: options?.waitFor || "all",
1717
+ maxConcurrency: options?.maxConcurrency
1718
+ };
1719
+ }
1720
+ function loop(items, step, options) {
1721
+ return {
1722
+ type: "loop",
1723
+ name: "loop",
1724
+ items,
1725
+ step,
1726
+ maxConcurrency: options?.maxConcurrency,
1727
+ breakIf: options?.breakIf
1728
+ };
1729
+ }
1730
+ function wait(until) {
1731
+ return {
1732
+ type: "wait",
1733
+ name: "wait",
1734
+ until
1735
+ };
1736
+ }
1737
+ function subworkflow(workflowType, payload, options) {
1738
+ return {
1739
+ type: "subworkflow",
1740
+ name: workflowType,
1741
+ workflowType,
1742
+ payload: typeof payload === "function" ? payload : payload ? () => payload : void 0,
1743
+ options
1744
+ };
1745
+ }
1746
+ function jobIf(condition, taskType, payload, options) {
1747
+ const step = task2(taskType, payload, options);
1748
+ return {
1749
+ ...step,
1750
+ if: condition
1751
+ };
1752
+ }
1753
+ function delay(ms) {
1754
+ return wait(ms);
1755
+ }
1756
+ function sleepUntil(date) {
1757
+ return wait(date);
1758
+ }
1759
+ function withRetry(step, options) {
1760
+ return {
1761
+ ...step,
1762
+ options: {
1763
+ ...step.options,
1764
+ maxRetries: options.maxRetries,
1765
+ retryDelay: options.retryDelay ? { type: "fixed", delay: options.retryDelay } : void 0
1766
+ }
1767
+ };
1768
+ }
1769
+ function withTimeout(step, timeoutMs) {
1770
+ return {
1771
+ ...step,
1772
+ options: {
1773
+ ...step.options,
1774
+ timeout: timeoutMs
1775
+ }
1776
+ };
1777
+ }
1778
+ function sequence(...workflows) {
1779
+ return workflows.map((workflow, index) => ({
1780
+ type: "subworkflow",
1781
+ name: `sequence-${index}-${workflow.type}`,
1782
+ workflowType: workflow.type
1783
+ }));
1784
+ }
1785
+ function fanOut(items, taskType, payloadMapper, options) {
1786
+ return loop(
1787
+ items,
1788
+ {
1789
+ type: "job",
1790
+ name: `fanout-${taskType}`,
1791
+ jobType: taskType,
1792
+ payload: (ctx) => {
1793
+ return {};
1794
+ }
1795
+ },
1796
+ { maxConcurrency: options?.maxConcurrency }
1797
+ );
1798
+ }
1799
+ function saga(steps) {
1800
+ const workflowSteps = [];
1801
+ for (let i = 0; i < steps.length; i++) {
1802
+ const step = steps[i];
1803
+ const forwardStep = {
1804
+ ...step.forward,
1805
+ name: `saga-forward-${i}-${step.forward.jobType}`,
1806
+ onComplete: (result, ctx) => {
1807
+ ctx.metadata.completedSagaSteps = [
1808
+ ...ctx.metadata.completedSagaSteps || [],
1809
+ i
1810
+ ];
1811
+ return result;
1812
+ }
1813
+ };
1814
+ workflowSteps.push(forwardStep);
1815
+ }
1816
+ return workflowSteps;
1817
+ }
1818
+ function validateWorkflow(workflow) {
1819
+ const errors = [];
1820
+ if (!workflow.type) {
1821
+ errors.push("Workflow type is required");
1822
+ }
1823
+ if (!workflow.steps || workflow.steps.length === 0) {
1824
+ errors.push("Workflow must have at least one step");
1825
+ }
1826
+ const stepNames = /* @__PURE__ */ new Set();
1827
+ const checkSteps = (steps) => {
1828
+ for (const step of steps) {
1829
+ if (stepNames.has(step.name)) {
1830
+ errors.push(`Duplicate step name: ${step.name}`);
1831
+ }
1832
+ stepNames.add(step.name);
1833
+ if (step.type === "conditional") {
1834
+ checkSteps(step.then);
1835
+ if (step.else) checkSteps(step.else);
1836
+ } else if (step.type === "parallel") {
1837
+ checkSteps(step.steps);
1838
+ } else if (step.type === "loop") {
1839
+ checkSteps([step.step]);
1840
+ }
1841
+ }
1842
+ };
1843
+ if (workflow.steps) {
1844
+ checkSteps(workflow.steps);
1845
+ }
1846
+ return errors;
1847
+ }
1848
+ var job = task2;
1849
+ export {
1850
+ DEFAULT_JOBS_CONFIG,
1851
+ DEFAULT_RETRY_DELAYS,
1852
+ JobsClient,
1853
+ StepCompleteSignal,
1854
+ StepSideEffectCompleteSignal,
1855
+ StepSideEffectStartSignal,
1856
+ StepSleepSignal,
1857
+ TasksClient,
1858
+ WorkflowBuilder,
1859
+ cancelTask,
1860
+ conditional,
1861
+ createCron,
1862
+ createJobsClient,
1863
+ createStepContext,
1864
+ createTasksClient,
1865
+ createTasksHandler,
1866
+ createWorkflow,
1867
+ delay,
1868
+ deleteCron,
1869
+ fanOut,
1870
+ getTask,
1871
+ getTaskRun,
1872
+ job,
1873
+ jobIf,
1874
+ listTaskRunDlq,
1875
+ listTasks,
1876
+ loop,
1877
+ parallel,
1878
+ pauseCron,
1879
+ replayTaskRun,
1880
+ resumeCron,
1881
+ saga,
1882
+ scheduleTask,
1883
+ sequence,
1884
+ serve,
1885
+ sleepUntil,
1886
+ subworkflow,
1887
+ task,
1888
+ taskStub,
1889
+ validateWorkflow,
1890
+ verifySignature,
1891
+ wait,
1892
+ withRetry,
1893
+ withTimeout
1894
+ };
1895
+ //# sourceMappingURL=tasks.mjs.map