@plitzi/sdk-server 0.39.3 → 0.39.4

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 (66) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +49 -7
  3. package/dist/auth.d.ts +3 -2
  4. package/dist/auth.js +26 -107
  5. package/dist/cache.js +1 -1
  6. package/dist/chunks/{buildBody-W9D8ySNY.js → buildBody-BSC0UbjP.js} +352 -110
  7. package/dist/chunks/{core-TlrWmT4B.js → core-w7FIMpgv.js} +86 -4
  8. package/dist/chunks/{createServer-Bd_b7T3k.js → createServer-BQ0KE0Qu.js} +157 -34
  9. package/dist/chunks/{platform-DhdFYWm5.js → platform-C0AVlwpB.js} +2 -2
  10. package/dist/chunks/throttle-CRiZB6_A.js +330 -0
  11. package/dist/chunks/{token-B2uY9JzU.js → token-CBUubxtm.js} +1 -1
  12. package/dist/chunks/views/template.ejs +7 -0
  13. package/dist/core/auth/api/context.d.ts +4 -4
  14. package/dist/core/auth/api/values.d.ts +6 -0
  15. package/dist/core/auth/createAuth.d.ts +1 -1
  16. package/dist/core/auth/throttle.d.ts +54 -4
  17. package/dist/core/createServer.d.ts +1 -1
  18. package/dist/core/platform.d.ts +1 -1
  19. package/dist/core/services/iconFaces.d.ts +3 -0
  20. package/dist/core/services/llmsTxt.d.ts +15 -0
  21. package/dist/core/services/robotsTxt.d.ts +2 -8
  22. package/dist/core/services/securityTxt.d.ts +10 -0
  23. package/dist/handlers.js +1 -1
  24. package/dist/helpers/documentParts.d.ts +10 -0
  25. package/dist/helpers/paintedCookie.d.ts +15 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +3 -3
  28. package/dist/modules/icons/glyphs.d.ts +21 -0
  29. package/dist/modules/icons/handler.d.ts +11 -0
  30. package/dist/modules/icons/spaceIcons.d.ts +26 -0
  31. package/dist/modules/rsc/connectorRscData.d.ts +4 -2
  32. package/dist/modules/rsc/resolveRscData.d.ts +4 -1
  33. package/dist/modules/ssr/csrfHint.d.ts +12 -0
  34. package/dist/modules/ssr/defaultFavicon.d.ts +1 -1
  35. package/dist/modules/ssr/spaceDocument.d.ts +8 -1
  36. package/dist/oauth.js +1 -1
  37. package/dist/platform.d.ts +1 -1
  38. package/dist/platform.js +1 -1
  39. package/dist/project.js +3 -3
  40. package/dist/spaces.js +1 -1
  41. package/dist/ssr.js +1 -1
  42. package/dist/types/config.d.ts +24 -0
  43. package/dist/types/index.d.ts +1 -1
  44. package/package.json +10 -8
  45. package/skills/plitzi-authoring/recipes/accordion.ts +3 -1
  46. package/skills/plitzi-authoring/recipes/carousel.ts +68 -63
  47. package/skills/plitzi-authoring/recipes/detail-page.ts +43 -33
  48. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +16 -11
  49. package/skills/plitzi-authoring/recipes/every-few-seconds.ts +52 -42
  50. package/skills/plitzi-authoring/recipes/feature-flag.ts +7 -2
  51. package/skills/plitzi-authoring/recipes/filter-a-list.ts +39 -31
  52. package/skills/plitzi-authoring/recipes/forms-and-modals.ts +34 -28
  53. package/skills/plitzi-authoring/recipes/from-tailwind.ts +11 -6
  54. package/skills/plitzi-authoring/recipes/link-to-a-section.ts +11 -6
  55. package/skills/plitzi-authoring/recipes/link-with-data.ts +21 -16
  56. package/skills/plitzi-authoring/recipes/marquee.ts +17 -12
  57. package/skills/plitzi-authoring/recipes/plugin.ts +16 -10
  58. package/skills/plitzi-authoring/recipes/scroll-a-row.ts +30 -25
  59. package/skills/plitzi-authoring/recipes/server-data.ts +15 -10
  60. package/skills/plitzi-authoring/recipes/show-data.ts +32 -24
  61. package/skills/plitzi-authoring/recipes/style-a-page.ts +9 -4
  62. package/skills/plitzi-authoring/recipes/typed-data.ts +26 -21
  63. package/skills/plitzi-authoring/recipes/usable-without-sight.ts +16 -11
  64. package/skills/plitzi-authoring/reference/authoring-errors.md +3 -0
  65. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  66. package/dist/chunks/throttle-BH7JLIOF.js +0 -108
@@ -1,4 +1,4 @@
1
- import { $ as visitorScheme, C as createOfflineDataLoader, F as offlineDataWith, I as spaceDocument, N as digest, P as hydrationPayload, Y as offlineDataCacheKeyOf, _ as buildServerInfo, et as readCookie, g as resolveDebugMode, it as requestPaintedState, x as scriptTemplateParams, y as googleFontsUrlOf } from "./core-TlrWmT4B.js";
1
+ import { C as pageSchemaOf, E as createOfflineDataLoader, I as digest$1, L as hydrationPayload, Q as offlineDataCacheKeyOf, R as offlineDataWith, T as sentInParts, _ as buildServerInfo, g as resolveDebugMode, nt as visitorScheme, rt as readCookie, st as requestPaintedStateWithDefaults, w as partTextOf, x as scriptTemplateParams, y as googleFontsUrlOf, z as spaceDocument } from "./core-w7FIMpgv.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { fetchOutbound, privateOriginsOf } from "@plitzi/sdk-kernel/outbound";
4
4
  import { collectServerElements, isOgType, jsonForScript, mayReceive, notFoundProvider, pageElementTypes, pageHeadTags, pageNotFound, pageSeoText, pageServerContext, pageStructuredData, pageWithheldOf, spaceIdentity, withholdPages } from "@plitzi/sdk-shared/schema";
