@plitzi/sdk-server 0.38.14 → 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +64 -2
  3. package/dist/core/auth/createAuth.d.ts +5 -0
  4. package/dist/core/auth/createAuth.js +5 -0
  5. package/dist/core/auth/csrf.d.ts +25 -0
  6. package/dist/core/auth/csrf.js +34 -32
  7. package/dist/core/createServer.js +4 -0
  8. package/dist/core/http/stages/authRoutes.js +3 -0
  9. package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
  10. package/dist/core/http/stages/crossSiteWrites.js +44 -0
  11. package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
  12. package/dist/core/http/stages/exchangeRoute.js +2 -0
  13. package/dist/core/server/fleet/link.d.ts +1 -1
  14. package/dist/core/server/fleet/stores.js +1 -1
  15. package/dist/core/services/registry.js +2 -0
  16. package/dist/functions-api.d.ts +5 -2
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +2 -1
  19. package/dist/modules/actions/tasks/realtime.js +1 -1
  20. package/dist/modules/authoringHost/index.d.ts +49 -0
  21. package/dist/modules/authoringHost/index.js +113 -0
  22. package/dist/modules/authoringHost/index.test.d.ts +1 -0
  23. package/dist/modules/functions/contract.d.ts +5 -2
  24. package/dist/modules/project/serveProject.js +4 -1
  25. package/dist/modules/realtime/hub.d.ts +7 -2
  26. package/dist/modules/realtime/hub.js +8 -4
  27. package/dist/modules/realtime/index.js +14 -7
  28. package/dist/modules/realtime/message.d.ts +3 -0
  29. package/dist/modules/realtime/message.js +5 -0
  30. package/dist/modules/realtime/retained.d.ts +24 -0
  31. package/dist/modules/realtime/retained.js +47 -0
  32. package/dist/modules/realtime/retained.test.d.ts +1 -0
  33. package/dist/modules/runtime/stages.d.ts +4 -1
  34. package/dist/modules/ssr/spaceDocument.js +5 -1
  35. package/package.json +3 -3
  36. package/skills/plitzi-authoring/SKILL.md +1 -1
  37. package/skills/plitzi-authoring/reference/index.md +3 -2
  38. package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
  39. package/skills/plitzi-authoring/reference/plugins.md +15 -31
  40. package/skills/plitzi-authoring/reference/realtime.md +11 -0
  41. package/skills/plitzi-authoring/reference/testing.md +3 -1
