@altenginenet/sdk 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1974 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AltEngine: () => AltEngine,
24
+ AltEngineError: () => AltEngineError,
25
+ AltEngineNetworkError: () => AltEngineNetworkError,
26
+ AuthClient: () => AuthClient,
27
+ AutomationClient: () => AutomationClient,
28
+ BlobClient: () => BlobClient,
29
+ ChannelClient: () => ChannelClient,
30
+ ChannelSocket: () => ChannelSocket,
31
+ ContainerClient: () => ContainerClient,
32
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
33
+ DEFAULT_WEBHOOK_TOLERANCE_MS: () => DEFAULT_WEBHOOK_TOLERANCE_MS,
34
+ DEV_BASE_URL: () => DEV_BASE_URL,
35
+ DatastoreClient: () => DatastoreClient,
36
+ MAX_SINGLE_PUT_BYTES: () => MAX_SINGLE_PUT_BYTES,
37
+ MAX_WAIT_SECONDS: () => MAX_WAIT_SECONDS,
38
+ MailboxClient: () => MailboxClient,
39
+ NamespaceAdmin: () => NamespaceAdmin,
40
+ SearchClient: () => SearchClient,
41
+ SearchIndex: () => SearchIndex,
42
+ TASK_MAX_ATTEMPTS_HEADER: () => TASK_MAX_ATTEMPTS_HEADER,
43
+ TASK_RETRY_AFTER_HEADER: () => TASK_RETRY_AFTER_HEADER,
44
+ TASK_RETRY_HEADER: () => TASK_RETRY_HEADER,
45
+ TasksClient: () => TasksClient,
46
+ WEBHOOK_SIGNATURE_HEADER: () => WEBHOOK_SIGNATURE_HEADER,
47
+ WEBHOOK_TIMESTAMP_HEADER: () => WEBHOOK_TIMESTAMP_HEADER,
48
+ attachmentBase64: () => attachmentBase64,
49
+ blobFromJobEnv: () => blobFromJobEnv,
50
+ defaultStorage: () => defaultStorage,
51
+ f: () => f,
52
+ facet: () => facet,
53
+ memoryStorage: () => memoryStorage,
54
+ verifyWebhook: () => verifyWebhook
55
+ });
56
+ module.exports = __toCommonJS(src_exports);
57
+
58
+ // src/errors.ts
59
+ var AltEngineError = class extends Error {
60
+ code;
61
+ status;
62
+ details;
63
+ /** Seconds to wait before retrying, from the `Retry-After` header (429s). */
64
+ retryAfter;
65
+ constructor(opts) {
66
+ super(opts.message);
67
+ this.name = "AltEngineError";
68
+ this.code = opts.code;
69
+ this.status = opts.status;
70
+ this.details = opts.details;
71
+ this.retryAfter = opts.retryAfter;
72
+ }
73
+ /** Whether the request can be safely retried after a backoff. 429 always carries
74
+ * Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */
75
+ get retryable() {
76
+ if (this.status === 429) return true;
77
+ return this.status === 502 || this.status === 503 || this.status === 504;
78
+ }
79
+ };
80
+ var AltEngineNetworkError = class extends Error {
81
+ cause;
82
+ constructor(message, cause) {
83
+ super(message);
84
+ this.name = "AltEngineNetworkError";
85
+ this.cause = cause;
86
+ }
87
+ };
88
+
89
+ // src/constants.ts
90
+ var DEFAULT_BASE_URL = "https://api.altengine.net";
91
+ var DEV_BASE_URL = "http://127.0.0.1:9191";
92
+ var seg = (s) => encodeURIComponent(String(s));
93
+ var nsSeg = (namespace) => seg(namespace === "" ? "_default" : namespace);
94
+
95
+ // src/http.ts
96
+ var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
97
+ function resolveBaseUrl(opts) {
98
+ if (opts.baseUrl) return opts.baseUrl;
99
+ if (opts.dev) return DEV_BASE_URL;
100
+ return env("ALTENGINE_URL") ?? DEFAULT_BASE_URL;
101
+ }
102
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
103
+ var Http = class {
104
+ baseUrl;
105
+ apiKey;
106
+ auth;
107
+ fetchImpl;
108
+ timeoutMs;
109
+ retry;
110
+ constructor(opts = {}) {
111
+ this.baseUrl = resolveBaseUrl(opts).replace(/\/+$/, "");
112
+ this.apiKey = opts.apiKey ?? env("ALTENGINE_API_KEY") ?? env("ALTENGINE_KEY");
113
+ this.auth = opts.auth;
114
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
115
+ if (!this.fetchImpl) throw new Error("no fetch implementation available; pass { fetch }");
116
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
117
+ this.retry = {
118
+ maxAttempts: opts.retry?.maxAttempts ?? 3,
119
+ baseDelayMs: opts.retry?.baseDelayMs ?? 250,
120
+ maxDelayMs: opts.retry?.maxDelayMs ?? 4e3
121
+ };
122
+ }
123
+ url(path, query) {
124
+ let url = this.baseUrl + path;
125
+ if (query) {
126
+ const qs = new URLSearchParams();
127
+ for (const [k, v] of Object.entries(query)) {
128
+ if (v !== void 0) qs.set(k, String(v));
129
+ }
130
+ const s = qs.toString();
131
+ if (s) url += "?" + s;
132
+ }
133
+ return url;
134
+ }
135
+ async request(method, path, opts = {}) {
136
+ const retry = opts.retry === false ? { maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0 } : { ...this.retry, ...opts.retry ?? {} };
137
+ let lastErr;
138
+ for (let attempt = 1; ; attempt++) {
139
+ try {
140
+ return await this.once(method, path, opts);
141
+ } catch (err) {
142
+ lastErr = err;
143
+ const retryable = err instanceof AltEngineNetworkError || err instanceof AltEngineError && err.retryable;
144
+ if (!retryable || attempt >= retry.maxAttempts) throw err;
145
+ let delay = Math.min(retry.baseDelayMs * 2 ** (attempt - 1), retry.maxDelayMs);
146
+ if (err instanceof AltEngineError && err.retryAfter !== void 0) {
147
+ delay = Math.max(delay, err.retryAfter * 1e3);
148
+ }
149
+ await sleep(delay * (0.5 + Math.random() * 0.5));
150
+ }
151
+ }
152
+ throw lastErr;
153
+ }
154
+ /**
155
+ * Fetch a URL that is NOT the altengine API — a presigned upload or download link.
156
+ *
157
+ * CARRIES NO CREDENTIAL OF OURS. A presigned URL's signature is the whole credential, and an
158
+ * org API key sent to object storage is an org API key handed to a third party. The bytes go
159
+ * straight between the caller and storage; nothing is proxied through the API.
160
+ *
161
+ * The client's request timeout does not apply either — a 20 GB upload is not a control-plane
162
+ * call. Bound it with `init.signal`.
163
+ */
164
+ async transfer(url, init = {}) {
165
+ const method = init.method ?? "GET";
166
+ let res;
167
+ try {
168
+ res = await this.fetchImpl(url, init);
169
+ } catch (err) {
170
+ throw new AltEngineNetworkError(`transfer failed: ${method} ${scrub(url)}`, err);
171
+ }
172
+ if (!res.ok) throw await toTransferError(res, method, url);
173
+ return res;
174
+ }
175
+ async once(method, path, opts) {
176
+ const headers = { ...opts.headers };
177
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "authorization")) {
178
+ const token = await this.auth?.getToken();
179
+ if (token) headers["authorization"] = `Bearer ${token}`;
180
+ else if (this.apiKey) headers["authorization"] = `Bearer ${this.apiKey}`;
181
+ }
182
+ let body;
183
+ if (opts.body !== void 0) {
184
+ headers["content-type"] = "application/json";
185
+ body = JSON.stringify(opts.body);
186
+ }
187
+ const ctrl = new AbortController();
188
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? this.timeoutMs);
189
+ let res;
190
+ try {
191
+ res = await this.fetchImpl(this.url(path, opts.query), { method, headers, body, signal: ctrl.signal });
192
+ } catch (err) {
193
+ throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);
194
+ } finally {
195
+ clearTimeout(timer);
196
+ }
197
+ if (!res.ok && !opts.acceptStatus?.includes(res.status)) throw await toApiError(res);
198
+ if (res.status === 204) return void 0;
199
+ return await res.json();
200
+ }
201
+ };
202
+ async function toApiError(res) {
203
+ let code = "INTERNAL";
204
+ let message = `HTTP ${res.status}`;
205
+ let details;
206
+ try {
207
+ const parsed = await res.json();
208
+ if (parsed?.error) {
209
+ code = parsed.error.code ?? code;
210
+ message = parsed.error.message ?? message;
211
+ details = parsed.error.details;
212
+ }
213
+ } catch {
214
+ }
215
+ const ra = res.headers.get("retry-after");
216
+ const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : void 0;
217
+ return new AltEngineError({ code, message, status: res.status, details, retryAfter });
218
+ }
219
+ var scrub = (url) => url.split("?")[0] ?? url;
220
+ async function toTransferError(res, method, url) {
221
+ const text = (await res.text().catch(() => "")).slice(0, 1e3);
222
+ let code = "INTERNAL";
223
+ let message = "";
224
+ try {
225
+ const parsed = JSON.parse(text);
226
+ if (parsed?.error) {
227
+ code = parsed.error.code ?? code;
228
+ message = parsed.error.message ?? "";
229
+ }
230
+ } catch {
231
+ code = /<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? code;
232
+ message = /<Message>([^<]+)<\/Message>/.exec(text)?.[1] ?? "";
233
+ }
234
+ if (!message) {
235
+ const snippet = text.replace(/\s+/g, " ").trim().slice(0, 200);
236
+ message = `${method} ${scrub(url)} failed with HTTP ${res.status}${snippet ? `: ${snippet}` : ""}`;
237
+ }
238
+ return new AltEngineError({ code, message, status: res.status });
239
+ }
240
+
241
+ // src/datastore/client.ts
242
+ var DatastoreClient = class _DatastoreClient {
243
+ instance;
244
+ namespace;
245
+ /** Namespace administration for the whole instance (not namespace-bound). */
246
+ namespaces;
247
+ http;
248
+ base;
249
+ nsBase;
250
+ constructor(http, instance, opts = {}) {
251
+ this.http = http;
252
+ this.instance = instance;
253
+ this.namespace = opts.namespace ?? "";
254
+ this.base = `/v1/datastore/${seg(instance)}`;
255
+ this.nsBase = `${this.base}/ns/${nsSeg(this.namespace)}`;
256
+ this.namespaces = new NamespaceAdmin(http, this.base);
257
+ }
258
+ /** Same instance, different namespace. */
259
+ withNamespace(namespace) {
260
+ return new _DatastoreClient(this.http, this.instance, { namespace });
261
+ }
262
+ /** Upsert up to 500 documents; returns their keys in order. */
263
+ async put(collection, documents) {
264
+ return this.http.request("POST", `${this.nsBase}/col/${seg(collection)}/documents`, {
265
+ body: { documents },
266
+ retry: documents.every((doc) => doc.key != null) ? void 0 : false
267
+ });
268
+ }
269
+ async get(collection, keyOrKeys) {
270
+ const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];
271
+ const res = await this.http.request(
272
+ "POST",
273
+ `${this.nsBase}/col/${seg(collection)}/documents/get`,
274
+ { body: { keys } }
275
+ );
276
+ const byKey = new Map(res.documents.map((d) => [d.key, d]));
277
+ const docs = keys.map((k) => byKey.get(String(k)) ?? null);
278
+ return Array.isArray(keyOrKeys) ? docs : docs[0];
279
+ }
280
+ /** Delete up to 500 documents by key; missing keys are no-ops. */
281
+ async delete(collection, keys) {
282
+ return this.http.request("POST", `${this.nsBase}/col/${seg(collection)}/documents/delete`, {
283
+ body: { keys }
284
+ });
285
+ }
286
+ /** Run one page of an index-served query. */
287
+ async query(collection, req = {}) {
288
+ return this.http.request("POST", `${this.nsBase}/col/${seg(collection)}/query`, { body: req });
289
+ }
290
+ /** Iterate every matching document across pages (cursor handled for you). */
291
+ async *queryAll(collection, req = {}) {
292
+ let cursor = req.cursor;
293
+ do {
294
+ const page = await this.query(collection, { ...req, cursor: cursor ?? void 0 });
295
+ for (const doc of page.documents ?? []) yield doc;
296
+ cursor = page.cursor;
297
+ } while (cursor);
298
+ }
299
+ /** Grouped metrics over an index-served filter. */
300
+ async aggregate(collection, req) {
301
+ return this.http.request("POST", `${this.nsBase}/col/${seg(collection)}/aggregate`, { body: req });
302
+ }
303
+ /** Apply up to 500 operations atomically within this namespace. NOT retried
304
+ * automatically (increments would double-apply); a failed `check` throws a 409. */
305
+ async transaction(operations) {
306
+ return this.http.request("POST", `${this.nsBase}/transaction`, { body: { operations }, retry: false });
307
+ }
308
+ indexes = {
309
+ list: async (collection) => this.http.request("GET", `${this.nsBase}/col/${seg(collection)}/indexes`),
310
+ create: async (collection, req) => this.http.request("POST", `${this.nsBase}/col/${seg(collection)}/indexes`, { body: req }),
311
+ delete: async (collection, id) => this.http.request("DELETE", `${this.nsBase}/col/${seg(collection)}/indexes/${seg(id)}`)
312
+ };
313
+ };
314
+ var NamespaceAdmin = class {
315
+ constructor(http, base) {
316
+ this.http = http;
317
+ this.base = base;
318
+ }
319
+ http;
320
+ base;
321
+ /** A page of the instance's namespaces, newest first. When `has_more` is set, pass the
322
+ * returned `cursor` back as `cursor` for the next page. */
323
+ async list(opts = {}) {
324
+ return this.http.request("GET", `${this.base}/ns`, { query: { q: opts.q, limit: opts.limit, cursor: opts.cursor } });
325
+ }
326
+ /** Delete a namespace and everything in it. Requires a `full` grant. */
327
+ async delete(namespace) {
328
+ return this.http.request("DELETE", `${this.base}/ns/${nsSeg(namespace)}`);
329
+ }
330
+ };
331
+
332
+ // src/search/client.ts
333
+ var SearchClient = class _SearchClient {
334
+ instance;
335
+ namespace;
336
+ http;
337
+ base;
338
+ /** Namespace-scoped base: `/v1/search/{instance}/ns/{ns}`. */
339
+ nsBase;
340
+ constructor(http, instance, opts = {}) {
341
+ this.http = http;
342
+ this.instance = instance;
343
+ this.namespace = opts.namespace ?? "";
344
+ this.base = `/v1/search/${seg(instance)}`;
345
+ this.nsBase = `${this.base}/ns/${nsSeg(this.namespace)}`;
346
+ }
347
+ /** Same instance, different namespace. */
348
+ withNamespace(namespace) {
349
+ return new _SearchClient(this.http, this.instance, { namespace });
350
+ }
351
+ index(name) {
352
+ return new SearchIndex(this.http, this.nsBase, name);
353
+ }
354
+ /** Indexes in this client's namespace. When `has_more` is set, pass the returned `cursor`
355
+ * back as `cursor` for the next page. */
356
+ async listIndexes(opts = {}) {
357
+ return this.http.request("GET", `${this.nsBase}/idx`, {
358
+ query: { q: opts.q, limit: opts.limit, cursor: opts.cursor }
359
+ });
360
+ }
361
+ /** Every index in this client's namespace, following the cursor for you.
362
+ *
363
+ * Stops on a cursor that does not advance as well as on a missing one: an SDK outlives the
364
+ * deployment it was written against, and a server that keeps handing back the same cursor
365
+ * would otherwise be followed for ever, billing each round. Same rule as `searchAll`. */
366
+ async *listAllIndexes(opts = {}) {
367
+ const seen = /* @__PURE__ */ new Set();
368
+ let cursor;
369
+ for (; ; ) {
370
+ const page = await this.listIndexes({ ...opts, cursor });
371
+ for (const index of page.indexes ?? []) yield index;
372
+ const next = page.cursor ?? void 0;
373
+ if (!page.indexes?.length || !next || seen.has(next)) return;
374
+ seen.add(next);
375
+ cursor = next;
376
+ }
377
+ }
378
+ /** Distinct namespaces with live indexes — alphabetical, `q` substring search,
379
+ * `limit` default 50 (max 100). Instance-wide (not bound to this client's
380
+ * namespace); the default namespace appears as `""`. */
381
+ async listNamespaces(opts = {}) {
382
+ return this.http.request("GET", `${this.base}/ns`, { query: { q: opts.q, limit: opts.limit } });
383
+ }
384
+ /** Delete an index and all its documents. Requires a `full` grant. */
385
+ async deleteIndex(name) {
386
+ return this.http.request("DELETE", `${this.nsBase}/idx/${seg(name)}`);
387
+ }
388
+ };
389
+ var SearchIndex = class {
390
+ constructor(http, nsBase, name) {
391
+ this.http = http;
392
+ this.name = name;
393
+ this.path = `${nsBase}/idx/${seg(name)}`;
394
+ }
395
+ http;
396
+ name;
397
+ path;
398
+ /** Upsert up to 200 documents; returns their ids in order (server-assigned when
399
+ * a document omits `id`). */
400
+ async put(documents) {
401
+ return this.http.request("POST", `${this.path}/documents`, { body: { documents } });
402
+ }
403
+ async get(idOrIds) {
404
+ const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
405
+ const res = await this.http.request(
406
+ "POST",
407
+ `${this.path}/documents/get`,
408
+ { body: { ids } }
409
+ );
410
+ const byId = new Map(res.documents.map((d) => [d.id, d]));
411
+ const docs = ids.map((id) => byId.get(id) ?? null);
412
+ return Array.isArray(idOrIds) ? docs : docs[0];
413
+ }
414
+ /** Delete up to 200 documents by id; missing ids are no-ops. Requires `full`. */
415
+ async delete(ids) {
416
+ return this.http.request("POST", `${this.path}/documents/delete`, { body: { ids } });
417
+ }
418
+ /** Run a search request (see `SearchRequest` for the full surface). */
419
+ async search(req) {
420
+ return this.http.request("POST", `${this.path}/search`, { body: req });
421
+ }
422
+ /**
423
+ * Iterate every hit across cursor pages.
424
+ *
425
+ * Stops on a cursor that does not advance, as well as on a missing one. Search paging ends at a
426
+ * fixed depth, and a server that kept issuing a cursor past it handed back the SAME page — so
427
+ * "follow the cursor until it is absent", which is what this loop did, fetched that page for
428
+ * ever and billed each round. The server no longer does that; this is the half that does not
429
+ * depend on which version you are talking to, since an SDK outlives the deployment it was
430
+ * written against.
431
+ */
432
+ async *searchAll(req) {
433
+ let cursor = req.cursor;
434
+ const seen = /* @__PURE__ */ new Set();
435
+ for (; ; ) {
436
+ const page = await this.search({ ...req, cursor, offset: void 0 });
437
+ for (const hit of page.results) yield hit;
438
+ const next = page.cursor;
439
+ if (!next || next === cursor || seen.has(next) || page.results.length === 0) return;
440
+ seen.add(next);
441
+ cursor = next;
442
+ }
443
+ }
444
+ async listDocuments(opts = {}) {
445
+ return this.http.request("GET", `${this.path}/documents`, {
446
+ query: {
447
+ start_id: opts.start_id,
448
+ include_start: opts.include_start,
449
+ limit: opts.limit,
450
+ ids_only: opts.ids_only
451
+ }
452
+ });
453
+ }
454
+ /** Iterate every document in the index (keyset pagination handled for you). */
455
+ async *listAllDocuments(opts = {}) {
456
+ let startId;
457
+ for (; ; ) {
458
+ const page = await this.listDocuments({
459
+ start_id: startId,
460
+ include_start: startId === void 0,
461
+ limit: opts.limit
462
+ });
463
+ const docs = page.documents;
464
+ if (!docs.length) return;
465
+ for (const doc of docs) yield doc;
466
+ startId = docs[docs.length - 1].id;
467
+ }
468
+ }
469
+ /** The index's union field schema. */
470
+ async schema() {
471
+ return this.http.request("GET", `${this.path}/schema`);
472
+ }
473
+ };
474
+
475
+ // src/channel/client.ts
476
+ var ChannelClient = class {
477
+ instance;
478
+ http;
479
+ base;
480
+ constructor(http, instance) {
481
+ this.http = http;
482
+ this.instance = instance;
483
+ this.base = `/v1/channel/${seg(instance)}`;
484
+ }
485
+ /** Mint a subscriber token (JWT) for the given channels. */
486
+ async createToken(req) {
487
+ return this.http.request("POST", `${this.base}/tokens`, { body: req });
488
+ }
489
+ /** Publish a message (framed ≤32 KiB) to a channel; returns the number of
490
+ * subscribers reached. NOT retried automatically (a retry double-delivers). */
491
+ async publish(channel, data) {
492
+ return this.http.request("POST", `${this.base}/publish`, { body: { channel, data }, retry: false });
493
+ }
494
+ /** Presence roster for a channel (requires the instance's presence flag). */
495
+ async presence(channel) {
496
+ return this.http.request("GET", `${this.base}/presence`, { query: { channel } });
497
+ }
498
+ };
499
+
500
+ // src/auth/storage.ts
501
+ function memoryStorage() {
502
+ const map = /* @__PURE__ */ new Map();
503
+ return {
504
+ get: (k) => map.get(k) ?? null,
505
+ set: (k, v) => void map.set(k, v),
506
+ remove: (k) => void map.delete(k)
507
+ };
508
+ }
509
+ function defaultStorage() {
510
+ try {
511
+ const ls = globalThis.localStorage;
512
+ if (!ls) return memoryStorage();
513
+ const probe = "__altengine_probe__";
514
+ ls.setItem(probe, "1");
515
+ ls.removeItem(probe);
516
+ return {
517
+ get: (k) => ls.getItem(k),
518
+ set: (k, v) => ls.setItem(k, v),
519
+ remove: (k) => ls.removeItem(k)
520
+ };
521
+ } catch {
522
+ return memoryStorage();
523
+ }
524
+ }
525
+
526
+ // src/auth/client.ts
527
+ var nowSec = () => Math.floor(Date.now() / 1e3);
528
+ var AuthClient = class {
529
+ instance;
530
+ baseUrl;
531
+ base;
532
+ storage;
533
+ key;
534
+ fetchImpl;
535
+ skew;
536
+ listeners = /* @__PURE__ */ new Set();
537
+ session;
538
+ /** In-flight refresh, so concurrent requests share one round trip. */
539
+ refreshing = null;
540
+ constructor(opts) {
541
+ if (!opts.instance) throw new Error("AuthClient requires an `instance`");
542
+ this.instance = opts.instance;
543
+ this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\/+$/, "");
544
+ this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;
545
+ this.storage = opts.storage ?? defaultStorage();
546
+ this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;
547
+ const f2 = opts.fetch ?? globalThis.fetch;
548
+ if (!f2) throw new Error("no fetch implementation available; pass { fetch }");
549
+ this.fetchImpl = f2;
550
+ this.skew = opts.refreshSkewSeconds ?? 30;
551
+ this.session = this.load();
552
+ }
553
+ // --- session state ------------------------------------------------------
554
+ /** The signed-in user, or null. Reads persisted state, so it survives reloads. */
555
+ get user() {
556
+ return this.session?.user ?? null;
557
+ }
558
+ get isSignedIn() {
559
+ return !!this.session?.id_token;
560
+ }
561
+ /** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */
562
+ onChange(fn) {
563
+ this.listeners.add(fn);
564
+ return () => void this.listeners.delete(fn);
565
+ }
566
+ emit() {
567
+ for (const fn of this.listeners) {
568
+ try {
569
+ fn(this.user);
570
+ } catch {
571
+ }
572
+ }
573
+ }
574
+ load() {
575
+ try {
576
+ const raw = this.storage.get(this.key);
577
+ return raw ? JSON.parse(raw) : null;
578
+ } catch {
579
+ return null;
580
+ }
581
+ }
582
+ save(s) {
583
+ this.session = s;
584
+ try {
585
+ if (s) this.storage.set(this.key, JSON.stringify(s));
586
+ else this.storage.remove(this.key);
587
+ } catch {
588
+ }
589
+ this.emit();
590
+ }
591
+ adopt(t) {
592
+ const user = t.user ?? this.session?.user ?? null;
593
+ this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });
594
+ return { ...t, user };
595
+ }
596
+ // --- transport ----------------------------------------------------------
597
+ async call(method, path, body, bearer) {
598
+ const headers = {};
599
+ if (bearer) headers["authorization"] = `Bearer ${bearer}`;
600
+ if (body !== void 0) headers["content-type"] = "application/json";
601
+ let res;
602
+ try {
603
+ res = await this.fetchImpl(this.base + path, {
604
+ method,
605
+ headers,
606
+ body: body === void 0 ? void 0 : JSON.stringify(body)
607
+ });
608
+ } catch (err) {
609
+ throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);
610
+ }
611
+ if (!res.ok) throw await toError(res);
612
+ if (res.status === 204) return void 0;
613
+ return await res.json();
614
+ }
615
+ // --- config -------------------------------------------------------------
616
+ /** The instance's public sign-in configuration — which fields the sign-up form
617
+ * collects, which one is the login identity, and which methods are enabled.
618
+ * Fetch this to render a sign-in UI that matches the instance's settings. */
619
+ async config() {
620
+ return this.call("GET", "/config");
621
+ }
622
+ // --- sign up / in / out -------------------------------------------------
623
+ /** Create an account. Pass the configured sign-up fields plus `password`,
624
+ * e.g. `{ email, name, password }`. Signs the new user in. */
625
+ async signUp(fields) {
626
+ const t = await this.call("POST", "/signup", fields);
627
+ return this.adopt(t);
628
+ }
629
+ /** Sign in with the identity field + password. When the account has two-factor
630
+ * enabled this resolves to `{ status: "mfa_required" }` and you must call
631
+ * {@link verifyMfa} with the code — no tokens are issued until then. */
632
+ async signIn(identifier, password) {
633
+ const t = await this.call("POST", "/signin", {
634
+ identifier,
635
+ password
636
+ });
637
+ if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
638
+ return { status: "signed_in", session: this.adopt(t) };
639
+ }
640
+ /** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */
641
+ async verifyMfa(mfaToken, code) {
642
+ const t = await this.call("POST", "/2fa/verify", { mfa_token: mfaToken, code });
643
+ return this.adopt(t);
644
+ }
645
+ /** Start passwordless sign-in: emails a one-time code. Always resolves — the
646
+ * server never reveals whether the account exists. */
647
+ async passwordlessStart(identifier) {
648
+ await this.call("POST", "/passwordless/start", { identifier });
649
+ }
650
+ /** Finish passwordless sign-in with the emailed code. */
651
+ async passwordlessVerify(identifier, code) {
652
+ const t = await this.call("POST", "/passwordless/verify", {
653
+ identifier,
654
+ code
655
+ });
656
+ if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
657
+ return { status: "signed_in", session: this.adopt(t) };
658
+ }
659
+ /** Start a password reset: emails a one-time code. Always resolves. */
660
+ async passwordResetStart(identifier) {
661
+ await this.call("POST", "/password/reset/start", { identifier });
662
+ }
663
+ /** Finish a password reset with the emailed code and a new password. */
664
+ async passwordResetVerify(identifier, code, password) {
665
+ await this.call("POST", "/password/reset/verify", { identifier, code, password });
666
+ }
667
+ /** The signed-in user, re-read from the server (picks up claim changes). */
668
+ async me() {
669
+ const tok = await this.getToken();
670
+ if (!tok) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
671
+ const { user } = await this.call("GET", "/me", void 0, tok);
672
+ if (user && this.session) this.save({ ...this.session, user });
673
+ return user;
674
+ }
675
+ /** Revoke the refresh token server-side and clear local state. Always clears
676
+ * locally, even if the network call fails. */
677
+ async signOut() {
678
+ const rt = this.session?.refresh_token;
679
+ this.save(null);
680
+ if (rt) {
681
+ try {
682
+ await this.call("POST", "/signout", { refresh_token: rt });
683
+ } catch {
684
+ }
685
+ }
686
+ }
687
+ // --- tokens -------------------------------------------------------------
688
+ /** Force a refresh-token rotation and return the new id_token. */
689
+ async refresh() {
690
+ const rt = this.session?.refresh_token;
691
+ if (!rt) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
692
+ const t = await this.call("POST", "/token/refresh", { refresh_token: rt });
693
+ this.adopt(t);
694
+ return t.id_token;
695
+ }
696
+ /**
697
+ * The current id_token, refreshed first if it is expired or about to be.
698
+ * Returns `undefined` when nobody is signed in. This is the `TokenProvider`
699
+ * the SDK calls before every Datastore/Search/Channel request — pass the
700
+ * client as `new AltEngine({ auth })` and tokens stay fresh automatically.
701
+ *
702
+ * Concurrent callers share a single refresh. If the refresh fails because the
703
+ * session is truly gone (401/403), local state is cleared so the app can react
704
+ * via {@link onChange} instead of retrying forever.
705
+ */
706
+ async getToken() {
707
+ const s = this.session;
708
+ if (!s?.id_token) return void 0;
709
+ if (s.expires_at - this.skew > nowSec()) return s.id_token;
710
+ if (!this.refreshing) {
711
+ this.refreshing = this.refresh().catch((err) => {
712
+ if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {
713
+ this.save(null);
714
+ return void 0;
715
+ }
716
+ throw err;
717
+ }).finally(() => {
718
+ this.refreshing = null;
719
+ });
720
+ }
721
+ return this.refreshing;
722
+ }
723
+ };
724
+ async function toError(res) {
725
+ let code = "INTERNAL";
726
+ let message = `HTTP ${res.status}`;
727
+ let details;
728
+ try {
729
+ const parsed = await res.json();
730
+ if (parsed?.error) {
731
+ code = parsed.error.code ?? code;
732
+ message = parsed.error.message ?? message;
733
+ details = parsed.error.details;
734
+ }
735
+ } catch {
736
+ }
737
+ const ra = res.headers.get("retry-after");
738
+ const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : void 0;
739
+ return new AltEngineError({ code, message, status: res.status, details, retryAfter });
740
+ }
741
+
742
+ // src/poll.ts
743
+ function sleep2(ms, signal) {
744
+ return new Promise((resolve, reject) => {
745
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
746
+ const t = setTimeout(() => {
747
+ signal?.removeEventListener("abort", onAbort);
748
+ resolve();
749
+ }, ms);
750
+ function onAbort() {
751
+ clearTimeout(t);
752
+ reject(signal?.reason ?? new Error("aborted"));
753
+ }
754
+ signal?.addEventListener("abort", onAbort, { once: true });
755
+ });
756
+ }
757
+
758
+ // src/automation/client.ts
759
+ var POLL_START_MS = 2e3;
760
+ var POLL_MAX_MS = 15e3;
761
+ var TERMINAL = /* @__PURE__ */ new Set(["done", "failed", "canceled", "abandoned"]);
762
+ var AutomationClient = class {
763
+ instance;
764
+ http;
765
+ base;
766
+ constructor(http, instance) {
767
+ this.http = http;
768
+ this.instance = instance;
769
+ this.base = `/v1/automation/${seg(instance)}`;
770
+ }
771
+ // --- runs ---------------------------------------------------------------
772
+ /**
773
+ * Start a run and return immediately.
774
+ *
775
+ * A `queued` run is NOT a failure — it means no machine matching the request is online yet, and
776
+ * an office PC being asleep is the ordinary case. It will be dispatched when one connects.
777
+ */
778
+ async start(req) {
779
+ const { run } = await this.http.request("POST", `${this.base}/runs`, {
780
+ body: req,
781
+ // A retried start is a SECOND RUN: it drives a real application, so a duplicate is a second
782
+ // pass over the same invoices rather than a wasted request.
783
+ retry: false
784
+ });
785
+ return run;
786
+ }
787
+ /** A run and its artifacts, each with a freshly minted download link. */
788
+ async get(runId) {
789
+ return this.http.request("GET", `${this.base}/runs/${seg(runId)}`);
790
+ }
791
+ async list(query = {}) {
792
+ return this.http.request("GET", `${this.base}/runs`, { query });
793
+ }
794
+ /** Stop a queued or running run. The script unwinds through its own cleanup. */
795
+ async cancel(runId) {
796
+ return this.http.request("POST", `${this.base}/runs/${seg(runId)}/cancel`, { retry: false });
797
+ }
798
+ /**
799
+ * A page of the run's log.
800
+ *
801
+ * While the run is going this is a live tail from the machine — the last few hundred lines, not
802
+ * a transcript. Once it finishes it is the complete log the run uploaded, so a finished run is
803
+ * readable even from a machine that has since been switched off. `source` says which answered.
804
+ */
805
+ async logs(runId, query = {}) {
806
+ return this.http.request("GET", `${this.base}/runs/${seg(runId)}/logs`, { query });
807
+ }
808
+ /** The run's artifacts, each with a freshly minted download link. */
809
+ async artifacts(runId) {
810
+ const { artifacts } = await this.http.request(
811
+ "GET",
812
+ `${this.base}/runs/${seg(runId)}/artifacts`
813
+ );
814
+ return artifacts;
815
+ }
816
+ /**
817
+ * Poll until a run reaches a terminal status, then return it with its artifacts.
818
+ *
819
+ * THE RUN IS FINISHED WHEN ITS OUTPUT HAS LANDED, not when its script returned — the agent holds
820
+ * the terminal report until every artifact has been stored — so a `done` here always has its
821
+ * files, and the links on them are live.
822
+ *
823
+ * `timeoutMs` bounds the WAIT, not the run: giving up here leaves the run going on the machine.
824
+ * Call `cancel` if that is what you meant. Zero (the default) waits indefinitely, which is
825
+ * usually right for a job that legitimately takes hours.
826
+ */
827
+ async wait(runId, opts = {}) {
828
+ const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : 0;
829
+ let delay = POLL_START_MS;
830
+ for (; ; ) {
831
+ const current = await this.get(runId);
832
+ opts.onPoll?.(current.run);
833
+ if (TERMINAL.has(current.run.status)) return current;
834
+ if (deadline && Date.now() >= deadline) {
835
+ throw new Error(
836
+ `run ${runId} was still ${current.run.status} after ${opts.timeoutMs}ms \u2014 it is still going on the machine; cancel it if that is not what you want`
837
+ );
838
+ }
839
+ let ms = delay;
840
+ if (deadline) ms = Math.min(ms, Math.max(0, deadline - Date.now()));
841
+ await sleep2(ms, opts.signal);
842
+ delay = Math.min(delay * 2, POLL_MAX_MS);
843
+ }
844
+ }
845
+ /** Start a run and wait for it. Convenience over `start` + `wait`. */
846
+ async run(req, opts = {}) {
847
+ const started = await this.start(req);
848
+ return this.wait(started.id, opts);
849
+ }
850
+ // --- machines, scripts, schedules ---------------------------------------
851
+ /** Enrolled machines, with whether each is connected right now. */
852
+ /**
853
+ * One page of enrolled machines, with whether each is connected right now.
854
+ *
855
+ * PAGED, and the cursor matters: a fleet of hundreds is the ordinary shape of this service —
856
+ * an office, a chain of dealerships — and a caller that ignores it is looking at part of one.
857
+ * `q` matches name, hostname or label, which are the three things a machine is known by.
858
+ */
859
+ async agents(query = {}) {
860
+ return this.http.request("GET", `${this.base}/agents`, { query });
861
+ }
862
+ /**
863
+ * Every enrolled machine, walking the pages for you.
864
+ *
865
+ * Here because the alternative — a `agents()` that quietly returned the first page — is how a
866
+ * fleet with more machines than a page silently became a smaller fleet. If you are counting
867
+ * machines, or acting on all of them, use this one.
868
+ */
869
+ async allAgents(query = {}) {
870
+ const out = [];
871
+ let cursor;
872
+ for (; ; ) {
873
+ const page = await this.agents({ ...query, cursor });
874
+ out.push(...page.agents);
875
+ if (!page.cursor) return out;
876
+ cursor = page.cursor;
877
+ }
878
+ }
879
+ async agent(agentId) {
880
+ return this.http.request("GET", `${this.base}/agents/${seg(agentId)}`);
881
+ }
882
+ /**
883
+ * One page of deployed scripts and their active versions. Deploy with the CLI.
884
+ *
885
+ * PAGED, like `agents`. Both routes return a cursor and both used to have it dropped here, so a
886
+ * caller past the first page saw part of an answer and was told nothing — which is the exact
887
+ * shape the `agents`/`allAgents` pair below already exists to avoid.
888
+ */
889
+ async scripts(query = {}) {
890
+ return this.http.request("GET", `${this.base}/scripts`, { query });
891
+ }
892
+ /** Every deployed script, walking the pages for you. */
893
+ async allScripts() {
894
+ const out = [];
895
+ let cursor;
896
+ for (; ; ) {
897
+ const page = await this.scripts({ cursor });
898
+ out.push(...page.scripts);
899
+ if (!page.cursor) return out;
900
+ cursor = page.cursor;
901
+ }
902
+ }
903
+ /** One page of declared schedules. */
904
+ async schedules(query = {}) {
905
+ return this.http.request("GET", `${this.base}/schedules`, { query });
906
+ }
907
+ /** Every declared schedule, walking the pages for you. */
908
+ async allSchedules() {
909
+ const out = [];
910
+ let cursor;
911
+ for (; ; ) {
912
+ const page = await this.schedules({ cursor });
913
+ out.push(...page.schedules);
914
+ if (!page.cursor) return out;
915
+ cursor = page.cursor;
916
+ }
917
+ }
918
+ /**
919
+ * Declare a schedule. The cloud owns WHAT should happen; the machine owns WHEN — it fires from
920
+ * its own clock, so a nightly export still runs while your internet is down and only the run's
921
+ * record is late.
922
+ */
923
+ async createSchedule(req) {
924
+ const { schedule } = await this.http.request("POST", `${this.base}/schedules`, {
925
+ body: req,
926
+ retry: false
927
+ });
928
+ return schedule;
929
+ }
930
+ async deleteSchedule(scheduleId) {
931
+ await this.http.request("DELETE", `${this.base}/schedules/${seg(scheduleId)}`, { retry: false });
932
+ }
933
+ // --- inbound data --------------------------------------------------------
934
+ /**
935
+ * Hand a value to whichever job is waiting for it — `job.waitForData(key)` on the other end.
936
+ *
937
+ * THE CASE THIS IS FOR: a script signs into a portal, the portal sends a one-time code to a
938
+ * mailbox or a phone, and whatever receives that message calls this. Everything else the agent
939
+ * does is outbound; this is the one way to tell a run something.
940
+ *
941
+ * ADDRESSED BY KEY, not by run id, because the thing that will deliver the code — an SMS
942
+ * webhook, an inbound-mail parser — was configured months before tonight's run existed. That
943
+ * puts a duty on the key: the value reaches every job executing on the instance, and only one
944
+ * that asks for that key ever sees it, so `otp.dealer-42` is the shape to write when more than
945
+ * one job can be in flight. `script` and `agentId` narrow it further.
946
+ *
947
+ * Throws when nothing is running. The usual failure is a race you cannot see — the code arrived
948
+ * four seconds after the script gave up — and an integration needs to log that rather than read
949
+ * a silent success.
950
+ *
951
+ * `delivered` counts what the MACHINES confirmed. A run in `undetermined` was written to and did
952
+ * not acknowledge, which is not a failure: do not send a replacement value, because the job may
953
+ * already have this one and a second one-time code invalidates the first.
954
+ */
955
+ async send(key, value, opts = {}) {
956
+ return this.http.request("POST", `${this.base}/data/${seg(key)}`, {
957
+ query: { script: opts.script, agent_id: opts.agentId },
958
+ body: value,
959
+ retry: false
960
+ });
961
+ }
962
+ /** The same, to ONE run by id — for when you were given the run id, typically because the
963
+ * script handed out `job.dataUrl(key)` when it triggered whatever produces the value.
964
+ *
965
+ * `delivered: false` with `undetermined: true` is the written-but-unacknowledged case: leave it
966
+ * alone and let the job's own timeout decide. */
967
+ async sendToRun(runId, key, value) {
968
+ return this.http.request("POST", `${this.base}/runs/${seg(runId)}/data/${seg(key)}`, {
969
+ body: value,
970
+ retry: false
971
+ });
972
+ }
973
+ // --- credentials ---------------------------------------------------------
974
+ /** The NAMES of the credentials this fleet's scripts read as `env.NAME`. Values are write-only
975
+ * and never returned — a leaked key can replace one but not harvest it. */
976
+ async env() {
977
+ const { env: env2 } = await this.http.request("GET", `${this.base}/env`);
978
+ return env2;
979
+ }
980
+ /**
981
+ * Replace the credential map. Omitting a name deletes it; `null` for a name KEEPS what is
982
+ * stored, which is the only way to rotate one without re-typing the others you cannot read.
983
+ */
984
+ async setEnv(env2) {
985
+ const res = await this.http.request("PUT", `${this.base}/env`, {
986
+ body: { env: env2 },
987
+ retry: false
988
+ });
989
+ return res.env;
990
+ }
991
+ };
992
+
993
+ // src/blob/client.ts
994
+ var MAX_SINGLE_PUT_BYTES = 5 * 1024 * 1024 * 1024;
995
+ var DEFAULT_CONTENT_TYPE = "application/octet-stream";
996
+ var BlobClient = class {
997
+ instance;
998
+ http;
999
+ base;
1000
+ constructor(http, instance) {
1001
+ this.http = http;
1002
+ this.instance = instance;
1003
+ this.base = `/v1/blob/${seg(instance)}`;
1004
+ }
1005
+ // --- uploading ------------------------------------------------------------
1006
+ /**
1007
+ * Store a file. Returns the finished object.
1008
+ *
1009
+ * Picks the transfer for you: one presigned PUT, or a multipart upload when a `Blob`/`File` is
1010
+ * larger than storage will take in a single request. `content` may be a string, an
1011
+ * `ArrayBuffer`, a typed array, or a `Blob`/`File` — only a `Blob` can be uploaded in parts,
1012
+ * since parts are sliced from it rather than held in memory.
1013
+ *
1014
+ * `contentType` is worth passing: without one an object is stored as
1015
+ * `application/octet-stream`, which a browser downloads rather than renders. A `File` carries
1016
+ * its own.
1017
+ */
1018
+ async put(name, content, opts = {}) {
1019
+ const body = toBody(content);
1020
+ const contentType = opts.contentType ?? blobType(content) ?? DEFAULT_CONTENT_TYPE;
1021
+ if (isBlob(body) && body.size > MAX_SINGLE_PUT_BYTES) {
1022
+ return this.putMultipart(name, body, contentType, opts);
1023
+ }
1024
+ const size = isBlob(body) ? body.size : body.byteLength;
1025
+ const minted = await this.uploadUrl({
1026
+ name,
1027
+ size,
1028
+ content_type: contentType,
1029
+ public: opts.public,
1030
+ meta: opts.meta
1031
+ });
1032
+ await this.http.transfer(minted.upload_url, {
1033
+ method: minted.method,
1034
+ // content-length is set by the runtime from the body. It is signed into the URL, so a
1035
+ // body of a different length is refused by storage rather than stored short.
1036
+ headers: { "content-type": contentType },
1037
+ body,
1038
+ signal: opts.signal
1039
+ });
1040
+ opts.onProgress?.({ uploaded: size, total: size });
1041
+ return this.read(minted.id);
1042
+ }
1043
+ /**
1044
+ * Mint a URL a client PUTs bytes to directly, without handing that client an API key.
1045
+ *
1046
+ * This is how a browser uploads: your backend decides whether this user may, and how big the
1047
+ * file may be, then hands over a URL that can do exactly that one thing for fifteen minutes.
1048
+ * The size is signed in, so it is the real bound on what the holder can make you store.
1049
+ */
1050
+ async uploadUrl(req) {
1051
+ return this.http.request("POST", `${this.base}/uploads`, { body: req, retry: false });
1052
+ }
1053
+ /** Reserve an object and sign the call that opens a multipart upload. Use `put` unless you
1054
+ * are driving the transfer yourself. */
1055
+ async beginMultipart(req) {
1056
+ return this.http.request("POST", `${this.base}/uploads/multipart`, { body: req, retry: false });
1057
+ }
1058
+ /** Sign a window of part URLs, plus the complete and abort URLs. At most 100 parts per call. */
1059
+ async multipartUrls(req) {
1060
+ return this.http.request("POST", `${this.base}/uploads/multipart/urls`, { body: req, retry: false });
1061
+ }
1062
+ // --- reading --------------------------------------------------------------
1063
+ /** An object's metadata plus a short-lived download URL. */
1064
+ async get(id) {
1065
+ return this.http.request("GET", `${this.base}/${seg(id)}`);
1066
+ }
1067
+ /** An object's bytes, fetched from storage rather than through the API. */
1068
+ async bytes(id, opts = {}) {
1069
+ const { download_url } = await this.get(id);
1070
+ const res = await this.http.transfer(download_url, { signal: opts.signal });
1071
+ return new Uint8Array(await res.arrayBuffer());
1072
+ }
1073
+ /**
1074
+ * One page of objects, newest first.
1075
+ *
1076
+ * PAGED, and the cursor matters: a store is small in development and unbounded in a real
1077
+ * account, so a caller that ignores it is looking at part of one.
1078
+ *
1079
+ * Refused for a container job token — a job is told its inputs rather than enumerating the
1080
+ * store it writes to.
1081
+ */
1082
+ async list(query = {}) {
1083
+ return this.http.request("GET", this.base, { query });
1084
+ }
1085
+ /** Every object, walking the pages for you. */
1086
+ async *listAll(query = {}) {
1087
+ let cursor;
1088
+ for (; ; ) {
1089
+ const page = await this.list({ ...query, cursor });
1090
+ for (const b of page.blobs) yield b;
1091
+ if (!page.cursor) return;
1092
+ cursor = page.cursor;
1093
+ }
1094
+ }
1095
+ // --- changing -------------------------------------------------------------
1096
+ /**
1097
+ * Publish or unpublish an object. A public object is served from a stable URL with no
1098
+ * credential at all; unpublishing drops the cached copies too.
1099
+ *
1100
+ * Refused for a container job token: publishing is the one operation whose effect outlives the
1101
+ * credential that made it.
1102
+ */
1103
+ async setPublic(id, isPublic = true) {
1104
+ const { blob } = await this.http.request("POST", `${this.base}/${seg(id)}/public`, {
1105
+ body: { public: isPublic },
1106
+ retry: false
1107
+ });
1108
+ return blob;
1109
+ }
1110
+ /** Delete up to 200 objects. Needs `full`; ids that do not exist are not counted. */
1111
+ async delete(ids) {
1112
+ return this.http.request("POST", `${this.base}/delete`, { body: { ids }, retry: false });
1113
+ }
1114
+ // --- the multipart transfer -----------------------------------------------
1115
+ /**
1116
+ * Cut a large file up, send the parts, and let storage glue them back together — so what the
1117
+ * customer downloads is one ordinary file rather than a split archive they need a tool for.
1118
+ *
1119
+ * Parts go up one at a time: these bytes usually leave an office connection, and a part that
1120
+ * fails is a part re-sent in full. ON ANY FAILURE THE UPLOAD IS ABORTED, because parts of an
1121
+ * upload nobody completed keep billing and no listing shows them.
1122
+ */
1123
+ async putMultipart(name, file, contentType, opts) {
1124
+ const begun = await this.beginMultipart({
1125
+ name,
1126
+ size: file.size,
1127
+ content_type: contentType,
1128
+ public: opts.public,
1129
+ meta: opts.meta
1130
+ });
1131
+ const created = await this.http.transfer(begun.create_url, {
1132
+ method: "POST",
1133
+ headers: { "content-type": contentType },
1134
+ signal: opts.signal
1135
+ });
1136
+ const uploadId = /<UploadId>([^<]+)<\/UploadId>/.exec(await created.text())?.[1];
1137
+ if (!uploadId) throw new AltEngineError({ code: "INTERNAL", message: "storage did not name an upload id", status: 502 });
1138
+ let abortUrl;
1139
+ try {
1140
+ const etags = [];
1141
+ let uploaded = 0;
1142
+ let next = 1;
1143
+ let completeUrl = "";
1144
+ while (next <= begun.parts) {
1145
+ const signed = await this.multipartUrls({ id: begun.id, upload_id: uploadId, from: next, count: begun.parts - next + 1 });
1146
+ abortUrl = signed.abort_url;
1147
+ completeUrl = signed.complete_url;
1148
+ if (!signed.part_urls.length || signed.part_urls[0].part_number !== next) {
1149
+ throw new AltEngineError({
1150
+ code: "INTERNAL",
1151
+ message: `asked for part ${next} and was signed none`,
1152
+ status: 502
1153
+ });
1154
+ }
1155
+ for (const part of signed.part_urls) {
1156
+ if (part.part_number > begun.parts) break;
1157
+ const start = (part.part_number - 1) * begun.part_size;
1158
+ const chunk = file.slice(start, Math.min(start + begun.part_size, file.size));
1159
+ const res = await this.http.transfer(part.url, { method: "PUT", body: chunk, signal: opts.signal });
1160
+ const etag = res.headers.get("etag");
1161
+ if (!etag) {
1162
+ throw new AltEngineError({
1163
+ code: "INTERNAL",
1164
+ message: `storage returned no ETag for part ${part.part_number}; it must be an exposed response header`,
1165
+ status: 502
1166
+ });
1167
+ }
1168
+ etags.push({ part_number: part.part_number, etag });
1169
+ uploaded += chunk.size;
1170
+ opts.onProgress?.({ uploaded, total: file.size });
1171
+ next = part.part_number + 1;
1172
+ }
1173
+ }
1174
+ await this.http.transfer(completeUrl, {
1175
+ method: "POST",
1176
+ headers: { "content-type": "application/xml" },
1177
+ body: completeXml(etags),
1178
+ signal: opts.signal
1179
+ });
1180
+ } catch (err) {
1181
+ const url = abortUrl ?? await this.multipartUrls({ id: begun.id, upload_id: uploadId, from: 1, count: 1 }).then((u) => u.abort_url).catch(() => void 0);
1182
+ if (url) await this.http.transfer(url, { method: "DELETE" }).catch(() => void 0);
1183
+ throw err;
1184
+ }
1185
+ return this.read(begun.id);
1186
+ }
1187
+ /** The finished record. A read, so it needs no grant an upload did not already have —
1188
+ * `write` outranks `read`. */
1189
+ async read(id) {
1190
+ return (await this.get(id)).blob;
1191
+ }
1192
+ };
1193
+ function blobFromJobEnv(opts = {}) {
1194
+ const url = typeof process !== "undefined" ? process.env?.AE_BLOB_URL : void 0;
1195
+ const token = typeof process !== "undefined" ? process.env?.AE_BLOB_TOKEN : void 0;
1196
+ if (!url || !token) {
1197
+ throw new AltEngineError({
1198
+ code: "FAILED_PRECONDITION",
1199
+ message: "AE_BLOB_URL and AE_BLOB_TOKEN are not set \u2014 this is not a container job, or its instance names no blobStore",
1200
+ status: 400
1201
+ });
1202
+ }
1203
+ const m = /^(.*)\/v1\/blob\/([^/]+)\/*$/.exec(url);
1204
+ if (!m) {
1205
+ throw new AltEngineError({ code: "INVALID_ARGUMENT", message: `AE_BLOB_URL is not a blob endpoint: ${url}`, status: 400 });
1206
+ }
1207
+ return new BlobClient(new Http({ ...opts, baseUrl: m[1], apiKey: token }), decodeURIComponent(m[2]));
1208
+ }
1209
+ function completeXml(parts) {
1210
+ const body = [...parts].sort((a, b) => a.part_number - b.part_number).map((p) => `<Part><PartNumber>${p.part_number}</PartNumber><ETag>${p.etag.replace(/[<>&]/g, "")}</ETag></Part>`).join("");
1211
+ return `<CompleteMultipartUpload>${body}</CompleteMultipartUpload>`;
1212
+ }
1213
+ var isBlob = (v) => typeof v === "object" && v !== null && typeof v.size === "number" && typeof v.slice === "function";
1214
+ var blobType = (content) => isBlob(content) && content.type ? content.type : void 0;
1215
+ function toBody(content) {
1216
+ if (typeof content === "string") return new TextEncoder().encode(content);
1217
+ if (isBlob(content)) return content;
1218
+ if (content instanceof ArrayBuffer) return new Uint8Array(content);
1219
+ if (ArrayBuffer.isView(content)) return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
1220
+ throw new AltEngineError({
1221
+ code: "INVALID_ARGUMENT",
1222
+ message: "content must be a string, an ArrayBuffer, a typed array, or a Blob",
1223
+ status: 400
1224
+ });
1225
+ }
1226
+
1227
+ // src/container/client.ts
1228
+ var POLL_START_MS2 = 2e3;
1229
+ var POLL_MAX_MS2 = 15e3;
1230
+ var TERMINAL2 = /* @__PURE__ */ new Set(["done", "failed", "canceled"]);
1231
+ var ContainerClient = class {
1232
+ instance;
1233
+ http;
1234
+ base;
1235
+ constructor(http, instance) {
1236
+ this.http = http;
1237
+ this.instance = instance;
1238
+ this.base = `/v1/container/${seg(instance)}`;
1239
+ }
1240
+ /**
1241
+ * Start a job and return as soon as its machine exists.
1242
+ *
1243
+ * There is nothing to await: a job that runs for twenty minutes has nowhere to send twenty
1244
+ * minutes of output. Poll with `wait`, or have the instance call a function when it ends.
1245
+ */
1246
+ async run(req) {
1247
+ const { job } = await this.http.request("POST", this.base, {
1248
+ body: req,
1249
+ // A retried launch is a SECOND MACHINE, billed for its own runtime.
1250
+ retry: false
1251
+ });
1252
+ return job;
1253
+ }
1254
+ /** One job: status, exit code, how long it ran, what it cost. */
1255
+ async get(jobId) {
1256
+ const { job } = await this.http.request("GET", `${this.base}/${seg(jobId)}`);
1257
+ return job;
1258
+ }
1259
+ /**
1260
+ * One page of jobs, newest first.
1261
+ *
1262
+ * PAGED, and the cursor matters. Note the shape: the response's `cursor` is fed back as
1263
+ * `before` — it is the `started_at` of the last job on the page.
1264
+ */
1265
+ async list(query = {}) {
1266
+ return this.http.request("GET", this.base, { query });
1267
+ }
1268
+ /** Every job matching the query, walking the pages for you. */
1269
+ async *listAll(query = {}) {
1270
+ let before;
1271
+ for (; ; ) {
1272
+ const page = await this.list({ ...query, before });
1273
+ for (const j of page.jobs) yield j;
1274
+ if (page.cursor == null) return;
1275
+ before = page.cursor;
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Stop a running job and destroy its machine now. It is billed for the time it ran.
1280
+ *
1281
+ * `canceled: false` means the job had already finished, which is not a failure.
1282
+ */
1283
+ async cancel(jobId) {
1284
+ return this.http.request("POST", `${this.base}/${seg(jobId)}/cancel`, { retry: false });
1285
+ }
1286
+ /**
1287
+ * What the job printed, oldest first.
1288
+ *
1289
+ * BEST EFFORT: an unavailable log service returns an empty page with a `note` rather than
1290
+ * throwing, and a job's own record — exit code, timing, cost — never depends on it. Logs are
1291
+ * kept for about a week after the machine is destroyed.
1292
+ */
1293
+ async logs(jobId, query = {}) {
1294
+ return this.http.request("GET", `${this.base}/${seg(jobId)}/logs`, { query });
1295
+ }
1296
+ /** What this instance will accept: the sizes, the image allowlist, and the two ceilings. */
1297
+ async sizes() {
1298
+ return this.http.request("GET", `${this.base}/sizes`);
1299
+ }
1300
+ /**
1301
+ * Poll until a job reaches a terminal status.
1302
+ *
1303
+ * `timeoutMs` bounds the WAIT, not the job: giving up here leaves the machine running and
1304
+ * billing. Call `cancel` if that is what you meant. Zero (the default) waits indefinitely.
1305
+ */
1306
+ async wait(jobId, opts = {}) {
1307
+ const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : 0;
1308
+ let delay = POLL_START_MS2;
1309
+ for (; ; ) {
1310
+ const job = await this.get(jobId);
1311
+ opts.onPoll?.(job);
1312
+ if (TERMINAL2.has(job.status)) return job;
1313
+ if (deadline && Date.now() >= deadline) {
1314
+ throw new Error(
1315
+ `job ${jobId} was still ${job.status} after ${opts.timeoutMs}ms \u2014 its machine is still running and still billing; cancel it if that is not what you want`
1316
+ );
1317
+ }
1318
+ let ms = delay;
1319
+ if (deadline) ms = Math.min(ms, Math.max(0, deadline - Date.now()));
1320
+ await sleep2(ms, opts.signal);
1321
+ delay = Math.min(delay * 2, POLL_MAX_MS2);
1322
+ }
1323
+ }
1324
+ /** Start a job and wait for it. Convenience over `run` + `wait`. */
1325
+ async runAndWait(req, opts = {}) {
1326
+ const started = await this.run(req);
1327
+ return this.wait(started.id, opts);
1328
+ }
1329
+ };
1330
+
1331
+ // src/mailbox/client.ts
1332
+ var MAX_WAIT_SECONDS = 60;
1333
+ function bytesToBase64(bytes) {
1334
+ let s = "";
1335
+ for (let i = 0; i < bytes.length; i += 32768) {
1336
+ s += String.fromCharCode(...bytes.subarray(i, i + 32768));
1337
+ }
1338
+ return btoa(s);
1339
+ }
1340
+ async function attachmentBase64(content) {
1341
+ if (typeof content === "string") return content;
1342
+ if (content instanceof Uint8Array) return bytesToBase64(content);
1343
+ if (content instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(content));
1344
+ if (ArrayBuffer.isView(content)) return bytesToBase64(new Uint8Array(content.buffer, content.byteOffset, content.byteLength));
1345
+ if (typeof Blob !== "undefined" && content instanceof Blob) return bytesToBase64(new Uint8Array(await content.arrayBuffer()));
1346
+ throw new TypeError("attachment content must be base64 text, a Uint8Array, an ArrayBuffer or a Blob");
1347
+ }
1348
+ async function encodeAttachments(list) {
1349
+ if (!list) return void 0;
1350
+ return Promise.all(list.map(async (a) => ({ ...a, content: await attachmentBase64(a.content) })));
1351
+ }
1352
+ var MailboxClient = class {
1353
+ instance;
1354
+ http;
1355
+ base;
1356
+ /** Names that carry a setting: registered, labelled or disabled. */
1357
+ addresses;
1358
+ constructor(http, instance) {
1359
+ this.http = http;
1360
+ this.instance = instance;
1361
+ this.base = `/v1/mailbox/${seg(instance)}`;
1362
+ this.addresses = {
1363
+ list: (query = {}) => this.http.request("GET", `${this.base}/addresses`, { query }),
1364
+ create: (req = {}) => this.http.request("POST", `${this.base}/addresses`, { body: req }),
1365
+ disable: (local) => this.http.request("DELETE", `${this.base}/addresses/${seg(local)}`)
1366
+ };
1367
+ }
1368
+ /** The main address, the pattern of every other one, and the settings a caller needs. */
1369
+ async info() {
1370
+ return this.http.request("GET", this.base);
1371
+ }
1372
+ /** One page of messages, newest first, without bodies. */
1373
+ async list(query = {}) {
1374
+ const { unread, ...rest } = query;
1375
+ return this.http.request("GET", `${this.base}/messages`, { query: { ...rest, unread: unread ? "1" : void 0 } });
1376
+ }
1377
+ /**
1378
+ * Wait for the next inbound mail after `after`, holding the request up to `timeoutSeconds`
1379
+ * (at most 60; the server checks every 5 s). Empty on timeout — call again with the returned `cursor` to keep waiting.
1380
+ *
1381
+ * Pass `after: "now"` BEFORE handing an address to whoever will mail it, so older mail is not
1382
+ * mistaken for the new one.
1383
+ */
1384
+ async wait(query) {
1385
+ const secs = Math.min(Math.max(query.timeoutSeconds ?? MAX_WAIT_SECONDS, 0), MAX_WAIT_SECONDS);
1386
+ return this.http.request("GET", `${this.base}/messages`, {
1387
+ query: { after: query.after, to: query.to, limit: query.limit, wait: secs },
1388
+ // The server holds the request; give it that long and some.
1389
+ timeoutMs: secs * 1e3 + 15e3
1390
+ });
1391
+ }
1392
+ /** One message with its bodies and attachment list. */
1393
+ async get(id) {
1394
+ const { message } = await this.http.request("GET", `${this.base}/messages/${seg(id)}`);
1395
+ return message;
1396
+ }
1397
+ /** A short-lived link to the raw .eml. Fails when the mailbox does not keep raw messages. */
1398
+ async raw(id) {
1399
+ const r = await this.http.request("GET", `${this.base}/messages/${seg(id)}`, {
1400
+ query: { raw: "1" }
1401
+ });
1402
+ return { url: r.rawUrl, expiresAt: r.expiresAt };
1403
+ }
1404
+ /** A short-lived download link for one attachment. The URL is the credential: no key needed. */
1405
+ async attachment(id, idx) {
1406
+ return this.http.request("GET", `${this.base}/messages/${seg(id)}/attachments/${seg(idx)}`);
1407
+ }
1408
+ /** Mark a received message read. */
1409
+ async markRead(id) {
1410
+ return this.http.request("POST", `${this.base}/messages/${seg(id)}/read`);
1411
+ }
1412
+ /**
1413
+ * Send a new message from a name on this mailbox. Refused when the send mode is `off`, and in
1414
+ * `reply` mode unless every recipient has written to this mailbox in authenticated mail.
1415
+ * Never retried: a retried send is a second email.
1416
+ */
1417
+ async send(req) {
1418
+ const body = { ...req, attachments: await encodeAttachments(req.attachments) };
1419
+ const { message } = await this.http.request("POST", `${this.base}/send`, {
1420
+ body,
1421
+ retry: false
1422
+ });
1423
+ return message;
1424
+ }
1425
+ /** Reply to a received message, threaded: to its Reply-To (or From), from the name it was
1426
+ * sent to, with `Re: <subject>` — unless you pass those. Same limits as `send`. */
1427
+ async reply(id, req = {}) {
1428
+ const body = { ...req, attachments: await encodeAttachments(req.attachments) };
1429
+ const { message } = await this.http.request("POST", `${this.base}/messages/${seg(id)}/reply`, {
1430
+ body,
1431
+ retry: false
1432
+ });
1433
+ return message;
1434
+ }
1435
+ /**
1436
+ * Keep one message until `days` (1–90) from now, overriding the mailbox's retention for it
1437
+ * alone. Extending needs `write`; an earlier date deletes the message sooner, so that needs
1438
+ * `full`.
1439
+ */
1440
+ async keep(id, days) {
1441
+ const { message } = await this.http.request("POST", `${this.base}/messages/${seg(id)}/keep`, {
1442
+ body: { days }
1443
+ });
1444
+ return message;
1445
+ }
1446
+ /** Delete a message and its attachments now. Needs `full`. */
1447
+ async delete(id) {
1448
+ return this.http.request("DELETE", `${this.base}/messages/${seg(id)}`);
1449
+ }
1450
+ };
1451
+
1452
+ // src/tasks/client.ts
1453
+ var TASK_RETRY_HEADER = "x-task-retry";
1454
+ var TASK_RETRY_AFTER_HEADER = "x-task-retry-after";
1455
+ var TASK_MAX_ATTEMPTS_HEADER = "x-task-max-attempts";
1456
+ function wireTask(t) {
1457
+ const { runAt, ...rest } = t;
1458
+ return runAt instanceof Date ? { ...rest, runAt: runAt.getTime() } : runAt === void 0 ? rest : { ...rest, runAt };
1459
+ }
1460
+ var TasksClient = class {
1461
+ instance;
1462
+ http;
1463
+ base;
1464
+ constructor(http, instance) {
1465
+ this.http = http;
1466
+ this.instance = instance;
1467
+ this.base = `/v1/tasks/${seg(instance)}`;
1468
+ }
1469
+ /** The instance's retention and its queues. */
1470
+ async info() {
1471
+ return this.http.request("GET", this.base);
1472
+ }
1473
+ // --- queues ---------------------------------------------------------------
1474
+ /** Every queue, with its settings and counts by state. */
1475
+ async queues() {
1476
+ const { queues } = await this.http.request("GET", `${this.base}/queues`);
1477
+ return queues;
1478
+ }
1479
+ async queue(name) {
1480
+ const { queue } = await this.http.request("GET", `${this.base}/queues/${seg(name)}`);
1481
+ return queue;
1482
+ }
1483
+ /** Create a queue. Settings left out take their defaults. Needs `full`. */
1484
+ async createQueue(name, settings = {}) {
1485
+ const { queue } = await this.http.request("POST", `${this.base}/queues`, {
1486
+ body: { ...settings, name }
1487
+ });
1488
+ return queue;
1489
+ }
1490
+ /** Change a queue: only the settings given change. Needs `full`. */
1491
+ async updateQueue(name, settings) {
1492
+ const { queue } = await this.http.request("PATCH", `${this.base}/queues/${seg(name)}`, {
1493
+ body: settings
1494
+ });
1495
+ return queue;
1496
+ }
1497
+ /** Stop delivering a queue's tasks; nothing is lost. Needs `full`. */
1498
+ async pauseQueue(name) {
1499
+ const { queue } = await this.http.request("POST", `${this.base}/queues/${seg(name)}/pause`);
1500
+ return queue;
1501
+ }
1502
+ async resumeQueue(name) {
1503
+ const { queue } = await this.http.request("POST", `${this.base}/queues/${seg(name)}/resume`);
1504
+ return queue;
1505
+ }
1506
+ /** Delete every task in a queue, in any state. Needs `full`. */
1507
+ async purgeQueue(name) {
1508
+ return this.http.request("POST", `${this.base}/queues/${seg(name)}/purge`);
1509
+ }
1510
+ /** Delete a queue and every task in it. `default` cannot be deleted. Needs `full`. */
1511
+ async deleteQueue(name) {
1512
+ return this.http.request("DELETE", `${this.base}/queues/${seg(name)}`);
1513
+ }
1514
+ // --- tasks ----------------------------------------------------------------
1515
+ /**
1516
+ * Add one task, or up to 100, to a queue. Each result says whether it was added or its name
1517
+ * was already taken — a name already used is a result, not a throw, so a producer that retries
1518
+ * with the same name is idempotent.
1519
+ *
1520
+ * Retried on a transient failure only when every task is named: an unnamed task sent twice is
1521
+ * two tasks.
1522
+ */
1523
+ async add(queue, tasks) {
1524
+ const list = Array.isArray(tasks) ? tasks : [tasks];
1525
+ const res = await this.http.request("POST", `${this.base}/queues/${seg(queue)}/tasks`, {
1526
+ body: { tasks: list.map(wireTask) },
1527
+ retry: list.every((t) => !!t.name) ? void 0 : false,
1528
+ // Every name already taken is a 409 whose body is still the per-task answer.
1529
+ acceptStatus: [409]
1530
+ });
1531
+ return res.tasks;
1532
+ }
1533
+ /** One page of a queue's tasks, without payloads. */
1534
+ async list(queue, query = {}) {
1535
+ return this.http.request("GET", `${this.base}/queues/${seg(queue)}/tasks`, { query: { ...query } });
1536
+ }
1537
+ /** Every task in a queue (narrowed by `query`), page by page. */
1538
+ async *listAll(queue, query = {}) {
1539
+ let cursor;
1540
+ for (; ; ) {
1541
+ const page = await this.list(queue, { ...query, cursor });
1542
+ for (const t of page.tasks) yield t;
1543
+ if (!page.cursor) return;
1544
+ cursor = page.cursor;
1545
+ }
1546
+ }
1547
+ /** One task, with its payload, every attempt and the target's answer. */
1548
+ async get(id) {
1549
+ const { task } = await this.http.request("GET", `${this.base}/tasks/${seg(id)}`);
1550
+ return task;
1551
+ }
1552
+ /** Cancel scheduled or leased tasks (up to 200). A running task cannot be stopped. */
1553
+ async cancel(ids) {
1554
+ return this.http.request("POST", `${this.base}/tasks/cancel`, { body: { ids: Array.isArray(ids) ? ids : [ids] } });
1555
+ }
1556
+ /**
1557
+ * Run a task now: a scheduled one is moved up, a failed or cancelled one is retried with its
1558
+ * attempts reset, and a finished one is run again as a NEW task with the same payload.
1559
+ */
1560
+ async run(id) {
1561
+ const { task } = await this.http.request("POST", `${this.base}/tasks/${seg(id)}/run`, { retry: false });
1562
+ return task;
1563
+ }
1564
+ // --- pull queues ----------------------------------------------------------
1565
+ /**
1566
+ * Lease up to `count` due tasks from a pull queue. Finish each with `ack`, or give it back with
1567
+ * `release`; a lease that runs out puts the task back with its attempt counted as failed.
1568
+ * Never retried: a retried lease would hold tasks nobody is working on.
1569
+ */
1570
+ async lease(queue, opts = {}) {
1571
+ const { tasks } = await this.http.request("POST", `${this.base}/queues/${seg(queue)}/lease`, {
1572
+ body: opts,
1573
+ retry: false
1574
+ });
1575
+ return tasks;
1576
+ }
1577
+ /** Finish a leased task, with an optional result (a string, or JSON) kept up to 16 KB. */
1578
+ async ack(id, leaseId, result) {
1579
+ const { task } = await this.http.request("POST", `${this.base}/tasks/${seg(id)}/ack`, {
1580
+ body: { leaseId, result: result ?? null }
1581
+ });
1582
+ return task;
1583
+ }
1584
+ /** Hold a lease longer: `leaseSeconds` (1–3600, default 300) from now. */
1585
+ async extend(id, leaseId, leaseSeconds) {
1586
+ const { task } = await this.http.request("POST", `${this.base}/tasks/${seg(id)}/extend`, {
1587
+ body: { leaseId, leaseSeconds }
1588
+ });
1589
+ return task;
1590
+ }
1591
+ /** Give a leased task back, to be leased again after `delaySeconds`. The attempt counts as
1592
+ * failed; on the last attempt the task fails instead. */
1593
+ async release(id, leaseId, opts = {}) {
1594
+ const { task } = await this.http.request("POST", `${this.base}/tasks/${seg(id)}/release`, {
1595
+ body: { leaseId, ...opts }
1596
+ });
1597
+ return task;
1598
+ }
1599
+ };
1600
+
1601
+ // src/search/fields.ts
1602
+ var f = {
1603
+ text: (name, value, language) => mk(name, "text", value, language),
1604
+ html: (name, value, language) => mk(name, "html", value, language),
1605
+ atom: (name, value) => mk(name, "atom", value),
1606
+ number: (name, value) => mk(name, "number", value),
1607
+ /** Accepts a Date, ISO string, or epoch milliseconds. */
1608
+ date: (name, value) => mk(name, "date", value instanceof Date ? value.toISOString() : value),
1609
+ geo: (name, value) => mk(name, "geo", value),
1610
+ tokenprefix: (name, value) => mk(name, "tokenprefix", value),
1611
+ untokenprefix: (name, value) => mk(name, "untokenprefix", value)
1612
+ };
1613
+ var facet = {
1614
+ atom: (name, value) => ({ name, type: "atom", value }),
1615
+ number: (name, value) => ({ name, type: "number", value })
1616
+ };
1617
+ function mk(name, type, value, language) {
1618
+ const field = { name, type, value };
1619
+ if (language !== void 0) field.language = language;
1620
+ return field;
1621
+ }
1622
+
1623
+ // src/automation/webhook.ts
1624
+ var WEBHOOK_SIGNATURE_HEADER = "x-altengine-signature";
1625
+ var WEBHOOK_TIMESTAMP_HEADER = "x-altengine-timestamp";
1626
+ var DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1e3;
1627
+ var enc = new TextEncoder();
1628
+ function bytesOf(body) {
1629
+ if (typeof body === "string") return enc.encode(body);
1630
+ return body instanceof Uint8Array ? body : new Uint8Array(body);
1631
+ }
1632
+ function hex(buf) {
1633
+ let s = "";
1634
+ for (const b of new Uint8Array(buf)) s += b.toString(16).padStart(2, "0");
1635
+ return s;
1636
+ }
1637
+ function constantTimeEqual(a, b) {
1638
+ const x = enc.encode(a);
1639
+ const y = enc.encode(b);
1640
+ if (x.length !== y.length) return false;
1641
+ let diff = 0;
1642
+ for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
1643
+ return diff === 0;
1644
+ }
1645
+ async function verifyWebhook(opts) {
1646
+ const { secret, signature } = opts;
1647
+ if (!secret || !signature) return false;
1648
+ const ts = opts.timestamp == null ? "" : String(opts.timestamp).trim();
1649
+ if (!/^\d+$/.test(ts)) return false;
1650
+ const tolerance = opts.toleranceMs ?? DEFAULT_WEBHOOK_TOLERANCE_MS;
1651
+ const now = opts.now ?? Date.now();
1652
+ if (!(Math.abs(now - Number(ts)) <= tolerance)) return false;
1653
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
1654
+ "sign"
1655
+ ]);
1656
+ const prefix = enc.encode(`${ts}.`);
1657
+ const body = bytesOf(opts.body);
1658
+ const signed = new Uint8Array(prefix.length + body.length);
1659
+ signed.set(prefix, 0);
1660
+ signed.set(body, prefix.length);
1661
+ const expected = `v1=${hex(await crypto.subtle.sign("HMAC", key, signed))}`;
1662
+ return constantTimeEqual(signature.trim(), expected);
1663
+ }
1664
+
1665
+ // src/channel/socket.ts
1666
+ var WS_PROTOCOL = "altengine.v1";
1667
+ var WS_TOKEN_PROTOCOL_PREFIX = "altengine.token.";
1668
+ var CONNECTING = 0;
1669
+ var OPEN = 1;
1670
+ var ChannelSocket = class {
1671
+ opts;
1672
+ listeners = {
1673
+ message: /* @__PURE__ */ new Set(),
1674
+ state: /* @__PURE__ */ new Set(),
1675
+ error: /* @__PURE__ */ new Set(),
1676
+ refused: /* @__PURE__ */ new Set()
1677
+ };
1678
+ ws;
1679
+ stateValue = "idle";
1680
+ desired = /* @__PURE__ */ new Set();
1681
+ explicitChannels;
1682
+ closedByUser = false;
1683
+ attempts = 0;
1684
+ pingTimer;
1685
+ lastActivity = 0;
1686
+ reconnectTimer;
1687
+ pendingSubscribes = [];
1688
+ pendingPublishes = [];
1689
+ constructor(opts) {
1690
+ this.opts = opts;
1691
+ this.explicitChannels = opts.channels !== void 0;
1692
+ for (const c of opts.channels ?? []) this.desired.add(c);
1693
+ }
1694
+ get state() {
1695
+ return this.stateValue;
1696
+ }
1697
+ on(event, fn) {
1698
+ this.listeners[event].add(fn);
1699
+ return () => this.listeners[event].delete(fn);
1700
+ }
1701
+ emit(event, payload) {
1702
+ for (const fn of this.listeners[event]) fn(payload);
1703
+ }
1704
+ setState(s) {
1705
+ if (this.stateValue === s) return;
1706
+ this.stateValue = s;
1707
+ this.emit("state", s);
1708
+ }
1709
+ /** Connect (resolves once the socket is open). Reconnects automatically until
1710
+ * `close()` is called. */
1711
+ async connect() {
1712
+ this.closedByUser = false;
1713
+ if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;
1714
+ await this.dial();
1715
+ }
1716
+ /** Stop reconnecting and close the connection. */
1717
+ close() {
1718
+ this.closedByUser = true;
1719
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
1720
+ this.stopPing();
1721
+ this.failPending(new Error("socket closed"));
1722
+ this.ws?.close(1e3, "client close");
1723
+ this.ws = void 0;
1724
+ this.setState("closed");
1725
+ }
1726
+ /** Subscribe to more channels (tracked and re-applied after reconnects).
1727
+ * Resolves with the server's ack. */
1728
+ async subscribe(channels) {
1729
+ for (const c of channels) this.desired.add(c);
1730
+ this.explicitChannels = true;
1731
+ if (!this.isOpen()) return [...this.desired];
1732
+ return new Promise((resolve, reject) => {
1733
+ this.pendingSubscribes.push({ channels, resolve, reject });
1734
+ this.send({ type: "subscribe", channels });
1735
+ });
1736
+ }
1737
+ /** Unsubscribe from channels. */
1738
+ unsubscribe(channels) {
1739
+ for (const c of channels) this.desired.delete(c);
1740
+ this.explicitChannels = true;
1741
+ if (this.isOpen()) this.send({ type: "unsubscribe", channels });
1742
+ }
1743
+ /** Publish over the socket (requires a ws-capable `publish` token). Resolves
1744
+ * with the delivered count from the server's ack. */
1745
+ async publish(channel, data) {
1746
+ if (!this.isOpen()) throw new Error("socket is not open");
1747
+ return new Promise((resolve, reject) => {
1748
+ this.pendingPublishes.push({ resolve, reject });
1749
+ this.send({ type: "publish", channel, data });
1750
+ });
1751
+ }
1752
+ // --- internals ---
1753
+ isOpen() {
1754
+ return !!this.ws && this.ws.readyState === OPEN;
1755
+ }
1756
+ send(frame) {
1757
+ this.ws?.send(typeof frame === "string" ? frame : JSON.stringify(frame));
1758
+ }
1759
+ /** Where to dial, and with which subprotocols. The token travels as a subprotocol
1760
+ * (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an
1761
+ * older server whose response has only `ws_url`, which is opened as it is. */
1762
+ target(tok) {
1763
+ const endpoint = tok.ws_endpoint ?? (tok.ws_url ? void 0 : this.opts.url);
1764
+ let url;
1765
+ let protocols;
1766
+ if (endpoint) {
1767
+ url = new URL(endpoint);
1768
+ protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];
1769
+ } else if (tok.ws_url) {
1770
+ url = new URL(tok.ws_url);
1771
+ if (!url.searchParams.has("token")) url.searchParams.set("token", tok.token);
1772
+ } else {
1773
+ throw new Error("no WebSocket URL: token response had no ws_endpoint and no url option was set");
1774
+ }
1775
+ if (this.explicitChannels && this.desired.size) {
1776
+ url.searchParams.set("channels", [...this.desired].join(","));
1777
+ }
1778
+ return { url: url.toString(), protocols };
1779
+ }
1780
+ async dial() {
1781
+ this.setState(this.attempts === 0 ? "connecting" : "reconnecting");
1782
+ let tok;
1783
+ try {
1784
+ tok = await this.opts.getToken();
1785
+ } catch (err) {
1786
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
1787
+ this.scheduleReconnect();
1788
+ return;
1789
+ }
1790
+ const WS = this.opts.webSocket ?? globalThis.WebSocket;
1791
+ if (!WS) throw new Error("no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)");
1792
+ await new Promise((resolve) => {
1793
+ let settled = false;
1794
+ const { url, protocols } = this.target(tok);
1795
+ const ws = protocols ? new WS(url, protocols) : new WS(url);
1796
+ this.ws = ws;
1797
+ ws.onopen = () => {
1798
+ settled = true;
1799
+ this.attempts = 0;
1800
+ this.lastActivity = Date.now();
1801
+ this.setState("open");
1802
+ this.startPing();
1803
+ resolve();
1804
+ };
1805
+ ws.onmessage = (ev) => this.handleMessage(ev);
1806
+ ws.onerror = () => {
1807
+ };
1808
+ ws.onclose = (ev) => {
1809
+ this.stopPing();
1810
+ this.failPending(new Error(`socket closed (${ev.code})`));
1811
+ if (!settled) {
1812
+ settled = true;
1813
+ resolve();
1814
+ }
1815
+ if (!this.closedByUser) this.scheduleReconnect();
1816
+ };
1817
+ });
1818
+ }
1819
+ handleMessage(ev) {
1820
+ this.lastActivity = Date.now();
1821
+ const raw = typeof ev.data === "string" ? ev.data : "";
1822
+ if (raw === "pong" || raw === "ping") return;
1823
+ let frame;
1824
+ try {
1825
+ frame = JSON.parse(raw);
1826
+ } catch {
1827
+ return;
1828
+ }
1829
+ switch (frame?.type) {
1830
+ case "subscribed": {
1831
+ const refused = Array.isArray(frame.refused) ? frame.refused : [];
1832
+ const head = this.pendingSubscribes[0];
1833
+ const acked = /* @__PURE__ */ new Set([...frame.channels ?? [], ...refused]);
1834
+ if (head && head.channels.every((c) => acked.has(c))) {
1835
+ this.pendingSubscribes.shift().resolve(frame.channels ?? []);
1836
+ }
1837
+ if (refused.length) this.emit("refused", refused);
1838
+ return;
1839
+ }
1840
+ case "published":
1841
+ this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);
1842
+ return;
1843
+ case "error": {
1844
+ const err = new Error(typeof frame.error === "string" ? frame.error : JSON.stringify(frame.error));
1845
+ (this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);
1846
+ this.emit("error", err);
1847
+ return;
1848
+ }
1849
+ default:
1850
+ if (frame && typeof frame.channel === "string" && frame.type === void 0) {
1851
+ this.emit("message", frame);
1852
+ }
1853
+ }
1854
+ }
1855
+ startPing() {
1856
+ const interval = Math.min(this.opts.pingIntervalMs ?? 3e4, 6e4);
1857
+ this.stopPing();
1858
+ this.pingTimer = setInterval(() => {
1859
+ if (!this.isOpen()) return;
1860
+ if (Date.now() - this.lastActivity > interval * 1.5) {
1861
+ this.ws?.close(4e3, "keepalive timeout");
1862
+ return;
1863
+ }
1864
+ this.send("ping");
1865
+ }, interval);
1866
+ }
1867
+ stopPing() {
1868
+ if (this.pingTimer) clearInterval(this.pingTimer);
1869
+ this.pingTimer = void 0;
1870
+ }
1871
+ scheduleReconnect() {
1872
+ if (this.closedByUser) return;
1873
+ const base = this.opts.backoffBaseMs ?? 250;
1874
+ const cap = this.opts.backoffMaxMs ?? 3e4;
1875
+ const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);
1876
+ this.attempts++;
1877
+ this.setState("reconnecting");
1878
+ this.reconnectTimer = setTimeout(() => void this.dial(), delay);
1879
+ }
1880
+ failPending(err) {
1881
+ for (const p of this.pendingSubscribes.splice(0)) p.reject(err);
1882
+ for (const p of this.pendingPublishes.splice(0)) p.reject(err);
1883
+ }
1884
+ };
1885
+
1886
+ // src/index.ts
1887
+ var AltEngine = class {
1888
+ http;
1889
+ constructor(opts = {}) {
1890
+ this.http = new Http(opts);
1891
+ }
1892
+ /** Client for a datastore instance (namespace-bound; default `""`). */
1893
+ datastore(instance, opts) {
1894
+ return new DatastoreClient(this.http, instance, opts);
1895
+ }
1896
+ /** Client for a search instance (namespace-bound; default `""`). */
1897
+ search(instance, opts) {
1898
+ return new SearchClient(this.http, instance, opts);
1899
+ }
1900
+ /** Server-side client for a channel instance (tokens, publish, presence). */
1901
+ channel(instance) {
1902
+ return new ChannelClient(this.http, instance);
1903
+ }
1904
+ /** Server-side client for an automation instance — start runs on your own machines, read
1905
+ * what they produced, and declare schedules. Organization API key only: a run spends time on
1906
+ * hardware you own, so end-user identity tokens are refused as they are for containers. */
1907
+ automation(instance) {
1908
+ return new AutomationClient(this.http, instance);
1909
+ }
1910
+ /** Client for a blob instance — files, stored and served. Upload bytes go straight to
1911
+ * storage on a presigned URL and never travel through the API. */
1912
+ blob(instance) {
1913
+ return new BlobClient(this.http, instance);
1914
+ }
1915
+ /** Server-side client for a container instance — a Docker image run as a background job.
1916
+ * Organization API key only: end-user identity tokens are refused, as they are for
1917
+ * automation, because access rules bound what a user may read, not what they may spend. */
1918
+ container(instance) {
1919
+ return new ContainerClient(this.http, instance);
1920
+ }
1921
+ /** Server-side client for a mailbox instance — email addresses an app or agent owns: read
1922
+ * what arrives, wait for the next message, send and reply. Organization API key only. */
1923
+ mailbox(instance) {
1924
+ return new MailboxClient(this.http, instance);
1925
+ }
1926
+ /** Server-side client for a tasks instance — queues of work delivered to a function, a channel
1927
+ * or a signed webhook with retries, or leased by workers. Organization API key only. */
1928
+ tasks(instance) {
1929
+ return new TasksClient(this.http, instance);
1930
+ }
1931
+ /** Client for an auth instance — end-user sign-up/sign-in and identity tokens.
1932
+ * Shares this client's API origin but never its API key (auth endpoints are
1933
+ * public; the end user's own credentials are the trust boundary). For browser
1934
+ * apps, import `AuthClient` from `@altenginenet/sdk/auth` directly instead. */
1935
+ auth(instance) {
1936
+ return new AuthClient({ instance, baseUrl: this.http.baseUrl });
1937
+ }
1938
+ };
1939
+ // Annotate the CommonJS export names for ESM import in node:
1940
+ 0 && (module.exports = {
1941
+ AltEngine,
1942
+ AltEngineError,
1943
+ AltEngineNetworkError,
1944
+ AuthClient,
1945
+ AutomationClient,
1946
+ BlobClient,
1947
+ ChannelClient,
1948
+ ChannelSocket,
1949
+ ContainerClient,
1950
+ DEFAULT_BASE_URL,
1951
+ DEFAULT_WEBHOOK_TOLERANCE_MS,
1952
+ DEV_BASE_URL,
1953
+ DatastoreClient,
1954
+ MAX_SINGLE_PUT_BYTES,
1955
+ MAX_WAIT_SECONDS,
1956
+ MailboxClient,
1957
+ NamespaceAdmin,
1958
+ SearchClient,
1959
+ SearchIndex,
1960
+ TASK_MAX_ATTEMPTS_HEADER,
1961
+ TASK_RETRY_AFTER_HEADER,
1962
+ TASK_RETRY_HEADER,
1963
+ TasksClient,
1964
+ WEBHOOK_SIGNATURE_HEADER,
1965
+ WEBHOOK_TIMESTAMP_HEADER,
1966
+ attachmentBase64,
1967
+ blobFromJobEnv,
1968
+ defaultStorage,
1969
+ f,
1970
+ facet,
1971
+ memoryStorage,
1972
+ verifyWebhook
1973
+ });
1974
+ //# sourceMappingURL=index.cjs.map