@plitzi/sdk-server 0.39.3 → 0.39.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +50 -8
- package/dist/adapters/cloudAdapters.d.ts +7 -0
- package/dist/adapters/space/index.d.ts +2 -0
- package/dist/adapters/space/resolvers.d.ts +14 -3
- package/dist/adapters/space/snapshotPreview.d.ts +45 -0
- package/dist/adapters/space/types.d.ts +4 -1
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +26 -107
- package/dist/cache.js +1 -1
- package/dist/chunks/{buildBody-W9D8ySNY.js → buildBody-Bm398uxH.js} +893 -114
- package/dist/chunks/{core-TlrWmT4B.js → core-CoKORAOg.js} +234 -26
- package/dist/chunks/{createServer-Bd_b7T3k.js → createServer-BSmQqzwb.js} +186 -639
- package/dist/chunks/{platform-DhdFYWm5.js → platform-BTssQQXp.js} +2 -2
- package/dist/chunks/sdkAssets-CXGoc_WE.js +60 -0
- package/dist/chunks/throttle-CRiZB6_A.js +330 -0
- package/dist/chunks/{token-B2uY9JzU.js → token-XEz1n4jp.js} +1 -1
- package/dist/chunks/views/template.ejs +12 -0
- package/dist/core/auth/api/context.d.ts +4 -4
- package/dist/core/auth/api/values.d.ts +6 -0
- package/dist/core/auth/createAuth.d.ts +1 -1
- package/dist/core/auth/throttle.d.ts +54 -4
- package/dist/core/createServer.d.ts +1 -1
- package/dist/core/platform.d.ts +1 -1
- package/dist/core/services/iconFaces.d.ts +3 -0
- package/dist/core/services/llmsTxt.d.ts +15 -0
- package/dist/core/services/robotsTxt.d.ts +5 -9
- package/dist/core/services/securityTxt.d.ts +10 -0
- package/dist/deploy/aws/s3.d.ts +51 -0
- package/dist/deploy/aws/sigv4.d.ts +33 -0
- package/dist/deploy/contentType.d.ts +2 -0
- package/dist/deploy/fingerprint.d.ts +18 -0
- package/dist/deploy/folder.d.ts +6 -0
- package/dist/deploy/ftp.d.ts +27 -0
- package/dist/deploy/sdkFiles.d.ts +11 -0
- package/dist/deploy/spaShell.d.ts +35 -0
- package/dist/deploy/staticSite.d.ts +44 -0
- package/dist/deploy/types.d.ts +58 -0
- package/dist/deploy/zip.d.ts +8 -0
- package/dist/deploy.d.ts +24 -0
- package/dist/deploy.js +938 -0
- package/dist/handlers.js +1 -1
- package/dist/helpers/documentParts.d.ts +10 -0
- package/dist/helpers/ownVersion.d.ts +1 -0
- package/dist/helpers/paintedCookie.d.ts +15 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/modules/icons/glyphs.d.ts +21 -0
- package/dist/modules/icons/handler.d.ts +11 -0
- package/dist/modules/icons/spaceIcons.d.ts +26 -0
- package/dist/modules/rsc/connectorRscData.d.ts +4 -2
- package/dist/modules/rsc/resolveRscData.d.ts +4 -1
- package/dist/modules/ssr/csrfHint.d.ts +12 -0
- package/dist/modules/ssr/defaultFavicon.d.ts +1 -1
- package/dist/modules/ssr/spaceDocument.d.ts +8 -1
- package/dist/oauth.js +1 -1
- package/dist/platform.d.ts +1 -1
- package/dist/platform.js +1 -1
- package/dist/project.js +3 -3
- package/dist/spaces.d.ts +2 -2
- package/dist/spaces.js +1 -1
- package/dist/ssr.d.ts +1 -1
- package/dist/ssr.js +1 -1
- package/dist/types/config.d.ts +24 -0
- package/dist/types/index.d.ts +1 -1
- package/package.json +17 -13
- package/skills/plitzi-authoring/recipes/accordion.ts +3 -1
- package/skills/plitzi-authoring/recipes/carousel.ts +68 -63
- package/skills/plitzi-authoring/recipes/detail-page.ts +43 -33
- package/skills/plitzi-authoring/recipes/embed-and-svg.ts +16 -11
- package/skills/plitzi-authoring/recipes/every-few-seconds.ts +52 -42
- package/skills/plitzi-authoring/recipes/feature-flag.ts +7 -2
- package/skills/plitzi-authoring/recipes/filter-a-list.ts +39 -31
- package/skills/plitzi-authoring/recipes/forms-and-modals.ts +34 -28
- package/skills/plitzi-authoring/recipes/from-tailwind.ts +11 -6
- package/skills/plitzi-authoring/recipes/link-to-a-section.ts +11 -6
- package/skills/plitzi-authoring/recipes/link-with-data.ts +21 -16
- package/skills/plitzi-authoring/recipes/marquee.ts +17 -12
- package/skills/plitzi-authoring/recipes/plugin.ts +16 -10
- package/skills/plitzi-authoring/recipes/scroll-a-row.ts +30 -25
- package/skills/plitzi-authoring/recipes/server-data.ts +15 -10
- package/skills/plitzi-authoring/recipes/show-data.ts +32 -24
- package/skills/plitzi-authoring/recipes/style-a-page.ts +9 -4
- package/skills/plitzi-authoring/recipes/typed-data.ts +26 -21
- package/skills/plitzi-authoring/recipes/usable-without-sight.ts +16 -11
- package/skills/plitzi-authoring/reference/authoring-errors.md +11 -4
- package/skills/plitzi-authoring/reference/efficiency.md +3 -1
- package/skills/plitzi-authoring/reference/layouts.md +2 -1
- package/dist/chunks/throttle-BH7JLIOF.js +0 -108
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
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";
|
|
@@ -9,14 +9,16 @@ 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
|
-
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 {
|
|
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,779 @@ 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
|
+
};
|
|
790
|
+
// src/modules/icons/glyphs.ts
|
|
791
|
+
var FACE_RULE = /@font-face\{([^}]*)\}/g;
|
|
792
|
+
var FACE_FIELD = (field) => new RegExp(`${field}:\\s*"?([^;"]+)"?`);
|
|
793
|
+
var FACE_FILE = /url\(webfonts\/([\w.-]+)\)/;
|
|
794
|
+
var GLYPH_RULE = /((?:\.fa-[a-z0-9-]+,?)+)\{--fa:"((?:\\[0-9a-f]+ ?)|[^"\\])"/g;
|
|
795
|
+
var BRANDS_FAMILY = "Font Awesome 7 Brands";
|
|
796
|
+
/** A CSS string's one character: `\f00c`, `\30 ` (an escape and the space that ends it) or the character itself. */
|
|
797
|
+
var codepointOf = (value) => value.startsWith("\\") ? Number.parseInt(value.slice(1).trim(), 16) : value.codePointAt(0) ?? 0;
|
|
798
|
+
var faceKey = (family, weight) => {
|
|
799
|
+
if (family === BRANDS_FAMILY) return "brands";
|
|
800
|
+
if (weight === "900") return "solid";
|
|
801
|
+
return weight === "400" ? "regular" : void 0;
|
|
802
|
+
};
|
|
803
|
+
/**
|
|
804
|
+
* The SDK's icon stylesheet read for what it draws: each name's glyph, the faces and their files. The sheet is Font
|
|
805
|
+
* Awesome's sheets one after another (`apps/sdk`'s `iconsPlugin`), the brands' last: a name declared after the brands'
|
|
806
|
+
* face is a brand.
|
|
807
|
+
*/
|
|
808
|
+
var parseIconGlyphs = (css) => {
|
|
809
|
+
const faces = [];
|
|
810
|
+
for (const [, body] of css.matchAll(FACE_RULE)) {
|
|
811
|
+
const family = FACE_FIELD("font-family").exec(body)?.[1];
|
|
812
|
+
const weight = FACE_FIELD("font-weight").exec(body)?.[1];
|
|
813
|
+
const file = FACE_FILE.exec(body)?.[1];
|
|
814
|
+
const key = family && weight ? faceKey(family, weight) : void 0;
|
|
815
|
+
if (family && weight && file && key) faces.push({
|
|
816
|
+
key,
|
|
817
|
+
family,
|
|
818
|
+
weight,
|
|
819
|
+
file
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
const brandsFrom = css.indexOf(`"${BRANDS_FAMILY}"`);
|
|
823
|
+
const codepoints = /* @__PURE__ */ new Map();
|
|
824
|
+
const brands = /* @__PURE__ */ new Set();
|
|
825
|
+
for (const match of css.matchAll(GLYPH_RULE)) {
|
|
826
|
+
const codepoint = codepointOf(match[2]);
|
|
827
|
+
for (const selector of match[1].split(",")) {
|
|
828
|
+
const name = selector.slice(1);
|
|
829
|
+
codepoints.set(name, codepoint);
|
|
830
|
+
if (brandsFrom >= 0 && match.index > brandsFrom) brands.add(name);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return {
|
|
834
|
+
codepoints,
|
|
835
|
+
brands,
|
|
836
|
+
faces
|
|
837
|
+
};
|
|
838
|
+
};
|
|
839
|
+
var read = /* @__PURE__ */ new Map();
|
|
840
|
+
/** The glyphs of the SDK installed at `sdkDir`, read once per process. */
|
|
841
|
+
var iconGlyphsAt = (sdkDir) => {
|
|
842
|
+
const known = read.get(sdkDir);
|
|
843
|
+
if (known) return known;
|
|
844
|
+
const glyphs = parseIconGlyphs(readFileSync(path.join(sdkDir, "plitzi-sdk-icons.css"), "utf8"));
|
|
845
|
+
read.set(sdkDir, glyphs);
|
|
846
|
+
return glyphs;
|
|
847
|
+
};
|
|
848
|
+
// src/modules/icons/spaceIcons.ts
|
|
849
|
+
/** Where a space's own icon faces are served: `/_plitzi/icons/<hash>-<face>.woff2`. */
|
|
850
|
+
var ICONS_PATH = "/_plitzi/icons/";
|
|
851
|
+
var JSON_STRING = /"(?:[^"\\]|\\.)*"/g;
|
|
852
|
+
var ICON_TOKEN = /\b(?:far|fas|fab|fa-(?:regular|solid|brands)|fa-[a-z0-9]+(?:-[a-z0-9]+)*)\b/g;
|
|
853
|
+
var STYLE_OF = {
|
|
854
|
+
far: "regular",
|
|
855
|
+
"fa-regular": "regular",
|
|
856
|
+
fas: "solid",
|
|
857
|
+
"fa-solid": "solid",
|
|
858
|
+
fab: "brands",
|
|
859
|
+
"fa-brands": "brands"
|
|
860
|
+
};
|
|
861
|
+
/**
|
|
862
|
+
* Each icon a text names, with the face its style class before it says — `far fa-heart` is the regular face's, `fa-check`
|
|
863
|
+
* alone the solid one's (Font Awesome's default) — and a brand's always its own.
|
|
864
|
+
*/
|
|
865
|
+
var namedIcons = (text, glyphs) => {
|
|
866
|
+
const faces = {
|
|
867
|
+
solid: /* @__PURE__ */ new Set(),
|
|
868
|
+
regular: /* @__PURE__ */ new Set(),
|
|
869
|
+
brands: /* @__PURE__ */ new Set()
|
|
870
|
+
};
|
|
871
|
+
for (const [literal] of text.matchAll(JSON_STRING)) {
|
|
872
|
+
let style = "solid";
|
|
873
|
+
for (const [token] of literal.matchAll(ICON_TOKEN)) {
|
|
874
|
+
const named = STYLE_OF[token];
|
|
875
|
+
if (named) {
|
|
876
|
+
style = named;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
const codepoint = glyphs.codepoints.get(token);
|
|
880
|
+
if (codepoint !== void 0) faces[glyphs.brands.has(token) ? "brands" : style === "brands" ? "solid" : style].add(codepoint);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return faces;
|
|
884
|
+
};
|
|
885
|
+
var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 16);
|
|
886
|
+
var found = /* @__PURE__ */ new WeakMap();
|
|
887
|
+
/**
|
|
888
|
+
* The glyphs a space names anywhere in its document — an attribute, a component's props, a binding's template, a flow's
|
|
889
|
+
* params: `'fas fa-check'` and both sides of `open ? 'fa-chevron-up' : 'fa-chevron-down'` alike. An icon named only by
|
|
890
|
+
* data the space reads at run time is not here, and needs nothing: the whole font is declared before these faces, so
|
|
891
|
+
* the browser draws a glyph these lack from it.
|
|
892
|
+
*/
|
|
893
|
+
var spaceIconsOf = (offlineData, glyphs) => {
|
|
894
|
+
const known = found.get(offlineData.schema);
|
|
895
|
+
if (known !== void 0) return known ?? void 0;
|
|
896
|
+
const icons = iconsIn(JSON.stringify(offlineData.schema), glyphs);
|
|
897
|
+
found.set(offlineData.schema, icons ?? null);
|
|
898
|
+
return icons;
|
|
899
|
+
};
|
|
900
|
+
var iconsIn = (text, glyphs) => {
|
|
901
|
+
const named = namedIcons(text, glyphs);
|
|
902
|
+
const cut = glyphs.faces.flatMap((face) => {
|
|
903
|
+
const codepoints = [...named[face.key]].sort((a, b) => a - b);
|
|
904
|
+
return codepoints.length > 0 ? [{
|
|
905
|
+
...face,
|
|
906
|
+
codepoints
|
|
907
|
+
}] : [];
|
|
908
|
+
});
|
|
909
|
+
if (cut.length === 0) return;
|
|
910
|
+
const hash = digest(cut.map((face) => `${face.key}:${face.codepoints.join(",")}`).join(";"));
|
|
911
|
+
return {
|
|
912
|
+
hash,
|
|
913
|
+
faces: cut.map((face) => ({
|
|
914
|
+
...face,
|
|
915
|
+
href: `${ICONS_PATH}${hash}-${face.key}.woff2`
|
|
916
|
+
}))
|
|
917
|
+
};
|
|
918
|
+
};
|
|
919
|
+
var hex = (codepoint) => codepoint.toString(16).toUpperCase();
|
|
920
|
+
/** The codepoints (sorted) as a `unicode-range`, a run of consecutive ones written as one: `U+F00C-F00E`. */
|
|
921
|
+
var unicodeRange = (codepoints) => {
|
|
922
|
+
const runs = [];
|
|
923
|
+
for (const codepoint of codepoints) {
|
|
924
|
+
const last = runs.at(-1);
|
|
925
|
+
if (last && codepoint === last[1] + 1) last[1] = codepoint;
|
|
926
|
+
else runs.push([codepoint, codepoint]);
|
|
927
|
+
}
|
|
928
|
+
return runs.map(([from, to]) => from === to ? `U+${hex(from)}` : `U+${hex(from)}-${hex(to)}`).join(",");
|
|
929
|
+
};
|
|
930
|
+
/**
|
|
931
|
+
* The faces as the head declares them. Declared after the whole font's, a face with a `unicode-range` is the one a
|
|
932
|
+
* glyph in its range is drawn from: the page fetches the space's few glyphs, not the whole font.
|
|
933
|
+
*/
|
|
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("");
|
|
935
|
+
// src/modules/ssr/resolvePageSeo.ts
|
|
936
|
+
/**
|
|
937
|
+
* The title and description the addressed page declares for itself.
|
|
938
|
+
*
|
|
939
|
+
* The page element has carried `seoEnabled` / `seoPageTitle` / `seoPageDescription` all along — the builder edits
|
|
940
|
+
* them and the client renders them into the head through Helmet — but the SSR document was built from a constant,
|
|
941
|
+
* so every server-rendered page arrived titled the same. That is the half a crawler and a link preview see, which
|
|
942
|
+
* is the half that matters: they read the document as delivered and never run the client.
|
|
943
|
+
*
|
|
944
|
+
* `seoEnabled: false` returns nothing rather than a default, so the deployment's own title stays in charge of a
|
|
945
|
+
* page that opted out. Blank strings are treated as absent for the same reason — the builder writes one for a
|
|
946
|
+
* field the author cleared, and an empty <title> is worse than a generic one.
|
|
947
|
+
*
|
|
948
|
+
* Either may be a template over the page's server providers and the address (`pageServerContext`): a detail page says
|
|
949
|
+
* the title of the record it shows, in the HTML a crawler reads. One that does not evaluate is nothing, as a blank is.
|
|
950
|
+
* So may each text of its JSON-LD (`pageStructuredData`).
|
|
951
|
+
*/
|
|
952
|
+
var resolvePageSeo = (schema, pageId, context = {}) => {
|
|
953
|
+
if (!schema || !pageId) return {};
|
|
954
|
+
const page = schema.flat[pageId];
|
|
955
|
+
if (!page?.attributes.seoEnabled) return {};
|
|
956
|
+
const title = pageSeoText(page.attributes.seoPageTitle, context);
|
|
957
|
+
const description = pageSeoText(page.attributes.seoPageDescription, context);
|
|
958
|
+
const robots = typeof page.attributes.seoRobots === "string" ? page.attributes.seoRobots.trim() : "";
|
|
959
|
+
const structuredData = pageStructuredData(page.attributes.seoStructuredData, context).map(jsonForScript);
|
|
960
|
+
const image = pageSeoText(page.attributes.seoImage, context);
|
|
961
|
+
const imageAlt = pageSeoText(page.attributes.seoImageAlt, context);
|
|
962
|
+
const { seoType } = page.attributes;
|
|
963
|
+
return {
|
|
964
|
+
...title ? { title } : {},
|
|
965
|
+
...description ? { description } : {},
|
|
966
|
+
...robots ? { robots } : {},
|
|
967
|
+
...structuredData.length > 0 ? { structuredData } : {},
|
|
968
|
+
...image ? { image } : {},
|
|
969
|
+
...image && imageAlt ? { imageAlt } : {},
|
|
970
|
+
...isOgType(seoType) ? { type: seoType } : {}
|
|
971
|
+
};
|
|
972
|
+
};
|
|
198
973
|
// src/core/services/resolve.ts
|
|
199
974
|
var resolveServices = (config) => {
|
|
200
975
|
const services = config.services ?? {};
|
|
@@ -244,6 +1019,8 @@ var SPACE_DOCUMENT_PATH = "/_plitzi/space/";
|
|
|
244
1019
|
/** The space as it is now, for a page that renders it itself rather than one the server drew (`handleCurrentSpace`). */
|
|
245
1020
|
var CURRENT_SPACE_PATH = "/_plitzi/space.json";
|
|
246
1021
|
var DOCUMENT_PATH = /^\/_plitzi\/space\/([\w-]{1,64})\.json$/;
|
|
1022
|
+
/** One part of a space sent in parts (`documentParts`), by its name: what a navigation to a page not yet held fetches. */
|
|
1023
|
+
var PART_PATH = /^\/_plitzi\/space\/part\/([\w-]{1,64})\.json$/;
|
|
247
1024
|
/**
|
|
248
1025
|
* The documents this process just put in a page, so the request that follows is answered without reading the space
|
|
249
1026
|
* again. Bounded: a document is megabytes, and only the latest of each space is ever asked for twice.
|
|
@@ -251,8 +1028,15 @@ var DOCUMENT_PATH = /^\/_plitzi\/space\/([\w-]{1,64})\.json$/;
|
|
|
251
1028
|
var RECENT = 8;
|
|
252
1029
|
var recent = /* @__PURE__ */ new Map();
|
|
253
1030
|
var recentKey = (spaceId, environment, hash) => `${String(spaceId)}|${environment}|${hash}`;
|
|
1031
|
+
/**
|
|
1032
|
+
* 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
|
|
1033
|
+
* process that did not draw the page — another replica, a process restarted — answers the same document rather than
|
|
1034
|
+
* the whole space (`documentNow`), which it did: a visitor whose page and document reached two processes downloaded
|
|
1035
|
+
* every page of the space.
|
|
1036
|
+
*/
|
|
1037
|
+
var PAGE_PARAM = "page";
|
|
254
1038
|
/** Where the page fetches `document` from — and the promise that this process can answer it. */
|
|
255
|
-
var publishSpaceDocument = (spaceId, environment, document, kept = []) => {
|
|
1039
|
+
var publishSpaceDocument = (spaceId, environment, document, kept = [], pageId) => {
|
|
256
1040
|
const key = recentKey(spaceId, environment, document.hash);
|
|
257
1041
|
recent.delete(key);
|
|
258
1042
|
recent.set(key, {
|
|
@@ -263,7 +1047,8 @@ var publishSpaceDocument = (spaceId, environment, document, kept = []) => {
|
|
|
263
1047
|
if (recent.size <= RECENT) break;
|
|
264
1048
|
recent.delete(oldest);
|
|
265
1049
|
}
|
|
266
|
-
|
|
1050
|
+
const page = pageId === void 0 ? "" : `?${PAGE_PARAM}=${encodeURIComponent(pageId)}`;
|
|
1051
|
+
return `${SPACE_DOCUMENT_PATH}${document.hash}.json${page}`;
|
|
267
1052
|
};
|
|
268
1053
|
var sendNoData = (res, spaceId, environment) => {
|
|
269
1054
|
res.setStatus(404);
|
|
@@ -279,7 +1064,7 @@ var sendNoData = (res, spaceId, environment) => {
|
|
|
279
1064
|
* it (`prepareRender`): an environment that is not the live draft is read once per version, and `cached` says this
|
|
280
1065
|
* request was answered from that copy — the cheaper visit, as a page served from the cache is.
|
|
281
1066
|
*/
|
|
282
|
-
var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
|
|
1067
|
+
var documentNow = async (req, config, offlineDataCache, { linkStyle, pageId }) => {
|
|
283
1068
|
const { environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
284
1069
|
const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
|
|
285
1070
|
const cacheKey = offlineDataCacheKeyOf(req.ctx.spaceDeployment);
|
|
@@ -287,9 +1072,11 @@ var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
|
|
|
287
1072
|
const offlineData = held ?? await config.adapters.getOfflineData(spaceId, environment, revision);
|
|
288
1073
|
if (!offlineData) return;
|
|
289
1074
|
if (cacheKey && !held) offlineDataCache?.set(cacheKey, offlineData);
|
|
290
|
-
const { schema, kept } = withholdPages(offlineData.schema, req.ctx.user);
|
|
291
|
-
const
|
|
292
|
-
|
|
1075
|
+
const { schema, kept, withheld } = withholdPages(offlineData.schema, req.ctx.user);
|
|
1076
|
+
const ofPage = linkStyle && pageId !== void 0 && schema.pages.includes(pageId) && sentInParts(schema) ? pageId : void 0;
|
|
1077
|
+
const sent = ofPage === void 0 ? schema : pageSchemaOf(schema, withheld, ofPage);
|
|
1078
|
+
const document = spaceDocument(offlineDataWith(offlineData, sent), { linkStyle });
|
|
1079
|
+
publishSpaceDocument(spaceId, environment, document, kept, ofPage);
|
|
293
1080
|
return {
|
|
294
1081
|
document,
|
|
295
1082
|
cached: held !== void 0
|
|
@@ -304,6 +1091,11 @@ var documentNow = async (req, config, offlineDataCache, { linkStyle }) => {
|
|
|
304
1091
|
* but not to be kept under a name that is not its own.
|
|
305
1092
|
*/
|
|
306
1093
|
var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
|
|
1094
|
+
const part = PART_PATH.exec(req.path)?.[1];
|
|
1095
|
+
if (part) {
|
|
1096
|
+
await handleSpacePart(req, res, config, part, offlineDataCache);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
307
1099
|
const hash = DOCUMENT_PATH.exec(req.path)?.[1];
|
|
308
1100
|
const { environment = "main" } = req.ctx.spaceDeployment ?? {};
|
|
309
1101
|
const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
|
|
@@ -316,7 +1108,11 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
|
|
|
316
1108
|
let json = known && mayReceive(known.kept, req.ctx.user) ? known.json : void 0;
|
|
317
1109
|
let current = json !== void 0;
|
|
318
1110
|
if (json === void 0) {
|
|
319
|
-
const
|
|
1111
|
+
const pageId = req.query[PAGE_PARAM];
|
|
1112
|
+
const found = await documentNow(req, config, offlineDataCache, {
|
|
1113
|
+
linkStyle: !req.query[SPACE_TOKEN_PARAM],
|
|
1114
|
+
...typeof pageId === "string" ? { pageId } : {}
|
|
1115
|
+
});
|
|
320
1116
|
if (!found) {
|
|
321
1117
|
sendNoData(res, spaceId, environment);
|
|
322
1118
|
return;
|
|
@@ -329,6 +1125,38 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
|
|
|
329
1125
|
res.send(json);
|
|
330
1126
|
};
|
|
331
1127
|
/**
|
|
1128
|
+
* Answers `/_plitzi/space/part/<name>.json`: one part of the space, from this visitor's own split — the space as they
|
|
1129
|
+
* 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,
|
|
1130
|
+
* is none of theirs and answers 404, as a name the space no longer has does. A page that is answered 404 loads the
|
|
1131
|
+
* address it was going to from the server, which draws it or says why not.
|
|
1132
|
+
*/
|
|
1133
|
+
var handleSpacePart = async (req, res, config, name, offlineDataCache) => {
|
|
1134
|
+
const { environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
1135
|
+
const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
|
|
1136
|
+
const cacheKey = offlineDataCacheKeyOf(req.ctx.spaceDeployment);
|
|
1137
|
+
const held = cacheKey ? offlineDataCache?.get(cacheKey) : void 0;
|
|
1138
|
+
const offlineData = held ?? await config.adapters.getOfflineData(spaceId, environment, revision);
|
|
1139
|
+
if (!offlineData) {
|
|
1140
|
+
sendNoData(res, spaceId, environment);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
if (cacheKey && !held) offlineDataCache?.set(cacheKey, offlineData);
|
|
1144
|
+
const { schema, withheld } = withholdPages(offlineData.schema, req.ctx.user);
|
|
1145
|
+
const text = partTextOf(schema, withheld, name);
|
|
1146
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1147
|
+
if (text === void 0) {
|
|
1148
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1149
|
+
res.setStatus(404);
|
|
1150
|
+
res.send(JSON.stringify({
|
|
1151
|
+
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`,
|
|
1152
|
+
reason: "part_gone"
|
|
1153
|
+
}));
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
res.setHeader("Cache-Control", `${req.ctx.user ? "private" : "public"}, max-age=31536000, immutable`);
|
|
1157
|
+
res.send(text);
|
|
1158
|
+
};
|
|
1159
|
+
/**
|
|
332
1160
|
* Lets a page of another origin read the space with its credential: the origins the credential was granted for
|
|
333
1161
|
* (`renderGrant` checked the page's against them), never any other. A page this host serves needs none of it.
|
|
334
1162
|
*/
|
|
@@ -407,7 +1235,7 @@ var handleCurrentSpace = async (req, res, config, offlineDataCache) => {
|
|
|
407
1235
|
...decision?.badge ? { badge: decision.badge } : {}
|
|
408
1236
|
};
|
|
409
1237
|
const visitJson = JSON.stringify(visit);
|
|
410
|
-
const etag = `"${document.hash}.${digest(visitJson)}"`;
|
|
1238
|
+
const etag = `"${document.hash}.${digest$1(visitJson)}"`;
|
|
411
1239
|
res.setHeader("Cache-Control", "private, no-cache");
|
|
412
1240
|
res.setHeader("ETag", etag);
|
|
413
1241
|
if (req.headers["if-none-match"] === etag) {
|
|
@@ -501,6 +1329,26 @@ var Component = ({ server, renderMode = "raw", previewMode = true, offlineData,
|
|
|
501
1329
|
}, key))
|
|
502
1330
|
});
|
|
503
1331
|
};
|
|
1332
|
+
// src/modules/ssr/csrfHint.ts
|
|
1333
|
+
/**
|
|
1334
|
+
* What a page is told about the CSRF token its writes to the deployment's own APIs echo: those APIs, the cookie each
|
|
1335
|
+
* keeps it in, and where a new one is handed out (`rsc.visitorCredentials`) — as JSON, for `<meta name="plitzi-csrf">`.
|
|
1336
|
+
* Only on the pages of a space trusted to carry its visitors' sessions there; none where the deployment names no
|
|
1337
|
+
* `csrfPath`.
|
|
1338
|
+
*/
|
|
1339
|
+
var csrfHintFor = async (config, space) => {
|
|
1340
|
+
const visitor = config.rsc?.visitorCredentials;
|
|
1341
|
+
if (!visitor?.csrfPath || visitor.origins.length === 0) return;
|
|
1342
|
+
if (visitor.spaces && !await visitor.spaces(space)) return;
|
|
1343
|
+
const hint = {
|
|
1344
|
+
apis: visitor.origins.map((origin) => ({
|
|
1345
|
+
origin,
|
|
1346
|
+
cookie: csrfCookieName(new URL(origin).hostname, config.authCookie)
|
|
1347
|
+
})),
|
|
1348
|
+
path: visitor.csrfPath
|
|
1349
|
+
};
|
|
1350
|
+
return JSON.stringify(hint);
|
|
1351
|
+
};
|
|
504
1352
|
// src/modules/ssr/registerExternalPlugins.ts
|
|
505
1353
|
var MANIFEST_TTL_MS = 6e5;
|
|
506
1354
|
var manifestCache = /* @__PURE__ */ new Map();
|
|
@@ -633,44 +1481,6 @@ var reportMissingPlugins = (spaceId, schema, available) => {
|
|
|
633
1481
|
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
1482
|
}
|
|
635
1483
|
};
|
|
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
1484
|
// src/modules/images/allowlist.ts
|
|
675
1485
|
/**
|
|
676
1486
|
* Whether a host is one a picture may come from: named exactly (`images.example.com`), or under a wildcard
|
|
@@ -1036,59 +1846,6 @@ var imagesStage = async (ctx) => {
|
|
|
1036
1846
|
ctx.res.send(answer.body);
|
|
1037
1847
|
return true;
|
|
1038
1848
|
};
|
|
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
1849
|
// src/modules/ssr/prepareRender.tsx
|
|
1093
1850
|
/** Last resort only: used for a page that declares no SEO title and a deployment that supplies none either. */
|
|
1094
1851
|
var DEFAULT_TITLE = "Plitzi App";
|
|
@@ -1164,9 +1921,11 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
1164
1921
|
loadOfflineData,
|
|
1165
1922
|
flagOverrides
|
|
1166
1923
|
})) : rscPath ? { serverData: {} } : void 0;
|
|
1924
|
+
const origin = requestOrigin(req);
|
|
1167
1925
|
const navigation = {
|
|
1168
1926
|
routeParams: pageMatch?.routeParams ?? {},
|
|
1169
|
-
queryParams: req.query
|
|
1927
|
+
queryParams: req.query,
|
|
1928
|
+
...origin === "" ? {} : { origin }
|
|
1170
1929
|
};
|
|
1171
1930
|
const pageContext = pageServerContext(serverElements, rscData?.serverData ?? {}, navigation);
|
|
1172
1931
|
const pageSeo = resolvePageSeo(schema, pageMatch?.pageId, pageContext);
|
|
@@ -1247,9 +2006,14 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
1247
2006
|
* the defaults the server drew. Read here, the server draws with it, and the page starts from the same values: it
|
|
1248
2007
|
* travels as the SDK's `state`, the starting `runtime.state`, in the render and in the payload alike, or the client
|
|
1249
2008
|
* 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`).
|
|
2009
|
+
* account wrote than the one this request proved, only the browser's (`browserState`). A key it holds none of, for an
|
|
2010
|
+
* account the request proved, is the deployment's default (`paintedDefaults`) — the one its providers asked with.
|
|
1251
2011
|
*/
|
|
1252
|
-
const paintedState =
|
|
2012
|
+
const paintedState = (await requestPaintedStateWithDefaults(req, schema?.settings, {
|
|
2013
|
+
spaceId: req.ctx.spaceDeployment?.spaceId ?? spaceId,
|
|
2014
|
+
environment: req.ctx.spaceDeployment?.environment ?? environment,
|
|
2015
|
+
account: req.ctx.user?.id
|
|
2016
|
+
}, config.paintedDefaults)).state;
|
|
1253
2017
|
/**
|
|
1254
2018
|
* The two layers of the space's flags this server answers for. Its own (`config.flags`), asked per space when it
|
|
1255
2019
|
* serves several; and the ones a tester forced from the dev tools, read from their cookie — only for a page allowed
|
|
@@ -1276,9 +2040,22 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
1276
2040
|
* not know to link it.
|
|
1277
2041
|
*/
|
|
1278
2042
|
const linkStyle = offlineDataOverride === void 0 && !spaceToken && config.templateFn === void 0;
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
2043
|
+
/**
|
|
2044
|
+
* The space in parts (`documentParts`): this page's own elements and its layouts', the rest named and fetched as a
|
|
2045
|
+
* link to it is followed. Only where the document travels beside the page under the host's own name — whole for a
|
|
2046
|
+
* draft, a space named by a token (`linkStyle`), a deployment's own template, and a URL that is no page.
|
|
2047
|
+
*/
|
|
2048
|
+
const inParts = linkStyle && config.ssrOnly !== true && pageMatch !== void 0 && offlineData !== void 0 && sentInParts(offlineData.schema);
|
|
2049
|
+
const sentData = inParts ? offlineDataWith(offlineData, pageSchemaOf(offlineData.schema, withholding?.withheld ?? [], pageMatch.pageId)) : offlineData;
|
|
2050
|
+
const document = sentData !== void 0 ? spaceDocument(sentData, { linkStyle }) : void 0;
|
|
2051
|
+
const sdkDir = linkStyle && rawOfflineData ? resolveSdkAssetsDir() : void 0;
|
|
2052
|
+
const spaceIcons = sdkDir && rawOfflineData ? spaceIconsOf(rawOfflineData, iconGlyphsAt(sdkDir)) : void 0;
|
|
2053
|
+
const csrfHint = await csrfHintFor(config, {
|
|
2054
|
+
spaceId: req.ctx.spaceDeployment?.spaceId ?? spaceId,
|
|
2055
|
+
environment: req.ctx.spaceDeployment?.environment ?? environment
|
|
2056
|
+
});
|
|
2057
|
+
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;
|
|
2058
|
+
const spaceDocumentPath = publishedDocument && spaceToken ? `${publishedDocument}${publishedDocument.includes("?") ? "&" : "?"}${SPACE_TOKEN_PARAM}=${encodeURIComponent(spaceToken)}` : publishedDocument;
|
|
1282
2059
|
const offlineDataStr = hydrationPayload(offlineData, {
|
|
1283
2060
|
offlineMode: true,
|
|
1284
2061
|
environment,
|
|
@@ -1344,7 +2121,6 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
1344
2121
|
});
|
|
1345
2122
|
const vendorJs = debugRendered ? assets.devVendorJsPath : assets.vendorJsPath;
|
|
1346
2123
|
const deploymentProps = req.ctx.spaceDeployment?.templateProps;
|
|
1347
|
-
const origin = requestOrigin(req);
|
|
1348
2124
|
const head = pageHeadTags({
|
|
1349
2125
|
title: pageSeo.title ?? deploymentProps?.title ?? DEFAULT_TITLE,
|
|
1350
2126
|
...pageSeo.description ?? deploymentProps?.description ? { description: pageSeo.description ?? deploymentProps?.description } : {},
|
|
@@ -1378,6 +2154,8 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
1378
2154
|
jsPath: assets.jsPath,
|
|
1379
2155
|
cssPath: assets.cssPath,
|
|
1380
2156
|
iconsCssPath: sdkIconsStylePath,
|
|
2157
|
+
...spaceIcons ? { iconFaces: iconFacesCss(spaceIcons) } : {},
|
|
2158
|
+
...csrfHint ? { csrfHint } : {},
|
|
1381
2159
|
spaceDocumentPath,
|
|
1382
2160
|
styleSheetPath: document?.data.style.cacheHref,
|
|
1383
2161
|
react: vendorJs,
|
|
@@ -1437,7 +2215,8 @@ var buildBody = async (req, config, spaceId, environment, revision, renderFn, pl
|
|
|
1437
2215
|
const templateStart = metrics ? performance.now() : 0;
|
|
1438
2216
|
const body = renderFn({
|
|
1439
2217
|
...prep.templateParams,
|
|
1440
|
-
html
|
|
2218
|
+
html,
|
|
2219
|
+
...result.prePaint ? { prePaint: result.prePaint } : {}
|
|
1441
2220
|
});
|
|
1442
2221
|
metrics?.record("template", Math.round(performance.now() - templateStart));
|
|
1443
2222
|
return {
|
|
@@ -1447,4 +2226,4 @@ var buildBody = async (req, config, spaceId, environment, revision, renderFn, pl
|
|
|
1447
2226
|
nonce: prep.templateParams.nonce ?? ""
|
|
1448
2227
|
};
|
|
1449
2228
|
};
|
|
1450
|
-
export {
|
|
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 };
|