@plitzi/sdk-server 0.39.4 → 0.39.7

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 (43) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/cloudAdapters.d.ts +7 -0
  4. package/dist/adapters/space/index.d.ts +2 -0
  5. package/dist/adapters/space/resolvers.d.ts +14 -3
  6. package/dist/adapters/space/snapshotPreview.d.ts +45 -0
  7. package/dist/adapters/space/types.d.ts +4 -1
  8. package/dist/cache.js +1 -1
  9. package/dist/chunks/{buildBody-BSC0UbjP.js → buildBody-Bm398uxH.js} +600 -63
  10. package/dist/chunks/{core-w7FIMpgv.js → core-CoKORAOg.js} +149 -23
  11. package/dist/chunks/{createServer-BQ0KE0Qu.js → createServer-BSmQqzwb.js} +31 -607
  12. package/dist/chunks/{platform-C0AVlwpB.js → platform-BTssQQXp.js} +1 -1
  13. package/dist/chunks/sdkAssets-CXGoc_WE.js +60 -0
  14. package/dist/chunks/{token-CBUubxtm.js → token-XEz1n4jp.js} +1 -1
  15. package/dist/chunks/views/template.ejs +5 -0
  16. package/dist/core/services/robotsTxt.d.ts +3 -1
  17. package/dist/deploy/aws/s3.d.ts +51 -0
  18. package/dist/deploy/aws/sigv4.d.ts +33 -0
  19. package/dist/deploy/contentType.d.ts +2 -0
  20. package/dist/deploy/fingerprint.d.ts +18 -0
  21. package/dist/deploy/folder.d.ts +6 -0
  22. package/dist/deploy/ftp.d.ts +27 -0
  23. package/dist/deploy/sdkFiles.d.ts +11 -0
  24. package/dist/deploy/spaShell.d.ts +35 -0
  25. package/dist/deploy/staticSite.d.ts +44 -0
  26. package/dist/deploy/types.d.ts +58 -0
  27. package/dist/deploy/zip.d.ts +8 -0
  28. package/dist/deploy.d.ts +24 -0
  29. package/dist/deploy.js +938 -0
  30. package/dist/handlers.js +1 -1
  31. package/dist/helpers/ownVersion.d.ts +1 -0
  32. package/dist/index.js +3 -3
  33. package/dist/oauth.js +1 -1
  34. package/dist/platform.js +1 -1
  35. package/dist/project.js +3 -3
  36. package/dist/spaces.d.ts +2 -2
  37. package/dist/spaces.js +1 -1
  38. package/dist/ssr.d.ts +1 -1
  39. package/dist/ssr.js +1 -1
  40. package/package.json +15 -13
  41. package/skills/plitzi-authoring/reference/authoring-errors.md +8 -4
  42. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  43. package/skills/plitzi-authoring/reference/layouts.md +2 -1
@@ -1,5 +1,5 @@
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
- import { createRequire } from "node:module";
1
+ import { A as sentInParts, E as scriptTemplateParams, H as hydrationPayload, O as pageSchemaOf, S as buildServerInfo, U as offlineDataWith, V as digest$1, W as spaceDocument, ct as visitorScheme, it as offlineDataCacheKeyOf, j as createOfflineDataLoader, k as partTextOf, lt as readCookie, pt as requestPaintedStateWithDefaults, w as googleFontsUrlOf, x as resolveDebugMode } from "./core-CoKORAOg.js";
2
+ import { n as pageAssets, r as resolveSdkAssetsDir } from "./sdkAssets-CXGoc_WE.js";
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";
5
5
  import fs from "node:fs/promises";