@@ -9,13 +9,13 @@ import { serverLog } from "@plitzi/sdk-kernel/log";
9
9
  import { flagUserFromSSR, flagValues, requestFlagOverrides, resolveFlags } from "@plitzi/sdk-shared/flags";
10
10
  import { getPaths, matchRoutePath } from "@plitzi/sdk-shared/navigation";
11
11
  import { IMAGE_PATH, IMAGE_WIDTHS, isImageWidth } from "@plitzi/sdk-shared/helpers";
12
- import { PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, SPACE_TOKEN_PARAM, authorizesDebugging, readDraftToken } from "@plitzi/sdk-kernel/identity";
12
+ import { PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, SPACE_TOKEN_PARAM, authorizesDebugging, csrfCookieName, readDraftToken } from "@plitzi/sdk-kernel/identity";
13
13
  import { debugCookieName } from "@plitzi/sdk-shared/devTools";
14
14
  import { themeFromCookies } from "@plitzi/sdk-shared/theme/cookie";
15
15
  import crypto, { createHash } from "node:crypto";
16
16
  import { fontUrlResolver, fontsToHead } from "@plitzi/sdk-shared/style";
17
17
  import { pathToFileURL } from "node:url";
18
- import { statSync } from "node:fs";
18
+ import { readFileSync, statSync } from "node:fs";
19
19
  import { writeFileAtomic } from "@plitzi/sdk-kernel/files";
20
20
  import { renderToString } from "react-dom/server";
21
21
  import PlitziSdk from "@plitzi/plitzi-sdk";
@@ -195,6 +195,245 @@ var draftSessionCookie = (req, token, ttlMs) => [
195
195
  `Max-Age=${Math.max(0, Math.floor(ttlMs / 1e3))}`,
196
196
  ...req.protocol === "https" ? ["Secure"] : []
197
197
  ].join("; ");
