@plitzi/sdk-server 0.38.14 → 0.38.16

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 (47) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +68 -6
  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/auth/identity.d.ts +4 -0
  8. package/dist/core/auth/identity.js +1 -0
  9. package/dist/core/createServer.js +4 -0
  10. package/dist/core/freePort.d.ts +4 -0
  11. package/dist/core/freePort.js +4 -4
  12. package/dist/core/http/stages/authRoutes.js +3 -0
  13. package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
  14. package/dist/core/http/stages/crossSiteWrites.js +44 -0
  15. package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
  16. package/dist/core/http/stages/exchangeRoute.js +2 -0
  17. package/dist/core/server/fleet/link.d.ts +1 -1
  18. package/dist/core/server/fleet/stores.js +1 -1
  19. package/dist/core/services/registry.js +2 -0
  20. package/dist/core/unusedPort.d.ts +7 -3
  21. package/dist/core/unusedPort.js +33 -15
  22. package/dist/functions-api.d.ts +5 -2
  23. package/dist/index.d.ts +2 -0
  24. package/dist/index.js +2 -1
  25. package/dist/modules/actions/tasks/realtime.js +1 -1
  26. package/dist/modules/authoringHost/index.d.ts +49 -0
  27. package/dist/modules/authoringHost/index.js +113 -0
  28. package/dist/modules/authoringHost/index.test.d.ts +1 -0
  29. package/dist/modules/functions/contract.d.ts +5 -2
  30. package/dist/modules/project/serveProject.js +4 -1
  31. package/dist/modules/realtime/hub.d.ts +7 -2
  32. package/dist/modules/realtime/hub.js +8 -4
  33. package/dist/modules/realtime/index.js +14 -7
  34. package/dist/modules/realtime/message.d.ts +3 -0
  35. package/dist/modules/realtime/message.js +5 -0
  36. package/dist/modules/realtime/retained.d.ts +24 -0
  37. package/dist/modules/realtime/retained.js +47 -0
  38. package/dist/modules/realtime/retained.test.d.ts +1 -0
  39. package/dist/modules/runtime/stages.d.ts +4 -1
  40. package/dist/modules/ssr/spaceDocument.js +5 -1
  41. package/package.json +3 -3
  42. package/skills/plitzi-authoring/SKILL.md +1 -1
  43. package/skills/plitzi-authoring/reference/index.md +3 -2
  44. package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
  45. package/skills/plitzi-authoring/reference/plugins.md +15 -31
  46. package/skills/plitzi-authoring/reference/realtime.md +11 -0
  47. package/skills/plitzi-authoring/reference/testing.md +3 -1
@@ -5,6 +5,7 @@ import { rscStage } from "./rsc.js";
5
5
  import { spaceDocumentStage } from "./spaceDocument.js";
6
6
  import { imagesStage } from "../http/stages/images.js";
7
7
  import { notFoundStage, ssrStage } from "./ssr.js";
8
+ import { crossSiteWritesStage } from "../http/stages/crossSiteWrites.js";
8
9
  import { authRoutesStages } from "../http/stages/authRoutes.js";
9
10
  import { fontAssetsStage } from "../http/stages/fontAssets.js";
10
11
  import { healthStage } from "../http/stages/health.js";
@@ -25,6 +26,7 @@ var buildPagePipeline = (services, extensions = {}) => {
25
26
  sdkAssetsStage
26
27
  ];
27
28
  stages.push(...extensions.preAuth ?? []);
29
+ stages.push(crossSiteWritesStage);
28
30
  stages.push(createMiddlewaresStage());
29
31
  if (services.rsc) stages.push(rscStage);
30
32
  stages.push(actionStage);
@@ -1,6 +1,10 @@
1
1
  /**
2
- * A port the system has just handed out and nobody holds — what a test listens on. Never a fixed number: one in the
3
- * system's ephemeral range (above 32768 on Linux) can be taken by any outgoing connection of a test running beside it,
4
- * and the listen fails with `EADDRINUSE` on a run that has nothing wrong with it.
2
+ * A port nobody holds, for a test to listen on — chosen where the system never hands one out by itself.
3
+ *
4
+ * Not one the system hands out (`listen(0)`): that range is the one every outgoing connection takes its local port
5
+ * from, so between the moment a port is handed out and the moment the test listens on it, a request of a test running
6
+ * beside it — another worker's `fetch`, a database connection — can take it, and the listen fails with `EADDRINUSE` on
7
+ * a run that has nothing wrong with it. Below that range only a port somebody chose explicitly is ever taken, and it is
8
+ * looked at first: one that answers, or that this process may not listen on, is passed over.
5
9
  */
6
10
  export declare const unusedPort: (host?: string) => Promise<number>;
@@ -1,20 +1,38 @@
1
- import { createServer } from "node:net";
1
+ import { portAnswers, portBindable } from "./freePort.js";
2
+ import { readFileSync } from "node:fs";
2
3
  //#region src/core/unusedPort.ts
