@plitzi/sdk-authoring 0.38.13 → 0.38.15

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.
package/dist/node.d.ts CHANGED
@@ -1094,6 +1094,8 @@ declare const AUTHORING_CODES: {
1094
1094
 
1095
1095
  declare type AuthoringCode = keyof Codes;
1096
1096
 
1097
+ export declare const authorIsolated: (file: string, options?: IsolatedOptions) => Promise<IsolatedAuthoring>;
1098
+
1097
1099
  /**
1098
1100
  * The project's space, authored: what a project's server serves — `serveProject({ space: authorProjectSpace })` — and
1099
1101
  * its visual tests read. `projectSpace`, then `authorSpace` with what it is checked against.
@@ -1187,6 +1189,13 @@ declare type ChannelDeclaration = {
1187
1189
  * a locked board.
1188
1190
  */
1189
1191
  grant?: boolean;
1192
+ /**
1193
+ * Whether the server keeps the latest message of each type on a topic, and hands them to every page that joins: state
1194
+ * all the screens share — a dashboard's lists, a board's settings — said once by the server (`ctx.publish`, a flow's
1195
+ * `realtime.publish`) and there for a page that opens later, as `<channel>.retained.<type>`. Kept until the next of
1196
+ * its type; `null` forgets it. Only on a channel the server alone publishes on (`publish: 'server'`).
1197
+ */
1198
+ retain?: boolean;
1190
1199
  /** The largest `data` a page may send, as JSON bytes. 4 KB when absent. */
1191
1200
  maxMessageBytes?: number;
1192
1201
  /** How many messages one connection may send a second. 30 when absent. */
@@ -1314,6 +1323,14 @@ declare type CssSpec = CssInput | ResponsiveCss;
1314
1323
 
1315
1324
  declare type DisplayMode = 'desktop' | 'tablet' | 'mobile';
1316
1325
 
1326
+ /**
1327
+ * How the document holding a page moves under a finger or a wheel, when the page says so — see
1328
+ * `PageProps.documentScroll`. Read by the authoring surface to refuse anything else.
1329
+ */
1330
+ declare const DOCUMENT_SCROLLS: readonly ["locked", "noBounce"];
1331
+
1332
+ declare type DocumentScroll = (typeof DOCUMENT_SCROLLS)[number];
1333
+
1317
1334
  /**
1318
1335
  * An element, keyed by the one name it answers to.
1319
1336
  *
@@ -1446,6 +1463,12 @@ declare interface ElementHandle {
1446
1463
  * Present only when true: almost nothing on a page is conditional, and the handles are serialized.
1447
1464
  */
1448
1465
  conditional?: true;
1466
+ /**
1467
+ * For an element an element that chooses its children (`choosesChildren`) may draw — one of those children, or what
1468
+ * is inside one under no condition of its own: that child, by id. It is `conditional`, since a bare visit owes none
1469
+ * of it; once the child is drawn, it and everything it holds are owed like the rest of the page.
1470
+ */
1471
+ shownWith?: string;
1449
1472
  /**
1450
1473
  * Whether this element sits inside a list's row, so it renders once per row — several times, or not at all while the
1451
1474
  * list is empty. Its selector matches every copy: address one with the driver's `.first()` / `.nth()`.
@@ -1707,6 +1730,53 @@ declare type InteractionCallbackType = 'trigger' | 'globalCallback' | 'callback'
1707
1730
 
1708
1731
  declare type InteractionParamType = 'boolean' | 'select' | 'text' | 'number' | 'textarea' | 'codemirror-text' | 'codemirror-json' | 'elements';
1709
1732
 
1733
+ export declare type IsolatedAuthoring = {
1734
+ ok: true;
1735
+ space: AuthoredSpace;
1736
+ }
1737
+ /** `authorSpace` refused it: `message` is its report, `refusals` the problems as data. */
1738
+ | {
1739
+ ok: false;
1740
+ reason: 'refused';
1741
+ message: string;
1742
+ refusals: SpaceRefusal[];
1743
+ }
1744
+ /**
1745
+ * `failed`: the module did not load, exports no `space`, or its process died — `message` says which, and where;
1746
+ * `timeout`: it ran past `timeoutMs`; `invalid`: what it answered is not a space `validateSpace` passes.
1747
+ */
1748
+ | {
1749
+ ok: false;
1750
+ reason: 'failed' | 'timeout' | 'invalid';
1751
+ message: string;
1752
+ };
1753
+
1754
+ /**
1755
+ * A space module somebody else wrote — an agent's, a visitor's — authored in a process of its own, which may read the
1756
+ * module's folder and the packages it imports and nothing else: no file written, no process or worker started, no
1757
+ * native addon, no environment variable of this one. What it answers is checked again here (`validateSpace`), so a
1758
+ * module that forges its own answer gains nothing by it.
1759
+ *
1760
+ * Network access is not one Node's permission model takes away before Node 25: serve what it authors on an origin of
1761
+ * its own (`createAuthoringHost` of `@plitzi/sdk-server`), never the app's, and do not run it where the network it
1762
+ * reaches is one to keep it from.
1763
+ *
1764
+ * ```ts
1765
+ * const result = await authorIsolated('tmp/pages/weather.ts');
1766
+ * if (result.ok) {
1767
+ * host.put(result.space);
1768
+ * } else {
1769
+ * reply(result.message); // a refusal reads as `authorSpace`'s: every problem, where it is and what to write
1770
+ * }
1771
+ * ```
1772
+ */
1773
+ export declare interface IsolatedOptions {
1774
+ /** How long the module may take, loaded and authored, before its process is killed. 10 s by default. */
1775
+ timeoutMs?: number;
1776
+ /** The most memory its process may hold, in MB. 512 by default. */
1777
+ memoryMb?: number;
1778
+ }
1779
+
1710
1780
  /**
1711
1781
  * A space's keyframes as an author writes them: by name, each frame keyed by its offset — `from`, `to`, `'50%'`,
1712
1782
  * `'0%, 100%'` — and its rules as any other CSS is written, shorthands allowed:
@@ -1912,6 +1982,14 @@ declare interface PageSpec {
1912
1982
  * navigation.routeParams.slug)) }}'`.
1913
1983
  */
1914
1984
  notFound?: string;
1985
+ /**
1986
+ * How the document moves while this page is on it. Left out, it scrolls as any page does. `'noBounce'` keeps the
1987
+ * scroll and takes away what a finger pulls past either end — iOS's rubber band, pull-to-refresh. `'locked'` holds it
1988
+ * still: a screen that fills the window — a dashboard, a board — where only the panels that scroll on their own
1989
+ * (`overflow: 'auto'`) move, and a finger dragged anywhere else no longer pulls the whole page. Never written onto a
1990
+ * document the space is embedded in.
1991
+ */
1992
+ documentScroll?: DocumentScroll;
1915
1993
  /**
1916
1994
  * Who this page is FOR, and the trap is that omitting it is not the same as `public`.
1917
1995
  *
@@ -1960,6 +2038,11 @@ declare interface PluginDeclarationData {
1960
2038
  sourceType?: string;
1961
2039
  /** Behaviour rather than content: it draws nothing on a page, so no check waits for it on screen. */
1962
2040
  drawsNothing?: boolean;
2041
+ /**
2042
+ * It shows only some of its children, chosen as it runs: no check waits for any of them on screen, and the ones it
2043
+ * draws are checked like the rest of the page.
2044
+ */
2045
+ choosesChildren?: boolean;
1963
2046
  /** The events it fires beyond the ones every element does, by action. */
1964
2047
  triggers?: Readonly<Record<string, {
1965
2048
  action: string;
@@ -2390,6 +2473,17 @@ declare interface SpaceHandles {
2390
2473
  page(idOrSlug: string): PageHandle;
2391
2474
  }
2392
2475
 
2476
+ /** One element `authorSpace` could not write: where to find it, and why. */
2477
+ declare type SpaceRefusal = {
2478
+ /** The nearest named element and the steps from it — `"store-footer" › container[1]`. Empty for the space itself. */
2479
+ place: string;
2480
+ /** The line of the author's own code that wrote it — `src/space/layout.ts:417` — when a factory recorded one. */
2481
+ at?: string;
2482
+ /** What `authoring-errors.md` files it under — a code of `AUTHORING_CODES`, or a structural one of `validateSchema`. */
2483
+ code?: string;
2484
+ message: string;
2485
+ };
2486
+
2393
2487
  declare interface SpaceSpec {
2394
2488
  name: string;
2395
2489
  permanentUrl: string;
package/dist/node.js CHANGED
@@ -1,7 +1,8 @@
1
- import { Yr as e, hn as e$1, n as authorSpace, p as compactSvg } from "./index-src.js";
1
+ import { ei as e, gn as e$1, l as validateSpace, n as authorSpace, p as compactSvg, yn as buildHandles } from "./index-src.js";
2
2
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
3
3
  import m from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { spawn } from "node:child_process";
5
6
  var r = `plitzi/author.ts`;
6
7
  var i$1 = "src/space";
7
8
  var a$1 = `${i$1}/index.ts`;
@@ -473,6 +474,209 @@ var l = (n, r, i) => {
473
474
  return m.join(n, o ? m.join(v$1, m.relative("src", r)).replace(/\.tsx?$/, ".js") : r);
474
475
  };
475
476
  //#endregion
477
+ //#region src/isolated.ts
478
+ /** The `node_modules` nearest the module that has `@plitzi/sdk-authoring` in it: where its imports resolve. */
479
+ var modulesOf = (dir) => {
480
+ for (let at = dir;; at = m.dirname(at)) {
481
+ if (existsSync(m.join(at, "node_modules", "@plitzi", "sdk-authoring"))) return m.join(at, "node_modules");
482
+ if (m.dirname(at) === at) return;
483
+ }
484
+ };
485
+ /**
486
+ * What the process may read: the module's folder, the packages it imports, and — where a package is linked in from
487
+ * elsewhere (a workspace) — the folder it really is in, which is the path Node reads it by.
488
+ */
489
+ var readable = (dir, modules) => {
490
+ const linked = readdirSync(m.join(modules, "@plitzi")).map((name) => realpathSync(m.join(modules, "@plitzi", name)));
491
+ return [.../* @__PURE__ */ new Set([
492
+ dir,
493
+ modules,
494
+ realpathSync(modules),
495
+ ...linked
496
+ ])];
497
+ };
498
+ /**
499
+ * The module's process: imports it, authors its `space` with the copy of `@plitzi/sdk-authoring` the module itself
500
+ * imports — one copy, so the marks a factory leaves on what it makes are read by the code that made them — and sends
501
+ * back what it answered.
502
+ */
503
+ var runner = (file) => `
504
+ const FILE = ${JSON.stringify(pathToFileURL(file).href)};
505
+ const NAME = ${JSON.stringify(m.basename(file))};
506
+ const send = message => new Promise(resolve => process.send(message, () => resolve()));
507
+ const firstLine = error => String(error instanceof Error ? error.message : error).split('\\n')[0];
508
+ const located = error => {
509
+ const frame = String(error instanceof Error ? error.stack ?? '' : '')
510
+ .split('\\n')
511
+ .map(line => /(file:\\/\\/[^\\s:()]+):(\\d+)/.exec(line))
512
+ .find(match => match && match[1] === FILE);
513
+
514
+ return frame ? NAME + ':' + frame[2] + ': ' + firstLine(error) : NAME + ': ' + firstLine(error);
515
+ };
516
+ try {
517
+ const { authorSpace } = await import('@plitzi/sdk-authoring');
518
+ let loaded;
519
+ try {
520
+ loaded = await import(FILE);
521
+ } catch (error) {
522
+ if (error instanceof Error && (error.name === 'AuthoringError' || error.name === 'SpaceRefusedError')) {
523
+ throw error;
524
+ }
525
+
526
+ await send({ ok: false, reason: 'failed', message: located(error) });
527
+ process.exit(0);
528
+ }
529
+
530
+ const space = loaded && loaded.space;
531
+ if (!space || typeof space !== 'object') {
532
+ await send({
533
+ ok: false,
534
+ reason: 'failed',
535
+ message: NAME + ' exports no \`space\`: \`export const space: SpaceSpec = { name, permanentUrl, pages, … }\`'
536
+ });
537
+ process.exit(0);
538
+ }
539
+
540
+ const { schema, style, handles, warnings, suggestions } = authorSpace(space);
541
+ await send({ ok: true, space: { schema, style, handles, warnings, suggestions } });
542
+ } catch (error) {
543
+ await send(
544
+ error instanceof Error && error.name === 'SpaceRefusedError'
545
+ ? { ok: false, reason: 'refused', message: error.message, refusals: error.refusals }
546
+ : { ok: false, reason: 'failed', message: located(error) }
547
+ );
548
+ }
549
+ process.exit(0);
550
+ `;
551
+ /** What the process answered, read for its shape and the space checked again: nothing it says is taken on trust. */
552
+ var readAnswer = (answer) => {
553
+ if (!e(answer) || typeof answer.ok !== "boolean") return;
554
+ if (!answer.ok) {
555
+ const message = typeof answer.message === "string" ? answer.message : "The module was not authored";
556
+ return answer.reason === "refused" && Array.isArray(answer.refusals) ? {
557
+ ok: false,
558
+ reason: "refused",
559
+ message,
560
+ refusals: answer.refusals.filter(isRefusal)
561
+ } : {
562
+ ok: false,
563
+ reason: "failed",
564
+ message
565
+ };
566
+ }
567
+ const space = answer.space;
568
+ if (!isWireAuthored(space)) return {
569
+ ok: false,
570
+ reason: "invalid",
571
+ message: "The module answered something that is not a space"
572
+ };
573
+ let checked;
574
+ try {
575
+ checked = validateSpace({
576
+ schema: space.schema,
577
+ style: space.style
578
+ });
579
+ } catch (error) {
580
+ return {
581
+ ok: false,
582
+ reason: "invalid",
583
+ message: `The space the module answered is not one: ${error instanceof Error ? error.message : String(error)}`
584
+ };
585
+ }
586
+ if (!checked.valid) return {
587
+ ok: false,
588
+ reason: "invalid",
589
+ message: `The space the module answered does not validate: ${checked.errors.map((error) => error.message).join("; ")}`
590
+ };
591
+ return {
592
+ ok: true,
593
+ space: {
594
+ ...space,
595
+ handles: buildHandles(space.handles.pages, space.handles.layouts)
596
+ }
597
+ };
598
+ };
599
+ var isRefusal = (value) => e(value) && typeof value.message === "string" && typeof value.place === "string";
600
+ /**
601
+ * The shape of that answer. The documents are what `validateSpace` checks; the rest is what the author said about them,
602
+ * read by whoever asked.
603
+ */
604
+ var isWireAuthored = (value) => e(value) && e(value.schema) && e(value.style) && e(value.handles) && e(value.handles.pages) && e(value.handles.layouts) && Array.isArray(value.warnings) && Array.isArray(value.suggestions);
605
+ var authorIsolated = (file, options = {}) => {
606
+ const { timeoutMs = 1e4, memoryMb = 512 } = options;
607
+ const module = m.resolve(file);
608
+ if (!existsSync(module)) return Promise.resolve({
609
+ ok: false,
610
+ reason: "failed",
611
+ message: `${file} does not exist`
612
+ });
613
+ const dir = m.dirname(module);
614
+ const modules = modulesOf(dir);
615
+ if (!modules) return Promise.resolve({
616
+ ok: false,
617
+ reason: "failed",
618
+ message: `No @plitzi/sdk-authoring is installed where ${file} is: put the module inside the project that installs it`
619
+ });
620
+ const reads = readable(realpathSync(dir), modules);
621
+ return new Promise((resolve) => {
622
+ const child = spawn(process.execPath, [
623
+ "--permission",
624
+ ...reads.map((read) => `--allow-fs-read=${read}`),
625
+ `--max-old-space-size=${String(memoryMb)}`,
626
+ "--input-type=module",
627
+ "-e",
628
+ runner(realpathSync(module))
629
+ ], {
630
+ cwd: dir,
631
+ env: {},
632
+ stdio: [
633
+ "ignore",
634
+ "ignore",
635
+ "pipe",
636
+ "ipc"
637
+ ]
638
+ });
639
+ let answer;
640
+ let stderr = "";
641
+ let timedOut = false;
642
+ const timer = setTimeout(() => {
643
+ timedOut = true;
644
+ child.kill("SIGKILL");
645
+ }, timeoutMs);
646
+ child.on("message", (message) => {
647
+ answer = message;
648
+ });
649
+ child.stderr?.setEncoding("utf8");
650
+ child.stderr?.on("data", (chunk) => {
651
+ stderr = (stderr + chunk).slice(-2e3);
652
+ });
653
+ child.on("error", (error) => {
654
+ clearTimeout(timer);
655
+ resolve({
656
+ ok: false,
657
+ reason: "failed",
658
+ message: `The module's process did not start: ${error.message}`
659
+ });
660
+ });
661
+ child.on("close", (code) => {
662
+ clearTimeout(timer);
663
+ if (timedOut) {
664
+ resolve({
665
+ ok: false,
666
+ reason: "timeout",
667
+ message: `${file} took longer than ${String(timeoutMs)} ms to author`
668
+ });
669
+ return;
670
+ }
671
+ resolve(readAnswer(answer) ?? {
672
+ ok: false,
673
+ reason: "failed",
674
+ message: `The module's process ended (${String(code)}) without an answer${stderr.trim() ? `: ${stderr.trim()}` : ""}`
675
+ });
676
+ });
677
+ });
678
+ };
679
+ //#endregion
476
680
  //#region src/node.ts
477
681
  /**
478
682
  * What only an author running on Node can do: read the project's own files. A separate entry, so the package's main
@@ -699,4 +903,4 @@ var authorProjectSpace = async () => {
699
903
  return authorSpace(space, authoring);
700
904
  };
701
905
  //#endregion
702
- export { ProjectModuleError, ProjectSpaceError, authorProjectSpace, compactSvg, moduleProblem, pluginDeclarations, pluginFolders, projectAuthoring, projectAuthoringAt, projectData, projectSpace, projectSpaceAt, publicData, svgFile, svgFiles };
906
+ export { ProjectModuleError, ProjectSpaceError, authorIsolated, authorProjectSpace, compactSvg, moduleProblem, pluginDeclarations, pluginFolders, projectAuthoring, projectAuthoringAt, projectData, projectSpace, projectSpaceAt, publicData, svgFile, svgFiles };
package/dist/plugin.d.ts CHANGED
@@ -150,6 +150,13 @@ export declare interface ElementDeclarationData {
150
150
  * `plitzi page check`), which would otherwise wait for it to be on screen and report it hidden.
151
151
  */
152
152
  drawsNothing?: boolean;
153
+ /**
154
+ * Whether the element shows only some of the children put inside it, chosen as it runs — a dashboard showing the
155
+ * panels of the layout saved for this device, a wizard its current step. Read by the page checks, which then owe none
156
+ * of them on screen; the ones it draws are checked like the rest of the page — there, visible, and what is named
157
+ * inside them too.
158
+ */
159
+ choosesChildren?: boolean;
153
160
  /**
154
161
  * The attributes the page server evaluates against a context of its own, never where the element renders: a
155
162
  * provider's `notFound`, read against its answer; a page's title and description, read against its server providers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-authoring",
3
- "version": "0.38.13",
3
+ "version": "0.38.15",
4
4
  "license": "AGPL-3.0",
5
5
  "files": [
6
6
  "dist/index.js",
@@ -61,11 +61,11 @@
61
61
  "devDependencies": {
62
62
  "@microsoft/api-extractor": "^7.59.3",
63
63
  "@plitzi/plitzi-ui": "^1.6.33",
64
- "@plitzi/sdk-elements": "0.38.13",
65
- "@plitzi/sdk-interactions": "0.38.13",
66
- "@plitzi/sdk-schema": "0.38.13",
67
- "@plitzi/sdk-shared": "0.38.13",
68
- "@plitzi/sdk-style": "0.38.13",
64
+ "@plitzi/sdk-elements": "0.38.15",
65
+ "@plitzi/sdk-interactions": "0.38.15",
66
+ "@plitzi/sdk-schema": "0.38.15",
67
+ "@plitzi/sdk-shared": "0.38.15",
68
+ "@plitzi/sdk-style": "0.38.15",
69
69
  "@types/react": "^19.3.0",
70
70
  "eslint": "^9.39.5",
71
71
  "prettier": "^3.9.9",
@@ -36,7 +36,7 @@ A space on Plitzi — edited in the builder — is edited through the Plitzi MCP
36
36
  when the text is not enough.
37
37
  4. **Before saying done:** `npm run lint:space` clean, and the [review checklist](reference/review-checklist.md).
38
38
 
39
- What a name means — an element, a step, a trigger, a code, any export (`pageFamily`, `SpaceSpec`): `npx plitzi explain
39
+ What a name means — an element, a step, a trigger, a code, any `@plitzi` export (`pageFamily`, `createServer`): `npx plitzi explain
40
40
  <name>`, in a few lines. Never read the `.d.ts`.
41
41
 
42
42
  ## Five rules authoring cannot check for you
@@ -22,8 +22,9 @@ Read one only when the task names its subject.
22
22
  | [authoring-errors.md](authoring-errors.md) | What `authorSpace` refuses or warns about, and what to write instead |
23
23
  | [templates.md](templates.md) | Any `{{ … }}` or `{% … %}`: where it runs, naming sources, filters, tests, dates |
24
24
  | [flows.md](flows.md) | Clicks, submits, page loads, every few seconds, server actions, modals, state |
25
- | [realtime.md](realtime.md) | Pages that see each other: channels, presence, cursors, a shared board, who may hear a topic |
26
- | [plugins.md](plugins.md) | A component of your own: props, binding them, writing state, channels, registering, behaving in the builder |
25
+ | [realtime.md](realtime.md) | Pages that see each other: channels, presence, cursors, a shared board, state every screen shares, who may hear a topic |
26
+ | [plugins.md](plugins.md) | A component of your own: props, binding them, writing state, registering, behaving in the builder |
27
+ | [plugin-reach.md](plugin-reach.md) | What a plugin says and to whom: a notification, another element, a server action, shared state, other pages |
27
28
  | [drawing.md](drawing.md) | A plugin that draws or animates: a canvas sized to the device, WebGL, a loop that stops when unseen |
28
29
  | [structure.md](structure.md) | A space bigger than one screen: files, helpers, naming, keeping it short |
29
30
  | [testing.md](testing.md) | Any test: `inspectPage`, handles, fixtures, catching a flash from the first frame, shortcuts, counting renders |
@@ -145,6 +145,16 @@ Every page is now its content and nothing else, and every page is guaranteed the
145
145
  by name — `"{{ not (apiContainer_feed.products|find('slug', navigation.routeParams.slug)) }}"`. The page renders as
146
146
  written: show its "not found" part with `visible`.
147
147
 
148
+ ## A screen that fills the window
149
+
150
+ A dashboard or a board — one screen whose panels scroll on their own — says so on its page: `documentScroll:
151
+ 'locked'` holds the document still, so a finger dragged on a tablet no longer pulls the whole page and bounces it
152
+ back. Give the shell the window's height (`height: '100dvh'`) and `overflow: 'auto'` to each part that scrolls; what
153
+ does not fit is cut off, with nothing a visitor can scroll to reach it. `'noBounce'` keeps a page scrolling without
154
+ the rubber band or pull-to-refresh. Either is written onto the document only while that page is on it, and only when
155
+ the document is the space's own — never the site a widget sits on, nor a space drawn inside another. Not an
156
+ `html, body` rule in `customCss`, which holds every page and the site the space is a widget on.
157
+
148
158
  ## Styles follow the same rule
149
159
 
150
160
  - A role used on several pages is ONE class (`panelCard`, `pageTitle`), declared in the module that owns the area and
@@ -0,0 +1,91 @@
1
+ # What a plugin says, and to whom
2
+
3
+ A plugin reaches the person, the space's other elements, the server and the other screens each one way. All of it is
4
+ imported from `@plitzi/plitzi-sdk` — the page's copy, which every plugin shares — never from `window` events or a
5
+ module of the project's (each plugin is a bundle of its own: a module two of them import is two).
6
+
7
+ ## To the person: `useNotify`
8
+
9
+ ```tsx
10
+ import { useNotify } from '@plitzi/plitzi-sdk';
11
+
12
+ const notify = useNotify();
13
+ notify('Deleted 79 recordings'); // what an `addNotification` step shows
14
+ notify('Training failed', { appearance: 'danger', autoDismiss: false });
15
+ ```
16
+
17
+ The page's own toasts, in the space's theme and with the look its `notifications` give them. For what only the plugin
18
+ knows; what the PAGE decides to say stays a flow (`on(…)` → `addNotification`).
19
+
20
+ ## To another element: an event, and the space's flow
21
+
22
+ A plugin never calls another one. It fires what happened, and the space's flow decides who acts — visible in the
23
+ space, and the same flow a button can start:
24
+
25
+ ```ts
26
+ // the assistant's declaration: triggers: { onOpenResult: { action: 'onOpenResult', preview: { index: 0 } } }
27
+ assistant({ id: 'jarvis', flows: [[
28
+ named('asked', declaredTrigger(assistantDeclaration, 'onOpenResult')),
29
+ declaredCallback(browserDeclaration, 'openResult', { on: 'browser', params: { index: '{{ asked.index }}' } })
30
+ ]] })
31
+ ```
32
+
33
+ The receiver declares the action (`callbacks`) and registers it from its declaration; a name either side does not
34
+ declare is refused when the space is authored.
35
+
36
+ ## To the server: `useServerAction`
37
+
38
+ One operation is one server action — `taskAction(tasks.done, …)` or `defineAction(…)` — whose input the server checks
39
+ before any code runs, never a `case` in one route. A plugin runs it awaited, typed by the action:
40
+
41
+ ```tsx
42
+ import { useServerAction } from '@plitzi/plitzi-sdk';
43
+ import type { habitDone } from '../../space/actions';
44
+
45
+ const done = useServerAction<typeof habitDone>('habits-done');
46
+ const result = await done({ id }); // the input its `call` way in declares
47
+ if (result.ok) { show(result.output.streak); } else { say(result.error ?? result.reason); }
48
+ ```
49
+
50
+ The same run a flow's `runServerAction` makes: its `access`, its refusals, its entry in the dev tools; a completed run
51
+ refreshes the page's cached requests (`{ invalidateQueries: 'none' }` for one that only reads).
52
+
53
+ ## State every screen shares: a channel that retains
54
+
55
+ What the server keeps and every page shows — a dashboard's lists, a board's settings — is a channel declared
56
+ `retain: true` (with `publish: 'server'`): the server keeps the latest message of each type and hands them to every
57
+ page that joins.
58
+
59
+ ```ts
60
+ channels: { desk: { access: { mode: 'session' }, publish: 'server', retain: true } }
61
+
62
+ // the server, in a task, a route or a flow's `realtime.publish`: kept, and said to every page on it
63
+ await ctx.publish('desk', 'lists', lists);
64
+ await ctx.publish('desk', 'lists', null); // forgotten
65
+
66
+ channel({ id: 'desk', topic: 'desk', children: [lists({ id: 'lists', bind: { lists: 'desk.retained.lists' } })] })
67
+ ```
68
+
69
+ `useChannel('desk').retained.lists` is the same value in a plugin, re-rendering when it changes; what the page is
70
+ handed on joining reaches `onMessage` too, as if just said. A page changes it by
71
+ asking the server (an action), which keeps it and says it. A topic keeps at most 64 types and 512 KB.
72
+
73
+ ## To other pages, at the speed of a cursor: `useChannel`
74
+
75
+ ```tsx
76
+ const room = useChannel(roomTopic, { onMessage: message => move(message.from, message.data) });
77
+ room.publish('pointer', { x, y }); // throttle it: ~20 a second, the latest position each time
78
+ room.publish('react', { emoji }, { echo: true }); // and heard here too
79
+ room.members; // who is here, with the state each announced
80
+ ```
81
+
82
+ Messages arrive through the callback and re-render nothing. Take the topic as a prop
83
+ (`bindTemplate('roomTopic', 'board.id', 'room:{{ source }}')`) so the space names its channels, and trust a message
84
+ you act on only when `message.from === 'server'`. The page has one connection and is one member per topic, however
85
+ many elements and plugins listen.
86
+
87
+ ## Its own server code
88
+
89
+ `plitzi plugin add board --server` writes `functions/index.ts` in its folder. Its routes answer under
90
+ `/fn/plugins/board/`, named with `usePluginRoute('board')('/layout')` (`undefined` where no server runs code, as on the
91
+ canvas). Its `ctx.kv` is the plugin's own; the space's credentials, channels and data are not.
@@ -55,8 +55,14 @@ const NebulaRun = ({ shipColor = 'amber', best = 0, className }: NebulaRunProps)
55
55
 
56
56
  - **Render `RootElement`**, not a `div`: it carries the element's id, classes and `data-plitzi-el`, so the CSS
57
57
  authored on the element applies, the builder can select it and a test can find it.
58
- - **Render the same thing on the server and on the first client pass.** A clock, a random number or anything read from
59
- `window` belongs in an effect; a hydration mismatch discards the whole tree, not the plugin.
58
+ - **Render the same thing on the server and on the first client pass** — a plugin is drawn on the server first. A
59
+ clock, a random number or anything read from `window` belongs in an effect; a hydration mismatch discards the whole
60
+ tree, not the plugin. A preference per device (a tab, muted) is never read from `localStorage` while rendering: write
61
+ it to `runtime.state` with `keepState` — and `paintedState` when it changes the first paint ([kept state](kept-state.md))
62
+ — and take it as a bound prop.
63
+ - **`@plitzi/plitzi-ui` is not the page's.** The build keeps out only React and the SDK: a plugin importing it carries
64
+ its own copy, whose contexts (its toasts) are not the page's and whose look is not the space's. Draw controls with the
65
+ space's tokens; tabs over the space's elements are a plugin that lays them out (below).
60
66
  - **Borrow colours.** `currentColor` and the space's `var(--…)` tokens follow the theme; a hard-coded colour is
61
67
  invisible in one of them. A canvas reads them with `getComputedStyle(element).getPropertyValue('--accent')` and
62
68
  again when `theme.resolved` changes (bind it as a prop).
@@ -64,19 +70,19 @@ const NebulaRun = ({ shipColor = 'amber', best = 0, className }: NebulaRunProps)
64
70
  ## Writing to the space
65
71
 
66
72
  A plugin that produces something the page shows — a score, a selection — writes it to `runtime.state`, where every
67
- binding reads it:
73
+ binding reads it — and where two plugins share it, each being a bundle of its own (a module both import is two):
68
74
 
69
75
  ```ts
70
76
  import { getStateManager } from '@plitzi/plitzi-sdk';
71
77
 
72
78
  const state = getStateManager();
73
79
  state.setStateByKey('arcadeBest', Math.max(score, Number(state.state.arcadeBest ?? 0)));
74
- const stop = state.subscribe(next => save(next)); // called after every change; call `stop()` to leave
80
+ const stop = state.subscribe(next => save(next)); // after every change; `stop()` to leave
75
81
  ```
76
82
 
77
83
  `state` is the current value, `setState` replaces it (or takes an updater), `setStateByKey` writes one key,
78
- `clearState` empties it, `subscribe` listens. Bindings on `state.*` re-render at once. With the space's `keepState`
79
- on ([kept state](kept-state.md)), what a plugin writes there — its layout, a choice — is back after a reload too.
84
+ `clearState` empties it, `subscribe` listens. Bindings on `state.*` re-render at once. With `keepState` on
85
+ ([kept state](kept-state.md)), what a plugin writes there is back after a reload.
80
86
 
81
87
  ## Laying out the space's elements
82
88
 
@@ -90,39 +96,17 @@ import { elementChildren } from '@plitzi/plitzi-sdk';
90
96
  {elementChildren(children).map(({ id, node }) => <section key={id} style={placed[id]}>{node}</section>)}
91
97
  ```
92
98
 
93
- Never write `style` onto an element the plugin does not render: nothing promises to keep it. Its boxes share one
99
+ One that shows only some of them — a dashboard's panels, a wizard's step — says `choosesChildren: true` in its
100
+ declaration: the page checks then owe none at rest, and check the ones it draws. Never write `style` onto an element
101
+ the plugin does not render: nothing promises to keep it. Its boxes share one
94
102
  stacking context, the plugin's. `useDisplayMode()` names the breakpoint showing (`desktop`, `tablet`, `mobile`) at the
95
103
  space's widths; `useElementSize(ref)`, its own box (`undefined` until measured).
96
104
 
97
- ## Its own server code
105
+ ## What it says, and to whom
98
106
 
99
- `plitzi plugin add board --server` writes `functions/index.ts` in its folder (the CLI skill). Its routes answer
100
- under `/fn/plugins/board/`; the component names them, with nothing for the space to wire:
101
-
102
- ```tsx
103
- const route = usePluginRoute('board'); // from '@plitzi/plitzi-sdk'
104
- const url = route('/layout'); // undefined where no server runs code (the canvas)
105
- ```
106
-
107
- Its `ctx.kv` is the plugin's own; the space's credentials, channels and data are not.
108
-
109
- ## Talking to other pages
110
-
111
- A plugin that moves at the speed of a cursor reads a realtime channel through `useChannel` rather than through flows —
112
- messages arrive through a callback and re-render nothing:
113
-
114
- ```tsx
115
- import { useChannel } from '@plitzi/plitzi-sdk';
116
-
117
- const room = useChannel(roomTopic, { onMessage: message => move(message.from, message.data) });
118
- room.publish('pointer', { x, y }); // throttle it: ~20 a second, the latest position each time
119
- room.publish('react', { emoji }, { echo: true }); // and heard here too
120
- room.members; // who is here, with the state each announced
121
- ```
122
-
123
- Take the topic as a prop (`bindTemplate('roomTopic', 'board.id', 'room:{{ source }}')`) so the space names its
124
- channels, and trust a message you act on only when `message.from === 'server'`. The page has one connection and is one
125
- member per topic, however many elements and plugins listen.
107
+ The person (`useNotify`), another element (an event and the space's flow — never a `window` event), the server
108
+ (`useServerAction`, typed by the action), state every screen shares (a channel that retains), other pages
109
+ (`useChannel`) and its own server code: [plugin-reach](plugin-reach.md).
126
110
 
127
111
  ## Feature flags
128
112
 
@@ -33,6 +33,17 @@ channels: { 'order:{id}': { access: { mode: 'session' }, grant: true } }
33
33
  channel({ id: 'order', topic: 'order:{{ id }}', bind: { grant: 'state.follow.grant' }, children: [...] })
34
34
  ```
35
35
 
36
+ State every screen shows and the server keeps — a dashboard's lists, a board's settings — goes on a channel declared
37
+ `retain: true` (and `publish: 'server'`): the server keeps the latest message of each type, sends it as it is said and
38
+ again to every page that joins — and to its `onMessage` flows, as if just said — which reads it as
39
+ `desk.retained.lists` (a plugin, `useChannel('desk').retained`).
40
+ Publishing `null` forgets the type; a topic keeps at most 64 types and 512 KB. No read of its own, no copy in `state`:
41
+
42
+ ```ts
43
+ channels: { desk: { access: { mode: 'session' }, publish: 'server', retain: true } }
44
+ // a flow: { task: 'realtime.publish', params: { topic: 'desk', type: 'lists', data: '{{ saved.lists }}' } }
45
+ ```
46
+
36
47
  Two people writing the same thing at once: `kv.setIf` writes only if the value is still the one the flow read (empty
37
48
  `expected` = only if nothing is there yet — claim a seat, a username), `list.put`/`list.range` keep an ordered list
38
49
  (latest first, a leaderboard), and `flow.rateLimit` first in a public action that writes.