@@ -0,0 +1,113 @@
1
+ import { serverLog } from "../../helpers/serverLog.js";
2
+ import { PREVIEW_TOKEN_PARAM, readDraftToken } from "../../core/previewToken.js";
3
+ import { createServer } from "../../core/createServer.js";
4
+ import { isRecord } from "@plitzi/sdk-shared/helpers/isRecord";
5
+ import { randomBytes } from "node:crypto";
6
+ import path from "node:path";
7
+ import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
+ //#region src/modules/authoringHost/index.ts
9
+ /** The one space the host serves, which every page is a draft of. */
10
+ var SPACE_ID = 1;
11
+ /** An id is a file's name and a query's value: nothing that could be read as a path or need escaping. */
12
+ var ID = /^[\w-]{1,64}$/;
13
+ /** A day: how long a browser remembers which page it was looking at, for a reload that lost the address. */
14
+ var SESSION_TTL_MS = 864e5;
15
+ var isDocuments = (value) => isRecord(value) && isRecord(value.schema) && isRecord(value.style);
16
+ /** The pages `dir` holds — what is not one is said, and left where it is. */
17
+ var readPages = (dir) => {
18
+ const pages = /* @__PURE__ */ new Map();
19
+ for (const file of readdirSync(dir).filter((name) => name.endsWith(".json"))) {
20
+ const id = file.slice(0, -5);
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(readFileSync(path.join(dir, file), "utf-8"));
24
+ } catch {
25
+ parsed = void 0;
26
+ }
27
+ if (ID.test(id) && isDocuments(parsed)) pages.set(id, {
28
+ schema: parsed.schema,
29
+ style: parsed.style
30
+ });
31
+ else serverLog.warn("AuthoringHost", `${path.join(dir, file)} is not a page this host wrote: left out`);
32
+ }
33
+ return pages;
34
+ };
35
+ var createAuthoringHost = ({ dir, frameAncestors, ...config }) => {
36
+ mkdirSync(dir, { recursive: true });
37
+ const pages = readPages(dir);
38
+ const fileOf = (id) => path.join(dir, `${id}.json`);
39
+ const keep = (id, data) => {
40
+ writeFileSync(fileOf(id), JSON.stringify({
41
+ schema: data.schema,
42
+ style: data.style
43
+ }));
44
+ pages.set(id, {
45
+ schema: data.schema,
46
+ style: data.style
47
+ });
48
+ };
49
+ const drop = (id) => {
50
+ if (!pages.delete(id)) return false;
51
+ rmSync(fileOf(id), { force: true });
52
+ return true;
53
+ };
54
+ const draftStore = {
55
+ put: (token, data) => {
56
+ if (ID.test(token)) keep(token, data);
57
+ },
58
+ take: (token) => {
59
+ const data = pages.get(token);
60
+ return data ? {
61
+ data,
62
+ reusable: true,
63
+ spaceId: SPACE_ID
64
+ } : void 0;
65
+ },
66
+ drop: (token) => {
67
+ drop(token);
68
+ }
69
+ };
70
+ const deployment = {
71
+ spaceId: SPACE_ID,
72
+ environment: "main",
73
+ revision: 0,
74
+ ...frameAncestors ? { frameAncestors } : {}
75
+ };
76
+ return {
77
+ server: createServer({
78
+ ...config,
79
+ preview: {
80
+ sessionTtlMs: SESSION_TTL_MS,
81
+ ...config.preview
82
+ },
83
+ draftStore,
84
+ adapters: {
85
+ getOfflineData: () => Promise.resolve(void 0),
86
+ getSpaceDeployment: (req) => {
87
+ const id = readDraftToken(req);
88
+ if (id === void 0) return Promise.resolve({ error: {
89
+ code: 404,
90
+ message: `Nothing here: each page of this host is at the address put() answered — /?${PREVIEW_TOKEN_PARAM}=<id>`
91
+ } });
92
+ if (!pages.has(id)) return Promise.resolve({ error: {
93
+ code: 404,
94
+ message: `No page "${id}" here: put() it, or it was dropped`
95
+ } });
96
+ return Promise.resolve(deployment);
97
+ }
98
+ }
99
+ }),
100
+ put: (documents, { id = randomBytes(16).toString("base64url") } = {}) => {
101
+ if (!ID.test(id)) throw new Error(`A page id is letters, digits, "-" and "_", up to 64 of them — not "${id}"`);
102
+ keep(id, documents);
103
+ return {
104
+ id,
105
+ path: `/?${PREVIEW_TOKEN_PARAM}=${id}`
106
+ };
107
+ },
108
+ drop,
109
+ ids: () => [...pages.keys()]
110
+ };
111
+ };
112
+ //#endregion
113
+ export { createAuthoringHost };
@@ -0,0 +1 @@
1
+ export {};
@@ -93,8 +93,11 @@ export type FunctionContext = {
93
93
  * One step a server action can take, written by the space. The shape of the platform's own tasks — addressed as
94
94
  * `<namespace>.<action>`, drawn in the builder from `params` — run with a {@link FunctionContext} rather than the
95
95
  * platform's full one.
96
+ *
97
+ * `R` is what `run` answers: `taskAction(task, …)` hands it, with `T`, to a page that runs the action
98
+ * (`useServerAction`), so `FunctionTask<{ id: string }, Habit>` is typed at both ends.
96
99
  */
97
- export type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>> = {
100
+ export type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>, R = unknown> = {
98
101
  namespace: string;
99
102
  action: string;
100
103
  title: string;
@@ -105,7 +108,7 @@ export type FunctionTask<T extends Record<string, unknown> = Record<string, unkn
105
108
  * what the server allows. Over the functions' own `limits`, for this task.
106
109
  */
107
110
  limits?: FunctionTimeLimits;
108
- run: (params: T, ctx: FunctionContext) => unknown;
111
+ run: (params: T, ctx: FunctionContext) => R | Promise<R>;
109
112
  };
110
113
  /** What a route's handler gets besides the request: the context, and the `:params` its key named, by name. */
111
114
  export type FunctionRouteContext = FunctionContext & {
@@ -245,7 +245,10 @@ var startProject = async (options) => {
245
245
  ...serverOptions.action,
246
246
  ...actions ? { lookups: actionLookups(actions, connectors, credentialsFromEnv()) } : {}
247
247
  }
248
- }, { preAuth: [spaceFailure.stage, ...runtime ? [runtime.stage] : []] });
248
+ }, {
249
+ preAuth: [spaceFailure.stage],
250
+ data: runtime ? [runtime.stage] : []
251
+ });
249
252
  await server.listen(port, host);
