@pexis/core 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/AGENTS.md +634 -0
  2. package/API.md +130 -0
  3. package/LICENSE +23 -0
  4. package/README.md +39 -2
  5. package/dist/app.d.ts +74 -0
  6. package/dist/app.js +1008 -0
  7. package/dist/app.js.map +1 -0
  8. package/dist/components.d.ts +53 -0
  9. package/dist/components.js +62 -0
  10. package/dist/components.js.map +1 -0
  11. package/dist/context.d.ts +17 -0
  12. package/dist/context.js +57 -0
  13. package/dist/context.js.map +1 -0
  14. package/dist/cors.d.ts +19 -0
  15. package/dist/cors.js +85 -0
  16. package/dist/cors.js.map +1 -0
  17. package/dist/csrf.d.ts +2 -0
  18. package/dist/csrf.js +42 -0
  19. package/dist/csrf.js.map +1 -0
  20. package/dist/form.d.ts +30 -0
  21. package/dist/form.js +101 -0
  22. package/dist/form.js.map +1 -0
  23. package/dist/host.d.ts +2 -0
  24. package/dist/host.js +16 -0
  25. package/dist/host.js.map +1 -0
  26. package/dist/html.d.ts +26 -0
  27. package/dist/html.js +114 -0
  28. package/dist/html.js.map +1 -0
  29. package/dist/index.d.ts +16 -0
  30. package/dist/index.js +15 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/jsx-runtime.d.ts +464 -0
  33. package/dist/jsx-runtime.js +166 -0
  34. package/dist/jsx-runtime.js.map +1 -0
  35. package/dist/page.d.ts +33 -0
  36. package/dist/page.js +143 -0
  37. package/dist/page.js.map +1 -0
  38. package/dist/rate-limit.d.ts +54 -0
  39. package/dist/rate-limit.js +117 -0
  40. package/dist/rate-limit.js.map +1 -0
  41. package/dist/registry.d.ts +99 -0
  42. package/dist/registry.js +144 -0
  43. package/dist/registry.js.map +1 -0
  44. package/dist/schema.d.ts +154 -0
  45. package/dist/schema.js +192 -0
  46. package/dist/schema.js.map +1 -0
  47. package/dist/security.d.ts +53 -0
  48. package/dist/security.js +129 -0
  49. package/dist/security.js.map +1 -0
  50. package/dist/styles.d.ts +31 -0
  51. package/dist/styles.js +127 -0
  52. package/dist/styles.js.map +1 -0
  53. package/dist/types.d.ts +398 -0
  54. package/dist/types.js +2 -0
  55. package/dist/types.js.map +1 -0
  56. package/dist/urls.d.ts +10 -0
  57. package/dist/urls.js +16 -0
  58. package/dist/urls.js.map +1 -0
  59. package/package.json +40 -4