@@ -13,10 +13,12 @@ import { PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, SPACE_TOKEN_PARAM, authorizesDebug
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
- import { fontUrlResolver, fontsToHead } from "@plitzi/sdk-shared/style";
16
+ import { fontUrlResolver, fontsToHead, inPluginLayer } from "@plitzi/sdk-shared/style";
17
17
  import { pathToFileURL } from "node:url";
18
- import { readFileSync, statSync } from "node:fs";
19
- import { writeFileAtomic } from "@plitzi/sdk-kernel/files";
18
+ import fs$1, { readFileSync } from "node:fs";
19
+ import { copyFileAtomic, writeFileAtomic } from "@plitzi/sdk-kernel/files";
20
+ import { esbuildBuild } from "@plitzi/sdk-kernel/build";
21
+ import { pluginAssetLoaders, pluginImportQueries } from "@plitzi/sdk-shared/plugins/bundle";
20
22
  import { renderToString } from "react-dom/server";
21
23
  import PlitziSdk from "@plitzi/plitzi-sdk";
22
24
  import { jsx } from "react/jsx-runtime";
@@ -195,6 +197,596 @@ var draftSessionCookie = (req, token, ttlMs) => [
195
197
  `Max-Age=${Math.max(0, Math.floor(ttlMs / 1e3))}`,
196
198
  ...req.protocol === "https" ? ["Secure"] : []
197
199
  ].join("; ");
200
+ // src/plugins/compile.ts
201
+ var EXTERNAL = [
202
+ "react",
203
+ "react-dom",
204
+ "react-dom/client",
205
+ "react/jsx-runtime",
206
+ "@plitzi/plitzi-sdk",
207
+ "@plitzi/sdk-shared"
208
+ ];
209
+ /**
210
+ * Everything that went into the bundle, so a server can tell when any of it has moved on: a dev server as it is
211
+ * edited, and any server — a deployment — when it finds a bundle built from something else (its content digest).
212
+ *
213
+ * The entry file is one file and a plugin is a directory: a component edited beside its `index.ts` leaves the entry's
214
+ * timestamp exactly where it was, and a watcher looking only at that never rebuilds. esbuild already knows the answer
215
+ * — this is its own list of inputs — so nothing has to be guessed from the file system.
216
+ *
217
+ * Dependencies are left out. They change when something is installed, which is not an edit anybody is waiting to see,
218
+ * and stat'ing a few thousand files on every cache miss to find that out is a real cost for no answer.
219
+ */
220
+ var sourceInputs = (metafile) => metafile ? Object.keys(metafile.inputs).filter((input) => !input.includes("node_modules")).map((input) => path.resolve(input.replace(/^plitzi-(raw|inline):/, ""))) : [];
221
+ var compilePlugin = async (jsPath, outDir, devMode = false) => {
222
+ const result = await esbuildBuild({
223
+ entryPoints: [jsPath],
224
+ bundle: true,
225
+ format: "esm",
226
+ external: EXTERNAL,
227
+ loader: pluginAssetLoaders(),
228
+ plugins: [pluginImportQueries()],
229
+ outdir: outDir,
230
+ entryNames: "index",
231
+ jsx: "automatic",
232
+ minify: !devMode,
233
+ splitting: false,
234
+ logLevel: "warning",
235
+ metafile: true,
236
+ write: false
237
+ });
238
+ await fs.mkdir(outDir, { recursive: true });
239
+ await Promise.all(result.outputFiles.map((output) => writeFileAtomic(output.path, output.path.endsWith(".css") ? inPluginLayer(output.text) : output.contents)));
240
+ return {
241
+ hasCSS: result.outputFiles.some((output) => path.basename(output.path) === "index.css"),
242
+ inputs: sourceInputs(result.metafile)
243
+ };
244
+ };
245
+ // src/plugins/copy.ts
246
+ var copyPlugin = async (src, destDir, filename) => {
247
+ const dest = path.join(destDir, filename);
248
+ if (src.startsWith("http://") || src.startsWith("https://")) {
249
+ const res = await fetch(src);
250
+ if (!res.ok) throw new Error(`[SSR] Plugin fetch failed ${src}: ${res.status}`);
251
+ await writeFileAtomic(dest, await res.text());
252
+ } else await copyFileAtomic(src, dest);
253
+ };
254
+ /**
255
+ * A plugin's stylesheet, copied or downloaded into the cache in the plugins' cascade layer — below the space's styles,
256
+ * as a compiled one is — whatever the file it came from says.
257
+ */
258
+ var copyPluginStylesheet = async (src, destDir) => {
259
+ let css;
260
+ if (src.startsWith("http://") || src.startsWith("https://")) {
261
+ const res = await fetch(src);
262
+ if (!res.ok) throw new Error(`[SSR] Plugin stylesheet fetch failed ${src}: ${res.status}`);
263
+ css = await res.text();
264
+ } else css = await fs.readFile(src, "utf8");
265
+ await writeFileAtomic(path.join(destDir, "index.css"), inPluginLayer(css));
266
+ };
267
+ // src/plugins/detect.ts
268
+ var isComponentSource = (source) => "component" in source;
269
+ var detectAction = (js) => {
270
+ if (js.startsWith("http://") || js.startsWith("https://")) return "copy";
271
+ if (js.endsWith(".tsx") || js.endsWith(".ts") || js.endsWith(".jsx")) return "compile";
272
+ return "copy";
273
+ };
274
+ // src/plugins/validate.ts
275
+ var isRemote = (js) => js.startsWith("http://") || js.startsWith("https://");
276
+ /** The file a plugin source needs on disk, or null when nothing local is involved — a remote URL (fetched and
277
+ * cached at request time) or a component handed in directly. */
278
+ var localSourcePath = (source) => {
279
+ if (isComponentSource(source) || isRemote(source.js)) return null;
280
+ return source.js;
281
+ };
282
+ /** Fail at boot on a plugin whose entry file is missing. A plugin entry is a plain string path in the server
283
+ * config, so nothing — not tsc, not eslint — notices when that file is moved or deleted; without this check the
284
+ * server starts happily and only dies on the first render that needs the plugin, with an esbuild resolve error
285
+ * far from its cause. */
286
+ var assertPluginSources = (plugins) => {
287
+ const missing = Object.entries(plugins).map(([name, source]) => ({
288
+ name,
289
+ file: localSourcePath(source)
290
+ })).filter((entry) => entry.file !== null && !fs$1.existsSync(entry.file)).map((entry) => ` ${entry.name}: ${entry.file ?? ""}`);
291
+ if (missing.length > 0) throw new Error(`Plugin entry file not found (declared in the server config):\n${missing.join("\n")}`);
292
+ };
293
+ // src/plugins/manager.ts
294
+ var META_FILE = "meta.json";
295
+ var DEFAULT_TTL_MS = 6048e5;
296
+ var DEFAULT_CACHE_DIR = "tmp/.sdk-plugins";
297
+ /** How long a rebuild of vanished bundles waits, once none is pending, for another of the same render to be noticed. */
298
+ var RESTORE_SETTLE_MS = 100;
299
+ /** One hash over every input's path and content — a file gone counts as changed, like a file edited. */
300
+ var digestOf = async (files) => {
301
+ const hash = createHash("sha256");
302
+ for (const file of [...files].sort()) {
303
+ hash.update(file);
304
+ hash.update("\0");
305
+ hash.update(await fs.readFile(file).catch(() => Buffer.from("\0missing")));
306
+ }
307
+ return hash.digest("hex");
308
+ };
309
+ /**
310
+ * Whether a key is this plugin — every version of it, or with `version` that one release — counting the sources a
311
+ * render named under it (`name@1.0.0+<identity>`, see {@link PluginManager.ensure}).
312
+ */
313
+ var isKeyOf = (key, name, version) => {
314
+ if (version) return key === `${name}@${version}` || key.startsWith(`${name}@${version}+`);
315
+ return key === name || key.startsWith(`${name}@`);
316
+ };
317
+ /**
318
+ * How often a dev server re-asks whether a cached plugin is still current.
319
+ *
320
+ * The check is a handful of `stat`s and this runs on every render, so it is throttled rather than free — a second is
321
+ * far below what anybody notices between saving a file and reloading a page, and far above per-request.
322
+ */
323
+ var STALE_CHECK_MS = 1e3;
324
+ var PluginManager = class {
325
+ urlPrefix = "/sdk-plugins";
326
+ outputDir;
327
+ plugins;
328
+ ttlMs;
329
+ mem = /* @__PURE__ */ new Map();
330
+ inflight = /* @__PURE__ */ new Map();
331
+ failed = /* @__PURE__ */ new Set();
332
+ /** Maps base plugin name → most recently registered effective key (may include @version) */
333
+ nameIndex = /* @__PURE__ */ new Map();
334
+ devMode = false;
335
+ /** Who is told what each built plugin was built from — a dev server's watcher (`watchPluginSources`). */
336
+ sourceListeners = /* @__PURE__ */ new Set();
337
+ /** The bundles being built again because they vanished from disk under this server — see `restore`. */
338
+ restoring;
339
+ constructor(plugins, cacheDir, ttlMs, devMode = false) {
340
+ assertPluginSources(plugins);
341
+ this.plugins = plugins;
342
+ this.outputDir = path.resolve(process.cwd(), cacheDir ?? DEFAULT_CACHE_DIR);
343
+ this.ttlMs = ttlMs ?? DEFAULT_TTL_MS;
344
+ this.devMode = devMode;
345
+ for (const key of Object.keys(plugins)) {
346
+ const baseName = key.replace(/@[^@]*$/, "");
347
+ this.nameIndex.set(baseName, key);
348
+ }
349
+ }
350
+ /**
351
+ * Tells `listener` the files every built plugin was built from — those built so far, at once, and each one built or
352
+ * found built from now on. Only a compiled plugin has any: a copied or downloaded one is not this server's source.
353
+ */
354
+ onSources(listener) {
355
+ this.sourceListeners.add(listener);
356
+ this.mem.forEach((cached, key) => {
357
+ if (cached.inputs?.length) listener(key, cached.inputs);
358
+ });
359
+ return () => {
360
+ this.sourceListeners.delete(listener);
361
+ };
362
+ }
363
+ /**
364
+ * Builds a plugin again because its source changed — and again after a build that failed, which `prepare` otherwise
365
+ * never retries: the edit that fixes a syntax error is exactly the one a dev server must not ignore.
366
+ */
367
+ async rebuild(name) {
368
+ const key = this.resolveKey(name) ?? name;
369
+ this.mem.delete(key);
370
+ this.failed.delete(key);
371
+ return this.prepare(key);
372
+ }
373
+ remember(key, cached) {
374
+ this.mem.set(key, cached);
375
+ const { inputs } = cached;
376
+ if (inputs?.length) this.sourceListeners.forEach((listener) => {
377
+ listener(key, inputs);
378
+ });
379
+ }
380
+ hasPlugin(name) {
381
+ return this.resolveKey(name) !== null;
382
+ }
383
+ /**
384
+ * A plugin no longer there — its folder removed under a dev server: never built again, nothing of it remembered. A run's
385
+ * preview logged "build failed … Could not resolve" for a plugin a task had deleted, build after build.
386
+ */
387
+ unregister(name) {
388
+ const base = name.replace(/@[^@]*$/, "");
389
+ for (const key of Object.keys(this.plugins).filter((each) => each.replace(/@[^@]*$/, "") === base)) Reflect.deleteProperty(this.plugins, key);
390
+ this.forget(base);
391
+ }
392
+ register(name, source) {
393
+ this.plugins[name] = source;
394
+ this.mem.delete(name);
395
+ this.failed.delete(name);
396
+ const baseName = name.replace(/@[^@]*$/, "");
397
+ this.nameIndex.set(baseName, name);
398
+ }
399
+ /**
400
+ * Keeps a source a render names, and returns the key to pass to getEntries(): `name@version+<identity>`, or
401
+ * `name@<identity>` without a version.
402
+ *
403
+ * The identity is what the source IS — where its files are, how they are served, the props it carries — because a
404
+ * name and a version are only what its author said about it. Keyed on those alone, the first source to arrive held
405
+ * the key for as long as the process ran: a plugin published again under the same version kept its old, now missing
406
+ * URLs, and two spaces each with a `board@1.0.0` of their own were served whichever this process had met first.
407
+ * Worked out from the source rather than handed out in order of arrival, so every worker names one source the same
408
+ * way — the key is also the folder a built bundle is written to, and all of them share it.
409
+ *
410
+ * Never taken as what a bare name means: {@link resolveKey} answers for the plugins this server was set up with, not
411
+ * for whichever space rendered last.
412
+ */
413
+ ensure(name, source) {
414
+ const identity = createHash("sha256").update(JSON.stringify([
415
+ source.js,
416
+ source.css,
417
+ isComponentSource(source) ? void 0 : source.action,
418
+ source.props
419
+ ])).digest("hex").slice(0, 12);
420
+ const key = `${name}@${source.version ? `${source.version}+` : ""}${identity}`;
421
+ if (!(key in this.plugins)) this.plugins[key] = source;
422
+ return key;
423
+ }
424
+ /**
425
+ * Resolves a caller-supplied name to the effective key stored in the plugins map.
426
+ * Accepts both the exact key (`plitziBuilder@1.0.0`) and the base name (`plitziBuilder`).
427
+ */
428
+ resolveKey(name) {
429
+ if (name in this.plugins) return name;
430
+ const indexed = this.nameIndex.get(name);
431
+ if (indexed && indexed in this.plugins) return indexed;
432
+ return null;
433
+ }
434
+ pluginDir(name) {
435
+ return path.join(this.outputDir, name);
436
+ }
437
+ isExpired(compiledAt) {
438
+ return Date.now() - compiledAt > this.ttlMs;
439
+ }
440
+ /**
441
+ * Whether anything the bundle was built from has moved on since. Dev mode only.
442
+ *
443
+ * The cache is keyed on time and version, neither of which changes when somebody edits a component: a versioned
444
+ * plugin never expires and an unversioned one lasts a week, so a change to the source showed up nowhere and the
445
+ * server kept serving the bundle it built the first time. In production that is exactly right — a deployment's
446
+ * plugins do not change under it — and while somebody is writing one it is a file that appears to do nothing.
447
+ *
448
+ * Every INPUT, not the entry file. A plugin is a directory and the entry is usually a barrel that re-exports it, so
449
+ * watching only `source.js` answers "nothing has changed" to every edit anybody actually makes — the file whose
450
+ * timestamp moves is the component next to it. The list comes from the build itself (see `compilePlugin`), so it is
451
+ * exactly what went in, including a file imported from another plugin's folder. A bundle built before this existed
452
+ * has no list, and falls back to the entry file rather than claiming to be fresh.
453
+ */
454
+ /**
455
+ * The same question of the entry this process is holding, asked at most once a second.
456
+ *
457
+ * `checkedAt` is stamped on the cached entry rather than kept in a second map, so it cannot outlive what it is about.
458
+ */
459
+ async isStaleInMemory(cached, source) {
460
+ if (!this.devMode) return false;
461
+ const now = Date.now();
462
+ if (cached.checkedAt && now - cached.checkedAt < STALE_CHECK_MS) return false;
463
+ cached.checkedAt = now;
464
+ return this.isStale({
465
+ compiledAt: cached.compiledAt,
466
+ inputs: cached.inputs
467
+ }, source);
468
+ }
469
+ /**
470
+ * Whether what a bundle on disk was built from reads differently now — asked once, when a process first finds the
471
+ * bundle, in production as much as in development.
472
+ *
473
+ * A version names a release, and a release is only as good as whoever bumps it: a deployment rebuilt from new source
474
+ * under the same version found last deployment's bundle in its cache folder and served it, with nothing anywhere
475
+ * saying so. The content decides instead. A bundle written before digests were recorded has none, and is built again
476
+ * once. What this server does not build from files — a download, a CDN, a component — is its version's business.
477
+ */
478
+ async contentChanged(meta, source) {
479
+ const inputs = this.inputsOf(source, meta.inputs ?? []);
480
+ if (inputs.length === 0) return false;
481
+ return meta.digest !== await digestOf(inputs);
482
+ }
483
+ /** The local files a bundle is built from: what the compiler reported, or the files it was copied from. */
484
+ inputsOf(source, compiled) {
485
+ if (isComponentSource(source) || source.action === "download" || source.action === "cdn") return [];
486
+ if (compiled.length > 0) return compiled;
487
+ return [source.js, source.css].filter((file) => typeof file === "string" && file !== "" && !/^https?:\/\//.test(file));
488
+ }
489
+ async isStale(meta, source) {
490
+ if (!this.devMode || !source.js || /^https?:\/\//.test(source.js) || isComponentSource(source)) return false;
491
+ const watched = meta.inputs?.length ? meta.inputs : [source.js];
492
+ if (meta.inputs?.length) {
493
+ const entry = await fs.realpath(source.js).catch(() => path.resolve(source.js));
494
+ if (!meta.inputs.includes(entry)) return true;
495
+ }
496
+ return (await Promise.all(watched.map((file) => fs.stat(file).then((stats) => stats.mtimeMs).catch(() => Number.POSITIVE_INFINITY)))).some((modifiedAt) => modifiedAt > meta.compiledAt);
497
+ }
498
+ /**
499
+ * The bundle's URL, stamped with when it was built.
500
+ *
501
+ * Plugin assets are served `immutable` for a year, which is right for a file whose URL identifies its contents
502
+ * and catastrophic for one whose URL never changes: a browser told a resource is immutable does not revalidate
503
+ * it at all — no conditional request, no ETag — so a rebuilt plugin never reaches anyone who had already loaded
504
+ * the old one. Not a stale render either: the page's own CSS is fresh while the plugin's is a year old, and the
505
+ * two disagree in ways nobody can read. The stamp is what makes the promise true.
506
+ */
507
+ assetUrl(name, file, compiledAt) {
508
+ return `${this.urlPrefix}/${name}/${file}?v=${compiledAt.toString(36)}`;
509
+ }
510
+ toEntry(name, hasJS, cssUrl, props = {}, compiledAt = 0) {
511
+ const keyName = name.split("@")[0];
512
+ return {
513
+ name,
514
+ varName: keyName.split("-").join("_").split(".").join("_"),
515
+ keyName,
516
+ js: hasJS ? this.assetUrl(name, "index.js", compiledAt) : void 0,
517
+ filePath: hasJS ? path.join(this.outputDir, name, "index.js") : void 0,
518
+ css: cssUrl,
519
+ props
520
+ };
521
+ }
522
+ /**
523
+ * A plugin served from where it was published, with nothing on this server's disk.
524
+ *
525
+ * No `filePath`, which is the whole point: `loadPluginComponents` only imports entries that have one, so a
526
+ * bundle this server did not build never enters the render process — and cannot bring a second copy of React
527
+ * in with it. The template already imports `js` in the browser, so the plugin still renders, just on the
528
+ * client.
529
+ */
530
+ toRemoteEntry(name, source) {
531
+ const keyName = name.split("@")[0];
532
+ return {
533
+ name,
534
+ varName: keyName.split("-").join("_").split(".").join("_"),
535
+ keyName,
536
+ js: source.js,
537
+ css: source.css,
538
+ props: source.props ?? {}
539
+ };
540
+ }
541
+ isWebUrl(s) {
542
+ return s.startsWith("/") || s.startsWith("http://") || s.startsWith("https://");
543
+ }
544
+ /**
545
+ * Builds every registered plugin now rather than on first use. A primary does it before starting its workers, so
546
+ * the workers find each one built — instead of all of them compiling the same plugin into the same folder at once.
547
+ */
548
+ async prepareAll() {
549
+ await Promise.all(Object.keys(this.plugins).map((key) => this.prepare(key)));
550
+ }
551
+ async prepare(name) {
552
+ const key = this.resolveKey(name) ?? name;
553
+ if (this.failed.has(key)) return null;
554
+ const inflight = this.inflight.get(key);
555
+ if (inflight !== void 0) return inflight;
556
+ const source = this.plugins[key];
557
+ if (source === void 0) return null;
558
+ if (isComponentSource(source) && !source.js) return this.toEntry(key, false, void 0, source.props);
559
+ if (!isComponentSource(source) && source.action === "cdn") return this.toRemoteEntry(key, source);
560
+ const cached = this.mem.get(key);
561
+ let missing = false;
562
+ if (cached && !this.isExpired(cached.compiledAt)) {
563
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.js"))) {
564
+ /**
565
+ * The disk check below never runs while this process holds the entry in memory, and a versioned plugin never
566
+ * expires — so without this a dev server serves the bundle it built when it started, for as long as it runs.
567
+ * Nothing else brings it back either: the components are named by PATH rather than imported, so editing one
568
+ * does not even restart the watcher.
569
+ */
570
+ if (!await this.isStaleInMemory(cached, source)) return cached.entry;
571
+ serverLog.info("SSR", `Plugin "${key}" source changed since it was built, rebuilding…`);
572
+ this.mem.delete(key);
573
+ await fs.rm(this.pluginDir(key), {
574
+ recursive: true,
575
+ force: true
576
+ });
577
+ } else {
578
+ serverLog.info("SSR", `Plugin "${key}" output missing, rebuilding…`);
579
+ this.mem.delete(key);
580
+ missing = true;
581
+ }
582
+ }
583
+ const meta = await this.readMeta(key);
584
+ if (meta) {
585
+ const sourceVersion = source.version;
586
+ if (await this.isStale(meta, source) || await this.contentChanged(meta, source)) {
587
+ serverLog.info("SSR", `Plugin "${key}" source changed since it was built, rebuilding…`);
588
+ await fs.rm(this.pluginDir(key), {
589
+ recursive: true,
590
+ force: true
591
+ });
592
+ } else if (sourceVersion && meta.version !== sourceVersion) {
593
+ serverLog.info("SSR", `Plugin "${key}" version changed (${meta.version ?? "none"} → ${sourceVersion}), rebuilding…`);
594
+ await fs.rm(this.pluginDir(key), {
595
+ recursive: true,
596
+ force: true
597
+ });
598
+ } else if (sourceVersion || !this.isExpired(meta.compiledAt)) {
599
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.js"))) {
600
+ const sourceCss = source.css;
601
+ let cssUrl;
602
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.css"))) cssUrl = this.assetUrl(key, "index.css", meta.compiledAt);
603
+ else if (sourceCss && this.isWebUrl(sourceCss)) cssUrl = sourceCss;
604
+ const entry = this.toEntry(key, true, cssUrl, source.props, meta.compiledAt);
605
+ this.remember(key, {
606
+ compiledAt: meta.compiledAt,
607
+ entry,
608
+ inputs: meta.inputs
609
+ });
610
+ return entry;
611
+ }
612
+ }
613
+ }
614
+ const promise = this.build(key, source).finally(() => this.inflight.delete(key));
615
+ this.inflight.set(key, promise);
616
+ if (missing) this.restore(key, promise);
617
+ return promise;
618
+ }
619
+ /**
620
+ * Bundles that vanished from disk under a running server are built again as one episode: said once when the first
621
+ * is noticed and once when the last is built — how many, how long, which failed — at the level it was noticed at.
622
+ * Said per plugin, it was a warning for each and a "ready" for each at a level a project's terminal does not show,
623
+ * so the rebuild never said it had finished.
624
+ */
625
+ restore(key, build) {
626
+ if (!this.restoring) {
627
+ this.restoring = {
628
+ started: Date.now(),
629
+ pending: /* @__PURE__ */ new Set(),
630
+ rebuilt: 0,
631
+ failed: []
632
+ };
633
+ const where = path.relative(process.cwd(), this.outputDir) || this.outputDir;
634
+ serverLog.warn("SSR", `Plugin bundles missing from ${where}: building them again…`);
635
+ }
636
+ const episode = this.restoring;
637
+ clearTimeout(episode.closing);
638
+ episode.pending.add(key);
639
+ build.then((entry) => {
640
+ episode.pending.delete(key);
641
+ if (entry) episode.rebuilt += 1;
642
+ else episode.failed.push(key);
643
+ if (episode.pending.size > 0) return;
644
+ episode.closing = setTimeout(() => {
645
+ if (this.restoring !== episode || episode.pending.size > 0) return;
646
+ this.restoring = void 0;
647
+ const seconds = ((Date.now() - episode.started) / 1e3).toFixed(1);
648
+ const failed = episode.failed.length > 0 ? ` — ${String(episode.failed.length)} failed (${episode.failed.join(", ")}), said above` : "";
649
+ serverLog.warn("SSR", `Plugin bundles built again: ${String(episode.rebuilt)} in ${seconds}s${failed}`);
650
+ }, RESTORE_SETTLE_MS);
651
+ episode.closing.unref();
652
+ });
653
+ }
654
+ async build(name, source) {
655
+ const dir = this.pluginDir(name);
656
+ await fs.mkdir(dir, { recursive: true });
657
+ const jsPath = source.js;
658
+ const cssPath = source.css;
659
+ const action = isComponentSource(source) ? source.js ? detectAction(source.js) : void 0 : source.action ?? detectAction(source.js);
660
+ if (!jsPath || !action) return this.toEntry(name, false, void 0, source.props);
661
+ serverLog.info("SSR", `Plugin "${name}" building (${action}: ${jsPath})…`);
662
+ try {
663
+ let cssUrl;
664
+ let buildInputs = [];
665
+ if (action === "compile") {
666
+ const { hasCSS, inputs } = await compilePlugin(jsPath, dir, this.devMode);
667
+ buildInputs = inputs;
668
+ if (hasCSS) cssUrl = `${this.urlPrefix}/${name}/index.css`;
669
+ else if (cssPath) {
670
+ if (this.isWebUrl(cssPath)) cssUrl = cssPath;
671
+ else {
672
+ await copyPluginStylesheet(cssPath, dir);
673
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
674
+ }
675
+ }
676
+ } else if (action === "download") {
677
+ const jsRes = await fetch(jsPath);
678
+ if (!jsRes.ok) throw new Error(`HTTP ${jsRes.status} downloading ${jsPath}`);
679
+ await writeFileAtomic(path.join(dir, "index.js"), await jsRes.text());
680
+ if (cssPath) {
681
+ if (cssPath.startsWith("http://") || cssPath.startsWith("https://")) await copyPluginStylesheet(cssPath, dir);
682
+ else if (this.isWebUrl(cssPath)) cssUrl = cssPath;
683
+ else await copyPluginStylesheet(cssPath, dir);
684
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
685
+ }
686
+ } else {
687
+ await copyPlugin(jsPath, dir, "index.js");
688
+ if (cssPath) {
689
+ if (this.isWebUrl(cssPath)) cssUrl = cssPath;
690
+ else {
691
+ await copyPluginStylesheet(cssPath, dir);
692
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
693
+ }
694
+ }
695
+ }
696
+ const compiledAt = Date.now();
697
+ const inputs = this.inputsOf(source, buildInputs);
698
+ await this.writeMeta(name, {
699
+ compiledAt,
700
+ version: source.version,
701
+ inputs: buildInputs,
702
+ ...inputs.length > 0 ? { digest: await digestOf(inputs) } : {}
703
+ });
704
+ if (cssUrl?.startsWith(this.urlPrefix)) cssUrl = this.assetUrl(name, "index.css", compiledAt);
705
+ const entry = this.toEntry(name, true, cssUrl, source.props, compiledAt);
706
+ this.remember(name, {
707
+ compiledAt,
708
+ entry,
709
+ inputs: buildInputs
710
+ });
711
+ serverLog.info("SSR", `Plugin "${name}" ready → ${entry.js}`);
712
+ return entry;
713
+ } catch (err) {
714
+ serverLog.error("SSR", `Plugin "${name}" build failed (js: ${source.js ?? "none"})`, err);
715
+ this.failed.add(name);
716
+ return null;
717
+ }
718
+ }
719
+ async getEntries(names) {
720
+ if (names.length === 0) return [];
721
+ return (await Promise.all(names.map((n) => this.prepare(n)))).filter((e) => e !== null && e.js !== void 0);
722
+ }
723
+ getComponents() {
724
+ const out = {};
725
+ for (const [name, source] of Object.entries(this.plugins)) if (isComponentSource(source)) out[name.replace(/@[^@]*$/, "")] = source.component;
726
+ return out;
727
+ }
728
+ /**
729
+ * Drops what this process remembers of a plugin — its entry, its failure, which version its name means — and
730
+ * leaves the disk alone. What an invalidation elsewhere in the fleet does here: that process removes the files,
731
+ * and each of the others only has to stop pointing at them.
732
+ */
733
+ forget(name, version) {
734
+ if (!name) {
735
+ this.mem.clear();
736
+ this.failed.clear();
737
+ this.nameIndex.clear();
738
+ return;
739
+ }
740
+ const keysToEvict = /* @__PURE__ */ new Set();
741
+ for (const key of [
742
+ ...Object.keys(this.plugins),
743
+ ...this.mem.keys(),
744
+ ...this.failed
745
+ ]) if (isKeyOf(key, name, version)) keysToEvict.add(key);
746
+ for (const key of keysToEvict) {
747
+ this.mem.delete(key);
748
+ this.failed.delete(key);
749
+ }
750
+ const indexed = this.nameIndex.get(name);
751
+ if (indexed !== void 0 && isKeyOf(indexed, name, version)) this.nameIndex.delete(name);
752
+ }
753
+ async invalidate(name, version) {
754
+ this.forget(name, version);
755
+ if (!name) {
756
+ await fs.rm(this.outputDir, {
757
+ recursive: true,
758
+ force: true
759
+ });
760
+ return;
761
+ }
762
+ try {
763
+ const entries = await fs.readdir(this.outputDir);
764
+ await Promise.all(entries.filter((entry) => isKeyOf(entry, name, version)).map((entry) => fs.rm(path.join(this.outputDir, entry), {
765
+ recursive: true,
766
+ force: true
767
+ })));
768
+ } catch {}
769
+ }
770
+ destroy() {
771
+ this.mem.clear();
772
+ this.failed.clear();
773
+ this.nameIndex.clear();
774
+ }
775
+ async readMeta(name) {
776
+ try {
777
+ const raw = await fs.readFile(path.join(this.pluginDir(name), META_FILE), "utf-8");
778
+ return JSON.parse(raw);
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+ async writeMeta(name, meta) {
784
+ await writeFileAtomic(path.join(this.pluginDir(name), META_FILE), JSON.stringify(meta));
785
+ }
786
+ async fileExists(p) {
787
+ return fs.access(p).then(() => true).catch(() => false);
788
+ }
789
+ };
198
790
  // src/modules/icons/glyphs.ts
199
791
  var FACE_RULE = /@font-face\{([^}]*)\}/g;
200
792
  var FACE_FIELD = (field) => new RegExp(`${field}:\\s*"?([^;"]+)"?`);
@@ -340,62 +932,6 @@ var unicodeRange = (codepoints) => {
340
932
  * glyph in its range is drawn from: the page fetches the space's few glyphs, not the whole font.
341
933
  */
342
934
  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
935
  // src/modules/ssr/resolvePageSeo.ts
400
936
  /**
401
937
  * The title and description the addressed page declares for itself.
@@ -1679,7 +2215,8 @@ var buildBody = async (req, config, spaceId, environment, revision, renderFn, pl
1679
2215
  const templateStart = metrics ? performance.now() : 0;
1680
2216
  const body = renderFn({
1681
2217
  ...prep.templateParams,
1682
- html
2218
+ html,
2219
+ ...result.prePaint ? { prePaint: result.prePaint } : {}
1683
2220
  });
1684
2221
  metrics?.record("template", Math.round(performance.now() - templateStart));
1685
2222
  return {
@@ -1689,4 +2226,4 @@ var buildBody = async (req, config, spaceId, environment, revision, renderFn, pl
1689
2226
  nonce: prep.templateParams.nonce ?? ""
1690
2227
  };
1691
2228
  };
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 };
2229
+ export { DRAFT_STORE_METHODS as C, invalidatePluginComponentCache as D, takeDraftOverride as E, matchRscPage as O, PluginManager as S, draftSessionCookie as T, resolveServices as _, applySSRResult as a, spaceIconsOf as b, withNotFound as c, SPACE_DOCUMENT_PATH as d, answerCurrentSpacePreflight as f, resolveRscEndpoint as g, meterPage as h, Component as i, 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, createMemoryDraftStore as w, iconGlyphsAt as x, ICONS_PATH as y };