@pexis/core 0.1.2 → 0.1.3

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 (56) hide show
  1. package/AGENTS.md +53 -10
  2. package/API.md +6 -5
  3. package/README.md +1 -1
  4. package/api.json +5951 -0
  5. package/dist/app.d.ts +77 -3
  6. package/dist/app.js +207 -31
  7. package/dist/app.js.map +1 -1
  8. package/dist/components.d.ts +54 -4
  9. package/dist/components.js +34 -3
  10. package/dist/components.js.map +1 -1
  11. package/dist/context.d.ts +27 -2
  12. package/dist/context.js +18 -2
  13. package/dist/context.js.map +1 -1
  14. package/dist/cors.d.ts +14 -0
  15. package/dist/cors.js +8 -0
  16. package/dist/cors.js.map +1 -1
  17. package/dist/csrf.d.ts +9 -0
  18. package/dist/csrf.js +9 -0
  19. package/dist/csrf.js.map +1 -1
  20. package/dist/form.d.ts +21 -3
  21. package/dist/form.js +38 -4
  22. package/dist/form.js.map +1 -1
  23. package/dist/host.d.ts +6 -1
  24. package/dist/host.js +6 -1
  25. package/dist/host.js.map +1 -1
  26. package/dist/html.d.ts +46 -5
  27. package/dist/html.js +112 -5
  28. package/dist/html.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js.map +1 -1
  31. package/dist/jsx-runtime.d.ts +32 -0
  32. package/dist/jsx-runtime.js +16 -0
  33. package/dist/jsx-runtime.js.map +1 -1
  34. package/dist/page.d.ts +74 -1
  35. package/dist/page.js +48 -5
  36. package/dist/page.js.map +1 -1
  37. package/dist/rate-limit.d.ts +46 -0
  38. package/dist/rate-limit.js +19 -0
  39. package/dist/rate-limit.js.map +1 -1
  40. package/dist/registry.d.ts +126 -3
  41. package/dist/registry.js +53 -1
  42. package/dist/registry.js.map +1 -1
  43. package/dist/schema.d.ts +129 -3
  44. package/dist/schema.js +80 -7
  45. package/dist/schema.js.map +1 -1
  46. package/dist/security.d.ts +38 -2
  47. package/dist/security.js +44 -9
  48. package/dist/security.js.map +1 -1
  49. package/dist/styles.d.ts +37 -2
  50. package/dist/styles.js +32 -2
  51. package/dist/styles.js.map +1 -1
  52. package/dist/types.d.ts +163 -19
  53. package/dist/urls.d.ts +8 -1
  54. package/dist/urls.js +8 -1
  55. package/dist/urls.js.map +1 -1
  56. package/package.json +2 -1
package/dist/app.d.ts CHANGED
@@ -7,15 +7,23 @@ export declare function memoryStateWarning(items: readonly string[], env: {
7
7
  production: boolean;
8
8
  singleInstance: boolean;
9
9
  }): string | null;