198
+ // src/modules/icons/glyphs.ts
199
+ var FACE_RULE = /@font-face\{([^}]*)\}/g;
200
+ var FACE_FIELD = (field) => new RegExp(`${field}:\\s*"?([^;"]+)"?`);
201
+ var FACE_FILE = /url\(webfonts\/([\w.-]+)\)/;
202
+ var GLYPH_RULE = /((?:\.fa-[a-z0-9-]+,?)+)\{--fa:"((?:\\[0-9a-f]+ ?)|[^"\\])"/g;
203
+ var BRANDS_FAMILY = "Font Awesome 7 Brands";
204
+ /** A CSS string's one character: `\f00c`, `\30 ` (an escape and the space that ends it) or the character itself. */
205
+ var codepointOf = (value) => value.startsWith("\\") ? Number.parseInt(value.slice(1).trim(), 16) : value.codePointAt(0) ?? 0;
206
+ var faceKey = (family, weight) => {
207
+ if (family === BRANDS_FAMILY) return "brands";
208
+ if (weight === "900") return "solid";
209
+ return weight === "400" ? "regular" : void 0;
210
+ };
211
+ /**
212
+ * The SDK's icon stylesheet read for what it draws: each name's glyph, the faces and their files. The sheet is Font
213
+ * Awesome's sheets one after another (`apps/sdk`'s `iconsPlugin`), the brands' last: a name declared after the brands'
214
+ * face is a brand.
215
+ */
216
+ var parseIconGlyphs = (css) => {
217
+ const faces = [];
218
+ for (const [, body] of css.matchAll(FACE_RULE)) {
219
+ const family = FACE_FIELD("font-family").exec(body)?.[1];
220
+ const weight = FACE_FIELD("font-weight").exec(body)?.[1];
221
+ const file = FACE_FILE.exec(body)?.[1];
222
+ const key = family && weight ? faceKey(family, weight) : void 0;
223
+ if (family && weight && file && key) faces.push({
224
+ key,
225
+ family,
226
+ weight,
227
+ file
228
+ });
229
+ }
230
+ const brandsFrom = css.indexOf(`"${BRANDS_FAMILY}"`);
231
+ const codepoints = /* @__PURE__ */ new Map();
232
+ const brands = /* @__PURE__ */ new Set();
233
+ for (const match of css.matchAll(GLYPH_RULE)) {
234
+ const codepoint = codepointOf(match[2]);
235
+ for (const selector of match[1].split(",")) {
236
+ const name = selector.slice(1);
237
+ codepoints.set(name, codepoint);
238
+ if (brandsFrom >= 0 && match.index > brandsFrom) brands.add(name);
239
+ }
240
+ }
241
+ return {
242
+ codepoints,
243
+ brands,
244
+ faces
245
+ };
246
+ };
247
+ var read = /* @__PURE__ */ new Map();
248
+ /** The glyphs of the SDK installed at `sdkDir`, read once per process. */
249
+ var iconGlyphsAt = (sdkDir) => {
250
+ const known = read.get(sdkDir);
251
+ if (known) return known;
252
+ const glyphs = parseIconGlyphs(readFileSync(path.join(sdkDir, "plitzi-sdk-icons.css"), "utf8"));
253
+ read.set(sdkDir, glyphs);
254
+ return glyphs;
255
+ };
256
+ // src/modules/icons/spaceIcons.ts
257
+ /** Where a space's own icon faces are served: `/_plitzi/icons/<hash>-<face>.woff2`. */
258
+ var ICONS_PATH = "/_plitzi/icons/";
259
+ var JSON_STRING = /"(?:[^"\\]|\\.)*"/g;
260
+ var ICON_TOKEN = /\b(?:far|fas|fab|fa-(?:regular|solid|brands)|fa-[a-z0-9]+(?:-[a-z0-9]+)*)\b/g;
261
+ var STYLE_OF = {
262
+ far: "regular",
263
+ "fa-regular": "regular",
264
+ fas: "solid",
265
+ "fa-solid": "solid",
266
+ fab: "brands",
267
+ "fa-brands": "brands"
268
+ };
269
+ /**
270
+ * Each icon a text names, with the face its style class before it says — `far fa-heart` is the regular face's, `fa-check`
271
+ * alone the solid one's (Font Awesome's default) — and a brand's always its own.
272
+ */
273
+ var namedIcons = (text, glyphs) => {
274
+ const faces = {
275
+ solid: /* @__PURE__ */ new Set(),
276
+ regular: /* @__PURE__ */ new Set(),
277
+ brands: /* @__PURE__ */ new Set()
278
+ };
279
+ for (const [literal] of text.matchAll(JSON_STRING)) {
280
+ let style = "solid";
281
+ for (const [token] of literal.matchAll(ICON_TOKEN)) {
282
+ const named = STYLE_OF[token];
283
+ if (named) {
284
+ style = named;
285
+ continue;
286
+ }
287
+ const codepoint = glyphs.codepoints.get(token);
288
+ if (codepoint !== void 0) faces[glyphs.brands.has(token) ? "brands" : style === "brands" ? "solid" : style].add(codepoint);
289
+ }
290
+ }
291
+ return faces;
292
+ };
293
+ var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 16);
294
+ var found = /* @__PURE__ */ new WeakMap();
295
+ /**
296
+ * The glyphs a space names anywhere in its document — an attribute, a component's props, a binding's template, a flow's
297
+ * params: `'fas fa-check'` and both sides of `open ? 'fa-chevron-up' : 'fa-chevron-down'` alike. An icon named only by
298
+ * data the space reads at run time is not here, and needs nothing: the whole font is declared before these faces, so
299
+ * the browser draws a glyph these lack from it.
300
+ */
301
+ var spaceIconsOf = (offlineData, glyphs) => {
302
+ const known = found.get(offlineData.schema);
303
+ if (known !== void 0) return known ?? void 0;
304
+ const icons = iconsIn(JSON.stringify(offlineData.schema), glyphs);
305
+ found.set(offlineData.schema, icons ?? null);
306
+ return icons;
307
+ };
308
+ var iconsIn = (text, glyphs) => {
309
+ const named = namedIcons(text, glyphs);
310
+ const cut = glyphs.faces.flatMap((face) => {
311
+ const codepoints = [...named[face.key]].sort((a, b) => a - b);
312
+ return codepoints.length > 0 ? [{
313
+ ...face,
314
+ codepoints
315
+ }] : [];
316
+ });
317
+ if (cut.length === 0) return;
318
+ const hash = digest(cut.map((face) => `${face.key}:${face.codepoints.join(",")}`).join(";"));
319
+ return {
320
+ hash,
321
+ faces: cut.map((face) => ({
322
+ ...face,
323
+ href: `${ICONS_PATH}${hash}-${face.key}.woff2`
324
+ }))
325
+ };
326
+ };
327
+ var hex = (codepoint) => codepoint.toString(16).toUpperCase();
328
+ /** The codepoints (sorted) as a `unicode-range`, a run of consecutive ones written as one: `U+F00C-F00E`. */
329
+ var unicodeRange = (codepoints) => {
330
+ const runs = [];
331
+ for (const codepoint of codepoints) {
332
+ const last = runs.at(-1);
333
+ if (last && codepoint === last[1] + 1) last[1] = codepoint;
334
+ else runs.push([codepoint, codepoint]);
335
+ }
336
+ return runs.map(([from, to]) => from === to ? `U+${hex(from)}` : `U+${hex(from)}-${hex(to)}`).join(",");
337
+ };
338
+ /**
339
+ * The faces as the head declares them. Declared after the whole font's, a face with a `unicode-range` is the one a
340
+ * glyph in its range is drawn from: the page fetches the space's few glyphs, not the whole font.
341
+ */
342
+ var iconFacesCss = (icons) => icons.faces.map((face) => `@font-face{font-family:"${face.family}";font-style:normal;font-weight:${face.weight};font-display:block;src:url(${face.href}) format("woff2");unicode-range:${unicodeRange(face.codepoints)}}`).join("");
343
+ // src/core/sdkAssets.ts
344
+ /** Where the rendered page is told to fetch the SDK bundle from. Emitted by the render, so it is also served. */
345
+ var SDK_ASSETS_PREFIX = "/sdk-assets";
346
+ var resolvedSdkDir;
347
+ /**
348
+ * The SDK's built output, resolved through the module system rather than guessed from `process.cwd()`.
349
+ *
350
+ * The rendered page asks for `/sdk-assets/plitzi-sdk.js` — the server puts that URL there itself — so the server is
351
+ * also what should answer it. It used to be a mount every deployment had to declare, and forgetting it produced no
352
+ * error at all: the asset requests fell through to the page renderer, which answered each one with a 200 and an HTML
353
+ * document. The browser then refused them for their MIME type and the page stayed blank. A missing line of config
354
+ * that looks like a broken SDK is not a choice worth offering.
355
+ *
356
+ * Returns undefined if the SDK is not installed, which is legitimate: a server rendering `ssrOnly` pages, or one
357
+ * whose deployment serves the bundle from a CDN, needs none of this.
358
+ */
359
+ var resolveSdkAssetsDir = () => {
360
+ if (resolvedSdkDir) return resolvedSdkDir.dir;
361
+ try {
362
+ const require = createRequire(import.meta.url);
363
+ resolvedSdkDir = { dir: path.dirname(require.resolve("@plitzi/plitzi-sdk/plitzi-sdk.css")) };
364
+ } catch {
365
+ resolvedSdkDir = { dir: void 0 };
366
+ }
367
+ return resolvedSdkDir.dir;
368
+ };
369
+ /**
370
+ * A cache-buster for the SDK URLs, taken from the bundle's own mtime.
371
+ *
372
+ * The assets are served with a long `Cache-Control`, so something has to change in the URL when the bundle does or
373
+ * browsers keep the old one. Since the version a deployment runs IS the version of this package, the server can work
374
+ * it out — nobody should have to compute it and pass it in, and forgetting to is a stale bundle nobody can explain.
375
+ */
376
+ var cachedVersion;
377
+ var sdkAssetVersion = () => {
378
+ if (cachedVersion !== void 0) return cachedVersion;
379
+ const dir = resolveSdkAssetsDir();
380
+ try {
381
+ cachedVersion = dir ? Math.floor(statSync(path.join(dir, "plitzi-sdk.js")).mtimeMs).toString(36) : "";
382
+ } catch {
383
+ cachedVersion = "";
384
+ }
385
+ return cachedVersion;
386
+ };
387
+ var pageAssets = (assetVersion) => {
388
+ const version = assetVersion ?? sdkAssetVersion();
389
+ const v = version ? `?v=${version}` : "";
390
+ return {
391
+ jsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk.js${v}`,
392
+ cssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk.css${v}`,
393
+ iconsCssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-icons.css${v}`,
394
+ devToolsCssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-devtools.css${v}`,
395
+ vendorJsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-vendor.js${v}`,
396
+ devVendorJsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-dev-vendor.js${v}`
397
+ };
398
+ };
399
+ // src/modules/ssr/resolvePageSeo.ts
400
+ /**
401
+ * The title and description the addressed page declares for itself.
402
+ *
403
+ * The page element has carried `seoEnabled` / `seoPageTitle` / `seoPageDescription` all along — the builder edits
404
+ * them and the client renders them into the head through Helmet — but the SSR document was built from a constant,
405
+ * so every server-rendered page arrived titled the same. That is the half a crawler and a link preview see, which
406
+ * is the half that matters: they read the document as delivered and never run the client.
407
+ *
408
+ * `seoEnabled: false` returns nothing rather than a default, so the deployment's own title stays in charge of a
409
+ * page that opted out. Blank strings are treated as absent for the same reason — the builder writes one for a
410
+ * field the author cleared, and an empty <title> is worse than a generic one.
411
+ *
412
+ * Either may be a template over the page's server providers and the address (`pageServerContext`): a detail page says
413
+ * the title of the record it shows, in the HTML a crawler reads. One that does not evaluate is nothing, as a blank is.
414
+ * So may each text of its JSON-LD (`pageStructuredData`).
415
+ */
416
+ var resolvePageSeo = (schema, pageId, context = {}) => {
417
+ if (!schema || !pageId) return {};
418
+ const page = schema.flat[pageId];
419
+ if (!page?.attributes.seoEnabled) return {};
420
+ const title = pageSeoText(page.attributes.seoPageTitle, context);
421
+ const description = pageSeoText(page.attributes.seoPageDescription, context);
422
+ const robots = typeof page.attributes.seoRobots === "string" ? page.attributes.seoRobots.trim() : "";
423
+ const structuredData = pageStructuredData(page.attributes.seoStructuredData, context).map(jsonForScript);
424
+ const image = pageSeoText(page.attributes.seoImage, context);
425
+ const imageAlt = pageSeoText(page.attributes.seoImageAlt, context);
426
+ const { seoType } = page.attributes;
427
+ return {
428
+ ...title ? { title } : {},
429
+ ...description ? { description } : {},
430
+ ...robots ? { robots } : {},
431
+ ...structuredData.length > 0 ? { structuredData } : {},
432
+ ...image ? { image } : {},
433
+ ...image && imageAlt ? { imageAlt } : {},
434
+ ...isOgType(seoType) ? { type: seoType } : {}
435
+ };
436
+ };
198
437
  // src/core/services/resolve.ts
