@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,256 @@
1
+ # Routes and tools
2
+
3
+ ## A route is a file
4
+
5
+ A file of `routes/` declares one operation; its name gives its path and method, below the API's base path,
6
+ `/api` by default:
7
+
8
+ | File | Serves |
9
+ | ------------------------------------------ | ------------------------------------- |
10
+ | `routes/v1/notes.post.ts` | `POST /api/v1/notes` |
11
+ | `routes/v1/notes/index.get.ts` | `GET /api/v1/notes` |
12
+ | `routes/v1/notes/[noteId].get.ts` | `GET /api/v1/notes/{noteId}` |
13
+ | `routes/v1/notes/[noteId]/archive.post.ts` | `POST /api/v1/notes/{noteId}/archive` |
14
+
15
+ - The method is `get`, `post`, `put`, `patch` or `delete`, before the extension. Every route lives below a
16
+ version folder, `routes/v1/`.
17
+ - `[name]` is a parameter that fills a whole segment; a folder in parentheses, `(admin)`, groups files
18
+ without changing the path.
19
+ - `<name>.dev.ts` exists in development alone (`vp dev` and `vp test`) and `<name>.prod.ts` in builds alone. Files that start with `_`
20
+ or `.`, and `*.test.ts`, `*.spec.ts` and `*.d.ts` files, are not routes.
21
+ - `prepare` refuses two files for one method whose paths differ only in a parameter's name, and a file
22
+ without a method.
23
+
24
+ `bunx maximus gen route post /v1/notes` writes the file with a placeholder handler; `--tool <snake_name>`
25
+ makes it an MCP tool too.
26
+
27
+ ```ts
28
+ // routes/v1/notes/[noteId].get.ts
29
+ import { defineHandler, UuidSchema } from '@arbol-ai/maximus';
30
+
31
+ import { NoteSchema } from '#src/notes.ts';
32
+
33
+ /** GET /api/v1/notes/{noteId}, also the MCP tool get_note: one note of the caller's organization. */
34
+ export default defineHandler(
35
+ async ({ input, notes, fail }) => {
36
+ const note = await notes.find(input.noteId);
37
+ if (!note) {
38
+ return fail('NOTE_NOT_FOUND');
39
+ }
40
+ return note;
41
+ },
42
+ {
43
+ description: 'Read one note of the organization by its id.',
44
+ input: { noteId: UuidSchema },
45
+ output: NoteSchema,
46
+ failures: ['NOTE_NOT_FOUND'],
47
+ mcp: { name: 'get_note' },
48
+ }
49
+ );
50
+ ```
51
+
52
+ ## What a route derives
53
+
54
+ What the contract leaves out, binding derives from the method and the path:
55
+
56
+ | Field | Derived | For the file above |
57
+ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
58
+ | Operation name | What the method does to what the path names: the `operationId` and the RPC method. `listNotes`, `createNote`, `archiveNote`. | `getNote` |
59
+ | `effect` | `GET` reads, `DELETE` deletes, every other method writes. | `read` |
60
+ | `scope` | `<namespace>:<resource>:read` for a read, `:write` otherwise; the resource is the first fixed segment after the version, in kebab-case. | `notes:notes:read` |
61
+ | `title` | The operation's words as a sentence: the OpenAPI `summary` and the MCP tool's title. | `Get a note` |
62
+ | `group` | The first fixed segment after the version, in words: the OpenAPI tag. | `Notes` |
63
+ | `mcp.idempotent` | `true` for `GET`, `PUT` and `DELETE`. | `true` |
64
+
65
+ A route whose path has no fixed segment after the version must declare its `scope`. A `DELETE` never declares
66
+ `effect: 'read'`, and only a read may use `GET`.
67
+
68
+ ## The handler
69
+
70
+ `defineHandler(handler, contract)` takes the handler first. The handler receives one object:
71
+
72
+ - `input`: decoded and checked against the contract's `input`, path parameters included.
73
+ - `fail(code, data?)`: answers a failure of the catalog; only the route's `failures` and the standard codes
74
+ an operation answers itself type-check, not `NOT_FOUND`, `HTTP_METHOD_NOT_ALLOWED`, `UNAUTHORIZED`,
75
+ `REQUEST_TOO_LARGE` or `UNSUPPORTED_MEDIA_TYPE`.
76
+ - `principal`: `{ actorId, actorKind, organizationId, requestId }`, the verified caller.
77
+ - `env`: the Worker's bindings.
78
+ - `authority`: the verified token's `{ surface, scopes, client, token }`, on HTTP and MCP calls whose token
79
+ names a client; absent over RPC.
80
+ - `background`: `waitUntil` for best-effort work after the answer.
81
+ - `body`: on a byte route, the body's reader.
82
+ - Whatever `context.ts` returns.
83
+
84
+ It answers its output, or `fail(code)`, directly or as a promise. A route without `output` answers the empty
85
+ object, and its handler may return nothing.
86
+
87
+ ## The contract
88
+
89
+ | Field | Meaning |
90
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `input`, `output` | A schema, or the fields of a strict object: `{ noteId: UuidSchema }`. Without `input`, the route takes none. |
92
+ | `description` | What it does, for people and agents. Required on a route that is an MCP tool. |
93
+ | `title`, `group` | The OpenAPI summary and tag. |
94
+ | `operationId` | Its name instead of the derived one: the `operationId` and the RPC method. |
95
+ | `scope`, `scopeMatch` | One scope or several, `<namespace>:<resource>:<action>`; several admit any one unless `scopeMatch: 'all'`. |
96
+ | `conditionalScopes` | Scopes the handler checks itself against `authority.scopes`; a call without `authority`, such as over RPC, is refused with `FORBIDDEN`. |
97
+ | `effect` | `read`, `write` or `delete`. It shapes the default scope and MCP hints; it never authorizes. |
98
+ | `failures` | The domain codes it may answer. Any other answers `INTERNAL_ERROR` and is reported. |
99
+ | `actorKinds` | `['user']`, `['service']` or both; every kind when omitted. |
100
+ | `visibility` | `'internal'` keeps it out of the public OpenAPI document and the discovery metadata; it stays routed and scope-checked. |
101
+ | `http` | `successStatus` (200, 201 or 202), `body: 'bytes'`, `headers`, `response: 'attachment'`. |
102
+ | `mcp` | `{ name, idempotent?, openWorld? }`: also an MCP tool. `openWorld` is `true` unless declared. |
103
+ | `rpc` | `true` for every caller in `rpc.callers`, or `{ callers }` for some of them. |
104
+ | `maxBodyBytes`, `maxOutputBytes` | Its own limits, up to 16 MiB; the application's (32 KiB and 256 KiB) otherwise. |
105
+
106
+ A field no operation has does not compile, and `.build()` refuses it. A contract kept in a `const` keeps
107
+ its types with `satisfies HandlerOptions`.
108
+
109
+ ## Input
110
+
111
+ - **Path parameters** are required string fields of the input. The query string or the body may not repeat
112
+ them.
113
+ - **A `GET`** reads its input from the query string: each field as its schema's kind (integer, number,
114
+ boolean, a comma-separated list of strings, else a string). A repeated key is refused, and so is a field
115
+ named `__proto__`.
116
+ - **`POST`, `PUT`, `PATCH` and `DELETE`** read a JSON body sent as `application/json`; another media type
117
+ answers `UNSUPPORTED_MEDIA_TYPE`. A `DELETE` without a body or `content-type` takes the empty input.
118
+ - A refused input answers `INVALID_INPUT`, with up to ten `{ path, message }` issues and never the value.
119
+
120
+ ## Schemas
121
+
122
+ Schemas are TypeBox's, imported as `t` from `@arbol-ai/maximus` (or `@arbol-ai/maximus/schemas`, which
123
+ browsers can import):
124
+
125
+ - Inputs and outputs are strict objects (`additionalProperties: false`) or unions of strict objects. Name a
126
+ shared entity with a PascalCase `$id`, one shape per name: `NoteSchema` with `$id: 'Note'`.
127
+ - The shared schemas: `UuidSchema`, `OrganizationIdSchema`, `EmailAddressSchema`, `PhoneNumberSchema`,
128
+ `HttpsUrlSchema`, `HexColorSchema`, `PostalAddressSchema`, `NamedReferenceSchema`, `SignedUrlSchema`,
129
+ `DeletedObjectSchema`, `EmptyInputSchema`.
130
+ - Absent values in an output are `t.Union([X, t.Null()])`: answer every field.
131
+ - Codecs from `@arbol-ai/maximus/schemas` (`normalizeSchema`, `transformSchema`, `refineSchema`,
132
+ `inspectSchema`, `pipeSchema`, `stripObject`) run only inside `inputSchema(…)`; `.build()` refuses an input
133
+ that uses them outside it. `defaultSchema` gives a field its default. A refinement's message reaches the
134
+ caller: never put a value in it.
135
+ - Read data that comes from outside the pipeline with `readSchema(schema, value)`, which throws on a value
136
+ that does not match, or `checkSchema(schema, value)`, which answers `{ success, data }` or
137
+ `{ success: false, error }`.
138
+
139
+ [Schemas and validation](https://github.com/getarbol/maximus/blob/main/docs/guides/schemas-and-validation.md)
140
+ covers codecs, query strings and named schemas.
141
+
142
+ ## Lists
143
+
144
+ A route that answers many items answers one page of them:
145
+
146
+ ```ts
147
+ // routes/v1/notes/index.get.ts
148
+ import { defineHandler, Page, PageQueryFields } from '@arbol-ai/maximus';
149
+
150
+ import { NoteSchema } from '#src/notes.ts';
151
+
152
+ /** GET /api/v1/notes: the organization's notes, a page at a time. */
153
+ export default defineHandler(
154
+ async ({ input, notes, fail }) => {
155
+ const page = await notes.list(input);
156
+ if (!page) {
157
+ return fail('INVALID_CURSOR');
158
+ }
159
+ return page;
160
+ },
161
+ {
162
+ description: "List the organization's notes, newest first. Pass pageInfo.nextCursor as cursor for more.",
163
+ input: PageQueryFields,
164
+ output: Page(NoteSchema, { $id: 'NotePage' }),
165
+ failures: ['INVALID_CURSOR'],
166
+ }
167
+ );
168
+ ```
169
+
170
+ `PageQueryFields` are `cursor`, `direction` (`forward` or `backward`) and `limit` (25 by default, at most
171
+ 100; `pageLimit({ maximum })` lowers it). The answer is `{ object: 'list', data, pageInfo }`, whose
172
+ `pageInfo` holds `hasNextPage`, `hasPreviousPage`, `nextCursor` and `previousCursor`. Spread the fields
173
+ beside a list's own filters: `{ ...PageQueryFields, text: t.String() }`.
174
+
175
+ ## Byte bodies and attachments
176
+
177
+ An upload declares `http: { body: 'bytes' }`. Its input comes from the path, the query string and the
178
+ headers its `http.headers` maps, and the handler reads the body when it has checked the request:
179
+
180
+ ```ts
181
+ async ({ input, body, documents }) => {
182
+ const upload = await body.read();
183
+ if (!upload.ok) {
184
+ return upload.error; // REQUEST_TOO_LARGE, UNSUPPORTED_MEDIA_TYPE or INVALID_INPUT
185
+ }
186
+ return documents.create(input.filename, input.contentType, upload.value);
187
+ },
188
+ // contract: http: { body: 'bytes', headers: { contentType: 'content-type' }, successStatus: 201 }
189
+ ```
190
+
191
+ A download declares `output: AttachmentOutputSchema` and `http: { response: 'attachment' }`, and answers
192
+ `{ body, contentType, filename, byteLength }`. Both are HTTP alone: never an MCP tool or an RPC method.
193
+
194
+ ## Tools only agents call
195
+
196
+ A file of `mcp/tools/`, named in kebab-case, default-exports `defineTool(handler, contract)`:
197
+
198
+ ```ts
199
+ // mcp/tools/search-notes.ts: the tool search_notes, operation searchNotes
200
+ import { defineTool, t } from '@arbol-ai/maximus';
201
+
202
+ import { NoteSchema } from '#src/notes.ts';
203
+
204
+ /** The most notes one search answers. */
205
+ const MAX_NOTES = 20;
206
+
207
+ /** The MCP tool search_notes, which no HTTP route serves: the newest notes that contain a text. */
208
+ export default defineTool(
209
+ async ({ input, notes }) => {
210
+ const matchingNotes = await notes.search(input.text, MAX_NOTES);
211
+ return { notes: matchingNotes };
212
+ },
213
+ {
214
+ description:
215
+ "Find the organization's notes whose title or body contains a text, newest first, at most twenty.",
216
+ effect: 'read',
217
+ input: { text: t.String({ minLength: 2, maxLength: 100 }) },
218
+ output: { notes: t.Array(NoteSchema) },
219
+ }
220
+ );
221
+ ```
222
+
223
+ A tool requires `description` and `effect`. Its default scope is `<namespace>:<file name>:read` for a read and
224
+ `:write` otherwise, it is idempotent only for a read unless `idempotent` says so, and it has no HTTP route.
225
+ `bunx maximus gen tool search-notes` writes the file.
226
+
227
+ ## Context and middleware
228
+
229
+ `context.ts` prepares what every handler receives, after admission:
230
+
231
+ ```ts
232
+ // context.ts
233
+ import { defineContext } from '@arbol-ai/maximus';
234
+
235
+ import { noteStore } from '#src/notes.ts';
236
+
237
+ /** What every handler receives besides its input: the caller's organization's notes. */
238
+ export default defineContext(({ env, principal }) => ({
239
+ notes: noteStore(env.NOTES, principal.organizationId),
240
+ }));
241
+ ```
242
+
243
+ A file of `middleware/` default-exports one of two declarations from `@arbol-ai/maximus/config`, and the
244
+ files run in the order of their names:
245
+
246
+ - `defineMiddleware((request, env, context, proceed) => …)` wraps every request before its token is read. It
247
+ sees a copy of the request without its body and no principal; it adds headers or answers the request
248
+ itself. It never admits a caller.
249
+ - `defineOperationMiddleware<PreparedContext<typeof context>>((context, proceed) => …)` runs around every
250
+ route and tool on HTTP, MCP and RPC, after admission and `context.ts`. It answers `proceed()`'s `Result` or
251
+ its own (`err(standardErrors.forbidden.create())`); the answer is checked as a handler's is.
252
+
253
+ `proceed()` runs once. See
254
+ [Context and middleware](https://github.com/getarbol/maximus/blob/main/docs/guides/middleware-and-context.md),
255
+ [Routes](https://github.com/getarbol/maximus/blob/main/docs/guides/routes.md) and
256
+ [Route and operation options](https://github.com/getarbol/maximus/blob/main/docs/reference/operations.md).
@@ -1,73 +1,160 @@
1
1
  # Testing
2
2
 
3
- Maximus tests its own guarantees (token verification, routing, envelopes, validation boundaries,
4
- diagnostics privacy, MCP pagination). Test what only the service knows: domain rules, tenant
5
- isolation in queries, provider projections, state, retries and policies. Do not copy the framework's
6
- matrices into every service.
3
+ Maximus tests its own guarantees: token verification, routing, envelopes, validation, the privacy of its
4
+ diagnostics. A project tests what only it knows: its routes' answers and refusals, its domain rules, that
5
+ one organization never reaches another's data, how it handles other services' failures, and its state.
7
6
 
8
- ## Handler tests (Node or Bun, Vitest)
7
+ ## Run
9
8
 
10
- ```ts
11
- import { createHttpHandler } from '@arbol-ai/maximus';
12
- import { app } from '../src/app'; // app.ts must not import cloudflare:workers
9
+ - `bun run test`: `vp test run`, in Node. `vp test` prepares the project as `vp dev` does, and leaves
10
+ Cloudflare's plugin out.
11
+ - `bun run typecheck`: `maximus prepare && tsc`, which checks the type tests; `vp test run` does not.
12
+ - `bun run verify`: types, lint and format, tests and the build.
13
+
14
+ ## Call the API
13
15
 
14
- const handle = createHttpHandler(app);
15
- const response = await handle(new Request('http://localhost:5173/v1/notes'), env);
16
+ `handler` from `#maximus/http` is the API as the Worker serves it: below `/api`, behind the request
17
+ middleware, with `/health`, OpenAPI, OAuth discovery and `/mcp`. Pages and a web app's files are not part
18
+ of it.
19
+
20
+ ```ts
21
+ import { beforeEach, expect, it } from 'vite-plus/test';
22
+
23
+ import { handler } from '#maximus/http';
24
+
25
+ import { testNamespace } from './kv.ts';
26
+
27
+ /** The development token `vp test` accepts from localhost, as a developer who holds every scope. */
28
+ const token = 'test-development-token-for-local-tests';
29
+ let env: Env;
30
+
31
+ beforeEach(() => {
32
+ env = { DEVELOPMENT_TOKEN: token, NOTES: testNamespace() } as Env;
33
+ });
34
+
35
+ /** Calls the API as the Worker serves it, with the development token, sending `body` as JSON. */
36
+ async function call(method: string, path: string, body?: unknown) {
37
+ const response = await handler(
38
+ new Request(`http://localhost/api${path}`, {
39
+ method,
40
+ headers: {
41
+ authorization: `Bearer ${token}`,
42
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
43
+ },
44
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
45
+ }),
46
+ env
47
+ );
48
+ return { status: response.status, body: (await response.json()) as { data: unknown; error: unknown } };
49
+ }
16
50
  ```
17
51
 
18
- - Fake bindings through the narrow interfaces in `Env` (a `Map` behind a `NoteStore`), not casts.
19
- - Default OAuth verification: `createHttpHandler(app, { verify: async () => claims })` replaces only
20
- the JWT check. Person claims: `{ sub, azp, org_id: 'org_1234567890abcdef', scope, permissions }`;
21
- machine: `{ sub: '<client>@clients', client_id: '<client>', org_id, scope }`. Send
22
- `authorization: Bearer a.b.c` (JWT-shaped). Never pass `verify` in production.
23
- - Custom `tokens.resolve`: put the test credential in `env` and exercise the real resolver.
24
- - Typed client against the handler:
25
-
26
- ```ts
27
- const client = createClient<typeof app>('http://localhost:5173', token, {
28
- response: 'data',
29
- fetch: async (input, init) => await handle(new Request(input, init), env),
30
- });
31
- ```
52
+ - The development token signs in when `env.DEVELOPMENT_TOKEN` holds it (32 characters at least) and the URL's
53
+ host is `localhost`: the caller is `local-developer` of `local-development`, with every scope.
54
+ - Test each refusal by its status and `error.code`: `400 INVALID_INPUT`, `401` without a token, the route's
55
+ own failures.
56
+ - Test tenant isolation through the store, with two organization ids:
57
+ `noteStore(namespace, 'org_1234567890abcdef').find(noteId)` never reads what
58
+ `noteStore(namespace, 'org_abcdef1234567890')` wrote.
59
+ - Calling `handler(request, env)` without a third argument records no observation; pass `{ waitUntil }` to
60
+ test observers.
61
+
62
+ ## Stand-ins for bindings
63
+
64
+ Implement the methods the code calls, cast once (`as unknown as KVNamespace`), and create a new stand-in in
65
+ `beforeEach`. The examples hold one of each kind, in their `tests/` folders: Workers KV over a `Map`
66
+ (`tasks`), D1 over `node:sqlite` with the project's migrations applied (`d1-notes`), R2 with SHA-256 checks
67
+ (`r2-documents`), a queue that records what it is sent and a batch that records `ack()` and `retry()`
68
+ (`queue-reminders`), a Durable Object namespace whose `getByName` constructs the class over `node:sqlite`
69
+ (`do-appointments`), and another Worker's binding as an object of `vi.fn()` methods typed by the module
70
+ `maximus prepare` writes from its RPC document (`worker-rpc/orders`). A queue or cron module is tested by
71
+ calling its default export with the event, `env` and an execution context.
72
+
73
+ Under Vitest, `maximus()` resolves `cloudflare:workers` to a stand-in: `WorkerEntrypoint` and
74
+ `DurableObject` keep the `ctx` and `env` they are constructed with, `RpcTarget` is an empty class and
75
+ `tracing` has no active span. A Durable Object class therefore constructs in Node:
76
+ `testNamespace((state) => new NoteCounter(state, env))`.
32
77
 
33
78
  ## MCP
34
79
 
35
80
  ```ts
