@aotter/mantle 0.2.0-alpha.8 → 0.2.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 (176) hide show
  1. package/README.md +26 -3
  2. package/dist/auth/adapter.js +10 -34
  3. package/dist/auth/admin.js +2 -5
  4. package/dist/auth/caller.js +0 -27
  5. package/dist/auth/consent.js +100 -0
  6. package/dist/auth/hardening.js +0 -7
  7. package/dist/auth/identity.js +0 -11
  8. package/dist/auth/oauth.js +0 -32
  9. package/dist/auth/resource-seeds.js +0 -2
  10. package/dist/auth/route-http.js +33 -0
  11. package/dist/auth/routes.js +8 -153
  12. package/dist/build/compiler.d.ts +19 -609
  13. package/dist/build/compiler.js +3 -6896
  14. package/dist/build/spec/domain/model/SqlIr.d.ts +2 -0
  15. package/dist/build/spec/domain/model/UserFields.d.ts +1 -0
  16. package/dist/bun/assets.js +0 -2
  17. package/dist/domain/adminOrder.js +0 -2
  18. package/dist/domain/columns.js +7 -20
  19. package/dist/domain/describe/chunk-SGMRVDGE.js +1 -0
  20. package/dist/domain/describe/index.js +1 -115
  21. package/dist/domain/describe/target-hash.js +1 -12
  22. package/dist/domain/entry.js +0 -14
  23. package/dist/domain/generated-tools.js +0 -1
  24. package/dist/domain/input.js +0 -2
  25. package/dist/domain/paging.js +0 -17
  26. package/dist/domain/recipes.js +10 -7
  27. package/dist/domain/userReferences.js +0 -1
  28. package/dist/domain/wireScalars.js +0 -6
  29. package/dist/infrastructure/adminEntries.js +10 -7
  30. package/dist/infrastructure/adminPaging.js +55 -57
  31. package/dist/infrastructure/artifacts.js +0 -4
  32. package/dist/infrastructure/authSchema.js +0 -9
  33. package/dist/infrastructure/bundle.js +17 -32
  34. package/dist/infrastructure/cli.js +25 -11
  35. package/dist/infrastructure/generate.js +18 -17
  36. package/dist/infrastructure/generateAuth.js +48 -5
  37. package/dist/infrastructure/help.js +55 -0
  38. package/dist/infrastructure/init.js +50 -0
  39. package/dist/infrastructure/inputs.js +0 -9
  40. package/dist/infrastructure/mounts.js +22 -0
  41. package/dist/infrastructure/wrangler.js +18 -9
  42. package/dist/kernel/authorization.js +0 -1
  43. package/dist/kernel/binds.d.ts +16 -7
  44. package/dist/kernel/binds.js +4 -10
  45. package/dist/kernel/caller-identity.d.ts +0 -3
  46. package/dist/kernel/caller-identity.js +0 -15
  47. package/dist/kernel/caller-mode.d.ts +4 -0
  48. package/dist/kernel/caller-mode.js +14 -0
  49. package/dist/kernel/contracts.d.ts +7 -11
  50. package/dist/kernel/contracts.js +8 -44
  51. package/dist/kernel/cron.js +0 -4
  52. package/dist/kernel/dialect/common.d.ts +0 -1
  53. package/dist/kernel/dialect/common.js +0 -3
  54. package/dist/kernel/dialect/postgres.js +0 -2
  55. package/dist/kernel/dialect/sqlite.js +1 -6
  56. package/dist/kernel/drain.js +2 -8
  57. package/dist/kernel/driver/bun-sqlite.js +0 -4
  58. package/dist/kernel/driver/d1.js +0 -1
  59. package/dist/kernel/driver/postgres.js +3 -17
  60. package/dist/kernel/driver/transaction-context.js +0 -1
  61. package/dist/kernel/email.js +0 -4
  62. package/dist/kernel/host-access.js +2 -3
  63. package/dist/kernel/host-caller.d.ts +1 -1
  64. package/dist/kernel/host-caller.js +3 -6
  65. package/dist/kernel/json-body.js +0 -2
  66. package/dist/kernel/mcp-apps.js +1 -6
  67. package/dist/kernel/mcp-call.js +0 -1
  68. package/dist/kernel/mcp-handler.js +3 -27
  69. package/dist/kernel/mcp.d.ts +5 -1
  70. package/dist/kernel/mcp.js +2 -6
  71. package/dist/kernel/media.js +0 -18
  72. package/dist/kernel/paging.js +1 -9
  73. package/dist/kernel/publishing.js +3 -4
  74. package/dist/kernel/r2-media.js +0 -7
  75. package/dist/kernel/rest-dispatch.js +0 -1
  76. package/dist/kernel/rest-router.js +2 -3
  77. package/dist/kernel/rest.js +0 -3
  78. package/dist/kernel/scalars.js +4 -11
  79. package/dist/kernel/search.js +0 -1
  80. package/dist/kernel/site.js +0 -2
  81. package/dist/kernel/store.d.ts +11 -1
  82. package/dist/kernel/store.js +21 -34
  83. package/dist/kernel/surface-failure.d.ts +10 -0
  84. package/dist/kernel/surface-failure.js +29 -0
  85. package/dist/kernel/surface.js +0 -3
  86. package/dist/kernel/sweep.js +0 -1
  87. package/dist/kernel/translations.js +0 -1
  88. package/dist/kernel/user-caller.js +2 -8
  89. package/dist/kernel/user-fields.d.ts +3 -2
  90. package/dist/kernel/user-fields.js +9 -9
  91. package/dist/kernel/validation.js +0 -8
  92. package/dist/kernel/web-gateway.js +0 -2
  93. package/dist/kernel/web-head.js +0 -1
  94. package/dist/kernel/web-index.js +39 -0
  95. package/dist/kernel/web-response.js +0 -1
  96. package/dist/kernel/web-serve.js +97 -0
  97. package/dist/kernel/web.d.ts +1 -1
  98. package/dist/kernel/web.js +10 -125
  99. package/dist/kernel/where.js +0 -6
  100. package/dist/usecase/adminBindings.js +30 -21
  101. package/dist/usecase/adminClient.js +0 -21
  102. package/dist/usecase/adminDescriptors.js +2 -9
  103. package/dist/usecase/generate.js +7 -12
  104. package/dist/usecase/handlers.js +0 -3
  105. package/dist/usecase/mcp-media.js +0 -1
  106. package/dist/usecase/mcp.js +0 -4
  107. package/dist/usecase/paging.js +1 -3
  108. package/dist/usecase/publishing.js +1 -5
  109. package/dist/usecase/rest.js +0 -1
  110. package/dist/usecase/site.js +0 -2
  111. package/dist/usecase/stores.js +4 -14
  112. package/dist/usecase/tool-version.js +0 -3
  113. package/dist/usecase/translations.js +0 -2
  114. package/dist/usecase/validation.js +8 -20
  115. package/docs/examples/README.md +13 -5
  116. package/docs/examples/app-shell/README.md +43 -8
  117. package/docs/examples/app-shell/accept.mjs +91 -0
  118. package/docs/examples/app-shell/gitignore +7 -0
  119. package/docs/examples/app-shell/package.json +7 -6
  120. package/docs/examples/app-shell/smoke-kit.mjs +29 -15
  121. package/docs/examples/app-shell/src/auth.ts +3 -2
  122. package/docs/examples/app-shell/src/routes.ts +6 -3
  123. package/docs/examples/app-shell/src/service.ts +4 -3
  124. package/docs/examples/club-events/README.md +7 -2
  125. package/docs/examples/club-events/manifests/club-events.yaml +22 -0
  126. package/docs/examples/club-events/smoke.mjs +7 -1
  127. package/docs/examples/club-events/src/handlers.ts +1 -1
  128. package/docs/examples/purchasing/README.md +12 -3
  129. package/docs/examples/purchasing/manifests/purchasing.yaml +36 -3
  130. package/docs/examples/purchasing/smoke.mjs +14 -0
  131. package/docs/examples/purchasing/src/handlers.ts +1 -1
  132. package/docs/examples/recipes/README.md +5 -3
  133. package/docs/handbook/cloudflare/authentication.md +21 -4
  134. package/docs/handbook/cloudflare/chatgpt-sites.md +4 -2
  135. package/docs/handbook/cloudflare/deploy-and-operate.md +24 -1
  136. package/docs/handbook/cloudflare/media-r2.md +2 -3
  137. package/docs/handbook/cloudflare/service-entry.md +17 -4
  138. package/docs/handbook/concepts/runtime-and-adapters.md +1 -1
  139. package/docs/handbook/examples/hub.md +1 -1
  140. package/docs/handbook/guides/agent-setup.md +15 -10
  141. package/docs/handbook/guides/agent-workflow-acceptance.md +232 -0
  142. package/docs/handbook/guides/local-testing.md +40 -0
  143. package/docs/handbook/guides/mcp-apps.md +78 -1
  144. package/docs/handbook/guides/native-admin.md +29 -6
  145. package/docs/handbook/guides/native-execution.md +5 -4
  146. package/docs/handbook/guides/oauth.md +58 -0
  147. package/docs/handbook/guides/public-pages.md +44 -4
  148. package/docs/handbook/guides/sql-patterns.md +266 -0
  149. package/docs/handbook/guides/typed-queries.md +173 -0
  150. package/docs/handbook/navigation.json +16 -0
  151. package/docs/handbook/reference/admin-descriptors.md +4 -1
  152. package/docs/handbook/reference/authorization.md +1 -1
  153. package/docs/handbook/reference/diagnostics.md +6 -1
  154. package/docs/handbook/reference/procedure.md +5 -5
  155. package/docs/handbook/reference/schema.md +10 -4
  156. package/docs/handbook/reference/sql.md +64 -0
  157. package/docs/handbook/reference/surface.md +11 -4
  158. package/docs/handbook/reference/trigger.md +9 -0
  159. package/docs/handbook/reference/view.md +11 -3
  160. package/docs/handbook/releases/index.md +27 -6
  161. package/docs/handbook/start/agents.md +45 -0
  162. package/docs/handbook/start/project-and-cli.md +15 -1
  163. package/docs/handbook/start/quickstart-worker.md +1 -1
  164. package/docs/skills/develop/SKILL.md +44 -16
  165. package/docs/skills/integrate/SKILL.md +4 -9
  166. package/docs/skills/provision/SKILL.md +15 -12
  167. package/docs/skills/update/SKILL.md +21 -18
  168. package/package.json +24 -4
  169. package/skills/README.md +1 -1
  170. package/skills/mantle/SKILL.md +48 -107
  171. package/dist/domain/describe/chunk-ZVXBGP7Y.js +0 -424
  172. package/docs/skills/develop/mcp-app.md +0 -39
  173. package/skills/.keep +0 -0
  174. package/skills/mantle/references/local-testing.md +0 -15
  175. package/skills/mantle/references/web.md +0 -41
  176. package/skills/mantle/references/website.md +0 -49