199
438
  var resolveServices = (config) => {
200
439
  const services = config.services ?? {};
@@ -244,6 +483,8 @@ var SPACE_DOCUMENT_PATH = "/_plitzi/space/";
244
483
  /** The space as it is now, for a page that renders it itself rather than one the server drew (`handleCurrentSpace`). */
245
484
  var CURRENT_SPACE_PATH = "/_plitzi/space.json";
246
485
  var DOCUMENT_PATH = /^\/_plitzi\/space\/([\w-]{1,64})\.json$/;
486
+ /** One part of a space sent in parts (`documentParts`), by its name: what a navigation to a page not yet held fetches. */
487
+ var PART_PATH = /^\/_plitzi\/space\/part\/([\w-]{1,64})\.json$/;
247
488
  /**
248
489
  * The documents this process just put in a page, so the request that follows is answered without reading the space
249
490
  * again. Bounded: a document is megabytes, and only the latest of each space is ever asked for twice.
@@ -251,8 +492,15 @@ var DOCUMENT_PATH = /^\/_plitzi\/space\/([\w-]{1,64})\.json$/;
251
492
  var RECENT = 8;
252
493
  var recent = /* @__PURE__ */ new Map();
253
494
  var recentKey = (spaceId, environment, hash) => `${String(spaceId)}|${environment}|${hash}`;
495
+ /**
496
+ * The page a document of the space in parts is that page's: its shell and its own part. Named in its address so that a
497
+ * process that did not draw the page — another replica, a process restarted — answers the same document rather than
498
+ * the whole space (`documentNow`), which it did: a visitor whose page and document reached two processes downloaded
499
+ * every page of the space.
500
+ */
501
+ var PAGE_PARAM = "page";
254
502
  /** Where the page fetches `document` from — and the promise that this process can answer it. */
255
- var publishSpaceDocument = (spaceId, environment, document, kept = []) => {
503
+ var publishSpaceDocument = (spaceId, environment, document, kept = [], pageId) => {
256
504
  const key = recentKey(spaceId, environment, document.hash);
257
505
  recent.delete(key);
258
506
  recent.set(key, {
@@ -263,7 +511,8 @@ var publishSpaceDocument = (spaceId, environment, document, kept = []) => {
263
511
  if (recent.size <= RECENT) break;
264
512
  recent.delete(oldest);
265
513
  }
266
- return `${SPACE_DOCUMENT_PATH}${document.hash}.json`;
514
+ const page = pageId === void 0 ? "" : `?${PAGE_PARAM}=${encodeURIComponent(pageId)}`;
515
+ return `${SPACE_DOCUMENT_PATH}${document.hash}.json${page}`;
267
516
  };
268
517
  var sendNoData = (res, spaceId, environment) => {
269
518
  res.setStatus(404);
@@ -279,7 +528,7 @@ var sendNoData = (res, spaceId, environment) => {
279
528
  * it (`prepareRender`): an environment that is not the live draft is read once per version, and `cached` says this
280
529
  * request was answered from that copy — the cheaper visit, as a page served from the cache is.
281
530
  */
282
- var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
531
+ var documentNow = async (req, config, offlineDataCache, { linkStyle, pageId }) => {
283
532
  const { environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
284
533
  const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
285
534
  const cacheKey = offlineDataCacheKeyOf(req.ctx.spaceDeployment);
@@ -287,9 +536,11 @@ var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
287
536
  const offlineData = held ?? await config.adapters.getOfflineData(spaceId, environment, revision);
288
537
  if (!offlineData) return;
289
538
  if (cacheKey && !held) offlineDataCache?.set(cacheKey, offlineData);
290
- const { schema, kept } = withholdPages(offlineData.schema, req.ctx.user);
291
- const document = spaceDocument(offlineDataWith(offlineData, schema), { linkStyle });
292
- publishSpaceDocument(spaceId, environment, document, kept);
539
+ const { schema, kept, withheld } = withholdPages(offlineData.schema, req.ctx.user);
540
+ const ofPage = linkStyle && pageId !== void 0 && schema.pages.includes(pageId) && sentInParts(schema) ? pageId : void 0;
541
+ const sent = ofPage === void 0 ? schema : pageSchemaOf(schema, withheld, ofPage);
542
+ const document = spaceDocument(offlineDataWith(offlineData, sent), { linkStyle });
543
+ publishSpaceDocument(spaceId, environment, document, kept, ofPage);
293
544
  return {
294
545
  document,
295
546
  cached: held !== void 0
@@ -304,6 +555,11 @@ var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
304
555
  * but not to be kept under a name that is not its own.
305
556
  */
306
557
  var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
558
+ const part = PART_PATH.exec(req.path)?.[1];
559
+ if (part) {
560
+ await handleSpacePart(req, res, config, part, offlineDataCache);
561
+ return;
562
+ }
307
563
  const hash = DOCUMENT_PATH.exec(req.path)?.[1];
308
564
  const { environment = "main" } = req.ctx.spaceDeployment ?? {};
309
565
  const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
@@ -316,7 +572,11 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
316
572
  let json = known && mayReceive(known.kept, req.ctx.user) ? known.json : void 0;
317
573
  let current = json !== void 0;
318
574
  if (json === void 0) {
319
- const found = await documentNow(req, config, offlineDataCache, { linkStyle: !req.query[SPACE_TOKEN_PARAM] });
575
+ const pageId = req.query[PAGE_PARAM];
576
+ const found = await documentNow(req, config, offlineDataCache, {
577
+ linkStyle: !req.query[SPACE_TOKEN_PARAM],
578
+ ...typeof pageId === "string" ? { pageId } : {}
579
+ });
320
580
  if (!found) {
321
581
  sendNoData(res, spaceId, environment);
322
582
  return;
@@ -329,6 +589,38 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
329
589
  res.send(json);
330
590
  };
331
591
  /**
592
+ * Answers `/_plitzi/space/part/<name>.json`: one part of the space, from this visitor's own split — the space as they
593
+ * may be sent it (`withholdPages`) — so a part of a page they may not see, or of a layout only such pages are drawn in,
594
+ * is none of theirs and answers 404, as a name the space no longer has does. A page that is answered 404 loads the
595
+ * address it was going to from the server, which draws it or says why not.
596
+ */
597
+ var handleSpacePart = async (req, res, config, name, offlineDataCache) => {
598
+ const { environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
599
+ const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
600
+ const cacheKey = offlineDataCacheKeyOf(req.ctx.spaceDeployment);
601
+ const held = cacheKey ? offlineDataCache?.get(cacheKey) : void 0;
602
+ const offlineData = held ?? await config.adapters.getOfflineData(spaceId, environment, revision);
603
+ if (!offlineData) {
604
+ sendNoData(res, spaceId, environment);
605
+ return;
606
+ }
607
+ if (cacheKey && !held) offlineDataCache?.set(cacheKey, offlineData);
608
+ const { schema, withheld } = withholdPages(offlineData.schema, req.ctx.user);
609
+ const text = partTextOf(schema, withheld, name);
610
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
611
+ if (text === void 0) {
612
+ res.setHeader("Cache-Control", "no-store");
613
+ res.setStatus(404);
614
+ res.send(JSON.stringify({
615
+ error: `No part "${name}" of this space for this visitor: the space changed since the page was drawn, or the part is a page they may not see`,
616
+ reason: "part_gone"
617
+ }));
618
+ return;
619
+ }
620
+ res.setHeader("Cache-Control", `${req.ctx.user ? "private" : "public"}, max-age=31536000, immutable`);
621
+ res.send(text);
622
+ };
623
+ /**
332
624
  * Lets a page of another origin read the space with its credential: the origins the credential was granted for
333
625
  * (`renderGrant` checked the page's against them), never any other. A page this host serves needs none of it.
334
626
  */
@@ -407,7 +699,7 @@ var handleCurrentSpace = async (req, res, config, offlineDataCache) => {
407
699
  ...decision?.badge ? { badge: decision.badge } : {}
408
700
  };
409
701
  const visitJson = JSON.stringify(visit);
410
- const etag = `"${document.hash}.${digest(visitJson)}"`;
702
+ const etag = `"${document.hash}.${digest$1(visitJson)}"`;
411
703
  res.setHeader("Cache-Control", "private, no-cache");
412
704
  res.setHeader("ETag", etag);
413
705
  if (req.headers["if-none-match"] === etag) {
@@ -501,6 +793,26 @@ var Component = ({ server, renderMode = "raw", previewMode = true, offlineData,
501
793
  }, key))
502
794
  });
503
795
  };
796
+ // src/modules/ssr/csrfHint.ts
797
+ /**
798
+ * What a page is told about the CSRF token its writes to the deployment's own APIs echo: those APIs, the cookie each
799
+ * keeps it in, and where a new one is handed out (`rsc.visitorCredentials`) — as JSON, for `<meta name="plitzi-csrf">`.
800
+ * Only on the pages of a space trusted to carry its visitors' sessions there; none where the deployment names no
801
+ * `csrfPath`.
802
+ */
803
+ var csrfHintFor = async (config, space) => {
804
+ const visitor = config.rsc?.visitorCredentials;
805
+ if (!visitor?.csrfPath || visitor.origins.length === 0) return;
806
+ if (visitor.spaces && !await visitor.spaces(space)) return;
807
+ const hint = {
808
+ apis: visitor.origins.map((origin) => ({
809
+ origin,
810
+ cookie: csrfCookieName(new URL(origin).hostname, config.authCookie)
811
+ })),
812
+ path: visitor.csrfPath
813
+ };
814
+ return JSON.stringify(hint);
815
+ };
504
816
  // src/modules/ssr/registerExternalPlugins.ts
505
817
  var MANIFEST_TTL_MS = 6e5;
506
818
  var manifestCache = /* @__PURE__ */ new Map();
@@ -633,44 +945,6 @@ var reportMissingPlugins = (spaceId, schema, available) => {
633
945
  serverLog.error("SSR", `Space ${String(spaceId)} renders the plugin "${renderType}" (element "${elementId}"), and this server has none by that name, so the page shows "Custom Component ${renderType} Not Found". Register it in \`plugins\` and name it in the deployment's \`pluginNames\`.`);
634
946
  }
635
947
  };
636
- // src/modules/ssr/resolvePageSeo.ts
637
- /**
638
- * The title and description the addressed page declares for itself.
639
- *
640
- * The page element has carried `seoEnabled` / `seoPageTitle` / `seoPageDescription` all along — the builder edits
641
- * them and the client renders them into the head through Helmet — but the SSR document was built from a constant,
642
- * so every server-rendered page arrived titled the same. That is the half a crawler and a link preview see, which
643
- * is the half that matters: they read the document as delivered and never run the client.
644
- *
645
- * `seoEnabled: false` returns nothing rather than a default, so the deployment's own title stays in charge of a
646
- * page that opted out. Blank strings are treated as absent for the same reason — the builder writes one for a
647
- * field the author cleared, and an empty <title> is worse than a generic one.
648
- *
649
- * Either may be a template over the page's server providers and the address (`pageServerContext`): a detail page says
650
- * the title of the record it shows, in the HTML a crawler reads. One that does not evaluate is nothing, as a blank is.
651
- * So may each text of its JSON-LD (`pageStructuredData`).
652
- */
653
- var resolvePageSeo = (schema, pageId, context = {}) => {
654
- if (!schema || !pageId) return {};
655
- const page = schema.flat[pageId];
656
- if (!page?.attributes.seoEnabled) return {};
657
- const title = pageSeoText(page.attributes.seoPageTitle, context);
658
- const description = pageSeoText(page.attributes.seoPageDescription, context);
659
- const robots = typeof page.attributes.seoRobots === "string" ? page.attributes.seoRobots.trim() : "";
660
- const structuredData = pageStructuredData(page.attributes.seoStructuredData, context).map(jsonForScript);
661
- const image = pageSeoText(page.attributes.seoImage, context);
662
- const imageAlt = pageSeoText(page.attributes.seoImageAlt, context);
663
- const { seoType } = page.attributes;
664
- return {
665
- ...title ? { title } : {},
666
- ...description ? { description } : {},
667
- ...robots ? { robots } : {},
668
- ...structuredData.length > 0 ? { structuredData } : {},
669
- ...image ? { image } : {},
670
- ...image && imageAlt ? { imageAlt } : {},
671
- ...isOgType(seoType) ? { type: seoType } : {}
672
- };
673
- };
674
948
  // src/modules/images/allowlist.ts
675
949
  /**
676
950
  * Whether a host is one a picture may come from: named exactly (`images.example.com`), or under a wildcard
@@ -1036,59 +1310,6 @@ var imagesStage = async (ctx) => {
1036
1310
  ctx.res.send(answer.body);
1037
1311
  return true;
1038
1312
  };
1039
- // src/core/sdkAssets.ts
1040
- /** Where the rendered page is told to fetch the SDK bundle from. Emitted by the render, so it is also served. */
1041
- var SDK_ASSETS_PREFIX = "/sdk-assets";
1042
- /**
1043
- * The SDK's built output, resolved through the module system rather than guessed from `process.cwd()`.
1044
- *
1045
- * The rendered page asks for `/sdk-assets/plitzi-sdk.js` — the server puts that URL there itself — so the server is
1046
- * also what should answer it. It used to be a mount every deployment had to declare, and forgetting it produced no
1047
- * error at all: the asset requests fell through to the page renderer, which answered each one with a 200 and an HTML
1048
- * document. The browser then refused them for their MIME type and the page stayed blank. A missing line of config
1049
- * that looks like a broken SDK is not a choice worth offering.
1050
- *
1051
- * Returns undefined if the SDK is not installed, which is legitimate: a server rendering `ssrOnly` pages, or one
1052
- * whose deployment serves the bundle from a CDN, needs none of this.
1053
- */
1054
- var resolveSdkAssetsDir = () => {
1055
- try {
1056
- const require = createRequire(import.meta.url);
1057
- return path.dirname(require.resolve("@plitzi/plitzi-sdk/plitzi-sdk.css"));
1058
- } catch {
1059
- return;
1060
- }
1061
- };
1062
- /**
1063
- * A cache-buster for the SDK URLs, taken from the bundle's own mtime.
1064
- *
1065
- * The assets are served with a long `Cache-Control`, so something has to change in the URL when the bundle does or
1066
- * browsers keep the old one. Since the version a deployment runs IS the version of this package, the server can work
1067
- * it out — nobody should have to compute it and pass it in, and forgetting to is a stale bundle nobody can explain.
1068
- */
1069
- var cachedVersion;
1070
- var sdkAssetVersion = () => {
1071
- if (cachedVersion !== void 0) return cachedVersion;
1072
- const dir = resolveSdkAssetsDir();
1073
- try {
1074
- cachedVersion = dir ? Math.floor(statSync(path.join(dir, "plitzi-sdk.js")).mtimeMs).toString(36) : "";
1075
- } catch {
1076
- cachedVersion = "";
1077
- }
1078
- return cachedVersion;
1079
- };
1080
- var pageAssets = (assetVersion) => {
1081
- const version = assetVersion ?? sdkAssetVersion();
1082
- const v = version ? `?v=${version}` : "";
1083
- return {
1084
- jsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk.js${v}`,
1085
- cssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk.css${v}`,
1086
- iconsCssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-icons.css${v}`,
1087
- devToolsCssPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-devtools.css${v}`,
1088
- vendorJsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-vendor.js${v}`,
1089
- devVendorJsPath: `${SDK_ASSETS_PREFIX}/plitzi-sdk-dev-vendor.js${v}`
1090
- };
1091
- };
1092
1313
  // src/modules/ssr/prepareRender.tsx
1093
1314
  /** Last resort only: used for a page that declares no SEO title and a deployment that supplies none either. */
1094
1315
  var DEFAULT_TITLE = "Plitzi App";
@@ -1164,9 +1385,11 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
1164
1385
  loadOfflineData,
1165
1386
  flagOverrides
1166
1387
  })) : rscPath ? { serverData: {} } : void 0;
1388
+ const origin = requestOrigin(req);
1167
1389
  const navigation = {
1168
1390
  routeParams: pageMatch?.routeParams ?? {},
1169
- queryParams: req.query
1391
+ queryParams: req.query,
1392
+ ...origin === "" ? {} : { origin }
1170
1393
  };
1171
1394
  const pageContext = pageServerContext(serverElements, rscData?.serverData ?? {}, navigation);
1172
1395
  const pageSeo = resolvePageSeo(schema, pageMatch?.pageId, pageContext);
@@ -1247,9 +1470,14 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
1247
1470
  * the defaults the server drew. Read here, the server draws with it, and the page starts from the same values: it
1248
1471
  * travels as the SDK's `state`, the starting `runtime.state`, in the render and in the payload alike, or the client
1249
1472
  * would hydrate other markup. Only the keys the space declares, only with `keepState` on, and of an entry another
1250
- * account wrote than the one this request proved, only the browser's (`browserState`).
1473
+ * account wrote than the one this request proved, only the browser's (`browserState`). A key it holds none of, for an
1474
+ * account the request proved, is the deployment's default (`paintedDefaults`) — the one its providers asked with.
1251
1475
  */
1252
- const paintedState = requestPaintedState(req, schema?.settings, req.ctx.user?.id).state;
1476
+ const paintedState = (await requestPaintedStateWithDefaults(req, schema?.settings, {
1477
+ spaceId: req.ctx.spaceDeployment?.spaceId ?? spaceId,
1478
+ environment: req.ctx.spaceDeployment?.environment ?? environment,
1479
+ account: req.ctx.user?.id
1480
+ }, config.paintedDefaults)).state;
1253
1481
  /**
1254
1482
  * The two layers of the space's flags this server answers for. Its own (`config.flags`), asked per space when it
1255
1483
  * serves several; and the ones a tester forced from the dev tools, read from their cookie — only for a page allowed
@@ -1276,9 +1504,22 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
1276
1504
  * not know to link it.
1277
1505
  */
1278
1506
  const linkStyle = offlineDataOverride === void 0 && !spaceToken && config.templateFn === void 0;
1279
- const document = offlineData !== void 0 ? spaceDocument(offlineData, { linkStyle }) : void 0;
1280
- const publishedDocument = document !== void 0 && offlineDataOverride === void 0 && config.templateFn === void 0 && config.ssrOnly !== true ? publishSpaceDocument(spaceId, environment, document, withholding?.kept ?? []) : void 0;
1281
- const spaceDocumentPath = publishedDocument && spaceToken ? `${publishedDocument}?${SPACE_TOKEN_PARAM}=${encodeURIComponent(spaceToken)}` : publishedDocument;
1507
+ /**
1508
+ * The space in parts (`documentParts`): this page's own elements and its layouts', the rest named and fetched as a
1509
+ * link to it is followed. Only where the document travels beside the page under the host's own name — whole for a
1510
+ * draft, a space named by a token (`linkStyle`), a deployment's own template, and a URL that is no page.
1511
+ */
1512
+ const inParts = linkStyle && config.ssrOnly !== true && pageMatch !== void 0 && offlineData !== void 0 && sentInParts(offlineData.schema);
1513
+ const sentData = inParts ? offlineDataWith(offlineData, pageSchemaOf(offlineData.schema, withholding?.withheld ?? [], pageMatch.pageId)) : offlineData;
1514
+ const document = sentData !== void 0 ? spaceDocument(sentData, { linkStyle }) : void 0;
1515
+ const sdkDir = linkStyle && rawOfflineData ? resolveSdkAssetsDir() : void 0;
1516
+ const spaceIcons = sdkDir && rawOfflineData ? spaceIconsOf(rawOfflineData, iconGlyphsAt(sdkDir)) : void 0;
1517
+ const csrfHint = await csrfHintFor(config, {
1518
+ spaceId: req.ctx.spaceDeployment?.spaceId ?? spaceId,
1519
+ environment: req.ctx.spaceDeployment?.environment ?? environment
1520
+ });
1521
+ const publishedDocument = document !== void 0 && offlineDataOverride === void 0 && config.templateFn === void 0 && config.ssrOnly !== true ? publishSpaceDocument(spaceId, environment, document, withholding?.kept ?? [], inParts ? pageMatch.pageId : void 0) : void 0;
1522
+ const spaceDocumentPath = publishedDocument && spaceToken ? `${publishedDocument}${publishedDocument.includes("?") ? "&" : "?"}${SPACE_TOKEN_PARAM}=${encodeURIComponent(spaceToken)}` : publishedDocument;
1282
1523
  const offlineDataStr = hydrationPayload(offlineData, {
1283
1524
  offlineMode: true,
1284
1525
  environment,
@@ -1344,7 +1585,6 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
1344
1585
  });
1345
1586
  const vendorJs = debugRendered ? assets.devVendorJsPath : assets.vendorJsPath;
1346
1587
  const deploymentProps = req.ctx.spaceDeployment?.templateProps;
1347
- const origin = requestOrigin(req);
1348
1588
  const head = pageHeadTags({
1349
1589
  title: pageSeo.title ?? deploymentProps?.title ?? DEFAULT_TITLE,
1350
1590
  ...pageSeo.description ?? deploymentProps?.description ? { description: pageSeo.description ?? deploymentProps?.description } : {},
@@ -1378,6 +1618,8 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
1378
1618
  jsPath: assets.jsPath,
1379
1619
  cssPath: assets.cssPath,
1380
1620
  iconsCssPath: sdkIconsStylePath,
1621
+ ...spaceIcons ? { iconFaces: iconFacesCss(spaceIcons) } : {},
1622
+ ...csrfHint ? { csrfHint } : {},
1381
1623
  spaceDocumentPath,
1382
1624
  styleSheetPath: document?.data.style.cacheHref,
1383
1625
  react: vendorJs,
@@ -1447,4 +1689,4 @@ var buildBody = async (req, config, spaceId, environment, revision, renderFn, pl
1447
1689
  nonce: prep.templateParams.nonce ?? ""
1448
1690
  };
1449
1691
  };
1450
- export { draftSessionCookie as C, matchRscPage as E, createMemoryDraftStore as S, invalidatePluginComponentCache as T, handleSpaceDocument as _, resolveSdkAssetsDir as a, resolveServices as b, applySSRResult as c, withNotFound as d, withRefusal as f, handleCurrentSpace as g, answerCurrentSpacePreflight as h, pageAssets as i, isReusable as l, SPACE_DOCUMENT_PATH as m, prepareRender as n, imagesStage as o, CURRENT_SPACE_PATH as p, SDK_ASSETS_PREFIX as r, Component as s, buildBody as t, renderParamsOf as u, meterPage as v, takeDraftOverride as w, DRAFT_STORE_METHODS as x, resolveRscEndpoint as y };
1692
+ export { matchRscPage as A, spaceIconsOf as C, draftSessionCookie as D, createMemoryDraftStore as E, takeDraftOverride as O, ICONS_PATH as S, DRAFT_STORE_METHODS as T, resolveServices as _, applySSRResult as a, pageAssets as b, withNotFound as c, SPACE_DOCUMENT_PATH as d, answerCurrentSpacePreflight as f, resolveRscEndpoint as g, meterPage as h, Component as i, invalidatePluginComponentCache as k, withRefusal as l, handleSpaceDocument as m, prepareRender as n, isReusable as o, handleCurrentSpace as p, imagesStage as r, renderParamsOf as s, buildBody as t, CURRENT_SPACE_PATH as u, resolvePageSeo as v, iconGlyphsAt as w, resolveSdkAssetsDir as x, SDK_ASSETS_PREFIX as y };