@plitzi/sdk-server 0.39.4 → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +21 -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,4 +1,5 @@
1
1
  import { schemaForPage, schemaFromWire, splitSchema } from "@plitzi/sdk-shared/schema";
2
+ import path from "node:path";
2
3
  import { compressBody, frameAncestorsOf, requestAuthority, requestOrigin } from "@plitzi/sdk-kernel/http";
3
4
  import { serverLog } from "@plitzi/sdk-kernel/log";
4
5
  import { flagsCookieName } from "@plitzi/sdk-shared/flags";
@@ -9,9 +10,11 @@ import { TtlCache } from "@plitzi/sdk-kernel/cache";
9
10
  import { debugCookieName } from "@plitzi/sdk-shared/devTools";
10
11
  import { requestScheme, themeFromCookies } from "@plitzi/sdk-shared/theme/cookie";
11
12
  import { brotliDecompressSync, gunzipSync } from "node:zlib";
12
- import { createHash, randomBytes, randomUUID } from "node:crypto";
13
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
13
14
  import { styleSheetCss, styleSheetHref, styleSheetLinkable } from "@plitzi/sdk-shared/style";
15
+ import { fileURLToPath } from "node:url";
14
16
  import { readFileSync, statSync, writeFileSync } from "node:fs";
17
+ import { CLIENT_HEADER, CURRENT_HEADER, behindText, clientHeaderValue } from "@plitzi/sdk-shared/clients";
15
18
  // src/helpers/paintedCookie.ts
16
19
  /**
17
20
  * The name the painted state of a server-rendered page is kept under, for this request's host.
@@ -637,7 +640,7 @@ var destroyServerCaches = ({ html, rsc, offlineData, rendering }) => {
637
640
  // src/helpers/cache/sharedCache.ts
638
641
  /** The topic the processes of a deployment tell each other what their pages no longer hold on. */
639
642
  var CACHE_TOPIC = "ssr.cache";
640
- var LABEL = "SSR cache";
643
+ var LABEL$1 = "SSR cache";
641
644
  /** A filter as it travelled: only the fields a filter has, of the types it has them. */