4
+ /** The lowest port handed out: above the well-known and the registered ones most local services sit on. */
5
+ var LOWEST = 1e4;
6
+ /** Below it, as far as a system lets a port be chosen for nobody: Linux's default, and below macOS's and Windows's. */
7
+ var EPHEMERAL_DEFAULT = 32768;
8
+ var ATTEMPTS = 50;
3
9
  /**
4
- * A port the system has just handed out and nobody holds — what a test listens on. Never a fixed number: one in the
5
- * system's ephemeral range (above 32768 on Linux) can be taken by any outgoing connection of a test running beside it,
6
- * and the listen fails with `EADDRINUSE` on a run that has nothing wrong with it.
10
+ * Where the system starts handing out ports by itself — to every outgoing connection and every `listen(0)`. Linux says
11
+ * where in `/proc`; macOS and Windows start at 49152, above Linux's default.
7
12
  */
8
- var unusedPort = (host = "127.0.0.1") => new Promise((resolve, reject) => {
9
- const probe = createServer();
10
- probe.once("error", reject);
11
- probe.listen(0, host, () => {
12
- const address = probe.address();
13
- probe.close(() => {
14
- if (typeof address === "object" && address) resolve(address.port);
15
- else reject(/* @__PURE__ */ new Error(`The system gave no port on ${host}`));
16
- });
17
- });
18
- });
13
+ var ephemeralStart = () => {
14
+ try {
15
+ const [low] = readFileSync("/proc/sys/net/ipv4/ip_local_port_range", "utf-8").trim().split(/\s+/).map(Number);
16
+ if (Number.isInteger(low) && low > 10050) return Math.min(low, EPHEMERAL_DEFAULT);
17
+ } catch {}
18
+ return EPHEMERAL_DEFAULT;
19
+ };
20
+ /**
21
+ * A port nobody holds, for a test to listen on — chosen where the system never hands one out by itself.
22
+ *
23
+ * Not one the system hands out (`listen(0)`): that range is the one every outgoing connection takes its local port
24
+ * from, so between the moment a port is handed out and the moment the test listens on it, a request of a test running
25
+ * beside it — another worker's `fetch`, a database connection — can take it, and the listen fails with `EADDRINUSE` on
26
+ * a run that has nothing wrong with it. Below that range only a port somebody chose explicitly is ever taken, and it is
27
+ * looked at first: one that answers, or that this process may not listen on, is passed over.
28
+ */
29
+ var unusedPort = async (host = "127.0.0.1") => {
30
+ const span = ephemeralStart() - LOWEST;
31
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
32
+ const port = LOWEST + Math.floor(Math.random() * span);
33
+ if (!await portAnswers(port, host) && await portBindable(port, host)) return port;
34
+ }
35
+ throw new Error(`No free port between ${String(LOWEST)} and ${String(LOWEST + span)} on ${host} after ${String(ATTEMPTS)} tries`);
36
+ };
19
37
  //#endregion
20
38
  export { unusedPort };