package/AGENTS.md ADDED
@@ -0,0 +1,634 @@
1
+ # Building a site with Pexis
2
+
3
+ For coding agents and people building an app on Pexis. This file ships inside the `@pexis/core` package, so it always matches the version installed: `node_modules/@pexis/core/AGENTS.md`. An app installs `@pexis/core`, `@pexis/node` to serve it, and one package per plugin it uses, all at the same version. Read it before writing code; it is short on purpose. If the app has a `pexis.config.ts`, read that first: it says where this app's pages and actions live.
4
+
5
+ Pexis is a server-rendered web framework. You define each page and each action once, and Pexis produces the HTML a person uses, the tool an AI agent calls, the head tags and structured data search engines read, and a Markdown copy for AI readers. Build checks fail when one of those would come out wrong.
6
+
7
+ ## Rules
8
+
9
+ These keep a Pexis site correct for people, search engines and agents at once. Code that breaks one is wrong even if it works.
10
+
11
+ 1. **HTML first.** The server sends HTML, and every page and form works with JavaScript turned off. Reach for a link, a form, `<details>`, `<dialog>` or the popover attribute before a script. `@pexis/components` has accessible ones ready.
12
+ 2. **No React-style state.** There are no hooks, no `useState`, no client state library, and components are plain functions that return markup. Data lives on the server and is loaded in a page's `load`.
13
+ 3. **Every change goes through an action.** Anything that writes data or has an effect is a `defineAction`, in its own file in `actions/`, and shown with `<ActionForm>`. Never handle a form post in a custom route: actions are what agents, MCP clients, the OpenAPI description, rate limits and the admin's log all see.
14
+ 4. **Permissions live on the action.** Give every action that changes data either `permission: (ctx) => ...` or `public: true`. A read action without `permission` can be called by anyone, which suits a search; give it a permission if what it returns is private. Hiding a button is not a permission check.
15
+ 5. **Say how risky an action is.** `risk: 'read'` (safe to repeat; a GET form), `'write'`, or `'irreversible'` (always needs the person's approval). Add `confirm: true` when an agent must show the person the values before sending. Know what that guarantees: browser agents using the Pexis client show an approval dialog, and MCP clients can only reach the action through `@pexis/approvals`, but the JSON endpoint itself cannot tell whether a person approved, so a script can call it directly, as it could submit the form. Where approval must be certain, give the action a permission that needs the signed-in person, so only their own browser session can call it.
16
+ 6. **Content written by users is untrusted.** Render reviews, comments, posts and anything from another site inside `<Untrusted>`. Never put it in an action's title or description.
17
+ 7. **Never `alert()`, `confirm()` or `prompt()`.** Use `<Dialog>` from `@pexis/components`.
18
+ 8. **Styles with `css` and `globalCss`.** They carry the Content Security Policy nonce for you. An inline `<script>` or `<style>` written another way needs `nonce={ctx.nonce}`.
19
+ 9. **Secrets come from environment variables,** never source code. Never log form values, tokens or session IDs.
20
+ 10. **AI is optional and last.** Answer from data and rules first. When a model can help, use `ctx.ai.answer()` from `@pexis/models`, which needs a fallback that works without AI. Do not call a model SDK directly. Render model text inside `<Untrusted>`.
21
+ 11. **Accessible by default.** Every control has a label (fields do this for you), every image has alt text, headings go in order from one `<h1>`, and everything works from the keyboard.
22
+ 12. **Fix the page, not the check.** When `pexis check` reports an error, change the page. Turning a rule off needs a reason a person agreed to.
23
+
24
+ ## The project
25
+
26
+ ```
27
+ app.tsx createApp(): site-wide settings, layout and plugins
28
+ pages/ one page per file; the file name is the URL
29
+ actions/ one action per file, named like the action: actions/book_table.ts
30
+ controllers/ only if you use @pexis/decorators: one @Controller class per file
31
+ components/ how pages are drawn: plain functions that return markup
32
+ layouts/ page shells: header, navigation, footer
33
+ lib/ domain logic and data, with no markup: used by pages and actions alike
34
+ public/ files served as they are: images, fonts, icons (/logo.svg is public/logo.svg)
35
+ pexis.gen.ts generated from the three folders by every pexis command; never edit or commit it
36
+ .pexis/ build output; never edit it
37
+ ```
38
+
39
+ Page files map to URLs:
40
+
41
+ | File | URL |
42
+ |---|---|
43
+ | `pages/index.tsx` | `/` |
44
+ | `pages/menu.tsx` or `pages/menu/index.tsx` | `/menu` |
45
+ | `pages/menu/[dish].tsx` | `/menu/:dish` |
46
+ | `pages/docs/[...rest].tsx` | `/docs/*`: one or more segments, so `/docs` itself needs its own page |
47
+
48
+ Files and folders starting with `_` or `.` are ignored, as are `*.test.tsx` files. In a fresh clone, `pexis.gen.ts` does not exist until a `pexis` command runs: `npx pexis routes` writes it (new apps run it on `npm install`), so the type checker can see it. Adding a page or an action is adding its file: never edit `app.tsx` for it. `public/` never serves HTML (make a page instead, so it gets head tags, the security policy and the checks) or dotfiles. Subfolders such as `pages/bookings/` and `actions/bookings/` group work by team or area.
49
+
50
+ ### Which folder may import which
51
+
52
+ | From | May import | Never |
53
+ |---|---|---|
54
+ | `pages/` | components, layouts, actions (to show their forms), lib | other pages |
55
+ | `actions/` | lib | pages, components, layouts: agents and MCP call actions with no page at all |
56
+ | `components/` | components, actions (to render a form), lib | pages |
57
+ | `layouts/` | components, lib | pages, actions |
58
+ | `lib/` | lib | anything that renders, and actions |
59
+
60
+ `pexis check` lists imports that break these as warnings under "Project structure". A Pexis app is built from what it can do: actions first, then the pages that present them, then the components pages are drawn with.
61
+
62
+ ### When the standard folders do not fit
63
+
64
+ An optional `pexis.config.ts` beside `app.tsx` lists where pages and actions come from instead. Each source keeps its own rules completely: in a `files()` source the file name is the route and the action name; in a `controllers()` source the decorators are.
65
+
66
+ ```ts
67
+ // pexis.config.ts
68
+ import { controllers, defineConfig, files } from '@pexis/cli/config';
69
+
70
+ export default defineConfig({
71
+ sources: [
72
+ files(), // pages/ and actions/
73
+ files({ pages: 'modules/marketing/pages', actions: 'modules/marketing/actions', base: '/marketing' }),
74
+ controllers('modules/billing/**/*.controller.tsx'), // a team that prefers classes
75
+ ],
76
+ });
77
+ ```
78
+
79
+ Folders must be inside the app, and a pattern must start with a folder (`*` matches within a name, `**` across folders). Two sources may not claim the same file, URL or action name. Without a config the app uses `files()` and `controllers('controllers')`.
80
+
81
+ ### Modules: one folder per team
82
+
83
+ When several teams share an app, each can own a module: a folder laid out like a small app, listed with `module()`. Experimental.
84
+
85
+ ```
86
+ modules/bookings/
87
+ index.ts what other modules may import
88
+ pages/ actions/ components/ layouts/ lib/ migrations/
89
+ ```
90
+
91
+ ```ts
92
+ // pexis.config.ts
93
+ import { defineConfig, files, module } from '@pexis/cli/config';
94
+
95
+ export default defineConfig({
96
+ sources: [files(), module('modules/bookings', { base: '/bookings' }), module('modules/menu')],
97
+ });
98
+ ```
99
+
100
+ - The module's pages are served under `base` (`modules/bookings/pages/index.tsx` is `/bookings`), and its actions are registered like any other.
101
+ - The same import rules apply inside a module.
102
+ - Another module is used only through its `index.ts`. `pexis check` warns (`structure/modules`) when one module imports another's files directly. To use another team's action, export it from their `index.ts` and run it with `ctx.call` (see "Using another team's action" below).
103
+ - Each `.sql` file in `migrations/` becomes a migration with the id `<module>.<file name>`. `pexis.gen.ts` exports them as `migrations`; pass them on with `data({ db, migrations: [...yours, ...migrations] })`.
104
+
105
+ Give each module folder an owner in CODEOWNERS, and `pexis.config.ts` to whoever owns the app.
106
+
107
+ ## Commands
108
+
109
+ | Command | What it does |
110
+ |---|---|
111
+ | `npx pexis dev` | Runs the site at http://localhost:3000. Saving a file rebuilds, restarts and reloads open pages |
112
+ | `npx pexis check` | Builds, then runs every check on every page; exits 1 on errors |
113
+ | `npx pexis check --browser` | Also loads each page in Chromium for Core Web Vitals and color contrast (warnings). Needs `npm install --save-dev playwright` and `npx playwright install chromium` |
114
+ | `npx pexis build` | Production build in `.pexis/build` (`--target bun` or `--target cloudflare` for other hosts) |
115
+ | `npx pexis routes` | Lists the pages and actions found, and writes `pexis.gen.ts` |
116
+
117
+ ## Pages
118
+
119
+ ```tsx
120
+ // pages/menu/[dish].tsx
121
+ import { definePage, notFound } from '@pexis/core';
122
+ import { dishes } from '../../data.js';
123
+
124
+ export default definePage({
125
+ // Runs on the server before rendering. Return notFound() or redirect(url) to stop.
126
+ load: (ctx) => dishes.find((d) => d.slug === ctx.params.dish) ?? notFound(),
127
+ // Title, description, canonical link and structured data come from here.
128
+ head: (dish) => ({
129
+ title: dish.name,
130
+ description: dish.summary,
131
+ structuredData: { '@type': 'MenuItem', name: dish.name },
132
+ }),
133
+ render: ({ data: dish }) => (
134
+ <>
135
+ <h1>{dish.name}</h1>
136
+ <p>{dish.summary}</p>
137
+ </>
138
+ ),
139
+ // Pages with parameters list their public URLs, for the sitemap and the checks.
140
+ entries: () => dishes.map((d) => ({ dish: d.slug })),
141
+ });
142
+ ```
143
+
144
+ - Every page needs a title and a description. The checks fail without them.
145
+ - `index: false` keeps a page out of search results, the sitemap and the checks (account pages, drafts).
146
+ - Values in JSX are escaped. Never build HTML from strings; `raw()` is for markup you wrote yourself, never for user input.
147
+ - `redirect('/somewhere')` only goes to this site; another site needs `redirect(url, 303, { external: true })`, and never with a URL a visitor supplied.
148
+ - Inside a component, `getContext()` returns the current request's `ctx` without passing it down.
149
+ - Headers, cookies and status go on `ctx.response` in `load` or `run`: `ctx.response.headers.set('cache-control', 'public, max-age=300')`, `ctx.response.headers.append('set-cookie', '...')`, `ctx.response.status = 410`. Security headers and the content type cannot be set there, and redirects use `redirect()`.
150
+ - Your own "not found" and "something went wrong" pages: `createApp({ errorPages: { notFound: { head, render }, serverError: { head, render } } })`. Keep the error page simple; if it fails, the built-in one is shown.
151
+ - `stream: true` (experimental) sends the head and the top of the layout as soon as `load` finishes, while slow async components on the page are still working. Put slow data in an async component, not in `load`, to benefit. Once streaming starts the status is 200, so an error after that shows a short message in the page and is logged.
152
+ - A page or action that takes more than 30 seconds gets 503 (`security.timeoutSeconds` changes it). Pass `ctx.signal` to `fetch()` and database calls, so they stop when the request does.
153
+ - Each page has one address: `/menu/` redirects to `/menu`, and a wrong method gets 405 with the methods that work.
154
+
155
+ ## Layout and styles
156
+
157
+ ```tsx
158
+ // app.tsx
159
+ import { createApp, css, defineLayout, globalCss } from '@pexis/core';
160
+ import { devtools } from '@pexis/devtools';
161
+ import { markdown } from '@pexis/markdown';
162
+ import { openapi } from '@pexis/openapi';
163
+ import { siteFiles } from '@pexis/site-files';
164
+ // Every file in pages/ and actions/, found by the pexis command.
165
+ import { actions, pages } from './pexis.gen.js';
166
+
167
+ const base = globalCss`body { font: 16px/1.5 system-ui, sans-serif; margin: 0; }`;
168
+ const shell = css`max-width: 40rem; margin: 0 auto; padding: 1rem;`;
169
+
170
+ const links = [
171
+ { href: '/', label: 'Home' },
172
+ { href: '/menu', label: 'Menu' },
173
+ ];
174
+
175
+ const layout = defineLayout(({ children, ctx }) => (
176
+ <>
177
+ <header>
178
+ <nav aria-label="Main">
179
+ {links.map((link) => (
180
+ // aria-current tells screen readers which page this is.
181
+ <a href={link.href} aria-current={ctx.url.pathname === link.href ? 'page' : undefined}>
182
+ {link.label}
183
+ </a>
184
+ ))}
185
+ </nav>
186
+ </header>
187
+ {/* A custom layout must include the <main> element. */}
188
+ <main class={shell}>{children}</main>
189
+ </>
190
+ ));
191
+
192
+ export default createApp({
193
+ origin: process.env.SITE_ORIGIN ?? 'http://localhost:3000',
194
+ layout,
195
+ styles: [base],
196
+ pages,
197
+ actions,
198
+ plugins: [markdown(), openapi(), siteFiles(), devtools()],
199
+ });
200
+ ```
201
+
202
+ `css` styles are scoped to where they are used and only sent with pages that use them.
203
+
204
+ ## Actions
205
+
206
+ ```tsx
207
+ // actions/book_table.ts: the file is named after the action.
208
+ import { defineAction, field, invalid } from '@pexis/core';
209
+
210
+ export default defineAction({
211
+ name: 'book_table', // the tool name agents see: lowercase, digits, underscores
212
+ title: 'Book a table', // the form's name and button text
213
+ description: 'Reserves a table. Needs a name, an email, a date and the number of guests. Returns a booking reference.',
214
+ risk: 'write',
215
+ confirm: true, // agents show the person the values first
216
+ public: true, // anyone may book; otherwise give permission: (ctx) => ...
217
+ input: {
218
+ name: field.text({ label: 'Your name', min: 1, max: 80, autocomplete: 'name' }),
219
+ email: field.text({ label: 'Email', format: 'email' }),
220
+ date: field.date({ label: 'Date' }),
221
+ guests: field.integer({ label: 'Guests', min: 1, max: 12 }),
222
+ seating: field.choice({ label: 'Seating', options: [{ value: 'inside', label: 'Inside' }, { value: 'terrace', label: 'Terrace' }] }),
223
+ notes: field.text({ label: 'Notes', multiline: true, optional: true }),
224
+ },
225
+ // input is validated and typed before run() is called.
226
+ async run(input, ctx) {
227
+ // Rules the fields cannot express: refuse with invalid(), naming the field.
228
+ if (input.date < new Date().toISOString().slice(0, 10)) return invalid({ date: 'Choose today or a later date.' });
229
+ return { message: `Booked for ${input.guests} on ${input.date}.`, data: { reference: 'AST-0001' } };
230
+ },
231
+ });
232
+ ```
233
+
234
+ (`invalid` is imported from `@pexis/core` too.) A refused call gets 422 with the errors; a person sees the form again with each message under its field. A JSON call with a field the action does not have is refused the same way, so a misspelled optional field is never silently dropped.
235
+
236
+ By default a submitted form loads a new page: a simple page with the action's `message` and a link back to the page the form was on. That is deliberate, so every form works without JavaScript. For the result to appear in place, without leaving the page, give the form a `target` and add `inPlace()` (see [Updating part of the page](#updating-part-of-the-page)); the `agents/in-place-script` check warns when a form has a `target` but the page has no script to use it.
237
+
238
+ | Field | Options (all take `label`, `description` for people and agents, and `optional`) |
239
+ |---|---|
240
+ | `field.text` | `min`, `max` (characters), `format: 'email' \| 'url' \| 'tel'` (url means http or https), `pattern`, `multiline`, `autocomplete` |
241
+ | `field.integer`, `field.number` | `min`, `max` |
242
+ | `field.date` | `min`, `max` as `YYYY-MM-DD` |
243
+ | `field.choice` | `options: [{ value, label }]`; agents send the value |
244
+ | `field.boolean` | a checkbox: unchecked is `false`, so it is never required |
245
+
246
+ Show it on a page with `import bookTable from '../actions/book_table.js'` and `<ActionForm action={bookTable} />`. The same definition is the HTML form, the agent tool at `/pexis/actions.json`, the JSON endpoint `POST /actions/book_table`, and an OpenAPI operation. Field kinds: `field.text`, `integer`, `number`, `date`, `choice`, `boolean`; more (time, radio, amount, color, range) in `@pexis/components` as `inputs.*`. Never ask for passwords or files in an action.
247
+
248
+ A search or lookup is `risk: 'read'`: it becomes a GET form, and agents may call it without asking.
249
+
250
+ AI agents working in a person's browser read the `px-` attributes `<ActionForm>` puts on the form, so they see the action with no script on the page. To also offer the tools as `window.pexis` and through WebMCP where a browser supports it, with approval in an in-page dialog, add `agentTools()` from `@pexis/client/plugin`: it puts one small module script on every page, so it is opt-in.
251
+
252
+ ### Updating part of the page
253
+
254
+ Experimental. Give the form a `target`, and with JavaScript on its result replaces that part of the page instead of loading a new one:
255
+
256
+ ```tsx
257
+ import { inPlace } from '@pexis/client/plugin';
258
+ // plugins: [inPlace()]
259
+ // In a page:
260
+ <ActionForm action={bookTable} target="booking" />
261
+ ```
262
+
263
+ `target` is the id of a region `<ActionForm>` renders around the form. On submit, a small script (sent only to pages with such a form) sends the same form to the same action endpoint with `fetch`, and the server answers with HTML for the region: the message, then the form again with the values sent. Invalid values show under their fields, and focus moves to the message, or to the first field with an error. With JavaScript off, or before the script loads, the form posts as always and the full result page comes back. Use it for searches, bookings and edits; it adds no client state, since the server renders every version.
264
+
265
+ - While a request is out the region has `aria-busy="true"`: style `[aria-busy="true"]` to show it is working. The message has the class `px-result`.
266
+ - Field ids start with the target's id, so two forms for one action need two targets, not `idPrefix`. Each target id must be unique on the page.
267
+ - People-only actions (`agents: false`, staff actions included) refuse a target: they need a real page submission.
268
+ - The reply brings no styles of its own: use the same `css` classes as the page.
269
+
270
+ ### Using another team's action: `ctx.call`
271
+
272
+ When code needs what another action does, call the action rather than its files. Experimental.
273
+
274
+ ```tsx
275
+ // modules/bookings/actions/book_dish.ts
276
+ import { defineAction, field, invalid } from '@pexis/core';
277
+ import { checkDish } from '../../menu/index.js'; // the menu team exports its action
278
+
279
+ export default defineAction({
280
+ name: 'book_dish',
281
+ title: 'Book a dish',
282
+ description: 'Reserves a dish for collection today. Returns a reference.',
283
+ risk: 'write',
284
+ public: true,
285
+ input: { dish: field.text({ label: 'Dish', max: 40 }) },
286
+ async run({ dish }, ctx) {
287
+ const found = await ctx.call(checkDish, { dish });
288
+ if (!found.ok) return invalid({ dish: found.message });
289
+ return { message: `Reserved ${dish}.` };
290
+ },
291
+ });
292
+ ```
293
+
294
+ `ctx.call` runs the other action's permission check and validation, as the person making this request, never with more rights, and records it in the activity log. It returns what an agent would get: `{ ok: true, message, data }`, or `{ ok: false, outcome, message }` (with `errors` when the outcome is `invalid`).
295
+
296
+ A call cannot carry more risk than the request it is in. A page's `load` may call only `read` actions; an action may call actions of the same risk or lower; an action with `confirm: true` only from another that has it. Breaking these throws, because it is a mistake in the code.
297
+
298
+ ## Decorators (optional)
299
+
300
+ Teams used to Angular, Java or C# can write pages and actions as classes with `@pexis/decorators`. They compile to the same definitions, so everything above still applies. Put each class in `controllers/`:
301
+
302
+ ```tsx
303
+ // controllers/bookings.tsx
304
+ import { Action, actionFor, Controller, Field, Page } from '@pexis/decorators';
305
+ import { ActionForm } from '@pexis/core';
306
+
307
+ class BookingInput {
308
+ @Field.text({ label: 'Your name', max: 80 }) name!: string;
309
+ @Field.integer({ label: 'Guests', min: 1, max: 12 }) guests!: number;
310
+ }
311
+
312
+ @Controller('/bookings')
313
+ export default class Bookings {
314
+ @Page('/', { head: { title: 'Book a table', description: 'Reserve a table.' } })
315
+ home() {
316
+ return <ActionForm action={actionFor(this.book)} />;
317
+ }
318
+
319
+ @Action({ name: 'book_table', title: 'Book a table', description: 'Reserves a table. Returns a reference.', risk: 'write', confirm: true, public: true, input: BookingInput })
320
+ book(input: BookingInput) {
321
+ return { message: `Booked for ${input.guests}.` };
322
+ }
323
+ }
324
+ ```
325
+
326
+ Field decorators are `@Field.text()`, `integer`, `number`, `date`, `choice`, `boolean` and `@Field.custom(kind, options)`. Use one style per area: a whole folder of functions, or a whole folder of classes. `pexis.config.ts` (above) can give different areas different styles.
327
+
328
+ ## Plugins
329
+
330
+ Add each to `plugins` in `createApp`. Each is one line, and none turns itself on.
331
+
332
+ | You need | Add | From |
333
+ |---|---|---|
334
+ | Markdown copies of pages for AI readers | `markdown()` | `@pexis/markdown` |
335
+ | robots.txt and sitemap.xml | `siteFiles()` | `@pexis/site-files` |
336
+ | An OpenAPI description of the actions | `openapi()` | `@pexis/openapi` |
337
+ | The dev toolbar and reload on save | `devtools()` | `@pexis/devtools` |
338
+ | Sessions and `ctx.user` | `sessions()` | `@pexis/sessions` |
339
+ | Sign-in with Google, Microsoft, GitHub, Apple or any OpenID provider | `auth({ providers })`, after `sessions()` | `@pexis/auth` |
340
+ | A database at `ctx.db` | `data({ db, migrations })` | `@pexis/data` |
341
+ | Translations at `/fr/...` | `i18n({ locales, defaultLocale, messages })` | `@pexis/i18n` |
342
+ | A password-protected, read-only admin | `admin({ password: process.env.PEXIS_ADMIN_PASSWORD })` | `@pexis/admin` |
343
+ | Changes by named staff, with an audit log | `admin({ password, staff, audit })` and `staffAction()`, after `auth()` | `@pexis/admin` |
344
+ | Staff approve what visitors wrote before it shows | `moderationQueue({ name, title, path, pending, approve, reject })` | `@pexis/admin` |
345
+ | AI answers with a fallback and a token budget | `models({ large })` | `@pexis/models` |
346
+ | The actions as MCP tools for AI apps | `mcp()` | `@pexis/mcp` |
347
+ | A person approving what an AI app asks for | `approvals()` | `@pexis/approvals` |
348
+ | Traces and model spend in an OpenTelemetry collector (`OTEL_*` variables) | `telemetry()`, `tracedDatabase(db)`, `tracedUsage(store)` | `@pexis/telemetry` |
349
+
350
+ ### Data
351
+
352
+ ```ts
353
+ import { data, sql } from '@pexis/data';
354
+ import { connect } from '@pexis/data/connect';
355
+
356
+ // file:data.db (SQLite, built in), postgres://, mysql:// or libsql://. Install only that database's client.
357
+ const db = await connect(process.env.DATABASE_URL ?? 'file:data.db');
358
+ // plugins: [data({ db, migrations: [{ id: '001-bookings', sql: 'CREATE TABLE bookings (id INTEGER PRIMARY KEY, name TEXT NOT NULL)' }] })]
359
+
360
+ // In load() or run(): every ${value} is a bound parameter, never pasted into the SQL.
361
+ await ctx.db.run(sql`INSERT INTO bookings (name) VALUES (${input.name})`);
362
+ const rows = await ctx.db.all(sql`SELECT name FROM bookings ORDER BY id DESC`);
363
+ ```
364
+
365
+ Search, experimental: `searchIndex(db, { name: 'menu' })` from `@pexis/data` finds documents by their words on every database. Give it an embedder (`await loadEmbedder(configFromEnv(process.env, 'PEXIS_AI_EMBED'))` from `@pexis/ai`) and it also finds by meaning ("something warm" finds the soup), falling back to words if the model is down. Each hit says whether it matched by words, meaning or both.
366
+
367
+ ```ts
368
+ const menu = searchIndex(db, { name: 'menu', embedder });
369
+ await menu.put('leek-soup', 'Leek soup with potatoes', { title: 'Leek soup', url: '/menu/leek-soup' });
370
+ const hits = await menu.query(input.q, { limit: 10 }); // [{ id, score, meta, by }]
371
+ ```
372
+
373
+ ### Sign-in
374
+
375
+ ```ts
376
+ import { auth, google, requireUser } from '@pexis/auth';
377
+ // plugins: [sessions(), auth({ providers: [google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! })] })]
378
+
379
+ // A page for signed-in people only:
380
+ // load: (ctx) => requireUser(ctx) ?? loadAccount(ctx.user!)
381
+ // An action for signed-in people only:
382
+ // permission: (ctx) => ctx.user !== null
383
+ ```
384
+
385
+ Before something sensitive (changing an email, deleting an account), ask people to sign in again when their sign-in is old, and check it on the action too:
386
+
387
+ ```ts
388
+ import { requireRecentSignIn } from '@pexis/auth';
389
+ import { signedInWithin } from '@pexis/sessions';
390
+ // The page with the form: load: (ctx) => requireRecentSignIn(ctx, 300) ?? loadSettings(ctx.user!)
391
+ // The action itself: permission: (ctx) => signedInWithin(ctx, 300)
392
+ ```
393
+
394
+ The provider is asked for the person's credentials again (`prompt=login`), and providers that speak OpenID Connect (Google, Microsoft, Apple, `oidc()`) must prove it with a recent `auth_time`. GitHub does not speak OpenID Connect, so it cannot prove it.
395
+
396
+ ### Staff changes and the audit log
397
+
398
+ Changes the site's staff make (canceling a booking, hiding a review) are actions like any other, made with `staffAction()` instead of `defineAction()`, in `actions/`. Staff sign in one by one with `@pexis/auth`; there is no shared password for changes.
399
+
400
+ ```ts
401
+ import { admin, staffAction } from '@pexis/admin';
402
+ import { auditStore } from '@pexis/data';
403
+ // plugins: [sessions(), auth({ providers }), data({ db }), admin({ password: process.env.PEXIS_ADMIN_PASSWORD, staff: process.env.PEXIS_ADMIN_STAFF, audit: auditStore(db) })]
404
+ // PEXIS_ADMIN_STAFF=google:1098765432,ada@example.com
405
+
406
+ // actions/cancel-booking.ts
407
+ export default staffAction({
408
+ name: 'cancel_booking',
409
+ title: 'Cancel booking',
410
+ description: 'Cancels a booking.',
411
+ risk: 'irreversible',
412
+ input: { booking: field.integer({ label: 'Booking', min: 1 }) },
413
+ record: (input) => `booking:${input.booking}`,
414
+ async run(input, ctx) {
415
+ await ctx.db.run(sql`DELETE FROM bookings WHERE id = ${input.booking}`);
416
+ return { message: 'Booking canceled.' };
417
+ },
418
+ });
419
+ ```
420
+
421
+ - The staff list comes from the environment: user ids (`ctx.user.id`, such as `google:1098765432`) or email addresses, which count only when the provider verified them. Ids are safer: they never change hands.
422
+ - A staff action is for people only. Agents never see it, JSON calls are refused, and it runs only from a form a browser submits on your site.
423
+ - An irreversible one needs a sign-in in the last five minutes. Put `requireRecentSignIn(ctx)` in the `load` of the page with the form, so staff are asked to sign in again before they get there. `isStaff(ctx)` tells a page whether to show the form.
424
+ - Each call is written to the audit log, at `/pexis/admin/audit`: who, which action, which record (from `record()`), the field names and the outcome, never the values. `record()` should return an id, never personal data.
425
+ - The admin's own pages stay read-only behind its password. Staff make changes on your site's pages.
426
+
427
+ For content visitors write that staff must approve first (reviews, comments), use a moderation queue instead of writing the page and actions yourself:
428
+
429
+ ```ts
430
+ import { moderationQueue } from '@pexis/admin';
431
+
432
+ // plugins: [..., admin({ ... }), moderationQueue({
433
+ // name: 'reviews',
434
+ // title: 'Reviews waiting',
435
+ // path: '/staff/reviews',
436
+ // pending: (ctx, limit) => ctx.db.all(sql`SELECT id, body AS content FROM reviews WHERE state = 'waiting' ORDER BY id LIMIT ${limit}`),
437
+ // approve: async (id, ctx) => (await ctx.db.run(sql`UPDATE reviews SET state = 'shown' WHERE id = ${id} AND state = 'waiting'`)).changes === 1,
438
+ // reject: async (id, ctx) => (await ctx.db.run(sql`UPDATE reviews SET state = 'hidden' WHERE id = ${id} AND state = 'waiting'`)).changes === 1,
439
+ // })]
440
+ ```
441
+
442
+ - It adds two staff actions, `reviews_approve` and `reviews_reject`, audited by item id, and a page at `path` that only staff can see (others get "not found"), listing what waits inside `<Untrusted>` with a form per decision. It works without JavaScript.
443
+ - `approve` and `reject` return false when the item is no longer waiting. Make the change conditional on the item still waiting, as above, so two staff deciding at once cannot both apply.
444
+ - The admin shows how many items wait and links to the page; it never shows what visitors wrote.
445
+
446
+ ### AI
447
+
448
+ ```tsx
449
+ import { configFromEnv, loadModel } from '@pexis/ai';
450
+ import { models, text } from '@pexis/models';
451
+
452
+ // Which model is configuration (PEXIS_AI_PROVIDER, PEXIS_AI_MODEL); null means none.
453
+ const model = await loadModel(configFromEnv(process.env));
454
+ // plugins: [models({ large: model, tokensPerDay: 200_000 })]
455
+
456
+ const summary = await ctx.ai.answer({
457
+ task: 'review-summary',
458
+ rule: () => (reviews.length === 0 ? 'No reviews yet.' : undefined),
459
+ ask: {
460
+ system: 'Summarize restaurant reviews in one plain sentence.',
461
+ prompt: 'Summarize what these guests say.',
462
+ untrusted: reviews.map((r) => r.text), // user content goes here, never in system or prompt
463
+ parse: text({ max: 240 }),
464
+ },
465
+ fallback: () => `${reviews.length} reviews.`,
466
+ keep: true, // generate once; reuse until the reviews change
467
+ });
468
+ // <Untrusted as="p">{summary.value}</Untrusted>
469
+ ```
470
+
471
+ `keep: true` stores the answer and reuses it until the question changes, so a page costs no tokens per view. Pass `models({ answers: answerStore(db) })` from `@pexis/data` to share kept answers between servers.
472
+
473
+ ### Live regions
474
+
475
+ Experimental. Part of a page that updates from the server, such as stock or a queue length:
476
+
477
+ ```tsx
478
+ import { defineLive, live } from '@pexis/client/live';
479
+
480
+ export const stock = defineLive({ name: 'stock', every: 30, render: async (ctx, params) => <p>{await countLeft(params.dish)} left</p> });
481
+ // plugins: [live([stock])]
482
+ // In a page: <stock.Region params={{ dish: 'soup' }} label="Soup in stock" />
483
+ ```
484
+
485
+ The page shows the current content, so it works without JavaScript. A small script, sent only on pages with a region, fetches fresh HTML from the server every `every` seconds (at least 5) while the tab is visible. The region has `role="status"`, so screen readers announce changes politely. Treat `params` as visitor input. Use the same `css` classes in every version, since a fresh copy brings no styles of its own.
486
+
487
+ ### Components
488
+
489
+ ```tsx
490
+ import { Accordion, Dialog, inputs } from '@pexis/components';
491
+
492
+ <Dialog title="Opening hours" trigger="See hours">
493
+ <p>Tuesday to Sunday, 12:00 to 22:00.</p>
494
+ </Dialog>
495
+
496
+ <Accordion items={[{ title: 'Do you take walk-ins?', content: <p>Yes, until 21:00.</p> }]} />
497
+
498
+ // More field kinds for actions: inputs.time, inputs.radio, inputs.amount, inputs.color, inputs.range
499
+ // time: inputs.time({ label: 'Time' })
500
+ ```
501
+
502
+ They use `<dialog>`, `<details>` and the popover attribute, so they work without JavaScript. Use `<Dialog>`, never `alert()` or `confirm()`.
503
+
504
+ ### Translations
505
+
506
+ ```tsx
507
+ import { i18n, LanguageLinks, t } from '@pexis/i18n';
508
+ // plugins: [i18n({ locales: ['en', 'fr'], defaultLocale: 'en', messages: { en, fr } })]
509
+ // with messages like { menu: { title: 'Menu', dishes: '{count, plural, one {# dish} other {# dishes}}' } }
510
+
511
+ <h1>{t('menu.title')}</h1>
512
+ <p>{t('menu.dishes', { count: 3 })}</p>
513
+ <LanguageLinks />
514
+ ```
515
+
516
+ The default language has no prefix (`/menu`) and others do (`/fr/menu`). Never redirect by the browser's language. `npx pexis translate --from en` fills missing messages into review files when a model is configured.
517
+
518
+ ### Agents outside the browser: MCP and approvals
519
+
520
+ ```ts
521
+ import { approvals } from '@pexis/approvals';
522
+ import { approvalStore } from '@pexis/data';
523
+ import { mcp } from '@pexis/mcp';
524
+ // plugins: [mcp({ name: 'Aster' }), approvals({ store: approvalStore(db) })]
525
+ // Without a database, approvals() keeps requests in memory, for one server.
526
+ ```
527
+
528
+ AI apps connect to `/pexis/mcp` and see the same actions as tools, through the same permission checks. An action with `confirm: true` (or `risk: 'irreversible'`) is offered only with `approvals()`: the call returns a link, and the person approves the exact values on your site before anything runs. The app can then check the outcome with the built-in `pexis-approval-status` tool, which reads only this site's own approval links.
529
+
530
+ ### Letting AI apps sign in as a person
531
+
532
+ Experimental. With `oauthServer()` an MCP client can sign in, so it can call actions that need a permission, as the person who allowed it:
533
+
534
+ ```ts
535
+ import { oauthServer } from '@pexis/auth/server';
536
+ import { oauthStore } from '@pexis/data';
537
+ // plugins: [sessions(), auth({ providers }), oauthServer({
538
+ // loadUser: (id) => findUser(id), // checked again on every request; null ends the grant
539
+ // clients: ['https://claude.ai/oauth/mcp-client-metadata.json'], // only these apps may sign in
540
+ // store: oauthStore(db),
541
+ // }), mcp(), approvals()]
542
+ ```
543
+
544
+ - The app sends the person to your site. They sign in as usual and see which app is asking (by its address), what it may do (look things up, or also make changes), and Allow or Deny.
545
+ - The app gets a token that works only at `/pexis/mcp`, as that person. Actions see `ctx.user` as usual, and `ctx.agent` tells them an app is acting: `permission: (ctx) => !ctx.agent && isStaff(ctx.user)` keeps an action for people.
546
+ - The token never reaches actions that need approval (they go through `approvals()`, and only the person can approve them), people-only actions, or `requireRecentSignIn`.
547
+ - People see and remove their apps at `/account/connected-apps`.
548
+ - `clients` lists the apps you allow, by `client_id` URL or host. To allow any app, use `clients: 'any'` with `fetchMetadata: publicFetch` from `@pexis/node/public-fetch`, which refuses addresses inside your network.
549
+ - `mcp({ signIn: 'required' })` refuses every tool call without a token.
550
+
551
+ ### Undoing what an app did
552
+
553
+ Experimental. A write an app makes with a token can be reversed by the person, when the action says how:
554
+
555
+ ```ts
556
+ // actions/book_table.ts
557
+ export default defineAction({
558
+ name: 'book_table',
559
+ risk: 'write',
560
+ // ...
561
+ run: async (input, ctx) => ({ message: 'Booked.', data: { reference: await book(input) } }),
562
+ undo: {
563
+ action: cancelBooking, // another registered write action, run as the person
564
+ input: (input, result) => ({ reference: (result.data as { reference: string }).reference }),
565
+ hours: 24, // how long it can be reversed
566
+ },
567
+ });
568
+ ```
569
+
570
+ - With `approvals()` installed, the person sees each change at `/pexis/approvals/activity`, grouped by app, with the exact values the undo will send. They reverse it with one button, as themselves.
571
+ - Build the undo input from `result.data` naming what this write created. Return `null` when the write changed nothing, so there is nothing to undo.
572
+ - Undo actions must be idempotent, and should check the thing is still as the write left it. If the app or the person runs the undo action another way, the change is marked reversed, so nothing runs twice.
573
+ - A write with outside effects (an email sent, a card charged) cannot be taken back: make it `irreversible`, or make its undo compensate (a cancellation email, a refund).
574
+ - Only writes made with a token are listed. A call made by an MCP client with cookies, or by a browser agent filling in a form, looks like the person.
575
+
576
+ ## Deploying
577
+
578
+ ```bash
579
+ npx pexis build # Node: NODE_ENV=production node .pexis/build/server.js
580
+ npx pexis build --target bun # Bun: bun .pexis/bun/server.js
581
+ npx pexis build --target cloudflare # Workers: prints the wrangler.toml lines
582
+ ```
583
+
584
+ - The built server reads `PORT` (default 3000) and `HOST` (default localhost; use `0.0.0.0` in a container). It says it is running only once the port is open, and stops with a clear message if the port is taken.
585
+ - Set `SITE_ORIGIN` (or `origin` in `createApp`) to the public address, including the port when it is not the default: canonical links, the sitemap and the CSRF check use it.
586
+ - Behind a load balancer, set `PEXIS_TRUSTED_PROXIES` to the number of proxies, or rate limits see the proxy's address.
587
+ - Several servers share sessions, rate limits, approvals, model budgets and the audit log through `@pexis/data` stores (`sessionStore(db)` and the others). Lambda, Cloud Run, Workers and most containers run several servers, or replace them often. In production, the app warns at startup about anything still kept in one server's memory, and says which store to add. An app that really runs as one long-lived server can set `PEXIS_SINGLE_INSTANCE=1` to turn the warning off.
588
+ - Sign-in with `auth()` works on any number of servers: the sign-in in progress is kept in the browser's own cookie, not in a server's memory.
589
+ - Secrets (`PEXIS_ADMIN_PASSWORD`, provider keys) and the staff list (`PEXIS_ADMIN_STAFF`) come from the environment, never the code.
590
+
591
+ ### Splitting a site into separately deployed areas
592
+
593
+ Most sites never need this: modules give each team its own folder, review and tests in one deployment, which is cheaper. Split only when a team needs its own release cycle.
594
+
595
+ Split by URL, never by stitching parts of pages together in the browser:
596
+
597
+ - Each area is its own app serving its own paths (`/bookings/*` in one, `/menu/*` in another), behind one domain, with path routing at the edge or the load balancer. Every app has the same `origin` (`SITE_ORIGIN`): the public address, not its own.
598
+ - A shared layout package (`@aster/layout`, exporting the `defineLayout` and the global styles) keeps the site looking like one site. Each app lists it in `createApp({ layout, styles })`.
599
+ - One domain and one session store keep people signed in across areas: every app uses `sessions({ store: sessionStore(db) })` on the same database. Sign-in (`auth()`) and `/pexis/*` routes stay with one app, the front app, so route `/auth/*` and `/pexis/*` there.
600
+ - `ctx.call` runs actions of the same app. To use another area's action, call its endpoint over HTTP as the person, passing on their cookie:
601
+
602
+ ```ts
603
+ const res = await fetch(`${process.env.MENU_URL}/actions/check_dish`, {
604
+ method: 'POST',
605
+ headers: { 'content-type': 'application/json', accept: 'application/json', cookie: ctx.request.headers.get('cookie') ?? '' },
606
+ body: JSON.stringify({ dish }),
607
+ });
608
+ const found = (await res.json()) as { ok: boolean; message: string };
609
+ ```
610
+
611
+ - Agents still see one site. The front app's `mcp()` lists every area's tools and passes calls to the area that has them, with the client's token:
612
+
613
+ ```ts
614
+ // The front app
615
+ mcp({ areas: [{ url: process.env.MENU_URL }, { url: process.env.BOOKINGS_URL }] })
616
+ // Each area runs mcp() too; with sign-in, oauthServer({ store: oauthStore(db), ... }) on the same database everywhere.
617
+ ```
618
+
619
+ - Each area checks everything itself: the token, scopes, permissions, validation and rate limits. Set `PEXIS_TRUSTED_PROXIES` on an area so it sees the visitor's address that the front app passes on, not the front app's.
620
+ - Tools that need approval stay with their own area: their approval links are that area's. Tool names must be unique across the site; if two areas share one, only the first is offered and the server logs which.
621
+
622
+ ## Before you say it is done
623
+
624
+ 1. `npx pexis check` passes with no errors.
625
+ 2. Load the page in a browser, with and without JavaScript, and use it from the keyboard.
626
+ 3. For an action, submit the form once as a person and once as JSON (`curl -H 'accept: application/json' -d ...`).
627
+ 4. Say what you ran and what you could not run.
628
+
629
+ ## More
630
+
631
+ - What each package does, with examples: its `README.md` in `node_modules/@pexis/<name>/`.
632
+ - The HTML attributes Pexis emits for agents: `node_modules/@pexis/spec/actions.md`.
633
+ - The check rules: `node_modules/@pexis/checks/RULES.md`.
634
+ - Source and issues: https://github.com/pexis-dev/pexis