@arbol-ai/maximus 7.2.0 → 7.3.1

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 (79) hide show
  1. package/config/oxfmt.mjs +1 -0
  2. package/config/oxlint.mjs +1 -0
  3. package/dist/analytics/analytics.d.ts +2 -4
  4. package/dist/analytics/analytics.js +3 -4
  5. package/dist/body.d.ts +1 -1
  6. package/dist/body.js +2 -2
  7. package/dist/chunks/{body-BcMbreNd.js → body-6LichrQm.js} +1 -2
  8. package/dist/chunks/{correlation-gaiEoMBr.js → correlation-BEkcFFGT.js} +1 -2
  9. package/dist/chunks/{execution-qfZuMSIu.js → execution-B-yy4C7N.js} +14 -23
  10. package/dist/chunks/{json-Dwni3u4c.js → json-Bu4BLT25.js} +2 -3
  11. package/dist/chunks/prepare-project-zi106pWF.js +146 -0
  12. package/dist/chunks/{record-D2H3cg8S.js → record-DY-lX9w1.js} +2 -4
  13. package/dist/chunks/runtime-BPnaa-NK.js +223 -0
  14. package/dist/chunks/{schemas-q-51wBMQ.js → schemas-CzTvbXb6.js} +6 -11
  15. package/dist/chunks/{src-Bqznd6Dd.js → src-DPSpGNnT.js} +13 -20
  16. package/dist/chunks/{telemetry-DvZgrzZn.js → telemetry-BTwB68m5.js} +2 -4
  17. package/dist/chunks/{types-BCPe0fok.d.ts → types-BWxDd3tY.d.ts} +105 -51
  18. package/dist/chunks/{validation-DWxKk1Js.js → validation-r-sgmsqb.js} +3 -6
  19. package/dist/client/client.d.ts +1 -3
  20. package/dist/client/client.js +7 -11
  21. package/dist/diagnostics.d.ts +1 -3
  22. package/dist/diagnostics.js +2 -2
  23. package/dist/errors.d.ts +1 -1
  24. package/dist/errors.js +3 -4
  25. package/dist/http-paths.d.ts +1 -1
  26. package/dist/http-paths.js +1 -2
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +7 -7
  29. package/dist/internals.d.ts +1 -1
  30. package/dist/internals.js +2 -2
  31. package/dist/mcp/index.d.ts +2 -4
  32. package/dist/mcp/index.js +5 -7
  33. package/dist/postgres/index.d.ts +0 -4
  34. package/dist/postgres/index.js +2 -4
  35. package/dist/project/index.d.ts +24 -0
  36. package/dist/project/index.js +82 -0
  37. package/dist/projection.d.ts +1 -3
  38. package/dist/projection.js +1 -2
  39. package/dist/schemas.d.ts +1 -1
  40. package/dist/schemas.js +2 -2
  41. package/dist/standard-failures.d.ts +1 -3
  42. package/dist/standard-failures.js +1 -2
  43. package/dist/tooling/cli.js +41 -24
  44. package/dist/tooling/testing.d.ts +1 -3
  45. package/dist/tooling/testing.js +1 -2
  46. package/dist/tooling/vite.d.ts +3 -0
  47. package/dist/tooling/vite.js +44 -0
  48. package/dist/webhooks.d.ts +2 -4
  49. package/dist/webhooks.js +1 -2
  50. package/dist/workers/runtime.d.ts +2 -112
  51. package/dist/workers/runtime.js +1 -226
  52. package/package.json +19 -6
  53. package/skills/maximus/SKILL.md +1 -1
  54. package/skills/maximus/references/building-a-service.md +9 -0
  55. package/templates/project/.agents/skills/project/SKILL.md.template +17 -0
  56. package/templates/project/.github/workflows/ci.yml.template +36 -0
  57. package/templates/project/.gitignore.template +10 -0
  58. package/templates/project/CLAUDE.md.template +34 -0
  59. package/templates/project/README.md.template +47 -0
  60. package/templates/project/cloudflare.config.ts.template +24 -0
  61. package/templates/project/package.json.template +38 -0
  62. package/templates/project/pages/index.ts.template +11 -0
  63. package/templates/project/routes/v1/greeting.ts.template +22 -0
  64. package/templates/project/src/app.ts.template +2 -0
  65. package/templates/project/src/application.ts.template +26 -0
  66. package/templates/project/src/index.ts.template +3 -0
  67. package/templates/project/src/worker.ts.template +6 -0
  68. package/templates/project/tsconfig.json.template +30 -0
  69. package/templates/project/vite.config.ts.template +11 -0
  70. package/templates/service/.github/workflows/ci.yml.template +1 -1
  71. package/templates/service/.gitignore.template +1 -0
  72. package/templates/service/CLAUDE.md.template +2 -0
  73. package/templates/service/README.md.template +7 -7
  74. package/templates/service/package.json.template +14 -9
  75. package/templates/service/tests/contract.test.ts.template +1 -1
  76. package/templates/service/vite.config.ts.template +8 -2
  77. package/templates/service/vitest.config.ts.template +1 -1
  78. package/templates/service/oxfmt.config.ts.template +0 -1
  79. package/templates/service/oxlint.config.ts.template +0 -1