@@ -160,8 +160,11 @@ export declare type FunctionsDefinition = {
160
160
  * One step a server action can take, written by the space. The shape of the platform's own tasks — addressed as
161
161
  * `<namespace>.<action>`, drawn in the builder from `params` — run with a {@link FunctionContext} rather than the
162
162
  * platform's full one.
163
+ *
164
+ * `R` is what `run` answers: `taskAction(task, …)` hands it, with `T`, to a page that runs the action
165
+ * (`useServerAction`), so `FunctionTask<{ id: string }, Habit>` is typed at both ends.
163
166
  */
164
- export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>> = {
167
+ export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>, R = unknown> = {
165
168
  namespace: string;
166
169
  action: string;
167
170
  title: string;
@@ -172,7 +175,7 @@ export declare type FunctionTask<T extends Record<string, unknown> = Record<stri
172
175
  * what the server allows. Over the functions' own `limits`, for this task.
173
176
  */
174
177
  limits?: FunctionTimeLimits;
175
- run: (params: T, ctx: FunctionContext) => unknown;
178
+ run: (params: T, ctx: FunctionContext) => R | Promise<R>;
176
179
  };
177
180
 
178
181
  /**
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export { createAuthAdapters } from './adapters/authAdapters';
12
12
  export { authoringPreview, createMemoryCache, createSpaceAdapters, fixedSpace, presentsCredential, refuse, verifiedDomain, wildcardSubdomain } from './adapters/space';
13
13
  export { createLocalFontStore, hostedPathsOf } from './core/fontStore';
14
14
  export { createMemoryDraftStore, takeDraftOverride } from './modules/ssr/preview';
15
+ export { createAuthoringHost } from './modules/authoringHost';
15
16
  export { createMemoryPubSub } from './modules/realtime/memoryPubSub';
16
17
  export { createRedisPubSub } from './modules/realtime/redisPubSub';
17
18
  export { PREVIEW_TOKEN_PARAM } from './core/previewToken';
@@ -27,5 +28,6 @@ export type { FontStore, StoredFont } from './core/fontStore';
27
28
  export type { PubSubAdapter, SSRRealtimeConfig } from '@plitzi/sdk-shared';
28
29
  export type { RedisPubSubClients } from './modules/realtime/redisPubSub';
29
30
  export type { ResolvedServices, ServerConfig } from './core/createServer';
31
+ export type { AuthoringHost, AuthoringHostConfig } from './modules/authoringHost';
30
32
  export type { Closable, CloseOnSignalsOptions } from './core/server/closeOnSignals';
31
33
  export type { BaseContext, PipelineExtensions, SSRContext, Stage } from './core/http/types';
package/dist/index.js CHANGED
@@ -19,5 +19,6 @@ import { createMemoryCache, refuse } from "./adapters/space/types.js";
19
19
  import { authoringPreview, fixedSpace, presentsCredential, verifiedDomain, wildcardSubdomain } from "./adapters/space/resolvers.js";
20
20
  import { createSpaceAdapters } from "./adapters/space/index.js";
21
21
  import { createLocalFontStore, hostedPathsOf } from "./core/fontStore.js";
22
+ import { createAuthoringHost } from "./modules/authoringHost/index.js";
22
23
  import { createRedisPubSub } from "./modules/realtime/redisPubSub.js";
23
- export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
24
+ export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createAuthoringHost, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
@@ -13,7 +13,7 @@ var realtimeTasks = [
13
13
  namespace: "realtime",
14
14
  action: "publish",
15
15
  title: "Publish On Channel",
16
- description: "Sends a message to every page subscribed to a topic of one of the space’s channels.",
16
+ description: "Sends a message to every page subscribed to a topic of one of the space’s channels. On a `retain: true` channel it is also kept, the latest of its type, for every page that joins later; `null` data forgets it.",
17
17
  params: {
18
18
  topic: {
19
19
  type: "text",
@@ -0,0 +1,49 @@
1
+ import { ServerConfig } from '../../core/createServer';
2
+ import { AuthoredDocuments } from '../project/watchSpace';
3
+ import { SSRServer } from '@plitzi/sdk-shared';
4
+ /**
5
+ * Pages somebody else authored — an agent designing a screen, a visitor's own page — served as a project's pages are,
6
+ * each at an address of its own, from one server.
7
+ *
8
+ * Each page is a space kept as a draft of the host's one space (`?__pt=<id>`), which is how a page server tells many
9
+ * apart on one host: the page arrives with its whole space in it, every page after it is the browser's, and a reload
10
+ * that lost the address finds it again in the draft's cookie. So a page here is drawn in the browser alone — no server
11
+ * provider, action, function or channel of its own: it is data and its look.
12
+ *
13
+ * Author them where they cannot reach anything (`authorIsolated` of `@plitzi/sdk-authoring/node`) and serve them here,
14
+ * on an origin of their own — never the app's, whose cookies a page somebody else wrote would then run beside.
15
+ *
16
+ * ```ts
17
+ * const host = createAuthoringHost({ dir: 'tmp/pages', port: 8091, frameAncestors: ['https://localhost:8080'] });
18
+ * await host.server.listen(8091, '0.0.0.0');
19
+ *
20
+ * const result = await authorIsolated('tmp/pages/weather.ts');
21
+ * if (result.ok) {
22
+ * const { path } = host.put(result.space, { id: 'weather' }); // `/?__pt=weather`
23
+ * }
24
+ * ```
25
+ */
26
+ export type AuthoringHostConfig = Omit<ServerConfig, 'adapters' | 'auth' | 'draftStore'> & {
27
+ /** Where the pages are kept, `<id>.json` each — read back when the host starts, so a restart serves them still. */
28
+ dir: string;
29
+ /** Who may show the pages in an iframe, as CSP `frame-ancestors` sources: the app that shows them. */
30
+ frameAncestors?: string[];
31
+ };
32
+ export type AuthoringHost = {
33
+ server: SSRServer;
34
+ /**
35
+ * Keeps a space under `id` — a new one when left out, which nobody can guess — replacing what it held, and answers
36
+ * the address its pages are at: its home is `path`, any other page that path with the page's own in front of `?`.
37
+ */
38
+ put: (documents: AuthoredDocuments, options?: {
39
+ id?: string;
40
+ }) => {
41
+ id: string;
42
+ path: string;
43
+ };
44
+ /** Forgets a page: its address answers 404 from then on. Whether there was one. */
45
+ drop: (id: string) => boolean;
46
+ /** The ids it serves. */
47
+ ids: () => string[];
48
+ };
49
+ export declare const createAuthoringHost: ({ dir, frameAncestors, ...config }: AuthoringHostConfig) => AuthoringHost;
@@ -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.16",
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.16",
100
+ "@plitzi/sdk-shared": "0.38.16",
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 |