@plitzi/sdk-server 0.38.24 → 0.39.0

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 (233) hide show
  1. package/CHANGELOG.md +152 -1
  2. package/README.md +55 -9
  3. package/dist/actions.d.ts +4 -1
  4. package/dist/actions.js +3 -2
  5. package/dist/auth.d.ts +2 -2
  6. package/dist/auth.js +5 -4
  7. package/dist/core/auth/api/accounts.d.ts +11 -0
  8. package/dist/core/auth/api/accounts.js +175 -0
  9. package/dist/core/auth/api/admin.d.ts +41 -0
  10. package/dist/core/auth/api/admin.js +146 -0
  11. package/dist/core/auth/api/context.d.ts +119 -0
  12. package/dist/core/auth/api/context.js +262 -0
  13. package/dist/core/auth/api/factors.d.ts +31 -0
  14. package/dist/core/auth/api/factors.js +209 -0
  15. package/dist/core/auth/api/index.d.ts +94 -0
  16. package/dist/core/auth/api/index.js +43 -0
  17. package/dist/core/auth/api/profile.d.ts +43 -0
  18. package/dist/core/auth/api/profile.js +243 -0
  19. package/dist/core/auth/api/session.d.ts +62 -0
  20. package/dist/core/auth/api/session.js +312 -0
  21. package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
  22. package/dist/core/auth/api/values.d.ts +67 -0
  23. package/dist/core/auth/api/values.js +90 -0
  24. package/dist/core/auth/createAuth.d.ts +49 -39
  25. package/dist/core/auth/createAuth.js +21 -1
  26. package/dist/core/auth/oauth/client.d.ts +2 -2
  27. package/dist/core/auth/oauth/client.js +6 -1
  28. package/dist/core/auth/oauth/index.d.ts +30 -7
  29. package/dist/core/auth/oauth/index.js +33 -14
  30. package/dist/core/auth/oauth/providers/github.js +1 -1
  31. package/dist/core/auth/oauth/providers/google.js +1 -1
  32. package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
  33. package/dist/core/auth/oauth/providers/oidc.js +197 -0
  34. package/dist/core/auth/oauth/state.d.ts +2 -0
  35. package/dist/core/auth/oauth/state.js +2 -0
  36. package/dist/core/auth/oauth/types.d.ts +21 -3
  37. package/dist/core/auth/oauth/types.js +4 -1
  38. package/dist/core/auth/routes.js +1 -1
  39. package/dist/core/auth/tokens.d.ts +3 -1
  40. package/dist/core/auth/tokens.js +2 -1
  41. package/dist/core/configSeam.d.ts +0 -4
  42. package/dist/core/configSeam.js +12 -1
  43. package/dist/core/createServer.js +16 -4
  44. package/dist/core/freePort.d.ts +10 -0
  45. package/dist/core/freePort.js +39 -1
  46. package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
  47. package/dist/core/handlers/socialRouteHandlers.js +46 -12
  48. package/dist/core/health.d.ts +1 -0
  49. package/dist/core/health.js +2 -1
  50. package/dist/core/http/stages/authRoutes.d.ts +6 -0
  51. package/dist/core/http/stages/authRoutes.js +42 -1
  52. package/dist/core/http/stages/images.js +5 -3
  53. package/dist/core/http/stages/livePages.js +1 -1
  54. package/dist/core/server/fleet/relay.js +9 -1
  55. package/dist/core/server/fleet/stores.d.ts +7 -0
  56. package/dist/core/server/fleet/stores.js +15 -2
  57. package/dist/core/server/pageServer.js +5 -1
  58. package/dist/core/services/realtime.js +4 -2
  59. package/dist/core/services/registry.js +7 -1
  60. package/dist/core/services/robotsTxt.d.ts +16 -0
  61. package/dist/core/services/robotsTxt.js +50 -0
  62. package/dist/core/services/servedSpace.d.ts +8 -0
  63. package/dist/core/services/servedSpace.js +16 -0
  64. package/dist/core/services/sitemapXml.d.ts +7 -0
  65. package/dist/core/services/sitemapXml.js +37 -0
  66. package/dist/functions-api.d.ts +69 -2
  67. package/dist/helpers/fileStore.d.ts +60 -0
  68. package/dist/helpers/fileStore.js +127 -0
  69. package/dist/helpers/outboundGuard.d.ts +32 -3
  70. package/dist/helpers/outboundGuard.js +50 -5
  71. package/dist/hosts/project/agentRuns.d.ts +24 -0
  72. package/dist/hosts/project/agentRuns.js +107 -0
  73. package/dist/hosts/project/laterAsks.d.ts +41 -0
  74. package/dist/hosts/project/laterAsks.js +117 -0
  75. package/dist/hosts/project/plugins.js +11 -4
  76. package/dist/hosts/project/serveProject.d.ts +8 -1
  77. package/dist/hosts/project/serveProject.js +81 -24
  78. package/dist/hosts/project/spaceFailure.d.ts +4 -0
  79. package/dist/hosts/project/spaceFailure.js +10 -0
  80. package/dist/hosts/project/watchSpace.d.ts +5 -5
  81. package/dist/hosts/project/watchSpace.js +15 -6
  82. package/dist/index.js +2 -2
  83. package/dist/kernel.js +1 -1
  84. package/dist/modules/actions/connectorWrite.js +3 -1
  85. package/dist/modules/actions/index.js +1 -1
  86. package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
  87. package/dist/modules/actions/jobs/fileQueue.js +72 -0
  88. package/dist/modules/actions/jobs/index.js +3 -3
  89. package/dist/modules/actions/jobs/memoryQueue.js +6 -215
  90. package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
  91. package/dist/modules/actions/jobs/queueDocument.js +22 -0
  92. package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
  93. package/dist/modules/actions/jobs/queueRules.js +270 -0
  94. package/dist/modules/actions/moduleFor.js +2 -0
  95. package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
  96. package/dist/modules/actions/runtime/fileKv.js +12 -98
  97. package/dist/modules/actions/runtime/guards.d.ts +19 -1
  98. package/dist/modules/actions/runtime/guards.js +10 -1
  99. package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
  100. package/dist/modules/actions/runtime/kvChange.js +23 -1
  101. package/dist/modules/actions/runtime/kvList.d.ts +4 -0
  102. package/dist/modules/actions/runtime/kvList.js +5 -1
  103. package/dist/modules/actions/runtime/kvStore.js +15 -1
  104. package/dist/modules/actions/runtime/namespaceKv.js +2 -0
  105. package/dist/modules/actions/runtime/renderResolver.js +31 -5
  106. package/dist/modules/actions/runtime/runAction.js +16 -6
  107. package/dist/modules/actions/runtime/scope.js +11 -0
  108. package/dist/modules/actions/runtime/taskContext.js +11 -32
  109. package/dist/modules/actions/tasks/auth.js +2 -0
  110. package/dist/modules/actions/tasks/connector.js +6 -2
  111. package/dist/modules/actions/tasks/flow.js +5 -0
  112. package/dist/modules/actions/tasks/http.js +2 -1
  113. package/dist/modules/actions/tasks/kv.js +5 -0
  114. package/dist/modules/actions/tasks/list.js +11 -2
  115. package/dist/modules/actions/tasks/transform.js +2 -0
  116. package/dist/modules/actions/transport/callHandler.js +25 -4
  117. package/dist/modules/actions/types.d.ts +46 -1
  118. package/dist/modules/connectors/engine.d.ts +7 -2
  119. package/dist/modules/connectors/engine.js +4 -4
  120. package/dist/modules/connectors/resolver.d.ts +2 -1
  121. package/dist/modules/connectors/resolver.js +3 -2
  122. package/dist/modules/functions/build.d.ts +7 -2
  123. package/dist/modules/functions/build.js +90 -6
  124. package/dist/modules/functions/capabilities.js +16 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +39 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +35 -0
  129. package/dist/modules/functions/load.d.ts +1 -1
  130. package/dist/modules/functions/load.js +2 -2
  131. package/dist/modules/functions/manifest.js +7 -1
  132. package/dist/modules/functions/oauth.d.ts +1 -1
  133. package/dist/modules/functions/oauth.js +4 -4
  134. package/dist/modules/functions/protocol.d.ts +6 -0
  135. package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
  136. package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
  137. package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
  138. package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
  139. package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
  140. package/dist/modules/functions/sandbox/guest/events.js +143 -0
  141. package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
  142. package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
  143. package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
  144. package/dist/modules/functions/sandbox/guest/index.js +130 -0
  145. package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
  146. package/dist/modules/functions/sandbox/isolate.js +20 -6
  147. package/dist/modules/functions/space.js +2 -8
  148. package/dist/modules/images/imageProxy.d.ts +3 -2
  149. package/dist/modules/images/imageProxy.js +2 -2
  150. package/dist/modules/mongo/jobQueue.js +0 -19
  151. package/dist/modules/mysql/accounts.js +12 -5
  152. package/dist/modules/mysql/jobs/index.d.ts +1 -1
  153. package/dist/modules/mysql/jobs/schema.d.ts +0 -6
  154. package/dist/modules/mysql/jobs/schema.js +2 -46
  155. package/dist/modules/mysql/schema.js +26 -1
  156. package/dist/modules/mysql/sessions.js +2 -1
  157. package/dist/modules/realtime/handlers.d.ts +9 -4
  158. package/dist/modules/realtime/handlers.js +20 -3
  159. package/dist/modules/realtime/hub.d.ts +4 -2
  160. package/dist/modules/realtime/hub.js +36 -4
  161. package/dist/modules/realtime/index.d.ts +14 -0
  162. package/dist/modules/realtime/index.js +14 -1
  163. package/dist/modules/realtime/presence.d.ts +33 -0
  164. package/dist/modules/realtime/presence.js +56 -0
  165. package/dist/modules/realtime/socket.d.ts +3 -1
  166. package/dist/modules/realtime/socket.js +2 -2
  167. package/dist/modules/rsc/connectorRscData.d.ts +6 -1
  168. package/dist/modules/rsc/connectorRscData.js +27 -6
  169. package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
  170. package/dist/modules/rsc/externalQueryReader.js +43 -0
  171. package/dist/modules/rsc/handler.js +1 -1
  172. package/dist/modules/rsc/resolveRscData.d.ts +11 -1
  173. package/dist/modules/rsc/resolveRscData.js +86 -16
  174. package/dist/modules/runtime/inside.js +1 -1
  175. package/dist/modules/runtime/runner.js +2 -1
  176. package/dist/modules/sqlite/jobQueue.d.ts +35 -0
  177. package/dist/modules/sqlite/jobQueue.js +56 -0
  178. package/dist/modules/sqlite/kv.d.ts +1 -1
  179. package/dist/modules/sqlite/kv.js +2 -10
  180. package/dist/modules/sqlite/open.d.ts +3 -0
  181. package/dist/modules/sqlite/open.js +13 -0
  182. package/dist/modules/ssr/Component.d.ts +5 -1
  183. package/dist/modules/ssr/Component.js +3 -1
  184. package/dist/modules/ssr/applySSRResult.d.ts +8 -1
  185. package/dist/modules/ssr/applySSRResult.js +23 -3
  186. package/dist/modules/ssr/handler.js +30 -5
  187. package/dist/modules/ssr/prepareRender.js +27 -5
  188. package/dist/modules/ssr/preview.d.ts +2 -0
  189. package/dist/modules/ssr/preview.js +6 -3
  190. package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
  191. package/dist/modules/ssr/registerExternalPlugins.js +2 -2
  192. package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
  193. package/dist/modules/ssr/resolvePageSeo.js +13 -2
  194. package/dist/modules/ssr/streamBody.js +2 -2
  195. package/dist/modules/ssr/views/template.ejs +21 -17
  196. package/dist/mysql.d.ts +1 -1
  197. package/dist/mysql.js +2 -2
  198. package/dist/plugins/manager.d.ts +5 -0
  199. package/dist/plugins/manager.js +9 -0
  200. package/dist/sqlite.d.ts +8 -1
  201. package/dist/sqlite.js +3 -1
  202. package/package.json +5 -5
  203. package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
  204. package/skills/plitzi-authoring/SKILL.md +4 -2
  205. package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
  206. package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
  207. package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
  208. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
  209. package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
  210. package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
  211. package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
  212. package/skills/plitzi-authoring/reference/accessibility.md +7 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
  215. package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
  216. package/skills/plitzi-authoring/reference/components.md +4 -1
  217. package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
  218. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  219. package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
  220. package/skills/plitzi-authoring/reference/flows.md +20 -8
  221. package/skills/plitzi-authoring/reference/kept-state.md +8 -0
  222. package/skills/plitzi-authoring/reference/layouts.md +18 -2
  223. package/skills/plitzi-authoring/reference/lists.md +20 -4
  224. package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
  225. package/skills/plitzi-authoring/reference/plugins.md +13 -2
  226. package/skills/plitzi-authoring/reference/realtime.md +8 -5
  227. package/skills/plitzi-authoring/reference/structure.md +17 -1
  228. package/skills/plitzi-authoring/reference/templates.md +11 -3
  229. package/skills/plitzi-authoring/reference/testing.md +82 -5
  230. package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
  231. package/skills/plitzi-authoring/reference/validation.md +1 -1
  232. package/dist/core/auth/api.js +0 -1323
  233. package/dist/modules/functions/sandbox/guest.js +0 -662