250
253
  if (speaks) {
251
254
  mkdirSync(path.join(root, PROJECT_TMP), { recursive: true });
@@ -1,3 +1,4 @@
1
+ import { RealtimeRetained } from './retained';
1
2
  import { ChannelDeclaration, PubSubAdapter, RealtimeMessage, RealtimeSender } from '@plitzi/sdk-shared';
2
3
  /** The space a connection belongs to: its topics are that space's and no other's. */
3
4
  export type RealtimeSpace = {
@@ -38,7 +39,7 @@ export type RealtimeHub = ReturnType<typeof createRealtimeHub>;
38
39
  * A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
39
40
  * arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
40
41
  */
41
- export declare const createRealtimeHub: (pubsub: PubSubAdapter) => {
42
+ export declare const createRealtimeHub: (pubsub: PubSubAdapter, retained: RealtimeRetained) => {
42
43
  publish: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
43
44
  from: (connection: RealtimeConnection, topic: string, type: string, data: unknown, echo?: boolean) => RealtimeMessage;
44
45
  find: (token: string) => RealtimeConnection | undefined;
@@ -47,7 +48,11 @@ export declare const createRealtimeHub: (pubsub: PubSubAdapter) => {
47
48
  * none. What stops a grant that is already in use; `grants.revoke` is what stops it being used again.
48
49
  */
49
50
  revoke: (space: RealtimeSpace, topic: string, grant?: string) => Promise<void>;
50
- /** Subscribes a new connection to its topics, and tells the members of each presence channel it arrived. */
51
+ /**
52
+ * Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
53
+ * each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
54
+ * message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
55
+ */
51
56
  connect: (connection: RealtimeConnection) => Promise<void>;
52
57
  /** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
53
58
  disconnect: (connection: RealtimeConnection) => Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { warnRealtime } from "./failure.js";
2
+ import { isMessage } from "./message.js";
2
3
  import { JOIN_TYPE, LEAVE_TYPE, REVOKED_TYPE } from "@plitzi/sdk-shared/realtime";
3
4
  //#region src/modules/realtime/hub.ts
4
5
  /** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
@@ -10,8 +11,6 @@ var adapterTopic = ({ spaceId, environment }, topic) => `${spaceId}/${environmen
10
11
  */
11
12
  var REVOKE_TYPE = "$revoke";
12
13
  var revokedGrant = (data) => typeof data === "object" && data !== null && "grant" in data && typeof data.grant === "string" ? data.grant : void 0;
13
- /** A message as the adapter carried it — written by this module, but read from a transport that is not. */
14
- var isMessage = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "type" in value && typeof value.type === "string" && "from" in value && typeof value.from === "string" && "at" in value && typeof value.at === "number";
15
14
  var parse = (raw) => {
16
15
  try {
17
16
  const value = JSON.parse(raw);
@@ -26,7 +25,7 @@ var parse = (raw) => {
26
25
  * A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
27
26
  * arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
28
27
  */
29
- var createRealtimeHub = (pubsub) => {
28
+ var createRealtimeHub = (pubsub, retained) => {
30
29
  const byToken = /* @__PURE__ */ new Map();
31
30
  const local = /* @__PURE__ */ new Map();
32
31
  const publish = (space, message) => pubsub.publish(adapterTopic(space, message.topic), JSON.stringify(message));
@@ -110,11 +109,16 @@ var createRealtimeHub = (pubsub) => {
110
109
  from: "server",
111
110
  at: Date.now()
112
111
  }),
113
- /** Subscribes a new connection to its topics, and tells the members of each presence channel it arrived. */
112
+ /**
113
+ * Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
114
+ * each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
115
+ * message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
116
+ */
114
117
  connect: async (connection) => {
115
118
  byToken.set(connection.token, connection);
116
119
  for (const [topic, declaration] of connection.topics) {
117
120
  await join(connection, topic);
121
+ if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", message));
118
122
  if (declaration.presence && !connection.observer) await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
119
123
  }
120
124
  },
@@ -4,6 +4,7 @@ import { createRealtimeGrants } from "./grants.js";
4
4
  import { createChannelResolver } from "./declarations.js";
5
5
  import { createRealtimeHub } from "./hub.js";
6
6
  import { createMemoryPubSub } from "./memoryPubSub.js";
7
+ import { createRealtimeRetained } from "./retained.js";
7
8
  import { handleRealtimePublish, handleRealtimeSubscribe } from "./handlers.js";
8
9
  import { handleRealtimeSocket } from "./socket.js";
9
10
  import { matchChannel } from "@plitzi/sdk-shared/realtime";
@@ -20,9 +21,11 @@ var realtimeModuleFor = (config) => {
20
21
  if (config.realtime === false || !getOfflineData) return;
21
22
  const existing = modules.get(config);
22
23
  if (existing) return existing;
23
- const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub());
24
+ const kv = config.action?.kv ?? fleetStore("realtime.kv", KV_METHODS) ?? createMemoryKv();
25
+ const retained = createRealtimeRetained(kv);
26
+ const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained);
24
27
  const resolveChannels = createChannelResolver(getOfflineData);
25
- const grants = createRealtimeGrants(config.action?.kv ?? fleetStore("realtime.grants", KV_METHODS) ?? createMemoryKv());
28
+ const grants = createRealtimeGrants(kv);
26
29
  const module = {
27
30
  hub,
28
31
  path: config.realtime?.path ?? "/_realtime",
@@ -32,16 +35,20 @@ var realtimeModuleFor = (config) => {
32
35
  grants,
33
36
  close: () => hub.closeAll(),
34
37
  publish: async (space, topic, type, data) => {
35
- const channels = await resolveChannels(space.spaceId, space.environment);
36
- if (!matchChannel(topic, channels)) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
38
+ const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
39
+ if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
37
40
  if (!SERVER_TYPE.test(type)) throw new Error("A message type is 1-64 of A-Z a-z 0-9 _ . : -");
38
- await hub.publish(space, {
41
+ const retain = match.declaration.retain === true;
42
+ const message = {
39
43
  topic,
40
44
  type,
41
45
  data,
42
46
  from: "server",
43
- at: Date.now()
44
- });
47
+ at: Date.now(),
48
+ ...retain ? { retained: true } : {}
49
+ };
50
+ if (retain) await retained.keep(space, message);
51
+ await hub.publish(space, message);
45
52
  },
46
53
  grant: async (space, topic, ttlSeconds) => {
47
54
  const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
@@ -0,0 +1,3 @@
1
+ import { RealtimeMessage } from '@plitzi/sdk-shared';
2
+ /** A message as a transport or a store carried it — written by this module, but read from something that is not. */
3
+ export declare const isMessage: (value: unknown) => value is RealtimeMessage;
@@ -0,0 +1,5 @@
1
+ //#region src/modules/realtime/message.ts
2
+ /** A message as a transport or a store carried it — written by this module, but read from something that is not. */
3
+ var isMessage = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "type" in value && typeof value.type === "string" && "from" in value && typeof value.from === "string" && "at" in value && typeof value.at === "number";
4
+ //#endregion
5
+ export { isMessage };
@@ -0,0 +1,24 @@
1
+ import { RealtimeSpace } from './hub';
2
+ import { ActionKvAdapter } from '../actions/types';
3
+ import { RealtimeMessage } from '@plitzi/sdk-shared';
4
+ /** The most types one topic keeps: state a page shows, never a log written one type per entry. */
5
+ export declare const MAX_RETAINED_TYPES = 64;
6
+ /** The most one topic keeps, as JSON: every page that joins is sent all of it. */
7
+ export declare const MAX_RETAINED_BYTES: number;
8
+ export type RealtimeRetained = {
9
+ /**
10
+ * Keeps `message` as its topic's latest of its type — or, with `null` data, forgets the type. Refused, before anything
11
+ * is sent, past {@link MAX_RETAINED_TYPES} types or {@link MAX_RETAINED_BYTES} for the topic.
12
+ */
13
+ keep: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
14
+ /** What a topic keeps: the latest message of each type, oldest first. */
15
+ of: (space: RealtimeSpace, topic: string) => Promise<RealtimeMessage[]>;
16
+ };
17
+ /**
18
+ * The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
19
+ * keeps what another hands a page that joins, and nothing new has to be configured for it.
20
+ *
21
+ * One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
22
+ * written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
23
+ */
24
+ export declare const createRealtimeRetained: (store: ActionKvAdapter) => RealtimeRetained;
@@ -0,0 +1,47 @@
1
+ import { isMessage } from "./message.js";
2
+ /** The most one topic keeps, as JSON: every page that joins is sent all of it. */
3
+ var MAX_RETAINED_BYTES = 524288;
4
+ /** How many times a write is tried while other writes on the same topic keep landing first. */
5
+ var ATTEMPTS = 8;
6
+ /** A topic's kept messages, by type, as stored — read from a store something else could have written. */
7
+ var parseKept = (raw) => {
8
+ try {
9
+ const value = JSON.parse(raw ?? "{}");
10
+ if (typeof value !== "object" || value === null) return {};
11
+ return Object.fromEntries(Object.entries(value).filter((entry) => isMessage(entry[1])));
12
+ } catch {
13
+ return {};
14
+ }
15
+ };
16
+ /**
17
+ * The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
18
+ * keeps what another hands a page that joins, and nothing new has to be configured for it.
19
+ *
20
+ * One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
21
+ * written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
22
+ */
23
+ var createRealtimeRetained = (store) => {
24
+ const key = ({ spaceId, environment }, topic) => `realtime-retained:${String(spaceId)}:${environment}:${topic}`;
25
+ return {
26
+ keep: async (space, message) => {
27
+ const at = key(space, message.topic);
28
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
29
+ const raw = await store.get(at);
30
+ const kept = parseKept(raw);
31
+ const others = Object.fromEntries(Object.entries(kept).filter(([type]) => type !== message.type));
32
+ const next = message.data === null ? others : {
33
+ ...others,
34
+ [message.type]: message
35
+ };
36
+ if (Object.keys(next).length > 64) throw new Error(`"${message.topic}" keeps at most ${String(64)} types of message: keep fewer, larger ones (one \`lists\` holding every list), or forget one with null`);
37
+ const written = JSON.stringify(next);
38
+ if (Buffer.byteLength(written) > 524288) throw new Error(`"${message.topic}" keeps at most ${String(MAX_RETAINED_BYTES / 1024)} KB, and "${message.type}" would take it past that: every page that joins is sent all of it — keep there what the screens show, the rest in kv`);
39
+ if (await store.swap(at, raw, written)) return;
40
+ }
41
+ throw new Error(`"${message.topic}" changed under ${String(ATTEMPTS)} writes in a row, so "${message.type}" was not kept: publish it again`);
42
+ },
43
+ of: async (space, topic) => Object.values(parseKept(await store.get(key(space, topic)))).sort((a, b) => a.at - b.at)
44
+ };
45
+ };
46
+ //#endregion
47
+ export { MAX_RETAINED_BYTES, createRealtimeRetained };
@@ -0,0 +1 @@
1
+ export {};
@@ -7,7 +7,10 @@ export declare const runtimeEndpointsStage: (endpoints: Record<string, SpaceRunt
7
7
  export type ServedRuntime = {
8
8
  /** Its tasks and routes, for `functions.native`. */
9
9
  native: FunctionsDefinition[];
10
- /** Its endpoints, for `preAuth` — they gate themselves, as the platform's forwarding does. */
10
+ /**
11
+ * Its endpoints, for `data` — where the platform forwards a space's: behind the auth chain and the cross-site guard,
12
+ * gating who may call them themselves.
13
+ */
11
14
  stage: Stage<SSRContext>;
12
15
  close: () => Promise<void>;
13
16
  };
@@ -56,7 +56,11 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
56
56
  const offlineData = cached ? JSON.parse(cached) : await config.adapters.getOfflineData(spaceId, environment, revision);
57
57
  if (!offlineData) {
58
58
  res.setStatus(404);
59
- res.end();
59
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
60
+ res.send(JSON.stringify({
61
+ error: `This request resolves to space ${String(spaceId)} (${environment}), which has no data: getSpaceDeployment chose it from what this request carries — its host and credentials, never the page’s path or query`,
62
+ reason: "not_found"
63
+ }));
60
64
  return;
61
65
  }
62
66
  const document = spaceDocument(offlineData);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-server",
3
- "version": "0.38.14",
3
+ "version": "0.38.15",
4
4
  "license": "AGPL-3.0",
5
5
  "files": [
6
6
  "dist",
@@ -96,8 +96,8 @@
96
96
  "./dist/env.js"
97
97
  ],
98
98
  "dependencies": {
99
- "@plitzi/plitzi-sdk": "0.38.14",
100
- "@plitzi/sdk-shared": "0.38.14",
99
+ "@plitzi/plitzi-sdk": "0.38.15",
100
+ "@plitzi/sdk-shared": "0.38.15",
101
101
  "ejs": "^6.0.1",
102
102
  "esbuild": "^0.28.2",
103
103
  "jsonwebtoken": "^9.0.3",
@@ -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 |
@@ -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).
@@ -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.
@@ -44,7 +44,9 @@ the list `inspectPage` holds a page to.
44
44
  Three flags say what a bare visit cannot promise, and `onScreen` leaves out:
45
45
 
46
46
  - `conditional` — on screen only under a condition of its own or of an ancestor, or with every child conditional (a
47
- list of flyouts at rest);
47
+ list of flyouts at rest). Under a plugin that chooses its children (`choosesChildren`), each child — and what is
48
+ inside it under no condition of its own — also carries `shownWith`, the child it comes with: once that child is
49
+ drawn it is owed like the rest (`onScreenIfChosen` lists them, and `inspectPage` checks them);
48
50
  - `repeated` — inside a list row, so rendered once per row: several copies, or none while the list is empty. Address
49
51
  one with `.first()` / `.nth(i)`, in a test that knows the data;
50
52
  - `boxless` — a provider with no tag, which renders its children and no element of its own; or a plugin whose