@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/constants.ts","../src/http.ts","../src/datastore/client.ts","../src/search/client.ts","../src/channel/client.ts","../src/auth/storage.ts","../src/auth/client.ts","../src/poll.ts","../src/automation/client.ts","../src/blob/client.ts","../src/container/client.ts","../src/mailbox/client.ts","../src/tasks/client.ts","../src/search/fields.ts","../src/automation/webhook.ts","../src/channel/socket.ts"],"sourcesContent":["/** @altenginenet/sdk — official JavaScript/TypeScript SDK for altengine\n * (https://www.altengine.net).\n *\n * ```ts\n * import { AltEngine, f } from \"@altenginenet/sdk\";\n *\n * const ae = new AltEngine({ apiKey: \"ae_...\" }); // production api.altengine.net\n * // const ae = new AltEngine({ dev: true, apiKey: \"dev\" }); // local `altengine dev`\n *\n * const db = ae.datastore(\"myapp\");\n * const { keys } = await db.put(\"todos\", [{ data: { title: \"ship SDK\" } }]);\n *\n * const idx = ae.search(\"myapp\").index(\"products\");\n * await idx.put([{ fields: [f.text(\"title\", \"Blue Shoes\"), f.number(\"price\", 59)] }]);\n *\n * const ch = ae.channel(\"myapp\");\n * const { token, ws_endpoint, protocols } = await ch.createToken({ channels: [\"room:1\"] });\n * ```\n *\n * For the browser WebSocket subscriber, import from `@altenginenet/sdk/channel`.\n * For client-side sign-in with no backend of your own, see `@altenginenet/sdk/auth`:\n *\n * ```ts\n * import { AuthClient } from \"@altenginenet/sdk/auth\";\n *\n * const auth = new AuthClient({ instance: \"myapp-auth\" });\n * await auth.signIn(\"alice@example.com\", \"hunter2\");\n * const ae = new AltEngine({ auth }); // requests now carry the user's token\n * ```\n */\n\nimport { Http, type ClientOptions } from \"./http.js\";\nimport { DatastoreClient, type DatastoreOptions } from \"./datastore/client.js\";\nimport { SearchClient, type SearchOptions } from \"./search/client.js\";\nimport { ChannelClient } from \"./channel/client.js\";\nimport { AuthClient } from \"./auth/client.js\";\nimport { AutomationClient } from \"./automation/client.js\";\nimport { BlobClient } from \"./blob/client.js\";\nimport { ContainerClient } from \"./container/client.js\";\nimport { MailboxClient } from \"./mailbox/client.js\";\nimport { TasksClient } from \"./tasks/client.js\";\n\nexport class AltEngine {\n private readonly http: Http;\n\n constructor(opts: ClientOptions = {}) {\n this.http = new Http(opts);\n }\n\n /** Client for a datastore instance (namespace-bound; default `\"\"`). */\n datastore(instance: string, opts?: DatastoreOptions): DatastoreClient {\n return new DatastoreClient(this.http, instance, opts);\n }\n\n /** Client for a search instance (namespace-bound; default `\"\"`). */\n search(instance: string, opts?: SearchOptions): SearchClient {\n return new SearchClient(this.http, instance, opts);\n }\n\n /** Server-side client for a channel instance (tokens, publish, presence). */\n channel(instance: string): ChannelClient {\n return new ChannelClient(this.http, instance);\n }\n\n /** Server-side client for an automation instance — start runs on your own machines, read\n * what they produced, and declare schedules. Organization API key only: a run spends time on\n * hardware you own, so end-user identity tokens are refused as they are for containers. */\n automation(instance: string): AutomationClient {\n return new AutomationClient(this.http, instance);\n }\n\n /** Client for a blob instance — files, stored and served. Upload bytes go straight to\n * storage on a presigned URL and never travel through the API. */\n blob(instance: string): BlobClient {\n return new BlobClient(this.http, instance);\n }\n\n /** Server-side client for a container instance — a Docker image run as a background job.\n * Organization API key only: end-user identity tokens are refused, as they are for\n * automation, because access rules bound what a user may read, not what they may spend. */\n container(instance: string): ContainerClient {\n return new ContainerClient(this.http, instance);\n }\n\n /** Server-side client for a mailbox instance — email addresses an app or agent owns: read\n * what arrives, wait for the next message, send and reply. Organization API key only. */\n mailbox(instance: string): MailboxClient {\n return new MailboxClient(this.http, instance);\n }\n\n /** Server-side client for a tasks instance — queues of work delivered to a function, a channel\n * or a signed webhook with retries, or leased by workers. Organization API key only. */\n tasks(instance: string): TasksClient {\n return new TasksClient(this.http, instance);\n }\n\n /** Client for an auth instance — end-user sign-up/sign-in and identity tokens.\n * Shares this client's API origin but never its API key (auth endpoints are\n * public; the end user's own credentials are the trust boundary). For browser\n * apps, import `AuthClient` from `@altenginenet/sdk/auth` directly instead. */\n auth(instance: string): AuthClient {\n return new AuthClient({ instance, baseUrl: this.http.baseUrl });\n }\n}\n\nexport { AltEngineError, AltEngineNetworkError, type ErrorCode } from \"./errors.js\";\nexport {\n DEFAULT_BASE_URL,\n DEV_BASE_URL,\n type ClientOptions,\n type RetryOptions,\n type RequestOptions,\n type TokenProvider,\n} from \"./http.js\";\n\nexport { AuthClient, type AuthClientOptions } from \"./auth/client.js\";\nexport { memoryStorage, defaultStorage, type TokenStorage } from \"./auth/storage.js\";\nexport * from \"./auth/types.js\";\n\nexport { DatastoreClient, NamespaceAdmin, type DatastoreOptions } from \"./datastore/client.js\";\nexport * from \"./datastore/types.js\";\n\nexport { SearchClient, SearchIndex, type SearchOptions } from \"./search/client.js\";\nexport * from \"./search/types.js\";\nexport { f, facet } from \"./search/fields.js\";\n\nexport { AutomationClient } from \"./automation/client.js\";\nexport * from \"./automation/types.js\";\nexport {\n verifyWebhook,\n WEBHOOK_SIGNATURE_HEADER,\n WEBHOOK_TIMESTAMP_HEADER,\n DEFAULT_WEBHOOK_TOLERANCE_MS,\n type VerifyWebhookOptions,\n} from \"./automation/webhook.js\";\n\nexport { BlobClient, blobFromJobEnv, MAX_SINGLE_PUT_BYTES } from \"./blob/client.js\";\nexport * from \"./blob/types.js\";\n\nexport { ContainerClient } from \"./container/client.js\";\nexport * from \"./container/types.js\";\n\nexport { MailboxClient, attachmentBase64, MAX_WAIT_SECONDS } from \"./mailbox/client.js\";\nexport * from \"./mailbox/types.js\";\n\nexport { TasksClient, TASK_RETRY_HEADER, TASK_RETRY_AFTER_HEADER, TASK_MAX_ATTEMPTS_HEADER } from \"./tasks/client.js\";\nexport * from \"./tasks/types.js\";\n\nexport { ChannelClient } from \"./channel/client.js\";\nexport * from \"./channel/types.js\";\n\n// Also exported from the browser-safe `@altenginenet/sdk/channel` subpath.\nexport { ChannelSocket, type ChannelSocketOptions, type SocketState, type SocketToken } from \"./channel/socket.js\";\n","/** Error codes emitted by the altengine API. The union is open (`string`) so new\n * server codes never break compilation. */\nexport type ErrorCode =\n | \"NOT_FOUND\"\n | \"INVALID_ARGUMENT\"\n | \"UNAUTHENTICATED\"\n | \"PERMISSION_DENIED\"\n | \"RATE_LIMITED\"\n | \"QUERY_TOO_COMPLEX\"\n | \"INDEX_REQUIRED\"\n | \"DOCUMENT_TOO_LARGE\"\n | \"INDEX_FULL\"\n | \"ALREADY_EXISTS\"\n | \"PRECONDITION_FAILED\"\n | \"INTERNAL\"\n | (string & {});\n\n/** A structured altengine API error: the `{error:{code,message,details?}}` envelope\n * plus transport context (HTTP status, Retry-After). */\nexport class AltEngineError extends Error {\n readonly code: ErrorCode;\n readonly status: number;\n readonly details?: unknown;\n /** Seconds to wait before retrying, from the `Retry-After` header (429s). */\n readonly retryAfter?: number;\n\n constructor(opts: { code: ErrorCode; message: string; status: number; details?: unknown; retryAfter?: number }) {\n super(opts.message);\n this.name = \"AltEngineError\";\n this.code = opts.code;\n this.status = opts.status;\n this.details = opts.details;\n this.retryAfter = opts.retryAfter;\n }\n\n /** Whether the request can be safely retried after a backoff. 429 always carries\n * Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */\n get retryable(): boolean {\n if (this.status === 429) return true;\n return this.status === 502 || this.status === 503 || this.status === 504;\n }\n}\n\n/** Thrown when the network/fetch layer fails before an HTTP response exists. */\nexport class AltEngineNetworkError extends Error {\n readonly cause?: unknown;\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"AltEngineNetworkError\";\n this.cause = cause;\n }\n}\n","/** Side-effect-free constants and path helpers shared by every client.\n *\n * These live apart from `http.ts` on purpose: the browser-safe entry points\n * (`@altenginenet/sdk/auth`, `@altenginenet/sdk/channel`) need the base URLs and path\n * encoders but must NOT pull in the API-key transport, which is a backend\n * credential path that has no business in a browser bundle. */\n\n/** Production API origin used when no override is given. */\nexport const DEFAULT_BASE_URL = \"https://api.altengine.net\";\n/** Where `altengine dev` (the local emulator) listens by default. */\nexport const DEV_BASE_URL = \"http://127.0.0.1:9191\";\n\n/** Encode one path segment (instance/index/collection/key names). */\nexport const seg = (s: string | number): string => encodeURIComponent(String(s));\n\n/** Encode a namespace path segment. The empty (default) namespace can't ride a\n * URL path — routers collapse the resulting \"//\", so it travels as the reserved\n * sentinel `_default` (the server maps it back to \"\"). */\nexport const nsSeg = (namespace: string): string => seg(namespace === \"\" ? \"_default\" : namespace);\n","import { AltEngineError, AltEngineNetworkError } from \"./errors.js\";\n\nexport interface RetryOptions {\n /** Total attempts including the first (default 3). Set 1 to disable retries. */\n maxAttempts?: number;\n /** Base backoff delay in ms (default 250); doubles per attempt with jitter. */\n baseDelayMs?: number;\n /** Backoff ceiling in ms (default 4000). */\n maxDelayMs?: number;\n}\n\n// Re-exported so `from \"./http.js\"` keeps working for every existing importer;\n// they live in constants.ts so browser-safe entries can use them without\n// dragging the API-key transport into the bundle.\nexport { DEFAULT_BASE_URL, DEV_BASE_URL, seg, nsSeg } from \"./constants.js\";\nimport { DEFAULT_BASE_URL, DEV_BASE_URL } from \"./constants.js\";\n\n/** Supplies a per-request end-user bearer token. `AuthClient` implements this, so\n * `new AltEngine({ auth })` sends the signed-in user's `id_token` (kept fresh)\n * rather than an org API key. */\nexport interface TokenProvider {\n getToken(): Promise<string | undefined> | string | undefined;\n}\n\nexport interface ClientOptions {\n /** API origin override. Resolution order: this option → `dev: true` →\n * `ALTENGINE_URL` env var → `https://api.altengine.net` (production). */\n baseUrl?: string;\n /** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */\n dev?: boolean;\n /** Org API key (`Authorization: Bearer`). Falls back to the `ALTENGINE_API_KEY`\n * env var; omit only for token-based flows. */\n apiKey?: string;\n /** End-user identity source (an `AuthClient`). When it yields a token, it takes\n * precedence over `apiKey` — an org key is a backend credential and must not be\n * shipped to a browser; the signed-in user's `id_token` is what a client-side\n * app sends, and access rules scope it to that user's own rows. */\n auth?: TokenProvider;\n /** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Per-request timeout in ms (default 30000). */\n timeoutMs?: number;\n /** Default retry policy for retryable failures (429/502/503/504/network). */\n retry?: RetryOptions;\n}\n\n/** Browser-safe env lookup (process is Node/edge-only). */\nconst env = (name: string): string | undefined =>\n typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n\nexport function resolveBaseUrl(opts: ClientOptions): string {\n if (opts.baseUrl) return opts.baseUrl;\n if (opts.dev) return DEV_BASE_URL;\n return env(\"ALTENGINE_URL\") ?? DEFAULT_BASE_URL;\n}\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n headers?: Record<string, string>;\n /** Override the client retry policy; `false` disables retries for this call\n * (used for non-idempotent endpoints: transaction, publish). */\n retry?: RetryOptions | false;\n /** Override the client's request timeout for this call (a long-poll holds the request open\n * for longer than an ordinary call takes). */\n timeoutMs?: number;\n /** Error statuses whose JSON body is still the answer — a task add where every name was\n * already taken is a 409 carrying the per-task results. */\n acceptStatus?: number[];\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Minimal JSON-over-fetch transport shared by all service clients. */\nexport class Http {\n readonly baseUrl: string;\n private readonly apiKey?: string;\n private readonly auth?: TokenProvider;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly timeoutMs: number;\n private readonly retry: Required<RetryOptions>;\n\n constructor(opts: ClientOptions = {}) {\n this.baseUrl = resolveBaseUrl(opts).replace(/\\/+$/, \"\");\n // ALTENGINE_KEY is what older CLI releases read; accepted so one shell setup serves both.\n this.apiKey = opts.apiKey ?? env(\"ALTENGINE_API_KEY\") ?? env(\"ALTENGINE_KEY\");\n this.auth = opts.auth;\n this.fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!this.fetchImpl) throw new Error(\"no fetch implementation available; pass { fetch }\");\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n this.retry = {\n maxAttempts: opts.retry?.maxAttempts ?? 3,\n baseDelayMs: opts.retry?.baseDelayMs ?? 250,\n maxDelayMs: opts.retry?.maxDelayMs ?? 4_000,\n };\n }\n\n url(path: string, query?: RequestOptions[\"query\"]): string {\n let url = this.baseUrl + path;\n if (query) {\n const qs = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) qs.set(k, String(v));\n }\n const s = qs.toString();\n if (s) url += \"?\" + s;\n }\n return url;\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const retry = opts.retry === false\n ? { maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0 }\n : { ...this.retry, ...(opts.retry ?? {}) };\n\n let lastErr: unknown;\n for (let attempt = 1; ; attempt++) {\n try {\n return await this.once<T>(method, path, opts);\n } catch (err) {\n lastErr = err;\n const retryable =\n err instanceof AltEngineNetworkError ||\n (err instanceof AltEngineError && err.retryable);\n if (!retryable || attempt >= retry.maxAttempts) throw err;\n let delay = Math.min(retry.baseDelayMs * 2 ** (attempt - 1), retry.maxDelayMs);\n if (err instanceof AltEngineError && err.retryAfter !== undefined) {\n delay = Math.max(delay, err.retryAfter * 1000);\n }\n // Full jitter keeps concurrent retries from stampeding in unison.\n await sleep(delay * (0.5 + Math.random() * 0.5));\n }\n }\n // Unreachable, but satisfies control-flow analysis.\n throw lastErr;\n }\n\n /**\n * Fetch a URL that is NOT the altengine API — a presigned upload or download link.\n *\n * CARRIES NO CREDENTIAL OF OURS. A presigned URL's signature is the whole credential, and an\n * org API key sent to object storage is an org API key handed to a third party. The bytes go\n * straight between the caller and storage; nothing is proxied through the API.\n *\n * The client's request timeout does not apply either — a 20 GB upload is not a control-plane\n * call. Bound it with `init.signal`.\n */\n async transfer(url: string, init: RequestInit = {}): Promise<Response> {\n const method = init.method ?? \"GET\";\n let res: Response;\n try {\n res = await this.fetchImpl(url, init);\n } catch (err) {\n throw new AltEngineNetworkError(`transfer failed: ${method} ${scrub(url)}`, err);\n }\n if (!res.ok) throw await toTransferError(res, method, url);\n return res;\n }\n\n private async once<T>(method: string, path: string, opts: RequestOptions): Promise<T> {\n const headers: Record<string, string> = { ...opts.headers };\n // Precedence: an explicit per-request header wins, then the end-user identity\n // token, then the org API key. Asking the provider each time is what keeps a\n // long-lived page's token fresh (AuthClient refreshes before it expires).\n if (!Object.keys(headers).some((k) => k.toLowerCase() === \"authorization\")) {\n const token = await this.auth?.getToken();\n if (token) headers[\"authorization\"] = `Bearer ${token}`;\n else if (this.apiKey) headers[\"authorization\"] = `Bearer ${this.apiKey}`;\n }\n let body: string | undefined;\n if (opts.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n body = JSON.stringify(opts.body);\n }\n\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? this.timeoutMs);\n let res: Response;\n try {\n res = await this.fetchImpl(this.url(path, opts.query), { method, headers, body, signal: ctrl.signal });\n } catch (err) {\n throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);\n } finally {\n clearTimeout(timer);\n }\n\n if (!res.ok && !opts.acceptStatus?.includes(res.status)) throw await toApiError(res);\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n\nasync function toApiError(res: Response): Promise<AltEngineError> {\n let code = \"INTERNAL\";\n let message = `HTTP ${res.status}`;\n let details: unknown;\n try {\n const parsed = (await res.json()) as { error?: { code?: string; message?: string; details?: unknown } };\n if (parsed?.error) {\n code = parsed.error.code ?? code;\n message = parsed.error.message ?? message;\n details = parsed.error.details;\n }\n } catch {\n // Non-JSON error body; keep the status-derived defaults.\n }\n const ra = res.headers.get(\"retry-after\");\n const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : undefined;\n return new AltEngineError({ code, message, status: res.status, details, retryAfter });\n}\n\n/** A presigned URL is a bearer capability. Its query string carries the signature, so the URL\n * is stripped before it can reach an error message, a log line or a bug report. */\nconst scrub = (url: string): string => url.split(\"?\")[0] ?? url;\n\n/**\n * The error from a storage endpoint, which does not speak our envelope: S3 answers XML, and the\n * emulator answers JSON. Both are read, because \"SignatureDoesNotMatch\" is the difference\n * between a bug and a clock, and `HTTP 403` alone names neither.\n */\nasync function toTransferError(res: Response, method: string, url: string): Promise<AltEngineError> {\n const text = (await res.text().catch(() => \"\")).slice(0, 1000);\n let code = \"INTERNAL\";\n let message = \"\";\n try {\n const parsed = JSON.parse(text) as { error?: { code?: string; message?: string } };\n if (parsed?.error) {\n code = parsed.error.code ?? code;\n message = parsed.error.message ?? \"\";\n }\n } catch {\n code = /<Code>([^<]+)<\\/Code>/.exec(text)?.[1] ?? code;\n message = /<Message>([^<]+)<\\/Message>/.exec(text)?.[1] ?? \"\";\n }\n if (!message) {\n const snippet = text.replace(/\\s+/g, \" \").trim().slice(0, 200);\n message = `${method} ${scrub(url)} failed with HTTP ${res.status}${snippet ? `: ${snippet}` : \"\"}`;\n }\n return new AltEngineError({ code, message, status: res.status });\n}\n\n","import { Http, seg, nsSeg } from \"../http.js\";\nimport type {\n AggregateRequest,\n AggregateResult,\n CreateIndexRequest,\n DatastoreDocument,\n IndexSpec,\n Key,\n NamespacesPage,\n PutDocument,\n QueryRequest,\n QueryResult,\n TransactionResult,\n TxnOp,\n} from \"./types.js\";\n\nexport interface DatastoreOptions {\n /** Namespace bound to this client (default `\"\"`). */\n namespace?: string;\n}\n\n/** Client for one datastore instance, bound to a namespace. */\nexport class DatastoreClient {\n readonly instance: string;\n readonly namespace: string;\n /** Namespace administration for the whole instance (not namespace-bound). */\n readonly namespaces: NamespaceAdmin;\n private readonly http: Http;\n private readonly base: string;\n private readonly nsBase: string;\n\n constructor(http: Http, instance: string, opts: DatastoreOptions = {}) {\n this.http = http;\n this.instance = instance;\n this.namespace = opts.namespace ?? \"\";\n this.base = `/v1/datastore/${seg(instance)}`;\n this.nsBase = `${this.base}/ns/${nsSeg(this.namespace)}`;\n this.namespaces = new NamespaceAdmin(http, this.base);\n }\n\n /** Same instance, different namespace. */\n withNamespace(namespace: string): DatastoreClient {\n return new DatastoreClient(this.http, this.instance, { namespace });\n }\n\n /** Upsert up to 500 documents; returns their keys in order. */\n async put<T>(collection: string, documents: PutDocument<T>[]): Promise<{ keys: string[] }> {\n return this.http.request(\"POST\", `${this.nsBase}/col/${seg(collection)}/documents`, {\n body: { documents },\n retry: documents.every((doc) => doc.key != null) ? undefined : false,\n });\n }\n\n /** Fetch one document (`null` when missing), or — passed an array — up to 500\n * documents in one round trip, order-preserving with `null` placeholders for\n * missing keys (App Engine `db.get` semantics). Both forms ride the batch\n * endpoint — there is no single-document route on the wire. */\n async get<T = unknown>(collection: string, key: Key): Promise<DatastoreDocument<T> | null>;\n async get<T = unknown>(collection: string, keys: Key[]): Promise<(DatastoreDocument<T> | null)[]>;\n async get<T = unknown>(\n collection: string,\n keyOrKeys: Key | Key[]\n ): Promise<DatastoreDocument<T> | null | (DatastoreDocument<T> | null)[]> {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n const res = await this.http.request<{ documents: DatastoreDocument<T>[] }>(\n \"POST\",\n `${this.nsBase}/col/${seg(collection)}/documents/get`,\n { body: { keys } }\n );\n // The wire response omits missing keys; rebuild positional correspondence\n // (numeric keys are stored as decimal strings, so String() aligns them).\n const byKey = new Map(res.documents.map((d) => [d.key, d]));\n const docs = keys.map((k) => byKey.get(String(k)) ?? null);\n return Array.isArray(keyOrKeys) ? docs : docs[0]!;\n }\n\n /** Delete up to 500 documents by key; missing keys are no-ops. */\n async delete(collection: string, keys: Key[]): Promise<{ deleted: number }> {\n return this.http.request(\"POST\", `${this.nsBase}/col/${seg(collection)}/documents/delete`, {\n body: { keys },\n });\n }\n\n /** Run one page of an index-served query. */\n async query<T = unknown>(collection: string, req: QueryRequest = {}): Promise<QueryResult<T>> {\n return this.http.request(\"POST\", `${this.nsBase}/col/${seg(collection)}/query`, { body: req });\n }\n\n /** Iterate every matching document across pages (cursor handled for you). */\n async *queryAll<T = unknown>(collection: string, req: QueryRequest = {}): AsyncGenerator<DatastoreDocument<T>> {\n let cursor: string | null | undefined = req.cursor;\n do {\n const page: QueryResult<T> = await this.query<T>(collection, { ...req, cursor: cursor ?? undefined });\n for (const doc of page.documents ?? []) yield doc;\n cursor = page.cursor;\n } while (cursor);\n }\n\n /** Grouped metrics over an index-served filter. */\n async aggregate(collection: string, req: AggregateRequest): Promise<AggregateResult> {\n return this.http.request(\"POST\", `${this.nsBase}/col/${seg(collection)}/aggregate`, { body: req });\n }\n\n /** Apply up to 500 operations atomically within this namespace. NOT retried\n * automatically (increments would double-apply); a failed `check` throws a 409. */\n async transaction(operations: TxnOp[]): Promise<TransactionResult> {\n return this.http.request(\"POST\", `${this.nsBase}/transaction`, { body: { operations }, retry: false });\n }\n\n readonly indexes = {\n list: async (collection: string): Promise<{ indexes: IndexSpec[] }> =>\n this.http.request(\"GET\", `${this.nsBase}/col/${seg(collection)}/indexes`),\n create: async (collection: string, req: CreateIndexRequest): Promise<{ index: IndexSpec }> =>\n this.http.request(\"POST\", `${this.nsBase}/col/${seg(collection)}/indexes`, { body: req }),\n delete: async (collection: string, id: number): Promise<{ deleted: boolean }> =>\n this.http.request(\"DELETE\", `${this.nsBase}/col/${seg(collection)}/indexes/${seg(id)}`),\n };\n}\n\nexport class NamespaceAdmin {\n constructor(private readonly http: Http, private readonly base: string) {}\n\n /** A page of the instance's namespaces, newest first. When `has_more` is set, pass the\n * returned `cursor` back as `cursor` for the next page. */\n async list(opts: { q?: string; limit?: number; cursor?: string } = {}): Promise<NamespacesPage> {\n return this.http.request(\"GET\", `${this.base}/ns`, { query: { q: opts.q, limit: opts.limit, cursor: opts.cursor } });\n }\n\n /** Delete a namespace and everything in it. Requires a `full` grant. */\n async delete(namespace: string): Promise<{ deleted: boolean }> {\n return this.http.request(\"DELETE\", `${this.base}/ns/${nsSeg(namespace)}`);\n }\n}\n","import { Http, seg, nsSeg } from \"../http.js\";\nimport type {\n IndexSchema,\n IndexesPage,\n IndexInfo,\n ListDocumentsOptions,\n SearchDocument,\n SearchHit,\n SearchRequest,\n SearchResponse,\n} from \"./types.js\";\n\nexport interface SearchOptions {\n /** Namespace for all index operations (default `\"\"`). Rides the request path\n * (`/ns/{ns}/idx/{index}/…`), mirroring datastore. */\n namespace?: string;\n}\n\n/** Client for one search instance, bound to a namespace. */\nexport class SearchClient {\n readonly instance: string;\n readonly namespace: string;\n private readonly http: Http;\n private readonly base: string;\n /** Namespace-scoped base: `/v1/search/{instance}/ns/{ns}`. */\n private readonly nsBase: string;\n\n constructor(http: Http, instance: string, opts: SearchOptions = {}) {\n this.http = http;\n this.instance = instance;\n this.namespace = opts.namespace ?? \"\";\n this.base = `/v1/search/${seg(instance)}`;\n this.nsBase = `${this.base}/ns/${nsSeg(this.namespace)}`;\n }\n\n /** Same instance, different namespace. */\n withNamespace(namespace: string): SearchClient {\n return new SearchClient(this.http, this.instance, { namespace });\n }\n\n index(name: string): SearchIndex {\n return new SearchIndex(this.http, this.nsBase, name);\n }\n\n /** Indexes in this client's namespace. When `has_more` is set, pass the returned `cursor`\n * back as `cursor` for the next page. */\n async listIndexes(opts: { q?: string; limit?: number; cursor?: string } = {}): Promise<IndexesPage> {\n return this.http.request(\"GET\", `${this.nsBase}/idx`, {\n query: { q: opts.q, limit: opts.limit, cursor: opts.cursor },\n });\n }\n\n /** Every index in this client's namespace, following the cursor for you.\n *\n * Stops on a cursor that does not advance as well as on a missing one: an SDK outlives the\n * deployment it was written against, and a server that keeps handing back the same cursor\n * would otherwise be followed for ever, billing each round. Same rule as `searchAll`. */\n async *listAllIndexes(opts: { q?: string; limit?: number } = {}): AsyncGenerator<IndexInfo> {\n const seen = new Set<string>();\n let cursor: string | undefined;\n for (;;) {\n const page: IndexesPage = await this.listIndexes({ ...opts, cursor });\n for (const index of page.indexes ?? []) yield index;\n const next = page.cursor ?? undefined;\n if (!page.indexes?.length || !next || seen.has(next)) return;\n seen.add(next);\n cursor = next;\n }\n }\n\n /** Distinct namespaces with live indexes — alphabetical, `q` substring search,\n * `limit` default 50 (max 100). Instance-wide (not bound to this client's\n * namespace); the default namespace appears as `\"\"`. */\n async listNamespaces(opts: { q?: string; limit?: number } = {}): Promise<{ namespaces: string[]; has_more: boolean }> {\n return this.http.request(\"GET\", `${this.base}/ns`, { query: { q: opts.q, limit: opts.limit } });\n }\n\n /** Delete an index and all its documents. Requires a `full` grant. */\n async deleteIndex(name: string): Promise<{ deleted: boolean }> {\n return this.http.request(\"DELETE\", `${this.nsBase}/idx/${seg(name)}`);\n }\n}\n\n/** Operations on one search index. */\nexport class SearchIndex {\n private readonly path: string;\n\n constructor(private readonly http: Http, nsBase: string, readonly name: string) {\n this.path = `${nsBase}/idx/${seg(name)}`;\n }\n\n /** Upsert up to 200 documents; returns their ids in order (server-assigned when\n * a document omits `id`). */\n async put(documents: SearchDocument[]): Promise<{ ids: string[] }> {\n return this.http.request(\"POST\", `${this.path}/documents`, { body: { documents } });\n }\n\n /** Fetch one document (`null` when missing), or — passed an array — up to 200\n * documents in one round trip, order-preserving with `null` placeholders for\n * missing ids. Both forms ride the batch endpoint. */\n async get(id: string): Promise<SearchDocument | null>;\n async get(ids: string[]): Promise<(SearchDocument | null)[]>;\n async get(idOrIds: string | string[]): Promise<SearchDocument | null | (SearchDocument | null)[]> {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n const res = await this.http.request<{ documents: SearchDocument[] }>(\n \"POST\",\n `${this.path}/documents/get`,\n { body: { ids } }\n );\n const byId = new Map(res.documents.map((d) => [d.id, d]));\n const docs = ids.map((id) => byId.get(id) ?? null);\n return Array.isArray(idOrIds) ? docs : docs[0]!;\n }\n\n /** Delete up to 200 documents by id; missing ids are no-ops. Requires `full`. */\n async delete(ids: string[]): Promise<{ deleted: number }> {\n return this.http.request(\"POST\", `${this.path}/documents/delete`, { body: { ids } });\n }\n\n /** Run a search request (see `SearchRequest` for the full surface). */\n async search(req: SearchRequest): Promise<SearchResponse> {\n return this.http.request(\"POST\", `${this.path}/search`, { body: req });\n }\n\n /**\n * Iterate every hit across cursor pages.\n *\n * Stops on a cursor that does not advance, as well as on a missing one. Search paging ends at a\n * fixed depth, and a server that kept issuing a cursor past it handed back the SAME page — so\n * \"follow the cursor until it is absent\", which is what this loop did, fetched that page for\n * ever and billed each round. The server no longer does that; this is the half that does not\n * depend on which version you are talking to, since an SDK outlives the deployment it was\n * written against.\n */\n async *searchAll(req: SearchRequest): AsyncGenerator<SearchHit> {\n let cursor: string | undefined = req.cursor;\n const seen = new Set<string>();\n for (;;) {\n const page: SearchResponse = await this.search({ ...req, cursor, offset: undefined });\n for (const hit of page.results) yield hit;\n const next = page.cursor;\n if (!next || next === cursor || seen.has(next) || page.results.length === 0) return;\n seen.add(next);\n cursor = next;\n }\n }\n\n /** One page of documents in id order (keyset pagination via `start_id`). */\n async listDocuments(opts: ListDocumentsOptions & { ids_only?: false }): Promise<{ documents: SearchDocument[] }>;\n async listDocuments(opts: ListDocumentsOptions & { ids_only: true }): Promise<{ ids: string[] }>;\n async listDocuments(\n opts: ListDocumentsOptions & { ids_only?: boolean } = {}\n ): Promise<{ documents?: SearchDocument[]; ids?: string[] }> {\n return this.http.request(\"GET\", `${this.path}/documents`, {\n query: {\n start_id: opts.start_id,\n include_start: opts.include_start,\n limit: opts.limit,\n ids_only: opts.ids_only,\n },\n });\n }\n\n /** Iterate every document in the index (keyset pagination handled for you). */\n async *listAllDocuments(opts: { limit?: number } = {}): AsyncGenerator<SearchDocument> {\n let startId: string | undefined;\n for (;;) {\n const page = await this.listDocuments({\n start_id: startId,\n include_start: startId === undefined,\n limit: opts.limit,\n });\n const docs = page.documents;\n if (!docs.length) return;\n for (const doc of docs) yield doc;\n startId = docs[docs.length - 1]!.id;\n }\n }\n\n /** The index's union field schema. */\n async schema(): Promise<IndexSchema> {\n return this.http.request(\"GET\", `${this.path}/schema`);\n }\n}\n","import { Http, seg } from \"../http.js\";\nimport type { PresenceResponse, TokenRequest, TokenResponse } from \"./types.js\";\n\n/** Server-side client for one channel instance (API-key auth): mint subscriber\n * tokens, publish over HTTP, and read presence. For the browser/edge WebSocket\n * subscriber, use `ChannelSocket` from `@altenginenet/sdk/channel`. */\nexport class ChannelClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/channel/${seg(instance)}`;\n }\n\n /** Mint a subscriber token (JWT) for the given channels. */\n async createToken(req: TokenRequest): Promise<TokenResponse> {\n return this.http.request(\"POST\", `${this.base}/tokens`, { body: req });\n }\n\n /** Publish a message (framed ≤32 KiB) to a channel; returns the number of\n * subscribers reached. NOT retried automatically (a retry double-delivers). */\n async publish(channel: string, data: unknown): Promise<{ delivered: number }> {\n return this.http.request(\"POST\", `${this.base}/publish`, { body: { channel, data }, retry: false });\n }\n\n /** Presence roster for a channel (requires the instance's presence flag). */\n async presence(channel: string): Promise<PresenceResponse> {\n return this.http.request(\"GET\", `${this.base}/presence`, { query: { channel } });\n }\n}\n","/** Where the signed-in session is kept between page loads. Implement this to use\n * cookies, IndexedDB, React Native's AsyncStorage (via a sync cache), or nothing\n * at all. The default picks `localStorage` in the browser and falls back to an\n * in-memory store everywhere else (Node, SSR, private-mode failures). */\nexport interface TokenStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\n/** A `TokenStorage` that forgets everything when the process/tab goes away. */\nexport function memoryStorage(): TokenStorage {\n const map = new Map<string, string>();\n return {\n get: (k) => map.get(k) ?? null,\n set: (k, v) => void map.set(k, v),\n remove: (k) => void map.delete(k),\n };\n}\n\n/** `localStorage` when it's present AND writable, else an in-memory store.\n * Safari private mode throws on `setItem`, so this probes with a real write. */\nexport function defaultStorage(): TokenStorage {\n try {\n const ls = globalThis.localStorage;\n if (!ls) return memoryStorage();\n const probe = \"__altengine_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n return {\n get: (k) => ls.getItem(k),\n set: (k, v) => ls.setItem(k, v),\n remove: (k) => ls.removeItem(k),\n };\n } catch {\n return memoryStorage();\n }\n}\n","/** AuthClient — the browser-side identity client for `/v1/auth/{instance}`.\n *\n * This is the piece that lets a client-side app talk to altengine with **no\n * backend of its own**: the end user signs in here, and the resulting `id_token`\n * is what Datastore/Channel requests carry. Access rules on the auth instance\n * decide what that user may read and write.\n *\n * Deliberately self-contained and API-key-free (like `ChannelSocket`) so it is\n * safe to ship to a browser — see the `@altenginenet/sdk/auth` subpath export.\n *\n * ```ts\n * import { AuthClient } from \"@altenginenet/sdk/auth\";\n * import { AltEngine } from \"@altenginenet/sdk\";\n *\n * const auth = new AuthClient({ instance: \"myapp-auth\" });\n * await auth.signIn(\"alice@example.com\", \"hunter2\");\n *\n * // Hand the client to the SDK: every request now carries the user's token.\n * const ae = new AltEngine({ auth });\n * const { documents } = await ae.datastore(\"myapp\").query(\"posts\", { limit: 20 });\n * ```\n */\n\nimport { AltEngineError, AltEngineNetworkError } from \"../errors.js\";\nimport { DEFAULT_BASE_URL, DEV_BASE_URL, seg } from \"../constants.js\";\nimport { defaultStorage, memoryStorage, type TokenStorage } from \"./storage.js\";\nimport type { AuthConfig, AuthSession, AuthUser, SignInResult, StoredSession, AuthTokens } from \"./types.js\";\n\nexport interface AuthClientOptions {\n /** The auth instance name, e.g. \"myapp-auth\". */\n instance: string;\n /** API origin override. Resolution order: this → `dev: true` → production. */\n baseUrl?: string;\n /** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */\n dev?: boolean;\n /** Where to persist the session (default: `localStorage`, else in-memory).\n * Pass `memoryStorage()` to keep the session out of storage entirely. */\n storage?: TokenStorage;\n /** Storage key prefix, so several apps/instances can share one origin.\n * Defaults to `altengine.auth.<instance>`. */\n storageKey?: string;\n /** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Refresh the id_token this many seconds before it expires (default 30). */\n refreshSkewSeconds?: number;\n}\n\ntype Listener = (user: AuthUser | null) => void;\n\nconst nowSec = () => Math.floor(Date.now() / 1000);\n\nexport class AuthClient {\n readonly instance: string;\n readonly baseUrl: string;\n\n private readonly base: string;\n private readonly storage: TokenStorage;\n private readonly key: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly skew: number;\n private readonly listeners = new Set<Listener>();\n\n private session: StoredSession | null;\n /** In-flight refresh, so concurrent requests share one round trip. */\n private refreshing: Promise<string | undefined> | null = null;\n\n constructor(opts: AuthClientOptions) {\n if (!opts.instance) throw new Error(\"AuthClient requires an `instance`\");\n this.instance = opts.instance;\n this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\\/+$/, \"\");\n this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;\n this.storage = opts.storage ?? defaultStorage();\n this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;\n const f = opts.fetch ?? globalThis.fetch;\n if (!f) throw new Error(\"no fetch implementation available; pass { fetch }\");\n this.fetchImpl = f;\n this.skew = opts.refreshSkewSeconds ?? 30;\n this.session = this.load();\n }\n\n // --- session state ------------------------------------------------------\n\n /** The signed-in user, or null. Reads persisted state, so it survives reloads. */\n get user(): AuthUser | null {\n return this.session?.user ?? null;\n }\n\n get isSignedIn(): boolean {\n return !!this.session?.id_token;\n }\n\n /** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */\n onChange(fn: Listener): () => void {\n this.listeners.add(fn);\n return () => void this.listeners.delete(fn);\n }\n\n private emit(): void {\n for (const fn of this.listeners) {\n try {\n fn(this.user);\n } catch {\n /* a listener must never break the auth flow */\n }\n }\n }\n\n private load(): StoredSession | null {\n try {\n const raw = this.storage.get(this.key);\n return raw ? (JSON.parse(raw) as StoredSession) : null;\n } catch {\n return null;\n }\n }\n\n private save(s: StoredSession | null): void {\n this.session = s;\n try {\n if (s) this.storage.set(this.key, JSON.stringify(s));\n else this.storage.remove(this.key);\n } catch {\n /* storage full / blocked — the session still works for this page */\n }\n this.emit();\n }\n\n private adopt(t: AuthTokens & { user?: AuthUser }): AuthSession {\n const user = t.user ?? this.session?.user ?? null;\n this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });\n return { ...t, user: user as AuthUser };\n }\n\n // --- transport ----------------------------------------------------------\n\n private async call<T>(method: string, path: string, body?: unknown, bearer?: string): Promise<T> {\n const headers: Record<string, string> = {};\n if (bearer) headers[\"authorization\"] = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n let res: Response;\n try {\n res = await this.fetchImpl(this.base + path, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);\n }\n if (!res.ok) throw await toError(res);\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n\n // --- config -------------------------------------------------------------\n\n /** The instance's public sign-in configuration — which fields the sign-up form\n * collects, which one is the login identity, and which methods are enabled.\n * Fetch this to render a sign-in UI that matches the instance's settings. */\n async config(): Promise<AuthConfig> {\n return this.call<AuthConfig>(\"GET\", \"/config\");\n }\n\n // --- sign up / in / out -------------------------------------------------\n\n /** Create an account. Pass the configured sign-up fields plus `password`,\n * e.g. `{ email, name, password }`. Signs the new user in. */\n async signUp(fields: Record<string, unknown>): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/signup\", fields);\n return this.adopt(t);\n }\n\n /** Sign in with the identity field + password. When the account has two-factor\n * enabled this resolves to `{ status: \"mfa_required\" }` and you must call\n * {@link verifyMfa} with the code — no tokens are issued until then. */\n async signIn(identifier: string, password: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/signin\", {\n identifier,\n password,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */\n async verifyMfa(mfaToken: string, code: string): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/2fa/verify\", { mfa_token: mfaToken, code });\n return this.adopt(t);\n }\n\n /** Start passwordless sign-in: emails a one-time code. Always resolves — the\n * server never reveals whether the account exists. */\n async passwordlessStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/passwordless/start\", { identifier });\n }\n\n /** Finish passwordless sign-in with the emailed code. */\n async passwordlessVerify(identifier: string, code: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/passwordless/verify\", {\n identifier,\n code,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Start a password reset: emails a one-time code. Always resolves. */\n async passwordResetStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/start\", { identifier });\n }\n\n /** Finish a password reset with the emailed code and a new password. */\n async passwordResetVerify(identifier: string, code: string, password: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/verify\", { identifier, code, password });\n }\n\n /** The signed-in user, re-read from the server (picks up claim changes). */\n async me(): Promise<AuthUser> {\n const tok = await this.getToken();\n if (!tok) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n // The wire wraps the user in a `{ user }` envelope.\n const { user } = await this.call<{ user: AuthUser }>(\"GET\", \"/me\", undefined, tok);\n // Keep the cached user in step, so claim changes made elsewhere land locally too.\n if (user && this.session) this.save({ ...this.session, user });\n return user;\n }\n\n /** Revoke the refresh token server-side and clear local state. Always clears\n * locally, even if the network call fails. */\n async signOut(): Promise<void> {\n const rt = this.session?.refresh_token;\n this.save(null);\n if (rt) {\n try {\n await this.call(\"POST\", \"/signout\", { refresh_token: rt });\n } catch {\n /* best-effort: local state is already gone */\n }\n }\n }\n\n // --- tokens -------------------------------------------------------------\n\n /** Force a refresh-token rotation and return the new id_token. */\n async refresh(): Promise<string> {\n const rt = this.session?.refresh_token;\n if (!rt) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n const t = await this.call<AuthTokens>(\"POST\", \"/token/refresh\", { refresh_token: rt });\n this.adopt(t);\n return t.id_token;\n }\n\n /**\n * The current id_token, refreshed first if it is expired or about to be.\n * Returns `undefined` when nobody is signed in. This is the `TokenProvider`\n * the SDK calls before every Datastore/Search/Channel request — pass the\n * client as `new AltEngine({ auth })` and tokens stay fresh automatically.\n *\n * Concurrent callers share a single refresh. If the refresh fails because the\n * session is truly gone (401/403), local state is cleared so the app can react\n * via {@link onChange} instead of retrying forever.\n */\n async getToken(): Promise<string | undefined> {\n const s = this.session;\n if (!s?.id_token) return undefined;\n if (s.expires_at - this.skew > nowSec()) return s.id_token;\n if (!this.refreshing) {\n this.refreshing = this.refresh()\n .catch((err) => {\n if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {\n this.save(null); // refresh token revoked/expired — session is over\n return undefined;\n }\n throw err; // transient (network/5xx): let the caller see it and retry\n })\n .finally(() => {\n this.refreshing = null;\n });\n }\n return this.refreshing;\n }\n}\n\nasync function toError(res: Response): Promise<AltEngineError> {\n let code = \"INTERNAL\";\n let message = `HTTP ${res.status}`;\n let details: unknown;\n try {\n const parsed = (await res.json()) as { error?: { code?: string; message?: string; details?: unknown } };\n if (parsed?.error) {\n code = parsed.error.code ?? code;\n message = parsed.error.message ?? message;\n details = parsed.error.details;\n }\n } catch {\n /* non-JSON error body */\n }\n const ra = res.headers.get(\"retry-after\");\n const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : undefined;\n return new AltEngineError({ code, message, status: res.status, details, retryAfter });\n}\n\nexport { memoryStorage, defaultStorage, type TokenStorage };\n","/** Sleep, abortable — so a `wait` inside a request handler dies with the request rather than\n * holding it open until work nobody is watching any more finishes. */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error(\"aborted\"));\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort() {\n clearTimeout(t);\n reject(signal?.reason ?? new Error(\"aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import { Http, seg } from \"../http.js\";\nimport { sleep } from \"../poll.js\";\nimport type {\n Agent,\n Artifact,\n Delivery,\n LogPage,\n Run,\n RunWithArtifacts,\n Schedule,\n Script,\n StartRunRequest,\n} from \"./types.js\";\n\n/** How long `wait` sleeps between polls, and the ceiling it backs off to.\n *\n * A run drives a real desktop for minutes or hours, so polling fast buys nothing and costs a\n * request every time. Starts at two seconds because a browser-only run can genuinely be quick. */\nconst POLL_START_MS = 2_000;\nconst POLL_MAX_MS = 15_000;\n\nconst TERMINAL = new Set([\"done\", \"failed\", \"canceled\", \"abandoned\"]);\n\n/**\n * Server-side client for one automation instance.\n *\n * ORGANIZATION API KEY ONLY. End-user identity tokens are refused by this service, as they are by\n * containers: a run spends time on a machine you own, and access rules bound what a user may\n * READ, not what they may spend. Have a page call a function that decides.\n *\n * Scripts are deployed with the CLI (`altengine automation deploy`), not from here — they are\n * bundled into one flat ES module before upload, and shipping a bundler in this package to do it\n * at runtime would be the wrong trade for every caller who never deploys.\n */\nexport class AutomationClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/automation/${seg(instance)}`;\n }\n\n // --- runs ---------------------------------------------------------------\n\n /**\n * Start a run and return immediately.\n *\n * A `queued` run is NOT a failure — it means no machine matching the request is online yet, and\n * an office PC being asleep is the ordinary case. It will be dispatched when one connects.\n */\n async start(req: StartRunRequest): Promise<Run> {\n const { run } = await this.http.request<{ run: Run }>(\"POST\", `${this.base}/runs`, {\n body: req,\n // A retried start is a SECOND RUN: it drives a real application, so a duplicate is a second\n // pass over the same invoices rather than a wasted request.\n retry: false,\n });\n return run;\n }\n\n /** A run and its artifacts, each with a freshly minted download link. */\n async get(runId: string): Promise<RunWithArtifacts> {\n return this.http.request(\"GET\", `${this.base}/runs/${seg(runId)}`);\n }\n\n async list(\n query: { status?: string; script?: string; agent_id?: string; limit?: number; cursor?: string } = {}\n ): Promise<{ runs: Run[]; cursor: string | null }> {\n return this.http.request(\"GET\", `${this.base}/runs`, { query });\n }\n\n /** Stop a queued or running run. The script unwinds through its own cleanup. */\n async cancel(runId: string): Promise<{ canceled: boolean }> {\n return this.http.request(\"POST\", `${this.base}/runs/${seg(runId)}/cancel`, { retry: false });\n }\n\n /**\n * A page of the run's log.\n *\n * While the run is going this is a live tail from the machine — the last few hundred lines, not\n * a transcript. Once it finishes it is the complete log the run uploaded, so a finished run is\n * readable even from a machine that has since been switched off. `source` says which answered.\n */\n async logs(runId: string, query: { cursor?: string } = {}): Promise<LogPage> {\n return this.http.request(\"GET\", `${this.base}/runs/${seg(runId)}/logs`, { query });\n }\n\n /** The run's artifacts, each with a freshly minted download link. */\n async artifacts(runId: string): Promise<Artifact[]> {\n const { artifacts } = await this.http.request<{ artifacts: Artifact[] }>(\n \"GET\",\n `${this.base}/runs/${seg(runId)}/artifacts`\n );\n return artifacts;\n }\n\n /**\n * Poll until a run reaches a terminal status, then return it with its artifacts.\n *\n * THE RUN IS FINISHED WHEN ITS OUTPUT HAS LANDED, not when its script returned — the agent holds\n * the terminal report until every artifact has been stored — so a `done` here always has its\n * files, and the links on them are live.\n *\n * `timeoutMs` bounds the WAIT, not the run: giving up here leaves the run going on the machine.\n * Call `cancel` if that is what you meant. Zero (the default) waits indefinitely, which is\n * usually right for a job that legitimately takes hours.\n */\n async wait(\n runId: string,\n opts: { timeoutMs?: number; signal?: AbortSignal; onPoll?: (run: Run) => void } = {}\n ): Promise<RunWithArtifacts> {\n const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : 0;\n let delay = POLL_START_MS;\n for (;;) {\n const current = await this.get(runId);\n opts.onPoll?.(current.run);\n if (TERMINAL.has(current.run.status)) return current;\n if (deadline && Date.now() >= deadline) {\n throw new Error(\n `run ${runId} was still ${current.run.status} after ${opts.timeoutMs}ms — it is still going on the machine; cancel it if that is not what you want`\n );\n }\n let ms = delay;\n if (deadline) ms = Math.min(ms, Math.max(0, deadline - Date.now()));\n await sleep(ms, opts.signal);\n delay = Math.min(delay * 2, POLL_MAX_MS);\n }\n }\n\n /** Start a run and wait for it. Convenience over `start` + `wait`. */\n async run(\n req: StartRunRequest,\n opts: { timeoutMs?: number; signal?: AbortSignal; onPoll?: (run: Run) => void } = {}\n ): Promise<RunWithArtifacts> {\n const started = await this.start(req);\n return this.wait(started.id, opts);\n }\n\n // --- machines, scripts, schedules ---------------------------------------\n\n /** Enrolled machines, with whether each is connected right now. */\n /**\n * One page of enrolled machines, with whether each is connected right now.\n *\n * PAGED, and the cursor matters: a fleet of hundreds is the ordinary shape of this service —\n * an office, a chain of dealerships — and a caller that ignores it is looking at part of one.\n * `q` matches name, hostname or label, which are the three things a machine is known by.\n */\n async agents(\n query: { cursor?: string; q?: string; limit?: number } = {}\n ): Promise<{ agents: Agent[]; cursor: string | null }> {\n return this.http.request(\"GET\", `${this.base}/agents`, { query });\n }\n\n /**\n * Every enrolled machine, walking the pages for you.\n *\n * Here because the alternative — a `agents()` that quietly returned the first page — is how a\n * fleet with more machines than a page silently became a smaller fleet. If you are counting\n * machines, or acting on all of them, use this one.\n */\n async allAgents(query: { q?: string } = {}): Promise<Agent[]> {\n const out: Agent[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await this.agents({ ...query, cursor });\n out.push(...page.agents);\n if (!page.cursor) return out;\n cursor = page.cursor;\n }\n }\n\n async agent(agentId: string): Promise<Agent> {\n return this.http.request(\"GET\", `${this.base}/agents/${seg(agentId)}`);\n }\n\n /**\n * One page of deployed scripts and their active versions. Deploy with the CLI.\n *\n * PAGED, like `agents`. Both routes return a cursor and both used to have it dropped here, so a\n * caller past the first page saw part of an answer and was told nothing — which is the exact\n * shape the `agents`/`allAgents` pair below already exists to avoid.\n */\n async scripts(\n query: { cursor?: string; limit?: number } = {}\n ): Promise<{ scripts: Script[]; cursor: string | null }> {\n return this.http.request(\"GET\", `${this.base}/scripts`, { query });\n }\n\n /** Every deployed script, walking the pages for you. */\n async allScripts(): Promise<Script[]> {\n const out: Script[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await this.scripts({ cursor });\n out.push(...page.scripts);\n if (!page.cursor) return out;\n cursor = page.cursor;\n }\n }\n\n /** One page of declared schedules. */\n async schedules(\n query: { cursor?: string; limit?: number } = {}\n ): Promise<{ schedules: Schedule[]; cursor: string | null }> {\n return this.http.request(\"GET\", `${this.base}/schedules`, { query });\n }\n\n /** Every declared schedule, walking the pages for you. */\n async allSchedules(): Promise<Schedule[]> {\n const out: Schedule[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await this.schedules({ cursor });\n out.push(...page.schedules);\n if (!page.cursor) return out;\n cursor = page.cursor;\n }\n }\n\n /**\n * Declare a schedule. The cloud owns WHAT should happen; the machine owns WHEN — it fires from\n * its own clock, so a nightly export still runs while your internet is down and only the run's\n * record is late.\n */\n async createSchedule(req: Partial<Schedule> & { script: string; cron: string }): Promise<Schedule> {\n const { schedule } = await this.http.request<{ schedule: Schedule }>(\"POST\", `${this.base}/schedules`, {\n body: req,\n retry: false,\n });\n return schedule;\n }\n\n async deleteSchedule(scheduleId: string): Promise<void> {\n await this.http.request(\"DELETE\", `${this.base}/schedules/${seg(scheduleId)}`, { retry: false });\n }\n\n // --- inbound data --------------------------------------------------------\n\n /**\n * Hand a value to whichever job is waiting for it — `job.waitForData(key)` on the other end.\n *\n * THE CASE THIS IS FOR: a script signs into a portal, the portal sends a one-time code to a\n * mailbox or a phone, and whatever receives that message calls this. Everything else the agent\n * does is outbound; this is the one way to tell a run something.\n *\n * ADDRESSED BY KEY, not by run id, because the thing that will deliver the code — an SMS\n * webhook, an inbound-mail parser — was configured months before tonight's run existed. That\n * puts a duty on the key: the value reaches every job executing on the instance, and only one\n * that asks for that key ever sees it, so `otp.dealer-42` is the shape to write when more than\n * one job can be in flight. `script` and `agentId` narrow it further.\n *\n * Throws when nothing is running. The usual failure is a race you cannot see — the code arrived\n * four seconds after the script gave up — and an integration needs to log that rather than read\n * a silent success.\n *\n * `delivered` counts what the MACHINES confirmed. A run in `undetermined` was written to and did\n * not acknowledge, which is not a failure: do not send a replacement value, because the job may\n * already have this one and a second one-time code invalidates the first.\n */\n async send(\n key: string,\n value: unknown,\n opts: { script?: string; agentId?: string } = {}\n ): Promise<Delivery> {\n return this.http.request(\"POST\", `${this.base}/data/${seg(key)}`, {\n query: { script: opts.script, agent_id: opts.agentId },\n body: value,\n retry: false,\n });\n }\n\n /** The same, to ONE run by id — for when you were given the run id, typically because the\n * script handed out `job.dataUrl(key)` when it triggered whatever produces the value.\n *\n * `delivered: false` with `undetermined: true` is the written-but-unacknowledged case: leave it\n * alone and let the job's own timeout decide. */\n async sendToRun(\n runId: string,\n key: string,\n value: unknown\n ): Promise<{ delivered: boolean; undetermined?: true; run: string; key: string; message?: string }> {\n return this.http.request(\"POST\", `${this.base}/runs/${seg(runId)}/data/${seg(key)}`, {\n body: value,\n retry: false,\n });\n }\n\n // --- credentials ---------------------------------------------------------\n\n /** The NAMES of the credentials this fleet's scripts read as `env.NAME`. Values are write-only\n * and never returned — a leaked key can replace one but not harvest it. */\n async env(): Promise<string[]> {\n const { env } = await this.http.request<{ env: string[] }>(\"GET\", `${this.base}/env`);\n return env;\n }\n\n /**\n * Replace the credential map. Omitting a name deletes it; `null` for a name KEEPS what is\n * stored, which is the only way to rotate one without re-typing the others you cannot read.\n */\n async setEnv(env: Record<string, string | null>): Promise<string[]> {\n const res = await this.http.request<{ env: string[] }>(\"PUT\", `${this.base}/env`, {\n body: { env },\n retry: false,\n });\n return res.env;\n }\n}\n","import { Http, seg, type ClientOptions } from \"../http.js\";\nimport { AltEngineError } from \"../errors.js\";\nimport type {\n BlobDownload,\n BlobListQuery,\n BlobPage,\n BlobRecord,\n MintedUpload,\n MultipartBegin,\n MultipartUrls,\n UploadOptions,\n UploadUrlRequest,\n} from \"./types.js\";\n\n/**\n * What one presigned PUT can carry, and therefore where multipart starts.\n *\n * Not our number: object storage caps a single upload here, and a presigned URL is exactly one\n * request. The instance's own size limit is a cost control and a different question.\n */\nexport const MAX_SINGLE_PUT_BYTES = 5 * 1024 * 1024 * 1024;\n\nconst DEFAULT_CONTENT_TYPE = \"application/octet-stream\";\n\n/**\n * Client for one blob instance.\n *\n * BYTES NEVER TRAVEL THROUGH THE API. Every upload and download here goes to a presigned URL,\n * so the API sees a reservation and storage sees the file. There is no commit step: the row is\n * promoted by the side that received the bytes.\n *\n * Levels are a ceiling — `read < write < full`. Uploading needs `write`; `delete` needs `full`.\n *\n * A CONTAINER JOB'S TOKEN IS NARROWER THAN AN API KEY, and the two refusals it carries are\n * refusals, not omissions: it may not `list` a store, and it may not publish — `setPublic`, and\n * `public: true` on an upload. Both come back as 403s naming what was refused. A job is told\n * its inputs; it does not go looking, and publishing is the one act that outlives the credential\n * that made it.\n */\nexport class BlobClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/blob/${seg(instance)}`;\n }\n\n // --- uploading ------------------------------------------------------------\n\n /**\n * Store a file. Returns the finished object.\n *\n * Picks the transfer for you: one presigned PUT, or a multipart upload when a `Blob`/`File` is\n * larger than storage will take in a single request. `content` may be a string, an\n * `ArrayBuffer`, a typed array, or a `Blob`/`File` — only a `Blob` can be uploaded in parts,\n * since parts are sliced from it rather than held in memory.\n *\n * `contentType` is worth passing: without one an object is stored as\n * `application/octet-stream`, which a browser downloads rather than renders. A `File` carries\n * its own.\n */\n async put(\n name: string,\n content: string | ArrayBuffer | ArrayBufferView | Blob,\n opts: UploadOptions = {}\n ): Promise<BlobRecord> {\n const body = toBody(content);\n const contentType = opts.contentType ?? blobType(content) ?? DEFAULT_CONTENT_TYPE;\n if (isBlob(body) && body.size > MAX_SINGLE_PUT_BYTES) {\n return this.putMultipart(name, body, contentType, opts);\n }\n const size = isBlob(body) ? body.size : body.byteLength;\n const minted = await this.uploadUrl({\n name,\n size,\n content_type: contentType,\n public: opts.public,\n meta: opts.meta,\n });\n await this.http.transfer(minted.upload_url, {\n method: minted.method,\n // content-length is set by the runtime from the body. It is signed into the URL, so a\n // body of a different length is refused by storage rather than stored short.\n headers: { \"content-type\": contentType },\n body: body as BodyInit,\n signal: opts.signal,\n });\n opts.onProgress?.({ uploaded: size, total: size });\n return this.read(minted.id);\n }\n\n /**\n * Mint a URL a client PUTs bytes to directly, without handing that client an API key.\n *\n * This is how a browser uploads: your backend decides whether this user may, and how big the\n * file may be, then hands over a URL that can do exactly that one thing for fifteen minutes.\n * The size is signed in, so it is the real bound on what the holder can make you store.\n */\n async uploadUrl(req: UploadUrlRequest): Promise<MintedUpload> {\n return this.http.request(\"POST\", `${this.base}/uploads`, { body: req, retry: false });\n }\n\n /** Reserve an object and sign the call that opens a multipart upload. Use `put` unless you\n * are driving the transfer yourself. */\n async beginMultipart(req: UploadUrlRequest): Promise<MultipartBegin> {\n return this.http.request(\"POST\", `${this.base}/uploads/multipart`, { body: req, retry: false });\n }\n\n /** Sign a window of part URLs, plus the complete and abort URLs. At most 100 parts per call. */\n async multipartUrls(req: { id: string; upload_id: string; from?: number; count?: number }): Promise<MultipartUrls> {\n return this.http.request(\"POST\", `${this.base}/uploads/multipart/urls`, { body: req, retry: false });\n }\n\n // --- reading --------------------------------------------------------------\n\n /** An object's metadata plus a short-lived download URL. */\n async get(id: string): Promise<BlobDownload> {\n return this.http.request(\"GET\", `${this.base}/${seg(id)}`);\n }\n\n /** An object's bytes, fetched from storage rather than through the API. */\n async bytes(id: string, opts: { signal?: AbortSignal } = {}): Promise<Uint8Array> {\n const { download_url } = await this.get(id);\n const res = await this.http.transfer(download_url, { signal: opts.signal });\n return new Uint8Array(await res.arrayBuffer());\n }\n\n /**\n * One page of objects, newest first.\n *\n * PAGED, and the cursor matters: a store is small in development and unbounded in a real\n * account, so a caller that ignores it is looking at part of one.\n *\n * Refused for a container job token — a job is told its inputs rather than enumerating the\n * store it writes to.\n */\n async list(query: BlobListQuery = {}): Promise<BlobPage> {\n return this.http.request(\"GET\", this.base, { query });\n }\n\n /** Every object, walking the pages for you. */\n async *listAll(query: Omit<BlobListQuery, \"cursor\"> = {}): AsyncGenerator<BlobRecord> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.list({ ...query, cursor });\n for (const b of page.blobs) yield b;\n if (!page.cursor) return;\n cursor = page.cursor;\n }\n }\n\n // --- changing -------------------------------------------------------------\n\n /**\n * Publish or unpublish an object. A public object is served from a stable URL with no\n * credential at all; unpublishing drops the cached copies too.\n *\n * Refused for a container job token: publishing is the one operation whose effect outlives the\n * credential that made it.\n */\n async setPublic(id: string, isPublic = true): Promise<BlobRecord> {\n const { blob } = await this.http.request<{ blob: BlobRecord }>(\"POST\", `${this.base}/${seg(id)}/public`, {\n body: { public: isPublic },\n retry: false,\n });\n return blob;\n }\n\n /** Delete up to 200 objects. Needs `full`; ids that do not exist are not counted. */\n async delete(ids: string[]): Promise<{ deleted: number }> {\n return this.http.request(\"POST\", `${this.base}/delete`, { body: { ids }, retry: false });\n }\n\n // --- the multipart transfer -----------------------------------------------\n\n /**\n * Cut a large file up, send the parts, and let storage glue them back together — so what the\n * customer downloads is one ordinary file rather than a split archive they need a tool for.\n *\n * Parts go up one at a time: these bytes usually leave an office connection, and a part that\n * fails is a part re-sent in full. ON ANY FAILURE THE UPLOAD IS ABORTED, because parts of an\n * upload nobody completed keep billing and no listing shows them.\n */\n private async putMultipart(\n name: string,\n file: Blob,\n contentType: string,\n opts: UploadOptions\n ): Promise<BlobRecord> {\n const begun = await this.beginMultipart({\n name,\n size: file.size,\n content_type: contentType,\n public: opts.public,\n meta: opts.meta,\n });\n\n // The content type is pinned by the call that creates the upload — storage takes the\n // finished object's metadata from it — and it is signed into that URL.\n const created = await this.http.transfer(begun.create_url, {\n method: \"POST\",\n headers: { \"content-type\": contentType },\n signal: opts.signal,\n });\n const uploadId = /<UploadId>([^<]+)<\\/UploadId>/.exec(await created.text())?.[1];\n if (!uploadId) throw new AltEngineError({ code: \"INTERNAL\", message: \"storage did not name an upload id\", status: 502 });\n\n let abortUrl: string | undefined;\n try {\n const etags: { part_number: number; etag: string }[] = [];\n let uploaded = 0;\n let next = 1;\n let completeUrl = \"\";\n while (next <= begun.parts) {\n const signed = await this.multipartUrls({ id: begun.id, upload_id: uploadId, from: next, count: begun.parts - next + 1 });\n abortUrl = signed.abort_url;\n completeUrl = signed.complete_url;\n // A window that signs nothing would spin here forever, which reads as a hang rather\n // than a failure.\n if (!signed.part_urls.length || signed.part_urls[0]!.part_number !== next) {\n throw new AltEngineError({\n code: \"INTERNAL\",\n message: `asked for part ${next} and was signed none`,\n status: 502,\n });\n }\n for (const part of signed.part_urls) {\n if (part.part_number > begun.parts) break;\n const start = (part.part_number - 1) * begun.part_size;\n const chunk = file.slice(start, Math.min(start + begun.part_size, file.size));\n const res = await this.http.transfer(part.url, { method: \"PUT\", body: chunk, signal: opts.signal });\n const etag = res.headers.get(\"etag\");\n // Without it the completion cannot name the part. In a browser this is the CORS\n // configuration talking, not the upload: ETag has to be an exposed header.\n if (!etag) {\n throw new AltEngineError({\n code: \"INTERNAL\",\n message: `storage returned no ETag for part ${part.part_number}; it must be an exposed response header`,\n status: 502,\n });\n }\n etags.push({ part_number: part.part_number, etag });\n uploaded += chunk.size;\n opts.onProgress?.({ uploaded, total: file.size });\n next = part.part_number + 1;\n }\n }\n\n await this.http.transfer(completeUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/xml\" },\n body: completeXml(etags),\n signal: opts.signal,\n });\n } catch (err) {\n // An abort URL only exists once a window has been signed, so a failure before the first\n // one has to go and ask for it — otherwise an upload that failed early is an upload\n // nothing ever aborts.\n const url = abortUrl ?? (await this.multipartUrls({ id: begun.id, upload_id: uploadId, from: 1, count: 1 })\n .then((u) => u.abort_url)\n .catch(() => undefined));\n // Best effort, and it must not replace the real error: the caller needs to know why the\n // upload failed, not why the tidy-up did.\n if (url) await this.http.transfer(url, { method: \"DELETE\" }).catch(() => undefined);\n throw err;\n }\n return this.read(begun.id);\n }\n\n /** The finished record. A read, so it needs no grant an upload did not already have —\n * `write` outranks `read`. */\n private async read(id: string): Promise<BlobRecord> {\n return (await this.get(id)).blob;\n }\n}\n\n/**\n * The blob client for the store a container job was handed, built from the two variables the\n * platform puts in every job an instance with a `blobStore` launches: `AE_BLOB_URL` (the store's\n * own endpoint) and `AE_BLOB_TOKEN` (a bearer that expires with the job).\n *\n * That token is scoped to one store and one job, at `write`. So it puts and gets; it does not\n * delete, does not `list` the store, and does not publish. Each of those comes back as a 403\n * naming what was refused.\n */\nexport function blobFromJobEnv(opts: Omit<ClientOptions, \"baseUrl\" | \"apiKey\" | \"auth\"> = {}): BlobClient {\n const url = typeof process !== \"undefined\" ? process.env?.AE_BLOB_URL : undefined;\n const token = typeof process !== \"undefined\" ? process.env?.AE_BLOB_TOKEN : undefined;\n if (!url || !token) {\n throw new AltEngineError({\n code: \"FAILED_PRECONDITION\",\n message:\n \"AE_BLOB_URL and AE_BLOB_TOKEN are not set — this is not a container job, or its instance names no blobStore\",\n status: 400,\n });\n }\n const m = /^(.*)\\/v1\\/blob\\/([^/]+)\\/*$/.exec(url);\n if (!m) {\n throw new AltEngineError({ code: \"INVALID_ARGUMENT\", message: `AE_BLOB_URL is not a blob endpoint: ${url}`, status: 400 });\n }\n return new BlobClient(new Http({ ...opts, baseUrl: m[1]!, apiKey: token }), decodeURIComponent(m[2]!));\n}\n\n/** The completion document: which parts, in which order, and the digest storage gave each. */\nfunction completeXml(parts: { part_number: number; etag: string }[]): string {\n const body = [...parts]\n .sort((a, b) => a.part_number - b.part_number)\n // The ETag travels verbatim, quotes included, because that is the form storage compares\n // against. Anything that could break the document out of its element is dropped.\n .map((p) => `<Part><PartNumber>${p.part_number}</PartNumber><ETag>${p.etag.replace(/[<>&]/g, \"\")}</ETag></Part>`)\n .join(\"\");\n return `<CompleteMultipartUpload>${body}</CompleteMultipartUpload>`;\n}\n\n/** Structural, not `instanceof`: a `File` from one realm is not a `Blob` from another, and\n * Node has had two `Blob` constructors at once. `size` plus `slice` is what this needs. */\nconst isBlob = (v: unknown): v is Blob =>\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as Blob).size === \"number\" &&\n typeof (v as Blob).slice === \"function\";\n\nconst blobType = (content: unknown): string | undefined =>\n isBlob(content) && content.type ? content.type : undefined;\n\n/** Whatever the caller passed, as something with a known byte length. */\nfunction toBody(content: string | ArrayBuffer | ArrayBufferView | Blob): Blob | Uint8Array {\n if (typeof content === \"string\") return new TextEncoder().encode(content);\n if (isBlob(content)) return content;\n if (content instanceof ArrayBuffer) return new Uint8Array(content);\n if (ArrayBuffer.isView(content)) return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);\n throw new AltEngineError({\n code: \"INVALID_ARGUMENT\",\n message: \"content must be a string, an ArrayBuffer, a typed array, or a Blob\",\n status: 400,\n });\n}\n","import { Http, seg } from \"../http.js\";\nimport { sleep } from \"../poll.js\";\nimport type {\n ContainerSizes,\n Job,\n JobListQuery,\n JobLogPage,\n JobPage,\n LaunchRequest,\n} from \"./types.js\";\n\n/** How long `wait` sleeps between polls, and the ceiling it backs off to. A job runs for\n * minutes or hours, so polling fast buys nothing and costs a request every time. */\nconst POLL_START_MS = 2_000;\nconst POLL_MAX_MS = 15_000;\n\nconst TERMINAL = new Set<string>([\"done\", \"failed\", \"canceled\"]);\n\n/**\n * Server-side client for one container instance — a Docker image run as a background job, for\n * the work that will not fit in a function.\n *\n * ORGANIZATION API KEY ONLY. End-user identity tokens are refused by this service, as they are\n * by automation: access rules bound what a user may READ, not what they may SPEND. Have a page\n * call a function that decides.\n *\n * A job's OUTPUT does not come back through here. It writes what it produces to blob — name a\n * `blobStore` on the instance and every job gets `AE_BLOB_URL` and `AE_BLOB_TOKEN` — or it calls\n * a function when it finishes.\n */\nexport class ContainerClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/container/${seg(instance)}`;\n }\n\n /**\n * Start a job and return as soon as its machine exists.\n *\n * There is nothing to await: a job that runs for twenty minutes has nowhere to send twenty\n * minutes of output. Poll with `wait`, or have the instance call a function when it ends.\n */\n async run(req: LaunchRequest): Promise<Job> {\n const { job } = await this.http.request<{ job: Job }>(\"POST\", this.base, {\n body: req,\n // A retried launch is a SECOND MACHINE, billed for its own runtime.\n retry: false,\n });\n return job;\n }\n\n /** One job: status, exit code, how long it ran, what it cost. */\n async get(jobId: string): Promise<Job> {\n const { job } = await this.http.request<{ job: Job }>(\"GET\", `${this.base}/${seg(jobId)}`);\n return job;\n }\n\n /**\n * One page of jobs, newest first.\n *\n * PAGED, and the cursor matters. Note the shape: the response's `cursor` is fed back as\n * `before` — it is the `started_at` of the last job on the page.\n */\n async list(query: JobListQuery = {}): Promise<JobPage> {\n return this.http.request(\"GET\", this.base, { query });\n }\n\n /** Every job matching the query, walking the pages for you. */\n async *listAll(query: Omit<JobListQuery, \"before\"> = {}): AsyncGenerator<Job> {\n let before: number | undefined;\n for (;;) {\n const page = await this.list({ ...query, before });\n for (const j of page.jobs) yield j;\n if (page.cursor == null) return;\n before = page.cursor;\n }\n }\n\n /**\n * Stop a running job and destroy its machine now. It is billed for the time it ran.\n *\n * `canceled: false` means the job had already finished, which is not a failure.\n */\n async cancel(jobId: string): Promise<{ job: Job; canceled: boolean }> {\n return this.http.request(\"POST\", `${this.base}/${seg(jobId)}/cancel`, { retry: false });\n }\n\n /**\n * What the job printed, oldest first.\n *\n * BEST EFFORT: an unavailable log service returns an empty page with a `note` rather than\n * throwing, and a job's own record — exit code, timing, cost — never depends on it. Logs are\n * kept for about a week after the machine is destroyed.\n */\n async logs(jobId: string, query: { cursor?: string | number } = {}): Promise<JobLogPage> {\n return this.http.request(\"GET\", `${this.base}/${seg(jobId)}/logs`, { query });\n }\n\n /** What this instance will accept: the sizes, the image allowlist, and the two ceilings. */\n async sizes(): Promise<ContainerSizes> {\n return this.http.request(\"GET\", `${this.base}/sizes`);\n }\n\n /**\n * Poll until a job reaches a terminal status.\n *\n * `timeoutMs` bounds the WAIT, not the job: giving up here leaves the machine running and\n * billing. Call `cancel` if that is what you meant. Zero (the default) waits indefinitely.\n */\n async wait(\n jobId: string,\n opts: { timeoutMs?: number; signal?: AbortSignal; onPoll?: (job: Job) => void } = {}\n ): Promise<Job> {\n const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : 0;\n let delay = POLL_START_MS;\n for (;;) {\n const job = await this.get(jobId);\n opts.onPoll?.(job);\n if (TERMINAL.has(job.status)) return job;\n if (deadline && Date.now() >= deadline) {\n throw new Error(\n `job ${jobId} was still ${job.status} after ${opts.timeoutMs}ms — its machine is still running and still billing; cancel it if that is not what you want`\n );\n }\n let ms = delay;\n if (deadline) ms = Math.min(ms, Math.max(0, deadline - Date.now()));\n await sleep(ms, opts.signal);\n delay = Math.min(delay * 2, POLL_MAX_MS);\n }\n }\n\n /** Start a job and wait for it. Convenience over `run` + `wait`. */\n async runAndWait(\n req: LaunchRequest,\n opts: { timeoutMs?: number; signal?: AbortSignal; onPoll?: (job: Job) => void } = {}\n ): Promise<Job> {\n const started = await this.run(req);\n return this.wait(started.id, opts);\n }\n}\n","import { Http, seg } from \"../http.js\";\nimport type {\n AddressPage,\n AddressRecord,\n AddressWithFull,\n AttachmentContent,\n AttachmentLink,\n CreateAddressRequest,\n DownloadLink,\n MailboxInfo,\n MailMessage,\n MessageListQuery,\n MessagePage,\n MessageSummary,\n OutgoingAttachment,\n ReplyRequest,\n SendRequest,\n WaitQuery,\n WaitResult,\n} from \"./types.js\";\n\n/** The longest the server holds a `wait`. */\nexport const MAX_WAIT_SECONDS = 60;\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(s);\n}\n\n/** Attachment content as the API takes it: a string is already base64; bytes are encoded. */\nexport async function attachmentBase64(content: AttachmentContent): Promise<string> {\n if (typeof content === \"string\") return content;\n if (content instanceof Uint8Array) return bytesToBase64(content);\n if (content instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(content));\n if (ArrayBuffer.isView(content)) return bytesToBase64(new Uint8Array(content.buffer, content.byteOffset, content.byteLength));\n if (typeof Blob !== \"undefined\" && content instanceof Blob) return bytesToBase64(new Uint8Array(await content.arrayBuffer()));\n throw new TypeError(\"attachment content must be base64 text, a Uint8Array, an ArrayBuffer or a Blob\");\n}\n\nasync function encodeAttachments(list: OutgoingAttachment[] | undefined) {\n if (!list) return undefined;\n return Promise.all(list.map(async (a) => ({ ...a, content: await attachmentBase64(a.content) })));\n}\n\n/**\n * Server-side client for one mailbox instance — email addresses an app or agent owns.\n *\n * ORGANIZATION API KEY ONLY: a mailbox holds third parties' mail and can send as you, so\n * end-user identity tokens are refused.\n *\n * Every name works: `<slug>.<anything>@<domain>` receives mail with no call needed, unless the\n * instance accepts registered names only. Every message expires after the mailbox's retention;\n * `keep` moves one message's date.\n */\nexport class MailboxClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n /** Names that carry a setting: registered, labelled or disabled. */\n readonly addresses: {\n /** One page, in name order. */\n list(query?: { cursor?: string; limit?: number }): Promise<AddressPage>;\n /** Register (and optionally label) a name; omit `local` to have an unguessable one minted. */\n create(req?: CreateAddressRequest): Promise<AddressWithFull>;\n /** Refuse the name's mail and stop it sending. Its messages stay. */\n disable(local: string): Promise<AddressRecord>;\n };\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/mailbox/${seg(instance)}`;\n this.addresses = {\n list: (query = {}) => this.http.request(\"GET\", `${this.base}/addresses`, { query }),\n create: (req = {}) => this.http.request(\"POST\", `${this.base}/addresses`, { body: req }),\n disable: (local) => this.http.request(\"DELETE\", `${this.base}/addresses/${seg(local)}`),\n };\n }\n\n /** The main address, the pattern of every other one, and the settings a caller needs. */\n async info(): Promise<MailboxInfo> {\n return this.http.request(\"GET\", this.base);\n }\n\n /** One page of messages, newest first, without bodies. */\n async list(query: MessageListQuery = {}): Promise<MessagePage> {\n const { unread, ...rest } = query;\n return this.http.request(\"GET\", `${this.base}/messages`, { query: { ...rest, unread: unread ? \"1\" : undefined } });\n }\n\n /**\n * Wait for the next inbound mail after `after`, holding the request up to `timeoutSeconds`\n * (at most 60; the server checks every 5 s). Empty on timeout — call again with the returned `cursor` to keep waiting.\n *\n * Pass `after: \"now\"` BEFORE handing an address to whoever will mail it, so older mail is not\n * mistaken for the new one.\n */\n async wait(query: WaitQuery): Promise<WaitResult> {\n const secs = Math.min(Math.max(query.timeoutSeconds ?? MAX_WAIT_SECONDS, 0), MAX_WAIT_SECONDS);\n return this.http.request(\"GET\", `${this.base}/messages`, {\n query: { after: query.after, to: query.to, limit: query.limit, wait: secs },\n // The server holds the request; give it that long and some.\n timeoutMs: secs * 1000 + 15_000,\n });\n }\n\n /** One message with its bodies and attachment list. */\n async get(id: string): Promise<MailMessage> {\n const { message } = await this.http.request<{ message: MailMessage }>(\"GET\", `${this.base}/messages/${seg(id)}`);\n return message;\n }\n\n /** A short-lived link to the raw .eml. Fails when the mailbox does not keep raw messages. */\n async raw(id: string): Promise<DownloadLink> {\n const r = await this.http.request<{ rawUrl: string; expiresAt: number }>(\"GET\", `${this.base}/messages/${seg(id)}`, {\n query: { raw: \"1\" },\n });\n return { url: r.rawUrl, expiresAt: r.expiresAt };\n }\n\n /** A short-lived download link for one attachment. The URL is the credential: no key needed. */\n async attachment(id: string, idx: number): Promise<AttachmentLink> {\n return this.http.request(\"GET\", `${this.base}/messages/${seg(id)}/attachments/${seg(idx)}`);\n }\n\n /** Mark a received message read. */\n async markRead(id: string): Promise<{ ok: true }> {\n return this.http.request(\"POST\", `${this.base}/messages/${seg(id)}/read`);\n }\n\n /**\n * Send a new message from a name on this mailbox. Refused when the send mode is `off`, and in\n * `reply` mode unless every recipient has written to this mailbox in authenticated mail.\n * Never retried: a retried send is a second email.\n */\n async send(req: SendRequest): Promise<MessageSummary> {\n const body = { ...req, attachments: await encodeAttachments(req.attachments) };\n const { message } = await this.http.request<{ message: MessageSummary }>(\"POST\", `${this.base}/send`, {\n body,\n retry: false,\n });\n return message;\n }\n\n /** Reply to a received message, threaded: to its Reply-To (or From), from the name it was\n * sent to, with `Re: <subject>` — unless you pass those. Same limits as `send`. */\n async reply(id: string, req: ReplyRequest = {}): Promise<MessageSummary> {\n const body = { ...req, attachments: await encodeAttachments(req.attachments) };\n const { message } = await this.http.request<{ message: MessageSummary }>(\"POST\", `${this.base}/messages/${seg(id)}/reply`, {\n body,\n retry: false,\n });\n return message;\n }\n\n /**\n * Keep one message until `days` (1–90) from now, overriding the mailbox's retention for it\n * alone. Extending needs `write`; an earlier date deletes the message sooner, so that needs\n * `full`.\n */\n async keep(id: string, days: number): Promise<MessageSummary> {\n const { message } = await this.http.request<{ message: MessageSummary }>(\"POST\", `${this.base}/messages/${seg(id)}/keep`, {\n body: { days },\n });\n return message;\n }\n\n /** Delete a message and its attachments now. Needs `full`. */\n async delete(id: string): Promise<{ deleted: number }> {\n return this.http.request(\"DELETE\", `${this.base}/messages/${seg(id)}`);\n }\n}\n","import { Http, seg } from \"../http.js\";\nimport type {\n AddResult,\n CancelResult,\n LeasedTask,\n LeaseOptions,\n QueueInfo,\n QueueSettingsPatch,\n ReleaseOptions,\n TaskInput,\n TaskListQuery,\n TaskPage,\n TaskRecord,\n TaskSummary,\n TasksInfo,\n} from \"./types.js\";\n\n/** Response headers a push target may answer with to steer its own retries (when the queue's\n * `targetControl` is on, the default). */\nexport const TASK_RETRY_HEADER = \"x-task-retry\";\nexport const TASK_RETRY_AFTER_HEADER = \"x-task-retry-after\";\nexport const TASK_MAX_ATTEMPTS_HEADER = \"x-task-max-attempts\";\n\nfunction wireTask(t: TaskInput): Record<string, unknown> {\n const { runAt, ...rest } = t;\n return runAt instanceof Date ? { ...rest, runAt: runAt.getTime() } : runAt === undefined ? rest : { ...rest, runAt };\n}\n\n/**\n * Server-side client for one tasks instance — queues of work.\n *\n * A push queue delivers each task to a function, a channel or a signed webhook and retries it\n * with backoff until it is accepted; a pull queue holds tasks for workers to `lease` and `ack`.\n * Delivery is at least once: handle a task idempotently on its id.\n *\n * ORGANIZATION API KEY ONLY: a task runs its target with the target's own grants, so end-user\n * identity tokens are refused.\n */\nexport class TasksClient {\n readonly instance: string;\n private readonly http: Http;\n private readonly base: string;\n\n constructor(http: Http, instance: string) {\n this.http = http;\n this.instance = instance;\n this.base = `/v1/tasks/${seg(instance)}`;\n }\n\n /** The instance's retention and its queues. */\n async info(): Promise<TasksInfo> {\n return this.http.request(\"GET\", this.base);\n }\n\n // --- queues ---------------------------------------------------------------\n\n /** Every queue, with its settings and counts by state. */\n async queues(): Promise<QueueInfo[]> {\n const { queues } = await this.http.request<{ queues: QueueInfo[] }>(\"GET\", `${this.base}/queues`);\n return queues;\n }\n\n async queue(name: string): Promise<QueueInfo> {\n const { queue } = await this.http.request<{ queue: QueueInfo }>(\"GET\", `${this.base}/queues/${seg(name)}`);\n return queue;\n }\n\n /** Create a queue. Settings left out take their defaults. Needs `full`. */\n async createQueue(name: string, settings: QueueSettingsPatch = {}): Promise<QueueInfo> {\n const { queue } = await this.http.request<{ queue: QueueInfo }>(\"POST\", `${this.base}/queues`, {\n body: { ...settings, name },\n });\n return queue;\n }\n\n /** Change a queue: only the settings given change. Needs `full`. */\n async updateQueue(name: string, settings: QueueSettingsPatch): Promise<QueueInfo> {\n const { queue } = await this.http.request<{ queue: QueueInfo }>(\"PATCH\", `${this.base}/queues/${seg(name)}`, {\n body: settings,\n });\n return queue;\n }\n\n /** Stop delivering a queue's tasks; nothing is lost. Needs `full`. */\n async pauseQueue(name: string): Promise<QueueInfo> {\n const { queue } = await this.http.request<{ queue: QueueInfo }>(\"POST\", `${this.base}/queues/${seg(name)}/pause`);\n return queue;\n }\n\n async resumeQueue(name: string): Promise<QueueInfo> {\n const { queue } = await this.http.request<{ queue: QueueInfo }>(\"POST\", `${this.base}/queues/${seg(name)}/resume`);\n return queue;\n }\n\n /** Delete every task in a queue, in any state. Needs `full`. */\n async purgeQueue(name: string): Promise<{ purged: number; pending: boolean }> {\n return this.http.request(\"POST\", `${this.base}/queues/${seg(name)}/purge`);\n }\n\n /** Delete a queue and every task in it. `default` cannot be deleted. Needs `full`. */\n async deleteQueue(name: string): Promise<{ deleted: boolean; pending: boolean }> {\n return this.http.request(\"DELETE\", `${this.base}/queues/${seg(name)}`);\n }\n\n // --- tasks ----------------------------------------------------------------\n\n /**\n * Add one task, or up to 100, to a queue. Each result says whether it was added or its name\n * was already taken — a name already used is a result, not a throw, so a producer that retries\n * with the same name is idempotent.\n *\n * Retried on a transient failure only when every task is named: an unnamed task sent twice is\n * two tasks.\n */\n async add<P = unknown>(queue: string, tasks: TaskInput<P> | TaskInput<P>[]): Promise<AddResult[]> {\n const list = Array.isArray(tasks) ? tasks : [tasks];\n const res = await this.http.request<{ tasks: AddResult[] }>(\"POST\", `${this.base}/queues/${seg(queue)}/tasks`, {\n body: { tasks: list.map(wireTask) },\n retry: list.every((t) => !!t.name) ? undefined : false,\n // Every name already taken is a 409 whose body is still the per-task answer.\n acceptStatus: [409],\n });\n return res.tasks;\n }\n\n /** One page of a queue's tasks, without payloads. */\n async list(queue: string, query: TaskListQuery = {}): Promise<TaskPage> {\n return this.http.request(\"GET\", `${this.base}/queues/${seg(queue)}/tasks`, { query: { ...query } });\n }\n\n /** Every task in a queue (narrowed by `query`), page by page. */\n async *listAll(queue: string, query: Omit<TaskListQuery, \"cursor\"> = {}): AsyncGenerator<TaskSummary> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.list(queue, { ...query, cursor });\n for (const t of page.tasks) yield t;\n if (!page.cursor) return;\n cursor = page.cursor;\n }\n }\n\n /** One task, with its payload, every attempt and the target's answer. */\n async get<P = unknown>(id: string): Promise<TaskRecord<P>> {\n const { task } = await this.http.request<{ task: TaskRecord<P> }>(\"GET\", `${this.base}/tasks/${seg(id)}`);\n return task;\n }\n\n /** Cancel scheduled or leased tasks (up to 200). A running task cannot be stopped. */\n async cancel(ids: string | string[]): Promise<CancelResult> {\n return this.http.request(\"POST\", `${this.base}/tasks/cancel`, { body: { ids: Array.isArray(ids) ? ids : [ids] } });\n }\n\n /**\n * Run a task now: a scheduled one is moved up, a failed or cancelled one is retried with its\n * attempts reset, and a finished one is run again as a NEW task with the same payload.\n */\n async run<P = unknown>(id: string): Promise<TaskRecord<P>> {\n const { task } = await this.http.request<{ task: TaskRecord<P> }>(\"POST\", `${this.base}/tasks/${seg(id)}/run`, { retry: false });\n return task;\n }\n\n // --- pull queues ----------------------------------------------------------\n\n /**\n * Lease up to `count` due tasks from a pull queue. Finish each with `ack`, or give it back with\n * `release`; a lease that runs out puts the task back with its attempt counted as failed.\n * Never retried: a retried lease would hold tasks nobody is working on.\n */\n async lease<P = unknown>(queue: string, opts: LeaseOptions = {}): Promise<LeasedTask<P>[]> {\n const { tasks } = await this.http.request<{ tasks: LeasedTask<P>[] }>(\"POST\", `${this.base}/queues/${seg(queue)}/lease`, {\n body: opts,\n retry: false,\n });\n return tasks;\n }\n\n /** Finish a leased task, with an optional result (a string, or JSON) kept up to 16 KB. */\n async ack<P = unknown>(id: string, leaseId: string, result?: unknown): Promise<TaskRecord<P>> {\n const { task } = await this.http.request<{ task: TaskRecord<P> }>(\"POST\", `${this.base}/tasks/${seg(id)}/ack`, {\n body: { leaseId, result: result ?? null },\n });\n return task;\n }\n\n /** Hold a lease longer: `leaseSeconds` (1–3600, default 300) from now. */\n async extend<P = unknown>(id: string, leaseId: string, leaseSeconds?: number): Promise<TaskRecord<P>> {\n const { task } = await this.http.request<{ task: TaskRecord<P> }>(\"POST\", `${this.base}/tasks/${seg(id)}/extend`, {\n body: { leaseId, leaseSeconds },\n });\n return task;\n }\n\n /** Give a leased task back, to be leased again after `delaySeconds`. The attempt counts as\n * failed; on the last attempt the task fails instead. */\n async release<P = unknown>(id: string, leaseId: string, opts: ReleaseOptions = {}): Promise<TaskRecord<P>> {\n const { task } = await this.http.request<{ task: TaskRecord<P> }>(\"POST\", `${this.base}/tasks/${seg(id)}/release`, {\n body: { leaseId, ...opts },\n });\n return task;\n }\n}\n","import type { FacetType, GeoPoint, SearchFacet, SearchField } from \"./types.js\";\n\n/** Field builders — `f.text(\"title\", \"Blue Shoes\")` reads better than object\n * literals and pins the right `type` string. */\nexport const f = {\n text: (name: string, value: string, language?: string): SearchField =>\n mk(name, \"text\", value, language),\n html: (name: string, value: string, language?: string): SearchField =>\n mk(name, \"html\", value, language),\n atom: (name: string, value: string): SearchField => mk(name, \"atom\", value),\n number: (name: string, value: number): SearchField => mk(name, \"number\", value),\n /** Accepts a Date, ISO string, or epoch milliseconds. */\n date: (name: string, value: Date | string | number): SearchField =>\n mk(name, \"date\", value instanceof Date ? value.toISOString() : value),\n geo: (name: string, value: GeoPoint): SearchField => mk(name, \"geo\", value),\n tokenprefix: (name: string, value: string): SearchField => mk(name, \"tokenprefix\", value),\n untokenprefix: (name: string, value: string): SearchField => mk(name, \"untokenprefix\", value),\n};\n\n/** Facet builders for document facets. */\nexport const facet = {\n atom: (name: string, value: string): SearchFacet => ({ name, type: \"atom\" as FacetType, value }),\n number: (name: string, value: number): SearchFacet => ({ name, type: \"number\" as FacetType, value }),\n};\n\nfunction mk(name: string, type: SearchField[\"type\"], value: unknown, language?: string): SearchField {\n const field: SearchField = { name, type, value };\n if (language !== undefined) field.language = language;\n return field;\n}\n","/** Verifying an automation completion webhook.\n *\n * Every webhook carries two headers:\n *\n * - `x-altengine-timestamp` — when it was sent, in milliseconds since the epoch.\n * - `x-altengine-signature` — `v1=<hex>`, an HMAC-SHA256 of `<timestamp>.<raw body>` keyed with\n * the instance's whole webhook signing secret, `whsec_` prefix included.\n *\n * Uses Web Crypto, so it runs the same on Node 20+, in a browser, and in any edge runtime. */\n\nexport const WEBHOOK_SIGNATURE_HEADER = \"x-altengine-signature\";\nexport const WEBHOOK_TIMESTAMP_HEADER = \"x-altengine-timestamp\";\n\n/** How far the timestamp may be from now, either way, by default: five minutes. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1000;\n\nexport interface VerifyWebhookOptions {\n /** The instance's webhook signing secret, `whsec_…`, as the console or MCP shows it. */\n secret: string;\n /** The body exactly as received — NOT a re-serialised parse, which signs different bytes. */\n body: string | Uint8Array | ArrayBuffer;\n /** The `x-altengine-signature` header. */\n signature: string | null | undefined;\n /** The `x-altengine-timestamp` header. */\n timestamp: string | number | null | undefined;\n /** Reject a timestamp further than this from now, either way. Default five minutes. */\n toleranceMs?: number;\n /** The current time in ms. For tests; defaults to `Date.now()`. */\n now?: number;\n}\n\nconst enc = new TextEncoder();\n\nfunction bytesOf(body: string | Uint8Array | ArrayBuffer): Uint8Array {\n if (typeof body === \"string\") return enc.encode(body);\n return body instanceof Uint8Array ? body : new Uint8Array(body);\n}\n\nfunction hex(buf: ArrayBuffer): string {\n let s = \"\";\n for (const b of new Uint8Array(buf)) s += b.toString(16).padStart(2, \"0\");\n return s;\n}\n\n/** Compares every byte whatever the first mismatch, so timing does not reveal how much matched. */\nfunction constantTimeEqual(a: string, b: string): boolean {\n const x = enc.encode(a);\n const y = enc.encode(b);\n if (x.length !== y.length) return false;\n let diff = 0;\n for (let i = 0; i < x.length; i++) diff |= x[i]! ^ y[i]!;\n return diff === 0;\n}\n\n/**\n * True when the webhook was signed with `secret` and its timestamp is within `toleranceMs` of now.\n *\n * ```ts\n * import { verifyWebhook } from \"@altenginenet/sdk\";\n *\n * const ok = await verifyWebhook({\n * secret: process.env.ALTENGINE_WEBHOOK_SECRET!,\n * body: await request.text(),\n * signature: request.headers.get(\"x-altengine-signature\"),\n * timestamp: request.headers.get(\"x-altengine-timestamp\"),\n * });\n * if (!ok) return new Response(\"bad signature\", { status: 401 });\n * ```\n *\n * Each delivery attempt is signed afresh, so a retry carries a new timestamp: deduplicate on\n * `run.id`, not on the signature.\n */\nexport async function verifyWebhook(opts: VerifyWebhookOptions): Promise<boolean> {\n const { secret, signature } = opts;\n if (!secret || !signature) return false;\n const ts = opts.timestamp == null ? \"\" : String(opts.timestamp).trim();\n // Digits only: the timestamp is signed as the header's own text, and Number() would accept\n // \"1e12\" or \"0x1f\" as a time while the signed string differs.\n if (!/^\\d+$/.test(ts)) return false;\n const tolerance = opts.toleranceMs ?? DEFAULT_WEBHOOK_TOLERANCE_MS;\n const now = opts.now ?? Date.now();\n if (!(Math.abs(now - Number(ts)) <= tolerance)) return false;\n\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n ]);\n const prefix = enc.encode(`${ts}.`);\n const body = bytesOf(opts.body);\n const signed = new Uint8Array(prefix.length + body.length);\n signed.set(prefix, 0);\n signed.set(body, prefix.length);\n const expected = `v1=${hex(await crypto.subtle.sign(\"HMAC\", key, signed))}`;\n return constantTimeEqual(signature.trim(), expected);\n}\n","/** ChannelSocket — the browser/edge WebSocket subscriber for altengine channels.\n *\n * Standalone and browser-safe: no API keys, no other SDK imports. Your backend\n * mints a subscriber token (`ChannelClient.createToken`) and hands the response\n * (`{token, ws_endpoint, protocols}`) to the page; the socket does the rest — connect, auto-reconnect with backoff,\n * token re-mint on reconnect, resubscribe, and keepalive pings.\n */\n\nimport type { ChannelMessage } from \"./types.js\";\n\nexport type SocketState = \"idle\" | \"connecting\" | \"open\" | \"reconnecting\" | \"closed\";\n\nexport interface SocketToken {\n token: string;\n /** Subscribe URL without the token, from the token response. */\n ws_endpoint?: string;\n /** Subprotocols that carry the token, from the token response. */\n protocols?: string[];\n /** @deprecated The subscribe URL with the token in its query string. Used only when the\n * response has no `ws_endpoint` (an older server). */\n ws_url?: string;\n}\n\n/** The subprotocol offered alongside the token, and the one the server answers with. */\nconst WS_PROTOCOL = \"altengine.v1\";\nconst WS_TOKEN_PROTOCOL_PREFIX = \"altengine.token.\";\n\nexport interface ChannelSocketOptions {\n /** Called before every connection attempt (including reconnects) so tokens are\n * always fresh. Return the token-mint response (or `{token}` with `url` set). */\n getToken: () => Promise<SocketToken> | SocketToken;\n /** Explicit subscribe URL (`wss://…/v1/channel/<instance>/subscribe`) when the token\n * response has no `ws_endpoint`. The token is sent as a subprotocol, not in the URL. */\n url?: string;\n /** Subset of the token's channels to subscribe on connect (default: all). */\n channels?: string[];\n /** WebSocket constructor for runtimes without a global one. */\n webSocket?: new (url: string, protocols?: string | string[]) => WebSocket;\n /** Keepalive ping interval in ms (default 30000, at most 60000). A silent\n * connection past ~1.5 intervals is treated as dead and reconnected. */\n pingIntervalMs?: number;\n /** Reconnect backoff base/cap in ms (defaults 250 / 30000). */\n backoffBaseMs?: number;\n backoffMaxMs?: number;\n}\n\nexport interface SocketEvents {\n message: ChannelMessage;\n state: SocketState;\n error: Error;\n /** Channels the server would not subscribe this socket to — on open or on a subscribe() —\n * because a channel or user limit was reached. They stay requested and are tried again on\n * the next reconnect. */\n refused: string[];\n}\n\ntype Listener<T> = (payload: T) => void;\n\n// readyState values, spelled out rather than read off the global `WebSocket`: Node 20 has no\n// global one (that is what the `webSocket` option is for), and `WebSocket.OPEN` there is a\n// ReferenceError the first time a connected socket is checked.\nconst CONNECTING = 0;\nconst OPEN = 1;\n\nexport class ChannelSocket {\n private readonly opts: ChannelSocketOptions;\n private readonly listeners: { [K in keyof SocketEvents]: Set<Listener<SocketEvents[K]>> } = {\n message: new Set(),\n state: new Set(),\n error: new Set(),\n refused: new Set(),\n };\n\n private ws?: WebSocket;\n private stateValue: SocketState = \"idle\";\n private desired = new Set<string>();\n private explicitChannels: boolean;\n private closedByUser = false;\n private attempts = 0;\n private pingTimer?: ReturnType<typeof setInterval>;\n private lastActivity = 0;\n private reconnectTimer?: ReturnType<typeof setTimeout>;\n private pendingSubscribes: { channels: string[]; resolve: (channels: string[]) => void; reject: (e: Error) => void }[] = [];\n private pendingPublishes: { resolve: (delivered: number) => void; reject: (e: Error) => void }[] = [];\n\n constructor(opts: ChannelSocketOptions) {\n this.opts = opts;\n this.explicitChannels = opts.channels !== undefined;\n for (const c of opts.channels ?? []) this.desired.add(c);\n }\n\n get state(): SocketState {\n return this.stateValue;\n }\n\n on<K extends keyof SocketEvents>(event: K, fn: Listener<SocketEvents[K]>): () => void {\n this.listeners[event].add(fn);\n return () => this.listeners[event].delete(fn);\n }\n\n private emit<K extends keyof SocketEvents>(event: K, payload: SocketEvents[K]): void {\n for (const fn of this.listeners[event]) fn(payload);\n }\n\n private setState(s: SocketState): void {\n if (this.stateValue === s) return;\n this.stateValue = s;\n this.emit(\"state\", s);\n }\n\n /** Connect (resolves once the socket is open). Reconnects automatically until\n * `close()` is called. */\n async connect(): Promise<void> {\n this.closedByUser = false;\n if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;\n await this.dial();\n }\n\n /** Stop reconnecting and close the connection. */\n close(): void {\n this.closedByUser = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.stopPing();\n this.failPending(new Error(\"socket closed\"));\n this.ws?.close(1000, \"client close\");\n this.ws = undefined;\n this.setState(\"closed\");\n }\n\n /** Subscribe to more channels (tracked and re-applied after reconnects).\n * Resolves with the server's ack. */\n async subscribe(channels: string[]): Promise<string[]> {\n for (const c of channels) this.desired.add(c);\n this.explicitChannels = true;\n if (!this.isOpen()) return [...this.desired];\n return new Promise<string[]>((resolve, reject) => {\n this.pendingSubscribes.push({ channels, resolve, reject });\n this.send({ type: \"subscribe\", channels });\n });\n }\n\n /** Unsubscribe from channels. */\n unsubscribe(channels: string[]): void {\n for (const c of channels) this.desired.delete(c);\n this.explicitChannels = true;\n if (this.isOpen()) this.send({ type: \"unsubscribe\", channels });\n }\n\n /** Publish over the socket (requires a ws-capable `publish` token). Resolves\n * with the delivered count from the server's ack. */\n async publish(channel: string, data: unknown): Promise<number> {\n if (!this.isOpen()) throw new Error(\"socket is not open\");\n return new Promise<number>((resolve, reject) => {\n this.pendingPublishes.push({ resolve, reject });\n this.send({ type: \"publish\", channel, data });\n });\n }\n\n // --- internals ---\n\n private isOpen(): boolean {\n return !!this.ws && this.ws.readyState === OPEN;\n }\n\n private send(frame: unknown): void {\n this.ws?.send(typeof frame === \"string\" ? frame : JSON.stringify(frame));\n }\n\n /** Where to dial, and with which subprotocols. The token travels as a subprotocol\n * (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an\n * older server whose response has only `ws_url`, which is opened as it is. */\n private target(tok: SocketToken): { url: string; protocols?: string[] } {\n const endpoint = tok.ws_endpoint ?? (tok.ws_url ? undefined : this.opts.url);\n let url: URL;\n let protocols: string[] | undefined;\n if (endpoint) {\n url = new URL(endpoint);\n protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];\n } else if (tok.ws_url) {\n url = new URL(tok.ws_url);\n if (!url.searchParams.has(\"token\")) url.searchParams.set(\"token\", tok.token);\n } else {\n throw new Error(\"no WebSocket URL: token response had no ws_endpoint and no url option was set\");\n }\n // Narrow the initial subscription to the explicitly requested subset.\n if (this.explicitChannels && this.desired.size) {\n url.searchParams.set(\"channels\", [...this.desired].join(\",\"));\n }\n return { url: url.toString(), protocols };\n }\n\n private async dial(): Promise<void> {\n this.setState(this.attempts === 0 ? \"connecting\" : \"reconnecting\");\n let tok: SocketToken;\n try {\n tok = await this.opts.getToken();\n } catch (err) {\n this.emit(\"error\", err instanceof Error ? err : new Error(String(err)));\n this.scheduleReconnect();\n return;\n }\n\n const WS = this.opts.webSocket ?? (globalThis.WebSocket as typeof WebSocket | undefined);\n if (!WS) throw new Error(\"no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)\");\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const { url, protocols } = this.target(tok);\n const ws = protocols ? new WS(url, protocols) : new WS(url);\n this.ws = ws;\n\n ws.onopen = () => {\n settled = true;\n this.attempts = 0;\n this.lastActivity = Date.now();\n this.setState(\"open\");\n this.startPing();\n resolve();\n };\n ws.onmessage = (ev: MessageEvent) => this.handleMessage(ev);\n ws.onerror = () => {\n // onclose always follows; error details aren't portable across runtimes.\n };\n ws.onclose = (ev: CloseEvent) => {\n this.stopPing();\n this.failPending(new Error(`socket closed (${ev.code})`));\n if (!settled) {\n settled = true;\n resolve();\n }\n if (!this.closedByUser) this.scheduleReconnect();\n };\n });\n }\n\n private handleMessage(ev: MessageEvent): void {\n this.lastActivity = Date.now();\n const raw = typeof ev.data === \"string\" ? ev.data : \"\";\n if (raw === \"pong\" || raw === \"ping\") return;\n let frame: any;\n try {\n frame = JSON.parse(raw);\n } catch {\n return;\n }\n switch (frame?.type) {\n case \"subscribed\": {\n // Only settle the oldest pending subscribe if this ack covers its channels —\n // an unsolicited ack (e.g. for the connect-time ?channels= subscription)\n // arriving late must not steal a runtime subscribe()'s resolution.\n // A refused channel is answered too, so it counts as covered; the promise resolves with\n // the channels actually admitted.\n const refused: string[] = Array.isArray(frame.refused) ? frame.refused : [];\n const head = this.pendingSubscribes[0];\n const acked = new Set<string>([...(frame.channels ?? []), ...refused]);\n if (head && head.channels.every((c) => acked.has(c))) {\n this.pendingSubscribes.shift()!.resolve(frame.channels ?? []);\n }\n if (refused.length) this.emit(\"refused\", refused);\n return;\n }\n case \"published\":\n this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);\n return;\n case \"error\": {\n const err = new Error(typeof frame.error === \"string\" ? frame.error : JSON.stringify(frame.error));\n // An error ack settles the oldest pending request, if any.\n (this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);\n this.emit(\"error\", err);\n return;\n }\n default:\n if (frame && typeof frame.channel === \"string\" && frame.type === undefined) {\n this.emit(\"message\", frame as ChannelMessage);\n }\n }\n }\n\n private startPing(): void {\n // The server closes (4408) a connection that pinged and then stops for 15 minutes.\n const interval = Math.min(this.opts.pingIntervalMs ?? 30_000, 60_000);\n this.stopPing();\n this.pingTimer = setInterval(() => {\n if (!this.isOpen()) return;\n if (Date.now() - this.lastActivity > interval * 1.5) {\n // Dead connection: no traffic (not even pongs). Force a reconnect.\n this.ws?.close(4000, \"keepalive timeout\");\n return;\n }\n this.send(\"ping\");\n }, interval);\n }\n\n private stopPing(): void {\n if (this.pingTimer) clearInterval(this.pingTimer);\n this.pingTimer = undefined;\n }\n\n private scheduleReconnect(): void {\n if (this.closedByUser) return;\n const base = this.opts.backoffBaseMs ?? 250;\n const cap = this.opts.backoffMaxMs ?? 30_000;\n const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);\n this.attempts++;\n this.setState(\"reconnecting\");\n this.reconnectTimer = setTimeout(() => void this.dial(), delay);\n }\n\n private failPending(err: Error): void {\n for (const p of this.pendingSubscribes.splice(0)) p.reject(err);\n for (const p of this.pendingPublishes.splice(0)) p.reject(err);\n }\n}\n\nexport type { ChannelMessage } from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAAoG;AAC9G,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AACjB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA,EAIA,IAAI,YAAqB;AACvB,QAAI,KAAK,WAAW,IAAK,QAAO;AAChC,WAAO,KAAK,WAAW,OAAO,KAAK,WAAW,OAAO,KAAK,WAAW;AA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