@arbol-ai/maximus 7.4.0 → 8.0.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 (135) hide show
  1. package/README.md +36 -38
  2. package/bin/maximus.js +4 -0
  3. package/config/oxfmt.mjs +1 -0
  4. package/config/oxlint.mjs +10 -0
  5. package/dist/analytics/analytics.d.ts +21 -9
  6. package/dist/analytics/analytics.js +19 -5
  7. package/dist/body.d.ts +1 -1
  8. package/dist/body.js +2 -2
  9. package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
  10. package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
  11. package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
  12. package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
  13. package/dist/chunks/define-app-CfVZBt7D.js +336 -0
  14. package/dist/chunks/{errors-D7zG9kx9.js → errors-WfyKhiyk.js} +9 -4
  15. package/dist/chunks/{execution-kVUJPy1A.js → execution-CfZEx_JP.js} +28 -15
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-DWTGoduQ.js +140 -0
  18. package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
  19. package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
  20. package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
  21. package/dist/chunks/names-ncD7A3DV.js +280 -0
  22. package/dist/chunks/openapi-CV0KmJpS.js +1588 -0
  23. package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
  24. package/dist/chunks/pages-DyC0m8Zb.js +14 -0
  25. package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
  26. package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
  27. package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
  28. package/dist/chunks/query-kind-CWKAXEME.js +40 -0
  29. package/dist/chunks/record-DQUDTpEA.js +10 -0
  30. package/dist/chunks/result-CKgZHrnj.js +56 -0
  31. package/dist/chunks/{runtime-DlqA7J38.js → runtime-CVVf5hmp.js} +50 -26
  32. package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
  33. package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
  34. package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
  35. package/dist/chunks/server-CCc7fil4.js +410 -0
  36. package/dist/chunks/src--HZrH1U9.js +568 -0
  37. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  38. package/dist/chunks/{types-DQdfRF3f.d.ts → types-BQYB4Ads.d.ts} +993 -341
  39. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  40. package/dist/chunks/workers-types-iONp32T4.d.ts +143 -0
  41. package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
  42. package/dist/diagnostics.d.ts +6 -4
  43. package/dist/diagnostics.js +2 -2
  44. package/dist/errors.d.ts +2 -2
  45. package/dist/errors.js +2 -2
  46. package/dist/http-paths.d.ts +1 -1
  47. package/dist/http-paths.js +1 -1
  48. package/dist/index.d.ts +2 -2
  49. package/dist/index.js +12 -11
  50. package/dist/internals.d.ts +1 -1
  51. package/dist/internals.js +5 -4
  52. package/dist/mcp/index.d.ts +3 -2
  53. package/dist/mcp/index.js +5 -387
  54. package/dist/postgres/index.d.ts +25 -8
  55. package/dist/postgres/index.js +17 -8
  56. package/dist/project/config.d.ts +110 -72
  57. package/dist/project/config.js +161 -45
  58. package/dist/project/index.d.ts +17 -4
  59. package/dist/project/index.js +44 -9
  60. package/dist/projection.d.ts +14 -13
  61. package/dist/projection.js +8 -32
  62. package/dist/schemas.d.ts +1 -1
  63. package/dist/schemas.js +2 -2
  64. package/dist/standard-failures.d.ts +2 -89
  65. package/dist/tooling/cli.js +149 -105
  66. package/dist/tooling/testing.js +2 -2
  67. package/dist/vite/cloudflare-workers.js +25 -0
  68. package/dist/vite/index.d.ts +157 -0
  69. package/dist/vite/index.js +1477 -0
  70. package/dist/webhooks.d.ts +12 -10
  71. package/dist/webhooks.js +26 -12
  72. package/dist/workers/runtime.d.ts +1 -1
  73. package/dist/workers/runtime.js +1 -1
  74. package/package.json +26 -22
  75. package/skills/maximus/SKILL.md +165 -68
  76. package/skills/maximus/references/deploying.md +73 -0
  77. package/skills/maximus/references/errors-and-results.md +114 -55
  78. package/skills/maximus/references/project.md +202 -0
  79. package/skills/maximus/references/routes-and-tools.md +256 -0
  80. package/skills/maximus/references/testing.md +137 -50
  81. package/skills/maximus/references/transports.md +113 -100
  82. package/skills/maximus/references/writing-code.md +84 -0
  83. package/templates/mcp/mcp/instructions.md.template +2 -0
  84. package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
  85. package/templates/mcp/tests/mcp.test.ts.template +36 -0
  86. package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
  87. package/templates/project/.github/workflows/ci.yml.template +4 -1
  88. package/templates/project/CLAUDE.md.template +41 -25
  89. package/templates/project/README.md.template +54 -48
  90. package/templates/project/middleware/10-response.ts.template +5 -2
  91. package/templates/project/package.json.template +13 -9
  92. package/templates/project/pages/index.ts.template +2 -4
  93. package/templates/project/routes/v1/greeting.get.ts.template +10 -0
  94. package/templates/project/routes/v1/greeting.post.ts.template +12 -0
  95. package/templates/project/tests/greeting.test.ts.template +45 -0
  96. package/templates/project/tsconfig.json.template +8 -6
  97. package/templates/project/vite.config.ts.template +15 -7
  98. package/templates/web/app/main.tsx.template +16 -0
  99. package/templates/web/app/root.tsx.template +17 -0
  100. package/templates/web/app/routes/index.tsx.template +9 -0
  101. package/templates/web/index.html.template +12 -0
  102. package/templates/web/package.json.template +12 -0
  103. package/templates/web/tsconfig.json.template +7 -0
  104. package/templates/web/vite.config.ts.template +22 -0
  105. package/dist/chunks/builder-BiXv7d2v.js +0 -100
  106. package/dist/chunks/define-app-DvD_1jUE.js +0 -625
  107. package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
  108. package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
  109. package/dist/chunks/record-DY-lX9w1.js +0 -34
  110. package/dist/chunks/src-N3oyx5QF.js +0 -1091
  111. package/dist/client/client.d.ts +0 -129
  112. package/dist/client/client.js +0 -321
  113. package/dist/tooling/vite.d.ts +0 -3
  114. package/dist/tooling/vite.js +0 -57
  115. package/skills/maximus/references/adding-an-operation.md +0 -179
  116. package/skills/maximus/references/building-a-service.md +0 -167
  117. package/skills/maximus/references/migration-from-v2.md +0 -62
  118. package/skills/maximus/references/migration-to-v5.md +0 -37
  119. package/skills/maximus/references/publishing-and-verification.md +0 -42
  120. package/templates/project/cloudflare.config.ts.template +0 -24
  121. package/templates/project/maximus.config.ts.template +0 -20
  122. package/templates/project/routes/v1/greeting.ts.template +0 -38
  123. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  124. package/templates/service/.github/workflows/ci.yml.template +0 -21
  125. package/templates/service/.gitignore.template +0 -9
  126. package/templates/service/CLAUDE.md.template +0 -5
  127. package/templates/service/README.md.template +0 -45
  128. package/templates/service/cloudflare.config.ts.template +0 -30
  129. package/templates/service/package.json.template +0 -36
  130. package/templates/service/src/app.ts.template +0 -30
  131. package/templates/service/src/index.ts.template +0 -13
  132. package/templates/service/tests/contract.test.ts.template +0 -12
  133. package/templates/service/tsconfig.json.template +0 -16
  134. package/templates/service/vite.config.ts.template +0 -13
  135. package/templates/service/vitest.config.ts.template +0 -10
