@oxy-hq/sdk 2.12.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +67 -0
  2. package/dist/{function-context-D8eyZuw_.d.cts → function-context-BNpL5bFb.d.cts} +223 -20
  3. package/dist/function-context-BNpL5bFb.d.cts.map +1 -0
  4. package/dist/{function-context-D8eyZuw_.d.mts → function-context-BNpL5bFb.d.mts} +223 -20
  5. package/dist/function-context-BNpL5bFb.d.mts.map +1 -0
  6. package/dist/index.cjs +80 -16
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +164 -3
  9. package/dist/index.d.cts.map +1 -1
  10. package/dist/index.d.mts +164 -3
  11. package/dist/index.d.mts.map +1 -1
  12. package/dist/index.mjs +78 -16
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/ops.d.cts +1 -1
  15. package/dist/ops.d.mts +1 -1
  16. package/dist/{react-DW7Z96sD.d.mts → react-CljeXJuw.d.cts} +142 -8
  17. package/dist/react-CljeXJuw.d.cts.map +1 -0
  18. package/dist/{react-DW7Z96sD.d.cts → react-CljeXJuw.d.mts} +142 -8
  19. package/dist/react-CljeXJuw.d.mts.map +1 -0
  20. package/dist/{react-DcT-mUPj.cjs → react-Dvkv2deI.cjs} +110 -59
  21. package/dist/react-Dvkv2deI.cjs.map +1 -0
  22. package/dist/{react-BXGyzgz0.mjs → react-OW1t_J0M.mjs} +103 -26
  23. package/dist/react-OW1t_J0M.mjs.map +1 -0
  24. package/dist/rolldown-runtime-KC0qvQup.cjs +34 -0
  25. package/dist/shell.cjs +38 -3
  26. package/dist/shell.cjs.map +1 -1
  27. package/dist/shell.d.cts +26 -3
  28. package/dist/shell.d.cts.map +1 -1
  29. package/dist/shell.d.mts +26 -3
  30. package/dist/shell.d.mts.map +1 -1
  31. package/dist/shell.mjs +34 -2
  32. package/dist/shell.mjs.map +1 -1
  33. package/dist/testing.cjs +4431 -0
  34. package/dist/testing.cjs.map +1 -0
  35. package/dist/testing.d.cts +656 -0
  36. package/dist/testing.d.cts.map +1 -0
  37. package/dist/testing.d.mts +656 -0
  38. package/dist/testing.d.mts.map +1 -0
  39. package/dist/testing.mjs +4395 -0
  40. package/dist/testing.mjs.map +1 -0
  41. package/package.json +22 -9
  42. package/dist/function-context-D8eyZuw_.d.cts.map +0 -1
  43. package/dist/function-context-D8eyZuw_.d.mts.map +0 -1
  44. package/dist/react-BXGyzgz0.mjs.map +0 -1
  45. package/dist/react-DW7Z96sD.d.cts.map +0 -1
  46. package/dist/react-DW7Z96sD.d.mts.map +0 -1
  47. package/dist/react-DcT-mUPj.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.cjs","names":["zooJson","nodeCryptoImport"],"sources":["../src/testing/host-contract.ts","../src/testing/fetch-rules.ts","../src/testing/host-error.ts","../src/testing/gates.ts","../src/testing/run.ts","../src/testing/sql.ts","../src/testing/shape-zoo.json","../src/testing/shape-zoo-sha256.ts","../src/testing/zoo.ts","../src/testing/stores.ts","../src/testing/context.ts"],"sourcesContent":["/**\n * The host's words, gates, op names and rules, as `@oxy-hq/sdk/testing`\n * enforces them on an app's unit tests.\n *\n * ONE SOURCE OF TRUTH, AND IT IS NOT THIS FILE. Every string below is quoted\n * from the host's source — `host.rs`, `host/destinations.rs`,\n * `host/airhouse_ops.rs`, `upsert_support.rs`, `tx.rs`, `runtime.rs` under\n * `crates/app/src/server/api/custom_apps_functions/`, and the connector's\n * `transaction.rs` / `postgres_tx/convert.rs` — never paraphrased.\n * `{placeholder}`s stand for what the host formats in (`{database}`,\n * `{dialect}`, …) and use the host's own names.\n *\n * HELD TO THE HOST BY A RUST TEST. `sdk_testing_drift.rs`, beside `host.rs`,\n * `include_str!`s this file and fails when a `refusal:` here is no longer a\n * sentence its `source:` file contains, when `HOST_OPS` differs from the\n * host's closed list, when `GATES` stops naming exactly the fields of\n * `FunctionCapabilities`, when `ABSENT_GLOBALS` differs from `oxyc`'s lint\n * list, or when `FETCH_RULES` differs from `is_safe_outbound`. One direction\n * only: this file is checked against the host, the host is never checked\n * against this file (`internal-docs/sdk-testing-context.md` §7, answer 9).\n *\n * THE RUST TEST READS TEXT, NOT TYPESCRIPT: after stripping comments it takes\n * the block from `export const HOST_OPS` to `] as const;`, every object whose\n * key line ends `: {` and carries `source:` and `refusal:` lines, the\n * `hostField:` / `ops:` lines of `GATES`, the `name:` / `member:` lines of\n * `ABSENT_GLOBALS`, and every quoted string in `FETCH_RULES`. Keep those keys\n * spelled as they are, each `refusal:` a single string literal, and none of\n * them behind a comment that is not a full-line one.\n *\n * NO `contractVersion` (§7, answer 10): a reworded refusal reaches an app on\n * its next SDK bump, which is the right moment to see it; a version field\n * with no consumer is a mechanism nobody reads.\n */\n\n/**\n * Every name the host pages an op under — `HOST_OPS` in `host_call_attrs.rs`,\n * \"pinned by unit tests to `host_op_name` and `runtime::host_call_span`\". The\n * `HostOp` type is this list, so `\"warehouse.inserts\"` does not compile.\n */\nexport const HOST_OPS = [\n \"query\",\n \"query_stream\",\n \"fetch\",\n \"semantic.query\",\n \"airway.run\",\n \"warehouse.insert\",\n \"warehouse.exec\",\n \"warehouse.upsert\",\n \"warehouse.query\",\n \"tx.begin\",\n \"tx.begin_oltp\",\n \"tx.query\",\n \"tx.exec\",\n \"tx.commit\",\n \"tx.rollback\",\n \"oltp.query\",\n \"oltp.exec\",\n \"airhouse.query\",\n \"airhouse.exec\",\n \"airhouse.append\",\n \"storage.getUploadUrl\",\n \"storage.getDownloadUrl\",\n \"storage.put\",\n \"storage.get\",\n \"storage.head\",\n \"storage.list\",\n \"storage.delete\",\n \"storage.copy\",\n \"secrets.set\",\n \"email.send\",\n \"org.people\",\n \"org.places\",\n \"org.assignments\"\n] as const;\n\n/** One of the host's closed list of op names. */\nexport type HostOp = (typeof HOST_OPS)[number];\n\n/**\n * The surface `reply_json` prefixes a refusal with (`runtime.rs`): a thrown\n * `HostError`'s message is `\"<surface>: <host message>\"`. Every `tx.*` verb —\n * `begin_oltp` included — answers under `ctx.tx`, because one op carries all\n * six.\n */\nexport const SURFACES = {\n query: \"ctx.query\",\n queryStream: \"ctx.queryStream\",\n fetch: \"ctx.fetch\",\n warehouse: \"ctx.warehouse\",\n tx: \"ctx.tx\",\n oltp: \"ctx.oltp\",\n airhouse: \"ctx.airhouse\",\n secretsSet: \"ctx.secrets.set\",\n emailSend: \"ctx.email.send\",\n storage: \"ctx.storage\",\n orgPeople: \"ctx.org.people\",\n orgPlaces: \"ctx.org.places\",\n orgAssignments: \"ctx.org.assignments\",\n semanticQuery: \"ctx.semantic.query\",\n airwayRun: \"ctx.airway.run\"\n} as const;\n\n/** One refusal the host writes: the file it is quoted from and its template. */\nexport interface RefusalTemplate {\n readonly source: string;\n readonly refusal: string;\n}\n\n/**\n * Every refusal the context throws, quoted from the host. The context renders\n * a template by substituting its `{placeholder}`s and prefixing the surface.\n */\nexport const REFUSALS = {\n secretsWrite: {\n source: \"host.rs\",\n // The host method embeds its own surface, and `reply_json` prefixes it\n // again, so a function sees `ctx.secrets.set: ctx.secrets.set: this …`.\n // Reproduced, not corrected: the context throws what production throws.\n refusal:\n \"ctx.secrets.set: this function has not declared the `secrets.write` capability (add it to oxy-app.json to permit writes)\"\n },\n emailSend: {\n source: \"host.rs\",\n refusal:\n 'EmailCapabilityMissing: this function has not declared the `email.send` capability (add \"email\": { \"send\": true } to its oxy-app.json entry)'\n },\n orgPeople: {\n source: \"host.rs\",\n refusal:\n 'OrgCapabilityMissing: this function has not declared the `org.read` capability (add \"org\": { \"read\": true } to its oxy-app.json entry)'\n },\n orgMember: {\n source: \"host.rs\",\n refusal:\n 'OrgCapabilityMissing: this function has not declared the `org.read` capability (add \"org\": { \"read\": true } to its oxy-app.json entry) — ctx.org.{member}'\n },\n storageWrite: {\n source: \"host.rs\",\n refusal:\n 'StorageCapabilityMissing: this function has not declared the `storage.write` capability (add \"storage\": { \"write\": true } to its oxy-app.json entry)'\n },\n storageRead: {\n source: \"host.rs\",\n refusal:\n 'StorageCapabilityMissing: this function has not declared the `storage.read` capability (add \"storage\": { \"read\": true } to its oxy-app.json entry)'\n },\n oltp: {\n source: \"host.rs\",\n refusal:\n 'OltpCapabilityMissing: this function has not declared the `oltp` capability (add \"oltp\": { \"enabled\": true } to its oxy-app.json entry). The schema it writes is derived from the app\\'s own slug — the manifest only enables access.'\n },\n airhouse: {\n source: \"host/airhouse_ops.rs\",\n refusal:\n 'AirhouseCapabilityMissing: this function has not declared the `airhouse` capability (add \"airhouse\": { \"enabled\": true } to its oxy-app.json entry). The schema it writes is derived from the app\\'s own slug — the manifest only enables access.'\n },\n destinationNotDeclared: {\n source: \"host.rs\",\n refusal:\n \"database '{database}' is not in this function's `destinations` allowlist (declare it in oxy-app.json to permit writes)\"\n },\n databaseNotConfigured: {\n source: \"host.rs\",\n refusal: \"database '{database}' is not configured for this project\"\n },\n managedOltpWrite: {\n source: \"host/destinations.rs\",\n refusal:\n \"database '{database}' is the org's OLTP store, which this surface reaches as the read-only analyst — write this app's own records with ctx.oltp\"\n },\n customerWarehouseWrite: {\n source: \"host/destinations.rs\",\n refusal:\n 'database \\'{database}\\' is a customer warehouse, and customer warehouses are read-only to apps. Facts this app records belong in Airhouse (ctx.airhouse); records it edits belong in ctx.oltp. If this write has to stay, say why on the function in oxy-app.json: \"customerWarehouseWrites\": { \"{database}\": \"<reason>\" }'\n },\n customerWarehouseTransaction: {\n source: \"host/destinations.rs\",\n refusal:\n \". A ctx.tx transaction counts as a write even when it only reads — read with ctx.warehouse.query instead\"\n },\n upsertUnsupported: {\n source: \"upsert_support.rs\",\n refusal:\n \"warehouse.upsert is not supported on {dialect}: it compiles to `INSERT … ON CONFLICT … DO UPDATE`, which only Postgres and DuckDB parse. Use warehouse.insert, or warehouse.exec with this warehouse's own upsert statement.\"\n },\n transactionOpen: {\n source: \"host.rs\",\n refusal: \"could not open a transaction on '{database}': {e}\"\n },\n transactionUnsupported: {\n source: \"transaction.rs\",\n refusal:\n \"{backend} does not support multi-statement transactions — ctx.tx() requires a Postgres-backed database (`type: postgres`). Use ctx.warehouse.{insert,exec,upsert} for single-statement writes.\"\n },\n transactionsOpen: {\n source: \"tx.rs\",\n refusal:\n \"this invocation already has {MAX_OPEN} transactions open. Commit or roll one back before opening another.\"\n },\n transactionFinished: {\n source: \"runtime.rs\",\n refusal:\n \"{label}: this transaction is already finished — {what} was called after the callback returned\"\n },\n transactionFnNotFunction: {\n source: \"runtime.rs\",\n refusal: \"{signature}: fn must be a function\"\n },\n btoaBytes: {\n source: \"runtime.rs\",\n refusal: \"btoa: expected a string. For bytes use bytesToBase64() from @oxy-hq/sdk\"\n },\n atobPadding: {\n source: \"runtime.rs\",\n refusal: \"atob: '=' may only appear as trailing padding\"\n },\n atobLength: {\n source: \"runtime.rs\",\n refusal: \"atob: invalid base64 length\"\n },\n fetchInvalidUrl: {\n source: \"host.rs\",\n refusal: \"invalid url: {e}\"\n },\n fetchBlocked: {\n source: \"host.rs\",\n refusal: \"fetch to '{url}' blocked by SSRF allowlist\"\n },\n fetchInvalidHeaderName: {\n source: \"host.rs\",\n refusal: \"InvalidFetchHeader: `{k}` is not a header name\"\n },\n fetchInvalidHeaderValue: {\n source: \"host.rs\",\n refusal: \"InvalidFetchHeader: the value of `{k}` is not a header value\"\n },\n fetchTooLarge: {\n source: \"host.rs\",\n refusal: \"response too large ({len} bytes > {max_bytes} cap)\"\n },\n // The third state of `WriterCapability` (`host.rs`): the capability is on and\n // the slug still cannot name a schema. Gating on the boolean alone gave a\n // green test for an app whose `ctx.oltp` is closed in production, and the\n // gate-marker scan cannot catch it — this wording shares nothing with the\n // \"has not declared the\" family.\n slugCannotBackASchema: {\n source: \"host.rs\",\n refusal:\n \"the capability is enabled, but this app's slug '{slug}' cannot back an {store} schema: \" +\n \"to do so a slug must start with a letter, be at most {max} characters, and use only \" +\n \"lowercase letters, digits and hyphens (a `_` is refused — it would collide with the \" +\n \"hyphenated form). A leading digit is a legal app slug but not a legal schema name. \" +\n \"Rename the app to one that qualifies.\"\n },\n oltpParamsNotArray: {\n source: \"host.rs\",\n refusal:\n \"`params` must be an array of values. Pass positional arguments for $1, $2, … — e.g. [name, partySize].\"\n },\n noDefaultDatabase: {\n source: \"host.rs\",\n refusal: \"this project has no databases configured\"\n },\n oltpUnsupportedColumn: {\n source: \"postgres_tx/convert.rs\",\n refusal:\n \"result column `{name}` has Postgres type `{ty}`, which cannot be returned directly. Cast it to text in the SELECT list and parse it in your function — cast the whole expression, not the output name (`avg(qty)::text`, `amount::text`). Note `avg`/`sum` over any numeric type, and a bare decimal literal, are all `numeric`. (Supported as-is: bool, int2/4/8, float4/8, text/varchar/char/name, json/jsonb, uuid, timestamptz/timestamp, date, time.)\"\n }\n} as const satisfies Record<string, RefusalTemplate>;\n\n/** One capability gate: the `FunctionCapabilities` field and the ops it refuses. */\nexport interface Gate {\n /** The `FunctionCapabilities` field in `host.rs`. */\n readonly hostField: string;\n /** The capability as the manifest and the refusal name it: `storage.write`. */\n readonly manifest: string;\n /** The host ops refused while the manifest lacks it. */\n readonly ops: readonly HostOp[];\n}\n\n/**\n * Every gate in `FunctionCapabilities`, in the struct's order. `storage_read`\n * and `storage_write` list `check_storage_capability`'s arms (`copy` needs\n * both); `customer_warehouse_writes` is decided per database by\n * `destination_write_policy`, after the `destinations` allowlist.\n * `storage_retention` and `fetch_max_bytes` are fields of the struct and\n * deliberately absent: they shape an allowed call, they never refuse one.\n */\nexport const GATES = [\n {\n hostField: \"secrets_write\",\n manifest: \"secrets.write\",\n ops: [\"secrets.set\"]\n },\n {\n hostField: \"email_send\",\n manifest: \"email.send\",\n ops: [\"email.send\"]\n },\n {\n hostField: \"org_read\",\n manifest: \"org.read\",\n ops: [\"org.people\", \"org.places\", \"org.assignments\"]\n },\n {\n hostField: \"storage_read\",\n manifest: \"storage.read\",\n ops: [\"storage.getDownloadUrl\", \"storage.get\", \"storage.head\", \"storage.list\", \"storage.copy\"]\n },\n {\n hostField: \"storage_write\",\n manifest: \"storage.write\",\n ops: [\"storage.getUploadUrl\", \"storage.put\", \"storage.delete\", \"storage.copy\"]\n },\n {\n hostField: \"oltp\",\n manifest: \"oltp.enabled\",\n ops: [\"oltp.query\", \"oltp.exec\", \"tx.begin_oltp\"]\n },\n {\n hostField: \"airhouse\",\n manifest: \"airhouse.enabled\",\n ops: [\"airhouse.query\", \"airhouse.exec\", \"airhouse.append\"]\n },\n {\n hostField: \"customer_warehouse_writes\",\n manifest: \"customerWarehouseWrites\",\n ops: [\"warehouse.insert\", \"warehouse.exec\", \"warehouse.upsert\", \"tx.begin\"]\n }\n] as const satisfies readonly Gate[];\n\n/**\n * The globals the isolate does not define, as `oxyc`'s `isolate-global` lint\n * names them (`ABSENT_GLOBALS` in `sdk/cli/src/publish/function-lint.ts`).\n * `member` narrows an entry to `<name>.<member>`; an empty `member` is the\n * whole of `process.*`. The isolate's bootstrap defines `Response`, `btoa`,\n * `atob`, `console` and `__buildCtx` and nothing else (`runtime.rs`), so it has\n * no `crypto` global at all; the lint singles out `subtle` because that is what\n * an author reaches for, and `run()` removes the whole global as production\n * does.\n */\nexport const ABSENT_GLOBALS = [\n { name: \"Buffer\" },\n { name: \"TextEncoder\" },\n { name: \"TextDecoder\" },\n { name: \"Blob\" },\n { name: \"File\" },\n { name: \"FormData\" },\n { name: \"crypto\", member: \"subtle\" },\n { name: \"process\", member: \"\" }\n] as const;\n\n/**\n * `is_safe_outbound` in `host.rs`, the first-layer check every `ctx.fetch`\n * URL meets before anything is sent: the scheme, the host names refused by\n * name, and the suffixes an internal name ends with. The IP rules (loopback,\n * unspecified, private, link-local, broadcast, documentation, v4-mapped and\n * embedded v6) are code, in `fetch-rules.ts`. What no unit test can reproduce\n * is the second layer — a public name that RESOLVES to a private address is\n * caught at connect time by `PublicOnlyDnsResolver` — so the context does not\n * pretend to.\n */\nexport const FETCH_RULES = {\n scheme: \"https\",\n literalHosts: [\"localhost\", \"ip6-localhost\", \"ip6-loopback\"],\n internalSuffixes: [\".internal\", \".local\", \".localdomain\", \".svc\", \".cluster.local\"]\n} as const;\n\n/** `FETCH_MAX_BYTES` in `host.rs`: the default `ctx.fetch` response ceiling. */\nexport const FETCH_MAX_BYTES = 10 * 1024 * 1024;\n\n/** `MAX_OPEN` in `tx.rs`: transactions one invocation may hold open at once. */\nexport const MAX_OPEN_TRANSACTIONS = 4;\n\n/**\n * How each dialect names itself in a refusal — `SqlDialect::as_str` in the\n * connector crate, which `upsert_support::check` and `transaction::unsupported`\n * format in. Only Postgres, DuckDB and SQLite parse `ON CONFLICT`\n * (`parses_on_conflict`), and only the Postgres connector opens a transaction.\n */\nexport const DIALECTS = {\n clickhouse: { name: \"ClickHouse\", parsesOnConflict: false, opensTransactions: false },\n postgres: { name: \"PostgreSQL\", parsesOnConflict: true, opensTransactions: true },\n duckdb: { name: \"DuckDB\", parsesOnConflict: true, opensTransactions: false }\n} as const;\n\nexport type Dialect = keyof typeof DIALECTS;\n","// `is_safe_outbound` and `is_public_ip` from `host.rs`, in TypeScript: the\n// first-layer check every `ctx.fetch` URL meets before anything is sent. The\n// names and suffixes come from `FETCH_RULES` in the contract, which the Rust\n// drift test holds to the host; the IP arithmetic below follows the Rust\n// line by line and is pinned by `fetch-rules.test.ts`.\n//\n// What this cannot do, because no unit test can: the host's second layer\n// resolves the name and refuses a public name that points at a private\n// address (`PublicOnlyDnsResolver`). A test that passes here with a hostname\n// says nothing about where that name resolves.\n\nimport { FETCH_RULES } from \"./host-contract\";\n\n/** The host's verdict on a URL: allowed, or refused before sending. */\nexport function isSafeOutbound(url: URL): boolean {\n if (url.protocol !== `${FETCH_RULES.scheme}:`) return false;\n const host = url.hostname;\n if (host === \"\") return false;\n // `URL` keeps the brackets on a v6 literal; the Rust strips them the same way.\n const forIp = host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n const ip = parseIp(forIp);\n if (ip) return isPublicIp(ip);\n const lower = host.toLowerCase();\n if ((FETCH_RULES.literalHosts as readonly string[]).includes(lower)) return false;\n return !FETCH_RULES.internalSuffixes.some((suffix) => lower.endsWith(suffix));\n}\n\ntype Ip = { v4: [number, number, number, number] } | { v6: number[] };\n\n/** A literal IPv4 or IPv6 address, or `null` when `s` is a name. */\nfunction parseIp(s: string): Ip | null {\n const v4 = parseV4(s);\n if (v4) return { v4 };\n const v6 = parseV6(s);\n return v6 ? { v6 } : null;\n}\n\nfunction parseV4(s: string): [number, number, number, number] | null {\n const m = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (!m) return null;\n const parts = m.slice(1).map(Number);\n if (parts.some((p) => p > 255)) return null;\n return parts as [number, number, number, number];\n}\n\n/** Eight 16-bit segments, or `null`. Accepts `::`, and a dotted v4 tail. */\nfunction parseV6(s: string): number[] | null {\n if (!s.includes(\":\")) return null;\n const zone = s.indexOf(\"%\");\n const text = zone >= 0 ? s.slice(0, zone) : s;\n const halves = text.split(\"::\");\n if (halves.length > 2) return null;\n const head = halves[0] === \"\" ? [] : halves[0].split(\":\");\n const tail = halves.length === 2 && halves[1] !== \"\" ? halves[1].split(\":\") : [];\n const words = (groups: string[]): number[] | null => {\n const out: number[] = [];\n for (const [i, g] of groups.entries()) {\n if (g.includes(\".\")) {\n if (i !== groups.length - 1) return null;\n const v4 = parseV4(g);\n if (!v4) return null;\n out.push((v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]);\n } else {\n if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null;\n out.push(Number.parseInt(g, 16));\n }\n }\n return out;\n };\n const h = words(head);\n const t = words(tail);\n if (!h || !t) return null;\n if (halves.length === 1) return h.length === 8 ? h : null;\n const fill = 8 - h.length - t.length;\n if (fill < 1) return null;\n return [...h, ...new Array<number>(fill).fill(0), ...t];\n}\n\n/** `is_public_ip` in `host.rs`. */\nexport function isPublicIp(ip: Ip): boolean {\n const canonical = \"v6\" in ip ? (mappedV4(ip.v6) ?? ip) : ip;\n if (\"v4\" in canonical) return isPublicV4(canonical.v4);\n const seg = canonical.v6;\n if (seg.every((w) => w === 0)) return false; // unspecified\n if (seg.slice(0, 7).every((w) => w === 0) && seg[7] === 1) return false; // loopback\n // NAT64 (`64:ff9b::/96`) and IPv4-compatible (`::/96`) embed a v4 address\n // in the low 32 bits: judge the embedded address.\n const embedded = embeddedV4(seg);\n if (embedded) return isPublicV4(embedded);\n const first = seg[0];\n const linkLocal = (first & 0xffc0) === 0xfe80;\n const uniqueLocal = (first & 0xfe00) === 0xfc00;\n return !linkLocal && !uniqueLocal;\n}\n\nfunction isPublicV4([a, b, c, d]: [number, number, number, number]): boolean {\n if (a === 127) return false; // loopback\n if (a === 0 && b === 0 && c === 0 && d === 0) return false; // unspecified\n const isPrivate = a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);\n const linkLocal = a === 169 && b === 254;\n const broadcast = a === 255 && b === 255 && c === 255 && d === 255;\n const documentation =\n (a === 192 && b === 0 && c === 2) ||\n (a === 198 && b === 51 && c === 100) ||\n (a === 203 && b === 0 && c === 113);\n return !isPrivate && !linkLocal && !broadcast && !documentation;\n}\n\n/** `to_canonical()`: an IPv4-mapped address (`::ffff:a.b.c.d`) as its v4. */\nfunction mappedV4(seg: number[]): Ip | null {\n if (seg.slice(0, 5).every((w) => w === 0) && seg[5] === 0xffff) {\n return { v4: [seg[6] >> 8, seg[6] & 0xff, seg[7] >> 8, seg[7] & 0xff] };\n }\n return null;\n}\n\n/** `embedded_ipv4`: the v4 in a `::/96` or `64:ff9b::/96` address. */\nfunction embeddedV4(seg: number[]): [number, number, number, number] | null {\n const compatible = seg.slice(0, 6).every((w) => w === 0);\n const nat64 = seg[0] === 0x64 && seg[1] === 0xff9b && seg.slice(2, 6).every((w) => w === 0);\n if (!compatible && !nat64) return null;\n return [seg[6] >> 8, seg[6] & 0xff, seg[7] >> 8, seg[7] & 0xff];\n}\n","// How the context throws: as the runtime throws. `__wrapOp` in `runtime.rs`\n// turns the `reply_json` envelope `{ __oxyError: \"HostError\", message }` into an\n// `Error` whose `name` is `\"HostError\"` and whose message is\n// `\"<surface>: <host message>\"`. A test that matches on `err.name` or on the\n// message prefix sees exactly what a function sees in production.\n\nimport type { RefusalTemplate } from \"./host-contract\";\n\n/** The `name` the runtime gives every refusal it unwraps. */\nexport const HOST_ERROR_NAME = \"HostError\";\n\n/**\n * Render a refusal template: every `{placeholder}` replaced by `vars[name]`.\n * A placeholder the caller did not supply is a bug in the context, not in the\n * app under test, so it throws rather than leaking `{database}` into a message\n * a test might then match on.\n */\nexport function render(\n template: RefusalTemplate,\n vars: Record<string, string | number> = {}\n): string {\n return template.refusal.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (whole, name: string) => {\n const value = vars[name];\n if (value === undefined) {\n throw new Error(`test context bug: refusal template leaves {${name}} unfilled: ${whole}`);\n }\n return String(value);\n });\n}\n\n/**\n * The error a function sees when the host refuses: `name` `\"HostError\"`,\n * message `\"<surface>: <message>\"`.\n */\nexport function hostError(surface: string, message: string): Error {\n const err = new Error(`${surface}: ${message}`);\n err.name = HOST_ERROR_NAME;\n return err;\n}\n\n/** `hostError` over a rendered template. */\nexport function refuse(\n surface: string,\n template: RefusalTemplate,\n vars: Record<string, string | number> = {}\n): Error {\n return hostError(surface, render(template, vars));\n}\n\n/** Whether `err` is a refusal the context (or the runtime) threw. */\nexport function isHostError(err: unknown): err is Error {\n return err instanceof Error && err.name === HOST_ERROR_NAME;\n}\n\n/**\n * An error in the context's OWN words — never the host's. Thrown where the\n * context cannot model what the host would do (an unrecognised statement, an\n * unregistered `fetch` answer) and says so, rather than answering something\n * production would not. Its `name` is `\"TestContextError\"` so a test can never\n * mistake it for a refusal.\n */\nexport function contextError(message: string): Error {\n const err = new Error(`@oxy-hq/sdk/testing: ${message}`);\n err.name = \"TestContextError\";\n return err;\n}\n","// What the manifest grants one function — `FunctionCapabilities` in `host.rs`,\n// read off the app's `oxy-app.json` the way the host and `oxyc`'s\n// `declares(spec)` read it (`sdk/cli/src/publish/capabilities.ts`).\n//\n// THE MANIFEST IS THE WHOLE `oxy-app.json` PLUS A FUNCTION NAME\n// (`internal-docs/sdk-testing-context.md` §7, answer 3): the app's `slug`\n// derives the OLTP and Airhouse schema (`app_writer_name` in the `oltp` crate:\n// hyphens to underscores), and `destinations` / `customerWarehouseWrites` are\n// per function. Making a caller split them invites the two halves to disagree.\n\nimport { contextError } from \"./host-error\";\n\n/** The loose shape a JSON import of `oxy-app.json` satisfies. */\nexport interface ManifestLike {\n slug?: string;\n functions?: Record<string, Record<string, unknown> | undefined>;\n}\n\n/** `FunctionCapabilities` for one function, plus its write allowlist. */\nexport interface FunctionGates {\n functionName: string;\n slug: string;\n /** `app_<slug>` with `-` → `_`, or `null` when the slug cannot back a writer. */\n writerSchema: string | null;\n secretsWrite: boolean;\n emailSend: boolean;\n orgRead: boolean;\n storageRead: boolean;\n storageWrite: boolean;\n oltp: boolean;\n airhouse: boolean;\n /** `destinations`: the databases `ctx.warehouse` writes and `ctx.tx` may name. */\n destinations: string[];\n /** `customerWarehouseWrites`: database → the non-blank reason, blank ones dropped. */\n customerWarehouseWrites: Record<string, string>;\n /** `fetch.maxResponseBytes`, when the entry raises the ceiling. */\n fetchMaxBytes: number | null;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `spec.<a>.<b> === true` — `flag` in `capabilities.ts`. */\nfunction flag(spec: Record<string, unknown>, a: string, b: string): boolean {\n const block = spec[a];\n return isObject(block) && block[b] === true;\n}\n\n/**\n * `MAX_NAME_LEN` in `crates/oltp/src/schema.rs`: 63 (Postgres) less `app_` and\n * the longest role suffix `_rw`.\n */\nexport const MAX_SCHEMA_NAME_LEN = 56;\n\n/**\n * `app_writer_name` + `WriterRef::schema_name`: the schema an app's slug\n * derives, or `null` when it derives none.\n *\n * Both halves matter. `app_writer_name` refuses a slug containing `_` outright\n * — `my_app` would otherwise alias the hyphenated sibling `my-app` onto one\n * schema and role — and then runs the derived name through `validate_name`,\n * which is what rejects a leading digit, an over-long name, and any character\n * outside `[a-z0-9_]`. Skipping that second half handed back a schema for slugs\n * the host answers `None` for, which is the difference between a green test and\n * a closed `ctx.oltp` in production.\n */\nexport function writerSchema(slug: string): string | null {\n if (slug.includes(\"_\")) return null;\n const name = slug.replace(/-/g, \"_\");\n if (name === \"\" || name.length > MAX_SCHEMA_NAME_LEN) return null;\n if (!/^[a-z]/.test(name)) return null;\n if (!/^[a-z0-9_]+$/.test(name)) return null;\n return `app_${name}`;\n}\n\n/** Read the gates for `functionName` from `manifest`, or throw naming what is missing. */\nexport function readGates(manifest: ManifestLike, functionName: string): FunctionGates {\n const spec = manifest.functions?.[functionName];\n if (!isObject(spec)) {\n const known = Object.keys(manifest.functions ?? {});\n throw contextError(\n `oxy-app.json declares no function \"${functionName}\" (functions: ${known.length ? known.join(\", \") : \"none\"})`\n );\n }\n const slug = typeof manifest.slug === \"string\" ? manifest.slug : \"\";\n const destinations = Array.isArray(spec.destinations)\n ? spec.destinations.filter((d): d is string => typeof d === \"string\")\n : [];\n const customerWarehouseWrites: Record<string, string> = {};\n if (isObject(spec.customerWarehouseWrites)) {\n for (const [db, reason] of Object.entries(spec.customerWarehouseWrites)) {\n if (typeof reason === \"string\" && reason.trim() !== \"\") customerWarehouseWrites[db] = reason;\n }\n }\n const fetch = isObject(spec.fetch) ? spec.fetch : {};\n return {\n functionName,\n slug,\n writerSchema: writerSchema(slug),\n secretsWrite: flag(spec, \"secrets\", \"write\"),\n emailSend: flag(spec, \"email\", \"send\"),\n orgRead: flag(spec, \"org\", \"read\"),\n storageRead: flag(spec, \"storage\", \"read\"),\n storageWrite: flag(spec, \"storage\", \"write\"),\n oltp: flag(spec, \"oltp\", \"enabled\"),\n airhouse: flag(spec, \"airhouse\", \"enabled\"),\n destinations,\n customerWarehouseWrites,\n fetchMaxBytes: typeof fetch.maxResponseBytes === \"number\" ? fetch.maxResponseBytes : null\n };\n}\n","// `t.run(fn)`: evaluate `fn` with the isolate's absent globals absent.\n//\n// A test runs under Node, where `Buffer`, `TextEncoder` and `process` exist; the\n// isolate defines `Response`, `btoa`, `atob`, `console` and `__buildCtx` and\n// nothing else (`runtime.rs`). The context cannot delete those globals for the\n// whole file without breaking vitest, so this removes them from `globalThis`\n// for the duration of ONE call and restores them after — the technique the\n// canary uses for `process` (`new Function(\"process\", script)(undefined)`),\n// generalised. Inside `fn`, `new TextEncoder()` throws the `ReferenceError` it\n// throws in production, and `btoa` / `atob` are the runtime's own, with its\n// `TypeError`s.\n//\n// THE EXPLICIT PER-CALL FORM ONLY (`internal-docs/sdk-testing-context.md` §7,\n// answer 7). A vitest environment that removes the globals for a whole file is\n// what an app would eventually want, and may follow; shipping both now would\n// mean two mechanisms with one job. Because this mutates `globalThis`, two\n// `run` calls must not overlap: vitest runs one test at a time per file unless\n// `test.concurrent` is used, and `run` refuses to nest.\n//\n// CALL THE FUNCTION UNDER TEST INSIDE; ASSERT OUTSIDE. What this removes, it\n// removes from the whole process for the duration — and the test runner needs\n// some of it. `expect(…)` inside `fn` throws `ReferenceError: Buffer is not\n// defined` from vitest's own frames, not from the code under test, and so does\n// `console.log`. That reads like a bug in the function being tested and is not\n// one. Do the work inside, return what you want to check, assert after:\n//\n// const rows = await t.run(() => handler(req, t.ctx));\n// expect(rows).toHaveLength(1);\n//\n// This is the price of the per-call form, and the strongest argument for the\n// file-wide vitest environment above: there the runner's own frames never\n// execute inside the window.\n\nimport { ABSENT_GLOBALS, REFUSALS } from \"./host-contract\";\nimport { contextError, render } from \"./host-error\";\n\nconst B64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst B64R = new Uint8Array(256).fill(255);\nfor (let i = 0; i < 64; i++) B64R[B64.charCodeAt(i)] = i;\n\n/** `globalThis.btoa` as the isolate defines it: strings only, Latin1 only. */\nexport function isolateBtoa(input: unknown): string {\n if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {\n throw new TypeError(render(REFUSALS.btoaBytes));\n }\n const s = String(input);\n let out = \"\";\n for (let i = 0; i < s.length; i += 3) {\n const c0 = s.charCodeAt(i);\n const c1 = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;\n const c2 = i + 2 < s.length ? s.charCodeAt(i + 2) : 0;\n if (c0 > 0xff || c1 > 0xff || c2 > 0xff) {\n throw new TypeError(\n 'btoa: input contains characters outside the Latin1 range; for text pass it directly with { encoding: \"utf8\" }'\n );\n }\n const n = (c0 << 16) | (c1 << 8) | c2;\n out +=\n B64[(n >> 18) & 63] +\n B64[(n >> 12) & 63] +\n (i + 1 < s.length ? B64[(n >> 6) & 63] : \"=\") +\n (i + 2 < s.length ? B64[n & 63] : \"=\");\n }\n return out;\n}\n\n/** `globalThis.atob` as the isolate defines it: WHATWG forgiving-base64. */\nexport function isolateAtob(input: unknown): string {\n let s = String(input).replace(/[ \\t\\n\\f\\r]/g, \"\");\n if (s.length % 4 === 0) {\n let pad = 0;\n while (pad < 2 && s.charCodeAt(s.length - 1) === 61) {\n s = s.slice(0, -1);\n pad++;\n }\n }\n if (s.indexOf(\"=\") >= 0) throw new TypeError(render(REFUSALS.atobPadding));\n if (s.length % 4 === 1) throw new TypeError(render(REFUSALS.atobLength));\n let out = \"\";\n let buf = 0;\n let bits = 0;\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n const v = code < 256 ? B64R[code] : 255;\n if (v === 255) throw new TypeError(`atob: invalid base64 character '${s[i]}'`);\n buf = (buf << 6) | v;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out += String.fromCharCode((buf >> bits) & 0xff);\n }\n }\n return out;\n}\n\nlet running = false;\n\n/**\n * Evaluate `fn` with every `ABSENT_GLOBALS` entry removed from `globalThis` and\n * `btoa` / `atob` replaced by the isolate's, restoring all of them afterwards\n * — whether `fn` resolves or throws.\n */\nexport async function runWithoutIsolateGlobals<T>(fn: () => Promise<T> | T): Promise<T> {\n if (running) throw contextError(\"t.run(fn) calls must not overlap — one at a time per test\");\n running = true;\n const saved: [string, PropertyDescriptor | undefined][] = [];\n const g = globalThis as Record<string, unknown>;\n const shadow = (name: string, value: unknown | undefined) => {\n saved.push([name, Object.getOwnPropertyDescriptor(globalThis, name)]);\n if (value === undefined) delete g[name];\n else Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });\n };\n try {\n for (const entry of ABSENT_GLOBALS) shadow(entry.name, undefined);\n shadow(\"btoa\", isolateBtoa);\n shadow(\"atob\", isolateAtob);\n return await fn();\n } finally {\n for (const [name, descriptor] of saved.reverse()) {\n if (descriptor) Object.defineProperty(globalThis, name, descriptor);\n else delete g[name];\n }\n running = false;\n }\n}\n","// The small subset of SQL the context evaluates against its in-memory tables.\n//\n// Deliberately tiny and deliberately loud: `CREATE TABLE`, `INSERT … VALUES`,\n// `SELECT <columns | count(*) | literals> FROM <table> [WHERE a = b AND …]\n// [ORDER BY col] [LIMIT n]`, `DELETE FROM`, `UPDATE … SET`, and a `SELECT`\n// of literals with no `FROM`. Anything else is not guessed at — the store\n// throws a `TestContextError` naming the statement and the two ways out\n// (`t.override(op, …)` to answer the call, or `t.state.<store>.raw(…)` to\n// seed rows). Every VALUES entry keeps its raw SQL text, so a zoo case's\n// `value_sql` round-trips exactly and `zoo.ts` can render it.\n\nimport { contextError } from \"./host-error\";\n\nexport interface ColumnDef {\n name: string;\n /** The native type as written: `Decimal(18, 4)`, `LowCardinality(String)`. */\n type: string;\n}\n\nexport interface CreateTable {\n kind: \"create\";\n table: string;\n ifNotExists: boolean;\n columns: ColumnDef[];\n}\n\nexport interface Insert {\n kind: \"insert\";\n table: string;\n /** The column list when written; otherwise the table's declared order. */\n columns: string[] | null;\n /** Each row's values as raw SQL text, in column order. */\n tuples: string[][];\n}\n\nexport type Predicate = { column: string; values: string[] };\n\nexport type Projection =\n | { kind: \"all\" }\n | { kind: \"count\"; alias: string }\n | { kind: \"column\"; column: string; alias: string }\n | { kind: \"literal\"; raw: string; alias: string };\n\nexport interface Select {\n kind: \"select\";\n table: string | null;\n items: Projection[];\n where: Predicate[];\n orderBy: { column: string; desc: boolean } | null;\n limit: number | null;\n}\n\nexport interface Delete {\n kind: \"delete\";\n table: string;\n where: Predicate[];\n}\n\nexport interface Update {\n kind: \"update\";\n table: string;\n set: { column: string; raw: string }[];\n where: Predicate[];\n}\n\nexport type Statement = CreateTable | Insert | Select | Delete | Update;\n\nconst STOP_WORDS =\n /^(DEFAULT|NOT|NULL|PRIMARY|UNIQUE|REFERENCES|CHECK|GENERATED|CODEC|COMMENT|TTL)$/i;\nconst CONSTRAINT_HEAD = /^(PRIMARY|UNIQUE|CONSTRAINT|FOREIGN|CHECK|KEY|INDEX)\\b/i;\n\n/** `sql` without its leading line and block comments and whitespace. */\nexport function stripLeadingComments(sql: string): string {\n let s = sql;\n for (;;) {\n const before = s;\n s = s\n .replace(/^\\s+/, \"\")\n .replace(/^--[^\\n]*\\n?/, \"\")\n .replace(/^\\/\\*[\\s\\S]*?\\*\\//, \"\");\n if (s === before) return s;\n }\n}\n\n/** Parse one statement, or throw in the context's own words. */\nexport function parse(sql: string): Statement {\n const text = stripLeadingComments(sql).replace(/;\\s*$/, \"\");\n const head = /^(\\w+)/.exec(text)?.[1]?.toUpperCase() ?? \"\";\n switch (head) {\n case \"CREATE\":\n return parseCreate(text);\n case \"INSERT\":\n return parseInsert(text);\n case \"SELECT\":\n case \"WITH\":\n return parseSelect(text);\n case \"DELETE\":\n return parseDelete(text);\n case \"UPDATE\":\n return parseUpdate(text);\n default:\n throw unsupported(text);\n }\n}\n\nexport function unsupported(sql: string): Error {\n const head = sql.trim().slice(0, 60).replace(/\\s+/g, \" \");\n return contextError(\n `the test context cannot evaluate this statement: \"${head}…\". It reads CREATE TABLE, INSERT … VALUES, SELECT <columns|count(*)|literals> FROM <table> [WHERE col = value AND …] [ORDER BY col] [LIMIT n], DELETE FROM and UPDATE … SET. Answer the call with t.override(op, …), or seed the rows it should find with t.state.<store>.raw(table, rows).`\n );\n}\n\n/** Strip the quotes an identifier was written with. */\nexport function ident(raw: string): string {\n const s = raw.trim();\n if ((s.startsWith('\"') && s.endsWith('\"')) || (s.startsWith(\"`\") && s.endsWith(\"`\"))) {\n return s.slice(1, -1);\n }\n return s;\n}\n\n/** Split `text` on top-level commas, respecting parentheses, brackets and quotes. */\nexport function splitTopLevel(text: string, separator = \",\"): string[] {\n const out: string[] = [];\n let depth = 0;\n let quote: string | null = null;\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (quote) {\n if (c === quote) {\n if (text[i + 1] === quote) i++;\n else quote = null;\n }\n continue;\n }\n if (c === \"'\" || c === '\"' || c === \"`\") quote = c;\n else if (c === \"(\" || c === \"[\") depth++;\n else if (c === \")\" || c === \"]\") depth--;\n else if (depth === 0 && text.startsWith(separator, i)) {\n out.push(text.slice(start, i).trim());\n i += separator.length - 1;\n start = i + 1;\n }\n }\n out.push(text.slice(start).trim());\n return out.filter((s) => s !== \"\");\n}\n\n/** The index just past the `)` matching the `(` at `open`. */\nfunction closeParen(text: string, open: number): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = open; i < text.length; i++) {\n const c = text[i];\n if (quote) {\n if (c === quote) {\n if (text[i + 1] === quote) i++;\n else quote = null;\n }\n continue;\n }\n if (c === \"'\" || c === '\"') quote = c;\n else if (c === \"(\") depth++;\n else if (c === \")\" && --depth === 0) return i + 1;\n }\n throw unsupported(text);\n}\n\nfunction parseCreate(text: string): CreateTable {\n const m = /^CREATE\\s+TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?([\\w.\"`]+)\\s*\\(/i.exec(text);\n if (!m) throw unsupported(text);\n const open = m[0].length - 1;\n const end = closeParen(text, open);\n const columns: ColumnDef[] = [];\n for (const def of splitTopLevel(text.slice(open + 1, end - 1))) {\n if (CONSTRAINT_HEAD.test(def)) continue;\n const words = splitTopLevel(def, \" \");\n const name = ident(words[0] ?? \"\");\n const rest = def.slice(def.indexOf(words[0] ?? \"\") + (words[0]?.length ?? 0)).trim();\n const typeWords = splitTopLevel(rest, \" \");\n const stop = typeWords.findIndex((w) => STOP_WORDS.test(w));\n const type = (stop < 0 ? typeWords : typeWords.slice(0, stop)).join(\" \");\n if (name) columns.push({ name, type });\n }\n return { kind: \"create\", table: ident(m[2]), ifNotExists: Boolean(m[1]), columns };\n}\n\nfunction parseInsert(text: string): Insert {\n const m = /^INSERT\\s+INTO\\s+([\\w.\"`]+)\\s*(\\(([^)]*)\\))?\\s*VALUES\\s*/i.exec(text);\n if (!m) throw unsupported(text);\n const columns = m[3] ? splitTopLevel(m[3]).map(ident) : null;\n const tuples: string[][] = [];\n let at = m[0].length;\n while (at < text.length) {\n if (text[at] !== \"(\") throw unsupported(text);\n const end = closeParen(text, at);\n tuples.push(splitTopLevel(text.slice(at + 1, end - 1)));\n at = end;\n const gap = /^\\s*,?\\s*/.exec(text.slice(at))?.[0] ?? \"\";\n at += gap.length;\n }\n return { kind: \"insert\", table: ident(m[1]), columns, tuples };\n}\n\n/** `a = 1 AND b = 'x' AND c IN (1, 2)` → predicates; anything else throws. */\nfunction parseWhere(text: string | undefined, whole: string): Predicate[] {\n if (!text) return [];\n return splitTopLevel(text, \" AND \").map((clause) => {\n const eq = /^([\\w.\"`]+)\\s*=\\s*(.+)$/s.exec(clause);\n if (eq) return { column: ident(eq[1]), values: [eq[2].trim()] };\n const inList = /^([\\w.\"`]+)\\s+IN\\s*\\((.*)\\)$/is.exec(clause);\n if (inList) return { column: ident(inList[1]), values: splitTopLevel(inList[2]) };\n throw contextError(\n `the test context cannot evaluate this WHERE clause: \"${clause}\". It reads \"col = value\" and \"col IN (…)\" joined by AND. Answer the call with t.override(op, …) instead: ${whole.slice(0, 80)}`\n );\n });\n}\n\n/**\n * Whether `literal()` will read this expression as a value rather than hand it\n * back as its own SQL text. The two must agree: a projection the parser accepts\n * as a literal but `literal()` cannot read comes back to the caller as the SQL\n * they wrote — a column named `sum(amount)` holding the string `\"sum(amount)\"`,\n * which is the one thing this module promises never to do.\n */\nfunction isReadableLiteral(expr: string): boolean {\n const s = expr.trim();\n return (\n /^\\$\\d+$/.test(s) ||\n /^(NULL|TRUE|FALSE)$/i.test(s) ||\n (s.startsWith(\"'\") && s.endsWith(\"'\") && s.length >= 2) ||\n /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(s)\n );\n}\n\n/**\n * The statement with every quoted string blanked, so a keyword scan reads the\n * SQL and not the data: `WHERE label = 'GROUP BY'` is a row, not a grouping.\n */\nfunction withoutStringLiterals(text: string): string {\n return text.replace(/'(?:[^']|'')*'/g, \"''\");\n}\n\nfunction parseSelect(text: string): Select {\n // GROUP BY used to be an optional, non-capturing branch of the regex below:\n // it matched, nothing read it, and the grouping silently vanished — so\n // `SELECT status, count(*) FROM orders GROUP BY status` answered with one\n // ungrouped row and no `status` column. Refusing is the contract; aggregating\n // for real is not something a fake should attempt.\n if (/\\bGROUP\\s+BY\\b/is.test(withoutStringLiterals(text))) {\n throw contextError(\n `the test context cannot evaluate GROUP BY: \"${text.trim().slice(0, 60).replace(/\\s+/g, \" \")}…\". ` +\n `It would have to aggregate, and a wrong aggregate reads like a right one. ` +\n `Answer the call with t.override(op, …) and assert on the arguments instead.`\n );\n }\n const m =\n /^SELECT\\s+(.*?)(?:\\s+FROM\\s+([\\w.\"`]+))?(?:\\s+WHERE\\s+(.*?))?(?:\\s+ORDER\\s+BY\\s+([\\w.\"`]+)(?:\\s+(ASC|DESC))?)?(?:\\s+LIMIT\\s+(\\d+))?\\s*$/is.exec(\n text\n );\n if (!m || (!m[2] && /\\bFROM\\b/i.test(m[1]))) throw unsupported(text);\n const items: Projection[] = splitTopLevel(m[1]).map((item) => {\n if (item === \"*\") return { kind: \"all\" };\n const aliased = /^(.*?)\\s+AS\\s+([\\w\"`]+)$/is.exec(item);\n const expr = (aliased ? aliased[1] : item).trim();\n const alias = aliased ? ident(aliased[2]) : null;\n if (/^count\\s*\\(\\s*\\*\\s*\\)$/i.test(expr)) return { kind: \"count\", alias: alias ?? \"count(*)\" };\n if (/^[\\w.\"`]+$/.test(expr) && !/^\\d/.test(expr) && !/^(true|false|null)$/i.test(expr)) {\n return { kind: \"column\", column: ident(expr), alias: alias ?? ident(expr) };\n }\n // Everything else used to fall through as a literal, which handed the SQL\n // back as its own value: `sum(amount)`, `DISTINCT a`, a cast, a window.\n if (!isReadableLiteral(expr)) throw unsupported(text);\n return { kind: \"literal\", raw: expr, alias: alias ?? expr };\n });\n return {\n kind: \"select\",\n table: m[2] ? ident(m[2]) : null,\n items,\n where: parseWhere(m[3], text),\n orderBy: m[4] ? { column: ident(m[4]), desc: (m[5] ?? \"\").toUpperCase() === \"DESC\" } : null,\n limit: m[6] ? Number(m[6]) : null\n };\n}\n\nfunction parseDelete(text: string): Delete {\n const m = /^DELETE\\s+FROM\\s+([\\w.\"`]+)(?:\\s+WHERE\\s+(.*))?\\s*$/is.exec(text);\n if (!m) throw unsupported(text);\n return { kind: \"delete\", table: ident(m[1]), where: parseWhere(m[2], text) };\n}\n\nfunction parseUpdate(text: string): Update {\n const m = /^UPDATE\\s+([\\w.\"`]+)\\s+SET\\s+(.*?)(?:\\s+WHERE\\s+(.*))?\\s*$/is.exec(text);\n if (!m) throw unsupported(text);\n const set = splitTopLevel(m[2]).map((assignment) => {\n const eq = /^([\\w.\"`]+)\\s*=\\s*(.+)$/s.exec(assignment);\n if (!eq) throw unsupported(text);\n // Same rule as a projection, for the same reason: an assignment `literal()`\n // cannot read is stored as its own SQL text, so `SET n = n + 1` would leave\n // the string `\"n + 1\"` in a numeric column and the test would pass on it.\n const raw = eq[2].trim();\n if (!isReadableLiteral(raw)) throw unsupported(text);\n return { column: ident(eq[1]), raw };\n });\n return { kind: \"update\", table: ident(m[1]), set, where: parseWhere(m[3], text) };\n}\n\n/**\n * A raw SQL value as a JS value, with no engine's rendering applied: a quoted\n * string, a number, NULL, TRUE/FALSE, or a `$n` bound parameter. Anything else\n * (a function call, a cast, an array literal) stays as its SQL text.\n */\nexport function literal(raw: string, params: readonly unknown[] = []): unknown {\n const s = raw.trim();\n const param = /^\\$(\\d+)$/.exec(s);\n if (param) return params[Number(param[1]) - 1];\n if (/^NULL$/i.test(s)) return null;\n if (/^TRUE$/i.test(s)) return true;\n if (/^FALSE$/i.test(s)) return false;\n if (s.startsWith(\"'\") && s.endsWith(\"'\")) return s.slice(1, -1).replace(/''/g, \"'\");\n if (/^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(s)) return Number(s);\n return s;\n}\n","","// Generated by scripts/data-shapes/sync-canary-zoo.mjs from fixtures/data-shapes/zoo.json.\nexport const ZOO_SHA256 = \"04f75f9054a46e521d8787d65f5d214440d041860971c77e66edc7bfbaf8d16a\";\n","// The shape zoo: the pinned JS value each engine's native types arrive as.\n//\n// `shape-zoo.json` is a byte copy of `fixtures/data-shapes/zoo.json` — 313\n// cases, one per native type and value class, each `expect` being what a real\n// read through the platform returned (`custom_app_functions_shape_zoo` on the\n// Rust side loads every case through the connector and reads it back through\n// a published function). `scripts/data-shapes/sync-canary-zoo.mjs` writes the\n// copy and its digest; `shape-zoo-sync.test.ts` fails when either is stale.\n//\n// The context answers reads from it two ways: a zoo TABLE (`t.state.<store>.zoo()`)\n// whose column `cNNN` is case NNN's expectation, and TYPED tables, where an\n// inserted SQL-side value is rendered through the case for its type — exactly\n// when the value IS a case's `value_sql`, and by the `plain` case's shape\n// otherwise. An author's own JS values (`raw`) are never rendered.\n\nimport { REFUSALS } from \"./host-contract\";\nimport { render } from \"./host-error\";\nimport zooJson from \"./shape-zoo.json\";\nimport { ZOO_SHA256 } from \"./shape-zoo-sha256\";\n\nexport type ZooEngine = \"clickhouse\" | \"postgres\" | \"duckdb\";\n/** Which plane read the value: `ctx.warehouse` / `ctx.query`, or `ctx.oltp` / `ctx.tx`. */\nexport type ZooPlane = \"warehouse\" | \"oltp\";\n\nexport interface ZooCase {\n key: string;\n native_type: string;\n class: string;\n value_sql: string;\n expect: { warehouse: unknown; oltp?: unknown };\n}\n\nexport interface ShapeZoo {\n version: number;\n engines: Record<ZooEngine, { cases: ZooCase[] }>;\n}\n\n/** Where a row value came from — the honesty flag on every read. */\nexport type RowSource = \"zoo\" | \"typed\" | \"author\";\n\n/** A value a read would REFUSE rather than return: `expect.oltp.$error`. */\nexport class ZooRefusal {\n constructor(\n readonly column: string,\n readonly nativeType: string,\n readonly detail: string\n ) {}\n /** The host's full sentence for it, from the contract. */\n message(): string {\n return render(REFUSALS.oltpUnsupportedColumn, { name: this.column, ty: this.nativeType });\n }\n}\n\nexport const ZOO: ShapeZoo = zooJson as unknown as ShapeZoo;\n\n/** The zoo table's name, from the fixture's digest — the canary's `zooTableName`. */\nexport function zooTableName(sha256Hex: string = ZOO_SHA256): string {\n return `oxy_shape_zoo_${sha256Hex.slice(0, 8)}`;\n}\n\n/** `c001`, `c002`, … — the zoo column for case `index`. */\nexport function zooColumn(index: number): string {\n return `c${String(index + 1).padStart(3, \"0\")}`;\n}\n\n/** The engine a dialect's cases are filed under. */\nexport function engineOf(dialect: \"clickhouse\" | \"postgres\" | \"duckdb\"): ZooEngine {\n return dialect;\n}\n\nconst isError = (v: unknown): v is { $error: string } =>\n typeof v === \"object\" && v !== null && \"$error\" in v;\n\n/** What a read of case `c` on `plane` returns — or refuses. */\nexport function expectation(c: ZooCase, plane: ZooPlane, column: string): unknown | ZooRefusal {\n const value = plane === \"oltp\" ? c.expect.oltp : c.expect.warehouse;\n return isError(value) ? new ZooRefusal(column, c.native_type, value.$error) : value;\n}\n\n/** Every case of `engine` for `nativeType`, as written in the zoo. */\nexport function casesFor(engine: ZooEngine, nativeType: string): ZooCase[] {\n return ZOO.engines[engine].cases.filter((c) => c.native_type === nativeType);\n}\n\n/** The native types the zoo pins for `engine`, for a declaration error to list. */\nexport function knownTypes(engine: ZooEngine): string[] {\n return [...new Set(ZOO.engines[engine].cases.map((c) => c.native_type))];\n}\n\nconst I64_MAX = 9223372036854775807n;\nconst I64_MIN = -9223372036854775808n;\n\n/**\n * Render one SQL-side value of a typed column through the zoo.\n *\n * - The value IS a case's `value_sql` for this type → that case's expectation\n * (`source: \"zoo\"`).\n * - `NULL` → `null`.\n * - Otherwise the `plain` case's SHAPE decides: a number-shaped type parses the\n * literal, except that an integer outside `i64` becomes its exact digits as a\n * string where the zoo pins that (`precision_gt_18` expecting a string) — the\n * host reads an overflowing column as `u64` rendered to text; a string-shaped\n * type unquotes; a boolean-shaped type reads `true`/`false`/`1`/`0`; a JSON\n * shape parses (`source: \"typed\"`).\n */\nexport function renderValue(\n engine: ZooEngine,\n nativeType: string,\n valueSql: string,\n plane: ZooPlane,\n column: string\n): { value: unknown | ZooRefusal; source: RowSource } {\n const cases = casesFor(engine, nativeType);\n const raw = valueSql.trim();\n const exact = cases.find((c) => c.value_sql.trim() === raw);\n if (exact) return { value: expectation(exact, plane, column), source: \"zoo\" };\n if (/^NULL$/i.test(raw)) return { value: null, source: \"typed\" };\n const plain = cases.find((c) => c.class === \"plain\") ?? cases[0];\n const shape = expectation(plain, plane, column);\n if (shape instanceof ZooRefusal) return { value: shape, source: \"zoo\" };\n return { value: shaped(raw, shape, cases, plane, column), source: \"typed\" };\n}\n\nfunction shaped(\n raw: string,\n shape: unknown,\n cases: ZooCase[],\n plane: ZooPlane,\n column: string\n): unknown {\n const unquoted =\n raw.startsWith(\"'\") && raw.endsWith(\"'\") ? raw.slice(1, -1).replace(/''/g, \"'\") : raw;\n switch (typeof shape) {\n case \"number\": {\n if (/^-?\\d+$/.test(raw)) {\n const big = BigInt(raw);\n if (big > I64_MAX || big < I64_MIN) {\n const wide = cases.find((c) => c.class === \"precision_gt_18\");\n if (wide && typeof expectation(wide, plane, column) === \"string\") return raw;\n }\n }\n const n = Number(unquoted);\n return Number.isNaN(n) ? unquoted : n;\n }\n case \"boolean\":\n return /^(true|1)$/i.test(unquoted);\n case \"string\":\n return unquoted;\n case \"object\": {\n if (shape === null) return null;\n try {\n return JSON.parse(unquoted);\n } catch {\n return unquoted;\n }\n }\n default:\n return unquoted;\n }\n}\n","// The context's stores: per-database warehouse tables, the app's OLTP rows,\n// its Airhouse tables — each a `TableStore` evaluating the SQL subset in\n// `sql.ts` — plus storage objects, secrets, emails, fetch answers and org\n// fixtures. Plain in-memory state a test inspects directly; no timers, no\n// network, no filesystem.\n\nimport type { OxyFunctionRow } from \"../custom-app/function-context\";\nimport { contextError } from \"./host-error\";\nimport {\n type Delete,\n type Insert,\n literal,\n parse,\n type Select,\n type Statement,\n type Update\n} from \"./sql\";\nimport {\n expectation,\n knownTypes,\n type RowSource,\n renderValue,\n ZOO,\n type ZooEngine,\n type ZooPlane,\n ZooRefusal,\n zooColumn,\n zooTableName\n} from \"./zoo\";\n\n/** One stored row and where its values came from. */\ninterface StoredRow {\n values: Record<string, unknown | ZooRefusal>;\n source: RowSource;\n}\n\ninterface Table {\n name: string;\n /** Native types by column for a typed table; `null` for a raw one. */\n columns: Record<string, string> | null;\n rows: StoredRow[];\n}\n\n/** A read's rows, and the weakest source among them. */\nexport interface ReadResult {\n rows: OxyFunctionRow[];\n source: RowSource | null;\n}\n\nconst RANK: Record<RowSource, number> = { zoo: 0, typed: 1, author: 2 };\nconst weakest = (a: RowSource | null, b: RowSource): RowSource =>\n a === null || RANK[b] > RANK[a] ? b : a;\n\n/**\n * One SQL-evaluating store: a warehouse database, the OLTP schema or the\n * Airhouse schema. `engine` picks which zoo cases render typed columns;\n * `plane` picks which expectation a case yields.\n */\nexport class TableStore {\n private readonly tables = new Map<string, Table>();\n\n constructor(\n readonly engine: ZooEngine,\n readonly plane: ZooPlane,\n /** For a schema-qualified name to resolve to a bare one: the schema, or `null`. */\n readonly schema: string | null = null\n ) {}\n\n /** The zoo table for this engine: column `cNNN` is case NNN's expectation. */\n zoo(): this {\n const cases = ZOO.engines[this.engine].cases;\n const columns: Record<string, string> = {};\n const values: Record<string, unknown | ZooRefusal> = {};\n cases.forEach((c, i) => {\n const column = zooColumn(i);\n columns[column] = c.native_type;\n values[column] = expectation(c, this.plane, column);\n });\n this.tables.set(zooTableName(), {\n name: zooTableName(),\n columns,\n rows: [{ values, source: \"zoo\" }]\n });\n return this;\n }\n\n /**\n * Declare a typed table: `{ id: \"UInt64\", amount: \"Decimal(18, 4)\" }`. A\n * type the zoo has no case for is an error here, not a guess at read time.\n */\n table(name: string, columns: Record<string, string>): TypedTable {\n const key = this.key(name);\n for (const [column, type] of Object.entries(columns)) {\n if (!ZOO.engines[this.engine].cases.some((c) => c.native_type === type)) {\n throw contextError(\n `the zoo has no ${this.engine} case for type \"${type}\" (column \"${column}\" of \"${name}\"); it pins: ${knownTypes(this.engine).join(\", \")}`\n );\n }\n }\n if (!this.tables.has(key)) this.tables.set(key, { name: key, columns, rows: [] });\n return new TypedTable(this, key);\n }\n\n /** Seed rows as JS values, unrendered — every read of them is `source: \"author\"`. */\n raw(name: string, rows: OxyFunctionRow[]): this {\n const key = this.key(name);\n const table = this.tables.get(key) ?? { name: key, columns: null, rows: [] };\n for (const row of rows) table.rows.push({ values: { ...row }, source: \"author\" });\n this.tables.set(key, table);\n return this;\n }\n\n /** Every row of `name` as a function would read it; a `$error` cell is its refusal text. */\n rows(name: string): OxyFunctionRow[] {\n return this.lookup(name)?.rows.map((r) => materialise(r.values)) ?? [];\n }\n\n /** The names of every table declared, seeded or created. */\n tableNames(): string[] {\n return [...this.tables.keys()];\n }\n\n /** Whether `name` exists. */\n has(name: string): boolean {\n return this.lookup(name) !== undefined;\n }\n\n /** Evaluate `sql` as a read: rows, or a throw. */\n query(sql: string, params: readonly unknown[] = []): ReadResult {\n const statement = parse(sql);\n if (statement.kind !== \"select\")\n throw contextError(\n `expected a SELECT, got ${statement.kind.toUpperCase()}: ${sql.slice(0, 80)}`\n );\n return this.select(statement, params);\n }\n\n /** Evaluate `sql` as a statement: rows affected, or a throw. */\n exec(sql: string, params: readonly unknown[] = []): number {\n const statement = parse(sql);\n switch (statement.kind) {\n case \"create\":\n return this.create(statement);\n case \"insert\":\n return this.insert(statement, params);\n case \"delete\":\n return this.remove(statement, params);\n case \"update\":\n return this.update(statement, params);\n case \"select\":\n return this.select(statement, params).rows.length;\n }\n }\n\n /** Append JS rows to `name` (`ctx.warehouse.insert`, `ctx.airhouse.append`): unrendered. */\n append(name: string, rows: OxyFunctionRow[]): number {\n this.raw(name, rows);\n return rows.length;\n }\n\n /** Snapshot every table, for `ctx.tx` rollback. */\n snapshot(): () => void {\n const copy = new Map(\n [...this.tables].map(([k, t]) => [\n k,\n { ...t, rows: t.rows.map((r) => ({ ...r, values: { ...r.values } })) }\n ])\n );\n return () => {\n this.tables.clear();\n for (const [k, t] of copy) this.tables.set(k, t);\n };\n }\n\n private key(name: string): string {\n const bare =\n this.schema && name.startsWith(`${this.schema}.`) ? name.slice(this.schema.length + 1) : name;\n return bare;\n }\n\n private lookup(name: string): Table | undefined {\n return this.tables.get(this.key(name)) ?? this.tables.get(name);\n }\n\n private require(name: string, statement: Statement): Table {\n const table = this.lookup(name);\n if (!table) {\n throw contextError(\n `${statement.kind.toUpperCase()} names a table the test context does not have: \"${name}\". Declare it with t.state.<store>.table(name, columns), seed it with .raw(name, rows), or let the function CREATE it first. Known: ${this.tableNames().join(\", \") || \"none\"}`\n );\n }\n return table;\n }\n\n private create(statement: Statement & { kind: \"create\" }): number {\n const key = this.key(statement.table);\n if (this.tables.has(key)) {\n if (statement.ifNotExists) return 0;\n throw contextError(`CREATE TABLE \"${statement.table}\": the table already exists`);\n }\n const columns: Record<string, string> = {};\n for (const c of statement.columns) columns[c.name] = c.type;\n this.tables.set(key, { name: key, columns, rows: [] });\n return 0;\n }\n\n private insert(statement: Insert, params: readonly unknown[]): number {\n const table = this.require(statement.table, statement);\n const names = statement.columns ?? (table.columns ? Object.keys(table.columns) : null);\n for (const tuple of statement.tuples) {\n if (!names || names.length !== tuple.length) {\n throw contextError(\n `INSERT INTO \"${statement.table}\" gives ${tuple.length} value(s) for ${names?.length ?? \"an unknown number of\"} column(s)`\n );\n }\n const values: Record<string, unknown | ZooRefusal> = {};\n let source: RowSource | null = null;\n names.forEach((column, i) => {\n const type = table.columns?.[column];\n if (type && !/^\\$\\d+$/.test(tuple[i].trim())) {\n const rendered = renderValue(this.engine, type, tuple[i], this.plane, column);\n values[column] = rendered.value;\n source = weakest(source, rendered.source);\n } else {\n values[column] = literal(tuple[i], params);\n source = weakest(source, \"author\");\n }\n });\n table.rows.push({ values, source: source ?? \"author\" });\n }\n return statement.tuples.length;\n }\n\n private matching(\n table: Table,\n statement: Select | Delete | Update,\n params: readonly unknown[]\n ): StoredRow[] {\n return table.rows.filter((row) =>\n statement.where.every((p) => {\n const cell = row.values[p.column];\n return p.values.some((v) => looselyEqual(cell, literal(v, params)));\n })\n );\n }\n\n private select(statement: Select, params: readonly unknown[]): ReadResult {\n if (statement.table === null) {\n const row: OxyFunctionRow = {};\n for (const item of statement.items) {\n if (item.kind === \"literal\") row[item.alias] = literal(item.raw, params);\n else\n throw contextError(\n `SELECT without FROM can only project literals: ${JSON.stringify(item)}`\n );\n }\n return { rows: [row], source: \"author\" };\n }\n const table = this.require(statement.table, statement);\n let matched = this.matching(table, statement, params);\n if (statement.items.some((i) => i.kind === \"count\")) {\n const alias =\n statement.items.find((i): i is { kind: \"count\"; alias: string } => i.kind === \"count\")\n ?.alias ?? \"count(*)\";\n return { rows: [{ [alias]: matched.length }], source: matched[0]?.source ?? null };\n }\n if (statement.orderBy) {\n const { column, desc } = statement.orderBy;\n matched = [...matched].sort(\n (a, b) => compare(a.values[column], b.values[column]) * (desc ? -1 : 1)\n );\n }\n if (statement.limit !== null) matched = matched.slice(0, statement.limit);\n let source: RowSource | null = null;\n const rows = matched.map((stored) => {\n source = weakest(source, stored.source);\n const out: OxyFunctionRow = {};\n for (const item of statement.items) {\n if (item.kind === \"all\") Object.assign(out, materialise(stored.values));\n else if (item.kind === \"column\")\n out[item.alias] = materialise({ v: stored.values[item.column] }).v;\n else if (item.kind === \"literal\") out[item.alias] = literal(item.raw, params);\n }\n return out;\n });\n return { rows, source };\n }\n\n private remove(statement: Delete, params: readonly unknown[]): number {\n const table = this.require(statement.table, statement);\n const gone = new Set(this.matching(table, statement, params));\n table.rows = table.rows.filter((r) => !gone.has(r));\n return gone.size;\n }\n\n private update(statement: Update, params: readonly unknown[]): number {\n const table = this.require(statement.table, statement);\n const hit = this.matching(table, statement, params);\n for (const row of hit) {\n for (const { column, raw } of statement.set) {\n row.values[column] = literal(raw, params);\n row.source = \"author\";\n }\n }\n return hit.length;\n }\n}\n\n/** A declared typed table: insert SQL-side values, rendered through the zoo. */\nexport class TypedTable {\n constructor(\n private readonly store: TableStore,\n readonly name: string\n ) {}\n\n /** Insert rows of SQL-side values (`{ id: \"42\", at: \"'2024-03-10 12:34:56'\" }`). */\n insert(rows: Record<string, string>[]): this {\n for (const row of rows) {\n const columns = Object.keys(row);\n const values = columns.map((c) => row[c]);\n this.store.exec(\n `INSERT INTO ${this.name} (${columns.join(\", \")}) VALUES (${values.join(\", \")})`\n );\n }\n return this;\n }\n}\n\n/** A stored row as a read returns it; a refusal cell throws the host's sentence. */\nfunction materialise(values: Record<string, unknown | ZooRefusal>): OxyFunctionRow {\n const out: OxyFunctionRow = {};\n for (const [k, v] of Object.entries(values)) {\n if (v instanceof ZooRefusal) throw refusalOf(v);\n out[k] = v;\n }\n return out;\n}\n\n/** Marker so the context can wrap a zoo refusal as the OLTP surface's `HostError`. */\nexport class ZooRefusalError extends Error {\n constructor(readonly refusal: ZooRefusal) {\n super(refusal.message());\n this.name = \"ZooRefusalError\";\n }\n}\n\nconst refusalOf = (r: ZooRefusal) => new ZooRefusalError(r);\n\nfunction looselyEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n return String(a) === String(b);\n}\n\nfunction compare(a: unknown, b: unknown): number {\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n return String(a).localeCompare(String(b));\n}\n\n// ── the other stores ─────────────────────────────────────────────────────────\n\n/** One object in the app's storage silo, body as base64. */\nexport interface StoredObject {\n key: string;\n body: string;\n contentType: string | null;\n size: number;\n lastModified: string;\n}\n\n/** What `ctx.fetch` should answer for a URL: a result, or a function of the call. */\nexport type FetchAnswer =\n | { status?: number; body?: string; encoding?: \"utf8\" | \"base64\" }\n | ((\n url: string,\n init: RequestInit & { encoding?: \"utf8\" | \"base64\" }\n ) => {\n status?: number;\n body?: string;\n encoding?: \"utf8\" | \"base64\";\n });\n\n/** The `ctx.fetch` side: answers by URL, and what was received. */\nexport class FetchStore {\n readonly received: { url: string; init: RequestInit & { encoding?: \"utf8\" | \"base64\" } }[] = [];\n private readonly answers: { match: string | RegExp; answer: FetchAnswer }[] = [];\n\n /** Answer every URL equal to `match` (or matching the RegExp) with `answer`. */\n on(match: string | RegExp, answer: FetchAnswer): this {\n this.answers.push({ match, answer });\n return this;\n }\n\n answerFor(url: string): FetchAnswer | undefined {\n return this.answers.find(({ match }) =>\n typeof match === \"string\" ? match === url : match.test(url)\n )?.answer;\n }\n}\n","// `createTestContext(manifest, options)`: a typed `OxyFunctionContext` whose\n// every member is the runtime's `__buildCtx` shape (`runtime.rs`), backed by\n// in-memory stores and refusing exactly where — and in the words — the host\n// refuses. Every host op the function makes is recorded as a `HostCall`.\n//\n// Each member mirrors `__buildCtx` one for one: the ctx member packs its\n// arguments into the op's payload, the \"host op\" answers (a gate, a store, an\n// override), and the member post-processes as the runtime does (`oltp.query`\n// returns `r.rows`, `airhouse.append` returns `r.rowCount`, …). An `override`\n// therefore replaces the HOST OP — gates included, as `fake.raw.warehouse.upsert\n// = async () => ({})` did on the canary — and answers with the JSON the host\n// would reply, not the value the ctx member returns.\n\nimport * as nodeCryptoImport from \"node:crypto\";\nimport type {\n OxyFunctionContext,\n OxyFunctionRow,\n OxyFunctionUser,\n OxyOrgAssignment,\n OxyOrgPlace,\n OxyTransaction\n} from \"../custom-app/function-context\";\nimport { isSafeOutbound } from \"./fetch-rules\";\nimport { type FunctionGates, MAX_SCHEMA_NAME_LEN, type ManifestLike, readGates } from \"./gates\";\nimport {\n DIALECTS,\n type Dialect,\n FETCH_MAX_BYTES,\n type HostOp,\n MAX_OPEN_TRANSACTIONS,\n REFUSALS,\n SURFACES\n} from \"./host-contract\";\nimport { contextError, hostError, isHostError, refuse } from \"./host-error\";\nimport { runWithoutIsolateGlobals } from \"./run\";\nimport { FetchStore, type StoredObject, TableStore, ZooRefusalError } from \"./stores\";\nimport type { RowSource } from \"./zoo\";\n\n// Captured at load: the stores are \"the host\", so they keep Node's facilities\n// even while `t.run(fn)` has removed them from the function under test.\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst nodeBtoa = globalThis.btoa;\nconst nodeAtob = globalThis.atob;\n\n/** The two `node:crypto` members `ctx.crypto` needs.\n *\n * A static import, not `process.getBuiltinModule(\"node:crypto\")`: the module\n * graph is evaluated once, long before any `t.run` can remove `process`, so\n * the reason to reach for that API does not apply — and it costs Node 20.16,\n * while this package says it runs on 18. */\ninterface NodeCryptoLike {\n createHmac(\n algorithm: string,\n key: string\n ): { update(data: string): { digest(encoding: \"hex\" | \"base64\"): string } };\n timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;\n}\nconst nodeCryptoModule: NodeCryptoLike = nodeCryptoImport as unknown as NodeCryptoLike;\n\n/** One database the project configures, as the context needs to know it. */\nexport interface TestDatabase {\n dialect: Dialect;\n /**\n * `destination_kind`'s mapping (`host/destinations.rs`): `airhouse` /\n * `airhouse_managed` may be written; `postgres_managed` is the org's OLTP\n * store, refused; anything else is a customer warehouse, read-only without a\n * `customerWarehouseWrites` reason. An unknown kind fails closed the same way.\n */\n kind: \"airhouse\" | \"airhouse_managed\" | \"postgres_managed\" | \"customer\";\n}\n\nexport interface TestContextOptions {\n /** The `functions.<name>` entry whose capabilities gate the context. */\n function: string;\n /** The project's databases by name; `ctx.query` reaches `defaultDatabase` or the first. */\n databases?: Record<string, TestDatabase>;\n defaultDatabase?: string;\n /** `ctx.env`. */\n env?: Record<string, string>;\n /** `ctx.user`, over a default org member. */\n user?: Partial<OxyFunctionUser>;\n}\n\n/** One host op the function made, as the context recorded it. */\nexport interface HostCall {\n op: HostOp;\n /** The op's payload as `__buildCtx` packs it: `{ database, table, rows }`, `{ sql, params }`, … */\n args: Record<string, unknown>;\n /** `refused`: a `HostError` the context threw; `threw`: any other error, an override's included. */\n outcome: \"ok\" | \"refused\" | \"threw\";\n /** The full error message — `\"<surface>: <host message>\"` for a refusal. */\n message?: string;\n /** What the host op replied, on `ok`. */\n result?: unknown;\n /** For a read answered from a store: the weakest source among its rows. */\n source?: RowSource;\n}\n\n/** The host op behind a ctx member: answers with what the host would reply. */\nexport type HostOpImpl = (args: Record<string, unknown>) => Promise<unknown> | unknown;\n\ntype Person = { id: string; name: string; role: string | null; kind: \"member\" | \"frontline\" };\n\n/** The stores, for a test to seed and inspect. */\nexport interface TestState {\n warehouse(database: string): TableStore;\n readonly oltp: TableStore;\n readonly airhouse: TableStore;\n readonly storage: Map<string, StoredObject>;\n readonly secrets: Map<string, string>;\n readonly emails: Record<string, unknown>[];\n readonly fetch: FetchStore;\n readonly org: { people: Person[]; places: OxyOrgPlace[]; assignments: OxyOrgAssignment[] };\n readonly semantic: { on(answer: (spec: Record<string, unknown>) => unknown): void };\n readonly airway: { runs: { pipelineRef: string; variables: unknown }[] };\n}\n\nexport interface TestContext {\n ctx: OxyFunctionContext;\n /** Every host op made, in order. */\n readonly calls: readonly HostCall[];\n /** The de-duplicated first-call order of op names. */\n ops(): HostOp[];\n callsTo(op: HostOp): HostCall[];\n /** Replace one host op for this context; still recorded. */\n override(op: HostOp, impl: HostOpImpl): void;\n /** Evaluate `fn` with the isolate's absent globals absent (`run.ts`). */\n run<T>(fn: () => Promise<T> | T): Promise<T>;\n readonly state: TestState;\n readonly gates: FunctionGates;\n}\n\nconst DEFAULT_USER: OxyFunctionUser = {\n id: \"user-1\",\n email: \"author@example.test\",\n orgId: \"org-1\",\n name: \"Author\",\n appRole: \"member\",\n orgRole: \"member\",\n teams: [],\n kind: \"user\",\n reach: { everywhere: true, via: \"org-member\", locations: [] }\n};\n\nexport function createTestContext(\n manifest: ManifestLike,\n options: TestContextOptions\n): TestContext {\n const gates = readGates(manifest, options.function);\n const manifestSlug = typeof manifest.slug === \"string\" ? manifest.slug : \"\";\n const databases = options.databases ?? {};\n const calls: HostCall[] = [];\n const overrides = new Map<HostOp, HostOpImpl>();\n const warehouses = new Map<string, TableStore>();\n let semanticAnswer: ((spec: Record<string, unknown>) => unknown) | null = null;\n\n const state: TestState = {\n warehouse(database) {\n const db = databases[database];\n if (!db) throw contextError(`no database \"${database}\" in options.databases`);\n let store = warehouses.get(database);\n if (!store) {\n store = new TableStore(db.dialect, \"warehouse\");\n warehouses.set(database, store);\n }\n return store;\n },\n oltp: new TableStore(\"postgres\", \"oltp\", gates.writerSchema),\n airhouse: new TableStore(\"duckdb\", \"warehouse\", gates.writerSchema),\n storage: new Map(),\n secrets: new Map(),\n emails: [],\n fetch: new FetchStore(),\n org: { people: [], places: [], assignments: [] },\n semantic: {\n on: (answer) => {\n semanticAnswer = answer;\n }\n },\n airway: { runs: [] }\n };\n\n /** Run one host op: the override or `impl`, recorded either way. */\n async function op(\n name: HostOp,\n args: Record<string, unknown>,\n impl: HostOpImpl\n ): Promise<unknown> {\n const call: HostCall = { op: name, args, outcome: \"ok\" };\n calls.push(call);\n try {\n const result = await (overrides.get(name) ?? impl)(args);\n if (result && typeof result === \"object\" && \"__source\" in result) {\n const { __source } = result as { __source: RowSource | null };\n if (__source) call.source = __source;\n const rest = Array.isArray(result)\n ? [...result]\n : Object.fromEntries(Object.entries(result).filter(([k]) => k !== \"__source\"));\n call.result = rest;\n return rest;\n }\n call.result = result;\n return result;\n } catch (err) {\n const thrown =\n err instanceof ZooRefusalError\n ? hostError(name.startsWith(\"tx.\") ? SURFACES.tx : SURFACES.oltp, err.message)\n : err;\n call.outcome = isHostError(thrown) ? \"refused\" : \"threw\";\n call.message = thrown instanceof Error ? thrown.message : String(thrown);\n throw thrown;\n }\n }\n\n // ── gates, in the host's order ───────────────────────────────────────────\n\n /** `check_write_destination` then `destination_write_policy` (`host.rs`, `destinations.rs`). */\n function checkWriteDestination(\n surface: string,\n database: string,\n transaction: boolean\n ): TestDatabase {\n if (!gates.destinations.includes(database)) {\n throw refuse(surface, REFUSALS.destinationNotDeclared, { database });\n }\n const db = databases[database];\n if (!db) throw refuse(surface, REFUSALS.databaseNotConfigured, { database });\n switch (db.kind) {\n case \"airhouse\":\n case \"airhouse_managed\":\n return db;\n case \"postgres_managed\":\n throw refuse(surface, REFUSALS.managedOltpWrite, { database });\n default: {\n if (gates.customerWarehouseWrites[database]) return db;\n const words: string[] = [REFUSALS.customerWarehouseWrite.refusal];\n if (transaction) words.push(REFUSALS.customerWarehouseTransaction.refusal);\n throw hostError(surface, words.join(\"\").replace(/\\{database\\}/g, database));\n }\n }\n }\n\n /**\n * The host's `WriterCapability` has three states, not two: enabled, disabled,\n * and enabled-but-the-slug-cannot-back-a-schema. Gating on the boolean alone\n * let an app whose slug derives no schema pass here and fail closed in\n * production — the exact shape this module exists to catch.\n */\n function requireWriterSchema(surface: string, store: \"OLTP\" | \"Airhouse\"): void {\n if (gates.writerSchema === null) {\n throw refuse(surface, REFUSALS.slugCannotBackASchema, {\n slug: manifestSlug,\n store,\n max: MAX_SCHEMA_NAME_LEN\n });\n }\n }\n\n function requireOltp(surface: string): TableStore {\n if (!gates.oltp) throw refuse(surface, REFUSALS.oltp);\n requireWriterSchema(surface, \"OLTP\");\n return state.oltp;\n }\n\n function requireAirhouse(): TableStore {\n if (!gates.airhouse) throw refuse(SURFACES.airhouse, REFUSALS.airhouse);\n requireWriterSchema(SURFACES.airhouse, \"Airhouse\");\n return state.airhouse;\n }\n\n function requireStorage(opName: string): void {\n const needsWrite = [\"getUploadUrl\", \"put\", \"delete\", \"copy\"].includes(opName);\n const needsRead = [\"getDownloadUrl\", \"get\", \"head\", \"list\", \"copy\"].includes(opName);\n if (needsWrite && !gates.storageWrite) throw refuse(SURFACES.storage, REFUSALS.storageWrite);\n if (needsRead && !gates.storageRead) throw refuse(SURFACES.storage, REFUSALS.storageRead);\n }\n\n function defaultDatabase(): string {\n const name = options.defaultDatabase ?? Object.keys(databases)[0];\n if (!name) throw refuse(SURFACES.query, REFUSALS.noDefaultDatabase);\n return name;\n }\n\n /** `oltp_statement`: `params` absent or an array, else refused. */\n function oltpParams(surface: string, params: unknown): unknown[] {\n if (params === undefined || params === null) return [];\n if (Array.isArray(params)) return params;\n throw refuse(surface, REFUSALS.oltpParamsNotArray);\n }\n\n const read = (store: TableStore, sql: string, params: unknown[] = []) => {\n const { rows, source } = store.query(sql, params);\n return { rows, truncated: false, __source: source };\n };\n\n // ── ctx.tx / ctx.oltp.tx: the runtime's `__runTx` bracket ────────────────\n\n let open = 0;\n let nextTxId = 0;\n\n async function runTx<T>(\n signature: string,\n label: string,\n beginOp: \"tx.begin\" | \"tx.begin_oltp\",\n beginPayload: Record<string, unknown>,\n fn: (tx: OxyTransaction) => Promise<T> | T\n ): Promise<T> {\n if (typeof fn !== \"function\") {\n throw new TypeError(\n REFUSALS.transactionFnNotFunction.refusal.replace(\"{signature}\", signature)\n );\n }\n let store: TableStore | null = null;\n // `open++` lives inside the begin impl, which `t.override(\"tx.begin\", …)`\n // replaces — so the unconditional `open--` below used to run for a\n // transaction that never incremented, leaving the counter negative and the\n // MAX_OPEN refusal permanently disarmed for the rest of the context.\n let incremented = false;\n const { id } = (await op(beginOp, beginPayload, () => {\n if (beginOp === \"tx.begin\") {\n const database = String(beginPayload.database);\n const db = checkWriteDestination(SURFACES.tx, database, true);\n if (!DIALECTS[db.dialect].opensTransactions) {\n const cause = REFUSALS.transactionUnsupported.refusal.replace(\n \"{backend}\",\n DIALECTS[db.dialect].name\n );\n throw refuse(SURFACES.tx, REFUSALS.transactionOpen, { database, e: cause });\n }\n store = state.warehouse(database);\n } else {\n store = requireOltp(SURFACES.tx);\n }\n if (open >= MAX_OPEN_TRANSACTIONS) {\n throw refuse(SURFACES.tx, REFUSALS.transactionsOpen, { MAX_OPEN: MAX_OPEN_TRANSACTIONS });\n }\n open++;\n incremented = true;\n return { id: ++nextTxId };\n })) as { id: number };\n // `store` is set inside the begin op; an override of `tx.begin` skips that,\n // so fall back to the store the payload names.\n const table: TableStore =\n (store as TableStore | null) ??\n (beginOp === \"tx.begin_oltp\"\n ? state.oltp\n : databases[String(beginPayload.database)]\n ? state.warehouse(String(beginPayload.database))\n : new TableStore(\"postgres\", \"warehouse\"));\n const restore = table.snapshot();\n let closed = false;\n const live = (what: string) => {\n if (closed) {\n throw hostError(\n label,\n REFUSALS.transactionFinished.refusal.replace(\"{label}\", label).replace(\"{what}\", what)\n );\n }\n };\n const handle: OxyTransaction = {\n query: async (sql, params) => {\n live(\"query\");\n const r = (await op(\"tx.query\", { id, sql: String(sql), params: params ?? [] }, (a) =>\n read(table, String(a.sql), oltpParams(SURFACES.tx, a.params))\n )) as { rows: OxyFunctionRow[] };\n return r.rows;\n },\n exec: async (sql, params) => {\n live(\"exec\");\n const r = (await op(\"tx.exec\", { id, sql: String(sql), params: params ?? [] }, (a) => ({\n rowCount: table.exec(String(a.sql), oltpParams(SURFACES.tx, a.params))\n }))) as { rowCount: number };\n return r.rowCount;\n }\n };\n let result: T;\n try {\n result = await fn(handle);\n } catch (err) {\n closed = true;\n if (incremented) open--;\n try {\n await op(\"tx.rollback\", { id }, () => {\n restore();\n return {};\n });\n } catch {\n // Swallowed, as `__runTx` swallows it: the author's error is the one to see.\n }\n throw err;\n }\n closed = true;\n if (incremented) open--;\n await op(\"tx.commit\", { id }, () => ({}));\n return result;\n }\n\n // ── ctx ──────────────────────────────────────────────────────────────────\n\n const ctx: OxyFunctionContext = {\n user: { ...DEFAULT_USER, ...options.user },\n env: { ...(options.env ?? {}) },\n log: () => {},\n crypto: nodeCrypto(),\n query: async (sql) =>\n (await op(\"query\", { sql: String(sql) }, (a) =>\n read(state.warehouse(defaultDatabase()), String(a.sql))\n )) as {\n rows: OxyFunctionRow[];\n truncated: boolean;\n },\n queryStream: async function* (sql, opts) {\n const batchSize = opts?.batchSize || 1000;\n const rows = (await op(\"query_stream\", { sql: String(sql) }, (a) => {\n const { rows, __source } = read(state.warehouse(defaultDatabase()), String(a.sql));\n return Object.assign(rows, { __source });\n })) as OxyFunctionRow[];\n for (let i = 0; i < rows.length; i += batchSize) yield rows.slice(i, i + batchSize);\n },\n fetch: (url, init) =>\n op(\"fetch\", { url, init: init ?? {} }, (a) =>\n fetchOp(String(a.url), (a.init ?? {}) as NonNullable<typeof init>)\n ) as ReturnType<OxyFunctionContext[\"fetch\"]>,\n warehouse: {\n insert: (database, table, rows) =>\n op(\"warehouse.insert\", { database, table, rows }, (a) => {\n checkWriteDestination(SURFACES.warehouse, String(a.database), false);\n state.warehouse(String(a.database)).append(String(a.table), a.rows as OxyFunctionRow[]);\n return { ok: true };\n }),\n exec: (database, sql) =>\n op(\"warehouse.exec\", { database, sql }, (a) => {\n checkWriteDestination(SURFACES.warehouse, String(a.database), false);\n state.warehouse(String(a.database)).exec(String(a.sql));\n return { ok: true };\n }),\n upsert: (database, table, rows, conflictColumns) =>\n op(\"warehouse.upsert\", { database, table, rows, conflictColumns }, (a) => {\n const database = String(a.database);\n const db = checkWriteDestination(SURFACES.warehouse, database, false);\n if (!DIALECTS[db.dialect].parsesOnConflict) {\n throw refuse(SURFACES.warehouse, REFUSALS.upsertUnsupported, {\n dialect: DIALECTS[db.dialect].name\n });\n }\n if (db.kind === \"airhouse\" || db.kind === \"airhouse_managed\") {\n // In the CONTEXT'S OWN WORDS, not the host's (§7, answer 6): the host lets\n // this statement through and DuckLake refuses it at runtime, because a\n // DuckLake table cannot carry the primary key ON CONFLICT needs. A fake\n // that resolved here would pass where production fails.\n throw contextError(\n `@oxy-hq/sdk/testing: ctx.warehouse.upsert on \"${database}\" would be refused by the ENGINE, not the host. Airhouse is DuckLake, and a DuckLake table cannot carry the primary key or unique constraint that INSERT … ON CONFLICT needs, so the statement the host lets through fails at runtime. Use ctx.airhouse.append and keep one row per id on read. (These are the test context's words, not a host refusal — assert that the call was refused, not on this text, which may be reworded.)`\n );\n }\n state.warehouse(database).append(String(a.table), a.rows as OxyFunctionRow[]);\n return { ok: true };\n }),\n query: (database, sql) =>\n op(\"warehouse.query\", { database, sql }, (a) => {\n const database = String(a.database);\n if (!databases[database])\n throw refuse(SURFACES.warehouse, REFUSALS.databaseNotConfigured, { database });\n return read(state.warehouse(database), String(a.sql));\n }) as Promise<{ rows: OxyFunctionRow[]; truncated: boolean }>\n },\n tx: (database, fn) =>\n runTx(\"ctx.tx(database, fn)\", SURFACES.tx, \"tx.begin\", { database: String(database) }, fn),\n oltp: {\n tx: (fn) => runTx(\"ctx.oltp.tx(fn)\", \"ctx.oltp.tx\", \"tx.begin_oltp\", {}, fn),\n query: async (sql, params) => {\n const r = (await op(\"oltp.query\", { sql: String(sql), params: params ?? [] }, (a) =>\n read(requireOltp(SURFACES.oltp), String(a.sql), oltpParams(SURFACES.oltp, a.params))\n )) as { rows: OxyFunctionRow[] };\n return r.rows;\n },\n exec: async (sql, params) => {\n const r = (await op(\"oltp.exec\", { sql: String(sql), params: params ?? [] }, (a) => ({\n rowCount: requireOltp(SURFACES.oltp).exec(\n String(a.sql),\n oltpParams(SURFACES.oltp, a.params)\n )\n }))) as { rowCount: number };\n return r.rowCount;\n }\n },\n airhouse: {\n schema: gates.airhouse ? gates.writerSchema : null,\n query: (sql) =>\n op(\"airhouse.query\", { sql: String(sql) }, (a) =>\n read(requireAirhouse(), String(a.sql))\n ) as Promise<{\n rows: OxyFunctionRow[];\n truncated: boolean;\n }>,\n exec: async (sql) => {\n await op(\"airhouse.exec\", { sql: String(sql) }, (a) => {\n requireAirhouse().exec(String(a.sql));\n return { ok: true };\n });\n },\n append: async (table, rows) => {\n const r = (await op(\"airhouse.append\", { table: String(table), rows }, (a) => ({\n rowCount: requireAirhouse().append(String(a.table), a.rows as OxyFunctionRow[])\n }))) as { rowCount: number };\n return r.rowCount;\n }\n },\n secrets: {\n set: async (key, value) => {\n await op(\"secrets.set\", { key: String(key), value: String(value) }, (a) => {\n if (!gates.secretsWrite) throw refuse(SURFACES.secretsSet, REFUSALS.secretsWrite);\n state.secrets.set(String(a.key), String(a.value));\n return null;\n });\n }\n },\n email: {\n send: (input) =>\n op(\"email.send\", { ...input }, (a) => {\n if (!gates.emailSend) throw refuse(SURFACES.emailSend, REFUSALS.emailSend);\n state.emails.push(a);\n return { messageId: `message-${state.emails.length}` };\n }) as Promise<{ messageId: string }>\n },\n org: {\n people: () =>\n op(\"org.people\", {}, () => {\n if (!gates.orgRead) throw refuse(SURFACES.orgPeople, REFUSALS.orgPeople);\n return { people: [...state.org.people], total: state.org.people.length };\n }) as ReturnType<OxyFunctionContext[\"org\"][\"people\"]>,\n places: () =>\n op(\"org.places\", {}, () => {\n if (!gates.orgRead)\n throw refuse(SURFACES.orgPlaces, REFUSALS.orgMember, { member: \"places\" });\n return { total: state.org.places.length, places: [...state.org.places] };\n }) as Promise<{ places: OxyOrgPlace[]; total: number }>,\n assignments: () =>\n op(\"org.assignments\", {}, () => {\n if (!gates.orgRead)\n throw refuse(SURFACES.orgAssignments, REFUSALS.orgMember, { member: \"assignments\" });\n return { total: state.org.assignments.length, assignments: [...state.org.assignments] };\n }) as Promise<{ assignments: OxyOrgAssignment[]; total: number }>\n },\n storage: storageApi(),\n semantic: {\n query: (spec) =>\n op(\"semantic.query\", { spec }, (a) => {\n if (!semanticAnswer) {\n throw contextError(\n \"ctx.semantic.query has no answer registered: the zoo pins no semantic payload, so supply one with t.state.semantic.on((spec) => result)\"\n );\n }\n return semanticAnswer(a.spec as Record<string, unknown>);\n })\n },\n airway: {\n run: (pipelineRef, variables) =>\n op(\n \"airway.run\",\n { pipelineRef: String(pipelineRef), variables: variables ?? null },\n (a) => {\n state.airway.runs.push({ pipelineRef: String(a.pipelineRef), variables: a.variables });\n return { runId: `run-${state.airway.runs.length}` };\n }\n ) as Promise<{ runId: string }>\n }\n };\n\n // ── ctx.fetch: `is_safe_outbound`, headers, the byte cap ─────────────────\n\n function fetchOp(url: string, init: RequestInit & { encoding?: \"utf8\" | \"base64\" }) {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch (e) {\n throw refuse(SURFACES.fetch, REFUSALS.fetchInvalidUrl, {\n e: e instanceof Error ? e.message : String(e)\n });\n }\n if (!isSafeOutbound(parsed)) throw refuse(SURFACES.fetch, REFUSALS.fetchBlocked, { url });\n for (const [k, v] of Object.entries(headersOf(init.headers))) {\n if (!/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(k))\n throw refuse(SURFACES.fetch, REFUSALS.fetchInvalidHeaderName, { k });\n if (/[\\r\\n\\0]/.test(v)) throw refuse(SURFACES.fetch, REFUSALS.fetchInvalidHeaderValue, { k });\n }\n state.fetch.received.push({ url, init });\n const answer = state.fetch.answerFor(url);\n if (answer === undefined) {\n throw contextError(\n `ctx.fetch has no answer for ${url}: register one with t.state.fetch.on(url, { status, body }) — nothing here reaches the network`\n );\n }\n const reply = typeof answer === \"function\" ? answer(url, init) : answer;\n const fixture = reply.body ?? \"\";\n const fixtureIsBase64 = reply.encoding === \"base64\";\n const max = gates.fetchMaxBytes ?? FETCH_MAX_BYTES;\n const len = fixtureIsBase64 ? base64ByteLength(fixture) : encoder.encode(fixture).length;\n if (len > max) throw refuse(SURFACES.fetch, REFUSALS.fetchTooLarge, { len, max_bytes: max });\n // The host encodes the bytes it received (`host.rs`): `utf8` is a lossy\n // string of them, `base64` is them encoded. It does not hand back what it\n // was given under a different label — reading a binary fixture as utf8, or\n // a text one as base64, changes the body. `ctx.storage.get` converts both\n // ways, and this is the gotcha `product-context.md` names, so convert here.\n if (init.encoding !== undefined && init.encoding !== \"utf8\" && init.encoding !== \"base64\") {\n throw contextError(\n `ctx.fetch: unknown encoding '${String(init.encoding)}' (expected 'utf8' or 'base64')`\n );\n }\n const wantBase64 = init.encoding === \"base64\";\n const body = wantBase64\n ? fixtureIsBase64\n ? fixture\n : utf8ToBase64(fixture)\n : fixtureIsBase64\n ? base64ToUtf8(fixture)\n : fixture;\n return { status: reply.status ?? 200, body, encoding: wantBase64 ? \"base64\" : \"utf8\" };\n }\n\n // ── ctx.storage: a Map with an offset cursor, as the canary's fake was ────\n\n function storageApi(): OxyFunctionContext[\"storage\"] {\n const now = () => new Date().toISOString();\n const put = (key: string, body: string, contentType: string | null): StoredObject => {\n const object = {\n key,\n body,\n contentType,\n size: base64ByteLength(body),\n lastModified: now()\n };\n state.storage.set(key, object);\n return object;\n };\n const storageOp = (name: string, args: Record<string, unknown>, impl: HostOpImpl) =>\n op(`storage.${name}` as HostOp, args, (a) => {\n requireStorage(name);\n return impl(a);\n });\n return {\n getUploadUrl: (opts) =>\n storageOp(\"getUploadUrl\", { ...opts }, (a) => {\n const pathname = String(a.pathname ?? `uploads/${String(a.filename ?? \"upload\")}`);\n const key = `${pathname.replace(/(\\.[^.]*)?$/, `-${randomSuffix()}$1`)}`;\n return { url: `https://storage.example.test/put/${key}`, key, expiresAt: now() };\n }) as ReturnType<OxyFunctionContext[\"storage\"][\"getUploadUrl\"]>,\n getDownloadUrl: (key, opts) =>\n storageOp(\"getDownloadUrl\", { key: String(key), ...opts }, (a) => ({\n url: `https://storage.example.test/get/${String(a.key)}`,\n expiresAt: now()\n })) as ReturnType<OxyFunctionContext[\"storage\"][\"getDownloadUrl\"]>,\n put: (pathname, body, opts) =>\n storageOp(\"put\", { pathname: String(pathname), body: String(body), ...opts }, (a) => {\n const key = a.addRandomSuffix\n ? String(a.pathname).replace(/(\\.[^.]*)?$/, `-${randomSuffix()}$1`)\n : String(a.pathname);\n if (state.storage.has(key) && !a.allowOverwrite) {\n throw hostError(\n SURFACES.storage,\n `put: \"${key}\" already exists (pass allowOverwrite: true)`\n );\n }\n const base64 = a.encoding === \"base64\" ? String(a.body) : utf8ToBase64(String(a.body));\n const stored = put(key, base64, (a.contentType as string | undefined) ?? null);\n return {\n key,\n size: stored.size,\n contentType: stored.contentType ?? \"application/octet-stream\"\n };\n }) as ReturnType<OxyFunctionContext[\"storage\"][\"put\"]>,\n get: (key, opts) =>\n storageOp(\"get\", { key: String(key), ...opts }, (a) => {\n const object = state.storage.get(String(a.key));\n if (!object) return null;\n const base64 = a.encoding === \"base64\";\n return {\n body: base64 ? object.body : base64ToUtf8(object.body),\n contentType: object.contentType,\n size: object.size,\n encoding: base64 ? \"base64\" : \"utf8\"\n };\n }) as ReturnType<OxyFunctionContext[\"storage\"][\"get\"]>,\n head: (key) =>\n storageOp(\"head\", { key: String(key) }, (a) => {\n const object = state.storage.get(String(a.key));\n return object\n ? {\n key: object.key,\n size: object.size,\n contentType: object.contentType,\n lastModified: object.lastModified\n }\n : null;\n }) as ReturnType<OxyFunctionContext[\"storage\"][\"head\"]>,\n list: (opts) =>\n storageOp(\"list\", { ...opts }, (a) => {\n const prefix = String(a.prefix ?? \"\");\n const limit = Number(a.limit ?? 1000);\n const offset = a.cursor ? Number(a.cursor) : 0;\n const keys = [...state.storage.keys()].filter((k) => k.startsWith(prefix)).sort();\n const page = keys.slice(offset, offset + limit).map((k) => {\n const o = state.storage.get(k) as StoredObject;\n return {\n key: o.key,\n size: o.size,\n contentType: o.contentType,\n lastModified: o.lastModified\n };\n });\n const hasMore = offset + limit < keys.length;\n return { objects: page, cursor: hasMore ? String(offset + limit) : null, hasMore };\n }) as ReturnType<OxyFunctionContext[\"storage\"][\"list\"]>,\n delete: (keyOrKeys) =>\n storageOp(\n \"delete\",\n Array.isArray(keyOrKeys) ? { keys: keyOrKeys.map(String) } : { key: String(keyOrKeys) },\n (a) => {\n const keys = Array.isArray(a.keys) ? (a.keys as string[]) : [String(a.key)];\n for (const k of keys) state.storage.delete(k);\n return { deleted: keys.length };\n }\n ) as ReturnType<OxyFunctionContext[\"storage\"][\"delete\"]>,\n copy: (fromKey, toPathname, opts) =>\n storageOp(\n \"copy\",\n { fromKey: String(fromKey), toPathname: String(toPathname), ...opts },\n (a) => {\n const from = state.storage.get(String(a.fromKey));\n if (!from)\n throw hostError(SURFACES.storage, `copy: \"${String(a.fromKey)}\" does not exist`);\n const key = String(a.toPathname);\n if (state.storage.has(key) && !a.allowOverwrite) {\n throw hostError(\n SURFACES.storage,\n `copy: \"${key}\" already exists (pass allowOverwrite: true)`\n );\n }\n const stored = put(key, from.body, from.contentType);\n return {\n key,\n size: stored.size,\n contentType: stored.contentType ?? \"application/octet-stream\"\n };\n }\n ) as ReturnType<OxyFunctionContext[\"storage\"][\"copy\"]>\n };\n }\n\n return {\n ctx,\n calls,\n ops: () => [...new Set(calls.map((c) => c.op))],\n callsTo: (name) => calls.filter((c) => c.op === name),\n override: (name, impl) => {\n overrides.set(name, impl);\n },\n run: runWithoutIsolateGlobals,\n state,\n gates\n };\n}\n\nfunction headersOf(headers: HeadersInit | undefined): Record<string, string> {\n if (!headers) return {};\n if (Array.isArray(headers)) return Object.fromEntries(headers);\n if (typeof Headers !== \"undefined\" && headers instanceof Headers)\n return Object.fromEntries(headers.entries());\n return headers as Record<string, string>;\n}\n\nfunction randomSuffix(): string {\n return Math.random().toString(36).slice(2, 8);\n}\n\n/**\n * Bytes a base64 string decodes to. `length * 3 / 4` overstates by the padding,\n * which made `size` wrong by up to two bytes and fired the `ctx.fetch` cap early.\n */\nfunction base64ByteLength(base64: string): number {\n const s = base64.trim();\n if (s === \"\") return 0;\n const padding = s.endsWith(\"==\") ? 2 : s.endsWith(\"=\") ? 1 : 0;\n return Math.floor((s.length * 3) / 4) - padding;\n}\n\nfunction utf8ToBase64(text: string): string {\n const bytes = encoder.encode(text);\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return nodeBtoa(binary);\n}\n\nfunction base64ToUtf8(base64: string): string {\n const binary = nodeAtob(base64);\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n return decoder.decode(bytes);\n}\n\n/**\n * `ctx.crypto` over `node:crypto`: the same three synchronous members\n * `__buildCtx` binds, with the host's argument rules (`key` and `data`\n * required; `signature` and both sides of `timingSafeEqual` lenient). A digest\n * is ASCII, so the byte views need no `Buffer` — which `t.run` removes.\n */\nfunction nodeCrypto(): OxyFunctionContext[\"crypto\"] {\n const lib = (): NodeCryptoLike => nodeCryptoModule;\n const ascii = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0));\n const digest = (algorithm: string, key: string, data: string, encoding: \"hex\" | \"base64\") =>\n lib().createHmac(algorithm, key).update(data).digest(encoding);\n const same = (a: string, b: string) =>\n a !== \"\" && b !== \"\" && a.length === b.length && lib().timingSafeEqual(ascii(a), ascii(b));\n return {\n hmac: ({ algorithm, key, data, encoding }) => {\n if (key == null)\n throw new TypeError(\"ctx.crypto.hmac: `key` is required — is the secret set?\");\n if (data == null) throw new TypeError(\"ctx.crypto.hmac: `data` is required\");\n return digest(algorithm ?? \"sha256\", String(key), String(data), encoding ?? \"hex\");\n },\n verifyHmac: ({ algorithm, key, data, signature, encoding }) => {\n if (key == null)\n throw new TypeError(\"ctx.crypto.verifyHmac: `key` is required — is the secret set?\");\n if (data == null) throw new TypeError(\"ctx.crypto.verifyHmac: `data` is required\");\n const expected = digest(algorithm ?? \"sha256\", String(key), String(data), encoding ?? \"hex\");\n return same(String(signature ?? \"\"), expected);\n },\n timingSafeEqual: (a, b) => same(a == null ? \"\" : String(a), b == null ? \"\" : String(b))\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,WAAW;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAWA,MAAa,WAAW;CACtB,OAAO;CACP,aAAa;CACb,OAAO;CACP,WAAW;CACX,IAAI;CACJ,MAAM;CACN,UAAU;CACV,YAAY;CACZ,WAAW;CACX,SAAS;CACT,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,eAAe;CACf,WAAW;AACb;;;;;AAYA,MAAa,WAAW;CACtB,cAAc;EACZ,QAAQ;EAIR,SACE;CACJ;CACA,WAAW;E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