@@ -4,7 +4,6 @@ export { definitive } from "../dialect/sqlite.js";
4
4
  import { context, guard } from "./transaction-context.js";
5
5
  const transactions = new WeakSet();
6
6
  const queues = new WeakMap();
7
- /** Only queued transactions make otherwise synchronous statements wait; a rejection cannot poison the queue. */
8
7
  function enqueue(db, fn) {
9
8
  const result = (queues.get(db) ?? Promise.resolve()).then(fn);
10
9
  const tail = result.then(() => { }, () => { });
@@ -15,11 +14,9 @@ function enqueue(db, fn) {
15
14
  }
16
15
  const available = (db, fn) => { guard(db); return queues.has(db) ? enqueue(db, fn) : fn(); };
17
16
  export const read = (db, sql, binds) => available(db, () => db.query(sql).all(...binds));
18
- /** One statement is atomic on its own; several run in a transaction, and a row statement that does not change exactly one row rolls it back. A unique-index clash is CONFLICT. */
19
17
  export async function procedure(db, steps, path) {
20
18
  const execute = (handle) => steps.map(s => {
21
19
  const statement = handle.query(s.sql);
22
- // a statement with columns (SELECT, RETURNING) gives rows, and their number is its affected count
23
20
  let rows = [], changes;
24
21
  try {
25
22
  rows = statement.columnNames.length ? statement.all(...s.binds) : [];
@@ -27,7 +24,6 @@ export async function procedure(db, steps, path) {
27
24
  changes = rows.length;
28
25
  else {
29
26
  statement.run(...s.binds);
30
- // Bun's run().changes includes FTS maintenance writes; SQLite changes() counts the authored statement only.
31
27
  changes = s.row ? Number(handle.query("SELECT changes() AS n").all()[0].n) : 0;
32
28
  }
33
29
  }
@@ -2,7 +2,6 @@ import { checkConflict, conflict } from "../contracts.js";
2
2
  import { unique } from "../dialect/sqlite.js";
3
3
  export { definitive } from "../dialect/sqlite.js";
4
4
  export const read = async (db, sql, binds) => (await db.prepare(sql).bind(...binds).all()).results;
5
- /** The assert table's trigger aborts the whole batch with `CONFLICT op=<k>` when statement k did not change exactly one row. */
6
5
  export async function procedure(db, steps, path) {
7
6
  const batch = [], at = [];
8
7
  steps.forEach((s, i) => {
@@ -1,4 +1,4 @@
1
- import { checkConflict, conflict, ContractError } from "../contracts.js";
1
+ import { conflict, ContractError, schemaCheckFailed } from "../contracts.js";
2
2
  import { context, guard } from "./transaction-context.js";
3
3
  const transactions = new WeakSet();
4
4
  const ISOLATION = ["serializable", "repeatable read", "read committed", "read uncommitted"];
@@ -7,35 +7,24 @@ export async function run(db, sql, binds) {
7
7
  const rows = await read(db, sql, binds);
8
8
  return { rows, changes: Number(rows.count ?? 0) };
9
9
  }
10
- /** SQLSTATE of a server error: `errno` on Bun.SQL, `code` on postgres.js. */
11
10
  const sqlstate = (error) => { const e = error; return typeof e?.errno === "string" ? e.errno : e?.code; };
12
- /** A structured server ErrorResponse proves rollback; missing evidence is uncertain. */
11
+ const check = (path, e) => schemaCheckFailed(path, e, e.table ?? e.table_name, e.constraint ?? e.constraint_name);
13
12
  export function definitive(error) {
14
13
  if (error instanceof ContractError)
15
14
  return error.code === "CONFLICT";
16
15
  const state = sqlstate(error);
17
16
  return typeof state === "string" && /^[0-9A-Z]{5}$/.test(state) && typeof error?.severity === "string" && !/^(08|28|53|57|58|XX)/.test(state);
18
17
  }
19
- /**
20
- * The error to throw when a PostgreSQL write fails where it may already have committed (autocommit, or COMMIT).
21
- * A server ErrorResponse (SQLSTATE + severity) outside connection/resource classes rolled back; anything else, such as a
22
- * lost socket, is OUTCOME_UNKNOWN.
23
- */
24
18
  export function postgresOutcome(error, path) {
25
19
  if (definitive(error))
26
20
  return error;
27
21
  return new ContractError("OUTCOME_UNKNOWN", "The write outcome is unknown; reconcile before retrying.", path, { cause: error });
28
22
  }
29
- /**
30
- * One statement is atomic on its own (a row statement touches at most one row, so a failed count check changes nothing)
31
- * and runs in autocommit. Several run in `begin(serializable)`: a failure before the callback returns was rolled back;
32
- * only a failed COMMIT can leave the outcome unknown.
33
- */
34
23
  export async function procedure(db, steps, path) {
35
24
  const execute = async (handle) => {
36
25
  const results = [];
37
26
  for (const s of steps) {
38
- const { rows, changes } = await run(handle, s.sql, s.binds).catch(error => { throw sqlstate(error) === "23505" ? conflict(path, true, error) : checkConflict(path, error, sqlstate(error) === "23514") ?? error; });
27
+ const { rows, changes } = await run(handle, s.sql, s.binds).catch(error => { throw sqlstate(error) === "23505" ? conflict(path, true, error) : sqlstate(error) === "23514" ? check(path, error) : error; });
39
28
  if (s.row && changes !== 1)
40
29
  throw conflict(path, false);
41
30
  results.push(rows);
@@ -54,18 +43,15 @@ export async function procedure(db, steps, path) {
54
43
  }
55
44
  return transaction(db, execute, undefined, path);
56
45
  }
57
- /** Shared BEGIN/COMMIT outcome handling for Procedures and interactive Store transactions. */
58
46
  export async function transaction(db, fn, options = {}, path = "store/transaction") {
59
47
  guard(db);
60
48
  if (transactions.has(db))
61
49
  throw new Error("Nested transactions are not supported.");
62
- // a transaction handle the app opened (postgres.js types it without `begin`) only suits reads and single statements
63
50
  if (typeof db.begin !== "function")
64
51
  throw new Error("This PostgreSQL handle is a transaction the app opened and cannot begin another: open the transaction with store(pool, caller).transaction and call Procedures through its tx.");
65
52
  let committing = false;
66
53
  const state = { outer: db };
67
54
  try {
68
- // printed into BEGIN, so only PostgreSQL's own four levels: a handler may pass request input here
69
55
  const level = options.isolation ?? "serializable";
70
56
  if (!ISOLATION.includes(level))
71
57
  throw new ContractError("INPUT_VALIDATION_FAILED", `isolation '${level}' is not a PostgreSQL isolation level`, path);
@@ -5,7 +5,6 @@ export function guard(db) {
5
5
  if (context.getStore()?.outer === db)
6
6
  throw new ContractError("INPUT_VALIDATION_FAILED", "Inside store.transaction use tx, not the outer store or handle.", "store/transaction");
7
7
  }
8
- /** One atomic write cannot publish a translation and change its parent's status. */
9
8
  export function translationWrite(db, schema, parent) {
10
9
  const state = context.getStore();
11
10
  if (!state || state.handle !== db)
@@ -24,10 +24,6 @@ export function adminInvitationEmail(role, signInUrl) {
24
24
  signInUrl,
25
25
  ]);
26
26
  }
27
- /**
28
- * Local development only: logs recipients and sign-in secrets, sends nothing.
29
- * Select at the application's environment boundary; never use in production.
30
- */
31
27
  export class ConsoleEmailSender {
32
28
  async send(args) {
33
29
  const { to, subject, text, locale, category } = args;
@@ -1,6 +1,6 @@
1
- /** Request-only gateway decisions and observation; no database or compiler dependencies. */
2
1
  import { forwarded, ContractError, wire } from "./contracts.js";
3
- import { isHostCaller, checkFresh } from "./caller-identity.js";
2
+ import { isHostCaller } from "./caller-identity.js";
3
+ import { checkFresh } from "./caller-mode.js";
4
4
  const logged = new WeakSet();
5
5
  export function accessRequest(ctx, options) {
6
6
  const present = forwarded(ctx);
@@ -43,7 +43,6 @@ export function accessRequest(ctx, options) {
43
43
  logged.add(listener);
44
44
  console.error("[mantle onAccess] listener failed");
45
45
  } };
46
- // Schedule observation after the decision without awaiting its promise.
47
46
  queueMicrotask(() => { try {
48
47
  void Promise.resolve(listener(finished)).catch(log);
49
48
  }
@@ -36,4 +36,4 @@ export declare function gatewayCaller(ctx: RequestContext | undefined, gateway:
36
36
  /** Host errors are machine-readable and never challenge for application credentials. */
37
37
  export declare function hostFailure(error: unknown, caller?: Caller, where?: string, challenge?: string): Response;
38
38
  export { isHostCaller } from "./caller-identity.js";
39
- export { checkFresh } from "./caller-identity.js";
39
+ export { checkFresh } from "./caller-mode.js";
@@ -1,10 +1,9 @@
1
- /** Request-only host contract validation. */
2
1
  export { draining } from "./drain.js";
3
- import { forwarded, ContractError, surfaceError, surfaceFailure } from "./contracts.js";
2
+ import { forwarded, ContractError } from "./contracts.js";
3
+ import { surfaceError, surfaceFailure } from "./surface-failure.js";
4
4
  import { userCaller } from "./user-caller.js";
5
5
  import { identities, isHostCaller } from "./caller-identity.js";
6
6
  const hostContract = (message, field) => { throw new ContractError("HOST_CONTRACT", message, "", { status: 412, fields: field ? { field } : undefined }); };
7
- /** Validate the forwarding contract and reuse the ordinary user validation and brand. */
8
7
  export function hostCaller(props, options) {
9
8
  const record = (v) => !!v && typeof v === "object" && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
10
9
  const text = (v) => typeof v === "string" && v.length > 0 && !v.includes("\0") && v.isWellFormed();
@@ -35,7 +34,6 @@ export function hostCaller(props, options) {
35
34
  identities.set(caller, Object.freeze({ ...identities.get(base), admin: caller.admin, host: true }));
36
35
  return caller;
37
36
  }
38
- /** Resolve only forwarded props, or trip on an entry that did not opt in. */
39
37
  export function gatewayCaller(ctx, gateway, fields) {
40
38
  const present = forwarded(ctx);
41
39
  if (!gateway)
@@ -44,7 +42,6 @@ export function gatewayCaller(ctx, gateway, fields) {
44
42
  return { kind: 'anonymous' };
45
43
  return hostCaller(ctx.props.mantle, { tenant: gateway.tenant, fields });
46
44
  }
47
- /** Host errors are machine-readable and never challenge for application credentials. */
48
45
  export function hostFailure(error, caller, where, challenge) {
49
46
  if ((!caller || !isHostCaller(caller)) && !(error instanceof ContractError && error.code === 'HOST_CONTRACT'))
50
47
  return surfaceFailure(error, challenge, where);
@@ -53,4 +50,4 @@ export function hostFailure(error, caller, where, challenge) {
53
50
  return Response.json({ error: { code, ...(typeof result.error.field === 'string' ? { field: result.error.field } : {}), ...(result.error.path ? { target: result.error.path } : {}) } }, { status: result.status === 401 ? 403 : result.status, headers: { 'cache-control': 'private, no-store' } });
54
51
  }
55
52
  export { isHostCaller } from "./caller-identity.js";
56
- export { checkFresh } from "./caller-identity.js";
53
+ export { checkFresh } from "./caller-mode.js";
@@ -1,5 +1,3 @@
1
- /** Request-only JSON reader: bound bytes before copying or parsing, independent of UTF-8 chunk boundaries. */
2
- /** Bound raw bytes before decoding a request body. */
3
1
  export async function bytes(request, limit, fail) {
4
2
  if (!Number.isSafeInteger(limit) || limit < 1)
5
3
  fail("Body limit must be a positive safe integer.");
@@ -1,9 +1,6 @@
1
1
  import { ContractError } from "./contracts.js";
2
- /** MCP Apps (ADR-0029 D7): UI resources served beside the tools that render in them. */
3
2
  export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
4
- /** Flatten contributors; `mcp(...)` reads static resources getters once at construction. */
5
3
  export const resourcesOf = (apps) => ({ resources: (Array.isArray(apps) ? apps : [apps]).flatMap(app => app.resources) });
6
- /** Static contributors are checked at construction; resolved factories are checked per request. A request-bound tool table defers tool-link checks until its first request. */
7
4
  export function linkApps(apps, tools, views) {
8
5
  const resources = resourcesOf(apps).resources;
9
6
  const uris = new Set(), names = new Set(), renders = new Map(), appOnly = new Set();
@@ -24,7 +21,6 @@ export function linkApps(apps, tools, views) {
24
21
  refuse(`Tool '${tool}' is claimed by two MCP App resources.`);
25
22
  renders.set(tool, resource.uri);
26
23
  }
27
- // an App acts for the user without the model seeing the call, so only a read may be hidden from the model
28
24
  for (const tool of resource.appOnly ?? []) {
29
25
  if (views && !views.has(tool))
30
26
  refuse(`App-only tool '${tool}' must be a View this endpoint serves.`);
@@ -33,8 +29,7 @@ export function linkApps(apps, tools, views) {
33
29
  }
34
30
  return { resources, renders, appOnly };
35
31
  }
36
- /** One endpoint's Apps bound to its tool table; `previous` is reused while the table's names are unchanged. */
37
32
  export function linkSurface(apps, selected, previous) {
38
- const key = JSON.stringify(selected.map(tool => tool.name).sort());
33
+ const key = JSON.stringify(selected.map(tool => [tool.name, !!tool.page]).sort(([a], [b]) => a.localeCompare(b)));
39
34
  return previous?.key === key ? previous : { key, links: linkApps(apps, new Set(selected.map(tool => tool.name)), new Set(selected.filter(tool => tool.page).map(tool => tool.name))) };
40
35
  }
@@ -3,7 +3,6 @@ import { checkPageLimit } from "./paging.js";
3
3
  export async function callTool(tool, raw, db, caller, handlers) {
4
4
  return callToolLazy(tool, raw, () => db, caller, handlers);
5
5
  }
6
- /** Transport input is checked before acquiring an application-owned native handle. */
7
6
  export async function callToolLazy(tool, raw, getDb, caller, handlers, dryRun) {
8
7
  if (tool.page) {
9
8
  const { limit, cursor, ...input } = raw;
@@ -1,6 +1,6 @@
1
- /** Request-only MCP implementation, excluded from Worker startup. */
2
1
  import { authorized, authorizeTarget } from "./authorization.js";
3
- import { forwarded, isAdmin, ContractError, checkOrigin, surfaceCaller, surfaceError, wire } from "./contracts.js";
2
+ import { forwarded, isAdmin, ContractError, wire } from "./contracts.js";
3
+ import { checkOrigin, surfaceCaller, surfaceError } from "./surface-failure.js";
4
4
  import { draining } from "./drain.js";
5
5
  import { callToolLazy as callTool } from "./mcp-call.js";
6
6
  import { RESOURCE_MIME_TYPE, linkSurface, resourcesOf } from "./mcp-apps.js";
@@ -19,15 +19,8 @@ function observe(listener, event) {
19
19
  catch { }
20
20
  }
21
21
  const paging = (schema) => ({ ...schema, properties: { ...schema.properties, limit: { type: "integer", minimum: 1, maximum: 500 }, cursor: { type: "string" } } });
22
- /**
23
- * Characters of `JSON.stringify(page)` an MCP View page may hold. A result carries its rows twice (text block and
24
- * `structuredContent`) and hosts are reported to truncate near 150k characters, so one copy stays at 60k.
25
- * ponytail: one fixed number; raise it or make it an option if hosts publish their limits.
26
- */
27
22
  const MCP_PAGE_BUDGET = 60_000;
28
- /** The scopes a challenge asks for: the credential's, plus what the request needs. */
29
23
  const union = (scopes, extra) => [...new Set([...scopes, ...extra])].join(" ");
30
- /** The handler for `/mcp` (public tools) and `/mcp/admin` (tools for `admin` roles); other paths are undefined. */
31
24
  export function handler(tools, options, apps = {}, reads = []) {
32
25
  const allowed = options.allowedOrigins ?? [];
33
26
  return draining(async (request, env, ctx) => {
@@ -38,8 +31,6 @@ export function handler(tools, options, apps = {}, reads = []) {
38
31
  const url = new URL(request.url), path = url.pathname.replace(/\/+$/, ""), surface = path === "/mcp" ? "public" : path === "/mcp/admin" ? "admin" : undefined;
39
32
  if (!surface)
40
33
  return;
41
- // MCP transport MUST: a present Origin is a browser, answered only for loopback or `allowedOrigins`. The request's own
42
- // host is not implied, since a DNS-rebinding page sends Origin == its rebound Host; a missing Origin is a server client.
43
34
  if (request.headers.has("origin")) {
44
35
  const sdk = await import("@modelcontextprotocol/server");
45
36
  const foreign = sdk.originValidationResponse(request, [...sdk.localhostAllowedOrigins(), ...allowed]);
@@ -51,7 +42,6 @@ export function handler(tools, options, apps = {}, reads = []) {
51
42
  }
52
43
  }
53
44
  const select = async () => (typeof tools === "function" ? await tools(request, env) : tools).filter(tool => tool.surface === surface);
54
- // Dynamic admin tables stay behind the admin gate; cache classification uses generated metadata only.
55
45
  let selected = surface === "public" ? await select() : [];
56
46
  let parsedBody, tooLarge = false;
57
47
  const cookieOnly = request.headers.has("cookie") && !request.headers.has("authorization");
@@ -94,7 +84,7 @@ export function handler(tools, options, apps = {}, reads = []) {
94
84
  observe(options.onRefusal, { at: Date.now(), status: result.status, reason: "credential" });
95
85
  }
96
86
  if (result.status === 401)
97
- scope ??= requiredScopes.join(" ");
87
+ scope = union(scope === undefined ? requiredScopes : scope.split(" "), options.authorizationScopes ?? []);
98
88
  return (await import("./host-caller.js")).hostFailure(error, resolved, `mcp ${path}`, bare ? undefined : 'Bearer ' + (scope ? (result.status === 403 ? 'error="insufficient_scope", ' : '') + 'scope="' + scope + '", ' : '') + 'resource_metadata="' + (options.resourceMetadata ?? url.origin + '/.well-known/oauth-protected-resource/mcp') + '"');
99
89
  };
100
90
  let caller;
@@ -120,7 +110,6 @@ export function handler(tools, options, apps = {}, reads = []) {
120
110
  }
121
111
  if (surface === "admin")
122
112
  selected = await select();
123
- // Before per-caller filtering, so every caller of a deploy sees one catalogue version.
124
113
  const version = catalogueVersion(selected);
125
114
  const { McpServer, ProtocolError, ProtocolErrorCode, createMcpHandler, fromJsonSchema } = await import("@modelcontextprotocol/server");
126
115
  if (request.method === "POST" && !cookieOnly && !options.gateway)
@@ -176,7 +165,6 @@ export function handler(tools, options, apps = {}, reads = []) {
176
165
  const sources = (Array.isArray(app) ? app : [app]);
177
166
  const dynamic = sources.some(source => typeof source === "function");
178
167
  const resolved = resourcesOf(await Promise.all(sources.map(source => typeof source === "function" ? source({ env, request }) : source)));
179
- // Equal tool names say nothing about request-bound resource identity or ownership.
180
168
  const current = linkSurface(resolved, selected, dynamic ? undefined : apps[surface]);
181
169
  if (!dynamic)
182
170
  apps[surface] = current;
@@ -193,7 +181,6 @@ export function handler(tools, options, apps = {}, reads = []) {
193
181
  tool.check?.(caller);
194
182
  await authorizeTarget(options.authorize, tool.target ?? { kind: tool.page ? "view" : "procedure", name: tool.name }, caller);
195
183
  }
196
- // an App's HTML is rendered for the same tools the caller's tools/list shows
197
184
  if ((Array.isArray(parsedBody) ? parsedBody : [parsedBody]).some(message => message?.method === "tools/list" || message?.method === "resources/read")) {
198
185
  const visible = [];
199
186
  for (const tool of selected) {
@@ -218,17 +205,13 @@ export function handler(tools, options, apps = {}, reads = []) {
218
205
  }
219
206
  }
220
207
  const serverInfo = { name: "aotter.mantle", ...options.serverInfo, version: options.serverInfo?.version ?? version };
221
- // Host calls execute in the SDK callback, after transport validation.
222
208
  const handler = createMcpHandler(() => {
223
209
  const schema = (value) => fromJsonSchema(value, { getValidator() { return (input) => ({ valid: true, data: input, errorMessage: undefined }); } });
224
- // Tools capability after construction: given to the constructor, the SDK installs its tools/call handler before the wrap below.
225
210
  const server = new McpServer(serverInfo, options.instructions ? { instructions: options.instructions } : {});
226
211
  server.server.registerCapabilities({ tools: { listChanged: false } });
227
212
  if (host)
228
213
  server.server.onclose = () => access?.finish(isRecord(parsedBody) && parsedBody.method === "initialize" ? undefined : new ContractError("INPUT_VALIDATION_FAILED", "MCP request refused.", "mcp", { status: 400 }));
229
214
  const appMeta = links ? registerApps(server, links, parsedBody, new Set(selected.map(tool => tool.name)), { env, request }) : undefined;
230
- // A host's stale copy names a tool this catalogue lacks: say so, with the catalogue version, instead of the SDK's bare "not found".
231
- // Wrapped where the SDK stores it, so transport and request validation still answer first.
232
215
  const registered = new Set(), set = server.server.setRequestHandler.bind(server.server);
233
216
  server.server.setRequestHandler = ((method, handler) => set(method, method === "tools/call" && typeof handler === "function" ? (request, context) => {
234
217
  if (!registered.has(request.params.name))
@@ -240,7 +223,6 @@ export function handler(tools, options, apps = {}, reads = []) {
240
223
  if (meta === false)
241
224
  continue;
242
225
  registered.add(tool.name);
243
- // Not part of structured output: the version, and on failure the current input contract.
244
226
  const about = (contract) => { const text = [tool.version && `tool version ${tool.version}`, contract && `input schema ${JSON.stringify(tool.page ? paging(tool.inputSchema) : tool.inputSchema)}`].filter(Boolean).join("; "); return text ? [{ type: "text", text }] : []; };
245
227
  server.registerTool(tool.name, { ...(meta ? { _meta: meta } : {}), ...(tool.title ? { title: text(tool.title, locale) } : {}), description: text(tool.description, locale) ?? text(tool.title, locale) ?? tool.name, inputSchema: schema(tool.page ? paging(tool.inputSchema) : tool.inputSchema), ...(tool.outputSchema ? { outputSchema: schema(tool.outputSchema) } : {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) }, async (raw) => {
246
228
  const metadata = options.onObservation ? { kind: "invocation", surface, invocationId: crypto.randomUUID(), tool: tool.name, caller: Object.freeze(caller.kind === "user" ? { ...caller, scopes: Object.freeze([...caller.scopes]) } : { ...caller }) } : undefined;
@@ -256,8 +238,6 @@ export function handler(tools, options, apps = {}, reads = []) {
256
238
  let db;
257
239
  const run = (input) => callTool(tool, input, () => db ??= options.db(env), caller, options.handlers, access?.dryRun ? () => ({ dryRun: true, event: access.finish() }) : undefined);
258
240
  let data = await run(raw);
259
- // A page is cut before the first row that overflows the budget: the same page re-runs with the limit that fits, so the cursor is the View's own.
260
- // Data can change between reads, so the re-run is measured again. A View without an order is one page and refuses a smaller limit: it stays whole.
261
241
  for (let tries = 0; tool.page && isRecord(data) && Array.isArray(data.rows); tries++) {
262
242
  const rows = data.rows, total = JSON.stringify(data).length;
263
243
  if (total <= MCP_PAGE_BUDGET)
@@ -299,7 +279,6 @@ export function handler(tools, options, apps = {}, reads = []) {
299
279
  }
300
280
  });
301
281
  }
302
- // An empty catalogue still answers tools/list and refuses calls the same way.
303
282
  if (registered.size === 0) {
304
283
  server.server.setRequestHandler("tools/list", () => ({ tools: [] }));
305
284
  server.server.setRequestHandler("tools/call", () => ({ content: [] }));
@@ -319,14 +298,12 @@ export function handler(tools, options, apps = {}, reads = []) {
319
298
  }
320
299
  });
321
300
  }
322
- /** A hash of the tools an endpoint serves (`surface:name:version`, sorted), as 32-bit FNV-1a hex: it changes with any tool's definition. */
323
301
  function catalogueVersion(tools) {
324
302
  const text = JSON.stringify(tools.map(tool => `${tool.surface}:${tool.name}:${tool.version ?? ""}`).sort());
325
303
  return [...text].reduce((h, c) => Math.imul(h ^ c.codePointAt(0), 16777619) >>> 0, 2166136261).toString(16).padStart(8, "0");
326
304
  }
327
305
  const CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities";
328
306
  const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
329
- /** `unknown`: a stateless request after `initialize` carries no capabilities, so only an explicit refusal hides Apps. */
330
307
  function clientUiSupport(message) {
331
308
  for (const m of Array.isArray(message) ? message : [message]) {
332
309
  if (!isRecord(m) || !isRecord(m.params))
@@ -344,7 +321,6 @@ function appMeta(r, csp = r.csp) {
344
321
  const ui = { ...(csp ? { csp } : {}), ...(r.permissions ? { permissions: r.permissions } : {}), ...(r.domain !== undefined ? { domain: r.domain } : {}), ...(r.prefersBorder !== undefined ? { prefersBorder: r.prefersBorder } : {}) };
345
322
  return Object.keys(ui).length > 0 ? { ui } : undefined;
346
323
  }
347
- /** Registration uses the official SDK; HTML loaders run only on resources/read. */
348
324
  function registerApps(server, links, message, tools, request) {
349
325
  const enabled = clientUiSupport(message) !== "unsupported";
350
326
  if (enabled)
@@ -2,7 +2,9 @@
2
2
  import type { Caller, Target, Authorize, Gateway, RequestContext, GatewayOptions } from "./contracts.js";
3
3
  import type { Conversions } from "./surface.js";
4
4
  import { type McpAppsSource } from "./mcp-apps.js";
5
- export { callTool, callToolLazy } from "./mcp-call.js";
5
+ type Call = typeof import("./mcp-call.js");
6
+ export declare const callTool: Call["callTool"];
7
+ export declare const callToolLazy: Call["callToolLazy"];
6
8
  export type { McpApps, McpAppsSource, McpAppResource, McpAppRender, McpAppPage, McpAppCsp } from "./mcp-apps.js";
7
9
  /** Options of a generated `mcp(...)`; it adds required `handlers` when the app declares ref Procedures. */
8
10
  export interface Options<Env, Database> extends GatewayOptions {
@@ -28,6 +30,8 @@ export interface Options<Env, Database> extends GatewayOptions {
28
30
  }[];
29
31
  };
30
32
  requiredScopes?: readonly string[];
33
+ /** Additional scopes requested by an unauthenticated OAuth challenge (for example offline_access), not an API scope floor. */
34
+ authorizationScopes?: readonly string[];
31
35
  resourceMetadata?: string;
32
36
  /** Browser origins MCP answers besides loopback, compared by hostname: `https://console.example` or the official SDK's bare `console.example`. The site's own origin is not implied. */
33
37
  allowedOrigins?: readonly string[];
@@ -1,21 +1,18 @@
1
1
  import { linkApps, linkSurface, resourcesOf } from "./mcp-apps.js";
2
- export { callTool, callToolLazy } from "./mcp-call.js";
3
- /** The selected MCP routes; all request work loads only when an MCP request arrives. */
2
+ export const callTool = async (...args) => (await import("./mcp-call.js")).callTool(...args);
3
+ export const callToolLazy = async (...args) => (await import("./mcp-call.js")).callToolLazy(...args);
4
4
  export function mcp(tools, options, reads = []) {
5
5
  let serve;
6
- // Check known static App configuration now; factories wait for the request caller gate.
7
6
  const linked = {};
8
7
  const apps = {};
9
8
  for (const surface of ["public", "admin"]) {
10
9
  const declared = options.apps?.[surface];
11
10
  if (declared) {
12
- // Read each static contributor's resources getter once, including mixed arrays.
13
11
  const sources = (Array.isArray(declared) ? declared : [declared])
14
12
  .map(source => typeof source === "function" ? source : resourcesOf(source));
15
13
  const fixed = resourcesOf(sources.filter(source => typeof source !== "function"));
16
14
  const dynamic = sources.some(source => typeof source === "function");
17
15
  apps[surface] = dynamic ? sources : fixed;
18
- // Known static conflicts still fail before any request or dynamic factory runs.
19
16
  if (typeof tools === "function")
20
17
  linkApps(fixed);
21
18
  else {
@@ -34,7 +31,6 @@ export function mcp(tools, options, reads = []) {
34
31
  return serve(request, env, ctx);
35
32
  };
36
33
  }
37
- /** `allowedOrigins` as the hostnames the official SDK compares; a bad entry fails here, not on each request. */
38
34
  function originHostnames(origins = []) {
39
35
  return Object.freeze(origins.map(origin => {
40
36
  let url;
@@ -1,33 +1,23 @@
1
- /** 0.2 media lifecycle over native target drivers. No bytes pass through this module. */
2
1
  import { ContractError } from "./contracts.js";
3
2
  const P = "media";
4
- /** HTTP status of each media code: a custom MediaStorage may throw them without one. */
5
3
  const STATUS = new Map(Object.entries({
6
4
  MEDIA_PURPOSE_REJECTED: 400, MEDIA_SVG_REJECTED: 400, MEDIA_MIME_REJECTED: 400, MEDIA_VARIANTS_INCOMPLETE: 400, MEDIA_VARIANT_SIZE_EXCEEDED: 400, MEDIA_VARIANTS_SUSPICIOUS_SIZE: 400,
7
5
  MEDIA_ASSET_NOT_FOUND: 404, MEDIA_OBJECT_NOT_FOUND: 409, MEDIA_UPLOAD_EXPIRED: 410, SITE_NOT_CONFIGURED: 501, MEDIA_NOT_CONFIGURED: 501, PARTIAL_FAILURE: 503,
8
6
  }));
9
7
  const extra = (code) => ({ status: STATUS.get(code), ...(code === "PARTIAL_FAILURE" ? { fields: { failure: { outcome: "partial", retry: "safe", resource: "media" } } } : {}) });
10
- /**
11
- * A media, site or partial-failure error with the HTTP status (and `failure` payload) its code has on the wire. Code
12
- * outside this module raising these codes uses it: core `statusOf` maps only the core codes.
13
- */
14
8
  export const mediaError = (code, message, path = P, options) => new ContractError(code, message, path, { ...options, ...extra(code) });
15
9
  const fail = (code, message, options) => mediaError(code, message, P, options);
16
- /** A storage error keeps the wire status its code has always had. */
17
10
  const own = (error) => { if (error instanceof ContractError && !error.status && STATUS.has(error.code))
18
11
  Object.assign(error, extra(error.code)); return error; };
19
12
  const rejected = (results) => results.filter((r) => r.status === "rejected");
20
13
  const bad = (expected) => fail("INPUT_VALIDATION_FAILED", `expected ${expected}`);
21
- /** SVG is refused: object storage does not sanitize it, and an SVG can carry script. */
22
14
  const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"]);
23
- /** Modern formats a skipped optimization makes larger than the fallback. */
24
15
  const MODERN = new Set(["image/avif", "image/webp"]);
25
16
  const ROLES = new Set(["primary", "alternate", "fallback"]);
26
17
  const TTL_MS = 15 * 60 * 1000;
27
18
  const obj = (v) => (v !== null && typeof v === "object" && !Array.isArray(v) ? v : {});
28
19
  const MAX_TEXT = 1000;
29
20
  const MAX_FILENAME = 255;
30
- /** `alt` and `caption`: absent, or a string of at most 1000 characters. */
31
21
  function texts(body) {
32
22
  const b = obj(body);
33
23
  for (const k of ["alt", "caption"])
@@ -35,7 +25,6 @@ function texts(body) {
35
25
  throw bad(`{ alt?: string, caption?: string }, each at most ${MAX_TEXT} characters`);
36
26
  return { ...(typeof b["alt"] === "string" ? { alt: b["alt"] } : {}), ...(typeof b["caption"] === "string" ? { caption: b["caption"] } : {}) };
37
27
  }
38
- /** Exactly one variant per required slot, nothing outside them, and exactly one primary. */
39
28
  function checkVariants(policy, variants) {
40
29
  const slots = policy.required.map(slot => slot.split(","));
41
30
  const slotOf = new Map(slots.flatMap((mimes, i) => mimes.map((m) => [m, i])));
@@ -99,7 +88,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
99
88
  checkVariants(policy, asked);
100
89
  const at = now();
101
90
  const expiresAt = at + TTL_MS;
102
- // bearer-equivalent until commit: storage keys under it must not be guessable
103
91
  const uploadGroupId = crypto.randomUUID();
104
92
  const specs = asked.map(({ mimeType, byteSize, role }) => ({ mimeType, byteSize, role, maxBytes: policy.maxBytes[mimeType] }));
105
93
  let capabilities;
@@ -126,7 +114,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
126
114
  return assetOf(committed);
127
115
  const row = await one(`SELECT record FROM pending_media_uploads WHERE id = ${p(1)}`, [uploadGroupId]);
128
116
  const record = row ? JSON.parse(String(row.record)) : null;
129
- // a rejected group's objects are deleted: an upload URL takes any type and size, so what was PUT is not trusted
130
117
  const discard = () => removeAll(record?.variants ?? []);
131
118
  if (!record || record.expiresAt <= now()) {
132
119
  if (record) {
@@ -139,7 +126,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
139
126
  try {
140
127
  asset = await storage.commitUpload({
141
128
  uploadGroupId, filename: record.filename, now: record.createdAt,
142
- // the declared size is the cap: a larger object than announced is refused
143
129
  variants: record.variants.map((v) => ({ mimeType: v.mimeType, role: v.role, storageKey: v.storageKey, maxBytes: Math.min(v.maxBytes, v.expectedSize) })),
144
130
  ...((patch.alt ?? record.alt) !== undefined ? { alt: patch.alt ?? record.alt } : {}),
145
131
  ...((patch.caption ?? record.caption) !== undefined ? { caption: patch.caption ?? record.caption } : {}),
@@ -158,7 +144,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
158
144
  if (asset.id !== uploadGroupId)
159
145
  throw new ContractError("OUTCOME_UNKNOWN", "Storage returned a different asset id; reconcile this upload group.", P);
160
146
  await driver.write([save(asset, p), unpend(uploadGroupId)]).catch(async (error) => {
161
- // Cleanup requires positive native rollback evidence; an unclassified failure may have committed.
162
147
  if (driver.definitive?.(error) === true) {
163
148
  const failed = rejected(await removeAll(asset.variants));
164
149
  if (failed.length)
@@ -168,7 +153,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
168
153
  throw error instanceof ContractError && error.code === "OUTCOME_UNKNOWN" ? error : new ContractError("OUTCOME_UNKNOWN", "The write outcome is unknown; reconcile this upload group before retrying.", P, { cause: error });
169
154
  });
170
155
  const durable = await get(uploadGroupId);
171
- // ON CONFLICT may select another concurrent attempt. Only discard this attempt's unselected copies.
172
156
  const selected = new Set(durable.variants.map(v => v.storageKey));
173
157
  if (rejected(await removeAll(asset.variants.filter(v => !selected.has(v.storageKey)))).length)
174
158
  throw new ContractError("OUTCOME_UNKNOWN", "The asset is committed, but unselected upload copies need storage reconciliation.", P);
@@ -193,7 +177,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
193
177
  const patch = Object.entries(texts(request));
194
178
  if (!patch.length)
195
179
  return get(id);
196
- // only the patched columns, and only a row that still exists: a concurrent delete or edit of the other field stands
197
180
  const [r] = (await driver.write([{ sql: `UPDATE media_assets SET ${patch.map(([k], i) => `${k} = ${p(i + 2)}`).join(", ")} WHERE id = ${p(1)} RETURNING ${COLUMNS}`, binds: [id, ...patch.map(([, v]) => v)] }]))[0];
198
181
  if (!r)
199
182
  throw fail("MEDIA_ASSET_NOT_FOUND", `no media asset '${id}'`);
@@ -209,7 +192,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
209
192
  },
210
193
  };
211
194
  }
212
- /** The 0.2 Admin library item's convenience fields, without changing the storage DTO. */
213
195
  export function mediaItem(asset) {
214
196
  const primary = asset.variants.find(v => v.role === "primary") ?? asset.variants[0];
215
197
  return { id: asset.id, variants: asset.variants, primaryUrl: primary?.publicUrl ?? null, mime: primary?.mimeType ?? null, byteSize: primary?.byteSize ?? null, alt: asset.alt ?? null, caption: asset.caption ?? null, createdAt: asset.createdAt };
@@ -1,7 +1,6 @@
1
- import { modeOf } from "./caller-identity.js";
1
+ import { modeOf } from "./caller-mode.js";
2
2
  import { binds } from "./binds.js";
3
3
  import { invalid } from "./surface.js";
4
- /** Shared keyset wire format; a selected View binds its cursor to its operation. */
5
4
  export const encodeCursor = (value, id, operation) => encodeURIComponent(JSON.stringify(operation === undefined ? [value, id] : [value, id, operation]));
6
5
  export function decodeCursor(cursor, path = "", operation) {
7
6
  try {
@@ -12,7 +11,6 @@ export function decodeCursor(cursor, path = "", operation) {
12
11
  catch { }
13
12
  invalid("Malformed or foreign cursor.", path);
14
13
  }
15
- /** Selected boundaries may accept a NULL key; their generated kind guard validates it before native I/O. */
16
14
  export function decodeNullableCursor(cursor, path, operation) {
17
15
  try {
18
16
  const c = JSON.parse(decodeURIComponent(cursor));
@@ -23,7 +21,6 @@ export function decodeNullableCursor(cursor, path, operation) {
23
21
  invalid("Malformed or foreign cursor.", path);
24
22
  }
25
23
  export const MAX_PAGE_SIZE = 500;
26
- /** Transport and native entry bounds share one check; Views retain their declared cap. */
27
24
  export function checkPageLimit(limit, path) {
28
25
  if (!Number.isSafeInteger(limit) || Number(limit) < 1 || Number(limit) > MAX_PAGE_SIZE)
29
26
  invalid("limit is 1 to 500.", path);
@@ -41,10 +38,6 @@ export function validCursor(kind, sqlite, key) {
41
38
  default: return typeof key === "string";
42
39
  }
43
40
  }
44
- /**
45
- * A View's paged boundary: `options.limit` defaults to min(50, cap) and is capped at cap and 500. Generated modules
46
- * call it from their exported function, so importing a View runs no kernel code.
47
- */
48
41
  export async function page(spec, db, caller, input, options = {}) {
49
42
  const { path, cap } = spec;
50
43
  spec.auth?.(caller);
@@ -62,7 +55,6 @@ export async function page(spec, db, caller, input, options = {}) {
62
55
  throw 0;
63
56
  if (spec.keys === 1 && encoded[0] !== encoded[1])
64
57
  throw 0;
65
- // Preserve the existing [id,id,operation] single-key and [value,id,operation] two-key formats.
66
58
  keys = spec.keys === 1 ? [encoded[1]] : encoded.slice(0, -1);
67
59
  for (const [i, kind] of spec.cursor.entries()) {
68
60
  if (!validCursor(kind, spec.sqlite, keys[i]))
@@ -1,6 +1,5 @@
1
- /** A generated publishing transition, admin or system only; `write` claims translation state, released on CONFLICT. */
2
- import { isAdmin, deny } from "./contracts.js";
3
- import { checkFresh } from "./caller-identity.js";
1
+ import { isAdmin, deny, ROW_CONFLICT } from "./contracts.js";
2
+ import { checkFresh } from "./caller-mode.js";
4
3
  import { bound } from "./binds.js";
5
4
  export async function transition(db, caller, input, path, steps, failure, d, execute, write) {
6
5
  checkFresh(caller, false, path);
@@ -9,7 +8,7 @@ export async function transition(db, caller, input, path, steps, failure, d, exe
9
8
  return { results: await execute(db, bound(d, steps, caller, input), path).catch(error => {
10
9
  if (release && error?.code === "CONFLICT")
11
10
  release();
12
- if (error?.code === "CONFLICT" && error.message === "Expected one affected row.")
11
+ if (error?.code === "CONFLICT" && error.message === ROW_CONFLICT)
13
12
  error.message = failure;
14
13
  throw error;
15
14
  }) };
@@ -1,4 +1,3 @@
1
- /** Native R2 binding plus an app-owned SigV4 signer. No SDK dependency. */
2
1
  import { ContractError } from "./contracts.js";
3
2
  import { mediaError } from "./media.js";
4
3
  const EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/gif": "gif" };
@@ -16,7 +15,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
16
15
  const ttl = Math.max(60, Math.floor((expiresAt - now) / 1000));
17
16
  return {
18
17
  capabilities: await Promise.all(variants.map(async (v) => {
19
- // server-made keys, one directory per asset so its variants list together
20
18
  const storageKey = `${UPLOADS}${purpose}/${uploadGroupId}/${v.role}.${ext(v.mimeType)}`;
21
19
  const target = new URL(`${s3}/${storageKey}`);
22
20
  target.searchParams.set("X-Amz-Expires", String(ttl));
@@ -26,7 +24,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
26
24
  };
27
25
  },
28
26
  async commitUpload({ uploadGroupId, filename, variants, alt, caption, now }) {
29
- // every variant is checked before any is published, so a rejected group publishes nothing
30
27
  const heads = await Promise.all(variants.map(spec => bucket.head(spec.storageKey)));
31
28
  for (const [i, spec] of variants.entries()) {
32
29
  const o = heads[i];
@@ -38,19 +35,16 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
38
35
  if (o.size > spec.maxBytes)
39
36
  throw fail("MEDIA_VARIANT_SIZE_EXCEEDED", `the stored ${spec.role} is ${o.size} bytes, more than ${spec.maxBytes}`);
40
37
  }
41
- // Each attempt owns its public copies: a concurrent loser cannot overwrite or clean up a committed winner.
42
38
  const attempt = crypto.randomUUID();
43
39
  const out = [];
44
40
  try {
45
41
  for (const [i, spec] of variants.entries()) {
46
42
  const key = `committed/${uploadGroupId}/${attempt}/${spec.role}.${ext(spec.mimeType)}`;
47
43
  const o = await bucket.get(spec.storageKey);
48
- // an upload URL may PUT again between the check and the copy: the copy must be what was checked
49
44
  if (!o || o.size !== heads[i].size || o.httpMetadata?.contentType !== spec.mimeType) {
50
45
  await cancel(o);
51
46
  throw fail("MEDIA_OBJECT_NOT_FOUND", `variant ${spec.role} of '${uploadGroupId}' changed during commit`);
52
47
  }
53
- // Remember a possibly published key before awaiting put: a failed response may still have stored it.
54
48
  out.push({ mimeType: spec.mimeType, publicUrl: `${base}/${key}`, storageKey: key, byteSize: o.size, role: spec.role });
55
49
  try {
56
50
  await bucket.put(key, o.body, {
@@ -63,7 +57,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
63
57
  throw error;
64
58
  }
65
59
  }
66
- // The use case removes upload keys only after its SQL transaction is durable.
67
60
  }
68
61
  catch (error) {
69
62
  const cleanup = await Promise.allSettled(out.map(v => bucket.delete(v.storageKey)));