10
+ /** What createApp() takes. Only `origin` is required. */
10
11
  export interface AppOptions {
11
12
  /** Public origin, for example https://example.com. */
12
13
  origin: string;
13
- /** Default <html lang>. Default "en". */
14
+ /**
15
+ * Default <html lang>.
16
+ *
17
+ * @default "en"
18
+ */
14
19
  lang?: string;
15
20
  /** Wraps every page body. Default: the body inside <main>. null for no wrapper. */
16
21
  layout?: Layout | null;
22
+ /** The site's pages. With `pexis dev`, the generated `pages` from pexis.gen.ts. */
17
23
  pages?: Page[];
24
+ /** The site's actions. With `pexis dev`, the generated `actions` from pexis.gen.ts. */
18
25
  actions?: Action[];
26
+ /** Plugins, set up in this order. A plugin that needs another lists it in `requires`, and must come after it. */
19
27
  plugins?: Plugin[];
20
28
  /** App middleware, run after plugin middleware. */
21
29
  middleware?: Middleware[];
@@ -31,10 +39,13 @@ export interface AppOptions {
31
39
  navigation?: NavigationOptions;
32
40
  /** Your own pages for "not found" (404) and "something went wrong" (500), in the site's layout. */
33
41
  errorPages?: {
42
+ /** Shown with 404 when no page matches, or a page's load() returns notFound(). */
34
43
  notFound?: ErrorPage;
44
+ /** Shown with 500 when a request fails. The error is logged, never shown. */
35
45
  serverError?: ErrorPage;
36
46
  };
37
47
  }
48
+ /** Navigation the browser does itself, with no JavaScript: page transitions and prefetching. Both off by default. */
38
49
  export interface NavigationOptions {
39
50
  /**
40
51
  * Cross-document View Transitions: browsers animate between pages of this
@@ -50,25 +61,88 @@ export interface NavigationOptions {
50
61
  */
51
62
  prefetch?: false | 'conservative' | 'moderate' | 'eager';
52
63
  }
64
+ /**
65
+ * The Speculation Rules JSON behind `navigation.prefetch`: prefetch same-site
66
+ * links, except the given path prefixes.
67
+ *
68
+ * @category plugins
69
+ * @param eagerness When the browser starts: on press, on hover, or sooner.
70
+ * @param exclude Path prefixes never to prefetch, such as "/auth/".
71
+ */
53
72
  export declare function speculationRules(eagerness: 'conservative' | 'moderate' | 'eager', exclude: readonly string[]): string;
73
+ /** The app createApp() returns: the whole site as one request handler, and what plugins and tools read. */
54
74
  export interface App {
55
75
  /**
56
76
  * The whole site, as one web-standard request handler. Adapters pass what
57
77
  * they know about the connection, such as the client's address.
58
78
  */
59
79
  fetch(request: Request, connection?: Connection): Promise<Response>;
80
+ /** The app's settings. */
60
81
  readonly config: AppConfig;
82
+ /** Every page, plugins' included, in routing order. */
61
83
  readonly pages: readonly Page[];
84
+ /** Every action, plugins' included. */
62
85
  readonly actions: readonly Action[];
63
86
  /** Every public page path, with route parameters filled in. */
64
87
  entries(): Promise<string[]>;
65
88
  /** Check rules from plugins and the app, for @pexis/checks. */
66
89
  readonly checkRules: readonly CheckRuleLike[];
90
+ /**
91
+ * Whether this app has something to say about the request: one of its pages,
92
+ * actions or plugin routes (including the right path with the wrong method).
93
+ * For mounting Pexis inside another server, which handles everything else.
94
+ */
95
+ matches(request: Request): boolean;
67
96
  }
97
+ /** Where agents read the site's tools: `/pexis/actions.json`. Every page names it in a `Link` header. */
68
98
  export declare const TOOLS_PATH = "/pexis/actions.json";
69
- /** Why an agent with a token may not run this action, or null if it may. */
99
+ /**
100
+ * Why an agent with a token may not run this action, or null if it may: it
101
+ * needs the person's approval, is for people only, or is outside the
102
+ * granted scopes. The core applies it to every agent request.
103
+ *
104
+ * @experimental
105
+ * @param agent Who the agent acts for, and what it was granted.
106
+ * @param action The action it wants to run.
107
+ */
70
108
  export declare function agentRefusal(agent: AgentIdentity, action: Action): string | null;
71
- /** Serializes JSON-LD for a script block, adding the schema.org context. */
109
+ /**
110
+ * Serializes JSON-LD for a script block, adding the schema.org context, with
111
+ * `<` escaped so the data cannot close the script.
112
+ *
113
+ * @category plugins
114
+ * @param data schema.org data, without "@context".
115
+ */
72
116
  export declare function jsonLd(data: Record<string, unknown>): string;
117
+ /**
118
+ * Builds the app: pages, actions, layout, plugins, and security and
119
+ * navigation options. The result is one web-standard request handler,
120
+ * `app.fetch(request)`, that an adapter serves on Node, Bun or Cloudflare
121
+ * Workers, or another server mounts. Throws when the options are invalid,
122
+ * such as two pages on one path or two actions with one name.
123
+ *
124
+ * @param options The app's origin, pages, actions, plugins and settings.
125
+ * @example
126
+ * ```ts
127
+ * export default createApp({
128
+ * origin: process.env.SITE_ORIGIN ?? 'http://localhost:3000',
129
+ * layout: site,
130
+ * pages,
131
+ * actions,
132
+ * plugins: [markdown(), openapi(), siteFiles()],
133
+ * });
134
+ * ```
135
+ */
73
136
  export declare function createApp(options: AppOptions): App;
137
+ /**
138
+ * Declares a plugin: a name and a setup function that receives the plugin
139
+ * API. Throws when the name is not valid.
140
+ *
141
+ * @param plugin Its name, the plugins it requires, and setup.
142
+ * @example
143
+ * ```ts
144
+ * const stylesheet = (href: string) =>
145
+ * definePlugin({ name: 'stylesheet', setup: (api) => api.head(() => html`<link rel="stylesheet" href="${href}">`) });
146
+ * ```
147
+ */
74
148
  export declare function definePlugin(plugin: Plugin): Plugin;
package/dist/app.js CHANGED
@@ -4,9 +4,10 @@ import { crossSiteRefusal, isSafeMethod } from './csrf.js';
4
4
  import { renderForm, TARGET_ID } from './form.js';
5
5
  import { IN_PLACE } from './components.js';
6
6
  import { escapeHtml, html, raw, renderToString } from './html.js';
7
+ import { Fragment, jsx } from './jsx-runtime.js';
7
8
  import { checkPath, compilePath, isSignal } from './page.js';
8
9
  import { rateLimiter } from './rate-limit.js';
9
- import { createRegistry, isInvalid } from './registry.js';
10
+ import { createRegistry, describeAction, isInvalid } from './registry.js';
10
11
  import { validate } from './schema.js';
11
12
  import { BodyError, contentSecurityPolicy, createNonce, DEFAULT_ACTION_RATE_LIMIT, DEFAULT_MAX_BODY_BYTES, documentSecurityHeaders, readActionInput, } from './security.js';
12
13
  import { usedStyles } from './styles.js';
@@ -29,6 +30,14 @@ export function memoryStateWarning(items, env) {
29
30
  ].join('\n');
30
31
  }
