@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,83 @@
1
+ import { n as createRpcOpenApi } from "./openapi-CV0KmJpS.js";
2
+ import { t as prepareConfiguredProject } from "./prepare-configured-Cithjf80.js";
3
+ import { t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+
7
+ // src/tooling/internal/openapi-file.ts
8
+ /**
9
+ * `maximus openapi`: the OpenAPI documents of a project's Worker, as files beside its sources. The HTTP
10
+ * document, the one the Worker serves, is the contract the project's clients are generated from; the RPC
11
+ * document, of the operations it serves over native RPC, is the one other services type their bindings from.
12
+ * `--check` keeps both current in CI.
13
+ */
14
+ /** The file `maximus openapi` writes the HTTP document to unless `--out` names another, at the project's root. */
15
+ const OPENAPI_FILE = "openapi.json";
16
+ /** The path of this package's stand-in for `cloudflare:workers`: built, or its source in this repository. */
17
+ function workersStandIn() {
18
+ const own = packageDirectory();
19
+ const built = join(own, "dist/vite/cloudflare-workers.js");
20
+ return existsSync(built) ? built : join(own, "src/vite/cloudflare-workers.ts");
21
+ }
22
+ /**
23
+ * The documents of the project's Worker: the HTTP one it serves at `<basePath>/openapi.json`, and the RPC one
24
+ * of its application. The project is prepared for production, as a build is, and its generated modules run in
25
+ * Node, with `cloudflare:workers` resolved to the stand-in its tests use.
26
+ */
27
+ async function projectDocuments(directory) {
28
+ const root = resolve(directory);
29
+ await prepareConfiguredProject(root, "production");
30
+ const { runnerImport } = await import("vite");
31
+ const options = {
32
+ root,
33
+ configFile: false,
34
+ logLevel: "silent",
35
+ resolve: { alias: { "cloudflare:workers": workersStandIn() } }
36
+ };
37
+ const { module: config } = await runnerImport(join(root, ".maximus/config.ts"), options);
38
+ const { module: http } = await runnerImport(join(root, ".maximus/http.ts"), options);
39
+ const { module: application } = await runnerImport(join(root, ".maximus/app.ts"), options);
40
+ const response = await http.handler(new Request(`http://localhost${config.worker.http?.basePath ?? ""}/openapi.json`), {});
41
+ if (!response.ok) throw new Error(`The Worker answered its OpenAPI document with ${response.status}.`);
42
+ return {
43
+ http: await response.json(),
44
+ rpc: createRpcOpenApi(application.app)
45
+ };
46
+ }
47
+ /** How many operations a document lists, across its paths. */
48
+ function operationCount(document) {
49
+ const paths = document.paths ?? {};
50
+ return Object.values(paths).reduce((count, methods) => count + Object.keys(methods).length, 0);
51
+ }
52
+ /** Writes a document to a file as JSON with two-space indentation, unless `check` asks only whether it differs. */
53
+ function writeDocument(file, document, check) {
54
+ const text = `${JSON.stringify(document, null, 2)}\n`;
55
+ const changed = !existsSync(file) || readFileSync(file, "utf-8") !== text;
56
+ if (changed && !check) {
57
+ mkdirSync(dirname(file), { recursive: true });
58
+ writeFileSync(file, text);
59
+ }
60
+ return {
61
+ file,
62
+ operations: operationCount(document),
63
+ changed
64
+ };
65
+ }
66
+ /**
67
+ * Writes the documents of the project's Worker: the HTTP one to `out`, `openapi.json` at its root by default,
68
+ * and, when an operation declares `rpc`, the RPC one beside it, `openapi.rpc.json`. With `check`, writes
69
+ * nothing and answers whether each file differs.
70
+ */
71
+ async function writeOpenApi(directory, { out = OPENAPI_FILE, check = false } = {}) {
72
+ const documents = await projectDocuments(directory);
73
+ const file = resolve(directory, out);
74
+ const written = writeDocument(file, documents.http, check);
75
+ if (!operationCount(documents.rpc)) return written;
76
+ const rpcFile = file.endsWith(".json") ? `${file.slice(0, -5)}.rpc.json` : `${file}.rpc.json`;
77
+ return {
78
+ ...written,
79
+ rpc: writeDocument(rpcFile, documents.rpc, check)
80
+ };
81
+ }
82
+
83
+ export { writeOpenApi };
@@ -0,0 +1,14 @@
1
+ import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-_h7xwgPC.js";
2
+
3
+ // src/project/pages.ts
4
+ /**
5
+ * Refuses a malformed page path, and one the Worker answers otherwise: the API's base path and below it, its
6
+ * discovery and liveness paths, versioned operation paths, `/.well-known`, a plain route, a mount or a
7
+ * transport.
8
+ */
9
+ function checkPagePaths(paths, tokens, neighbors) {
10
+ const native = nativePaths(tokens, neighbors.http ?? {});
11
+ for (const path of paths) if (!/^\/(?:[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*)?$/.test(path) || path.split("/").some((segment) => segment === "." || segment === "..") || native.reserved.has(path) || native.base && ownsPrefix(native.base, path) || VERSIONED_PATH.test(path) || ownsPrefix("/.well-known", path) || Object.hasOwn(neighbors.routes ?? {}, path) || Object.keys(neighbors.http?.mounts ?? {}).some((prefix) => ownsPrefix(prefix, path)) || neighbors.transports?.some((transport) => ownsPrefix(transport.path, path))) throw new TypeError(`Page path is reserved or malformed: ${path}. Move the API with http.basePath.`);
12
+ }
13
+
14
+ export { checkPagePaths as t };
@@ -0,0 +1,3 @@
1
+ import { t as prepareConfiguredProject } from "./prepare-configured-Cithjf80.js";
2
+
3
+ export { prepareConfiguredProject };
@@ -0,0 +1,52 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+
4
+ // src/tooling/internal/prepare-configured.ts
5
+ /**
6
+ * `maximus prepare`: the project is prepared by the plugin its `vite.config.ts` configures, as a build would,
7
+ * so the command and the build generate the same modules.
8
+ */
9
+ /** A configuration's plugins, as Vite flattens them from nested lists and promises. */
10
+ async function pluginsOf(option) {
11
+ const resolved = await option;
12
+ if (!Array.isArray(resolved)) return [resolved];
13
+ return (await Promise.all(resolved.map(pluginsOf))).flat();
14
+ }
15
+ /** The configuration files Vite reads, in the order it looks for them: the first it finds is the one it loads. */
16
+ const VITE_CONFIGS = [
17
+ "vite.config.js",
18
+ "vite.config.mjs",
19
+ "vite.config.ts",
20
+ "vite.config.cjs",
21
+ "vite.config.mts",
22
+ "vite.config.cts"
23
+ ];
24
+ /** The API of the Maximus plugin among a configuration's plugins, if it has one. */
25
+ function projectApi(plugin) {
26
+ if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === "maximus-project") {
27
+ const api = "api" in plugin ? plugin.api : void 0;
28
+ if (api && typeof api === "object" && "prepare" in api && typeof api.prepare === "function") return api;
29
+ }
30
+ }
31
+ /**
32
+ * Prepares the project at `directory`: loads its `vite.config.ts` with Vite, which evaluates it as every
33
+ * `vp` command does, and prepares it through the `maximus()` plugin it configures. Application modules are
34
+ * only parsed.
35
+ */
36
+ async function prepareConfiguredProject(directory, mode = "production") {
37
+ const root = resolve(directory);
38
+ const viteConfig = VITE_CONFIGS.find((name) => existsSync(join(root, name)));
39
+ if (!viteConfig) throw new TypeError("Configure the project in vite.config.ts with maximus() from @arbol-ai/maximus/vite.");
40
+ const { loadConfigFromFile } = await import("vite");
41
+ const loaded = await loadConfigFromFile({
42
+ command: "build",
43
+ mode
44
+ }, join(root, viteConfig), root);
45
+ for (const plugin of await pluginsOf(loaded?.config.plugins)) {
46
+ const api = projectApi(plugin);
47
+ if (api) return api.prepare(root, mode);
48
+ }
49
+ throw new TypeError(`${viteConfig} configures no maximus() plugin from @arbol-ai/maximus/vite.`);
50
+ }
51
+
52
+ export { prepareConfiguredProject as t };
@@ -0,0 +1,130 @@
1
+ import { existsSync, lstatSync, readdirSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+
4
+ // src/tooling/internal/project-files.ts
5
+ /**
6
+ * Deterministic module discovery: only ordinary source files inside the convention directories are read, and
7
+ * the project's commands write through no folder linked from elsewhere.
8
+ */
9
+ /** The convention directories prepare discovers modules in; bindings and triggers stay in vite.config.ts. */
10
+ const PROJECT_DIRECTORIES = [
11
+ "routes",
12
+ "mcp",
13
+ "pages",
14
+ "middleware",
15
+ "crons",
16
+ "queues",
17
+ "email",
18
+ "durable-objects"
19
+ ];
20
+ /** A full recipient, `local@domain.tld`: what an email module is named after. */
21
+ const RECIPIENT = /^[^@/]+@[^@/]+\.[^@./]+$/;
22
+ /** The convention directories whose module names have no dots, so `.dev` and `.prod` alone name a mode. */
23
+ const UNDOTTED = /* @__PURE__ */ new Set([
24
+ "middleware",
25
+ "crons",
26
+ "queues"
27
+ ]);
28
+ /**
29
+ * Whether a `.dev`, `.prod`, `.test` or `.spec` ending is the last label of an email module's recipient,
30
+ * `help@example.dev`, rather than a mode or test suffix: only what precedes it is no recipient.
31
+ */
32
+ function endsRecipient(directory, name, rest) {
33
+ return directory === "email" && RECIPIENT.test(name) && !RECIPIENT.test(rest);
34
+ }
35
+ /** Sort by code units so generated imports are identical on every locale and platform. */
36
+ function compareNames(a, b) {
37
+ return a < b ? -1 : Number(a > b);
38
+ }
39
+ /**
40
+ * Refuses `folder`, or a folder of the project on the way to it, that is a symlink: what a command writes
41
+ * below it would land wherever the link leads. The project's root itself may be reached through one.
42
+ */
43
+ function checkProjectFolder(root, folder) {
44
+ let current = root;
45
+ for (const segment of relative(root, folder).split(sep).filter(Boolean)) {
46
+ current = join(current, segment);
47
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) throw new TypeError(`Project directory cannot be a symlink: ${relative(root, current)}`);
48
+ }
49
+ }
50
+ /** Discover without following symlinks or importing user code into the build host. */
51
+ function projectFiles(root, directory, mode) {
52
+ const folder = resolve(root, directory);
53
+ if (!existsSync(folder)) return [];
54
+ if (lstatSync(folder).isSymbolicLink()) throw new TypeError(`Project directory cannot be a symlink: ${directory}`);
55
+ const files = [];
56
+ function visit(current) {
57
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
58
+ if (entry.name.startsWith(".") || entry.name.startsWith("_") && !(directory === "email" && entry.name.startsWith("_default."))) continue;
59
+ const file = join(current, entry.name);
60
+ if (entry.isSymbolicLink()) throw new TypeError(`Project modules cannot be symlinks: ${relative(root, file)}`);
61
+ if (entry.isDirectory()) visit(file);
62
+ else if (entry.isFile() && /\.(?:[cm]?ts|tsx|[cm]?js|jsx)$/.test(entry.name)) {
63
+ const stem = relative(folder, file).split(sep).join("/").replace(/\.[^.]+$/, "");
64
+ const suffix = /\.(dev|prod)$/.exec(stem);
65
+ const environment = suffix && !endsRecipient(directory, stem, stem.slice(0, suffix.index)) ? suffix : void 0;
66
+ const name = environment ? stem.slice(0, environment.index) : stem;
67
+ const marker = /\.(d|test|spec)$/.exec(name);
68
+ if (marker && (marker[1] === "d" || !endsRecipient(directory, name, name.slice(0, marker.index)))) continue;
69
+ const own = name.slice(name.lastIndexOf("/") + 1);
70
+ if (directory === "email" && own !== "_default" && !RECIPIENT.test(own)) throw new TypeError(`Name an email module after the recipient it handles, such as help@example.com, or _default: ${relative(root, file)}`);
71
+ if (UNDOTTED.has(directory) && own.includes(".")) throw new TypeError(`Name a module without dots but its mode suffix, .dev or .prod: ${relative(root, file)}`);
72
+ if (environment && (environment[1] === "dev" ? mode !== "development" : mode !== "production")) continue;
73
+ files.push({
74
+ file,
75
+ name
76
+ });
77
+ }
78
+ }
79
+ }
80
+ visit(folder);
81
+ files.sort((a, b) => compareNames(a.file, b.file));
82
+ return files;
83
+ }
84
+ /**
85
+ * Convert groups, index files and dynamic segments into a native Maximus path, or into the React Router path
86
+ * of a web app's page (`app/routes/tasks/[taskId].tsx` is `/tasks/:taskId`).
87
+ */
88
+ function projectPath(name, kind) {
89
+ const segments = name.split("/").filter((segment) => !/^\([a-zA-Z0-9_-]+\)$/.test(segment));
90
+ if (segments.at(-1) === "index") segments.pop();
91
+ const path = `/${segments.map((segment) => {
92
+ const parameter = /^\[([a-zA-Z][a-zA-Z0-9_]*)\]$/.exec(segment)?.[1];
93
+ if (parameter && kind !== "pages") return kind === "routes" ? `{${parameter}}` : `:${parameter}`;
94
+ if (!/^[a-zA-Z0-9_-]+$/.test(segment)) throw new TypeError(`Unsupported ${kind} segment: ${segment}. Pages use fixed paths; operations and app pages support [parameter].`);
95
+ return segment;
96
+ }).join("/")}`;
97
+ if (kind === "routes" && !/^\/v[1-9][0-9]*\/.+/.test(path)) throw new TypeError(`Operation file must live below routes/v1/ (or another version): ${name}`);
98
+ return path;
99
+ }
100
+ /** A route path's shape: `/v1/tasks/{taskId}` and `/v1/tasks/{id}` match the same paths. */
101
+ function routeShape(path) {
102
+ return path.replaceAll(/\{[^}]+\}/g, "{}");
103
+ }
104
+ /**
105
+ * The files of a web app's `public/`, which its build copies to the root as they are: the paths the Worker
106
+ * serves them at, such as `/favicon.svg`. Dotfiles stay out; symlinks and other names are refused.
107
+ */
108
+ function publicFiles(root) {
109
+ const folder = resolve(root, "public");
110
+ if (!existsSync(folder)) return [];
111
+ if (lstatSync(folder).isSymbolicLink()) throw new TypeError("Project directory cannot be a symlink: public");
112
+ const paths = [];
113
+ function visit(current) {
114
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
115
+ const file = join(current, entry.name);
116
+ if (entry.name.startsWith(".")) continue;
117
+ if (entry.isSymbolicLink()) throw new TypeError(`Public files cannot be symlinks: ${relative(root, file)}`);
118
+ if (entry.isDirectory()) visit(file);
119
+ else if (entry.isFile()) {
120
+ const path = `/${relative(folder, file).split(sep).join("/")}`;
121
+ if (!/^(?:\/[a-zA-Z0-9._~-]+)+$/.test(path)) throw new TypeError(`Name public files with letters, digits, dots, underscores, tildes and hyphens: ${relative(root, file)}`);
122
+ paths.push(path);
123
+ }
124
+ }
125
+ }
126
+ visit(folder);
127
+ return paths.toSorted(compareNames);
128
+ }
129
+
130
+ export { projectPath as a, projectFiles as i, checkProjectFolder as n, publicFiles as o, compareNames as r, routeShape as s, PROJECT_DIRECTORIES as t };
@@ -0,0 +1,40 @@
1
+ import { t as isRecord } from "./record-DQUDTpEA.js";
2
+
3
+ // src/internal/query-kind.ts
4
+ /**
5
+ * How an input field travels in a query string: the one rule the HTTP decoder reads a GET's query by and a
6
+ * gateway's generated clients write it by, so the two agree without coordinating. Browser-safe: no runtime,
7
+ * no schema library.
8
+ */
9
+ /** A schema with its `$ref`s followed through `resolve`, up to 16 deep; undefined when one cannot be. */
10
+ function resolved(schema, resolve) {
11
+ let value = schema;
12
+ for (let depth = 0; isRecord(value) && typeof value.$ref === "string"; depth += 1) {
13
+ if (!resolve || depth > 16) return;
14
+ value = resolve(value.$ref);
15
+ }
16
+ return value;
17
+ }
18
+ /**
19
+ * How one input field travels in a query string, its `$ref`s followed through `resolve`, or null when it
20
+ * cannot: objects and nested lists do not. Lists are comma separated; a `null` alternative is not
21
+ * expressible and is ignored.
22
+ */
23
+ function queryKind(schema, resolve) {
24
+ const value = resolved(schema, resolve);
25
+ if (!isRecord(value)) return null;
26
+ let branches = null;
27
+ if (Array.isArray(value.anyOf)) branches = value.anyOf;
28
+ else if (Array.isArray(value.oneOf)) branches = value.oneOf;
29
+ if (branches) {
30
+ const kinds = branches.filter((branch) => !(isRecord(branch) && branch.type === "null")).map((branch) => queryKind(branch, resolve));
31
+ if (!kinds.length || kinds.includes(null)) return null;
32
+ if (kinds.includes("list")) return kinds.every((kind) => kind === "list" || kind === "string") ? "list" : null;
33
+ return kinds.every((kind) => kind === kinds[0]) ? kinds[0] ?? null : null;
34
+ }
35
+ if (value.type === "array") return queryKind(value.items, resolve) === "string" ? "list" : null;
36
+ if (value.type === "string" || typeof value.const === "string" || Array.isArray(value.enum) && value.enum.every((entry) => typeof entry === "string")) return "string";
37
+ return value.type === "integer" || value.type === "number" || value.type === "boolean" ? value.type : null;
38
+ }
39
+
40
+ export { queryKind as t };
@@ -0,0 +1,10 @@
1
+ // src/internal/record.ts
2
+ /**
3
+ * The plain-record guard the readers of untrusted values share.
4
+ */
5
+ /** Whether an untrusted value is an object with fields: neither null nor an array. */
6
+ function isRecord(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8
+ }
9
+
10
+ export { isRecord as t };
@@ -0,0 +1,56 @@
1
+ import { t as isRecord } from "./record-DQUDTpEA.js";
2
+
3
+ // src/internal/http-routes.ts
4
+ /**
5
+ * The parameter's schema in an object input, or in each member of a union. Every one must declare the
6
+ * parameter as a required string field, or this throws a TypeError.
7
+ */
8
+ function pathParameterSchemas(input, parameter) {
9
+ if (input.type === "object") {
10
+ const schema = input.properties?.[parameter];
11
+ if (!schema || schema.type !== "string" || !input.required?.includes(parameter)) throw new TypeError(`Path parameter "${parameter}" must be a required string input field.`);
12
+ return [schema];
13
+ }
14
+ if (Array.isArray(input.anyOf) && input.anyOf.length > 0) return input.anyOf.flatMap((schema) => pathParameterSchemas(schema, parameter));
15
+ throw new TypeError("Path parameters require object input contracts.");
16
+ }
17
+ /**
18
+ * The group a route's path names, which OpenAPI publishes as its tag: its first fixed segment after the
19
+ * version, in words, such as `Notes` for `/v1/notes/{noteId}` and `Task lists` for `/v1/task-lists`;
20
+ * undefined when only parameters follow the version.
21
+ */
22
+ function routeGroup(path) {
23
+ const segments = path.split("/").filter(Boolean);
24
+ const segment = (/^v[1-9][0-9]*$/.test(segments[0] ?? "") ? segments.slice(1) : segments).find((part) => !part.startsWith("{"));
25
+ if (segment === void 0) return;
26
+ const words = segment.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s_-]+/).filter(Boolean).join(" ").toLowerCase();
27
+ return words.charAt(0).toUpperCase() + words.slice(1);
28
+ }
29
+
30
+ // src/result.ts
31
+ /** A success carrying `value`. */
32
+ function ok(value) {
33
+ return {
34
+ ok: true,
35
+ value
36
+ };
37
+ }
38
+ /** A failure carrying `error`, usually `catalog.someFailure.create()`. */
39
+ function err(error) {
40
+ return {
41
+ ok: false,
42
+ error
43
+ };
44
+ }
45
+ /**
46
+ * Whether an untrusted answer (a Service Binding's, a stored one) is a Maximus Result: a success with
47
+ * its value, or a failure with a well-formed error. Anything else is not an answer at all.
48
+ */
49
+ function isResult(value) {
50
+ if (!isRecord(value)) return false;
51
+ if (value.ok === true) return "value" in value;
52
+ const { error } = value;
53
+ return value.ok === false && isRecord(error) && typeof error.code === "string" && typeof error.message === "string" && typeof error.retryable === "boolean" && isRecord(error.data);
54
+ }
55
+
56
+ export { routeGroup as a, pathParameterSchemas as i, isResult as n, ok as r, err as t };
@@ -1,10 +1,11 @@
1
- import { r as parseInput } from "./validation-r-sgmsqb.js";
2
- import { r as isRequestId } from "./correlation-BEkcFFGT.js";
3
- import { i as standardErrors } from "./errors-D7zG9kx9.js";
4
- import { f as ok, n as PrincipalSchema, u as err } from "./define-app-DvD_1jUE.js";
5
- import { r as createHttpHandler } from "./src-N3oyx5QF.js";
6
- import { a as telemetryEnabled, r as recordExecution, s as withTelemetry } from "./telemetry-BTwB68m5.js";
7
- import { t as executeOperation } from "./execution-kVUJPy1A.js";
1
+ import { r as parseInput } from "./validation-fTohBT6R.js";
2
+ import { r as isRequestId } from "./correlation-4b23a-a4.js";
3
+ import { i as standardErrors } from "./errors-WfyKhiyk.js";
4
+ import { r as ok, t as err } from "./result-CKgZHrnj.js";
5
+ import { y as PrincipalSchema } from "./openapi-CV0KmJpS.js";
6
+ import { r as createHttpHandler } from "./src--HZrH1U9.js";
7
+ import { a as telemetryEnabled, i as reportUnexpected, r as recordExecution, s as withTelemetry } from "./telemetry-C3LfZcOB.js";
8
+ import { t as executeOperation } from "./execution-CfZEx_JP.js";
8
9
  import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