@@ -0,0 +1,28 @@
1
+ import { OutboundOptions } from '../../helpers/outboundGuard';
2
+ import { ServerQuery } from '@plitzi/sdk-shared/schema';
3
+ /** What one answer of another site may carry into a page: the same ceiling an action's response has by default. */
4
+ export declare const EXTERNAL_QUERY_MAX_BYTES = 5000000;
5
+ /** Reads one server provider's query that is another site's address: `{ status, data }`, or why not. */
6
+ export type ExternalQueryReader = (query: Extract<ServerQuery, {
7
+ kind: 'url';
8
+ }>, signal: AbortSignal) => Promise<{
9
+ status: number;
10
+ data: unknown;
11
+ }>;
12
+ /**
13
+ * A server provider whose `query` is another site's address, asked by the page server while the page is built — so
14
+ * the page arrives with it, as it does with a connector's or an action's answer, rather than drawing empty and
15
+ * filling in once the browser has asked.
16
+ *
17
+ * Asked as the browser would have asked it — GET, the headers the provider declares — and never with what the browser
18
+ * would have added: no cookie, no credential of the visitor's. Every hop is judged by the rule every authored request
19
+ * is (`fetchOutbound`: no private network but the origins the deployment names as its own, every redirect checked),
20
+ * the answer is held to a ceiling, and the element's own budget aborts it. Answered as a browser request publishes,
21
+ * `{ status, data }`; an answer that is not a success, or not JSON, is the provider's error state — as it is in the
22
+ * browser — with why said.
23
+ */
24
+ export declare const externalQueryReader: ({ base, maxBytes, outbound }?: {
25
+ base?: typeof fetch;
26
+ maxBytes?: number;
27
+ outbound?: OutboundOptions;
28
+ }) => ExternalQueryReader;
@@ -0,0 +1,43 @@
1
+ import { cappedResponse, fetchOutbound } from "../../helpers/outboundGuard.js";
2
+ //#region src/modules/rsc/externalQueryReader.ts
3
+ /** What one answer of another site may carry into a page: the same ceiling an action's response has by default. */
4
+ var EXTERNAL_QUERY_MAX_BYTES = 5e6;
5
+ /**
6
+ * A server provider whose `query` is another site's address, asked by the page server while the page is built — so
7
+ * the page arrives with it, as it does with a connector's or an action's answer, rather than drawing empty and
8
+ * filling in once the browser has asked.
9
+ *
10
+ * Asked as the browser would have asked it — GET, the headers the provider declares — and never with what the browser
11
+ * would have added: no cookie, no credential of the visitor's. Every hop is judged by the rule every authored request
12
+ * is (`fetchOutbound`: no private network but the origins the deployment names as its own, every redirect checked),
13
+ * the answer is held to a ceiling, and the element's own budget aborts it. Answered as a browser request publishes,
14
+ * `{ status, data }`; an answer that is not a success, or not JSON, is the provider's error state — as it is in the
15
+ * browser — with why said.
16
+ */
17
+ var externalQueryReader = ({ base = fetch, maxBytes = EXTERNAL_QUERY_MAX_BYTES, outbound } = {}) => {
18
+ return async (query, signal) => {
19
+ const response = await fetchOutbound(base, query.url, {
20
+ method: "GET",
21
+ headers: {
22
+ Accept: "application/json",
23
+ ...query.headers
24
+ },
25
+ credentials: "omit",
26
+ signal
27
+ }, outbound);
28
+ const text = await cappedResponse(response, maxBytes, (message) => /* @__PURE__ */ new Error(`${query.url.href}: ${message}`)).text();
29
+ if (!response.ok) throw new Error(`${query.url.href} answered ${String(response.status)}`);
30
+ let data;
31
+ try {
32
+ data = JSON.parse(text);
33
+ } catch {
34
+ throw new Error(`${query.url.href} did not answer JSON`);
35
+ }
36
+ return {
37
+ status: response.status,
38
+ data
39
+ };
40
+ };
41
+ };
42
+ //#endregion
43
+ export { EXTERNAL_QUERY_MAX_BYTES, externalQueryReader };
@@ -1,10 +1,10 @@
1
1
  import { serverLog } from "../../helpers/serverLog.js";