36
- const handle = createHttpHandler(app, { verify: async () => claims, transports: [mcp()] });
37
- // POST /mcp with accept: application/json, text/event-stream and a JSON-RPC body;
38
- // parse the response with /data: (\{[^\n]*)/
81
+ /** Sends one JSON-RPC request to the MCP server, signed in, and answers its result. */
82
+ async function callMcp(method: string, params: object = {}) {
83
+ const response = await handler(
84
+ new Request('http://localhost/mcp', {
85
+ method: 'POST',
86
+ headers: {
87
+ authorization: `Bearer ${token}`,
88
+ 'content-type': 'application/json',
89
+ accept: 'application/json, text/event-stream',
90
+ 'mcp-protocol-version': '2025-11-25',
91
+ },
92
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
93
+ }),
94
+ env
95
+ );
96
+ // The answer is a server-sent event whose `data:` line holds the JSON-RPC message.
97
+ const text = await response.text();
98
+ const message = JSON.parse(/data: (\{[^\n]*)/u.exec(text)?.[1] ?? text) as {
99
+ result: Record<string, unknown>;
100
+ };
101
+ return message.result;
102
+ }
39
103
  ```
40
104
 
41
- ## Without a transport
105
+ A tool's output is `result.structuredContent`; a failure is a result with `isError: true` whose text is the
106
+ failure.
42
107
 
43
- `executeOperation(app, app.operations.name, env, principal, input, authority?)` from
44
- `@arbol-ai/maximus/internals` runs the shared execution path (input decoding, derive, middleware,
45
- handler, output check) for RPC-only operations. Principal:
46
- `{ actorId, actorKind, organizationId: 'org_' + 16 alphanumerics, requestId: crypto.randomUUID() }`.
108
+ ## RPC documents and bindings
47
109
 
48
- ## Contract smoke
110
+ An owner proves the RPC document it commits, the one its callers bind to, is the one its routes declare:
49
111
 
50
- `verifyContract((request) => handle(request, env), origin)` from `@arbol-ai/maximus/testing` checks
51
- that `/openapi.json` and `/openapi.yaml` are the same document and returns `{ paths, operations }`.
52
- Run one per service against the real Worker (workerd or a deployment).
112
+ ```ts
113
+ import { readFileSync } from 'node:fs';
114
+ import { join } from 'node:path';
53
115
 
54
- ## workerd
116
+ import { createRpcOpenApi } from '@arbol-ai/maximus';
117
+ import { expect, it } from 'vite-plus/test';
55
118
 
56
- Durable Objects, real bindings and Service Bindings: Cloudflare's Vitest integration with remote
57
- bindings off, or Miniflare with several Workers.
119
+ import { app } from '#maximus/app';
58
120
 
59
- ## RPC types
121
+ it('publishes the RPC document its callers bind to, current with its routes', () => {
122
+ const published: unknown = JSON.parse(
123
+ readFileSync(join(import.meta.dirname, '../openapi.rpc.json'), 'utf-8')
124
+ );
125
+ expect(published).toStrictEqual(createRpcOpenApi(app));
126
+ });
127
+ ```
60
128
 
61
- ```ts
62
- type AssertFalse<T extends false> = T;
63
- type IsNever<T> = [T] extends [never] ? true : false;
64
- export type QuoteReturnExists = AssertFalse<IsNever<Awaited<ReturnType<Service<typeof PricingService>['quoteItems']>>>>;
65
- // @ts-expect-error The control must fail; otherwise the check proves nothing.
66
- export type NeverControl = AssertFalse<IsNever<never>>;
129
+ `bunx maximus openapi --check` proves the same in CI. A caller's tests stand in for the binding with an object
130
+ typed by the generated module, `{ quoteItems: vi.fn<PricingService['quoteItems']>() }` with `PricingService`
131
+ from `#maximus/services/pricing`; a compile-only file with `@ts-expect-error` lines proves a call the owner's
132
+ document does not allow fails `tsc`.
133
+
134
+ ## The contract check
135
+
136
+ `verifyContract(fetch, origin)` from `@arbol-ai/maximus/testing` fetches `<origin>/openapi.json` and
137
+ `<origin>/openapi.yaml` without a token, throws `OpenAPI is unavailable.` when either is not a 2xx and
138
+ `OpenAPI JSON/YAML differ.` when the YAML is not the same document, and answers `{ paths, operations }`:
139
+ the path templates and the `operationId`s, in the document's order. The origin includes the base path:
140
+ `verifyContract((request) => handler(request, env), 'http://localhost/api')`.
141
+
142
+ ## Against a running Worker
143
+
144
+ A suite that reads the Worker's origin from the environment, and skips without one, checks a running Worker:
145
+ `vp dev`, `vp preview` (the production build) or a deployment. `/health` answers `200`, `verifyContract`
146
+ passes, and a call without a token answers `401` with `www-authenticate: Bearer resource_metadata="…"`. A
147
+ production build accepts no development token: a signed-in check needs a real access token for a test
148
+ organization, kept out of the repository.
149
+
150
+ ```sh
151
+ WORKER_URL=http://localhost:5173 bun run test running
67
152
  ```
68
153
 
69
- ## CI rules
154
+ ## Rules
155
+
156
+ Synthetic data only, such as `org_1234567890abcdef`: no customer records, no clinical data, no real
157
+ credentials. No test reaches production resources. A green suite over stand-ins is no evidence that a
158
+ deployment works: check the deployed Worker.
70
159
 
71
- Synthetic data only; no live providers, paid services or production resources; remote bindings
72
- off. Scripts call domain functions or the typed client, never a second provider implementation.
73
- Keep security, privacy and retry tests where they are.
160
+ See [Testing](https://github.com/getarbol/maximus/blob/main/docs/guides/testing.md).