31
32
  const VIEW_TRANSITIONS = '@view-transition{navigation:auto}@media (prefers-reduced-motion: reduce){::view-transition-group(*),::view-transition-old(*),::view-transition-new(*){animation:none!important}}';
33
+ /**
34
+ * The Speculation Rules JSON behind `navigation.prefetch`: prefetch same-site
35
+ * links, except the given path prefixes.
36
+ *
37
+ * @category plugins
38
+ * @param eagerness When the browser starts: on press, on hover, or sooner.
39
+ * @param exclude Path prefixes never to prefetch, such as "/auth/".
40
+ */
32
41
  export function speculationRules(eagerness, exclude) {
33
42
  return JSON.stringify({
34
43
  prefetch: [
@@ -45,11 +54,20 @@ export function speculationRules(eagerness, exclude) {
45
54
  ],
46
55
  }).replaceAll('<', '\\u003c');
47
56
  }
57
+ /** Where agents read the site's tools: `/pexis/actions.json`. Every page names it in a `Link` header. */
48
58
  export const TOOLS_PATH = '/pexis/actions.json';
49
59
  const ACTION_PATH = /^\/actions\/([a-z][a-z0-9_]{0,63})$/;
50
60
  const PLUGIN_NAME = /^[a-z0-9@][a-z0-9@/._-]*$/;
51
61
  const STATUS = { done: 200, invalid: 422, forbidden: 403, failed: 500 };
52
- /** Why an agent with a token may not run this action, or null if it may. */
62
+ /**
63
+ * Why an agent with a token may not run this action, or null if it may: it
64
+ * needs the person's approval, is for people only, or is outside the
65
+ * granted scopes. The core applies it to every agent request.
66
+ *
67
+ * @experimental
68
+ * @param agent Who the agent acts for, and what it was granted.
69
+ * @param action The action it wants to run.
70
+ */
53
71
  export function agentRefusal(agent, action) {
54
72
  if (action.agents === false)
55
73
  return 'This action is for people only. Use the form on the page.';
@@ -64,9 +82,44 @@ export function agentRefusal(agent, action) {
64
82
  const RISK_ORDER = { read: 0, write: 1, irreversible: 2 };
65
83
  /** Calls one request may make, so actions calling each other in a circle stop. */
66
84
  const MAX_CALLS = 100;
85
+ /** The inputs whose form data carries a list: groups of checkboxes. */
86
+ function listFields(action) {
87
+ return new Set(Object.entries(action.input).filter(([, f]) => f.kind === 'choices').map(([name]) => name));
88
+ }
67
89
  function json(body, status = 200) {
68
90
  return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8' } });
69
91
  }
92
+ /**
93
+ * The result with its link kept only when it stays on this site: a path, or a
94
+ * URL on the app's own origin, stored as a path. Anything else (another site,
95
+ * javascript:, a malformed URL, empty text) is a mistake in the action, so it
96
+ * is dropped and logged rather than rendered.
97
+ */
98
+ function withSafeLink(action, result, ctx) {
99
+ if (result.link === undefined)
100
+ return result;
101
+ const { link, ...rest } = result;
102
+ const href = typeof link?.href === 'string' ? link.href : '';
103
+ const text = typeof link?.text === 'string' ? link.text.trim() : '';
104
+ let url = null;
105
+ if (text && text.length <= 200 && !href.startsWith('//') && !href.includes('\\')) {
106
+ try {
107
+ url = new URL(href, ctx.url);
108
+ }
109
+ catch {
110
+ url = null;
111
+ }
112
+ }
113
+ if (!url || url.origin !== ctx.url.origin) {
114
+ console.error(`[pexis] Action "${action.name}" returned a link that is not on this site, or has no text; it was dropped.`);
115
+ return rest;
116
+ }
117
+ return { ...rest, link: { href: url.pathname + url.search + url.hash, text } };
118
+ }
119
+ /** A result's link as an absolute URL, for agents and JSON. */
120
+ function absoluteLink(result, ctx) {
121
+ return result.link ? { link: { href: new URL(result.link.href, ctx.url).href, text: result.link.text } } : {};
122
+ }
70
123
  function wantsJson(ctx) {
71
124
  return (ctx.request.headers.get('accept') ?? '').includes('application/json');
72
125
  }
@@ -103,7 +156,13 @@ function fragment(target, status, body) {
103
156
  function messageFragment(target, status, message) {
104
157
  return fragment(target, status, html `<p class="px-result" tabindex="-1">${message}</p>`);
105
158
  }
106
- /** Serializes JSON-LD for a script block, adding the schema.org context. */
159
+ /**
160
+ * Serializes JSON-LD for a script block, adding the schema.org context, with
161
+ * `<` escaped so the data cannot close the script.
162
+ *
163
+ * @category plugins
164
+ * @param data schema.org data, without "@context".
165
+ */
107
166
  export function jsonLd(data) {
108
167
  // Escaping "<" stops a value such as "</script>" from ending the block.
109
168
  return JSON.stringify({ '@context': 'https://schema.org', ...data }).replaceAll('<', '\\u003c');
@@ -114,7 +173,79 @@ function backLink(ctx) {
114
173
  return referer;
115
174
  return '/';
116
175
  }
176
+ // After a people-only action, the person goes back to the page they were on
177
+ // (Post/Redirect/Get) and sees the outcome there once. The message travels in
178
+ // a short-lived HttpOnly cookie, never the URL, since it can hold personal
179
+ // details. It is shown escaped, so even an edited cookie is only text.
180
+ const NOTICE_MAX = 1000;
181
+ function noticeCookieName(origin) {
182
+ return origin.startsWith('https://') ? '__Host-pexis_notice' : 'pexis_notice';
183
+ }
184
+ function noticeCookie(origin, value, maxAge) {
185
+ return [`${noticeCookieName(origin)}=${value}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAge}`, origin.startsWith('https://') ? 'Secure' : ''].filter(Boolean).join('; ');
186
+ }
187
+ function readCookie(header, name) {
188
+ for (const part of (header ?? '').split(';')) {
189
+ const at = part.indexOf('=');
190
+ if (at !== -1 && part.slice(0, at).trim() === name)
191
+ return part.slice(at + 1).trim();
192
+ }
193
+ return undefined;
194
+ }
195
+ /** The page a people-only form was sent from, when it is a page of this site. */
196
+ function returnPage(ctx) {
197
+ const referer = ctx.request.headers.get('referer');
198
+ if (!referer || !URL.canParse(referer))
199
+ return null;
200
+ const url = new URL(referer);
201
+ if (url.origin !== ctx.url.origin || url.pathname.startsWith('/actions/') || url.pathname.startsWith('/pexis/'))
202
+ return null;
203
+ return url.pathname + url.search;
204
+ }
205
+ function encodeNotice(notice) {
206
+ const bytes = new TextEncoder().encode(JSON.stringify(notice));
207
+ let binary = '';
208
+ for (const b of bytes)
209
+ binary += String.fromCharCode(b);
210
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
211
+ }
212
+ function decodeNotice(value) {
213
+ if (!value || value.length > NOTICE_MAX * 2 || !/^[A-Za-z0-9_-]+$/.test(value))
214
+ return null;
215
+ try {
216
+ const binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));
217
+ const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))));
218
+ if (typeof parsed.message !== 'string' || !parsed.message)
219
+ return null;
220
+ const link = parsed.link;
221
+ // A link is rendered only as a path on this site, whatever the cookie says.
222
+ const safe = link && typeof link.href === 'string' && typeof link.text === 'string' && link.href.startsWith('/') && !link.href.startsWith('//') && !link.href.includes('\\');
223
+ return { message: parsed.message.slice(0, NOTICE_MAX), ...(safe ? { link: { href: link.href, text: link.text.slice(0, 200) } } : {}) };
224
+ }
225
+ catch {
226
+ return null;
227
+ }
228
+ }
117
229
  const defaultLayout = { kind: 'layout', render: ({ children }) => html `<main>${children}</main>` };