@@ -0,0 +1,1477 @@
1
+ import { t as checkMcpResourceNames } from "../chunks/define-app-CfVZBt7D.js";
2
+ import { a as operationPathParameters } from "../chunks/http-paths-DMBxwpp6.js";
3
+ import { a as ownsPrefix, t as VERSIONED_PATH } from "../chunks/http-layout-_h7xwgPC.js";
4
+ import { t as checkPagePaths } from "../chunks/pages-DyC0m8Zb.js";
5
+ import { t as routeName } from "../chunks/names-ncD7A3DV.js";
6
+ import { a as projectPath, i as projectFiles, o as publicFiles, r as compareNames, s as routeShape, t as PROJECT_DIRECTORIES } from "../chunks/project-files-C0OX7MQQ.js";
7
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { cloudflare } from "@cloudflare/vite-plugin";
11
+ import { bindings, triggers } from "cf/config";
12
+ import { parseSync } from "vite";
13
+
14
+ // src/vite/options.ts
15
+ /**
16
+ * What `vite.config.ts` states and what follows from it: the application the generated modules carry and
17
+ * the Worker Cloudflare's plugin builds. Development is `vp dev`: every build is a production build, whatever
18
+ * its Vite mode, so no deployed Worker carries what only development needs.
19
+ */
20
+ /**
21
+ * The Worker's observability: the options' own settings, key by key over the defaults, which are logs with
22
+ * invocation logs and traces, query strings redacted. Logs and traces follow `enabled` unless the options set
23
+ * theirs, so turning observability off turns them off too.
24
+ */
25
+ function observability(own = {}) {
26
+ const enabled = own.enabled ?? true;
27
+ return {
28
+ enabled,
29
+ redactQueryString: true,
30
+ ...own,
31
+ logs: {
32
+ enabled,
33
+ invocationLogs: true,
34
+ ...own.logs
35
+ },
36
+ traces: {
37
+ enabled,
38
+ ...own.traces
39
+ }
40
+ };
41
+ }
42
+ /** A Worker and scope namespace name: lowercase letters, digits and single hyphens, 2 to 63 characters. */
43
+ const SERVICE_NAME = /^(?=.{2,63}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
44
+ /** The application's options and the Worker's settings, apart. `assets` is maximus()'s own. */
45
+ function split(options) {
46
+ if ("assets" in options) throw new TypeError("maximus() configures the assets: index.html at the root makes the project a web app.");
47
+ const { name, namespace, title, description, groups, version, origin, tokens, rpc, http, maxBodyBytes, maxOutputBytes, rateLimit, env, services, webApp, ...worker } = options;
48
+ return {
49
+ application: {
50
+ name,
51
+ namespace,
52
+ title,
53
+ description,
54
+ groups,
55
+ version,
56
+ origin,
57
+ tokens,
58
+ rpc,
59
+ http,
60
+ maxBodyBytes,
61
+ maxOutputBytes,
62
+ rateLimit
63
+ },
64
+ env,
65
+ services,
66
+ webApp,
67
+ worker
68
+ };
69
+ }
70
+ /** The binding a web app's build is served through. */
71
+ const ASSETS = "ASSETS";
72
+ /** Whether the project is a web app: `index.html` at its root, which Vite builds for the browser. */
73
+ function servesWebApp(root) {
74
+ return existsSync(join(root, "index.html"));
75
+ }
76
+ /**
77
+ * A web app's build as its Worker serves it: from the root, its hashed files below `/assets`. Refuses a
78
+ * configuration that moves them, whose app would otherwise miss its own files once deployed.
79
+ */
80
+ function checkWebAppBuild(root, config) {
81
+ const builds = [config.build, config.environments?.client?.build];
82
+ if (servesWebApp(root) && ((config.base ?? "/") !== "/" || builds.some((build) => (build?.assetsDir ?? "assets") !== "assets"))) throw new TypeError("maximus() serves a web app from the root with its hashed files below /assets: keep base and build.assetsDir at their defaults.");
83
+ }
84
+ /** The service's name and version: the options', else the package's, its name without a scope. */
85
+ function identity(root, options) {
86
+ const path = join(root, "package.json");
87
+ const manifest = existsSync(path) ? JSON.parse(readFileSync(path, "utf-8")) : {};
88
+ const field = (key) => typeof manifest === "object" && manifest !== null && key in manifest ? Reflect.get(manifest, key) : void 0;
89
+ const packageName = field("name");
90
+ const packageVersion = field("version");
91
+ const name = options.name ?? (typeof packageName === "string" ? packageName.replace(/^@[^/]+\//, "") : void 0);
92
+ if (name === void 0 || !SERVICE_NAME.test(name)) throw new TypeError("Name the service with maximus({ name }), or in package.json: lowercase letters, digits and single hyphens.");
93
+ return {
94
+ name,
95
+ version: options.version ?? (typeof packageVersion === "string" ? packageVersion : "0.0.0")
96
+ };
97
+ }
98
+ /** The development token's policy: `DEVELOPMENT_TOKEN` unless the options name another or refuse it. */
99
+ function developmentToken(options) {
100
+ const development = options.tokens?.development;
101
+ return development === false ? void 0 : development ?? { binding: "DEVELOPMENT_TOKEN" };
102
+ }
103
+ /** A binding's name: an uppercase letter, then uppercase letters, digits and underscores. */
104
+ const BINDING_NAME = /^[A-Z][A-Z0-9_]{0,62}$/;
105
+ /**
106
+ * The binding of each service the project calls over native RPC: the `Service` entrypoint of its Worker, with
107
+ * this service's name as the caller. A binding that is not an uppercase name, that `env` declares too, or
108
+ * whose worker or document is not named throws a TypeError.
109
+ */
110
+ function serviceBindings(root, options) {
111
+ const services = Object.entries(options.services ?? {});
112
+ if (!services.length) return {};
113
+ const caller = identity(root, options).name;
114
+ return Object.fromEntries(services.map(([binding, service]) => {
115
+ if (!BINDING_NAME.test(binding) || Object.hasOwn(options.env ?? {}, binding)) throw new TypeError(`services.${binding}: name each service's binding in uppercase, such as PRICING, once: env declares the others.`);
116
+ const { worker, openapi } = service ?? {};
117
+ if (typeof worker !== "string" || !worker || typeof openapi !== "string" || !openapi) throw new TypeError(`services.${binding} names the service's Worker and the OpenAPI document it publishes: { worker, openapi }.`);
118
+ return [binding, bindings.worker({
119
+ worker,
120
+ exportName: "Service",
121
+ props: { caller }
122
+ })];
123
+ }));
124
+ }
125
+ /**
126
+ * The Worker's bindings in a phase: the declared ones and each service's, a web app's assets and, under
127
+ * `vp dev` alone, the development token. A declared binding cannot take the name of either of those.
128
+ */
129
+ function workerEnv(root, options, phase) {
130
+ const declared = {
131
+ ...Object.fromEntries(Object.entries(options.env ?? {}).filter(([, binding]) => binding)),
132
+ ...serviceBindings(root, options)
133
+ };
134
+ const development = developmentToken(options);
135
+ if (development && Object.hasOwn(declared, development.binding)) throw new TypeError(`${development.binding} is the development token: Maximus declares it under vp dev alone, so no deployed Worker carries it.`);
136
+ const web = servesWebApp(root);
137
+ if (web && Object.hasOwn(declared, ASSETS)) throw new TypeError(`${ASSETS} serves the web app index.html starts: Maximus declares it.`);
138
+ return {
139
+ ...declared,
140
+ ...web ? { [ASSETS]: bindings.assets() } : {},
141
+ ...development && phase === "development" ? { [development.binding]: bindings.secret() } : {}
142
+ };
143
+ }
144
+ /**
145
+ * The origins the web app's pages may call besides their own: each token issuer's and the token endpoint's,
146
+ * resolved against the canonical issuer. Behind Cloudflare Access, none: Access signs people in at the edge,
147
+ * and the pages call their own origin alone.
148
+ */
149
+ function tokenOrigins(tokens = {}) {
150
+ const { issuer = [], tokenEndpoint = "oauth/token" } = tokens;
151
+ const issuers = typeof issuer === "string" ? [issuer] : issuer;
152
+ const [canonical] = issuers;
153
+ if (!canonical || tokens.source === "cloudflare-access") return [];
154
+ const endpoint = new URL(tokenEndpoint, canonical);
155
+ return [.../* @__PURE__ */ new Set([...issuers.map((listed) => new URL(listed).origin), endpoint.origin])];
156
+ }
157
+ /**
158
+ * The headers of a web app's pages and files: the defaults, then the options' own, a `false` one left out.
159
+ * The Content Security Policy and HSTS apply in production alone.
160
+ */
161
+ function webAppHeaders(options, phase) {
162
+ const production = phase === "production";
163
+ const policy = [
164
+ "default-src 'self'",
165
+ "base-uri 'self'",
166
+ `connect-src ${["'self'", ...tokenOrigins(options.tokens)].join(" ")}`,
167
+ "font-src 'self'",
168
+ "form-action 'self'",
169
+ "frame-ancestors 'none'",
170
+ "img-src 'self' data: blob:",
171
+ "object-src 'none'",
172
+ "script-src 'self'",
173
+ "style-src 'self' 'unsafe-inline'",
174
+ "upgrade-insecure-requests"
175
+ ].join("; ");
176
+ const headers = {
177
+ ...production ? {
178
+ "content-security-policy": policy,
179
+ "strict-transport-security": "max-age=31536000; includeSubDomains"
180
+ } : {},
181
+ "cross-origin-opener-policy": "same-origin",
182
+ "cross-origin-resource-policy": "same-origin",
183
+ "referrer-policy": "no-referrer",
184
+ "x-frame-options": "DENY"
185
+ };
186
+ for (const [name, value] of Object.entries(options.webApp?.headers ?? {})) {
187
+ const header = name.toLowerCase();
188
+ if (production || header !== "content-security-policy" && header !== "strict-transport-security") headers[header] = value;
189
+ }
190
+ return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== false));
191
+ }
192
+ /**
193
+ * What the generated modules carry in a phase: the application this file configures, with the development
194
+ * token's policy under `vp dev` alone, the Worker's HTTP paths, pinned to the origin in production behind
195
+ * Cloudflare Access, and a web app's binding and headers.
196
+ */
197
+ function projectOptions(root, options, phase = "production") {
198
+ const { application } = split(options);
199
+ const { name, version } = identity(root, options);
200
+ const { audience = application.origin, development: _declared, ...tokens } = application.tokens ?? {};
201
+ const development = developmentToken(options);
202
+ const pinned = phase === "production" && tokens.source === "cloudflare-access";
203
+ return {
204
+ application: {
205
+ name,
206
+ namespace: application.namespace ?? name,
207
+ title: application.title ?? name,
208
+ ...application.description === void 0 ? {} : { description: application.description },
209
+ ...application.groups === void 0 ? {} : { groups: application.groups },
210
+ version,
211
+ origin: application.origin,
212
+ tokens: {
213
+ ...tokens,
214
+ audience,
215
+ ...development && phase === "development" ? { development } : {}
216
+ },
217
+ rpc: application.rpc ?? { callers: [] },
218
+ ...application.maxBodyBytes === void 0 ? {} : { maxBodyBytes: application.maxBodyBytes },
219
+ ...application.maxOutputBytes === void 0 ? {} : { maxOutputBytes: application.maxOutputBytes },
220
+ ...application.rateLimit === void 0 ? {} : { rateLimit: application.rateLimit }
221
+ },
222
+ worker: {
223
+ http: {
224
+ basePath: application.http?.basePath ?? "/api",
225
+ healthPath: application.http?.healthPath ?? "/health",
226
+ ...pinned ? { origins: [new URL(application.origin).origin] } : {}
227
+ },
228
+ ...servesWebApp(root) ? { assets: {
229
+ binding: ASSETS,
230
+ headers: webAppHeaders(options, phase)
231
+ } } : {}
232
+ },
233
+ ...options.services ? { services: options.services } : {},
234
+ env: {
235
+ production: workerEnv(root, options, "production"),
236
+ development: workerEnv(root, options, "development")
237
+ }
238
+ };
239
+ }
240
+ /**
241
+ * Where a deployment serves the Worker unless the options route it themselves: at its `workers.dev`
242
+ * subdomain when the origin is one, and otherwise at the origin's host, as its custom domain alone.
243
+ */
244
+ function hosting(options, worker) {
245
+ const { hostname } = new URL(options.origin);
246
+ const onWorkersDev = hostname.endsWith(".workers.dev");
247
+ const routed = worker.domains !== void 0 || worker.triggers?.some(({ type }) => type === "fetch");
248
+ return {
249
+ workersDev: onWorkersDev,
250
+ ...onWorkersDev || routed ? {} : { domains: [hostname] }
251
+ };
252
+ }
253
+ /**
254
+ * The Worker Cloudflare's plugin builds: the options' settings, the generated entry, `nodejs_compat`, which
255
+ * Maximus needs for its diagnostics, the bindings of the phase, where it is served, its observability, a cron
256
+ * trigger for each schedule the cron modules state, a consumer trigger for each queue module the options do not
257
+ * subscribe themselves and, for a web app, its build as assets every request reaches through the Worker,
258
+ * which decides what they answer.
259
+ */
260
+ function workerConfig(root, phase, options, { crons, queues }) {
261
+ const { worker } = split(options);
262
+ const subscribed = new Set((worker.triggers ?? []).flatMap((trigger) => trigger.type === "queue" ? [trigger.name] : []));
263
+ const consumers = queues.filter((queue) => !subscribed.has(queue)).map((queue) => triggers.queue({ name: queue }));
264
+ const declared = new Set((worker.triggers ?? []).flatMap((trigger) => trigger.type === "scheduled" ? [trigger.schedule] : []));
265
+ const schedules = crons.map(({ file, cron }) => {
266
+ if (cron === void 0) throw new TypeError(`${file}: export the schedule as a string literal, export const cron = '0 8 * * *'.`);
267
+ return cron;
268
+ });
269
+ const scheduled = [...new Set(schedules)].filter((schedule) => !declared.has(schedule)).map((schedule) => triggers.scheduled({ schedule }));
270
+ return {
271
+ ...hosting(options, worker),
272
+ previewUrls: false,
273
+ ...worker,
274
+ observability: observability(worker.observability),
275
+ name: identity(root, options).name,
276
+ compatibilityFlags: [.../* @__PURE__ */ new Set(["nodejs_compat", ...worker.compatibilityFlags ?? []])],
277
+ entrypoint: "./.maximus/entry.ts",
278
+ ...servesWebApp(root) ? { assets: {
279
+ htmlHandling: "none",
280
+ notFoundHandling: "none",
281
+ runWorkerFirst: true
282
+ } } : {},
283
+ env: workerEnv(root, options, phase),
284
+ triggers: [
285
+ ...worker.triggers ?? [],
286
+ ...scheduled,
287
+ ...consumers
288
+ ]
289
+ };
290
+ }
291
+
292
+ // src/tooling/internal/project-exports.ts
293
+ /** Reads what project modules export with Oxc, without importing or executing them. */
294
+ /**
295
+ * Parses a project module of `root`, refusing runtime imports of generated modules that would form a cycle
296
+ * and, in the modules that complete the application, imports that only load in workerd. The application and
297
+ * the API built from it (`app` and `http`) import routes and middleware; a module only the generated Worker
298
+ * imports (a page, a cron, queue or email handler, a Durable Object) may use them: only the Worker, which
299
+ * imports it, would form a cycle. Only `import type` and `export type` are type-only: under
300
+ * `verbatimModuleSyntax`, `import { type x }` still loads its module.
301
+ */
302
+ function readProjectModule(root, file, role) {
303
+ const shown = relative(root, file);
304
+ const parsed = parseSync(file, readFileSync(file, "utf-8"));
305
+ if (parsed.errors.length) throw new TypeError(`Cannot discover ${shown}: ${parsed.errors[0]?.message}`);
306
+ for (const node of parsed.program.body) {
307
+ let source;
308
+ if (node.type === "ImportDeclaration" && node.importKind !== "type") source = node.source.value;
309
+ else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.exportKind !== "type") source = node.source?.value;
310
+ if (!source) continue;
311
+ const generated = /(?:\.maximus\/|#maximus\/)([^/.?#]+)/.exec(posix.normalize(source))?.[1];
312
+ if (generated && (role === "config" || ["worker", "entry"].includes(generated) || role !== "worker" && (generated === "app" || generated === "http") || role === "middleware" && (generated === "base" || generated === "middleware"))) throw new TypeError(`Runtime import ${source} creates a generated-module cycle in ${shown}. Use a type-only import or shared domain module.`);
313
+ if (role === "config" && (source.startsWith("cloudflare:") || /^@arbol-ai\/maximus\/(?:workers|project)$/.test(source))) throw new TypeError(`Configuration must remain importable outside workerd: ${source} in ${shown}. Import its types only.`);
314
+ }
315
+ return parsed;
316
+ }
317
+ /** The initializer of a top-level `const` of the module, exported or not. */
318
+ function constInitializer(body, name) {
319
+ let initializer;
320
+ for (const node of body) {
321
+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
322
+ if (declaration?.type === "VariableDeclaration" && declaration.kind === "const") {
323
+ for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === name) initializer = declarator.init;
324
+ }
325
+ }
326
+ return initializer;
327
+ }
328
+ /** What a module default-exports: `export default x`, or the initializer of the local const it names. */
329
+ function defaultExpression(body) {
330
+ let local;
331
+ let expression;
332
+ for (const node of body) if (node.type === "ExportDefaultDeclaration") {
333
+ if (node.declaration.type === "Identifier") local = node.declaration.name;
334
+ else expression = node.declaration;
335
+ } else if (node.type === "ExportNamedDeclaration" && !node.source) {
336
+ for (const specifier of node.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : void 0) === "default" && specifier.local.type === "Identifier") local = specifier.local.name;
337
+ }
338
+ return local === void 0 ? expression : constInitializer(body, local);
339
+ }
340
+ /** An expression without the `as`, `satisfies`, `!` or parentheses around it, which leave its value as it is. */
341
+ function unwrap(expression) {
342
+ let current = expression;
343
+ while (current?.type === "TSAsExpression" || current?.type === "TSSatisfiesExpression" || current?.type === "TSNonNullExpression" || current?.type === "ParenthesizedExpression") current = current.expression;
344
+ return current;
345
+ }
346
+ /**
347
+ * Whether a `defineHandler` call's contract, its second argument, names an MCP tool: false without one, true
348
+ * or false as its object shows it, written in the call or in a const of the module, or undefined when a
349
+ * spread, a computed key or another value hides it.
350
+ */
351
+ function declaresMcp(expression, body) {
352
+ const call = unwrap(expression);
353
+ if (call?.type !== "CallExpression") return;
354
+ const [, second] = call.arguments;
355
+ if (second === void 0) return false;
356
+ let argument = second.type === "SpreadElement" ? void 0 : unwrap(second);
357
+ if (argument?.type === "Identifier") argument = unwrap(constInitializer(body, argument.name));
358
+ if (argument?.type !== "ObjectExpression") return;
359
+ let hidden = false;
360
+ for (const property of argument.properties) if (property.type !== "Property" || property.computed && property.key.type !== "Literal") hidden = true;
361
+ else if (property.key.type === "Identifier" && !property.computed && property.key.name === "mcp" || property.key.type === "Literal" && property.key.value === "mcp") return true;
362
+ return hidden ? void 0 : false;
363
+ }
364
+ /**
365
+ * A `defineHandler` route or `defineTool` module: one default export, the declaration, and types. Returns
366
+ * whether the declaration names an MCP tool, as its fields show it; the generated Worker serves MCP when one
367
+ * does. A route whose fields prepare cannot see is refused, so a tool is never silently left unserved.
368
+ */
369
+ function declarationExports(root, file, helper) {
370
+ const parsed = readProjectModule(root, file, "route");
371
+ const names = /* @__PURE__ */ new Set();
372
+ for (const statement of parsed.module.staticExports) for (const entry of statement.entries) if (!entry.isType) names.add(entry.exportName.kind === "Default" ? "default" : entry.exportName.name ?? "*");
373
+ if (names.size !== 1 || !names.has("default")) throw new TypeError(`${relative(root, file)} must default-export its ${helper} declaration and nothing else. Keep helpers private or in _files.`);
374
+ if (helper === "defineTool") return { mcp: true };
375
+ const mcp = declaresMcp(defaultExpression(parsed.program.body), parsed.program.body);
376
+ if (mcp === void 0) throw new TypeError(`${relative(root, file)} must write its defineHandler contract as an object, in the call or in a const of the module: prepare reads from it whether the route is an MCP tool.`);
377
+ return { mcp };
378
+ }
379
+ /**
380
+ * The schedule a cron module exports, `export const cron = '0 8 * * *'`, when it is a string literal: what
381
+ * a project configured in `vite.config.ts` declares as the Worker's cron trigger. Undefined otherwise.
382
+ */
383
+ function cronExpression(root, file) {
384
+ for (const node of readProjectModule(root, file, "worker").program.body) {
385
+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : void 0;
386
+ if (declaration?.type === "VariableDeclaration" && declaration.kind === "const") {
387
+ for (const { id, init } of declaration.declarations) if (id.type === "Identifier" && id.name === "cron") return init?.type === "Literal" && typeof init.value === "string" ? init.value : void 0;
388
+ }
389
+ }
390
+ }
391
+
392
+ // src/tooling/internal/project-markdown.ts
393
+ /**
394
+ * The MCP server's own description, written as Markdown in `mcp/`: `instructions.md` for every client that
395
+ * connects, `guides/<name>.md` served as resources and prompts, and `skills/<name>.md` served as Agent Skills.
396
+ */
397
+ /** A guide's or a skill's name, from its file: lowercase letters and digits joined by single hyphens. */
398
+ const NAME = /^(?=.{1,64}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
399
+ /** The Markdown files of a folder of `mcp/`, by name. Symlinks and other names are refused. */
400
+ function markdownFiles(root, folder) {
401
+ const directory = join(root, folder);
402
+ if (!existsSync(directory)) return [];
403
+ if (lstatSync(directory).isSymbolicLink()) throw new TypeError(`Project directory cannot be a symlink: ${folder}`);
404
+ return readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.name.endsWith(".md") && !entry.name.startsWith(".")).map((entry) => {
405
+ const path = relative(root, join(directory, entry.name));
406
+ if (!entry.isFile()) throw new TypeError(`MCP Markdown must be an ordinary file: ${path}`);
407
+ const name = entry.name.slice(0, -3);
408
+ if (!NAME.test(name)) throw new TypeError(`Name MCP Markdown in kebab-case, at most 64 characters: ${path}`);
409
+ return {
410
+ name,
411
+ path,
412
+ text: readFileSync(join(directory, entry.name), "utf-8")
413
+ };
414
+ }).toSorted((a, b) => compareNames(a.name, b.name));
415
+ }
416
+ /** A guide: its title is the `# heading` it starts with, and its text the whole Markdown. */
417
+ function guide({ name, path, text }) {
418
+ const title = /^# (.+)$/.exec(text.split(/\r?\n/, 1)[0] ?? "")?.[1]?.trim();
419
+ if (!title) throw new TypeError(`Start the guide with its # title: ${path}`);
420
+ return {
421
+ name,
422
+ title,
423
+ text
424
+ };
425
+ }
426
+ /**
427
+ * A skill: frontmatter states its one-line `description` (and `name`, which must be its file's), as an
428
+ * Agent Skill's `SKILL.md` does; the Markdown after it is the instructions.
429
+ */
430
+ function skill({ name, path, text }) {
431
+ const document = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(text);
432
+ if (!document) throw new TypeError(`Start the skill with frontmatter, ---, description: …, ---: ${path}`);
433
+ let description;
434
+ for (const line of (document[1] ?? "").split(/\r?\n/).filter((entry) => entry.trim())) {
435
+ const [, key, raw = ""] = /^([a-z-]+):\s*(.*?)\s*$/.exec(line) ?? [];
436
+ const value = /^(["'])(.*)\1$/.exec(raw)?.[2] ?? raw;
437
+ if (key === "description") description = value || void 0;
438
+ else if (key !== "name" || value !== name) throw new TypeError(`A skill's frontmatter states its one-line description, and its name only as its file does: ${path}`);
439
+ }
440
+ if (!description) throw new TypeError(`State the skill's one-line description in its frontmatter: ${path}`);
441
+ return {
442
+ name,
443
+ description,
444
+ text: document[2] ?? ""
445
+ };
446
+ }
447
+ /** What `mcp/` describes of the MCP server, or nothing when it holds none of its Markdown. */
448
+ function mcpMarkdown(root) {
449
+ const instructions = join(root, "mcp/instructions.md");
450
+ if (existsSync(instructions) && !lstatSync(instructions).isFile()) throw new TypeError("MCP Markdown must be an ordinary file: mcp/instructions.md");
451
+ const guides = markdownFiles(root, "mcp/guides").map(guide);
452
+ const skills = markdownFiles(root, "mcp/skills").map(skill);
453
+ checkMcpResourceNames({
454
+ guides,
455
+ skills
456
+ });
457
+ const configuration = {
458
+ ...existsSync(instructions) ? { instructions: readFileSync(instructions, "utf-8") } : {},
459
+ ...guides.length ? { guides } : {},
460
+ ...skills.length ? { skills } : {}
461
+ };
462
+ return Object.keys(configuration).length ? configuration : void 0;
463
+ }
464
+
465
+ // src/tooling/internal/service-types.ts
466
+ /** Whether a JSON value is an object, rather than a list or a scalar. */
467
+ function isObject(value) {
468
+ return typeof value === "object" && value !== null && !Array.isArray(value);
469
+ }
470
+ /** The prefix of a reference to a component schema. */
471
+ const COMPONENT = "#/components/schemas/";
472
+ /** A name TypeScript reads as an identifier. */
473
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
474
+ /** The methods OpenAPI names an operation under. */
475
+ const METHODS = [
476
+ "get",
477
+ "post",
478
+ "put",
479
+ "patch",
480
+ "delete"
481
+ ];
482
+ /** The names the module imports, which no type of the document may take. */
483
+ const IMPORTED = [
484
+ "Principal",
485
+ "Result",
486
+ "WorkerEntrypoint"
487
+ ];
488
+ /** A component's name as a type: its letters and digits, each part capitalized, `Note_2` as `Note2`. */
489
+ function typeName(component) {
490
+ const name = component.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
491
+ return /^[A-Za-z]/.test(name) ? name : `Schema${name}`;
492
+ }
493
+ /**
494
+ * A JSON value as a TypeScript literal type, a string in single quotes: `'USD'`, `true`, `null`, `3`. A
495
+ * string keeps JSON's escapes, so no character of it ends the literal or its line.
496
+ */
497
+ function literal(value) {
498
+ if (typeof value === "string") return `'${JSON.stringify(value).slice(1, -1).replaceAll("'", "\\'")}'`;
499
+ return JSON.stringify(value ?? null);
500
+ }
501
+ /** A property's name as TypeScript writes it: bare when it is an identifier, quoted otherwise. */
502
+ function propertyName(name) {
503
+ return IDENTIFIER.test(name) ? name : literal(name);
504
+ }
505
+ /** A type alias's declaration, with a union that spans lines starting on the line after `=`. */
506
+ function typeAlias(name, type) {
507
+ return `export type ${name} =${type.startsWith("\n") ? "" : " "}${type};`;
508
+ }
509
+ /** A union's members on one line, or one per line when they would not fit in 110 columns. */
510
+ function unionText(members, indent) {
511
+ const inline = members.join(" | ");
512
+ if (members.length < 2 || inline.length + indent.length <= 90) return inline;
513
+ return members.map((member) => `\n${indent} | ${member}`).join("");
514
+ }
515
+ /** A description as a JSDoc comment at an indentation, or nothing without one. */
516
+ function comment(description, indent) {
517
+ if (typeof description !== "string" || !description.trim()) return [];
518
+ const text = description.trim().replaceAll("*/", "* /");
519
+ const lines = text.split(/\r\n?|\n|\u2028|\u2029/);
520
+ return lines.length === 1 ? [`${indent}/** ${text} */`] : [
521
+ `${indent}/**`,
522
+ ...lines.map((line) => `${indent} * ${line}`.trimEnd()),
523
+ `${indent} */`
524
+ ];
525
+ }
526
+ /** Whether a type joins others with `|` or `&` at its top level, outside brackets and string literals. */
527
+ function isCompound(type) {
528
+ let depth = 0;
529
+ let quote;
530
+ for (let index = 0; index < type.length; index += 1) {
531
+ const character = type.charAt(index);
532
+ if (quote) {
533
+ if (character === "\\") index += 1;
534
+ else if (character === quote) quote = void 0;
535
+ } else if (character === "'" || character === "\"") quote = character;
536
+ else if ("{([<".includes(character)) depth += 1;
537
+ else if ("})]>".includes(character)) depth -= 1;
538
+ else if (depth === 0 && (character === "|" || character === "&")) return true;
539
+ }
540
+ return false;
541
+ }
542
+ /**
543
+ * Writes TypeScript for the JSON Schemas of one document: each expression as it is met, and a declaration
544
+ * for every component an expression names, in the order they are first named.
545
+ */
546
+ var TypeWriter = class {
547
+ #schemas;
548
+ /** The components named so far, by their component name, each with its type's name. */
549
+ #named = /* @__PURE__ */ new Map();
550
+ /** The declarations of the components named so far, in order. */
551
+ #declarations = [];
552
+ constructor(schemas) {
553
+ this.#schemas = schemas;
554
+ }
555
+ /** The declarations of every component the expressions named. */
556
+ get declarations() {
557
+ return this.#declarations;
558
+ }
559
+ /** The type a component's name stands for, declaring the component the first time it is named. */
560
+ named(component) {
561
+ const known = this.#named.get(component);
562
+ if (known) return known;
563
+ const schema = this.#schemas[component];
564
+ if (!isObject(schema)) throw new TypeError(`The document refers to the component ${component}, which it does not define.`);
565
+ const name = typeName(component);
566
+ this.#named.set(component, name);
567
+ const declaration = [...comment(schema.description, "")];
568
+ const object = this.#isPlainObject(schema) ? this.#objectType(schema, "") : void 0;
569
+ if (object?.startsWith("{")) declaration.push(`export interface ${name} ${object}`);
570
+ else declaration.push(typeAlias(name, object ?? this.type(schema)));
571
+ this.#declarations.push(declaration.join("\n"));
572
+ return name;
573
+ }
574
+ /** The TypeScript type of a schema. */
575
+ type(schema, indent = "") {
576
+ if (!isObject(schema)) return schema === false ? "never" : "unknown";
577
+ if (typeof schema.$ref === "string") {
578
+ if (!schema.$ref.startsWith(COMPONENT)) throw new TypeError(`The document refers to ${schema.$ref}, outside its component schemas.`);
579
+ return this.named(schema.$ref.slice(21));
580
+ }
581
+ if ("const" in schema) return literal(schema.const);
582
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => literal(value)).join(" | ") || "never";
583
+ const members = Array.isArray(schema.anyOf) ? schema.anyOf : schema.oneOf;
584
+ if (Array.isArray(members)) return this.#union(members, indent);
585
+ if (Array.isArray(schema.allOf)) return schema.allOf.map((member) => this.#wrapped(this.type(member, indent))).join(" & ") || "unknown";
586
+ if (Array.isArray(schema.type)) return this.#union(schema.type.map((type) => ({
587
+ ...schema,
588
+ type
589
+ })), indent);
590
+ switch (schema.type) {
591
+ case "string": return "string";
592
+ case "integer":
593
+ case "number": return "number";
594
+ case "boolean": return "boolean";
595
+ case "null": return "null";
596
+ case "array": return this.#arrayType(schema, indent);
597
+ case "object": return this.#objectType(schema, indent);
598
+ default: return schema.properties ? this.#objectType(schema, indent) : "unknown";
599
+ }
600
+ }
601
+ /** Whether a schema is one object with named fields, which an interface declares. */
602
+ #isPlainObject(schema) {
603
+ return schema.type === "object" && isObject(schema.properties) && schema.patternProperties === void 0 && !isObject(schema.additionalProperties);
604
+ }
605
+ /** A union of schemas' types, each member parenthesized where `|` would bind it otherwise. */
606
+ #union(members, indent) {
607
+ const types = [...new Set(members.map((member) => this.#wrapped(this.type(member, indent))))];
608
+ return types.length ? unionText(types, indent) : "never";
609
+ }
610
+ /** A type wrapped in parentheses when it is a union or an intersection itself. */
611
+ #wrapped(type) {
612
+ return isCompound(type) ? `(${type})` : type;
613
+ }
614
+ /** An array's type: a tuple of its `prefixItems`, else a list of its `items`. */
615
+ #arrayType(schema, indent) {
616
+ if (Array.isArray(schema.prefixItems)) return `[${schema.prefixItems.map((item) => this.type(item, indent)).join(", ")}]`;
617
+ const item = this.type(schema.items, indent);
618
+ return /^[\w.$]+$/.test(item) ? `${item}[]` : `Array<${item}>`;
619
+ }
620
+ /** An object's type: its fields, optional unless required, and any key a pattern or the rest admits. */
621
+ #objectType(schema, indent) {
622
+ const inner = `${indent} `;
623
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
624
+ const fields = Object.entries(isObject(schema.properties) ? schema.properties : {}).flatMap(([name, field]) => [...comment(isObject(field) ? field.description : void 0, inner), `${inner}${propertyName(name)}${required.has(name) ? "" : "?"}: ${this.type(field, inner)};`]);
625
+ const keyed = [...Object.values(isObject(schema.patternProperties) ? schema.patternProperties : {}), ...isObject(schema.additionalProperties) ? [schema.additionalProperties] : []];
626
+ if (keyed.length) fields.push(`${inner}[key: string]: ${this.#union(keyed, inner)};`);
627
+ else if (schema.additionalProperties === true || schema.type === "object" && !fields.length && schema.additionalProperties !== false) fields.push(`${inner}[key: string]: unknown;`);
628
+ return fields.length ? `{\n${fields.join("\n")}\n${indent}}` : "Record<string, never>";
629
+ }
630
+ };
631
+ /** The operations of a document that are native RPC methods, in the document's order. */
632
+ function rpcOperations(paths) {
633
+ return Object.values(paths).flatMap((item) => METHODS.flatMap((method) => {
634
+ const operation = isObject(item) ? item[method] : void 0;
635
+ if (!isObject(operation) || operation["x-native-rpc"] !== true) return [];
636
+ const name = operation.operationId;
637
+ if (typeof name !== "string" || !/^[a-z][A-Za-z0-9]*$/.test(name)) throw new TypeError("Every native RPC operation of the document has a camelCase operationId.");
638
+ const { summary, description } = operation;
639
+ return [{
640
+ name,
641
+ summary: typeof summary === "string" ? summary : void 0,
642
+ description: typeof description === "string" ? description : void 0,
643
+ operation
644
+ }];
645
+ }));
646
+ }
647
+ /** The schema of a response's or body's JSON content. */
648
+ function jsonSchema(content) {
649
+ const json = isObject(content) ? content["application/json"] : void 0;
650
+ return isObject(json) ? json.schema : void 0;
651
+ }
652
+ /**
653
+ * The input an RPC method takes: the fields of its path and query parameters, joined with its JSON body;
654
+ * the RPC method receives them as one object, as the route's handler does.
655
+ */
656
+ function inputType(operation, types) {
657
+ const fields = (Array.isArray(operation.parameters) ? operation.parameters.filter(isObject) : []).map((parameter) => {
658
+ const name = String(parameter.name);
659
+ const optional = parameter.required === true ? "" : "?";
660
+ return [...comment(parameter.description, " "), ` ${propertyName(name)}${optional}: ${types.type(parameter.schema, " ")};`];
661
+ });
662
+ const located = fields.length ? `{\n${fields.flat().join("\n")}\n}` : void 0;
663
+ const body = isObject(operation.requestBody) ? jsonSchema(operation.requestBody.content) : void 0;
664
+ const sent = body === void 0 ? void 0 : types.type(body);
665
+ if (located && sent) return `${located} & ${sent}`;
666
+ return located ?? sent ?? "Record<string, never>";
667
+ }
668
+ /** The component an envelope reference names, read from the document's schemas. */
669
+ function envelopeField(reference, field, schemas) {
670
+ if (!isObject(reference) || typeof reference.$ref !== "string" || !reference.$ref.startsWith(COMPONENT)) return;
671
+ const envelope = schemas[reference.$ref.slice(21)];
672
+ const properties = isObject(envelope) ? envelope.properties : void 0;
673
+ return isObject(properties) ? properties[field] : void 0;
674
+ }
675
+ /** What an RPC method answers when it succeeds: the `data` of its success envelope. */
676
+ function outputType(operation, types, schemas) {
677
+ const responses = isObject(operation.responses) ? operation.responses : {};
678
+ const success = Object.entries(responses).find(([status]) => /^2\d\d$/.test(status))?.[1];
679
+ const data = envelopeField(jsonSchema(isObject(success) ? success.content : void 0), "data", schemas);
680
+ return data === void 0 ? "unknown" : types.type(data);
681
+ }
682
+ /** The failures an RPC method may answer: the `error` of each failure envelope its responses document. */
683
+ function failureType(operation, types, schemas) {
684
+ const responses = isObject(operation.responses) ? operation.responses : {};
685
+ const failures = Object.entries(responses).flatMap(([status, response]) => {
686
+ if (!/^[45]\d\d$/.test(status) || !isObject(response)) return [];
687
+ const error = envelopeField(jsonSchema(response.content), "error", schemas);
688
+ return error === void 0 ? [] : [types.type(error)];
689
+ });
690
+ const unique = [...new Set(failures)];
691
+ return unique.length ? unionText(unique, "") : "never";
692
+ }
693
+ /** A binding's name as a type: `PRICING` is `Pricing`, `NOTES_API` is `NotesApi`. */
694
+ function serviceTypeName(binding) {
695
+ return binding.toLowerCase().split("_").filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
696
+ }
697
+ /**
698
+ * The module that types a service binding from the OpenAPI document its service publishes: the service's
699
+ * entrypoint, `<Binding>Service`, with one method per operation the document marks as native RPC, each
700
+ * answering a Result of its output or one of the failures its responses document, and the types of each
701
+ * input, output and failure. A document that is not an OpenAPI 3.1 document of paths, or that marks no
702
+ * operation as native RPC, throws a TypeError naming the binding and its file.
703
+ */
704
+ function serviceModule(binding, document, source) {
705
+ const parsed = document;
706
+ const where = `services.${binding}: ${source}`;
707
+ if (!isObject(parsed) || typeof parsed.openapi !== "string" || !parsed.openapi.startsWith("3.1") || !isObject(parsed.paths)) throw new TypeError(`${where} is not an OpenAPI 3.1 document; write it with maximus openapi in that service.`);
708
+ const components = isObject(parsed.components) ? parsed.components : {};
709
+ const schemas = isObject(components.schemas) ? components.schemas : {};
710
+ const operations = rpcOperations(parsed.paths);
711
+ if (!operations.length) throw new TypeError(`${where} documents no route served over native RPC: declare rpc in the routes this service calls.`);
712
+ const types = new TypeWriter(schemas);
713
+ const service = `${serviceTypeName(binding)}Service`;
714
+ const methods = operations.flatMap(({ name, summary, description, operation }) => {
715
+ const prefix = name.charAt(0).toUpperCase() + name.slice(1);
716
+ const input = `${prefix}Input`;
717
+ const failure = `${prefix}Failure`;
718
+ const taken = inputType(operation, types);
719
+ const inputDeclaration = taken === input ? [] : [`/** What \`${name}\` takes. */\n${typeAlias(input, taken)}`];
720
+ const answer = outputType(operation, types, schemas);
721
+ const output = /^[A-Za-z_$][\w$]*$/.test(answer) ? answer : `${prefix}Output`;
722
+ const outputDeclaration = output === answer ? [] : [`/** What \`${name}\` answers when it succeeds. */\n${typeAlias(output, answer)}`];
723
+ const answered = failureType(operation, types, schemas);
724
+ const failureDeclaration = answered === failure ? [] : [`/** The failures \`${name}\` may answer. */\n${typeAlias(failure, answered)}`];
725
+ return [{
726
+ method: [...comment([summary, description].filter(Boolean).join(": "), " "), ` ${name}(principal: Principal, input: ${input}): Promise<Result<${output}, ${failure}>>;`].join("\n"),
727
+ declarations: [
728
+ ...inputDeclaration,
729
+ ...outputDeclaration,
730
+ ...failureDeclaration
731
+ ]
732
+ }];
733
+ });
734
+ const title = isObject(parsed.info) && typeof parsed.info.title === "string" ? parsed.info.title : binding;
735
+ const declared = [
736
+ ...IMPORTED,
737
+ service,
738
+ ...[...methods.flatMap(({ declarations }) => declarations), ...types.declarations].flatMap((declaration) => /export (?:interface|type) (\w+)/.exec(declaration)?.[1] ?? [])
739
+ ];
740
+ const twice = declared.find((name, index) => declared.indexOf(name) !== index);
741
+ if (twice) throw new TypeError(`${where} names ${twice} twice among the types of the binding: rename that schema or operation in the service.`);
742
+ const owner = title.endsWith("s") ? `${title}'` : `${title}'s`;
743
+ return [
744
+ `// Generated by maximus prepare from ${source.replaceAll(/[\r\n\u2028\u2029]/g, " ")}. Change that service's routes and run maximus openapi there; never edit this file.`,
745
+ "import type { Principal, Result } from '@arbol-ai/maximus';",
746
+ "import type { WorkerEntrypoint } from 'cloudflare:workers';",
747
+ "",
748
+ ...comment(`${owner} \`Service\` entrypoint, as the ${binding} binding reaches it: one method per operation it serves over native RPC.`, ""),
749
+ `export interface ${service} extends WorkerEntrypoint {`,
750
+ methods.map(({ method }) => method).join("\n"),
751
+ "}",
752
+ "",
753
+ ...methods.flatMap(({ declarations }) => declarations.flatMap((declaration) => [declaration, ""])),
754
+ ...types.declarations.flatMap((declaration) => [declaration, ""])
755
+ ].join("\n");
756
+ }
757
+
758
+ // src/tooling/internal/prepare-project.ts
759
+ /**
760
+ * `maximus prepare`: turns a project's files and what its `vite.config.ts` states into the modules of
761
+ * `.maximus/`, which the Worker and the type checker load. Discovery parses application modules and never
762
+ * runs them, so preparing a project executes none of its code and keeps filesystem code out of the Worker.
763
+ */
764
+ /** The modules a generated one imports, each under a stable identifier. */
765
+ var Imports = class {
766
+ #lines = [];
767
+ #output;
768
+ constructor(output) {
769
+ this.#output = output;
770
+ }
771
+ /** The specifier that imports `file` from `.maximus/`. */
772
+ source(file) {
773
+ return JSON.stringify(relative(this.#output, file).split(sep).join("/"));
774
+ }
775
+ /** Imports `file`'s default export as `identifier`, or the clause given. */
776
+ add(identifier, file) {
777
+ this.#lines.push(`import ${identifier} from ${this.source(file)};`);
778
+ return identifier;
779
+ }
780
+ get lines() {
781
+ return this.#lines;
782
+ }
783
+ };
784
+ /** A generated module: the header that marks it, its imports and its statements. */
785
+ function generatedModule(mode, imports, body) {
786
+ return [
787
+ `// Generated by maximus prepare (${mode}). Edit the source modules, not this file.`,
788
+ ...imports,
789
+ ...imports.length ? [""] : [],
790
+ ...body,
791
+ ""
792
+ ].join("\n");
793
+ }
794
+ /**
795
+ * The one module of a convention (`errors`, `app/root`, …), in any of its extensions, if any.
796
+ */
797
+ function rootModule(root, name, extensions = [
798
+ "ts",
799
+ "mts",
800
+ "js",
801
+ "mjs"
802
+ ]) {
803
+ const found = extensions.map((extension) => `${name}.${extension}`).filter((file) => existsSync(join(root, file)));
804
+ if (found.length > 1) throw new TypeError(`Keep at most one ${name} module: ${found.join(" or ")}.`);
805
+ const [module] = found;
806
+ if (module && lstatSync(join(root, module)).isSymbolicLink()) throw new TypeError(`The ${name} module cannot be a symlink.`);
807
+ return module;
808
+ }
809
+ /** The specifier `.maximus/` imports a root module by. */
810
+ function relativeModule(module) {
811
+ return JSON.stringify(`../${module}`);
812
+ }
813
+ /** The HTTP methods a route or page file's suffix names: `index.get.ts` answers GET. */
814
+ const FILE_METHODS = [
815
+ "GET",
816
+ "POST",
817
+ "PUT",
818
+ "PATCH",
819
+ "DELETE"
820
+ ];
821
+ /** The method a file's name ends in, and the name before it: `index.get` is GET and `index`. */
822
+ function fileMethod(name) {
823
+ const method = FILE_METHODS.find((candidate) => name.endsWith(`.${candidate.toLowerCase()}`));
824
+ return method && {
825
+ method,
826
+ stem: name.slice(0, -(method.length + 1))
827
+ };
828
+ }
829
+ /**
830
+ * The routes `routes/` declares: one `defineHandler` per file, its path and method from the file's name, so
831
+ * `routes/v1/tasks/[taskId].get.ts` answers `GET /v1/tasks/{taskId}`. Returns the mounts and whether any
832
+ * route is also an MCP tool.
833
+ */
834
+ function discoverRoutes(root, files, imports) {
835
+ const owners = /* @__PURE__ */ new Map();
836
+ let mcp = false;
837
+ return {
838
+ mounts: files.map(({ name, file }, index) => {
839
+ const suffix = fileMethod(name);
840
+ if (!suffix) throw new TypeError(`Name a route file by its method, such as routes/v1/tasks/index.get.ts: ${relative(root, file)}`);
841
+ const { method, stem } = suffix;
842
+ const path = projectPath(stem, "routes");
843
+ try {
844
+ operationPathParameters(path);
845
+ } catch (error) {
846
+ throw new TypeError(`${relative(root, file)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
847
+ }
848
+ const claim = `${method} ${routeShape(path)}`;
849
+ const owner = owners.get(claim);
850
+ if (owner) throw new TypeError(`Multiple route files claim ${method} ${path}: ${relative(root, owner)} and ${relative(root, file)}.`);
851
+ owners.set(claim, file);
852
+ mcp = declarationExports(root, file, "defineHandler").mcp || mcp;
853
+ const identifier = imports.add(`route_${index}`, file);
854
+ const operation = JSON.stringify(routeName(method, path));
855
+ return `.mount(bindRoute(base, ${identifier}, ${JSON.stringify(path)}, ${JSON.stringify(method)}, ${operation}))`;
856
+ }),
857
+ mcp
858
+ };
859
+ }
860
+ /** The tools only MCP serves: each a top-level module of `mcp/tools/`, named by its file. */
861
+ function discoverTools(root, files, imports) {
862
+ return files.map(({ name, file }, index) => {
863
+ const tool = /^tools\/([a-z][a-z0-9]*(?:-[a-z0-9]+)*)$/.exec(name)?.[1];
864
+ if (!tool) throw new TypeError(`MCP modules are kebab-case tools directly in mcp/tools/, such as mcp/tools/summarize-tasks.ts: ${relative(root, file)}`);
865
+ declarationExports(root, file, "defineTool");
866
+ return `.mount(bindTool(base, ${imports.add(`tool_${index}`, file)}, ${JSON.stringify(tool)}))`;
867
+ });
868
+ }
869
+ /**
870
+ * The pages `pages/` declares: native responses at fixed paths outside the API, refused at a path the generated
871
+ * Worker answers otherwise, as it would refuse them when it starts. A page answers `GET` (and `HEAD`), or the
872
+ * method its name ends with, as a route's does: `hooks/billing.post.ts` answers `POST /hooks/billing`.
873
+ */
874
+ function discoverPages(root, files, imports, project, mcp) {
875
+ const pages = /* @__PURE__ */ new Map();
876
+ for (const [index, { name, file }] of files.entries()) {
877
+ const suffix = fileMethod(name);
878
+ const method = suffix?.method ?? "GET";
879
+ const path = projectPath(suffix?.stem ?? name, "pages");
880
+ const methods = pages.get(path) ?? /* @__PURE__ */ new Map();
881
+ const owner = methods.get(method);
882
+ if (owner) throw new TypeError(`Multiple page files claim ${method} ${path}: ${relative(root, owner.file)} and ${relative(root, file)}.`);
883
+ methods.set(method, {
884
+ file,
885
+ page: imports.add(`page_${index}`, file)
886
+ });
887
+ pages.set(path, methods);
888
+ }
889
+ checkPagePaths(pages.keys(), project.application.tokens, {
890
+ http: project.worker.http,
891
+ transports: mcp ? [{ path: "/mcp" }] : []
892
+ });
893
+ const entries = [...pages].map(([path, methods]) => {
894
+ const answered = [...methods].map(([method, { page }]) => `${method}: ${page}`);
895
+ return `${JSON.stringify(path)}: ${objectLiteral(answered)}`;
896
+ });
897
+ return {
898
+ paths: new Set(pages.keys()),
899
+ entries
900
+ };
901
+ }
902
+ /** A generated object literal of these entries, `{ a: b }`, or `{}` without any. */
903
+ function objectLiteral(entries) {
904
+ return entries.length ? `{ ${entries.join(", ")} }` : "{}";
905
+ }
906
+ /** The queue consumers or email recipients a folder declares, each a top-level module named after its key. */
907
+ function discoverEvents(kind, files, imports) {
908
+ const keys = /* @__PURE__ */ new Set();
909
+ return files.map(({ name, file }, index) => {
910
+ if (name.includes("/") || keys.has(name)) throw new TypeError(`${kind} modules require distinct top-level names: ${name}`);
911
+ keys.add(name);
912
+ return `${JSON.stringify(name)}: ${imports.add(`${kind === "queues" ? "queue" : "email"}_${index}`, file)}`;
913
+ });
914
+ }
915
+ /** The name a Durable Object module's class is exported under: `session-store.ts` exports `SessionStore`. */
916
+ function durableObjectClass(name) {
917
+ return name.split("-").map((part) => part[0]?.toUpperCase() + part.slice(1)).join("");
918
+ }
919
+ /**
920
+ * Each binding to one of the Worker's own Durable Object classes, in every mode, as the namespace of that
921
+ * class. Cloudflare's inference sees the Worker only by its name there, and types the namespace without it.
922
+ */
923
+ function durableObjectBindings(project, files, imports) {
924
+ const classes = new Map(files.map(({ name, file }) => [durableObjectClass(name), imports.source(file)]));
925
+ const { production, development } = project.env;
926
+ return Object.entries(production).flatMap(([key, binding]) => {
927
+ if (typeof binding !== "object" || binding === null || !Object.hasOwn(development, key)) return [];
928
+ const { type, worker, exportName } = binding;
929
+ const source = typeof exportName === "string" ? classes.get(exportName) : void 0;
930
+ return type === "durable-object" && worker === project.application.name && source ? [` ${JSON.stringify(key)}: DurableObjectNamespace<import(${source}).default>;`] : [];
931
+ });
932
+ }
933
+ /** The Durable Object classes `durable-objects/` declares, exported under the PascalCase of their files. */
934
+ function discoverDurableObjects(files, imports) {
935
+ const classes = /* @__PURE__ */ new Set(["Service"]);
936
+ return files.map(({ name, file }, index) => {
937
+ 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}`);
938
+ const className = durableObjectClass(name);
939
+ if (classes.has(className)) throw new TypeError(`Duplicate Worker export: ${className}`);
940
+ classes.add(className);
941
+ return `export const ${className} = worker.durableObject(${imports.add(`durable_object_${index}`, file)});`;
942
+ });
943
+ }
944
+ /**
945
+ * A web app: `index.html` at the root, which the plugin found, and the pages `app/routes/` declares. The same
946
+ * files make React Router's routes and the paths the Worker answers with the app's shell.
947
+ */
948
+ function discoverWebApp(root, output, mode, project, pagePaths) {
949
+ const web = project.worker.assets;
950
+ if (!web) {
951
+ if (existsSync(join(root, "app/routes"))) throw new TypeError("app/routes/ holds the pages of a web app: add its index.html at the project root.");
952
+ return;
953
+ }
954
+ if (existsSync(join(root, "app")) && lstatSync(join(root, "app")).isSymbolicLink()) throw new TypeError("Project directory cannot be a symlink: app");
955
+ const { basePath, healthPath } = project.worker.http;
956
+ if (basePath === "" || basePath === "/") throw new TypeError("A web app answers at the root: keep the API below http.basePath, /api by default.");
957
+ const layout = rootModule(root, "app/root", [
958
+ "tsx",
959
+ "jsx",
960
+ "ts",
961
+ "js"
962
+ ]);
963
+ const pages = projectFiles(root, "app/routes", mode);
964
+ const shell = {
965
+ paths: pages.length ? [] : ["/"],
966
+ patterns: []
967
+ };
968
+ const claimed = /* @__PURE__ */ new Map();
969
+ const imports = new Imports(output);
970
+ const routes = pages.map(({ name, file }) => {
971
+ const route = projectPath(name, "app");
972
+ const shape = route.replaceAll(/:[^/]+/g, ":");
973
+ const owner = claimed.get(shape);
974
+ if (owner) throw new TypeError(`Multiple page files claim ${route}: ${relative(root, owner)} and ${relative(root, file)}.`);
975
+ claimed.set(shape, file);
976
+ if (route.includes(":")) shell.patterns.push(`/^${route.replaceAll(/:[^/]+/g, "[^/]+").replaceAll("/", String.raw`\/`)}$/`);
977
+ else shell.paths.push(route);
978
+ return `{ path: ${JSON.stringify(route)}, caseSensitive: true, lazy: () => import(${imports.source(file)}).then(page) }`;
979
+ });
980
+ for (const route of [...shell.paths, ...pages.map(({ name }) => projectPath(name, "app"))]) if ([
981
+ basePath,
982
+ "/.well-known",
983
+ "/mcp",
984
+ "/assets"
985
+ ].some((prefix) => ownsPrefix(prefix, route)) || route === healthPath || VERSIONED_PATH.test(route) || pagePaths.has(route)) throw new TypeError(`The page ${route} claims a path the API, discovery, MCP, the build's assets or pages/ answer: move it in app/routes/.`);
986
+ const source = pages.length ? generatedModule(mode, [
987
+ "import type { ComponentType } from 'react';",
988
+ "import type { RouteObject } from 'react-router';",
989
+ ...layout ? [`import * as layout from ${imports.source(join(root, layout))};`] : []
990
+ ], [
991
+ "/** A page module: its default export renders the page, and its other exports are React Router’s. */",
992
+ "function page<Module extends { default: ComponentType }>({ default: Component, ...route }: Module) {",
993
+ " return { ...route, Component };",
994
+ "}",
995
+ "",
996
+ "/** The pages app/routes/ declares, each loaded when it is first visited. */",
997
+ `export const routes: RouteObject[] = ${layout ? `[{ ...page(layout), children: [\n ${routes.join(",\n ")},\n] }]` : `[\n ${routes.join(",\n ")},\n]`};`
998
+ ]) : void 0;
999
+ return {
1000
+ policy: `{ ${[
1001
+ `binding: ${JSON.stringify(web.binding)}`,
1002
+ ...web.headers && Object.keys(web.headers).length ? [`headers: ${JSON.stringify(web.headers)}`] : [],
1003
+ `pages: { paths: ${JSON.stringify(shell.paths)}, patterns: [${shell.patterns.join(", ")}] }`,
1004
+ `files: ${JSON.stringify(publicFiles(root))}`,
1005
+ "immutablePrefixes: ['/assets']",
1006
+ `development: ${mode === "development"}`
1007
+ ].join(", ")} }`,
1008
+ routes: source,
1009
+ files: [...pages.map(({ file }) => file), ...layout ? [join(root, layout)] : []],
1010
+ pages: pages.length
1011
+ };
1012
+ }
1013
+ /**
1014
+ * Writes the generated modules, replacing only those whose text changed, and removes the ones whose sources
1015
+ * are gone. Every destination is checked before any is replaced, so a refusal keeps the previous output.
1016
+ */
1017
+ function writeGenerated(output, generated, owned) {
1018
+ const stale = owned.filter((name) => !(name in generated) && existsSync(join(output, name)));
1019
+ for (const name of [...Object.keys(generated), ...stale]) {
1020
+ const target = join(output, name);
1021
+ if (existsSync(target) && (lstatSync(target).isSymbolicLink() || !lstatSync(target).isFile())) throw new TypeError(`Generated files must be ordinary files: ${name}`);
1022
+ }
1023
+ if (existsSync(join(output, "services")) && lstatSync(join(output, "services")).isSymbolicLink()) throw new TypeError("The generated .maximus/services directory cannot be a symlink.");
1024
+ mkdirSync(output, { recursive: true });
1025
+ let changed = false;
1026
+ for (const [name, content] of Object.entries(generated)) {
1027
+ const target = join(output, name);
1028
+ mkdirSync(dirname(target), { recursive: true });
1029
+ if (!existsSync(target) || readFileSync(target, "utf-8") !== content) {
1030
+ changed = true;
1031
+ const temporary = `${target}.${process.pid}.tmp`;
1032
+ writeFileSync(temporary, content, { flag: "wx" });
1033
+ renameSync(temporary, target);
1034
+ }
1035
+ }
1036
+ for (const name of stale) {
1037
+ rmSync(join(output, name));
1038
+ changed = true;
1039
+ }
1040
+ return changed;
1041
+ }
1042
+ /** The file under `.maximus/services/` that types a binding: `PRICING` is `pricing.ts`, `NOTES_API` `notes-api.ts`. */
1043
+ function serviceFile(binding) {
1044
+ return `${binding.toLowerCase().replaceAll("_", "-")}.ts`;
1045
+ }
1046
+ /**
1047
+ * The modules that type the services the project calls, each from the OpenAPI document its service publishes,
1048
+ * with the documents read, which the plugin watches, and the `Env` entry each binding's type takes.
1049
+ */
1050
+ function serviceTypes(root, project) {
1051
+ const services = Object.entries(project.services ?? {});
1052
+ return {
1053
+ modules: Object.fromEntries(services.map(([binding, { openapi }]) => {
1054
+ const file = resolve(root, openapi);
1055
+ if (!existsSync(file)) throw new TypeError(`services.${binding}: ${openapi} does not exist; write it with maximus openapi in that service.`);
1056
+ let document;
1057
+ try {
1058
+ document = JSON.parse(readFileSync(file, "utf-8"));
1059
+ } catch (error) {
1060
+ throw new TypeError(`services.${binding}: ${openapi} is not JSON.`, { cause: error });
1061
+ }
1062
+ return [`services/${serviceFile(binding)}`, serviceModule(binding, document, openapi)];
1063
+ })),
1064
+ files: services.map(([, { openapi }]) => resolve(root, openapi)),
1065
+ bindings: services.map(([binding]) => ` ${JSON.stringify(binding)}: Service<import('./services/${serviceFile(binding)}').${serviceTypeName(binding)}Service>;`)
1066
+ };
1067
+ }
1068
+ /**
1069
+ * Prepares the project at `directory` for a mode, `development` under `vp dev` and `production` for every
1070
+ * build: discovers its modules, refuses what would build a Worker other than the one its files describe, and
1071
+ * writes `.maximus/`. A refusal never replaces the previous output.
1072
+ */
1073
+ function prepareProject(directory, mode, project) {
1074
+ const root = resolve(directory);
1075
+ const output = join(root, ".maximus");
1076
+ if (existsSync(output) && lstatSync(output).isSymbolicLink()) throw new TypeError("The generated .maximus directory cannot be a symlink.");
1077
+ const catalog = rootModule(root, "errors");
1078
+ const auth = rootModule(root, "auth");
1079
+ const context = rootModule(root, "context");
1080
+ const telemetry = rootModule(root, "telemetry");
1081
+ for (const module of [
1082
+ catalog,
1083
+ auth,
1084
+ context,
1085
+ telemetry
1086
+ ]) if (module) readProjectModule(root, join(root, module), "config");
1087
+ const files = Object.fromEntries(PROJECT_DIRECTORIES.map((name) => [name, projectFiles(root, name, mode)]));
1088
+ for (const { file } of files.middleware) readProjectModule(root, file, "middleware");
1089
+ for (const { file } of [
1090
+ ...files.pages,
1091
+ ...files.queues,
1092
+ ...files.email,
1093
+ ...files["durable-objects"]
1094
+ ]) readProjectModule(root, file, "worker");
1095
+ const schedules = files.crons.map(({ file }) => ({
1096
+ file,
1097
+ cron: cronExpression(root, file)
1098
+ }));
1099
+ const described = mcpMarkdown(root);
1100
+ const application = new Imports(output);
1101
+ const routes = discoverRoutes(root, files.routes, application);
1102
+ const tools = discoverTools(root, files.mcp, application);
1103
+ const servesMcp = routes.mcp || tools.length > 0 || described !== void 0;
1104
+ if (servesMcp && project.application.tokens.source === "cloudflare-access") throw new TypeError("A project behind Cloudflare Access serves no MCP, whose clients sign in through OAuth: remove mcp from its routes, and the mcp/ folder.");
1105
+ const binders = [
1106
+ ...files.routes.length ? ["bindRoute"] : [],
1107
+ ...tools.length ? ["bindTool"] : [],
1108
+ "checkProjectPipeline"
1109
+ ];
1110
+ const middleware = new Imports(output);
1111
+ const middlewareModules = files.middleware.map(({ file }, index) => middleware.add(`middleware_${index}`, file));
1112
+ const worker = new Imports(output);
1113
+ const pages = discoverPages(root, files.pages, worker, project, servesMcp);
1114
+ const crons = files.crons.map(({ file }, index) => {
1115
+ worker.add(`cron_${index}, { cron as schedule_${index} }`, file);
1116
+ return `{ cron: schedule_${index}, handler: cron_${index} }`;
1117
+ });
1118
+ const queues = discoverEvents("queues", files.queues, worker);
1119
+ const email = discoverEvents("email", files.email, worker);
1120
+ const durableObjects = discoverDurableObjects(files["durable-objects"], worker);
1121
+ const objects = durableObjectBindings(project, files["durable-objects"], new Imports(output));
1122
+ const services = serviceTypes(root, project);
1123
+ const typed = [...objects.length ? [{
1124
+ name: "DurableObjects",
1125
+ entries: objects
1126
+ }] : [], ...services.bindings.length ? [{
1127
+ name: "Services",
1128
+ entries: services.bindings
1129
+ }] : []];
1130
+ const web = discoverWebApp(root, output, mode, project, pages.paths);
1131
+ return {
1132
+ directory: root,
1133
+ mode,
1134
+ changed: writeGenerated(output, {
1135
+ "config.ts": generatedModule(mode, ["import type { WorkerOptions } from '@arbol-ai/maximus/workers';"], [`export const application = ${JSON.stringify(project.application)} as const;`, `export const worker: WorkerOptions<Env> = ${JSON.stringify({ http: project.worker.http })};`]),
1136
+ "env.d.ts": generatedModule(mode, [], [
1137
+ "type Bindings = import('cf/config').InferEnv<",
1138
+ ` { env: ${JSON.stringify(project.env.production)} } | { env: ${JSON.stringify(project.env.development)} }`,
1139
+ ">;",
1140
+ ...typed.flatMap(({ name, entries }) => [
1141
+ `type ${name} = {`,
1142
+ ...entries,
1143
+ "};"
1144
+ ]),
1145
+ "",
1146
+ "declare global {",
1147
+ " namespace Cloudflare {",
1148
+ typed.length ? ` interface Env extends Omit<Bindings, ${typed.map(({ name }) => `keyof ${name}`).join(" | ")}>, ${typed.map(({ name }) => name).join(", ")} {}` : " interface Env extends Bindings {}",
1149
+ " }",
1150
+ " interface Env extends Cloudflare.Env {}",
1151
+ "}",
1152
+ "",
1153
+ "export {};"
1154
+ ]),
1155
+ "middleware.ts": generatedModule(mode, ["import { collectMiddleware } from '@arbol-ai/maximus/config';", ...middleware.lines], [`export const { middleware, requestMiddleware } = collectMiddleware([${middlewareModules.join(", ")}] as const);`]),
1156
+ "base.ts": generatedModule(mode, [
1157
+ `import { ${[
1158
+ ...auth ? ["defineAuth"] : [],
1159
+ ...telemetry ? ["defineTelemetry"] : [],
1160
+ "maximus",
1161
+ ...catalog ? [] : ["standardErrors"]
1162
+ ].join(", ")} } from '@arbol-ai/maximus';`,
1163
+ `import { ${context ? "bindContext, " : ""}useProjectMiddleware } from '@arbol-ai/maximus/config';`,
1164
+ "import { application } from './config.ts';",
1165
+ "import { middleware } from './middleware.ts';",
1166
+ ...described ? ["import { mcp } from './mcp.ts';"] : [],
1167
+ ...catalog ? [`import errors from ${relativeModule(catalog)};`] : [],
1168
+ ...auth ? [`import auth from ${relativeModule(auth)};`] : [],
1169
+ ...context ? [`import context from ${relativeModule(context)};`] : [],
1170
+ ...telemetry ? [`import telemetry from ${relativeModule(telemetry)};`] : []
1171
+ ], [`const configured = maximus<Env>({ ${[
1172
+ "...application",
1173
+ ...auth ? ["tokens: { ...application.tokens, ...defineAuth(auth) }"] : [],
1174
+ catalog ? "errors" : "errors: standardErrors",
1175
+ ...described ? ["mcp"] : [],
1176
+ ...telemetry ? ["telemetry: defineTelemetry(telemetry)"] : []
1177
+ ].join(", ")} });`, `export const base = useProjectMiddleware(${context ? "bindContext(configured, context)" : "configured"}, middleware);`]),
1178
+ "register.d.ts": generatedModule(mode, ["import type { base } from './base.ts';", ...catalog ? [`import type errors from ${relativeModule(catalog)};`] : []], [
1179
+ "declare global {",
1180
+ " interface MaximusRegister {",
1181
+ " base: typeof base;",
1182
+ ...catalog ? [" errors: typeof errors;"] : [],
1183
+ " env: Env;",
1184
+ " }",
1185
+ "}"
1186
+ ]),
1187
+ "app.ts": generatedModule(mode, [
1188
+ `import { ${binders.join(", ")} } from '@arbol-ai/maximus/config';`,
1189
+ "import { base } from './base.ts';",
1190
+ ...application.lines
1191
+ ], [
1192
+ "export const app = checkProjectPipeline(",
1193
+ " base,",
1194
+ ` base${[...routes.mounts, ...tools].map((mount) => `\n ${mount}`).join("")}`,
1195
+ " .build()",
1196
+ ");"
1197
+ ]),
1198
+ "worker.ts": generatedModule(mode, [
1199
+ "import { createProjectWorker } from '@arbol-ai/maximus/project';",
1200
+ "import type { WorkerRuntime } from '@arbol-ai/maximus/workers';",
1201
+ ...servesMcp ? ["import { mcp } from '@arbol-ai/maximus/mcp';"] : [],
1202
+ "import { app } from './app.ts';",
1203
+ "import { worker as options } from './config.ts';",
1204
+ "import { requestMiddleware } from './middleware.ts';",
1205
+ ...worker.lines
1206
+ ], [
1207
+ "const worker: WorkerRuntime<Env, typeof app.operations> = createProjectWorker(",
1208
+ " app,",
1209
+ " {",
1210
+ ` pages: ${objectLiteral(pages.entries)},`,
1211
+ ` crons: [${crons.join(", ")}],`,
1212
+ ` queues: ${objectLiteral(queues)},`,
1213
+ ` email: ${objectLiteral(email)},`,
1214
+ " },",
1215
+ " {",
1216
+ " ...options,",
1217
+ ...servesMcp ? [" transports: [mcp()],"] : [],
1218
+ ...web ? [` assets: ${web.policy},`] : [],
1219
+ " http: { ...options.http, middleware: requestMiddleware },",
1220
+ " }",
1221
+ ");",
1222
+ "",
1223
+ "export default worker.handler;",
1224
+ "export const Service = worker.entrypoint;",
1225
+ ...durableObjects
1226
+ ]),
1227
+ "http.ts": generatedModule(mode, [
1228
+ "import { createHttpHandler } from '@arbol-ai/maximus';",
1229
+ ...servesMcp ? ["import { mcp } from '@arbol-ai/maximus/mcp';"] : [],
1230
+ "import { app } from './app.ts';",
1231
+ "import { worker } from './config.ts';",
1232
+ "import { requestMiddleware } from './middleware.ts';"
1233
+ ], ["/** The API as the Worker serves it, below its base path and behind its middleware, for tests in Node. */", `export const handler = createHttpHandler(app, { ...worker.http, middleware: requestMiddleware${servesMcp ? ", transports: [mcp()]" : ""} });`]),
1234
+ "entry.ts": generatedModule(mode, [], ["export { default } from './worker.ts';", "export * from './worker.ts';"]),
1235
+ ...services.modules,
1236
+ ...web?.routes ? { "app-routes.ts": web.routes } : {},
1237
+ ...described ? { "mcp.ts": generatedModule(mode, ["import type { McpConfiguration } from '@arbol-ai/maximus';"], [`export const mcp: McpConfiguration = ${JSON.stringify(described)};`]) } : {}
1238
+ }, [
1239
+ "app-routes.ts",
1240
+ "mcp.ts",
1241
+ "routes.ts",
1242
+ ...existsSync(join(output, "services")) ? readdirSync(join(output, "services")).map((name) => `services/${name}`) : []
1243
+ ]),
1244
+ durableObjects: files["durable-objects"].map(({ file }) => file),
1245
+ crons: schedules,
1246
+ queues: files.queues.map(({ name }) => name),
1247
+ webApp: web !== void 0,
1248
+ files: [
1249
+ ...Object.values(files).flat().map(({ file }) => file),
1250
+ ...web?.files ?? [],
1251
+ ...services.files
1252
+ ],
1253
+ modules: {
1254
+ ...Object.fromEntries(Object.entries(files).map(([kind, entries]) => [kind, entries.length])),
1255
+ app: web?.pages ?? 0
1256
+ }
1257
+ };
1258
+ }
1259
+
1260
+ // src/vite/project.ts
1261
+ /**
1262
+ * The Vite plugin that keeps `.maximus/` in step with a project's files, which `maximus()` composes with
1263
+ * Cloudflare's.
1264
+ */
1265
+ /** A web app's pages and layout, and the files its build serves by name. */
1266
+ const WEB_APP_DIRECTORIES = ["app", "public"];
1267
+ /** The root modules that complete the application, and the web app's HTML entry. */
1268
+ const ROOT_MODULE = /^(?:(?:errors|auth|context|telemetry)\.(?:ts|mts|js|mjs)|index\.html)$/;
1269
+ /**
1270
+ * What the Worker's configuration and exports follow from a prepared project: Cloudflare's plugin reads them as
1271
+ * the server starts, so only a restart applies a change to them.
1272
+ */
1273
+ function workerShape({ webApp, durableObjects, crons, queues }) {
1274
+ return JSON.stringify({
1275
+ webApp,
1276
+ durableObjects,
1277
+ crons,
1278
+ queues
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Prepares the project before every build and before Vite reloads source modules during development, and
1283
+ * asks for a restart when the Worker itself changes: a web app appears or goes, a Durable Object does, or a
1284
+ * trigger its cron and queue modules state. The project is prepared for `development` under `vp dev` alone;
1285
+ * every build is `production`.
1286
+ */
1287
+ function maximusProject(project) {
1288
+ let root = process.cwd();
1289
+ let mode = "production";
1290
+ let previous;
1291
+ const prepare = (directory, preparing) => prepareProject(directory, preparing, project(resolve(directory), preparing));
1292
+ const reconcile = () => {
1293
+ const current = prepare(root, mode);
1294
+ const restart = previous !== void 0 && workerShape(previous) !== workerShape(current);
1295
+ previous = current;
1296
+ return {
1297
+ ...current,
1298
+ restart
1299
+ };
1300
+ };
1301
+ const isProjectFile = (file) => {
1302
+ const [first = "", ...rest] = relative(root, file).split(/[\\/]/);
1303
+ return [...PROJECT_DIRECTORIES, ...WEB_APP_DIRECTORIES].some((name) => name === first) || rest.length === 0 && ROOT_MODULE.test(first);
1304
+ };
1305
+ return {
1306
+ name: "maximus-project",
1307
+ enforce: "pre",
1308
+ api: { prepare },
1309
+ config(config, environment) {
1310
+ root = resolve(config.root ?? root);
1311
+ mode = environment.command === "serve" && !environment.isPreview ? "development" : "production";
1312
+ reconcile();
1313
+ },
1314
+ buildStart() {
1315
+ const current = reconcile();
1316
+ for (const file of current.files) this.addWatchFile(file);
1317
+ for (const directory of [...PROJECT_DIRECTORIES, ...WEB_APP_DIRECTORIES]) {
1318
+ const path = resolve(root, directory);
1319
+ if (existsSync(path)) this.addWatchFile(path);
1320
+ }
1321
+ },
1322
+ hotUpdate: {
1323
+ order: "pre",
1324
+ async handler({ file, server }) {
1325
+ if (!isProjectFile(file)) return;
1326
+ const current = reconcile();
1327
+ if (current.restart) {
1328
+ await server.restart();
1329
+ return [];
1330
+ }
1331
+ if (current.changed) this.environment.hot.send({ type: "full-reload" });
1332
+ }
1333
+ }
1334
+ };
1335
+ }
1336
+
1337
+ // src/vite/tokens.ts
1338
+ /** A host name in lowercase: labels of letters, digits and inner hyphens, joined by dots. */
1339
+ const HOST_NAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
1340
+ /** Every algorithm `Auth0Algorithm` names. */
1341
+ const AUTH0_ALGORITHMS = /* @__PURE__ */ new Set([
1342
+ "RS256",
1343
+ "RS512",
1344
+ "PS256"
1345
+ ]);
1346
+ /** A Zero Trust team name: one lowercase label of letters, digits and inner hyphens. */
1347
+ const TEAM_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1348
+ /** An Access application's AUD tag: 64 lowercase hexadecimal characters. */
1349
+ const AUD_TAG = /^[0-9a-f]{64}$/;
1350
+ /**
1351
+ * The token options of an API whose access tokens Auth0 issues: its issuer, `https://<domain>/` with the
1352
+ * trailing slash of Auth0's `iss`, its audience and its algorithms. The JWKS, the endpoints and the claims
1353
+ * keep their defaults, which are Auth0's. Throws a TypeError for a domain that is not a lowercase host name,
1354
+ * such as one with a scheme or a path, and for an algorithm other than RS256, RS512 and PS256: HS256 tokens
1355
+ * are signed with a secret, which no JWKS publishes.
1356
+ */
1357
+ function auth0({ domain, audience, algorithms = ["RS256"] }) {
1358
+ const domains = typeof domain === "string" ? [domain] : domain;
1359
+ if (!domains.length || domains.some((name) => typeof name !== "string" || !HOST_NAME.test(name))) throw new TypeError("auth0() takes the tenant's domain as a lowercase host name, such as acme.us.auth0.com: no scheme, port or path.");
1360
+ if (!algorithms.length || algorithms.some((name) => !AUTH0_ALGORITHMS.has(name))) throw new TypeError("auth0() verifies tokens signed with RS256, RS512 or PS256: an HS256 token is signed with a secret, which no JWKS publishes.");
1361
+ return {
1362
+ issuer: typeof domain === "string" ? `https://${domain}/` : domains.map((name) => `https://${name}/`),
1363
+ audience,
1364
+ algorithms
1365
+ };
1366
+ }
1367
+ /**
1368
+ * The token options of an application behind Cloudflare Access: the application token Access sets in
1369
+ * `Cf-Access-Jwt-Assertion`, read from there alone and verified against the team's keys (RS256, issued by
1370
+ * `https://<team>.cloudflareaccess.com`) for the application's AUD tag, and the scopes `scopes` grants. A
1371
+ * production build pins the Worker to its origin, so no request reaches it around Access. Throws a TypeError
1372
+ * for a team that is not a team name, such as the team's domain, and an AUD tag that is not 64 lowercase
1373
+ * hexadecimal characters.
1374
+ */
1375
+ function cloudflareAccess({ team, aud, organizationId, scopes }) {
1376
+ if (typeof team !== "string" || !TEAM_NAME.test(team)) throw new TypeError("cloudflareAccess() takes the Zero Trust team name, such as acme for acme.cloudflareaccess.com.");
1377
+ if (typeof aud !== "string" || !AUD_TAG.test(aud)) throw new TypeError("cloudflareAccess() takes the Access application's AUD tag: 64 lowercase hexadecimal characters.");
1378
+ const issuer = `https://${team}.cloudflareaccess.com`;
1379
+ return {
1380
+ source: "cloudflare-access",
1381
+ issuer,
1382
+ jwksUri: `${issuer}/cdn-cgi/access/certs`,
1383
+ audience: [aud],
1384
+ algorithms: ["RS256"],
1385
+ access: {
1386
+ ...organizationId === void 0 ? {} : { organizationId },
1387
+ people: scopes.people,
1388
+ ...scopes.services === void 0 ? {} : { services: scopes.services }
1389
+ }
1390
+ };
1391
+ }
1392
+
1393
+ // src/vite/index.ts
1394
+ /**
1395
+ * `@arbol-ai/maximus/vite`: one `vite.config.ts` configures a Maximus application and the Cloudflare Worker
1396
+ * that serves it. `maximus()` keeps the project's generated modules in step with its files and runs
1397
+ * Cloudflare's Vite plugin with the Worker its options describe.
1398
+ */
1399
+ /**
1400
+ * The Maximus lint and format presets, for each of `lint` and `fmt` the configuration does not set itself.
1401
+ * They need oxlint, oxfmt and Ultracite, which the starters install; without them, Vite+'s defaults apply.
1402
+ */
1403
+ async function presets(config) {
1404
+ const added = {};
1405
+ try {
1406
+ if (!("lint" in config)) {
1407
+ const { default: lint } = await import("@arbol-ai/maximus/oxlint");
1408
+ added.lint = {
1409
+ ...lint,
1410
+ options: { typeAware: false }
1411
+ };
1412
+ }
1413
+ if (!("fmt" in config)) {
1414
+ const { default: fmt } = await import("@arbol-ai/maximus/oxfmt");
1415
+ added.fmt = fmt;
1416
+ }
1417
+ } catch (error) {
1418
+ if (!(error instanceof Error && "code" in error && error.code === "ERR_MODULE_NOT_FOUND")) throw error;
1419
+ }
1420
+ return added;
1421
+ }
1422
+ /**
1423
+ * Maximus in Vite+: prepares the project from its files before every build and source change, brings the
1424
+ * Maximus lint and format presets, and builds, runs and deploys the Worker these options describe through
1425
+ * Cloudflare's Vite plugin.
1426
+ */
1427
+ function maximus(options) {
1428
+ const project = maximusProject((root, phase) => projectOptions(root, options, phase));
1429
+ let worker;
1430
+ const configure = {
1431
+ name: "maximus",
1432
+ enforce: "pre",
1433
+ async config(config, { command, isPreview }) {
1434
+ const root = resolve(config.root ?? process.cwd());
1435
+ const phase = command === "serve" && !isPreview ? "development" : "production";
1436
+ for (const [file, subject] of [["cloudflare.config.ts", "the Worker"], ["maximus.config.ts", "the application"]]) if (existsSync(join(root, file))) throw new TypeError(`maximus() configures ${subject}: move ${file} into maximus()'s options.`);
1437
+ checkWebAppBuild(root, config);
1438
+ worker = workerConfig(root, phase, options, project.api.prepare(root, phase));
1439
+ return await presets(config);
1440
+ },
1441
+ configEnvironment(name, config) {
1442
+ if (name !== "client" && config.build?.minify === void 0) return { build: { minify: true } };
1443
+ }
1444
+ };
1445
+ if (process.env.VITEST) return [
1446
+ configure,
1447
+ project,
1448
+ testing()
1449
+ ];
1450
+ const customize = () => worker;
1451
+ return [
1452
+ configure,
1453
+ project,
1454
+ ...cloudflare({ config: customize })
1455
+ ];
1456
+ }
1457
+ /** The path of this package's stand-in for `cloudflare:workers`, with this extension. */
1458
+ function workersStandIn(extension) {
1459
+ return fileURLToPath(new URL(`cloudflare-workers.${extension}`, import.meta.url));
1460
+ }
1461
+ /**
1462
+ * What a project's tests run with in Node: `cloudflare:workers` resolves to this package's stand-in, whose
1463
+ * entrypoint and Durable Object base classes keep the context and bindings a test constructs them with.
1464
+ * Maximus's own modules are inlined, so the generated Worker resolves the stand-in too.
1465
+ */
1466
+ function testing() {
1467
+ const workers = existsSync(workersStandIn("js")) ? workersStandIn("js") : workersStandIn("ts");
1468
+ return {
1469
+ name: "maximus:test",
1470
+ config: () => ({
1471
+ resolve: { alias: { "cloudflare:workers": workers } },
1472
+ test: { server: { deps: { inline: [/@arbol-ai\/maximus/] } } }
1473
+ })
1474
+ };
1475
+ }
1476
+
1477
+ export { auth0, cloudflareAccess, maximus };