@arbol-ai/maximus 8.0.1 → 8.4.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 (70) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +4 -4
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +37 -0
  6. package/dist/capture/index.js +181 -0
  7. package/dist/chunks/{define-app-x7uY70_1.js → define-app-CQpWqqqE.js} +44 -14
  8. package/dist/chunks/delay-BsKQP_lF.js +12 -0
  9. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  10. package/dist/chunks/digest-C51F1bhA.js +12 -0
  11. package/dist/chunks/{errors-C5w9WY1l.js → errors-BoutSmiy.js} +2 -3
  12. package/dist/chunks/execution-Bpq6s4nA.js +265 -0
  13. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  14. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  15. package/dist/chunks/{http-layout-DS8DnPyu.js → http-layout-BcYH4I2w.js} +1 -1
  16. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  17. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  18. package/dist/chunks/{openapi-CeolxIqa.js → openapi-D2rds7vy.js} +32 -130
  19. package/dist/chunks/{openapi-file-Bz9FRaE6.js → openapi-file-BK8zET5U.js} +24 -6
  20. package/dist/chunks/{pages-iZTvFs5a.js → pages-B7ysoFAM.js} +1 -1
  21. package/dist/chunks/result-CF4OzG9O.js +29 -0
  22. package/dist/chunks/{runtime-D94vx21X.js → runtime-CGtS2rOb.js} +165 -11
  23. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  24. package/dist/chunks/{server-Bzf1Q1_4.js → server-CVhTLNj2.js} +38 -101
  25. package/dist/chunks/{src-CPrJpbOM.js → src-D67OfW9B.js} +94 -27
  26. package/dist/chunks/tasks-C873C3le.js +100 -0
  27. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  28. package/dist/chunks/{telemetry-C3LfZcOB.js → telemetry-BtxJh69Q.js} +4 -4
  29. package/dist/chunks/{types-DTIuIEJ-.d.ts → types-BfGa2aJT.d.ts} +537 -124
  30. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  31. package/dist/chunks/{workers-types-BRk_Xa_5.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  32. package/dist/diagnostics.d.ts +1 -1
  33. package/dist/diagnostics.js +1 -1
  34. package/dist/errors.d.ts +1 -1
  35. package/dist/errors.js +1 -1
  36. package/dist/http-paths.d.ts +1 -1
  37. package/dist/http-paths.js +1 -1
  38. package/dist/index.d.ts +2 -2
  39. package/dist/index.js +12 -11
  40. package/dist/internals.d.ts +2 -2
  41. package/dist/internals.js +6 -6
  42. package/dist/mcp/index.d.ts +1 -1
  43. package/dist/mcp/index.js +1 -1
  44. package/dist/mcp/tasks.d.ts +33 -0
  45. package/dist/mcp/tasks.js +3 -0
  46. package/dist/project/config.d.ts +2 -2
  47. package/dist/project/config.js +3 -2
  48. package/dist/project/index.d.ts +2 -2
  49. package/dist/project/index.js +3 -3
  50. package/dist/schemas.d.ts +2 -2
  51. package/dist/schemas.js +3 -3
  52. package/dist/standard-failures.d.ts +1 -1
  53. package/dist/tooling/cli.js +2 -2
  54. package/dist/vite/index.d.ts +2 -2
  55. package/dist/vite/index.js +15 -9
  56. package/dist/webhooks.d.ts +13 -2
  57. package/dist/webhooks.js +38 -1
  58. package/dist/workers/runtime.d.ts +1 -1
  59. package/dist/workers/runtime.js +1 -1
  60. package/package.json +15 -3
  61. package/skills/maximus/SKILL.md +14 -4
  62. package/skills/maximus/references/project.md +4 -0
  63. package/skills/maximus/references/routes-and-tools.md +11 -1
  64. package/templates/project/CLAUDE.md.template +3 -3
  65. package/templates/project/README.md.template +1 -0
  66. package/templates/project/tsconfig.json.template +1 -0
  67. package/dist/chunks/execution-rOiLo8VG.js +0 -84
  68. package/dist/chunks/result-CKgZHrnj.js +0 -56
  69. package/dist/chunks/schemas-p_aRcMC1.js +0 -227
  70. package/dist/chunks/validation-fTohBT6R.js +0 -420
@@ -1,113 +1,16 @@
1
- import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
2
- import { S as wireInput, r as parseInput } from "./validation-fTohBT6R.js";
3
- import { i as standardErrors } from "./errors-C5w9WY1l.js";
4
- import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
5
- import { a as routeGroup, i as pathParameterSchemas, r as ok, t as err } from "./result-CKgZHrnj.js";
1
+ import { i as parseInput } from "./validation-CpzAxj2_.js";
2
+ import { L as wireInput, i as UuidSchema, n as OrganizationIdSchema, z as withoutSecretKeyword } from "./schemas-_UJcx_uY.js";
6
3
  import { t as isRecord } from "./record-DQUDTpEA.js";
7
- import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-p_aRcMC1.js";
4
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
5
+ import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
6
+ import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
7
+ import { S as matchesScopes, _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, x as isNamespacedScope, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
8
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
8
9
  import { t as queryKind } from "./query-kind-CWKAXEME.js";
9
- import { Type } from "@sinclair/typebox";
10
+ import { t as sha256Hex } from "./digest-C51F1bhA.js";
11
+ import { Type } from "typebox";
10
12
  import { createRemoteJWKSet, jwtVerify } from "jose";
11
13
 
12
- // src/scopes.ts
13
- /** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
14
- const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
15
- /** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
16
- function isNamespacedScope(scope, namespace) {
17
- return scope.startsWith(`${namespace}:`) && SCOPE_NAME.test(scope);
18
- }
19
- /**
20
- * Whether granted scopes admit a requirement: any one of the required scopes, or all of them with `all`.
21
- * An empty requirement admits nobody.
22
- */
23
- function matchesScopes(required, granted, match = "any") {
24
- if (!required.length) return false;
25
- const has = (scope) => granted.includes(scope);
26
- return match === "all" ? required.every(has) : match === "any" && required.some(has);
27
- }
28
-
29
- // src/manifest.ts
30
- /** Whether an operation belongs in public contracts: the OpenAPI document and the discovery metadata. */
31
- function isPublicOperation(declaration) {
32
- return declaration.visibility !== "internal";
33
- }
34
- /** The scopes of an operation as a list. */
35
- function operationScopes(declaration) {
36
- return typeof declaration.scope === "string" ? [declaration.scope] : declaration.scope;
37
- }
38
- /**
39
- * Whether granted scopes admit an operation: any one of its scopes, or every one under `scopeMatch: 'all'`.
40
- * HTTP admission, MCP listing and calls, and execution share it.
41
- */
42
- function operationMatchesScopes(declaration, granted) {
43
- return matchesScopes(operationScopes(declaration), granted, declaration.scopeMatch);
44
- }
45
- /**
46
- * Declares one operation on its own, keeping its literal types. The builder's `.operation()` is the usual way
47
- * to declare one. As there, `execute` receives the decoded input, `StaticDecode<typeof input>`.
48
- */
49
- function operation(definition) {
50
- return definition;
51
- }
52
- /** Where an operation is served, for a refusal that names it: its HTTP route, else its MCP tool. */
53
- function servedAs(declared) {
54
- if (declared?.http) return `${declared.http.method} ${declared.http.path}`;
55
- return declared?.mcp && `the tool ${declared.mcp.name}`;
56
- }
57
- /**
58
- * Merges groups of operations into one, never overwriting: a name two groups declare throws a TypeError,
59
- * `Duplicate operation: <name>`, which names the route or tool of each when both have one.
60
- */
61
- function composeOperations(...groups) {
62
- const result = {};
63
- for (const group of groups) for (const [name, op] of Object.entries(group)) {
64
- if (Object.hasOwn(result, name)) {
65
- const first = servedAs(result[name]);
66
- const second = servedAs(op);
67
- throw new TypeError(first && second ? `Duplicate operation: ${name} names both ${first} and ${second}; give one of them its own operationId.` : `Duplicate operation: ${name}`);
68
- }
69
- Object.defineProperty(result, name, {
70
- value: op,
71
- enumerable: true
72
- });
73
- }
74
- return result;
75
- }
76
- /** The failure codes every operation may answer without declaring them. */
77
- const STANDARD_CODES = new Set(Object.values(STANDARD_FAILURES).map(({ code }) => code));
78
- /**
79
- * The standard failures only routing and admission answer, before an operation runs: an unknown path or
80
- * method, and a missing or refused token. An operation's context, middleware or handler never answers them.
81
- */
82
- const ADMISSION_CODES = /* @__PURE__ */ new Set([
83
- STANDARD_FAILURES.notFound.code,
84
- STANDARD_FAILURES.methodNotAllowed.code,
85
- STANDARD_FAILURES.unauthorized.code
86
- ]);
87
- /**
88
- * The standard failures of reading a request body: admission answers them for a JSON body, and a byte body's
89
- * `read()` for the operation that reads one.
90
- */
91
- const BODY_CODES = /* @__PURE__ */ new Set([STANDARD_FAILURES.tooLarge.code, STANDARD_FAILURES.unsupportedMedia.code]);
92
- /** Default request body limit when neither the operation nor the application sets one. */
93
- const DEFAULT_MAX_BODY_BYTES = 32768;
94
- /** Default output limit when neither the operation nor the application sets one. */
95
- const DEFAULT_MAX_OUTPUT_BYTES = 262144;
96
- /** Largest body limit an application or operation may declare: the body is buffered in memory. */
97
- const MAX_BODY_BYTES_CEILING = 16777216;
98
- /** The request body limit an operation is held to: its own, else the application's, else the default. */
99
- function operationBodyLimit(application, declaration) {
100
- return declaration.maxBodyBytes ?? application.maxBodyBytes ?? 32768;
101
- }
102
- /** The output limit an operation is held to: its own, else the application's, else the default. */
103
- function operationOutputLimit(application, declaration) {
104
- return declaration.maxOutputBytes ?? application.maxOutputBytes ?? 262144;
105
- }
106
- /** Whether an operation's MCP tool reaches outside the service: it does unless it declares otherwise. */
107
- function mcpOpenWorld(tool) {
108
- return tool.openWorld ?? true;
109
- }
110
-
111
14
  // src/internal/claims.ts
112
15
  /**
113
16
  * Reading a verified token's claims, which token verification and Cloudflare Access share.
@@ -371,7 +274,7 @@ function queryInput(kinds, params) {
371
274
  * Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
372
275
  * in place for a reader without components, such as an MCP tool listing.
373
276
  */
374
- /** Plain identifiers TypeBox uses for Recursive/Ref schemas; URLs and pointers are left untouched. */
277
+ /** Plain identifiers TypeBox uses for Cyclic/Ref schemas; URLs and pointers are left untouched. */
375
278
  const SCHEMA_ID = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
376
279
  /** Use-site annotations: they describe one occurrence and do not change which values validate. */
377
280
  const ANNOTATIONS = /* @__PURE__ */ new Set([
@@ -421,15 +324,17 @@ function replaceReferences(value, replace) {
421
324
  return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, key === "$ref" && typeof child === "string" ? replace(child) : replaceReferences(child, replace)]));
422
325
  }
423
326
  /**
424
- * Bundles `$id`-named schemas (TypeBox Recursive/Ref) into components so that every reference in an
327
+ * Bundles `$id`-named schemas (TypeBox Cyclic/Ref) into components so that every reference in an
425
328
  * OpenAPI document is a local `#/components/schemas/<name>` pointer. A plain-name reference resolves
426
329
  * against its enclosing `$id`, as in JSON Schema; structurally different definitions that share an
427
330
  * `$id` (for example a normalized input projection and its output) become distinct components. A
428
331
  * reference outside any definition must name exactly one variant. Use-site annotations stay beside
429
- * the reference. The owner's runtime schemas are not changed.
332
+ * the reference, and `secret`, which only capture reads, is left out. The owner's runtime schemas are not
333
+ * changed.
430
334
  */
431
335
  function bundleSchemas(sources, existing) {
432
- const ids = schemaIds(sources);
336
+ const published = sources.map((source) => withoutSecretKeyword(source));
337
+ const ids = schemaIds(published);
433
338
  const components = {};
434
339
  const variants = /* @__PURE__ */ new Map();
435
340
  const taken = new Set(Object.keys(existing));
@@ -441,6 +346,15 @@ function bundleSchemas(sources, existing) {
441
346
  if (Array.isArray(value)) return value.map((item) => rewrite(item, scope));
442
347
  if (!value || typeof value !== "object") return value;
443
348
  const record = value;
349
+ const definitions = record.$defs;
350
+ if (definitions && typeof record.$ref === "string" && Object.hasOwn(definitions, record.$ref)) {
351
+ for (const [name, definition] of Object.entries(definitions)) if (name !== record.$ref) rewrite(definition, scope);
352
+ const annotations = Object.fromEntries(Object.entries(record).filter(([key]) => ANNOTATIONS.has(key)));
353
+ return {
354
+ ...rewrite(definitions[record.$ref], scope),
355
+ ...annotations
356
+ };
357
+ }
444
358
  if (typeof record.$id === "string" && ids.has(record.$id)) {
445
359
  const { $id: id, ...rest } = record;
446
360
  const definition = Object.fromEntries(Object.entries(rest).filter(([key]) => !ANNOTATIONS.has(key)));
@@ -469,7 +383,7 @@ function bundleSchemas(sources, existing) {
469
383
  return [key, rewrite(child, scope)];
470
384
  }));
471
385
  }
472
- const rewritten = sources.map((source) => rewrite(source, /* @__PURE__ */ new Map()));
386
+ const rewritten = published.map((source) => rewrite(source, /* @__PURE__ */ new Map()));
473
387
  /**
474
388
  * A pending reference as the one component its name has once every variant is known; refused when the name
475
389
  * has several shapes or none.
@@ -505,7 +419,7 @@ function collectReferences(value, references) {
505
419
  /**
506
420
  * The schema with every `$id` nothing refers to removed, the definition left in place: what a reader
507
421
  * that resolves no components meets, the same as before the schema was named. A definition a `$ref`
508
- * names (TypeBox Recursive or Ref) keeps its `$id`, so the reference still resolves.
422
+ * names (TypeBox Cyclic or Ref) keeps its `$id`, so the reference still resolves.
509
423
  */
510
424
  function inlineSchemaNames(value) {
511
425
  const references = /* @__PURE__ */ new Set();
@@ -740,18 +654,6 @@ function failureUnion(codes) {
740
654
  };
741
655
  }
742
656
 
743
- // src/internal/digest.ts
744
- /**
745
- * SHA-256 digests in hexadecimal, for rate limit keys, the development token's comparison and skill
746
- * manifests.
747
- */
748
- /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
749
- async function sha256Hex(value) {
750
- const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
751
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
752
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
753
- }
754
-
755
657
  // src/tokens.ts
756
658
  /**
757
659
  * Token verification: the principal every operation receives, the token policy, OAuth access token
@@ -1101,7 +1003,7 @@ function bodyWithoutPathParameters(input, names) {
1101
1003
  const { $id: _id, ...union } = input;
1102
1004
  return {
1103
1005
  ...union,
1104
- anyOf: input.anyOf.map((schema) => bodyWithoutPathParameters(schema, names))
1006
+ anyOf: (input.anyOf ?? []).map((schema) => bodyWithoutPathParameters(schema, names))
1105
1007
  };
1106
1008
  }
1107
1009
  const carried = Object.keys(input.properties ?? {}).filter((name) => names.has(name)).length;
@@ -1109,7 +1011,7 @@ function bodyWithoutPathParameters(input, names) {
1109
1011
  const { $id: _id, minProperties, maxProperties, ...object } = input;
1110
1012
  return {
1111
1013
  ...object,
1112
- properties: Object.fromEntries(Object.entries(input.properties).filter(([name]) => !names.has(name))),
1014
+ properties: Object.fromEntries(Object.entries(input.properties ?? {}).filter(([name]) => !names.has(name))),
1113
1015
  required: (input.required ?? []).filter((name) => !names.has(name)),
1114
1016
  ...typeof minProperties === "number" && minProperties > carried ? { minProperties: minProperties - carried } : {},
1115
1017
  ...typeof maxProperties === "number" ? { maxProperties: maxProperties - carried } : {}
@@ -1122,7 +1024,7 @@ function bodyWithoutPathParameters(input, names) {
1122
1024
  * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
1123
1025
  *
1124
1026
  * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
1125
- * schemas of its paths and components (TypeBox Recursive/Ref) become components, as `bundleSchemas`
1027
+ * schemas of its paths and components (TypeBox Cyclic/Ref) become components, as `bundleSchemas`
1126
1028
  * describes. A schema `$id` that takes the name of a component the document writes itself, and a component
1127
1029
  * named as a generator names an operation's own types, such as `CreateNoteResponse`, throw a TypeError.
1128
1030
  */
@@ -1267,7 +1169,7 @@ function openApiDocument(manifest, kind) {
1267
1169
  },
1268
1170
  ...rpc ? {} : { servers: [{ url: manifest.origin }] },
1269
1171
  tags: groups.map((group) => {
1270
- const description = manifest.groups?.[group];
1172
+ const description = manifest.groups?.[group] ?? (group === "Operation tasks" ? "The tasks of operations that answer before they finish: read one you started, or cancel one that has not started running." : void 0);
1271
1173
  return description ? {
1272
1174
  name: group,
1273
1175
  description
@@ -1504,7 +1406,7 @@ function failureResponse(name, status, failures, components) {
1504
1406
  }
1505
1407
  /** A failure as its component, `<Code>Failure`, with its data: the schema its definition declares, else `Empty`. */
1506
1408
  function addFailure(definition, components) {
1507
- const { dataSchema } = definition;
1409
+ const dataSchema = definition.dataSchema;
1508
1410
  let data;
1509
1411
  if (dataSchema === void 0 || isEmptyObject(dataSchema)) data = components.add("Empty", EMPTY_OBJECT);
1510
1412
  else if (typeof dataSchema.$id === "string") data = dataSchema;
@@ -1585,4 +1487,4 @@ function securitySchemes(tokens, scopes) {
1585
1487
  };
1586
1488
  }
1587
1489
 
1588
- export { operationOutputLimit as A, MAX_BODY_BYTES_CEILING as C, mcpOpenWorld as D, isPublicOperation as E, isNamespacedScope as M, matchesScopes as N, operation as O, DEFAULT_MAX_BODY_BYTES as S, composeOperations as T, projectAccessToken as _, createTokenVerifier as a, ADMISSION_CODES as b, tokenIssuer as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, operationScopes as j, operationMatchesScopes as k, usesOwnBearer as l, queryInput as m, createRpcOpenApi as n, projectToken as o, standaloneSchema as p, checkTokenAuthority as r, tokenAudiences as s, createOpenApi as t, sha256Hex as u, usesCloudflareAccess as v, STANDARD_CODES as w, BODY_CODES as x, PrincipalSchema as y };
1490
+ export { projectAccessToken as _, createTokenVerifier as a, tokenAudiences as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, tokenIssuer as l, queryInput as m, createRpcOpenApi as n, presentedToken as o, standaloneSchema as p, checkTokenAuthority as r, projectToken as s, createOpenApi as t, usesOwnBearer as u, usesCloudflareAccess as v, PrincipalSchema as y };
@@ -1,15 +1,15 @@
1
- import { n as createRpcOpenApi } from "./openapi-CeolxIqa.js";
1
+ import { n as createRpcOpenApi } from "./openapi-D2rds7vy.js";
2
2
  import { t as prepareConfiguredProject } from "./prepare-configured-Cithjf80.js";
3
3
  import { t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
5
+ import { dirname, join, relative, resolve } from "node:path";
6
6
 
7
7
  // src/tooling/internal/openapi-file.ts
8
8
  /**
9
9
  * `maximus openapi`: the OpenAPI documents of a project's Worker, as files beside its sources. The HTTP
10
10
  * document, the one the Worker serves, is the contract the project's clients are generated from; the RPC
11
11
  * document, of the operations it serves over native RPC, is the one other services type their bindings from.
12
- * `--check` keeps both current in CI.
12
+ * `--check` keeps both current and valid OpenAPI 3.1 in CI.
13
13
  */
14
14
  /** The file `maximus openapi` writes the HTTP document to unless `--out` names another, at the project's root. */
15
15
  const OPENAPI_FILE = "openapi.json";
@@ -49,6 +49,19 @@ function operationCount(document) {
49
49
  const paths = document.paths ?? {};
50
50
  return Object.values(paths).reduce((count, methods) => count + Object.keys(methods).length, 0);
51
51
  }
52
+ /** The most problems a refused document names. */
53
+ const MAX_PROBLEMS = 5;
54
+ /**
55
+ * Throws when a document is not valid OpenAPI 3.1, naming its file and its first problems. The validator is
56
+ * build-time tooling: it loads for the check alone, never in a Worker.
57
+ */
58
+ async function assertValidOpenApi(name, document) {
59
+ const { validate } = await import("@scalar/openapi-parser");
60
+ const result = await validate(structuredClone(document));
61
+ if (result.valid && result.version === "3.1") return;
62
+ const problems = result.valid ? [`it declares OpenAPI ${result.version}`] : result.errors.slice(0, MAX_PROBLEMS).map(({ path, message }) => path?.length ? `${[path].flat().join("/")}: ${message}` : message);
63
+ throw new Error(`${name} is not valid OpenAPI 3.1: ${problems.join("; ")}.`);
64
+ }
52
65
  /** Writes a document to a file as JSON with two-space indentation, unless `check` asks only whether it differs. */
53
66
  function writeDocument(file, document, check) {
54
67
  const text = `${JSON.stringify(document, null, 2)}\n`;
@@ -66,14 +79,19 @@ function writeDocument(file, document, check) {
66
79
  /**
67
80
  * Writes the documents of the project's Worker: the HTTP one to `out`, `openapi.json` at its root by default,
68
81
  * and, when an operation declares `rpc`, the RPC one beside it, `openapi.rpc.json`. With `check`, writes
69
- * nothing and answers whether each file differs.
82
+ * nothing, throws for a document that is not valid OpenAPI 3.1 and answers whether each file differs.
70
83
  */
71
84
  async function writeOpenApi(directory, { out = OPENAPI_FILE, check = false } = {}) {
72
85
  const documents = await projectDocuments(directory);
73
86
  const file = resolve(directory, out);
74
- const written = writeDocument(file, documents.http, check);
75
- if (!operationCount(documents.rpc)) return written;
76
87
  const rpcFile = file.endsWith(".json") ? `${file.slice(0, -5)}.rpc.json` : `${file}.rpc.json`;
88
+ const servesRpc = operationCount(documents.rpc) > 0;
89
+ if (check) {
90
+ await assertValidOpenApi(relative(directory, file), documents.http);
91
+ if (servesRpc) await assertValidOpenApi(relative(directory, rpcFile), documents.rpc);
92
+ }
93
+ const written = writeDocument(file, documents.http, check);
94
+ if (!servesRpc) return written;
77
95
  return {
78
96
  ...written,
79
97
  rpc: writeDocument(rpcFile, documents.rpc, check)
@@ -1,4 +1,4 @@
1
- import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-DS8DnPyu.js";
1
+ import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-BcYH4I2w.js";
2
2
 
3
3
  // src/project/pages.ts
4
4
  /**
@@ -0,0 +1,29 @@
1
+ import { t as isRecord } from "./record-DQUDTpEA.js";
2
+
3
+ // src/result.ts
4
+ /** A success carrying `value`. */
5
+ function ok(value) {
6
+ return {
7
+ ok: true,
8
+ value
9
+ };
10
+ }
11
+ /** A failure carrying `error`, usually `catalog.someFailure.create()`. */
12
+ function err(error) {
13
+ return {
14
+ ok: false,
15
+ error
16
+ };
17
+ }
18
+ /**
19
+ * Whether an untrusted answer (a Service Binding's, a stored one) is a Maximus Result: a success with
20
+ * its value, or a failure with a well-formed error. Anything else is not an answer at all.
21
+ */
22
+ function isResult(value) {
23
+ if (!isRecord(value)) return false;
24
+ if (value.ok === true) return "value" in value;
25
+ const { error } = value;
26
+ return value.ok === false && isRecord(error) && typeof error.code === "string" && typeof error.message === "string" && typeof error.retryable === "boolean" && isRecord(error.data);
27
+ }
28
+
29
+ export { isResult as n, ok as r, err as t };
@@ -1,11 +1,12 @@
1
- import { r as parseInput } from "./validation-fTohBT6R.js";
1
+ import { i as parseInput } from "./validation-CpzAxj2_.js";
2
2
  import { r as isRequestId } from "./correlation-4b23a-a4.js";
3
- import { i as standardErrors } from "./errors-C5w9WY1l.js";
4
- import { r as ok, t as err } from "./result-CKgZHrnj.js";
5
- import { y as PrincipalSchema } from "./openapi-CeolxIqa.js";
6
- import { r as createHttpHandler } from "./src-CPrJpbOM.js";
7
- import { a as telemetryEnabled, i as reportUnexpected, r as recordExecution, s as withTelemetry } from "./telemetry-C3LfZcOB.js";
8
- import { t as executeOperation } from "./execution-rOiLo8VG.js";
3
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
4
+ import { y as PrincipalSchema } from "./openapi-D2rds7vy.js";
5
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
+ import { r as createHttpHandler } from "./src-D67OfW9B.js";
7
+ import { t as delay } from "./delay-BsKQP_lF.js";
8
+ import { a as recordExecution, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
9
+ import { n as recordCapture, t as executeOperation } from "./execution-Bpq6s4nA.js";
9
10
  import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
10
11
 
11
12
  // src/workers/assets.ts
@@ -149,6 +150,129 @@ function annotateInvocation(service, operation, requestId, attributeNames = {
149
150
  } catch {}
150
151
  }
151
152
 
153
+ // src/workers/tasks.ts
154
+ /**
155
+ * The task store and its executor: one SQLite Durable Object per task keeps it and runs it from its alarm, at
156
+ * once and at most once, so no task waits for another. The input is never stored: it stays in the object's
157
+ * memory until the alarm starts the task. A task found started but still working, after the object restarted
158
+ * mid-run, settles as OUTCOME_UNKNOWN and never runs again; one whose input went with a restart before it
159
+ * started settles as INTERNAL_ERROR, never having run. The object deletes everything once the task's TTL has
160
+ * passed since its call.
161
+ */
162
+ /** Where the object keeps its task. */
163
+ const KEY = "task";
164
+ /** Whether `principal` started the task: the same organization and the same actor. */
165
+ const owns = (task, principal) => task.principal.organizationId === principal.organizationId && task.principal.actorId === principal.actorId && task.principal.actorKind === principal.actorKind;
166
+ /** The task store class of an application, which a Worker exports for its `MAXIMUS_TASKS` binding. */
167
+ function tasksObject(manifest) {
168
+ return class MaximusTasks extends DurableObject {
169
+ /** The task's input, in memory alone, until the task starts. */
170
+ #input;
171
+ /** Answers the call waiting for the task to settle. */
172
+ #settled;
173
+ /** Whether this instance is running the task: a task found started otherwise was interrupted. */
174
+ #running = false;
175
+ /** Keeps the task, has the alarm start it at once, and answers it once it settles or `waitMs` passes. */
176
+ async run(task, input, waitMs) {
177
+ const settled = new Promise((resolve) => {
178
+ this.#settled = resolve;
179
+ });
180
+ this.#input = { value: input };
181
+ await this.ctx.storage.put(KEY, task);
182
+ await this.ctx.storage.setAlarm(Date.now());
183
+ await Promise.race([settled, delay(waitMs)]);
184
+ return await this.ctx.storage.get(KEY) ?? task;
185
+ }
186
+ /** The task, when `principal` started it and it has not expired. */
187
+ async get(taskId, principal) {
188
+ const task = await this.ctx.storage.get(KEY);
189
+ if (!task || task.taskId !== taskId || task.createdAt + task.ttlMs <= Date.now()) return;
190
+ return owns(task, principal) ? task : void 0;
191
+ }
192
+ /** Cancels a task `principal` started that has not started running; one that has runs to its end. */
193
+ async cancel(taskId, principal) {
194
+ const task = await this.get(taskId, principal);
195
+ if (task?.status !== "working" || task.started) return task;
196
+ this.#input = void 0;
197
+ const cancelled = {
198
+ ...task,
199
+ status: "cancelled",
200
+ lastUpdatedAt: Date.now()
201
+ };
202
+ await this.ctx.storage.put(KEY, cancelled);
203
+ return cancelled;
204
+ }
205
+ /** Runs the task, or settles one a restart interrupted, then wakes once more to delete it when it expires. */
206
+ async alarm() {
207
+ const input = this.#input;
208
+ this.#input = void 0;
209
+ const task = await this.ctx.storage.get(KEY);
210
+ if (!task || task.createdAt + task.ttlMs <= Date.now()) {
211
+ await this.ctx.storage.deleteAll();
212
+ return;
213
+ }
214
+ if (task.status === "working" && !this.#running) {
215
+ if (task.started) await this.#settle(task, err(standardErrors.outcomeUnknown.create()));
216
+ else if (input) await this.#execute(task, input.value);
217
+ else await this.#settle(task, err(standardErrors.internal.create()));
218
+ }
219
+ await this.ctx.storage.setAlarm(task.createdAt + task.ttlMs);
220
+ }
221
+ /** Marks the task started, then runs its operation as its caller and keeps the result. */
222
+ async #execute(task, input) {
223
+ const pending = [];
224
+ const background = { waitUntil: (promise) => {
225
+ pending.push(promise);
226
+ } };
227
+ this.#running = true;
228
+ try {
229
+ await this.ctx.storage.put(KEY, {
230
+ ...task,
231
+ started: true
232
+ });
233
+ const operation = manifest.operations[task.operation];
234
+ const surface = task.authority?.surface ?? "http";
235
+ const call = { taskId: task.taskId };
236
+ const started = performance.now();
237
+ const result = operation ? await executeOperation(manifest, operation, this.env, task.principal, input, task.authority, background, void 0, call) : err(standardErrors.notFound.create());
238
+ recordExecution(manifest, this.env, background, {
239
+ principal: task.principal,
240
+ operation: task.operation,
241
+ surface,
242
+ started,
243
+ result
244
+ });
245
+ recordCapture(manifest, this.env, background, {
246
+ operation: task.operation,
247
+ surface,
248
+ requestId: task.principal.requestId,
249
+ principal: task.principal,
250
+ requestStarted: started,
251
+ executionStarted: started,
252
+ result,
253
+ call
254
+ });
255
+ await this.#settle(task, result);
256
+ } finally {
257
+ this.#running = false;
258
+ }
259
+ await Promise.allSettled(pending);
260
+ }
261
+ /** Keeps how the task ended and answers the call waiting for it. */
262
+ async #settle(task, result) {
263
+ const status = result.ok ? "completed" : "failed";
264
+ await this.ctx.storage.put(KEY, {
265
+ ...task,
266
+ started: true,
267
+ status,
268
+ result,
269
+ lastUpdatedAt: Date.now()
270
+ });
271
+ this.#settled?.();
272
+ }
273
+ };
274
+ }
275
+
152
276
  // src/workers/credentials.ts
153
277
  /**
154
278
  * Reads one organization's credential from its own store, such as a Durable Object per organization, and
@@ -200,13 +324,32 @@ function createWorker(application, options = {}) {
200
324
  Object.defineProperty(Entrypoint.prototype, name, {
201
325
  configurable: true,
202
326
  async value(principal, input) {
327
+ const requestStarted = performance.now();
203
328
  const props = this.ctx.props;
204
- if (!props || Object.keys(props).length !== 1 || typeof props.caller !== "string" || !callers.includes(props.caller)) return err(standardErrors.unauthorized.create());
205
329
  const parsed = parseInput(PrincipalSchema, principal);
206
- if (!parsed.ok) return err(standardErrors.unauthorized.create());
330
+ /**
331
+ * Refuses the call, and captures the refusal: the principal it names is unverified, so the record keeps
332
+ * its request id, for correlation, and never its organization or actor.
333
+ */
334
+ const refuse = () => {
335
+ const refusal = err(standardErrors.unauthorized.create());
336
+ recordCapture(manifest, this.env, this.ctx, {
337
+ operation: name,
338
+ surface: "rpc",
339
+ requestId: parsed.ok ? parsed.value.requestId : crypto.randomUUID(),
340
+ principal: null,
341
+ requestStarted,
342
+ result: refusal,
343
+ call: typeof props?.caller === "string" ? { rpcCaller: props.caller.slice(0, 64) } : {}
344
+ });
345
+ return refusal;
346
+ };
347
+ if (!props || Object.keys(props).length !== 1 || typeof props.caller !== "string" || !callers.includes(props.caller)) return refuse();
348
+ if (!parsed.ok) return refuse();
207
349
  if (telemetryEnabled(manifest.telemetry, this.env)) annotateInvocation(manifest.name, name, parsed.value.requestId);
350
+ const call = { rpcCaller: props.caller };
208
351
  const started = performance.now();
209
- const result = await withTelemetry(manifest.telemetry, this.env, () => executeOperation(manifest, op, this.env, parsed.value, input, void 0, this.ctx));
352
+ const result = await withTelemetry(manifest.telemetry, this.env, () => executeOperation(manifest, op, this.env, parsed.value, input, void 0, this.ctx, void 0, call));
210
353
  recordExecution(manifest, this.env, this.ctx, {
211
354
  principal: parsed.value,
212
355
  operation: name,
@@ -214,6 +357,16 @@ function createWorker(application, options = {}) {
214
357
  started,
215
358
  result
216
359
  });
360
+ recordCapture(manifest, this.env, this.ctx, {
361
+ operation: name,
362
+ surface: "rpc",
363
+ requestId: parsed.value.requestId,
364
+ principal: parsed.value,
365
+ requestStarted,
366
+ executionStarted: started,
367
+ result,
368
+ call
369
+ });
217
370
  return result;
218
371
  }
219
372
  });
@@ -241,7 +394,8 @@ function createWorker(application, options = {}) {
241
394
  service,
242
395
  durableObject(implementation) {
243
396
  return instrumentDurableObject(implementation, manifest.telemetry);
244
- }
397
+ },
398
+ tasks: instrumentDurableObject(tasksObject(manifest), manifest.telemetry)
245
399
  };
246
400
  }
247
401