package/config/oxfmt.mjs CHANGED
@@ -18,6 +18,7 @@ export default defineConfig({
18
18
  ...ultracite.ignorePatterns,
19
19
  '**/.private/**',
20
20
  '**/.cloudflare/**',
21
+ '**/.maximus/**',
21
22
  '**/.wrangler/**',
22
23
  '**/dist/**',
23
24
  '**/.agents/**',
package/config/oxlint.mjs CHANGED
@@ -32,6 +32,7 @@ export default defineConfig({
32
32
  ignorePatterns: [
33
33
  ...core.ignorePatterns,
34
34
  '**/.cloudflare',
35
+ '**/.maximus',
35
36
  '**/.wrangler',
36
37
  '**/.private',
37
38
  '**/.agents',
@@ -1,6 +1,5 @@
1
- import { bn as Result, kn as Failure, qt as Observer } from "../chunks/types-BCPe0fok.js";
1
+ import { $t as Observer, En as Result, Fn as Failure } from "../chunks/types-BWxDd3tY.js";
2
2
  import { Static } from "@sinclair/typebox";
3
- //#region src/analytics/analytics.d.ts
4
3
  /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
5
4
  export declare const ExecutionEventSchema: import("@sinclair/typebox").TObject<{
6
5
  id: import("@sinclair/typebox").TString;
@@ -30,5 +29,4 @@ export interface ExecutionSink {
30
29
  export declare function analytics<E>(options: {
31
30
  enabled?: boolean | ((env: E) => boolean);
32
31
  record: (env: E, event: ExecutionEvent) => Promise<unknown>;
33
- }): Observer<E>;
34
- //#endregion
32
+ }): Observer<E>;
@@ -1,8 +1,8 @@
1
- import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-q-51wBMQ.js";
2
- import { a as telemetryEnabled } from "../chunks/telemetry-DvZgrzZn.js";
1
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-CzTvbXb6.js";
2
+ import { a as telemetryEnabled } from "../chunks/telemetry-BTwB68m5.js";
3
3
  import { Type } from "@sinclair/typebox";
4
4
 
5
- //#region src/analytics/analytics.ts
5
+ // src/analytics/analytics.ts
6
6
  /**
7
7
  * `@arbol-ai/maximus/analytics`: an observer that turns each operation call's observation into an
8
8
  * allowlisted analytics event and records it in a sink the application provides. No input, output or
@@ -58,5 +58,4 @@ function analytics(options) {
58
58
  } };
59
59
  }
60
60
 
61
- //#endregion
62
61
  export { ExecutionEventSchema, analytics };
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { c as isJsonMediaType, d as retryAfterSeconds, f as BodyReadOptions, g as readBodyText, h as readBodyBytes, l as readJsonBody, m as HttpBodyFailureReason, p as HttpBodyFailure, u as readJsonResponse } from "./chunks/types-BCPe0fok.js";
1
+ import { S as readBodyText, _ as retryAfterSeconds, b as HttpBodyFailureReason, g as readJsonResponse, h as readJsonBody, m as isJsonMediaType, v as BodyReadOptions, x as readBodyBytes, y as HttpBodyFailure } from "./chunks/types-BWxDd3tY.js";
2
2
  export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
package/dist/body.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as readBodyBytes, r as readBodyText } from "./chunks/body-BcMbreNd.js";
2
- import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-Dwni3u4c.js";
1
+ import { n as readBodyBytes, r as readBodyText } from "./chunks/body-6LichrQm.js";
2
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-Bu4BLT25.js";
3
3
 
4
4
  export { isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -1,4 +1,4 @@
1
- //#region src/internal/body.ts
1
+ // src/internal/body.ts
2
2
  /** Closed decoding vocabulary used by bounded transport readers. */
3
3
  const HTTP_BODY_FAILURES = [
4
4
  "too_large",
@@ -102,5 +102,4 @@ async function readBodyText(source, options) {
102
102
  }
103
103
  }
104
104
 
105
- //#endregion
106
105
  export { readBodyBytes as n, readBodyText as r, httpBodyFailure as t };
@@ -1,4 +1,4 @@
1
- //#region src/internal/correlation.ts
1
+ // src/internal/correlation.ts
2
2
  /**
3
3
  * Request correlation: request ids (a UUID, or a ray id from a trusted Cloudflare edge), W3C `traceparent`
4
4
  * parsing, and the correlation that durable work persists.
@@ -41,5 +41,4 @@ function durableCorrelation(requestId, originTraceParent) {
41
41
  };
42
42
  }
43
43
 
44
- //#endregion
45
44
  export { parseTraceParent as i, durableCorrelation as n, isRequestId as r, createRequestId as t };
@@ -1,16 +1,16 @@
1
1
  import { STANDARD_FAILURES } from "../standard-failures.js";
2
- import { l as hasUncompiledCodecs, r as parseInput, t as decodeInput } from "./validation-DWxKk1Js.js";
2
+ import { l as hasUncompiledCodecs, r as parseInput, t as decodeInput } from "./validation-r-sgmsqb.js";
3
3
  import { standardErrors } from "../errors.js";
4
- import { n as readBodyBytes } from "./body-BcMbreNd.js";
5
- import { n as exactLength, t as isRecord } from "./record-D2H3cg8S.js";
4
+ import { n as readBodyBytes } from "./body-6LichrQm.js";
5
+ import { n as exactLength, t as isRecord } from "./record-DY-lX9w1.js";
6
6
  import { createHttpRouteResolver, isInputHeaderName, operationPathParameters } from "../http-paths.js";
7
- import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-q-51wBMQ.js";
8
- import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-DvZgrzZn.js";
7
+ import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-CzTvbXb6.js";
8
+ import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-BTwB68m5.js";
9
9
  import { Kind, Type } from "@sinclair/typebox";
10
10
  import { Value } from "@sinclair/typebox/value";
11
11
  import { createRemoteJWKSet, jwtVerify } from "jose";
12
12
 
13
- //#region src/binary.ts
13
+ // src/binary.ts
14
14
  /**
15
15
  * Byte bodies and file attachments over HTTP: the on-demand reader of a declared byte body, the checks an
16
16
  * attachment output passes before anything is sent, and the exact-length response that serves it.
@@ -82,8 +82,7 @@ function attachmentResponse(file, status = 200) {
82
82
  });
83
83
  }
84
84
 
85
- //#endregion
86
- //#region src/internal/http-routes.ts
85
+ // src/internal/http-routes.ts
87
86
  /** Every body variant must declare its path authority as a required string field. */
88
87
  function pathParameterSchemas(input, parameter) {
89
88
  if (input.type === "object") {
@@ -95,8 +94,7 @@ function pathParameterSchemas(input, parameter) {
95
94
  throw new TypeError("Path parameters require object input contracts.");
96
95
  }
97
96
 
98
- //#endregion
99
- //#region src/scopes.ts
97
+ // src/scopes.ts
100
98
  /** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
101
99
  const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
102
100
  /** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
@@ -113,8 +111,7 @@ function matchesScopes(required, granted, match = "any") {
113
111
  return match === "all" ? required.every(has) : match === "any" && required.some(has);
114
112
  }
115
113
 
116
- //#endregion
117
- //#region src/manifest.ts
114
+ // src/manifest.ts
118
115
  /** Whether an operation belongs in public contracts (OpenAPI, typed clients, discovery metadata). */
119
116
  function isPublicOperation(declaration) {
120
117
  return declaration.visibility !== "internal";
@@ -167,8 +164,7 @@ function mcpOpenWorld(tool) {
167
164
  return tool.openWorld ?? true;
168
165
  }
169
166
 
170
- //#endregion
171
- //#region src/internal/digest.ts
167
+ // src/internal/digest.ts
172
168
  /**
173
169
  * SHA-256 digests in hexadecimal, for rate limit keys and skill manifests.
174
170
  */
@@ -179,8 +175,7 @@ async function sha256Hex(value) {
179
175
  return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
180
176
  }
181
177
 
182
- //#endregion
183
- //#region src/result.ts
178
+ // src/result.ts
184
179
  /** A success carrying `value`. */
185
180
  function ok(value) {
186
181
  return {
@@ -206,8 +201,7 @@ function isResult(value) {
206
201
  return value.ok === false && isRecord(error) && typeof error.code === "string" && typeof error.message === "string" && typeof error.retryable === "boolean" && isRecord(error.data);
207
202
  }
208
203
 
209
- //#endregion
210
- //#region src/tokens.ts
204
+ // src/tokens.ts
211
205
  /**
212
206
  * Token verification: the principal every operation receives, the token policy, OAuth access token
213
207
  * verification against the issuer's JWKS, claim projection, and request admission by scope.
@@ -481,8 +475,7 @@ function createTokenAuthorization(policy, given) {
481
475
  };
482
476
  }
483
477
 
484
- //#endregion
485
- //#region src/define-app.ts
478
+ // src/define-app.ts
486
479
  /** Names a Worker entrypoint already uses, or that would break a class or a promise. */
487
480
  const RESERVED_NAMES = /* @__PURE__ */ new Set([
488
481
  "fetch",
@@ -631,8 +624,7 @@ function strictObject(schema, unions) {
631
624
  return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
632
625
  }
633
626
 
634
- //#endregion
635
- //#region src/execution.ts
627
+ // src/execution.ts
636
628
  /**
637
629
  * The one execution path every transport calls: the caller's eligibility, input decoding, context
638
630
  * preparation, middleware, the handler, and the checks on what it returns.
@@ -696,5 +688,4 @@ async function executeOperation(manifest, operation, env, principal, input, auth
696
688
  }
697
689
  }
698
690
 
699
- //#endregion
700
691
  export { operationMatchesScopes as C, pathParameterSchemas as D, matchesScopes as E, attachmentResponse as O, operationBodyLimit as S, operationScopes as T, STANDARD_CODES as _, createTokenVerifier as a, mcpOpenWorld as b, tokenEndpoints as c, err as d, isResult as f, MAX_BODY_BYTES_CEILING as g, DEFAULT_MAX_BODY_BYTES as h, createTokenAuthorization as i, binaryBody as k, tokenIssuer as l, sha256Hex as m, defineApp as n, projectToken as o, ok as p, PrincipalSchema as r, tokenAudiences as s, executeOperation as t, usesOwnBearer as u, composeOperations as v, operationOutputLimit as w, operation as x, isPublicOperation as y };
@@ -1,6 +1,6 @@
1
- import { r as readBodyText, t as httpBodyFailure } from "./body-BcMbreNd.js";
1
+ import { r as readBodyText, t as httpBodyFailure } from "./body-6LichrQm.js";
2
2
 
3
- //#region src/internal/json.ts
3
+ // src/internal/json.ts
4
4
  /** The media type of a Content-Type value, lowercased and without its parameters. */
5
5
  function mediaType(contentType) {
6
6
  return contentType?.split(";", 1)[0]?.trim().toLowerCase();
@@ -59,5 +59,4 @@ function retryAfterSeconds(value, nowMs, maximum = 3600) {
59
59
  return Number.isFinite(seconds) ? Math.min(maximum, Math.max(0, Math.ceil(seconds))) : void 0;
60
60
  }
61
61
 
62
- //#endregion
63
62
  export { retryAfterSeconds as a, readJsonResponse as i, mediaType as n, readJsonBody as r, isJsonMediaType as t };
@@ -0,0 +1,146 @@
1
+ import { join, relative, resolve, sep } from "node:path";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
3
+
4
+ // src/tooling/internal/project-files.ts
5
+ /** Deterministic source discovery. Only ordinary source files inside opted-in directories are loaded. */
6
+ /** Project-owned convention directories; infrastructure remains in cloudflare.config.ts. */
7
+ const PROJECT_DIRECTORIES = [
8
+ "routes",
9
+ "pages",
10
+ "middleware",
11
+ "crons",
12
+ "queues",
13
+ "email",
14
+ "durable-objects"
15
+ ];
16
+ /** Sort by code units so generated imports are identical on every locale and platform. */
17
+ function compareNames(a, b) {
18
+ return a < b ? -1 : Number(a > b);
19
+ }
20
+ /** Discover without following symlinks or importing user code into the build host. */
21
+ function projectFiles(root, directory, mode) {
22
+ const folder = resolve(root, directory);
23
+ if (!existsSync(folder)) return [];
24
+ if (lstatSync(folder).isSymbolicLink()) throw new TypeError(`Project directory cannot be a symlink: ${directory}`);
25
+ const files = [];
26
+ function visit(current) {
27
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
28
+ if (entry.name.startsWith(".") || entry.name.startsWith("_") && !(directory === "email" && entry.name.startsWith("_default."))) continue;
29
+ const file = join(current, entry.name);
30
+ if (entry.isSymbolicLink()) throw new TypeError(`Project modules cannot be symlinks: ${relative(root, file)}`);
31
+ if (entry.isDirectory()) visit(file);
32
+ else if (entry.isFile() && /\.(?:[cm]?ts|tsx|[cm]?js|jsx)$/.test(entry.name) && !/\.(?:d|test|spec)(?:\.(?:dev|prod))?\.[^.]+$/.test(entry.name)) {
33
+ const name = relative(folder, file).split(sep).join("/").replace(/\.[^.]+$/, "");
34
+ const environment = /\.(dev|prod)$/.exec(name)?.[1];
35
+ if (environment && (environment === "dev" ? mode !== "development" : mode !== "production")) continue;
36
+ files.push({
37
+ file,
38
+ name: name.replace(/\.(?:dev|prod)$/, "")
39
+ });
40
+ }
41
+ }
42
+ }
43
+ visit(folder);
44
+ files.sort((a, b) => compareNames(a.file, b.file));
45
+ return files;
46
+ }
47
+ /** Convert groups, index files and dynamic operation segments into a native Maximus path. */
48
+ function projectPath(name, kind) {
49
+ const segments = name.split("/").filter((segment) => !/^\([a-zA-Z0-9_-]+\)$/.test(segment));
50
+ if (segments.at(-1) === "index") segments.pop();
51
+ const path = `/${segments.map((segment) => {
52
+ const parameter = /^\[([a-zA-Z][a-zA-Z0-9_]*)\]$/.exec(segment)?.[1];
53
+ if (parameter && kind === "routes") return `{${parameter}}`;
54
+ if (!/^[a-zA-Z0-9_-]+$/.test(segment)) throw new TypeError(`Unsupported ${kind} segment: ${segment}. Pages use fixed paths; operations support [parameter].`);
55
+ return segment;
56
+ }).join("/")}`;
57
+ if (kind === "routes" && !/^\/v[1-9][0-9]*\/.+/.test(path)) throw new TypeError(`Operation file must live below routes/v1/ (or another version): ${name}`);
58
+ return path;
59
+ }
60
+
61
+ // src/tooling/internal/prepare-project.ts
62
+ /** Build-time source generation preserves each operation's literal type and keeps filesystem code out of Workers. */
63
+ /** Generate only owned modules; a failed discovery never replaces the previous output. */
64
+ function prepareProject(directory, mode = "production") {
65
+ const root = resolve(directory);
66
+ for (const required of ["src/application.ts", "src/worker.ts"]) if (!existsSync(join(root, required))) throw new TypeError(`A project layout requires ${required}. Create one with maximus init --layout project.`);
67
+ const output = join(root, ".maximus");
68
+ if (existsSync(output) && lstatSync(output).isSymbolicLink()) throw new TypeError("The generated .maximus directory cannot be a symlink.");
69
+ const files = Object.fromEntries(PROJECT_DIRECTORIES.map((name) => [name, projectFiles(root, name, mode)]));
70
+ const header = "// Generated by maximus prepare. Edit the source modules, not this file.\n";
71
+ const imports = [];
72
+ const source = (file) => JSON.stringify(relative(output, file).split(sep).join("/"));
73
+ const register = (kind) => (files[kind] ?? []).map((file, index) => {
74
+ const identifier = `${kind.replaceAll("-", "_")}_${index}`;
75
+ imports.push(`import ${identifier} from ${source(file.file)};`);
76
+ return {
77
+ ...file,
78
+ identifier
79
+ };
80
+ });
81
+ const routes = register("routes");
82
+ const occupied = /* @__PURE__ */ new Set();
83
+ const mounts = routes.map(({ name, identifier }) => {
84
+ const path = projectPath(name, "routes");
85
+ if (occupied.has(path)) throw new TypeError(`Multiple route files claim ${path}; put its methods in one module.`);
86
+ occupied.add(path);
87
+ return `.mount(${identifier}(${JSON.stringify(path)}))`;
88
+ });
89
+ const application = `${header}import { base } from '../src/application.ts';\n${imports.join("\n")}\nexport const app = base${mounts.join("")}.build();\n`;
90
+ imports.length = 0;
91
+ const middleware = register("middleware");
92
+ const middlewareSource = `${header}${imports.join("\n")}\nexport const middleware = [${middleware.map(({ identifier }) => identifier).join(", ")}] as const;\n`;
93
+ imports.length = 0;
94
+ const pages = register("pages");
95
+ const pagePaths = /* @__PURE__ */ new Set();
96
+ const pageEntries = pages.map(({ name, identifier }) => {
97
+ const path = projectPath(name, "pages");
98
+ if (pagePaths.has(path)) throw new TypeError(`Multiple page files claim ${path}.`);
99
+ pagePaths.add(path);
100
+ return `${JSON.stringify(path)}: ${identifier}`;
101
+ });
102
+ const crons = (files.crons ?? []).map(({ file }, index) => {
103
+ imports.push(`import cron_${index}, { cron as schedule_${index} } from ${source(file)};`);
104
+ return `{ cron: schedule_${index}, handler: cron_${index} }`;
105
+ });
106
+ const eventEntries = (kind) => {
107
+ const keys = /* @__PURE__ */ new Set();
108
+ return register(kind).map(({ name, identifier }) => {
109
+ if (name.includes("/") || keys.has(name)) throw new TypeError(`${kind} modules require distinct top-level names: ${name}`);
110
+ keys.add(name);
111
+ return `${JSON.stringify(name)}: ${identifier}`;
112
+ });
113
+ };
114
+ const queues = eventEntries("queues");
115
+ const email = eventEntries("email");
116
+ const classes = /* @__PURE__ */ new Set(["Service"]);
117
+ const durableObjects = register("durable-objects").map(({ name, identifier }) => {
118
+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name)) throw new TypeError(`Durable Object filenames must be top-level kebab-case names: ${name}`);
119
+ const className = name.split("-").map((part) => part[0]?.toUpperCase() + part.slice(1)).join("");
120
+ if (classes.has(className)) throw new TypeError(`Duplicate Worker export: ${className}`);
121
+ classes.add(className);
122
+ return `export const ${className} = worker.durableObject(${identifier});`;
123
+ });
124
+ const worker = `${header}import { createProjectWorker } from '@arbol-ai/maximus/project';\nimport { app } from './app.ts';\nimport { options } from '../src/worker.ts';\n${imports.join("\n")}\nconst worker = createProjectWorker(app, { pages: { ${pageEntries.join(", ")} }, crons: [${crons.join(", ")}], queues: { ${queues.join(", ")} }, email: { ${email.join(", ")} } }, options);\nexport default worker.handler;\nexport const Service = worker.entrypoint;\n${durableObjects.join("\n")}\n`;
125
+ mkdirSync(output, { recursive: true });
126
+ for (const [name, content] of Object.entries({
127
+ "app.ts": application,
128
+ "middleware.ts": middlewareSource,
129
+ "worker.ts": worker
130
+ })) {
131
+ const target = join(output, name);
132
+ if (existsSync(target) && lstatSync(target).isSymbolicLink()) throw new TypeError(`Generated files cannot be symlinks: ${name}`);
133
+ if (!existsSync(target) || readFileSync(target, "utf-8") !== content) {
134
+ const temporary = `${target}.${process.pid}.tmp`;
135
+ writeFileSync(temporary, content, { flag: "wx" });
136
+ renameSync(temporary, target);
137
+ }
138
+ }
139
+ return {
140
+ directory: root,
141
+ mode,
142
+ modules: Object.fromEntries(Object.entries(files).map(([kind, entries]) => [kind, entries.length]))
143
+ };
144
+ }
145
+
146
+ export { PROJECT_DIRECTORIES as n, prepareProject as t };
@@ -1,4 +1,4 @@
1
- //#region src/internal/exact-length.ts
1
+ // src/internal/exact-length.ts
2
2
  /**
3
3
  * Byte streams held to the length their headers declare.
4
4
  */
@@ -22,8 +22,7 @@ function exactLength(stream, length) {
22
22
  }));
23
23
  }
24
24
 
25
- //#endregion
26
- //#region src/internal/record.ts
25
+ // src/internal/record.ts
27
26
  /**
28
27
  * The plain-record guard the readers of untrusted values share.
29
28
  */
@@ -32,5 +31,4 @@ function isRecord(value) {
32
31
  return typeof value === "object" && value !== null && !Array.isArray(value);
33
32
  }
34
33
 
35
- //#endregion
36
34
  export { exactLength as n, isRecord as t };
@@ -0,0 +1,223 @@
1
+ import { r as parseInput } from "./validation-r-sgmsqb.js";
2
+ import { r as isRequestId } from "./correlation-BEkcFFGT.js";
3
+ import { standardErrors } from "../errors.js";
4
+ import { d as err, p as ok, r as PrincipalSchema, t as executeOperation } from "./execution-B-yy4C7N.js";
5
+ import { r as createHttpHandler } from "./src-DPSpGNnT.js";
6
+ import { a as telemetryEnabled, r as recordExecution, s as withTelemetry } from "./telemetry-BTwB68m5.js";
7
+ import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
8
+
9
+ // src/workers/assets.ts
10
+ /**
11
+ * Serves a web app's build through a Workers static-assets binding: known pages get the app shell, named
12
+ * files revalidate, content-hashed files are immutable, and every other path is refused.
13
+ */
14
+ /** An absolute asset path of unreserved characters, without a query or a fragment. */
15
+ const ASSET_PATH = /^\/(?:[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*)?$/;
16
+ /** The path, refused at construction when it is not an absolute asset path or has dot segments. */
17
+ function requireAssetPath(path) {
18
+ if (!ASSET_PATH.test(path) || path.split("/").some((segment) => segment === "." || segment === "..")) throw new TypeError(`Asset path must be absolute without query, fragments or dot segments: ${path}`);
19
+ return path;
20
+ }
21
+ /** Whether a binding can fetch assets. */
22
+ function isAssetBinding(value) {
23
+ return typeof value === "object" && value !== null && "fetch" in value && typeof value.fetch === "function";
24
+ }
25
+ /** Compile the explicit build policy once; core HTTP retains ownership of API and transport misses. */
26
+ function createAssetHandler(options) {
27
+ const bindingName = options.binding;
28
+ const pages = new Set(options.pages?.paths.map(requireAssetPath));
29
+ const files = new Set(options.files?.map(requireAssetPath));
30
+ const shell = requireAssetPath(options.pages?.shell ?? "/index.html");
31
+ const patterns = options.pages?.patterns?.map((pattern) => {
32
+ if (!(pattern instanceof RegExp) || pattern.global || pattern.sticky) throw new TypeError("Asset page patterns must be stateless regular expressions without global or sticky flags.");
33
+ return new RegExp(pattern.source, pattern.flags);
34
+ }) ?? [];
35
+ const immutablePrefixes = options.immutablePrefixes?.map((path) => {
36
+ const prefix = requireAssetPath(path.endsWith("/") ? path.slice(0, -1) : path);
37
+ if (prefix === "/") throw new TypeError("An immutable assets prefix must not claim the entire origin.");
38
+ return prefix;
39
+ }) ?? [];
40
+ const configuredHeaders = typeof options.headers === "function" ? options.headers : new Headers(options.headers);
41
+ return async (request, env, context) => {
42
+ if (request.method !== "GET" && request.method !== "HEAD") return context.fail(standardErrors.methodNotAllowed.create(), { Allow: "GET, HEAD" });
43
+ const url = new URL(request.url);
44
+ const isPage = pages.has(url.pathname) || patterns.some((pattern) => pattern.test(url.pathname));
45
+ const isFile = files.has(url.pathname);
46
+ const isImmutable = immutablePrefixes.some((prefix) => url.pathname === prefix || url.pathname.startsWith(`${prefix}/`));
47
+ const binding = env[bindingName];
48
+ if (!(isPage || isFile || isImmutable)) {
49
+ if (options.development && isAssetBinding(binding)) return binding.fetch(request);
50
+ return context.fail(standardErrors.notFound.create());
51
+ }
52
+ if (!isAssetBinding(binding)) throw new TypeError("The configured Worker assets binding does not implement fetch.");
53
+ const assetUrl = new URL(isPage ? shell : url.pathname, url.origin);
54
+ const asset = await binding.fetch(new Request(assetUrl, { method: request.method }));
55
+ const headers = new Headers(asset.headers);
56
+ const policy = typeof configuredHeaders === "function" ? new Headers(configuredHeaders(request, env)) : configuredHeaders;
57
+ for (const [name, value] of policy) if (name !== "content-type" && name !== "cache-control") headers.set(name, value);
58
+ headers.set("x-content-type-options", "nosniff");
59
+ let cache = "public, max-age=31536000, immutable";
60
+ if (isPage || asset.status !== 200) cache = "no-store";
61
+ else if (isFile) cache = "no-cache";
62
+ headers.set("cache-control", cache);
63
+ if (request.method === "HEAD" && asset.body) await asset.body.cancel();
64
+ return new Response(request.method === "HEAD" ? null : asset.body, {
65
+ status: asset.status,
66
+ statusText: asset.statusText,
67
+ headers
68
+ });
69
+ };
70
+ }
71
+
72
+ // src/workers/internal/instrumentation.ts
73
+ /**
74
+ * Runs the methods of a Worker's own entrypoints and Durable Objects inside the application's diagnostics.
75
+ */
76
+ /**
77
+ * A subclass of `implementation` whose every method, its own and those it inherits up to the Workers
78
+ * base class `runtime`, runs inside the application's diagnostics for the instance's `env`.
79
+ */
80
+ function instrumentMethods(implementation, runtime, telemetry) {
81
+ const Base = implementation;
82
+ const environments = /* @__PURE__ */ new WeakMap();
83
+ class Observed extends Base {
84
+ constructor(context, env) {
85
+ super(context, env);
86
+ environments.set(this, env);
87
+ }
88
+ }
89
+ let { prototype } = implementation;
90
+ const methods = /* @__PURE__ */ new Set();
91
+ while (prototype && prototype !== runtime.prototype) {
92
+ for (const name of Object.getOwnPropertyNames(prototype)) {
93
+ const method = Object.getOwnPropertyDescriptor(prototype, name)?.value;
94
+ if (name === "constructor" || methods.has(name) || typeof method !== "function") continue;
95
+ methods.add(name);
96
+ Object.defineProperty(Observed.prototype, name, {
97
+ configurable: true,
98
+ value(...args) {
99
+ return withTelemetry(telemetry, environments.get(this), () => Reflect.apply(method, this, args));
100
+ }
101
+ });
102
+ }
103
+ prototype = Object.getPrototypeOf(prototype);
104
+ }
105
+ return Observed;
106
+ }
107
+ /** A named entrypoint whose RPC methods run inside the application's diagnostics. */
108
+ function instrumentService(implementation, telemetry) {
109
+ return instrumentMethods(implementation, WorkerEntrypoint, telemetry);
110
+ }
111
+ /** A Durable Object whose methods run inside the application's diagnostics. */
112
+ function instrumentDurableObject(implementation, telemetry) {
113
+ return instrumentMethods(implementation, DurableObject, telemetry);
114
+ }
115
+
116
+ // src/workers/internal/worker-tracing.ts
117
+ /**
118
+ * Annotates the active Workers trace span with the service, the operation and the request id.
119
+ */
120
+ /**
121
+ * Call inside the invocation, after authenticating the native principal. Service
122
+ * and operation are developer constants. Adds correlation to the existing native
123
+ * span; does not mint/fake trace ids or enable exporters. No raw exception is
124
+ * recorded on the native span.
125
+ * Older workerd versions do not expose getActiveSpan. Annotation is best effort:
126
+ * an unavailable or failing telemetry API must never change the business result.
127
+ */
128
+ function annotateInvocation(service, operation, requestId, attributeNames = {
129
+ service: "service.name",
130
+ operation: "operation.name",
131
+ requestId: "request.id"
132
+ }) {
133
+ try {
134
+ if (typeof tracing.getActiveSpan === "function") tracing.getActiveSpan()?.setAttributes({
135
+ [attributeNames.service]: service,
136
+ [attributeNames.operation]: operation,
137
+ ...isRequestId(requestId) ? { [attributeNames.requestId]: requestId } : {}
138
+ });
139
+ } catch {}
140
+ }
141
+
142
+ // src/workers/credentials.ts
143
+ /**
144
+ * Reads one organization's credential from its own store, such as a Durable Object per organization, and
145
+ * checks that it belongs to that organization.
146
+ */
147
+ /** Typed organization credential preparation for one derived operation group. */
148
+ async function credentials(options) {
149
+ const { organizationId } = options.principal;
150
+ const result = await options.accounts.getByName(organizationId).readCredential(organizationId);
151
+ if (!result.ok) return result;
152
+ const parsed = parseInput(options.schema, result.value);
153
+ if (!parsed.ok || !parsed.value || typeof parsed.value !== "object" || !("organizationId" in parsed.value) || parsed.value.organizationId !== organizationId) return err(standardErrors.internal.create());
154
+ return ok({ credential: parsed.value });
155
+ }
156
+
157
+ // src/workers/runtime.ts
158
+ /**
159
+ * `@arbol-ai/maximus/workers`: turns an application into a Cloudflare Worker: its fetch handler, its RPC
160
+ * entrypoint, and the instrumentation of the Worker's other classes.
161
+ */
162
+ /**
163
+ * Turns an application into a Cloudflare Worker: `handler` (export it as default) serves HTTP and the other
164
+ * handlers you pass; `entrypoint` (export it by name) serves every operation that declares `rpc` to the
165
+ * Workers whose Service Binding names an allowed `caller`.
166
+ */
167
+ function createWorker(application, options = {}) {
168
+ if (options.assets && options.http?.fallback) throw new TypeError("Worker assets and an HTTP fallback cannot both own unmatched paths.");
169
+ const assets = options.assets ? createAssetHandler(options.assets) : void 0;
170
+ const manifest = application;
171
+ const fetch = createHttpHandler(manifest, {
172
+ ...options.http,
173
+ fallback: assets ?? options.http?.fallback,
174
+ transports: options.transports,
175
+ routes: options.routes,
176
+ annotate: (operation, id) => annotateInvocation(manifest.name, operation, id)
177
+ });
178
+ class Entrypoint extends WorkerEntrypoint {}
179
+ for (const [name, op] of Object.entries(manifest.operations)) {
180
+ if (!op.rpc) continue;
181
+ const callers = op.rpc === true ? manifest.rpc.callers : op.rpc.callers;
182
+ Object.defineProperty(Entrypoint.prototype, name, {
183
+ configurable: true,
184
+ async value(principal, input) {
185
+ const props = this.ctx.props;
186
+ if (!props || Object.keys(props).length !== 1 || typeof props.caller !== "string" || !callers.includes(props.caller)) return err(standardErrors.unauthorized.create());
187
+ const parsed = parseInput(PrincipalSchema, principal);
188
+ if (!parsed.ok) return err(standardErrors.unauthorized.create());
189
+ if (telemetryEnabled(manifest.telemetry, this.env)) annotateInvocation(manifest.name, name, parsed.value.requestId);
190
+ const started = performance.now();
191
+ const result = await withTelemetry(manifest.telemetry, this.env, () => executeOperation(manifest, op, this.env, parsed.value, input, void 0, this.ctx));
192
+ recordExecution(manifest, this.env, this.ctx, {
193
+ principal: parsed.value,
194
+ operation: name,
195
+ surface: "rpc",
196
+ started,
197
+ result
198
+ });
199
+ return result;
200
+ }
201
+ });
202
+ }
203
+ const service = (implementation) => instrumentService(implementation, manifest.telemetry);
204
+ const entrypoint = service(Entrypoint);
205
+ const handler = {
206
+ ...options.handlers,
207
+ fetch
208
+ };
209
+ const scheduledHandler = options.handlers?.scheduled;
210
+ if (scheduledHandler) handler.scheduled = function scheduled(controller, env, ctx) {
211
+ return withTelemetry(manifest.telemetry, env, () => scheduledHandler.call(this, controller, env, ctx));
212
+ };
213
+ return {
214
+ handler,
215
+ entrypoint,
216
+ service,
217
+ durableObject(implementation) {
218
+ return instrumentDurableObject(implementation, manifest.telemetry);
219
+ }
220
+ };
221
+ }
222
+
223
+ export { credentials as n, createAssetHandler as r, createWorker as t };