9
10
 
10
11
  // src/workers/assets.ts
@@ -14,16 +15,24 @@ import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
14
15
  */
15
16
  /** An absolute asset path of unreserved characters, without a query or a fragment. */
16
17
  const ASSET_PATH = /^\/(?:[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*)?$/;
18
+ /** Whether a path is an absolute asset path: unreserved characters, nothing encoded, no dot segments. */
19
+ function isAssetPath(path) {
20
+ return ASSET_PATH.test(path) && !path.split("/").some((segment) => segment === "." || segment === "..");
21
+ }
17
22
  /** The path, refused at construction when it is not an absolute asset path or has dot segments. */
18
23
  function requireAssetPath(path) {
19
- 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}`);
24
+ if (!isAssetPath(path)) throw new TypeError(`Asset path must be absolute without query, fragments or dot segments: ${path}`);
20
25
  return path;
21
26
  }
22
27
  /** Whether a binding can fetch assets. */
23
28
  function isAssetBinding(value) {
24
29
  return typeof value === "object" && value !== null && "fetch" in value && typeof value.fetch === "function";
25
30
  }
26
- /** Compile the explicit build policy once; core HTTP retains ownership of API and transport misses. */
31
+ /**
32
+ * The route that serves a web app's build by `options`, which `createWorker` installs as the HTTP fallback,
33
+ * so it answers only paths no operation, transport or other route claims. Construction throws a TypeError
34
+ * for a path that is not an absolute asset path, a global or sticky pattern, or an immutable prefix of `/`.
35
+ */
27
36
  function createAssetHandler(options) {
28
37
  const bindingName = options.binding;
29
38
  const pages = new Set(options.pages?.paths.map(requireAssetPath));
@@ -44,7 +53,7 @@ function createAssetHandler(options) {
44
53
  const url = new URL(request.url);
45
54
  const isPage = pages.has(url.pathname) || patterns.some((pattern) => pattern.test(url.pathname));
46
55
  const isFile = files.has(url.pathname);
47
- const isImmutable = immutablePrefixes.some((prefix) => url.pathname === prefix || url.pathname.startsWith(`${prefix}/`));
56
+ const isImmutable = isAssetPath(url.pathname) && immutablePrefixes.some((prefix) => url.pathname === prefix || url.pathname.startsWith(`${prefix}/`));
48
57
  const binding = env[bindingName];
49
58
  if (!(isPage || isFile || isImmutable)) {
50
59
  if (options.development && isAssetBinding(binding)) return binding.fetch(request);
@@ -96,6 +105,7 @@ function instrumentMethods(implementation, runtime, telemetry) {
96
105
  methods.add(name);
97
106
  Object.defineProperty(Observed.prototype, name, {
98
107
  configurable: true,
108
+ writable: true,
99
109
  value(...args) {
100
110
  return withTelemetry(telemetry, environments.get(this), () => Reflect.apply(method, this, args));
101
111
  }
@@ -119,12 +129,11 @@ function instrumentDurableObject(implementation, telemetry) {
119
129
  * Annotates the active Workers trace span with the service, the operation and the request id.
120
130
  */
121
131
  /**
122
- * Call inside the invocation, after authenticating the native principal. Service
123
- * and operation are developer constants. Adds correlation to the existing native
124
- * span; does not mint/fake trace ids or enable exporters. No raw exception is
125
- * recorded on the native span.
126
- * Older workerd versions do not expose getActiveSpan. Annotation is best effort:
127
- * an unavailable or failing telemetry API must never change the business result.
132
+ * Sets the service, the operation and, when it is a valid request id, the request id as attributes of the
133
+ * active Workers trace span. Call it inside the invocation once the principal is verified, with constant
134
+ * service and operation names. It starts no span, creates no trace id, enables no exporter and records no
135
+ * error. A runtime without `tracing.getActiveSpan` is left alone, and a failing tracing API never changes the
136
+ * result.
128
137
  */
129
138
  function annotateInvocation(service, operation, requestId, attributeNames = {
130
139
  service: "service.name",
@@ -145,7 +154,13 @@ function annotateInvocation(service, operation, requestId, attributeNames = {
145
154
  * Reads one organization's credential from its own store, such as a Durable Object per organization, and
146
155
  * checks that it belongs to that organization.
147
156
  */
148
- /** Typed organization credential preparation for one derived operation group. */
157
+ /**
158
+ * Reads the caller's organization credential, for a `.derive()` that prepares it: `accounts.getByName`
159
+ * addresses the organization's own store by its id (a Durable Object namespace, for example), whose
160
+ * `readCredential` answers the credential. A failure it answers is returned as it is; a credential that does
161
+ * not match `schema` or names another `organizationId` answers `INTERNAL_ERROR`. Otherwise it answers
162
+ * `{ credential }`.
163
+ */
149
164
  async function credentials(options) {
150
165
  const { organizationId } = options.principal;
151
166
  const result = await options.accounts.getByName(organizationId).readCredential(organizationId);
@@ -163,7 +178,9 @@ async function credentials(options) {
163
178
  /**
164
179
  * Turns an application into a Cloudflare Worker: `handler` (export it as default) serves HTTP and the other
165
180
  * handlers you pass; `entrypoint` (export it by name) serves every operation that declares `rpc` to the
166
- * Workers whose Service Binding names an allowed `caller`.
181
+ * Workers whose Service Binding names an allowed `caller`. An RPC call whose binding's props are anything but
182
+ * `{ caller }` with an allowed caller, or whose principal does not match `PrincipalSchema`, answers
183
+ * `UNAUTHORIZED`; an admitted one runs through the shared execution path without `authority`.
167
184
  */
168
185
  function createWorker(application, options = {}) {
169
186
  if (options.assets && options.http?.fallback) throw new TypeError("Worker assets and an HTTP fallback cannot both own unmatched paths.");
@@ -203,14 +220,21 @@ function createWorker(application, options = {}) {
203
220
  }
204
221
  const service = (implementation) => instrumentService(implementation, manifest.telemetry);
205
222
  const entrypoint = service(Entrypoint);
206
- const handler = {
207
- ...options.handlers,
208
- fetch
209
- };
210
- const scheduledHandler = options.handlers?.scheduled;
211
- if (scheduledHandler) handler.scheduled = function scheduled(controller, env, ctx) {
212
- return withTelemetry(manifest.telemetry, env, () => scheduledHandler.call(this, controller, env, ctx));
213
- };
223
+ const handler = { fetch };
224
+ for (const [event, implementation] of Object.entries(options.handlers ?? {})) {
225
+ if (typeof implementation !== "function") continue;
226
+ const run = implementation;
227
+ handler[event] = function handle(payload, env, context) {
228
+ return withTelemetry(manifest.telemetry, env, async () => {
229
+ try {
230
+ return await run.call(this, payload, env, context);
231
+ } catch (error) {
232
+ reportUnexpected(error, event);
233
+ throw error;
234
+ }
235
+ });
236
+ };
237
+ }
214
238
  return {
215
239
  handler,
216
240
  entrypoint,
@@ -0,0 +1,3 @@
1
+ import { n as scaffold, t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
2
+
3
+ export { scaffold };