642
645
  var cacheFilterOf = (value) => {
643
646
  if (!isRecord(value)) return {};
@@ -695,13 +698,13 @@ var shareCache = (cache, sharing) => {
695
698
  const from = randomUUID();
696
699
  const invalidator = createCacheInvalidator(sharing, from);
697
700
  const told = (what) => (error) => {
698
- serverLog.warn(LABEL, `${what} reached only this process: the other replicas keep those pages until their TTL`, error);
701
+ serverLog.warn(LABEL$1, `${what} reached only this process: the other replicas keep those pages until their TTL`, error);
699
702
  };
700
703
  let unsubscribe;
701
704
  const ready = sharing.bus ? sharing.bus.subscribe(CACHE_TOPIC, (raw) => {
702
705
  const message = messageOf(raw);
703
706
  if (!message) {
704
- serverLog.warn(LABEL, `A message on ${CACHE_TOPIC} was ignored: it is not one this server sends`);
707
+ serverLog.warn(LABEL$1, `A message on ${CACHE_TOPIC} was ignored: it is not one this server sends`);
705
708
  return;
706
709
  }
707
710
  if (message.from === from) return;
@@ -710,7 +713,7 @@ var shareCache = (cache, sharing) => {
710
713
  }).then((stop) => {
711
714
  unsubscribe = stop;
712
715
  }).catch((error) => {
713
- serverLog.warn(LABEL, `Not subscribed to ${CACHE_TOPIC}: what other replicas invalidate is kept here until its TTL`, error);
716
+ serverLog.warn(LABEL$1, `Not subscribed to ${CACHE_TOPIC}: what other replicas invalidate is kept here until its TTL`, error);
714
717
  }) : Promise.resolve();
715
718
  return {
716
719
  cache: {
@@ -1304,6 +1307,25 @@ var RequestMetrics = class {
1304
1307
  serverLog.debug("SSR", `${label} — ${parts} | total=${total}ms`);
1305
1308
  }
1306
1309
  };
1310
+ // src/helpers/ownVersion.ts
1311
+ /**
1312
+ * The version of `@plitzi/sdk-server` this code is, read from its own `package.json` — found from where this module is,
1313
+ * as source or built, and whoever compiles it: a build-time constant is only there when this package's own build
1314
+ * defines it, and a package that bundles its source (the MCP) would read nothing. Once a process.
1315
+ */
1316
+ var read;
1317
+ var ownVersion = () => {
1318
+ if (read !== void 0) return read;
1319
+ read = "unknown";
1320
+ for (let dir = path.dirname(fileURLToPath(import.meta.url)); dir !== path.dirname(dir); dir = path.dirname(dir)) try {
1321
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
1322
+ if (manifest !== null && typeof manifest === "object" && "name" in manifest && manifest.name === "@plitzi/sdk-server" && "version" in manifest && typeof manifest.version === "string") {
1323
+ read = manifest.version;
1324
+ break;
1325
+ }
1326
+ } catch {}
1327
+ return read;
1328
+ };
1307
1329
  // src/adapters/cloudAdapters.ts
1308
1330
  /**
1309
1331
  * A space fetched from Plitzi, for a server that is not Plitzi's.
@@ -1351,8 +1373,8 @@ var SPACE_QUERY = `query InitQuery($environment: String!, $revision: Int) {
1351
1373
  * magnitude cheaper — for this deployment and for Plitzi — than pulling a whole space down to discover it did not
1352
1374
  * change. The space itself is fetched only when this answer moves.
1353
1375
  */
1354
- var LATEST_REVISION_QUERY = `query SpaceLatestRevisionQuery($environment: String!) {
1355
- SpaceLatestRevision(environment: $environment) {
1376
+ var LATEST_REVISION_QUERY = `query SpaceLatestRevisionQuery($environment: String!, $domain: String) {
1377
+ SpaceLatestRevision(environment: $environment, domain: $domain) {
1356
1378
  snapshot { revision }
1357
1379
  flagsHash
1358
1380
  }
@@ -1403,7 +1425,8 @@ var assertHostKey = (webKey) => {
1403
1425
  throw new Error(`createCloudAdapters needs a space host key; this one is scoped "${scope}".`);
1404
1426
  };
1405
1427
  var createCloudAdapters = (config) => {
1406
- const { serverUrl = PLITZI_SERVER_URL, webKey, environment = "main", revision, cacheSeconds = 60, cache, spaceId = 1, deployment, fetchImpl = fetch } = config;
1428
+ const { serverUrl = PLITZI_SERVER_URL, webKey, environment = "main", revision, cacheSeconds = 60, cache, spaceId = 1, deployment, domain, fetchImpl = fetch } = config;
1429
+ let toldBehind = false;
1407
1430
  assertHostKey(webKey);
1408
1431
  /** `main` is the document somebody is editing right now. Nothing about it is worth remembering for a minute. */
1409
1432
  const isLive = (env) => env === "main";
@@ -1415,15 +1438,22 @@ var createCloudAdapters = (config) => {
1415
1438
  method: "POST",
1416
1439
  headers: {
1417
1440
  "Content-Type": "application/json",
1418
- authorization: `Bearer ${webKey}`
1441
+ authorization: `Bearer ${webKey}`,
1442
+ [CLIENT_HEADER]: clientHeaderValue("sdkServer", ownVersion())
1419
1443
  },
1420
1444
  body: JSON.stringify({
1421
1445
  query,
1422
1446
  variables
1423
1447
  })
1424
1448
  });
1449
+ const current = response.headers.get(CURRENT_HEADER);
1450
+ if (current && !toldBehind) {
1451
+ toldBehind = true;
1452
+ serverLog.warn("CloudAdapters", behindText("sdkServer", ownVersion(), current));
1453
+ }
1425
1454
  if (!response.ok) {
1426
- serverLog.error("CloudAdapters", `${what} answered ${response.status}`);
1455
+ const said = await response.json().catch(() => void 0);
1456
+ serverLog.error("CloudAdapters", `${what} answered ${String(response.status)}${isRecord(said) && typeof said.error === "string" ? `: ${said.error}` : ""}`);
1427
1457
  return;
1428
1458
  }
1429
1459
  const payload = await response.json();
@@ -1451,7 +1481,10 @@ var createCloudAdapters = (config) => {
1451
1481
  };
1452
1482
  /** Which revision is current, and what the flags are at — one small question for both halves of a served space. */
1453
1483
  const probe = async (env) => {
1454
- const answer = (await post(LATEST_REVISION_QUERY, { environment: env }, `latest revision of ${env}`))?.SpaceLatestRevision;
1484
+ const answer = (await post(LATEST_REVISION_QUERY, {
1485
+ environment: env,
1486
+ domain: domain ?? null
1487
+ }, `latest revision of ${env}`))?.SpaceLatestRevision;
1455
1488
  return {
1456
1489
  revision: answer?.snapshot?.revision,
1457
1490
  flagsHash: answer?.flagsHash ?? void 0
@@ -1820,7 +1853,7 @@ var verifiedDomain = (find) => {
1820
1853
  spaceId,
1821
1854
  ...environment ? { environment } : {},
1822
1855
  revision: row.revision ?? 0,
1823
- ...credential ? { credential } : {},
1856
+ ...credential ? { credentials: [credential] } : {},
1824
1857
  ...security ? { security } : {}
1825
1858
  };
1826
1859
  };
@@ -1839,10 +1872,13 @@ var wildcardSubdomain = ({ suffix, find }) => {
1839
1872
  const slug = req.hostname.slice(0, -dotted.length);
1840
1873
  if (!slug || slug.includes(".")) return;
1841
1874
  const space = await find(slug);
1842
- return space ? {
1843
- ...space,
1844
- revision: 0
1845
- } : void 0;
1875
+ if (!space) return;
1876
+ const { credential, ...found } = space;
1877
+ return {
1878
+ ...found,
1879
+ revision: 0,
1880
+ ...credential ? { credentials: [credential] } : {}
1881
+ };
1846
1882
  };
1847
1883
  };
1848
1884
  /**
@@ -1882,6 +1918,15 @@ var ENVIRONMENTS = [
1882
1918
  "development"
1883
1919
  ];
1884
1920
  var isEnvironment = (value) => value !== void 0 && ENVIRONMENTS.includes(value);
1921
+ var originHostOf = (req) => {
1922
+ const origin = req.headers.origin;
1923
+ if (typeof origin !== "string") return;
1924
+ try {
1925
+ return new URL(origin).hostname;
1926
+ } catch {
1927
+ return;
1928
+ }
1929
+ };
1885
1930
  /**
1886
1931
  * A page that renders the space itself — a site published as files, an embed, the desktop app — asking for it with the
1887
1932
  * space's public `render` credential, from wherever it is served.
@@ -1890,9 +1935,9 @@ var isEnvironment = (value) => value !== void 0 && ENVIRONMENTS.includes(value);
1890
1935
  * credential in `Authorization`, which a page's `fetch` sends: one in the address (`?access-token`) is a page opened
1891
1936
  * by a tool — a screenshot, a journey — and stays what it was. The grant is checked with the page's `Origin` and the
1892
1937
  * host it was presented on, as every browser credential is; it names the space, and the request the environment and
1893
- * revision — the live one when it names none, which is what a published site asks for.
1938
+ * revision — when it names none, the one its page's domain is published at (`served`), or the live one.
1894
1939
  */
1895
- var renderGrant = ({ resolveGrant, find }) => {
1940
+ var renderGrant = ({ resolveGrant, find, served }) => {
1896
1941
  return async (req) => {
1897
1942
  if (!req.headers.authorization) return;
1898
1943
  const result = await resolveGrant(req, { host: req.hostname });
@@ -1901,11 +1946,14 @@ var renderGrant = ({ resolveGrant, find }) => {
1901
1946
  if (!space) return refuse(404, "Space not found");
1902
1947
  const asked = req.query.environment;
1903
1948
  if (asked && !isEnvironment(asked)) return refuse(400, `No environment "${asked}": ask for one of ${ENVIRONMENTS.join(", ")}, or none for the live one`);
1904
- const revision = Number(req.query.revision);
1949
+ const environment = isEnvironment(asked) ? asked : space.environment ?? "main";
1950
+ const named = Number(req.query.revision);
1951
+ const originHost = originHostOf(req);
1952
+ const revision = Number.isInteger(named) && named > 0 ? named : served && originHost && environment !== "main" ? await served(space.spaceId, originHost, environment) ?? 0 : 0;
1905
1953
  return {
1906
1954
  spaceId: space.spaceId,
1907
- environment: isEnvironment(asked) ? asked : space.environment ?? "main",
1908
- revision: Number.isInteger(revision) && revision > 0 ? revision : 0,
1955
+ environment,
1956
+ revision,
1909
1957
  grantOrigins: result.grant.origins
1910
1958
  };
1911
1959
  };
@@ -1914,8 +1962,86 @@ var renderGrant = ({ resolveGrant, find }) => {
1914
1962
  var fixedSpace = (resolution) => {
1915
1963
  return () => Promise.resolve(resolution);
1916
1964
  };
1965
+ // src/adapters/space/snapshotPreview.ts
1966
+ /**
1967
+ * A snapshot's own address: `<name>--r12-production-<space>-<key>.<suffix>` serves `production r12` of one space, so it
1968
+ * can be looked at — and shown to whoever should see it — before any domain serves it.
1969
+ *
1970
+ * The address is a capability: its `key` is the deployment's secret for that one snapshot (an HMAC of it, say), so
1971
+ * nobody reaches a snapshot whose address they were not given, and nothing guessable names one. `name` is for the
1972
+ * person reading it — the space's sub-domain, cut to fit — and decides nothing: the space is the id the label carries.
1973
+ * A preview is never for search (`noindex`) and is served, and counted, as any page of the space is.
1974
+ */
1975
+ /** The environments a snapshot is taken of: the draft has no revisions, so it has no preview address. */
1976
+ var SNAPSHOT_ENVIRONMENTS = [
1977
+ "development",
1978
+ "staging",
1979
+ "production"
1980
+ ];
1981
+ /** RFC 1035: a label is at most 63 characters. */
1982
+ var MAX_LABEL = 63;
1983
+ /** How long a key is, in the label: the characters of [a-z0-9] the deployment's `keyOf` answers. */
1984
+ var PREVIEW_KEY_LENGTH = 12;
1985
+ var LABEL = new RegExp(`^(?:[a-z0-9-]*?--)?r(\\d{1,9})-(${SNAPSHOT_ENVIRONMENTS.join("|")})-([0-9a-z]{1,11})-([a-z0-9]{${String(12)}})$`);
1986
+ var sameKey = (presented, expected) => {
1987
+ const a = Buffer.from(presented);
1988
+ const b = Buffer.from(expected);
1989
+ return a.length === b.length && timingSafeEqual(a, b);
1990
+ };
1991
+ /**
1992
+ * The label of a snapshot's preview address, for a deployment that serves them with {@link snapshotPreview}: the
1993
+ * snapshot, the space's id and its key — and `name` before them, cut to what the label leaves room for (or left out).
1994
+ */
1995
+ var previewLabel = (name, address, key) => {
1996
+ const tail = `r${String(address.revision)}-${address.environment}-${address.spaceId.toString(36)}-${key}`;
1997
+ const room = MAX_LABEL - tail.length - 2;
1998
+ const cut = name.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, Math.max(room, 0)).replace(/-+$/, "");
1999
+ if (!cut || cut.length === 2) return tail;
2000
+ return `${cut}--${tail}`;
2001
+ };
2002
+ /** The snapshot a label names, when it is a preview label at all. */
2003
+ var parsePreviewLabel = (label) => {
2004
+ const match = LABEL.exec(label);
2005
+ if (!match) return;
2006
+ const [, revision, environment, space, key] = match;
2007
+ const spaceId = parseInt(space, 36);
2008
+ const found = SNAPSHOT_ENVIRONMENTS.find((known) => known === environment);
2009
+ if (!found || !Number.isSafeInteger(spaceId) || spaceId <= 0) return;
2010
+ return {
2011
+ spaceId,
2012
+ environment: found,
2013
+ revision: Number(revision),
2014
+ key
2015
+ };
2016
+ };
2017
+ /**
2018
+ * Serves a snapshot at its preview address. Put it before `wildcardSubdomain`, whose sub-domains it shares: a label that
2019
+ * is not a preview's goes on to it, and one that is a preview's with the wrong key ends the chain as a 404 — the same
2020
+ * answer as a space that does not exist, so an address says nothing about which spaces do.
2021
+ */
2022
+ var snapshotPreview = ({ suffix, keyOf, find }) => {
2023
+ const dotted = suffix.startsWith(".") ? suffix : `.${suffix}`;
2024
+ return async (req) => {
2025
+ if (!req.hostname.endsWith(dotted)) return;
2026
+ const label = req.hostname.slice(0, -dotted.length);
2027
+ const asked = label.includes(".") ? void 0 : parsePreviewLabel(label);
2028
+ if (!asked) return;
2029
+ const { key, ...address } = asked;
2030
+ if (!sameKey(key, keyOf(address))) return refuse(404, "Space not found");
2031
+ const space = await find(address.spaceId);
2032
+ if (!space) return refuse(404, "Space not found");
2033
+ return {
2034
+ spaceId: space.spaceId,
2035
+ environment: address.environment,
2036
+ revision: address.revision,
2037
+ noindex: true,
2038
+ ...space.security ? { security: space.security } : {},
2039
+ ...space.credentials && space.credentials.length > 0 ? { credentials: space.credentials } : {}
2040
+ };
2041
+ };
2042
+ };
1917
2043
  // src/adapters/space/index.ts
1918
- var RESOLUTION_PREFIX = "space:resolution:";
2044
+ var RESOLUTION_PREFIX = "space:resolution:v2:";
1919
2045
  var DOMAINS_PREFIX = "space:domains:";
1920
2046
  /**
1921
2047
  * `getSpaceDeployment`, assembled.
@@ -2197,4 +2323,4 @@ var createRedisPageStore = (client, { prefix = "plitzi:{pages}:", maxBytes = byt
2197
2323
  return typeof count === "number" ? count : 0;
2198
2324
  }
2199
2325
  });
2200
- export { ignoredQueryParamsOf as $, cacheLimitsOf as A, styleSheetOf as B, pageSchemaOf as C, reportReactBuild as D, createOfflineDataLoader as E, destroyServerCaches as F, keepPage as G, renderLimitFor as H, digest as I, buildCacheManager as J, pageHtml as K, hydrationPayload as L, createCacheInvalidator as M, shareCache as N, normalizePluginSource as O, createServerCaches as P, offlineDataCacheKeyOf as Q, offlineDataWith as R, sendScriptPolicy as S, sentInParts as T, renderLimitOf as U, DEFAULT_RENDER_WAIT_MS as V, fromSharedPage as W, buildRscCacheKey as X, buildHtmlCacheKey as Y, keepsVersion as Z, buildServerInfo as _, presentsCredential as a, DEFAULT_IGNORED_QUERY_PARAMS as at, CSP_REPORT_PATH as b, wildcardSubdomain as c, createAuthAdapters as d, renderedQuery as et, createJsonAdapters as f, resolveDebugMode as g, escapeHtml as h, fixedSpace as i, DEFAULT_CACHE_BYTES as it, cacheFilterOf as j, normalizePlugins as k, createMemoryCache as l, RequestMetrics as m, createSpaceAdapters as n, visitorScheme as nt, renderGrant as o, DEFAULT_TTL_MS as ot, createCloudAdapters as p, toSharedPage as q, authoringPreview as r, readCookie as rt, verifiedDomain as s, requestPaintedStateWithDefaults as st, createRedisPageStore as t, SCHEME_HINT_HEADER as tt, refuse as u, googleFontsStage as v, partTextOf as w, scriptTemplateParams as x, googleFontsUrlOf as y, spaceDocument as z };
2326
+ export { toSharedPage as $, sentInParts as A, destroyServerCaches as B, googleFontsStage as C, sendScriptPolicy as D, scriptTemplateParams as E, cacheLimitsOf as F, styleSheetOf as G, hydrationPayload as H, cacheFilterOf as I, renderLimitFor as J, escapeJson as K, createCacheInvalidator as L, reportReactBuild as M, normalizePluginSource as N, pageSchemaOf as O, normalizePlugins as P, pageHtml as Q, shareCache as R, buildServerInfo as S, CSP_REPORT_PATH as T, offlineDataWith as U, digest as V, spaceDocument as W, fromSharedPage as X, renderLimitOf as Y, keepPage as Z, createCloudAdapters as _, previewLabel as a, ignoredQueryParamsOf as at, escapeHtml as b, fixedSpace as c, visitorScheme as ct, verifiedDomain as d, DEFAULT_IGNORED_QUERY_PARAMS as dt, buildCacheManager as et, wildcardSubdomain as f, DEFAULT_TTL_MS as ft, createJsonAdapters as g, createAuthAdapters as h, parsePreviewLabel as i, offlineDataCacheKeyOf as it, createOfflineDataLoader as j, partTextOf as k, presentsCredential as l, readCookie as lt, refuse as m, createSpaceAdapters as n, buildRscCacheKey as nt, snapshotPreview as o, renderedQuery as ot, createMemoryCache as p, requestPaintedStateWithDefaults as pt, DEFAULT_RENDER_WAIT_MS as q, PREVIEW_KEY_LENGTH as r, keepsVersion as rt, authoringPreview as s, SCHEME_HINT_HEADER as st, createRedisPageStore as t, buildHtmlCacheKey as tt, renderGrant as u, DEFAULT_CACHE_BYTES as ut, ownVersion as v, googleFontsUrlOf as w, resolveDebugMode as x, RequestMetrics as y, createServerCaches as z };