230
+ /**
231
+ * Builds the app: pages, actions, layout, plugins, and security and
232
+ * navigation options. The result is one web-standard request handler,
233
+ * `app.fetch(request)`, that an adapter serves on Node, Bun or Cloudflare
234
+ * Workers, or another server mounts. Throws when the options are invalid,
235
+ * such as two pages on one path or two actions with one name.
236
+ *
237
+ * @param options The app's origin, pages, actions, plugins and settings.
238
+ * @example
239
+ * ```ts
240
+ * export default createApp({
241
+ * origin: process.env.SITE_ORIGIN ?? 'http://localhost:3000',
242
+ * layout: site,
243
+ * pages,
244
+ * actions,
245
+ * plugins: [markdown(), openapi(), siteFiles()],
246
+ * });
247
+ * ```
248
+ */
118
249
  export function createApp(options) {
119
250
  if (!/^https?:\/\//.test(options.origin) || !URL.canParse(options.origin)) {
120
251
  throw new Error(`createApp: origin "${options.origin}" must be an absolute http(s) URL, such as https://example.com.`);
@@ -147,6 +278,7 @@ export function createApp(options) {
147
278
  // Paths where a visit has an effect or is private, never prefetched.
148
279
  const prefetchExclusions = new Set(['/actions/', '/pexis/']);
149
280
  const pluginMiddleware = [];
281
+ const answerers = [];
150
282
  const heads = [];
151
283
  const bodyEnds = [];
152
284
  const listeners = [];
@@ -183,7 +315,11 @@ export function createApp(options) {
183
315
  const seen = new Set();
184
316
  const api = {
185
317
  config,
186
- use: (mw) => void pluginMiddleware.push(mw),
318
+ use: (mw, useOptions) => {
319
+ pluginMiddleware.push(mw);
320
+ if (useOptions?.answers)
321
+ answerers.push(useOptions.answers);
322
+ },
187
323
  maxBodyBytes,
188
324
  noPrefetch: (prefix) => {
189
325
  if (!/^\/[A-Za-z0-9._~/-]*\/$/.test(prefix))
@@ -231,7 +367,6 @@ export function createApp(options) {
231
367
  },
232
368
  entries: () => entries(),
233
369
  fetch: (request, connection) => app.fetch(request, connection),
234
- renderPage: (path, ctx) => renderPageAt(path, ctx),
235
370
  };
236
371
  for (const plugin of options.plugins ?? []) {
237
372
  if (!PLUGIN_NAME.test(plugin.name))
@@ -253,6 +388,7 @@ export function createApp(options) {
253
388
  console.warn(memoryWarning);
254
389
  // Validates names and catches duplicate actions.
255
390
  const registry = createRegistry(actions);
391
+ const offersTools = registry.describe().length > 0;
256
392
  // Undo actions must be this app's own, and something must keep the records:
257
393
  // a declared undo with nowhere to record it would promise what cannot happen.
258
394
  const undoTargets = new Set();
@@ -378,6 +514,9 @@ export function createApp(options) {
378
514
  const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });
379
515
  if (!doc.index)
380
516
  headers.set('x-robots-tag', 'noindex');
517
+ // Agents find the site's actions from any page's headers, even with a HEAD request.
518
+ if (offersTools)
519
+ headers.append('link', `<${TOOLS_PATH}>; rel="service-desc"; type="application/json"`);
381
520
  documentSecurityHeaders(headers, config.origin, cspExtra === false ? null : contentSecurityPolicy(ctx.nonce, cspExtra ?? {}));
382
521
  return headers;
383
522
  }
@@ -481,9 +620,21 @@ export function createApp(options) {
481
620
  return signalResponse(data, ctx);
482
621
  }
483
622
  const head = typeof page.head === 'function' ? page.head(data, ctx) : page.head;
623
+ let body = page.render({ data, ctx, params: ctx.params });
624
+ // The outcome of a people-only action, shown once at the top of the page
625
+ // it was sent from. Focused on load, with no role: a screen reader reads a
626
+ // focused element in full (a focused role="status" is read by NVDA only
627
+ // as "status bar"), and the page works without script.
628
+ const notice = ctx.request.method === 'GET' ? decodeNotice(readCookie(ctx.request.headers.get('cookie'), noticeCookieName(config.origin))) : null;
629
+ if (notice) {
630
+ const link = notice.link ? html ` <a href="${notice.link.href}">${notice.link.text}</a>` : '';
631
+ body = jsx(Fragment, { children: [html `<p class="px-notice" tabindex="-1" autofocus>${notice.message}${link}</p>`, body] });
632
+ ctx.response.headers.append('set-cookie', noticeCookie(config.origin, '', 0));
633
+ ctx.response.headers.set('cache-control', 'private, no-store');
634
+ }
484
635
  const doc = {
485
636
  head,
486
- body: page.render({ data, ctx, params: ctx.params }),
637
+ body,
487
638
  layout: page.layout === undefined ? appLayout : page.layout,
488
639
  lang: page.lang ?? ctx.lang ?? config.lang,
489
640
  index: page.index,
@@ -539,18 +690,6 @@ export function createApp(options) {
539
690
  await runWithContext(pageCtx, () => run(0));
540
691
  return captured;
541
692
  }
542
- async function renderPageAt(path, ctx) {
543
- // Only a path on this site: "//host" or "https://host" would resolve elsewhere.
544
- if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
545
- return null;
546
- const url = new URL(path, ctx.url);
547
- const rewritten = applyRewrites(url);
548
- const found = matchPage(rewritten.pathname);
549
- if (!found)
550
- return null;
551
- const pageCtx = { ...ctx, ...rewritten.context, url, params: found.params, route: { kind: 'page', page: found.page, params: found.params } };
552
- return runWithContext(pageCtx, () => pageResponse(found.page, pageCtx));
553
- }
554
693
  // --- Actions -----------------------------------------------------------------
555
694
  function emit(event) {
556
695
  for (const listener of listeners) {
@@ -602,7 +741,7 @@ export function createApp(options) {
602
741
  }
603
742
  return { kind: 'invalid', errors: { ...result.errors }, values: input };
604
743
  }
605
- return { kind: 'done', result };
744
+ return { kind: 'done', result: withSafeLink(action, result, ctx) };
606
745
  }
607
746
  catch (error) {
608
747
  console.error(`[pexis] Action "${action.name}" failed:`, withoutValues(error, input));
@@ -664,10 +803,10 @@ export function createApp(options) {
664
803
  console.error(`[pexis] Could not mark writes undone after "${action.name}":`, error.message);
665
804
  }
666
805
  }
667
- function actionJson(outcome) {
806
+ function actionJson(outcome, ctx) {
668
807
  switch (outcome.kind) {
669
808
  case 'done':
670
- return json({ ok: true, message: outcome.result.message, data: outcome.result.data }, 200);
809
+ return json({ ok: true, message: outcome.result.message, data: outcome.result.data, ...absoluteLink(outcome.result, ctx) }, 200);
671
810
  case 'invalid':
672
811
  return json({ ok: false, message: 'Some values need fixing.', errors: outcome.errors }, 422);
673
812
  case 'forbidden':
@@ -681,7 +820,7 @@ export function createApp(options) {
681
820
  const status = STATUS[outcome.kind];
682
821
  switch (outcome.kind) {
683
822
  case 'done':
684
- return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="status">${outcome.result.message}</p><p><a href="${back}">Back</a></p>`);
823
+ return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="status">${outcome.result.message}</p>${outcome.result.link ? html `<p><a href="${outcome.result.link.href}">${outcome.result.link.text}</a></p>` : ''}<p><a href="${back}">Back</a></p>`);
685
824
  case 'invalid':
686
825
  return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="alert">Some values need fixing.</p>${renderForm(action, { values: outcome.values, errors: outcome.errors })}`);
687
826
  case 'forbidden':
@@ -697,13 +836,17 @@ export function createApp(options) {
697
836
  * it, with any errors; after success, a copy the page gives its own values
698
837
  * (a saved setting, a row's id) keeps them. When the page cannot be rendered again, the
699
838
  * message alone: the page keeps its form. Focus goes to the message, or to
700
- * the first field with an error, so only the success message is a live region.
839
+ * the first field with an error.
701
840
  */
702
841
  async function actionFragment(action, outcome, ctx, target, input) {
703
842
  const status = STATUS[outcome.kind];
704
- const message = outcome.kind === 'done'
705
- ? html `<p class="px-result" role="status" tabindex="-1">${outcome.result.message}</p>`
706
- : html `<p class="px-result" tabindex="-1">${outcome.kind === 'invalid' ? 'Some values need fixing.' : outcome.kind === 'forbidden' ? 'You are not allowed to do this.' : 'Something went wrong. Nothing was changed. Please try again.'}</p>`;
843
+ // No role="status": the script moves focus to the message, and focus alone
844
+ // is read everywhere. NVDA announces a focused status only as "status bar",
845
+ // without its text (PEX-74, heard with real NVDA and VoiceOver in CI).
846
+ const text = outcome.kind === 'done' ? outcome.result.message : outcome.kind === 'invalid' ? 'Some values need fixing.' : outcome.kind === 'forbidden' ? 'You are not allowed to do this.' : 'Something went wrong. Nothing was changed. Please try again.';
847
+ // A link goes inside the message, so moving focus there reads both.
848
+ const link = outcome.kind === 'done' && outcome.result.link ? html ` <a href="${outcome.result.link.href}">${outcome.result.link.text}</a>` : '';
849
+ const message = html `<p class="px-result" tabindex="-1">${text}${link}</p>`;
707
850
  const state = outcome.kind === 'invalid' ? { values: outcome.values, errors: outcome.errors } : { values: input };
708
851
  // Px-Form: which copy of this action's form in the region was sent, so only it shows the values.
709
852
  const index = Number(ctx.request.headers.get('px-form') ?? '0');
@@ -767,7 +910,7 @@ export function createApp(options) {
767
910
  }
768
911
  let input;
769
912
  try {
770
- input = await readActionInput(ctx.request, ctx.url, maxBodyBytes);
913
+ input = await readActionInput(ctx.request, ctx.url, maxBodyBytes, listFields(action));
771
914
  }
772
915
  catch (error) {
773
916
  if (error instanceof BodyError)
@@ -792,7 +935,15 @@ export function createApp(options) {
792
935
  fields: Object.keys(input).filter((key) => Object.hasOwn(action.input, key)),
793
936
  userAgent: ctx.request.headers.get('user-agent'),
794
937
  });
795
- const response = viaJson ? actionJson(outcome) : target ? await actionFragment(action, outcome, ctx, target, input) : await actionHtml(action, outcome, ctx);
938
+ const back = !viaJson && action.agents === false && outcome.kind === 'done' ? returnPage(ctx) : null;
939
+ const notice = outcome.kind === 'done' ? encodeNotice({ message: outcome.result.message.slice(0, NOTICE_MAX), ...(outcome.result.link ? { link: outcome.result.link } : {}) }) : '';
940
+ const response = back && notice.length <= NOTICE_MAX * 2
941
+ ? new Response(null, { status: 303, headers: { location: back, 'set-cookie': noticeCookie(config.origin, notice, 60) } })
942
+ : viaJson
943
+ ? actionJson(outcome, ctx)
944
+ : target
945
+ ? await actionFragment(action, outcome, ctx, target, input)
946
+ : await actionHtml(action, outcome, ctx);
796
947
  // Results can hold personal data (a booking reference, a name): never cached.
797
948
  response.headers.set('cache-control', 'no-store');
798
949
  return response;
@@ -835,7 +986,7 @@ export function createApp(options) {
835
986
  });
836
987
  switch (outcome.kind) {
837
988
  case 'done':
838
- return { ok: true, message: outcome.result.message, data: outcome.result.data };
989
+ return { ok: true, message: outcome.result.message, data: outcome.result.data, ...absoluteLink(outcome.result, ctx) };
839
990
  case 'invalid':
840
991
  return { ok: false, outcome: 'invalid', message: 'Some values need fixing.', errors: outcome.errors };
841
992
  case 'forbidden':
@@ -851,7 +1002,8 @@ export function createApp(options) {
851
1002
  const route = ctx.route;
852
1003
  switch (route.kind) {
853
1004
  case 'builtin':
854
- return json({ tools: registry.describe() });
1005
+ // Each tool says where to send it, so an agent can call it without the page.
1006
+ return json({ tools: registry.list().filter((a) => a.agents !== false).map((a) => ({ ...describeAction(a), url: `/actions/${a.name}`, method: a.method })) });
855
1007
  case 'action':
856
1008
  return actionResponse(route.action, ctx);
857
1009
  case 'route':
@@ -1041,7 +1193,20 @@ export function createApp(options) {
1041
1193
  response = new Response(null, { status: response.status, headers: response.headers });
1042
1194
  return response;
1043
1195
  }
1044
- app = Object.freeze({ fetch, config, pages: orderedPages, actions: registry.list(), entries, checkRules });
1196
+ function matches(request) {
1197
+ const url = new URL(request.url);
1198
+ const method = request.method === 'HEAD' ? 'GET' : request.method;
1199
+ const { pathname } = applyRewrites(url);
1200
+ const route = matchRoute(method, pathname);
1201
+ if (route.kind !== 'none' || route.allow)
1202
+ return true;
1203
+ // Middleware sees the request as sent, before rewrites.
1204
+ if (answerers.some((answers) => answers(url, method)))
1205
+ return true;
1206
+ // "/menu/" is answered with a redirect to "/menu" when that is a page.
1207
+ return method === 'GET' && pathname.length > 1 && pathname.endsWith('/') && Boolean(matchPage(pathname.replace(/\/+$/, '')));
1208
+ }
1209
+ app = Object.freeze({ fetch, config, pages: orderedPages, actions: registry.list(), entries, checkRules, matches });
1045
1210
  return app;
1046
1211
  }
1047
1212
  /**
@@ -1070,6 +1235,17 @@ function withoutValues(error, input) {
1070
1235
  text = text.split(value).join('[value removed]');
1071
1236
  return text;
1072
1237
  }
1238
+ /**
1239
+ * Declares a plugin: a name and a setup function that receives the plugin
1240
+ * API. Throws when the name is not valid.
1241
+ *
1242
+ * @param plugin Its name, the plugins it requires, and setup.
1243
+ * @example
1244
+ * ```ts
1245
+ * const stylesheet = (href: string) =>
1246
+ * definePlugin({ name: 'stylesheet', setup: (api) => api.head(() => html`<link rel="stylesheet" href="${href}">`) });
1247
+ * ```
1248
+ */
1073
1249
  export function definePlugin(plugin) {
1074
1250
  if (!PLUGIN_NAME.test(plugin.name))
1075
1251
  throw new Error(`Plugin name "${plugin.name}" is not valid.`);