@plitzi/sdk-server 0.38.23 → 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 +172 -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 +75 -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 +11 -3
  77. package/dist/hosts/project/serveProject.js +94 -36
  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 +21 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +45 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +39 -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 +3 -1
  133. package/dist/modules/functions/oauth.js +20 -7
  134. package/dist/modules/functions/protocol.d.ts +9 -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
@@ -1,5 +1,6 @@
1
1
  import { warnRealtime } from "./failure.js";
2
2
  import { isMessage } from "./message.js";
3
+ import { PRESENCE_HEARTBEAT_MS } from "./presence.js";
3
4
  import { JOIN_TYPE, LEAVE_TYPE, REVOKED_TYPE } from "@plitzi/sdk-shared/realtime";
4
5
  //#region src/modules/realtime/hub.ts
5
6
  /** A space's topic, as the adapter knows it: namespaced, so two spaces never hear each other. */
@@ -25,8 +26,30 @@ var parse = (raw) => {
25
26
  * A hundred pages on one board are a hundred connections here and a single subscription to the adapter: a message
26
27
  * arrives once and is written to each of them. The last one to leave a topic unsubscribes it.
27
28
  */
28
- var createRealtimeHub = (pubsub, retained) => {
29
+ var createRealtimeHub = (pubsub, retained, presence) => {
29
30
  const byToken = /* @__PURE__ */ new Map();
31
+ /** The presence topics a connection is counted on: those of a `presence: true` channel, for a page that is not watching. */
32
+ const counted = (connection) => connection.observer ? [] : [...connection.topics].flatMap(([topic, declaration]) => declaration.presence ? [topic] : []);
33
+ const memberOf = (connection) => ({
34
+ from: connection.id,
35
+ ...connection.user ? { user: connection.user } : {},
36
+ since: Date.now()
37
+ });
38
+ const heartbeat = presence ? setInterval(() => {
39
+ const byTopic = /* @__PURE__ */ new Map();
40
+ for (const connection of byToken.values()) for (const topic of counted(connection)) {
41
+ const key = adapterTopic(connection.space, topic);
42
+ const entry = byTopic.get(key) ?? {
43
+ space: connection.space,
44
+ topic,
45
+ members: []
46
+ };
47
+ entry.members.push(memberOf(connection));
48
+ byTopic.set(key, entry);
49
+ }
50
+ for (const { space, topic, members } of byTopic.values()) presence.touch(space, topic, members).catch(warnRealtime(`"${topic}"'s presence was not refreshed`));
51
+ }, PRESENCE_HEARTBEAT_MS) : void 0;
52
+ heartbeat?.unref();
30
53
  const local = /* @__PURE__ */ new Map();
31
54
  const publish = (space, message) => pubsub.publish(adapterTopic(space, message.topic), JSON.stringify(message));
32
55
  const join = async (connection, topic) => {
@@ -112,19 +135,27 @@ var createRealtimeHub = (pubsub, retained) => {
112
135
  /**
113
136
  * Subscribes a new connection to its topics, hands it what each `retain: true` one keeps, and tells the members of
114
137
  * each presence channel it arrived. What is kept is read AFTER joining, so nothing said in between is missed; a
115
- * message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`.
138
+ * message heard live and then kept arrives twice, and the page keeps the newer of a type by its `at`. Each kept one
139
+ * is `replayed`: a page that joins tells it from what is said now.
116
140
  */
117
141
  connect: async (connection) => {
118
142
  byToken.set(connection.token, connection);
119
143
  for (const [topic, declaration] of connection.topics) {
120
144
  await join(connection, topic);
121
- if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", message));
122
- if (declaration.presence && !connection.observer) await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
145
+ if (declaration.retain === true) (await retained.of(connection.space, topic)).forEach((message) => connection.send("message", {
146
+ ...message,
147
+ replayed: true
148
+ }));
149
+ if (declaration.presence && !connection.observer) {
150
+ await publish(connection.space, from(connection, topic, JOIN_TYPE, null));
151
+ await presence?.touch(connection.space, topic, [memberOf(connection)]).catch(warnRealtime(`"${topic}"'s presence was not recorded`));
152
+ }
123
153
  }
124
154
  },
125
155
  /** Unsubscribes a connection that went away, and tells the channels it announced itself on. */
126
156
  disconnect: async (connection) => {
127
157
  byToken.delete(connection.token);
158
+ for (const topic of counted(connection)) await presence?.depart(connection.space, topic, connection.id).catch(warnRealtime(`"${topic}"'s presence was not let go of`));
128
159
  for (const topic of connection.topics.keys()) {
129
160
  if (connection.announced.has(topic)) await publish(connection.space, from(connection, topic, LEAVE_TYPE, null));
130
161
  await leave(connection, topic);
@@ -136,6 +167,7 @@ var createRealtimeHub = (pubsub, retained) => {
136
167
  * goes when its page leaves.
137
168
  */
138
169
  closeAll: () => {
170
+ clearInterval(heartbeat);
139
171
  [...byToken.values()].forEach((connection) => connection.end());
140
172
  },
141
173
  /** How many connections this process holds — for tests and for a health endpoint. */
@@ -2,6 +2,7 @@ import { ChannelResolver } from './declarations';
2
2
  import { RealtimeGrants } from './grants';
3
3
  import { RealtimeHub } from './hub';
4
4
  import { JobLookup } from './jobs';
5
+ import { RealtimePresenceMember } from './presence';
5
6
  import { FunctionJobView, RealtimeTransport, SSRServerConfig } from '@plitzi/sdk-shared';
6
7
  export { createMemoryPubSub } from './memoryPubSub';
7
8
  export { handleRealtimePublish, handleRealtimeSubscribe } from './handlers';
@@ -13,6 +14,8 @@ export type RealtimeModule = {
13
14
  transport: RealtimeTransport;
14
15
  /** Origins besides the server's own whose pages may open a socket. */
15
16
  allowedOrigins: readonly string[];
17
+ /** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
18
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
16
19
  resolveChannels: ChannelResolver;
17
20
  /** The grants issued for topics of channels declared `grant: true`, and the check a subscription makes. */
18
21
  grants: RealtimeGrants;
@@ -44,6 +47,17 @@ export type RealtimeModule = {
44
47
  spaceId: number;
45
48
  environment: string;
46
49
  }, topic: string, grant?: string) => Promise<void>;
50
+ /**
51
+ * Who is on a topic of a `presence: true` channel now, on every replica — what a function's `ctx.presence` reads. A
52
+ * topic of any other channel is refused: nobody is counted there, and an empty answer would read as an empty room.
53
+ */
54
+ presence: (space: {
55
+ spaceId: number;
56
+ environment: string;
57
+ }, topic: string) => Promise<{
58
+ count: number;
59
+ members: RealtimePresenceMember[];
60
+ }>;
47
61
  /** Says a job of the space's functions as it is now on its topic (`$job:<id>`), kept for a page that joins later. */
48
62
  publishJob: (space: {
49
63
  spaceId: number;
@@ -2,6 +2,7 @@ import { fleetStore } from "../../core/server/fleet/link.js";
2
2
  import { KV_METHODS, createMemoryKv } from "../actions/runtime/memoryKv.js";
3
3
  import { createRealtimeGrants } from "./grants.js";
4
4
  import { createChannelResolver } from "./declarations.js";
5
+ import { createRealtimePresence } from "./presence.js";
5
6
  import { createRealtimeHub } from "./hub.js";
6
7
  import { publishJobView } from "./jobs.js";
7
8
  import { createMemoryPubSub } from "./memoryPubSub.js";
@@ -24,7 +25,8 @@ var realtimeModuleFor = (config) => {
24
25
  if (existing) return existing;
25
26
  const kv = config.action?.kv ?? fleetStore("realtime.kv", KV_METHODS) ?? createMemoryKv();
26
27
  const retained = createRealtimeRetained(kv);
27
- const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained);
28
+ const presence = createRealtimePresence(kv);
29
+ const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained, presence);
28
30
  const resolveChannels = createChannelResolver(getOfflineData);
29
31
  const grants = createRealtimeGrants(kv);
30
32
  let jobLookup;
@@ -33,6 +35,7 @@ var realtimeModuleFor = (config) => {
33
35
  path: config.realtime?.path ?? "/_realtime",
34
36
  transport: config.realtime?.transport ?? "sse",
35
37
  allowedOrigins: config.realtime?.allowedOrigins ?? [],
38
+ ...config.realtime?.admitSpace ? { admitSpace: config.realtime.admitSpace } : {},
36
39
  resolveChannels,
37
40
  grants,
38
41
  close: () => hub.closeAll(),
@@ -52,6 +55,16 @@ var realtimeModuleFor = (config) => {
52
55
  if (retain) await retained.keep(space, message);
53
56
  await hub.publish(space, message);
54
57
  },
58
+ presence: async (space, topic) => {
59
+ const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
60
+ if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
61
+ if (match.declaration.presence !== true) throw new Error(`"${match.pattern}" counts nobody: declare it \`presence: true\` for its pages to be counted, and read here`);
62
+ const members = await presence.of(space, topic);
63
+ return {
64
+ count: members.length,
65
+ members
66
+ };
67
+ },
55
68
  grant: async (space, topic, ttlSeconds) => {
56
69
  const match = matchChannel(topic, await resolveChannels(space.spaceId, space.environment));
57
70
  if (!match) throw new Error(`No channel of this space matches "${topic}": declare it in the space's \`channels\``);
@@ -0,0 +1,33 @@
1
+ import { RealtimeSpace } from './hub';
2
+ import { ActionKvAdapter } from '../actions/types';
3
+ import { RealtimeSender } from '@plitzi/sdk-shared';
4
+ /** How often a replica says its members are still there: a connection open for hours is seen every this often. */
5
+ export declare const PRESENCE_HEARTBEAT_MS = 30000;
6
+ /** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
7
+ export declare const PRESENCE_STALE_MS: number;
8
+ /** One page on a presence channel, as every replica sees it. */
9
+ export type RealtimePresenceMember = {
10
+ /** Its public name on the channel — the `from` of what it says. */
11
+ from: string;
12
+ /** Who is signed in on it, when someone is. */
13
+ user?: RealtimeSender['user'];
14
+ /** When it arrived, ms. */
15
+ since: number;
16
+ };
17
+ export type RealtimePresence = {
18
+ /** Records the pages that arrived on `topic` here — or are still on it, at a heartbeat: their `seenAt` moves on. */
19
+ touch: (space: RealtimeSpace, topic: string, members: readonly RealtimePresenceMember[]) => Promise<void>;
20
+ /** The page left `topic`. */
21
+ depart: (space: RealtimeSpace, topic: string, from: string) => Promise<void>;
22
+ /** Who is on `topic` now, on every replica, the earliest first — those not seen within {@link PRESENCE_STALE_MS} not. */
23
+ of: (space: RealtimeSpace, topic: string) => Promise<RealtimePresenceMember[]>;
24
+ };
25
+ /**
26
+ * Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
27
+ * so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
28
+ * replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
29
+ *
30
+ * One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
31
+ * down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
32
+ */
33
+ export declare const createRealtimePresence: (store: ActionKvAdapter, now?: () => number) => RealtimePresence;
@@ -0,0 +1,56 @@
1
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
2
+ //#region src/modules/realtime/presence.ts
3
+ /** How often a replica says its members are still there: a connection open for hours is seen every this often. */
4
+ var PRESENCE_HEARTBEAT_MS = 3e4;
5
+ /** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
6
+ var PRESENCE_STALE_MS = 3 * PRESENCE_HEARTBEAT_MS;
7
+ /** How many times a write is tried while other writes on the same topic keep landing first. */
8
+ var ATTEMPTS = 8;
9
+ var isMember = (value) => isRecord(value) && typeof value.from === "string" && typeof value.since === "number" && typeof value.seenAt === "number" && (value.user === void 0 || isRecord(value.user));
10
+ /** A topic's members, as stored — read from a store something else could have written. */
11
+ var parseKept = (raw) => {
12
+ try {
13
+ const value = JSON.parse(raw ?? "{}");
14
+ return isRecord(value) ? Object.fromEntries(Object.entries(value).filter((entry) => isMember(entry[1]))) : {};
15
+ } catch {
16
+ return {};
17
+ }
18
+ };
19
+ var fresh = (kept, now) => Object.fromEntries(Object.entries(kept).filter(([, member]) => now - member.seenAt < PRESENCE_STALE_MS));
20
+ /**
21
+ * Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
22
+ * so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
23
+ * replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
24
+ *
25
+ * One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
26
+ * down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
27
+ */
28
+ var createRealtimePresence = (store, now = Date.now) => {
29
+ const key = ({ spaceId, environment }, topic) => `realtime-presence:${String(spaceId)}:${environment}:${topic}`;
30
+ const change = async (space, topic, next) => {
31
+ const at = key(space, topic);
32
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
33
+ const raw = await store.get(at);
34
+ const written = JSON.stringify(next(fresh(parseKept(raw), now())));
35
+ if (await store.swap(at, raw, written, Math.ceil(90))) return;
36
+ }
37
+ throw new Error(`"${topic}" changed under ${String(ATTEMPTS)} writes in a row: its presence was not recorded`);
38
+ };
39
+ return {
40
+ touch: (space, topic, members) => change(space, topic, (kept) => ({
41
+ ...kept,
42
+ ...Object.fromEntries(members.map((member) => [member.from, {
43
+ ...kept[member.from] ?? member,
44
+ seenAt: now()
45
+ }]))
46
+ })),
47
+ depart: (space, topic, from) => change(space, topic, (kept) => Object.fromEntries(Object.entries(kept).filter(([name]) => name !== from))),
48
+ of: async (space, topic) => Object.values(fresh(parseKept(await store.get(key(space, topic))), now())).map((member) => ({
49
+ from: member.from,
50
+ since: member.since,
51
+ ...member.user ? { user: member.user } : {}
52
+ })).sort((a, b) => a.since - b.since)
53
+ };
54
+ };
55
+ //#endregion
56
+ export { PRESENCE_HEARTBEAT_MS, PRESENCE_STALE_MS, createRealtimePresence };
@@ -16,6 +16,8 @@ export type SocketDeps = {
16
16
  allowedOrigins: readonly string[];
17
17
  /** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
18
18
  jobs?: JobLookup;
19
+ /** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
20
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
19
21
  };
20
22
  /**
21
23
  * A page's realtime connection as a WebSocket: the same topics, rules and messages as the Server-Sent Events one, in
@@ -25,4 +27,4 @@ export type SocketDeps = {
25
27
  * Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
26
28
  * reports it exactly as it would there.
27
29
  */
28
- export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }: SocketDeps) => Promise<void>;
30
+ export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }: SocketDeps) => Promise<void>;
@@ -50,7 +50,7 @@ var ackId = (id) => typeof id === "number" && Number.isInteger(id) || typeof id
50
50
  * Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
51
51
  * reports it exactly as it would there.
52
52
  */
53
- var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }) => {
53
+ var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }) => {
54
54
  if (!originAllowed(raw, req, allowedOrigins)) {
55
55
  answer(res, {
56
56
  status: 403,
@@ -59,7 +59,7 @@ var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels
59
59
  });
60
60
  return;
61
61
  }
62
- const admission = await admit(req, resolveChannels, grants, jobs);
62
+ const admission = await admit(req, resolveChannels, grants, jobs, admitSpace);
63
63
  if (!admission.ok) {
64
64
  answer(res, admission.answer);
65
65
  return;
@@ -1,3 +1,4 @@
1
+ import { OutboundOptions } from '../../helpers/outboundGuard';
1
2
  import { ActionsModule } from '../actions';
2
3
  import { ProjectDataLookup } from '../actions/runtime/projectData';
3
4
  import { ActionLookups } from '../actions/types';
@@ -18,7 +19,7 @@ import { SSRAdapters } from '@plitzi/sdk-shared';
18
19
  *
19
20
  * A deployment that resolves server elements some other way still supplies its own `getRscData`, and that one wins.
20
21
  */
21
- export declare const connectorRscData: ({ connectors, actions, publicDir, data, elementTimeoutMs }: {
22
+ export declare const connectorRscData: ({ connectors, actions, publicDir, data, elementTimeoutMs, sayFailures, outbound }: {
22
23
  connectors?: ConnectorLookups;
23
24
  actions?: {
24
25
  lookups: ActionLookups;
@@ -33,4 +34,8 @@ export declare const connectorRscData: ({ connectors, actions, publicDir, data,
33
34
  data?: ProjectDataLookup;
34
35
  /** The deployment's per-element ceiling, when it set one. `resolveRscData` decides the default. */
35
36
  elementTimeoutMs?: number;
37
+ /** While developing: a failed element says why where the page reads it. */
38
+ sayFailures?: boolean;
39
+ /** The deployment's own origins a connector or a query may reach on its network (`outbound.privateOrigins`). */
40
+ outbound?: OutboundOptions;
36
41
  }) => NonNullable<SSRAdapters["getRscData"]>;
@@ -1,7 +1,9 @@
1
1
  import { createActionResolver } from "../actions/runtime/renderResolver.js";
2
2
  import { createConnectorResolver } from "../connectors/resolver.js";
3
+ import { externalQueryReader } from "./externalQueryReader.js";
3
4
  import { dataLookupResolver, publicFileResolver } from "./publicFileResolver.js";
4
5
  import { resolveRscData } from "./resolveRscData.js";
6
+ import { serverQueryOf } from "@plitzi/sdk-shared/schema";
5
7
  //#region src/modules/rsc/connectorRscData.ts
6
8
  /**
7
9
  * `getRscData`, built from the producers the server was already given — connectors, actions, its own static files.
@@ -18,24 +20,42 @@ import { resolveRscData } from "./resolveRscData.js";
18
20
  *
19
21
  * A deployment that resolves server elements some other way still supplies its own `getRscData`, and that one wins.
20
22
  */
21
- var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs }) => {
22
- const resolveConnector = connectors ? createConnectorResolver(connectors) : void 0;
23
+ var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs, sayFailures = false, outbound }) => {
24
+ const resolveConnector = connectors ? createConnectorResolver(connectors, outbound) : void 0;
23
25
  const resolveAction = actions ? createActionResolver(actions.lookups, actions.module) : void 0;
24
26
  const resolvePublicFile = publicDir ? publicFileResolver(publicDir) : void 0;
25
27
  const resolveDataFile = data ? dataLookupResolver(data) : void 0;
28
+ const readExternal = externalQueryReader({ outbound });
26
29
  /**
27
30
  * An element names ONE producer, and which one decides how its data is fetched.
28
31
  *
29
32
  * A connector is the declarative read and stays the default; an action is the read a manifest cannot express; a
30
- * file of the server's own is the read with no backend at all. Checked in that order so an element carrying more
33
+ * file of the server's own is the read with no backend at all, and another site's address is asked as the browser
34
+ * would have asked it (`externalQueryResolver`). Checked in that order so an element carrying more
31
35
  * than one keeps resolving the way its page already renders, instead of silently changing under them.
32
36
  */
33
37
  const resolveElement = async (context) => {
34
38
  const attributes = context.element.attributes;
35
39
  if (attributes.connector) return resolveConnector ? resolveConnector(context) : void 0;
36
40
  if (attributes.action) return resolveAction ? resolveAction(context) : void 0;
37
- const fromData = resolveDataFile ? await resolveDataFile(context) : void 0;
38
- return fromData !== void 0 ? fromData : resolvePublicFile ? resolvePublicFile(context) : void 0;
41
+ const query = serverQueryOf(context.element, context.templateData);
42
+ if (query === void 0) return;
43
+ if (query.kind === "unresolved") throw new Error(`the page server cannot read its query: ${query.why}`);
44
+ if (query.kind === "url") return readExternal(query, context.signal);
45
+ const atPath = {
46
+ ...context,
47
+ element: {
48
+ ...context.element,
49
+ attributes: {
50
+ ...context.element.attributes,
51
+ query: query.path
52
+ }
53
+ }
54
+ };
55
+ const fromData = resolveDataFile ? await resolveDataFile(atPath) : void 0;
56
+ const fromFile = fromData !== void 0 ? fromData : resolvePublicFile ? await resolvePublicFile(atPath) : void 0;
57
+ if (fromFile === void 0) throw new Error(`no file of this server's answers ${query.path}`);
58
+ return fromFile;
39
59
  };
40
60
  return async ({ req, spaceId, environment, user, ids, loadOfflineData, flagOverrides, signal }) => {
41
61
  const offlineData = await loadOfflineData();
@@ -50,7 +70,8 @@ var connectorRscData = ({ connectors, actions, publicDir, data, elementTimeoutMs
50
70
  resolveElement,
51
71
  ...flagOverrides ? { flagOverrides } : {},
52
72
  ...signal ? { signal } : {},
53
- ...elementTimeoutMs === void 0 ? {} : { timeoutMs: elementTimeoutMs }
73
+ ...elementTimeoutMs === void 0 ? {} : { timeoutMs: elementTimeoutMs },
74
+ sayFailures
54
75
  });
55
76
  };
56
77
  };
@@ -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. */