2
+ import { readDraftToken } from "../../core/previewToken.js";
2
3
  import { requestAuthority } from "../../core/requestParser.js";
3
4
  import { requestFlagOverrides } from "../../helpers/flagOverrides.js";
4
5
  import { resolveDebugAuthorization } from "../../helpers/debugAuthorization.js";
5
6
  import { DEFAULT_TTL_MS } from "../../helpers/cache/defaults.js";
6
7
  import { buildRscCacheKey } from "../../helpers/cache/keys.js";
7
- import { readDraftToken } from "../../core/previewToken.js";
8
8
  import { createOfflineDataLoader } from "../../helpers/offlineDataLoader.js";
9
9
  import { forcedFlagsFromCookies } from "@plitzi/sdk-shared/flags";
10
10
  //#region src/modules/rsc/handler.ts
@@ -1,12 +1,20 @@
1
1
  import { Element, Environment, Schema, SSRRequest, SSRRscData, SSRUser } from '@plitzi/sdk-shared';
2
2
  import { FlagOverrides } from '@plitzi/sdk-shared/flags';
3
+ import { ServerTemplateData } from '@plitzi/sdk-shared/schema';
3
4
  /** Everything an element resolver needs to turn one `runtime: 'server'` element into its data slice. */
4
5
  export type RscResolveContext = {
5
6
  element: Element;
7
+ /**
8
+ * What its input resolves to on the page server: what it was saved with, and its bound input the server reads — the
9
+ * address, the answers of the server providers before it (`serverInputOf`).
10
+ */
11
+ input?: unknown;
6
12
  /** The whole element map, so a resolver can inspect the subtree that consumes its data. */
7
13
  flat: Record<string, Element>;
8
14
  routeParams: Record<string, string | undefined>;
9
15
  queryParams: Record<string, string>;
16
+ /** What the page server knows of the visit as a template reads it — the space's variables for this host, `navigation`. */
17
+ templateData: ServerTemplateData;
10
18
  req: SSRRequest;
11
19
  spaceId: number;
12
20
  environment: Environment;
@@ -42,6 +50,8 @@ export type ResolveRscDataOptions = {
42
50
  timeoutMs?: number;
43
51
  /** Whoever asked stopped waiting: every element still resolving is cancelled, as when its budget runs out. */
44
52
  signal?: AbortSignal;
53
+ /** While developing: a failed element says why in its data (`RSC_FAILURE`), where its provider shows it. */
54
+ sayFailures?: boolean;
45
55
  };
46
56
  /**
47
57
  * Resolves the server-side data slices for the page addressed by `req`.
@@ -50,4 +60,4 @@ export type ResolveRscDataOptions = {
50
60
  * and the route params are what the browser will see. Each `runtime: 'server'` element resolves independently:
51
61
  * a provider that fails or hangs costs its own slice and nothing else.
52
62
  */
53
- export declare const resolveRscData: ({ schema, req, spaceId, environment, user, ids, resolveElement, flagOverrides, timeoutMs, signal }: ResolveRscDataOptions) => Promise<SSRRscData>;
63
+ export declare const resolveRscData: ({ schema, req, spaceId, environment, user, ids, resolveElement, flagOverrides, timeoutMs, signal, sayFailures }: ResolveRscDataOptions) => Promise<SSRRscData>;
@@ -1,8 +1,12 @@
1
1
  import { serverLog } from "../../helpers/serverLog.js";
2
+ import { requestOrigin } from "../../core/requestParser.js";
2
3
  import onAbort from "../../helpers/onAbort.js";
3
4
  import { matchRscPage } from "./matchRscPage.js";
5
+ import { evaluateRuleGroup } from "@plitzi/sdk-shared/helpers";
4
6
  import { flagUserFromSSR, flagValues, resolveFlags } from "@plitzi/sdk-shared/flags";
5
- import { collectServerElements, pageAccessOf, pageAccessRefusal } from "@plitzi/sdk-shared/schema";
7
+ import { RSC_FAILURE, collectServerElements, inputProviders, inputReadings, pageAccessOf, pageAccessRefusal, serverInputOf, serverProviderSource, serverWhenValues, whenOf, whenProviders, whenUnknownToServer, withholdPages } from "@plitzi/sdk-shared/schema";
8
+ import { getSourceName } from "@plitzi/sdk-shared/dataSource/helpers";
9
+ import { resolveVariables } from "@plitzi/sdk-shared/dataSource/variables";
6
10
  //#region src/modules/rsc/resolveRscData.ts
7
11
  var DEFAULT_ELEMENT_TIMEOUT_MS = 5e3;
8
12
  /**
@@ -35,12 +39,12 @@ var withBudget = async (run, timeoutMs, label, asked) => {
35
39
  * and the route params are what the browser will see. Each `runtime: 'server'` element resolves independently:
36
40
  * a provider that fails or hangs costs its own slice and nothing else.
37
41
  */
38
- var resolveRscData = async ({ schema, req, spaceId, environment, user, ids, resolveElement, flagOverrides, timeoutMs = DEFAULT_ELEMENT_TIMEOUT_MS, signal }) => {
42
+ var resolveRscData = async ({ schema, req, spaceId, environment, user, ids, resolveElement, flagOverrides, timeoutMs = DEFAULT_ELEMENT_TIMEOUT_MS, signal, sayFailures = false }) => {
39
43
  if (schema.rsc?.enabled === false) return {};
40
44
  const match = matchRscPage(schema, req.path, user);
41
45
  if (!match) return { serverData: {} };
42
46
  const { pageId, routeParams } = match;
43
- if (pageAccessRefusal(pageAccessOf(schema.flat[pageId].attributes), user) !== void 0) return { serverData: {} };
47
+ const drawn = pageAccessRefusal(pageAccessOf(schema.flat[pageId].attributes), user) !== void 0 ? withholdPages(schema, user).schema : schema;
44
48
  const flags = flagValues(resolveFlags(schema.flags, {
45
49
  environment,
46
50
  hostname: req.hostname,
@@ -48,24 +52,90 @@ var resolveRscData = async ({ schema, req, spaceId, environment, user, ids, reso
48
52
  queryParams: req.query,
49
53
  user: flagUserFromSSR(user)
50
54
  }, flagOverrides));
51
- const targets = collectServerElements(schema, pageId, ids, flags);
55
+ const all = collectServerElements(drawn, pageId, void 0, flags);
56
+ const asked = ids ? new Set(ids) : void 0;
57
+ const targets = asked ? all.filter((element) => asked.has(element.id)) : all;
52
58
  if (targets.length === 0) return { serverData: {} };
53
- return { serverData: (await Promise.allSettled(targets.map(async (element) => ({
54
- id: element.id,
55
- data: await withBudget((signal) => resolveElement({
56
- element,
57
- flat: schema.flat,
59
+ const templateData = {
60
+ variables: resolveVariables(schema.variables, {
58
61
  routeParams,
59
62
  queryParams: req.query,
60
- req,
61
- spaceId,
62
- environment,
63
- user,
64
- signal
65
- }), timeoutMs, `element ${element.id}`, signal)
63
+ hostname: req.hostname,
64
+ environment
65
+ }),
66
+ routeParams,
67
+ queryParams: req.query,
68
+ origin: requestOrigin(req) || `${req.protocol}://${req.hostname}`
69
+ };
70
+ const byId = new Map(all.map((element) => [element.id, element]));
71
+ const serverIds = new Set(byId.keys());
72
+ const resolving = /* @__PURE__ */ new Map();
73
+ const readingsOf = /* @__PURE__ */ new Map();
74
+ const resolveOne = (element, chain) => {
75
+ const started = resolving.get(element.id);
76
+ if (started) return started;
77
+ const run = async () => {
78
+ const answersOf = async (ids, what) => Object.fromEntries(await Promise.all(ids.filter((id) => id !== element.id && !chain.includes(id)).map(async (id) => {
79
+ const other = byId.get(id);
80
+ return [id, {
81
+ answer: other ? await resolveOne(other, [...chain, element.id]).catch((reason) => {
82
+ if (asked && !asked.has(id)) serverLog.warn("RSC", `element ${element.id}'s ${what} reads ${id}, which failed to resolve`, reason);
83
+ }) : void 0,
84
+ singleRecord: other?.attributes.singleRecord === true
85
+ }];
86
+ })));
87
+ const gate = whenOf(element);
88
+ if (gate && whenUnknownToServer(gate, schema.flat, serverIds).length === 0) {
89
+ const values = serverWhenValues({
90
+ routeParams,
91
+ queryParams: req.query,
92
+ pageId,
93
+ user,
94
+ answers: await answersOf(whenProviders(gate, serverIds), "`when`")
95
+ });
96
+ if (!evaluateRuleGroup(gate, values)) return;
97
+ }
98
+ const reads = await answersOf(inputProviders(element, serverIds), "input");
99
+ const address = {
100
+ routeParams,
101
+ queryParams: req.query
102
+ };
103
+ const providers = Object.fromEntries(Object.entries(reads).map(([id, { answer, singleRecord }]) => [getSourceName("apiContainer", id), serverProviderSource(answer, singleRecord)]));
104
+ const input = serverInputOf(element, address, providers);
105
+ readingsOf.set(element.id, inputReadings(element, address, providers));
106
+ return withBudget((elementSignal) => resolveElement({
107
+ element,
108
+ input,
109
+ flat: schema.flat,
110
+ routeParams,
111
+ queryParams: req.query,
112
+ templateData,
113
+ req,
114
+ spaceId,
115
+ environment,
116
+ user,
117
+ signal: elementSignal
118
+ }), timeoutMs, `element ${element.id}`, signal);
119
+ };
120
+ const promise = run();
121
+ resolving.set(element.id, promise);
122
+ return promise;
123
+ };
124
+ return { serverData: (await Promise.allSettled(targets.map(async (element) => ({
125
+ id: element.id,
126
+ data: await resolveOne(element, [])
66
127
  })))).reduce((acum, result, index) => {
67
128
  if (result.status === "rejected") {
68
- if (!signal?.aborted) serverLog.error("RSC", `element ${targets[index].id} failed to resolve`, result.reason);
129
+ if (!signal?.aborted) {
130
+ const reason = result.reason;
131
+ const readings = readingsOf.get(targets[index].id) ?? [];
132
+ const itsInput = readings.length > 0 ? ` — its input: ${readings.join("; ")}` : "";
133
+ if (reason instanceof Error && "refused" in reason && reason.refused === true) serverLog.warn("RSC", `element ${targets[index].id}: ${reason.message}${itsInput}`);
134
+ else serverLog.error("RSC", `element ${targets[index].id} failed to resolve${itsInput}`, reason);
135
+ const said = reason instanceof Error && "said" in reason && typeof reason.said === "string" ? reason.said : void 0;
136
+ if (said !== void 0) acum[targets[index].id] = { [RSC_FAILURE]: said };
137
+ else if (sayFailures) acum[targets[index].id] = { [RSC_FAILURE]: `${reason instanceof Error ? reason.message : String(reason)}${itsInput}` };
138
+ }
69
139
  return acum;
70
140
  }
71
141
  if (result.value.data !== void 0) acum[result.value.id] = result.value.data;
@@ -1,5 +1,5 @@
1
- import { X509Certificate } from "node:crypto";
2
1
  import net from "node:net";
2
+ import { X509Certificate } from "node:crypto";
3
3
  import tls from "node:tls";
4
4
  //#region src/modules/runtime/inside.ts
5
5
  /** Headers as a dispatch carries them — a record, name/value pairs flattened into one list, or pairs — plus one more. */
@@ -1,5 +1,5 @@
1
1
  import { ActionRefusal, isActionRefusal } from "../actions/runtime/errors.js";
2
- import { changeKv } from "../actions/runtime/kvChange.js";
2
+ import { changeKv, changeListEntry } from "../actions/runtime/kvChange.js";
3
3
  import { requestFromWire, responseOf, wireResponseFrom, wireResponseOf } from "../functions/capabilities.js";
4
4
  import { FunctionFailure } from "../functions/protocol.js";
5
5
  import { createFunctionsDriver, describeFunctions } from "../functions/driver.js";
@@ -33,6 +33,7 @@ var createRuntimeRunner = (definition = {}) => ({
33
33
  };
34
34
  },
35
35
  changeKv,
36
+ changeListEntry,
36
37
  refusal: (message) => new ActionRefusal(message)
37
38
  });
38
39
  try {
@@ -0,0 +1,35 @@
1
+ import { JobQueue } from '@plitzi/sdk-shared';
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ export type SqliteJobQueueOptions = ({
4
+ /** The database file — created, with its folder, when it is not there. Opened in WAL mode. */
5
+ file: string;
6
+ db?: never;
7
+ } | {
8
+ /** A database the deployment opened and shares with its own tables — its `kv` (`createSqliteKv`) among them. */
9
+ db: DatabaseSync;
10
+ file?: never;
11
+ }) & {
12
+ /** The table the queue lives in, created when it is not there. Default `action_jobs`. */
13
+ table?: string;
14
+ /** How many finished jobs to keep before the oldest are dropped. Default 500. */
15
+ retainFinished?: number;
16
+ /** What the queue calls now, in epoch ms: every process on the file reads the machine's clock. */
17
+ clock?: () => number;
18
+ };
19
+ /**
20
+ * The job queue in a SQLite file, over Node's own `node:sqlite`: what `ctx.later`, a schedule's fires and a function's
21
+ * jobs wait in, surviving a restart AND shared — every process on the file (replicas on one machine, a server started
22
+ * with `workers`) claims from the same queue, each job by one of them.
23
+ *
24
+ * ```ts
25
+ * import { createSqliteJobQueue, createSqliteKv } from '@plitzi/sdk-server/sqlite';
26
+ *
27
+ * createServer({ action: { kv: createSqliteKv({ db }), jobs: { queue: createSqliteJobQueue({ db }) } } });
28
+ * ```
29
+ *
30
+ * The rules are the in-process queue's, to the letter (`queueRules`), run on the state as the table holds it, inside
31
+ * one `BEGIN IMMEDIATE` transaction a call: two processes never claim one job, nor write over each other's change. The
32
+ * state is one row, read whole each call — right for what a project's queue holds (its jobs waiting and the last
33
+ * `retainFinished` done); a deployment of thousands a minute keeps its queue in a database (`JobQueue`).
34
+ */
35
+ export declare const createSqliteJobQueue: (options: SqliteJobQueueOptions) => JobQueue;
@@ -0,0 +1,56 @@
1
+ import { applyRule, changedBy, emptyState, queueOver, queueRules } from "../actions/jobs/queueRules.js";
2
+ import { openDatabase } from "./open.js";
3
+ import { documentOf, stateOf } from "../actions/jobs/queueDocument.js";
4
+ //#region src/modules/sqlite/jobQueue.ts
5
+ /**
6
+ * The job queue in a SQLite file, over Node's own `node:sqlite`: what `ctx.later`, a schedule's fires and a function's
7
+ * jobs wait in, surviving a restart AND shared — every process on the file (replicas on one machine, a server started
8
+ * with `workers`) claims from the same queue, each job by one of them.
9
+ *
10
+ * ```ts
11
+ * import { createSqliteJobQueue, createSqliteKv } from '@plitzi/sdk-server/sqlite';
12
+ *
13
+ * createServer({ action: { kv: createSqliteKv({ db }), jobs: { queue: createSqliteJobQueue({ db }) } } });
14
+ * ```
15
+ *
16
+ * The rules are the in-process queue's, to the letter (`queueRules`), run on the state as the table holds it, inside
17
+ * one `BEGIN IMMEDIATE` transaction a call: two processes never claim one job, nor write over each other's change. The
18
+ * state is one row, read whole each call — right for what a project's queue holds (its jobs waiting and the last
19
+ * `retainFinished` done); a deployment of thousands a minute keeps its queue in a database (`JobQueue`).
20
+ */
21
+ var createSqliteJobQueue = (options) => {
22
+ const table = options.table ?? "action_jobs";
23
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSqliteJobQueue: "${table}" is not a table name (letters, digits and _, not starting with a digit).`);
24
+ const db = options.db ?? openDatabase(options.file);
25
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK (id = 1), document TEXT NOT NULL)`);
26
+ const statements = {
27
+ read: db.prepare(`SELECT document FROM ${table} WHERE id = 1`),
28
+ write: db.prepare(`INSERT INTO ${table} (id, document) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET document = excluded.document`)
29
+ };
30
+ const rulesOptions = {
31
+ retainFinished: options.retainFinished ?? 500,
32
+ clock: options.clock ?? Date.now
33
+ };
34
+ const read = () => {
35
+ const row = statements.read.get();
36
+ if (typeof row?.document !== "string") return emptyState();
37
+ const state = stateOf(JSON.parse(row.document));
38
+ if (typeof state === "string") throw new Error(`createSqliteJobQueue: the table ${table} holds no queue it wrote (${state}). Point \`table\` elsewhere.`);
39
+ return state;
40
+ };
41
+ return queueOver((method, args) => {
42
+ db.exec("BEGIN IMMEDIATE");
43
+ try {
44
+ const state = read();
45
+ const answer = applyRule(queueRules(state, rulesOptions), method, args);
46
+ if (changedBy(method, answer)) statements.write.run(JSON.stringify(documentOf(state)));
47
+ db.exec("COMMIT");
48
+ return Promise.resolve(answer);
49
+ } catch (error) {
50
+ db.exec("ROLLBACK");
51
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
52
+ }
53
+ });
54
+ };
55
+ //#endregion
56
+ export { createSqliteJobQueue };
@@ -1,5 +1,5 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
1
  import { ActionKvAdapter } from '../actions/types';
2
+ import { DatabaseSync } from 'node:sqlite';
3
3
  export type SqliteKvOptions = ({
4
4
  /** The database file — created, with its folder, when it is not there. Opened in WAL mode. */
5
5
  file: string;
@@ -1,18 +1,10 @@
1
- import path from "node:path";
2
- import fs from "node:fs";
3
- import { DatabaseSync } from "node:sqlite";
1
+ import { openDatabase } from "./open.js";
4
2
  //#region src/modules/sqlite/kv.ts
5
3
  /**
6
4
  * The STORE's clock in epoch ms, read inside each statement: every process on the file agrees on what "now" is.
7
5
  * `julianday()` with no argument is the current instant.
8
6
  */
9
7
  var NOW_MS = "CAST((julianday() - 2440587.5) * 86400000 AS INTEGER)";
10
- var open = (file) => {
11
- fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
12
- const db = new DatabaseSync(file);
13
- db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;");
14
- return db;
15
- };
16
8
  /**
17
9
  * A key/value store in a SQLite file, over Node's own `node:sqlite` — nothing to install, nothing to run beside the
18
10
  * server. For a deployment with no database that wants what `kv` keeps to survive a restart AND to be shared: every
@@ -35,7 +27,7 @@ var open = (file) => {
35
27
  var createSqliteKv = (options) => {
36
28
  const table = options.table ?? "action_kv";
37
29
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSqliteKv: "${table}" is not a table name (letters, digits and _, not starting with a digit).`);
38
- const db = options.db ?? open(options.file);
30
+ const db = options.db ?? openDatabase(options.file);
39
31
  db.exec(`CREATE TABLE IF NOT EXISTS ${table} (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER)`);
40
32
  const live = `(expires_at IS NULL OR expires_at > ${NOW_MS})`;
41
33
  const expiry = (ttlSeconds) => ttlSeconds === void 0 ? null : ttlSeconds * 1e3;
@@ -0,0 +1,3 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ /** A SQLite file opened for the stores that share it — its folder made when it is not there. */
3
+ export declare const openDatabase: (file: string) => DatabaseSync;
@@ -0,0 +1,13 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ //#region src/modules/sqlite/open.ts
5
+ /** A SQLite file opened for the stores that share it — its folder made when it is not there. */
6
+ var openDatabase = (file) => {
7
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
8
+ const db = new DatabaseSync(file);
9
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;");
10
+ return db;
11
+ };
12
+ //#endregion
13
+ export { openDatabase };
@@ -12,6 +12,10 @@ export type ComponentProps = {
12
12
  debugMode?: boolean;
13
13
  /** Set when the metering adapter degrades this render: the account behind this space is over its quota. */
14
14
  overQuota?: boolean;
15
+ /** Set when the metering adapter says the space has nearly spent its allowance. */
16
+ quotaNear?: boolean;
17
+ /** Set when the metering adapter keeps the deployment's badge on this render. */
18
+ badge?: boolean;
15
19
  /** The theme this document was rendered with, from the visitor's cookie. See `prepareRender`. */
16
20
  theme?: Theme;
17
21
  /** The kept state the first paint depends on (`settings.paintedState`), from the visitor's cookie. */
@@ -21,5 +25,5 @@ export type ComponentProps = {
21
25
  /** The flags a tester forced, for a page allowed to debug. See `prepareRender`. */
22
26
  forcedFlags?: Record<string, boolean>;
23
27
  };
24
- declare const Component: ({ server, renderMode, previewMode, offlineData, environment, plugins, ssrResult, sdkDevToolsStylePath, sdkIconsStylePath, debugMode, overQuota, theme, state, serverFlags, forcedFlags }: ComponentProps) => import('react').JSX.Element;
28
+ declare const Component: ({ server, renderMode, previewMode, offlineData, environment, plugins, ssrResult, sdkDevToolsStylePath, sdkIconsStylePath, debugMode, overQuota, quotaNear, badge, theme, state, serverFlags, forcedFlags }: ComponentProps) => import('react').JSX.Element;
25
29
  export default Component;
@@ -1,7 +1,7 @@
1
1
  import PlitziSdk from "@plitzi/plitzi-sdk";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  //#region src/modules/ssr/Component.tsx
4
- var Component = ({ server, renderMode = "raw", previewMode = true, offlineData, environment = "main", plugins, ssrResult, sdkDevToolsStylePath, sdkIconsStylePath, debugMode = false, overQuota, theme, state, serverFlags, forcedFlags }) => {
4
+ var Component = ({ server, renderMode = "raw", previewMode = true, offlineData, environment = "main", plugins, ssrResult, sdkDevToolsStylePath, sdkIconsStylePath, debugMode = false, overQuota, quotaNear, badge, theme, state, serverFlags, forcedFlags }) => {
5
5
  const serverWithResult = {
6
6
  ...server,
7
7
  ssr: {
@@ -20,6 +20,8 @@ var Component = ({ server, renderMode = "raw", previewMode = true, offlineData,
20
20
  sdkIconsStylePath,
21
21
  debugMode,
22
22
  ...overQuota === void 0 ? {} : { overQuota },
23
+ ...quotaNear === void 0 ? {} : { quotaNear },
24
+ ...badge === void 0 ? {} : { badge },
23
25
  ...theme === void 0 ? {} : { theme },
24
26
  ...state === void 0 ? {} : { state },
25
27
  ...serverFlags === void 0 ? {} : { serverFlags },
@@ -1,5 +1,12 @@
1
1
  import { SSRRenderResult, SSRResponseHelpers } from '@plitzi/sdk-shared';
2
- export declare const applySSRResult: (res: SSRResponseHelpers, result: SSRRenderResult) => boolean;
2
+ /** The render's own parameters the request carried, to keep on a redirect within the site. */
3
+ export declare const renderParamsOf: (query: Record<string, string>) => [string, string][];
4
+ /**
5
+ * `location` with the render's parameters, when it is on this site — a path. An address on another origin is never
6
+ * given them: a space token sent there is a credential handed to somebody else.
7
+ */
8
+ export declare const withRenderParams: (location: string, params: readonly [string, string][]) => string;
9
+ export declare const applySSRResult: (res: SSRResponseHelpers, result: SSRRenderResult, kept?: readonly [string, string][]) => boolean;
3
10
  /**
4
11
  * Whether a render may be kept and served again: only a page that answered 200. A cached page is sent without the
5
12
  * status it was rendered with, and a "not found" kept per address would let anybody asking for addresses at random
@@ -1,9 +1,29 @@
1
+ import { PREVIEW_TOKEN_PARAM } from "../../core/previewToken.js";
2
+ import { SPACE_TOKEN_PARAM } from "../../core/auth/credentials.js";
1
3
  //#region src/modules/ssr/applySSRResult.ts
2
- var applySSRResult = (res, result) => {
4
+ /**
5
+ * What names the render rather than the page: the space (`access-token`, on a host serving many) and the draft (`__pt`).
6
+ * A redirect within the site that dropped them landed on another space, or the live one, without its preview session —
7
+ * a space's journey on a page for signed-in visitors, opened by the server's runner, lost the space it was playing.
8
+ */
9
+ var RENDER_PARAMS = [SPACE_TOKEN_PARAM, PREVIEW_TOKEN_PARAM];
10
+ /** The render's own parameters the request carried, to keep on a redirect within the site. */
11
+ var renderParamsOf = (query) => RENDER_PARAMS.flatMap((name) => query[name] ? [[name, query[name]]] : []);
12
+ /**
13
+ * `location` with the render's parameters, when it is on this site — a path. An address on another origin is never
14
+ * given them: a space token sent there is a credential handed to somebody else.
15
+ */
16
+ var withRenderParams = (location, params) => {
17
+ if (params.length === 0 || !location.startsWith("/") || location.startsWith("//")) return location;
18
+ const url = new URL(location, "http://site.invalid");
19
+ for (const [name, value] of params) if (!url.searchParams.has(name)) url.searchParams.set(name, value);
20
+ return `${url.pathname}${url.search}${url.hash}`;
21
+ };
22
+ var applySSRResult = (res, result, kept = []) => {
3
23
  if (result.headers) for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
4
24
  if (result.redirect !== void 0) {
5
25
  res.setStatus(result.status ?? 302);
6
- res.setHeader("Location", result.redirect);
26
+ res.setHeader("Location", withRenderParams(result.redirect, kept));
7
27
  res.send("");
8
28
  return true;
9
29
  }
@@ -31,4 +51,4 @@ var withRefusal = (result, refused) => {
31
51
  if (refused && result.redirect === void 0 && result.status === void 0) result.status = refused === "unauthenticated" ? 401 : 403;
32
52
  };
33
53
  //#endregion
34
- export { applySSRResult, isReusable, withNotFound, withRefusal };
54
+ export { applySSRResult, isReusable, renderParamsOf, withNotFound, withRefusal, withRenderParams };
@@ -1,8 +1,9 @@
1
- import { buildHtmlCacheKey } from "../../helpers/cache/keys.js";
2
1
  import { draftSessionCookie, takeDraftOverride } from "./preview.js";
3
- import { applySSRResult, isReusable } from "./applySSRResult.js";
2
+ import { buildHtmlCacheKey } from "../../helpers/cache/keys.js";
3
+ import { applySSRResult, isReusable, renderParamsOf } from "./applySSRResult.js";
4
4
  import { buildBody } from "./buildBody.js";
5
5
  import { streamBody } from "./streamBody.js";
6
+ import { escapeHtml } from "../../helpers/escapeHtml.js";
6
7
  import { RequestMetrics } from "../../helpers/metrics.js";
7
8
  //#region src/modules/ssr/handler.tsx
8
9
  var meterPage = async (req, config, spaceId, environment, revision, cached) => {
@@ -20,12 +21,24 @@ var meterPage = async (req, config, spaceId, environment, revision, cached) => {
20
21
  return;
21
22
  }
22
23
  };
24
+ /**
25
+ * A page the deployment holds back (`SSRMeterDecision.unavailable`), in the words it chose: 503, kept by nobody — no
26
+ * cache, no index — and nothing of the space rendered. Light and dark, as the visitor's system is.
27
+ */
28
+ var sendUnavailable = (res, said) => {
29
+ res.setStatus(503);
30
+ res.setHeader("Cache-Control", "no-store");
31
+ res.setHeader("X-Robots-Tag", "noindex, nofollow");
32
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
33
+ res.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Not available</title><style>:root{color-scheme:light dark}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font:16px/1.5 ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;background:#fff;color:#18181b}@media (prefers-color-scheme:dark){body{background:#09090b;color:#f4f4f5}}main{max-width:520px;padding:24px;text-align:center}</style></head><body><main><p>${escapeHtml(said)}</p></main></body></html>`);
34
+ };
23
35
  var renderSSR = async (req, res, config, renderFn, pluginManager, caches) => {
24
36
  const { environment = "main", spaceId = 1, revision = 0 } = req.ctx.spaceDeployment || {};
25
37
  const devMode = config.devMode ?? false;
26
38
  res.setHeader("Content-Type", "text/html; charset=utf-8");
27
39
  const draft = await takeDraftOverride(req, config);
28
40
  const offlineDataOverride = draft?.data;
41
+ if (draft?.inspected) req.ctx.inspectedDraft = true;
29
42
  if (draft) {
30
43
  /**
31
44
  * Unsaved work, told not to travel.
@@ -45,12 +58,24 @@ var renderSSR = async (req, res, config, renderFn, pluginManager, caches) => {
45
58
  if (cached) {
46
59
  res.setHeader("X-Cache", "HIT");
47
60
  if (devMode) res.setHeader("Server-Timing", "html;desc=\"cache-hit\";dur=0");
48
- await meterPage(req, config, spaceId, environment, revision, true);
61
+ const decision = await meterPage(req, config, spaceId, environment, revision, true);
62
+ if (decision?.unavailable !== void 0) {
63
+ sendUnavailable(res, decision.unavailable);
64
+ return;
65
+ }
66
+ if (decision?.noindex) res.setHeader("X-Robots-Tag", "noindex, nofollow");
49
67
  res.send(cached.html, { compressed: cached.compressed });
50
68
  return;
51
69
  }
52
70
  }
53
- if (!offlineDataOverride) req.ctx.meter = await meterPage(req, config, spaceId, environment, revision, false);
71
+ if (!offlineDataOverride) {
72
+ req.ctx.meter = await meterPage(req, config, spaceId, environment, revision, false);
73
+ if (req.ctx.meter?.unavailable !== void 0) {
74
+ sendUnavailable(res, req.ctx.meter.unavailable);
75
+ return;
76
+ }
77
+ if (req.ctx.meter?.noindex) res.setHeader("X-Robots-Tag", "noindex, nofollow");
78
+ }
54
79
  const metrics = devMode ? new RequestMetrics() : void 0;
55
80
  if (cacheKey) res.setHeader("X-Cache", "MISS");
56
81
  if (config.streaming) {
@@ -62,7 +87,7 @@ var renderSSR = async (req, res, config, renderFn, pluginManager, caches) => {
62
87
  res.setHeader("Server-Timing", metrics.toServerTimingHeader());
63
88
  metrics.log(`${req.method} ${req.path}`);
64
89
  }
65
- if (applySSRResult(res, result)) return;
90
+ if (applySSRResult(res, result, renderParamsOf(req.query))) return;
66
91
  if (htmlCache && cacheKey && body !== void 0 && cacheable && isReusable(result)) {
67
92
  const page = {
68
93
  html: body,