@plitzi/sdk-server 0.38.20 → 0.38.22

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 (245) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +2 -2
  3. package/dist/actions.d.ts +6 -0
  4. package/dist/actions.js +2 -1
  5. package/dist/core/auth/createAuth.d.ts +1 -1
  6. package/dist/core/auth/tokens.d.ts +1 -1
  7. package/dist/core/configSeam.js +12 -2
  8. package/dist/core/services/functionRoutes.js +7 -2
  9. package/dist/core/services/realtime.js +5 -2
  10. package/dist/functions-api.d.ts +176 -3
  11. package/dist/functions.d.ts +3 -1
  12. package/dist/functions.js +2 -1
  13. package/dist/helpers/serverLog.d.ts +1 -1
  14. package/dist/helpers/serverLog.js +1 -1
  15. package/dist/hosts/project/plugins.js +20 -3
  16. package/dist/hosts/project/serveProject.js +16 -1
  17. package/dist/modules/actions/index.js +17 -4
  18. package/dist/modules/actions/jobs/index.d.ts +4 -3
  19. package/dist/modules/actions/jobs/index.js +2 -1
  20. package/dist/modules/actions/jobs/later.d.ts +2 -2
  21. package/dist/modules/actions/jobs/later.js +5 -2
  22. package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
  23. package/dist/modules/actions/jobs/memoryQueue.js +69 -25
  24. package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
  25. package/dist/modules/actions/jobs/scheduler.js +5 -2
  26. package/dist/modules/actions/jobs/worker.d.ts +6 -3
  27. package/dist/modules/actions/jobs/worker.js +104 -10
  28. package/dist/modules/actions/runtime/errors.d.ts +9 -1
  29. package/dist/modules/actions/runtime/errors.js +12 -2
  30. package/dist/modules/actions/runtime/runAction.d.ts +5 -2
  31. package/dist/modules/actions/runtime/runAction.js +5 -3
  32. package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
  33. package/dist/modules/actions/runtime/taskContext.js +9 -1
  34. package/dist/modules/actions/types.d.ts +22 -6
  35. package/dist/modules/functions/capabilities.js +124 -13
  36. package/dist/modules/functions/config.d.ts +20 -0
  37. package/dist/modules/functions/context.d.ts +2 -2
  38. package/dist/modules/functions/context.js +16 -3
  39. package/dist/modules/functions/contract.d.ts +97 -3
  40. package/dist/modules/functions/driver.js +136 -9
  41. package/dist/modules/functions/jobControl.d.ts +21 -0
  42. package/dist/modules/functions/jobControl.js +43 -0
  43. package/dist/modules/functions/jobs.d.ts +98 -0
  44. package/dist/modules/functions/jobs.js +438 -0
  45. package/dist/modules/functions/manifest.d.ts +2 -0
  46. package/dist/modules/functions/manifest.js +37 -4
  47. package/dist/modules/functions/native.js +2 -1
  48. package/dist/modules/functions/oauth.d.ts +3 -2
  49. package/dist/modules/functions/oauth.js +53 -19
  50. package/dist/modules/functions/protocol.d.ts +98 -7
  51. package/dist/modules/functions/protocol.js +15 -1
  52. package/dist/modules/functions/routes.d.ts +9 -1
  53. package/dist/modules/functions/routes.js +50 -25
  54. package/dist/modules/functions/runner/messages.d.ts +0 -1
  55. package/dist/modules/functions/runner/messages.js +46 -5
  56. package/dist/modules/functions/runner/remote.js +60 -8
  57. package/dist/modules/functions/runner/service.js +54 -8
  58. package/dist/modules/functions/sandbox/guest.js +5 -3
  59. package/dist/modules/functions/sandbox/isolate.js +7 -8
  60. package/dist/modules/functions/space.js +4 -4
  61. package/dist/modules/mongo/jobQueue.d.ts +3 -3
  62. package/dist/modules/mongo/jobQueue.js +137 -26
  63. package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
  64. package/dist/modules/mysql/jobs/jobQueue.js +97 -33
  65. package/dist/modules/mysql/jobs/schema.js +38 -11
  66. package/dist/modules/realtime/handlers.d.ts +5 -2
  67. package/dist/modules/realtime/handlers.js +15 -4
  68. package/dist/modules/realtime/index.d.ts +11 -1
  69. package/dist/modules/realtime/index.js +8 -1
  70. package/dist/modules/realtime/jobs.d.ts +20 -0
  71. package/dist/modules/realtime/jobs.js +41 -0
  72. package/dist/modules/realtime/retained.d.ts +3 -2
  73. package/dist/modules/realtime/retained.js +2 -2
  74. package/dist/modules/realtime/socket.d.ts +4 -1
  75. package/dist/modules/realtime/socket.js +2 -2
  76. package/dist/modules/rsc/resolveRscData.js +2 -1
  77. package/dist/modules/runtime/host.js +1 -1
  78. package/dist/modules/runtime/runner.d.ts +1 -1
  79. package/dist/modules/runtime/runner.js +12 -2
  80. package/dist/modules/runtime/stages.js +1 -1
  81. package/dist/modules/ssr/applySSRResult.d.ts +5 -0
  82. package/dist/modules/ssr/applySSRResult.js +8 -1
  83. package/dist/modules/ssr/buildBody.js +2 -1
  84. package/dist/modules/ssr/prepareRender.d.ts +3 -0
  85. package/dist/modules/ssr/prepareRender.js +17 -5
  86. package/dist/modules/ssr/spaceDocument.d.ts +2 -1
  87. package/dist/modules/ssr/spaceDocument.js +14 -5
  88. package/dist/modules/ssr/streamBody.js +2 -1
  89. package/package.json +3 -3
  90. package/skills/plitzi-authoring/reference/auth.md +6 -0
  91. package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
  92. package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
  93. package/skills/plitzi-authoring/reference/realtime.md +4 -0
  94. package/dist/adapters/cloudAdapters.test.d.ts +0 -1
  95. package/dist/adapters/jsonAdapters.test.d.ts +0 -1
  96. package/dist/adapters/space/space.test.d.ts +0 -1
  97. package/dist/core/auth/api.test.d.ts +0 -1
  98. package/dist/core/auth/authorize.test.d.ts +0 -1
  99. package/dist/core/auth/createAuth.test.d.ts +0 -1
  100. package/dist/core/auth/csrf.test.d.ts +0 -1
  101. package/dist/core/auth/domains.test.d.ts +0 -1
  102. package/dist/core/auth/identity.test.d.ts +0 -1
  103. package/dist/core/auth/lifecycle.test.d.ts +0 -1
  104. package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
  105. package/dist/core/auth/redirects.test.d.ts +0 -1
  106. package/dist/core/auth/routes.test.d.ts +0 -1
  107. package/dist/core/auth/session.test.d.ts +0 -1
  108. package/dist/core/auth/spaceTokens.test.d.ts +0 -1
  109. package/dist/core/auth/throttle.test.d.ts +0 -1
  110. package/dist/core/auth/tokens.test.d.ts +0 -1
  111. package/dist/core/auth/totp.test.d.ts +0 -1
  112. package/dist/core/configSeam.test.d.ts +0 -1
  113. package/dist/core/createServer.actions.test.d.ts +0 -1
  114. package/dist/core/createServer.functions.test.d.ts +0 -1
  115. package/dist/core/createServer.livePages.test.d.ts +0 -1
  116. package/dist/core/createServer.notFound.test.d.ts +0 -1
  117. package/dist/core/createServer.oauth.test.d.ts +0 -1
  118. package/dist/core/createServer.publicData.test.d.ts +0 -1
  119. package/dist/core/createServer.test.d.ts +0 -1
  120. package/dist/core/fontStore.test.d.ts +0 -1
  121. package/dist/core/freePort.test.d.ts +0 -1
  122. package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
  123. package/dist/core/handlers/handlers.test.d.ts +0 -1
  124. package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
  125. package/dist/core/http/dispatcher.test.d.ts +0 -1
  126. package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
  127. package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
  128. package/dist/core/http/stages/images.test.d.ts +0 -1
  129. package/dist/core/http/stages/middlewares.test.d.ts +0 -1
  130. package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
  131. package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
  132. package/dist/core/oauth/authorize.test.d.ts +0 -1
  133. package/dist/core/oauth/register.test.d.ts +0 -1
  134. package/dist/core/oauth/token.test.d.ts +0 -1
  135. package/dist/core/requestParser.test.d.ts +0 -1
  136. package/dist/core/server/baseServer.test.d.ts +0 -1
  137. package/dist/core/server/closeOnSignals.test.d.ts +0 -1
  138. package/dist/core/server/drain.test.d.ts +0 -1
  139. package/dist/core/server/fleet/channel.test.d.ts +0 -1
  140. package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
  141. package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
  142. package/dist/core/server/fleet/relay.test.d.ts +0 -1
  143. package/dist/core/server/fleet/role.test.d.ts +0 -1
  144. package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
  145. package/dist/core/services/resolve.test.d.ts +0 -1
  146. package/dist/core/staticFiles.test.d.ts +0 -1
  147. package/dist/env.test.d.ts +0 -1
  148. package/dist/helpers/atomicFile.test.d.ts +0 -1
  149. package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
  150. package/dist/helpers/buildServerInfo.test.d.ts +0 -1
  151. package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
  152. package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
  153. package/dist/helpers/cache/keys.test.d.ts +0 -1
  154. package/dist/helpers/compress.test.d.ts +0 -1
  155. package/dist/helpers/hydrationPayload.test.d.ts +0 -1
  156. package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
  157. package/dist/helpers/onAbort.test.d.ts +0 -1
  158. package/dist/helpers/outboundGuard.test.d.ts +0 -1
  159. package/dist/helpers/reportReactBuild.test.d.ts +0 -1
  160. package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
  161. package/dist/helpers/serverLog.test.d.ts +0 -1
  162. package/dist/hosts/authoringHost/index.test.d.ts +0 -1
  163. package/dist/hosts/project/serveProject.test.d.ts +0 -1
  164. package/dist/layers.test.d.ts +0 -1
  165. package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
  166. package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
  167. package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
  168. package/dist/modules/actions/jobs/later.test.d.ts +0 -1
  169. package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
  170. package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
  171. package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
  172. package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
  173. package/dist/modules/actions/moduleFor.test.d.ts +0 -1
  174. package/dist/modules/actions/runtime/check.test.d.ts +0 -1
  175. package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
  176. package/dist/modules/actions/runtime/email.test.d.ts +0 -1
  177. package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
  178. package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
  179. package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
  180. package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
  181. package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
  182. package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
  183. package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
  184. package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
  185. package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
  186. package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
  187. package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
  188. package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
  189. package/dist/modules/actions/tasks/db.test.d.ts +0 -1
  190. package/dist/modules/actions/tasks/email.test.d.ts +0 -1
  191. package/dist/modules/actions/tasks/http.test.d.ts +0 -1
  192. package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
  193. package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
  194. package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
  195. package/dist/modules/connectors/engine.test.d.ts +0 -1
  196. package/dist/modules/connectors/projection.test.d.ts +0 -1
  197. package/dist/modules/connectors/resolver.test.d.ts +0 -1
  198. package/dist/modules/functions/build.test.d.ts +0 -1
  199. package/dist/modules/functions/load.test.d.ts +0 -1
  200. package/dist/modules/functions/local.test.d.ts +0 -1
  201. package/dist/modules/functions/manifest.test.d.ts +0 -1
  202. package/dist/modules/functions/native.test.d.ts +0 -1
  203. package/dist/modules/functions/oauth.test.d.ts +0 -1
  204. package/dist/modules/functions/plugins.test.d.ts +0 -1
  205. package/dist/modules/functions/routes.test.d.ts +0 -1
  206. package/dist/modules/functions/runner/remote.test.d.ts +0 -1
  207. package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
  208. package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
  209. package/dist/modules/images/imageProxy.test.d.ts +0 -1
  210. package/dist/modules/images/transform.test.d.ts +0 -1
  211. package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
  212. package/dist/modules/mysql/accounts.test.d.ts +0 -1
  213. package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
  214. package/dist/modules/mysql/schema.test.d.ts +0 -1
  215. package/dist/modules/mysql/store.integration.test.d.ts +0 -1
  216. package/dist/modules/realtime/realtime.test.d.ts +0 -1
  217. package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
  218. package/dist/modules/realtime/retained.test.d.ts +0 -1
  219. package/dist/modules/realtime/socket.test.d.ts +0 -1
  220. package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
  221. package/dist/modules/rsc/handler.test.d.ts +0 -1
  222. package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
  223. package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
  224. package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
  225. package/dist/modules/runtime/entry.test.d.ts +0 -1
  226. package/dist/modules/runtime/inside.test.d.ts +0 -1
  227. package/dist/modules/runtime/ownServer.test.d.ts +0 -1
  228. package/dist/modules/runtime/runtime.test.d.ts +0 -1
  229. package/dist/modules/sqlite/kv.test.d.ts +0 -1
  230. package/dist/modules/ssr/draftSession.test.d.ts +0 -1
  231. package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
  232. package/dist/modules/ssr/metering.test.d.ts +0 -1
  233. package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
  234. package/dist/modules/ssr/redirect.test.d.ts +0 -1
  235. package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
  236. package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
  237. package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
  238. package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
  239. package/dist/modules/ssr/template.test.d.ts +0 -1
  240. package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
  241. package/dist/modules/ssr/vendor.test.d.ts +0 -1
  242. package/dist/plugins/compile.test.d.ts +0 -1
  243. package/dist/plugins/copy.test.d.ts +0 -1
  244. package/dist/plugins/manager.test.d.ts +0 -1
  245. package/dist/plugins/validate.test.d.ts +0 -1
@@ -1,5 +1,6 @@
1
1
  import { ActionRefusal } from "../actions/runtime/errors.js";
2
2
  import { fetchOutbound } from "../../helpers/outboundGuard.js";
3
+ import { OWN_AUTHORIZE_PARAMS } from "./manifest.js";
3
4
  import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
4
5
  import { isRecord } from "@plitzi/sdk-shared/helpers";
5
6
  import { createHash, randomBytes } from "node:crypto";
@@ -12,7 +13,8 @@ import { createHash, randomBytes } from "node:crypto";
12
13
  * exchanges the code with the app's id and secret (a credential of the space's, resolved here) and keeps the tokens
13
14
  * sealed under the connection and its owner; `fetch` writes the access token into a request, renewing it first when it
14
15
  * is about to lapse and once more on a 401. Sealed with the space's own key, which no signature of `ctx.sign` reaches:
15
- * the code reads only ciphertext, even with `ctx.kv`.
16
+ * the code reads only ciphertext, even with `ctx.kv`. The one way out is `token`, for a connection that declares
17
+ * `exposeToken`: the access token, for an SDK in the page — the refresh token never leaves.
16
18
  */
17
19
  /** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
18
20
  var OAUTH_CALLBACK_PATH = "/oauth/callback";
@@ -25,6 +27,8 @@ var OWNER = /^[\w:.@-]{1,128}$/;
25
27
  var KEY_PREFIX = "plitzi:oauth";
26
28
  var stateKey = (state) => `${KEY_PREFIX}:state:${state}`;
27
29
  var tokenKey = (connection, owner) => `${KEY_PREFIX}:token:${connection}:${owner}`;
30
+ var refused = (message, code) => new ActionRefusal(message, { code });
31
+ var notConnected = (connection) => refused(`Not connected to "${connection}": ctx.oauth.connect first`, "oauth-not-connected");
28
32
  var discovered = /* @__PURE__ */ new Map();
29
33
  var stringField = (record, key) => typeof record[key] === "string" ? record[key] : void 0;
30
34
  /** The connection's endpoints: written out, or read from its issuer's OpenID metadata — what is written wins. */
@@ -88,7 +92,7 @@ var clientOf = async (run, connection, spec) => {
88
92
  };
89
93
  };
90
94
  /** A request to the token endpoint: the grant, and the app's proof of who it is where the provider wants it. */
91
- var tokenRequest = async (run, connection, spec, url, grant) => {
95
+ var tokenRequest = async (run, connection, spec, url, grant, signal = run.signal) => {
92
96
  const client = await clientOf(run, connection, spec);
93
97
  const form = new URLSearchParams(grant);
94
98
  const headers = {
@@ -104,7 +108,7 @@ var tokenRequest = async (run, connection, spec, url, grant) => {
104
108
  method: "POST",
105
109
  headers,
106
110
  body: form.toString(),
107
- signal: run.signal
111
+ signal
108
112
  });
109
113
  const body = await answer.json().catch(() => void 0);
110
114
  const said = isRecord(body) ? body : {};
@@ -139,11 +143,11 @@ var readSealed = async (run, key, check) => {
139
143
  return check(parsed) ? parsed : void 0;
140
144
  };
141
145
  var isTokens = (value) => isRecord(value) && typeof value.access === "string" && typeof value.type === "string";
142
- var isPending = (value) => isRecord(value) && typeof value.connection === "string" && isRecord(value.spec) && typeof value.owner === "string" && typeof value.returnTo === "string" && typeof value.verifier === "string" && typeof value.redirectUri === "string";
146
+ var isPending = (value) => isRecord(value) && typeof value.connection === "string" && isRecord(value.spec) && typeof value.owner === "string" && typeof value.origin === "string" && typeof value.returnTo === "string" && typeof value.verifier === "string" && typeof value.redirectUri === "string";
143
147
  /** Whose the connection is: the code's own key, or the signed-in visitor — and none is refused, saying which to name. */
144
148
  var ownerOf = (run, connection, options) => {
145
149
  const owner = options?.owner ?? (run.user ? `user:${String(run.user.id)}` : void 0);
146
- if (!owner) throw new ActionRefusal(`OAuth connection "${connection}" is somebody's: sign the visitor in, or name its owner ({ owner: 'space' }, a key of your own)`);
150
+ if (!owner) throw refused(`OAuth connection "${connection}" is somebody's: sign the visitor in, or name its owner ({ owner: 'space' }, a key of your own)`, "oauth-no-owner");
147
151
  if (!OWNER.test(owner)) throw new Error(`An OAuth owner is letters, digits and ":._@-", up to 128 — not "${owner}"`);
148
152
  return owner;
149
153
  };
@@ -152,10 +156,21 @@ var pathOf = (returnTo) => {
152
156
  if (!returnTo.startsWith("/") || returnTo.startsWith("//") || returnTo.includes("\\")) throw new Error(`returnTo is a path of the space ("/settings"), not "${returnTo}"`);
153
157
  return returnTo;
154
158
  };
155
- var withQuery = (path, params) => {
156
- const url = new URL(path, "http://space");
159
+ /** `returnTo` on the origin the visitor started from, told how the consent went. */
160
+ var backTo = (origin, path, params) => {
161
+ const url = new URL(path, origin);
157
162
  Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
158
- return `${url.pathname}${url.search}${url.hash}`;
163
+ return url.href;
164
+ };
165
+ /** What one consent adds to the connection's `authorizeParams` (`prompt: 'select_account'`): strings, none the platform's. */
166
+ var authorizeParamsOf = (connection, params) => {
167
+ if (params === void 0) return {};
168
+ if (!isRecord(params)) throw new Error(`OAuth connection "${connection}": authorizeParams is an object of strings`);
169
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => {
170
+ if (OWN_AUTHORIZE_PARAMS.has(key)) throw new Error(`OAuth connection "${connection}": authorizeParams.${key} is the platform's to write`);
171
+ if (typeof value !== "string") throw new Error(`OAuth connection "${connection}": authorizeParams.${key} is a string`);
172
+ return [key, value];
173
+ }));
159
174
  };
160
175
  /**
161
176
  * `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
@@ -172,7 +187,7 @@ var oauthFor = (run, connections, allowed) => {
172
187
  };
173
188
  const save = (connection, owner, tokens) => run.kv.set(tokenKey(connection, owner), sealed(run).seal(JSON.stringify(tokens)));
174
189
  /** The connection's tokens, renewed first when they are about to lapse (or `force`d, after a 401). */
175
- const tokensOf = async (connection, owner, force = false) => {
190
+ const tokensOf = async (connection, owner, { force = false, signal = run.signal } = {}) => {
176
191
  const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
177
192
  if (!tokens) return;
178
193
  if (!(tokens.expiresAt !== void 0 && tokens.expiresAt - RENEW_BEFORE_MS <= Date.now() || force) || !tokens.refresh) return tokens;
@@ -181,7 +196,7 @@ var oauthFor = (run, connections, allowed) => {
181
196
  const renewed = tokensFrom(await tokenRequest(run, connection, spec, token, {
182
197
  grant_type: "refresh_token",
183
198
  refresh_token: tokens.refresh
184
- }), tokens);
199
+ }, signal), tokens);
185
200
  await save(connection, owner, renewed);
186
201
  return renewed;
187
202
  };
@@ -191,15 +206,17 @@ var oauthFor = (run, connections, allowed) => {
191
206
  const owner = ownerOf(run, connection, options);
192
207
  const returnTo = pathOf(options.returnTo);
193
208
  if (!run.origin) throw new Error(`OAuth connection "${connection}" is made from a visitor's request: this run has none to return to`);
209
+ const once = authorizeParamsOf(connection, options.authorizeParams);
194
210
  const { authorize } = await endpointsOf(run, connection, spec);
195
211
  const client = await clientOf(run, connection, spec);
196
212
  const verifier = randomBytes(32).toString("base64url");
197
213
  const state = randomBytes(24).toString("base64url");
198
- const redirectUri = `${run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
214
+ const redirectUri = `${run.oauthCallbackOrigin ?? run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
199
215
  const pending = {
200
216
  connection,
201
217
  spec,
202
218
  owner,
219
+ origin: run.origin,
203
220
  returnTo,
204
221
  verifier,
205
222
  redirectUri
@@ -208,6 +225,7 @@ var oauthFor = (run, connections, allowed) => {
208
225
  const url = new URL(authorize);
209
226
  const params = {
210
227
  ...spec.authorizeParams,
228
+ ...once,
211
229
  response_type: "code",
212
230
  client_id: client.id,
213
231
  redirect_uri: redirectUri,
@@ -233,6 +251,7 @@ var oauthFor = (run, connections, allowed) => {
233
251
  const owner = ownerOf(run, connection, init);
234
252
  const url = new URL(typeof input === "string" ? input : input.href);
235
253
  allowed(url);
254
+ const signal = init.signal ? AbortSignal.any([run.signal, init.signal]) : run.signal;
236
255
  const send = (tokens) => fetchOutbound(run.fetch, url, {
237
256
  method: init.method ?? "GET",
238
257
  headers: {
@@ -240,13 +259,16 @@ var oauthFor = (run, connections, allowed) => {
240
259
  authorization: `${/^bearer$/i.test(tokens.type) ? "Bearer" : tokens.type} ${tokens.access}`
241
260
  },
242
261
  body: init.body,
243
- signal: run.signal
262
+ signal
244
263
  });
245
- const tokens = await tokensOf(connection, owner);
246
- if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
264
+ const tokens = await tokensOf(connection, owner, { signal });
265
+ if (!tokens) throw notConnected(connection);
247
266
  const answer = await send(tokens);
248
267
  if (answer.status !== 401 || !tokens.refresh) return answer;
249
- const renewed = await tokensOf(connection, owner, true);
268
+ const renewed = await tokensOf(connection, owner, {
269
+ force: true,
270
+ signal
271
+ });
250
272
  return renewed ? send(renewed) : answer;
251
273
  },
252
274
  disconnect: async (connection, options) => {
@@ -258,6 +280,17 @@ var oauthFor = (run, connections, allowed) => {
258
280
  if (revoke) await tokenRequest(run, connection, spec, revoke, { token: tokens.refresh ?? tokens.access }).catch(() => void 0);
259
281
  await run.kv.delete(tokenKey(connection, owner));
260
282
  return true;
283
+ },
284
+ token: async (connection, options) => {
285
+ if (!specOf(connection).exposeToken) throw new Error(`OAuth connection "${connection}" keeps its token on the server: declare exposeToken: true on it for the code to read it, or reach its API with ctx.oauth.fetch`);
286
+ const tokens = await tokensOf(connection, ownerOf(run, connection, options));
287
+ if (!tokens) throw notConnected(connection);
288
+ return {
289
+ token: tokens.access,
290
+ type: tokens.type,
291
+ ...tokens.expiresAt ? { expiresAt: tokens.expiresAt } : {},
292
+ ...tokens.scopes ? { scopes: tokens.scopes } : {}
293
+ };
261
294
  }
262
295
  };
263
296
  };
@@ -268,7 +301,8 @@ var noOAuth = (why) => {
268
301
  connect: refused,
269
302
  status: refused,
270
303
  fetch: refused,
271
- disconnect: refused
304
+ disconnect: refused,
305
+ token: refused
272
306
  };
273
307
  };
274
308
  /**
@@ -286,13 +320,13 @@ var oauthCallback = async (run, query) => {
286
320
  });
287
321
  const back = (params) => new Response(null, {
288
322
  status: 303,
289
- headers: { location: withQuery(pending.returnTo, {
323
+ headers: { location: backTo(pending.origin, pending.returnTo, {
290
324
  oauth: pending.connection,
291
325
  ...params
292
326
  }) }
293
327
  });
294
- const refused = query.get("error");
295
- if (refused) return back({ oauth_error: refused });
328
+ const denied = query.get("error");
329
+ if (denied) return back({ oauth_error: denied });
296
330
  const code = query.get("code");
297
331
  if (!code) return back({ oauth_error: "no_code" });
298
332
  try {
@@ -55,13 +55,43 @@ export type WireResponse = {
55
55
  headers: WireHeaders;
56
56
  body: WireBody | null;
57
57
  };
58
+ /**
59
+ * A route's answer as it is written rather than once it is done — what a space's runtime answers, so a route there
60
+ * streams as an endpoint does, with the platform's `ctx` all the same: its head at once, its body as the code writes it.
61
+ * Never JSON: it lives in the process that holds the run, its body fed by the runner's `chunk` messages.
62
+ */
63
+ export type StreamedRouteAnswer = {
64
+ streamed: true;
65
+ status: number;
66
+ statusText: string;
67
+ headers: WireHeaders;
68
+ body: ReadableStream<Uint8Array>;
69
+ };
70
+ export declare const isStreamedRouteAnswer: (value: unknown) => value is StreamedRouteAnswer;
58
71
  /** Who and what an invocation is for: the facts a {@link FunctionContext} carries, sent with it rather than asked for. */
59
72
  export type FunctionInvocationContext = Pick<FunctionContext, 'spaceId' | 'environment' | 'runId' | 'trigger' | 'callerId' | 'user'>;
73
+ /** The slice of a job an invocation runs: which job, what it saved so far, and which attempt this is. */
74
+ export type FunctionJobSlice = {
75
+ id: string;
76
+ state?: unknown;
77
+ attempt: number;
78
+ };
60
79
  export type FunctionInvocation = {
61
80
  kind: 'task';
62
81
  name: string;
63
82
  params: Record<string, unknown>;
64
83
  context: FunctionInvocationContext;
84
+ } | {
85
+ kind: 'job';
86
+ name: string;
87
+ input: Record<string, unknown>;
88
+ job: FunctionJobSlice;
89
+ context: FunctionInvocationContext;
90
+ /**
91
+ * How long the code gets to save and return once the slice is asked to end (`signal` aborting with why: the
92
+ * `FunctionJobStop`), before the runner cuts it.
93
+ */
94
+ graceMs: number;
65
95
  } | {
66
96
  kind: 'route';
67
97
  key: string;
@@ -69,9 +99,14 @@ export type FunctionInvocation = {
69
99
  request: WireRequest;
70
100
  context: FunctionInvocationContext;
71
101
  };
102
+ /** A request's init as the wire carries it: what the code wrote but its `signal`, which never crosses (`request`). */
103
+ export type WireFetchInit = Omit<FunctionFetchInit, 'signal'>;
72
104
  /**
73
105
  * One call back from the code to the platform: a {@link FunctionContext} method, by name, with its arguments. The
74
106
  * platform answers it with the run's own context — scoped to the space and the run before anything is done.
107
+ *
108
+ * A request the code may cut short (its init had a `signal`) carries `request`, the code's own number for it, and the
109
+ * code's `abort` names that number when the signal fires: a signal is the code's object, and does not cross.
75
110
  */
76
111
  export type FunctionCall = {
77
112
  op: 'kv';
@@ -80,7 +115,11 @@ export type FunctionCall = {
80
115
  } | {
81
116
  op: 'fetch';
82
117
  url: string;
83
- init: FunctionFetchInit;
118
+ init: WireFetchInit;
119
+ request?: number;
120
+ } | {
121
+ op: 'abort';
122
+ request: number;
84
123
  } | {
85
124
  op: 'publish';
86
125
  topic: string;
@@ -119,10 +158,11 @@ export type FunctionCall = {
119
158
  method: 'connect';
120
159
  connection: string;
121
160
  returnTo: string;
161
+ authorizeParams?: Record<string, string>;
122
162
  owner?: string;
123
163
  } | {
124
164
  op: 'oauth';
125
- method: 'status' | 'disconnect';
165
+ method: 'status' | 'disconnect' | 'token';
126
166
  connection: string;
127
167
  owner?: string;
128
168
  } | {
@@ -130,8 +170,32 @@ export type FunctionCall = {
130
170
  method: 'fetch';
131
171
  connection: string;
132
172
  url: string;
133
- init: Omit<FunctionFetchInit, 'credential'>;
173
+ init: Omit<WireFetchInit, 'credential'>;
134
174
  owner?: string;
175
+ request?: number;
176
+ }
177
+ /** `ctx.jobs`: the space's jobs, started and stopped by its code. */
178
+ | {
179
+ op: 'jobs';
180
+ method: 'start';
181
+ name: string;
182
+ input: Record<string, unknown>;
183
+ key?: string;
184
+ } | {
185
+ op: 'jobs';
186
+ method: 'get' | 'pause' | 'resume' | 'cancel';
187
+ id: string;
188
+ }
189
+ /** A job's `save` and `report`: what its slice keeps, and how far it is. */
190
+ | {
191
+ op: 'job';
192
+ method: 'save';
193
+ state: unknown;
194
+ } | {
195
+ op: 'job';
196
+ method: 'report';
197
+ fraction: number;
198
+ step?: string;
135
199
  }
136
200
  /** Each value as the guest could send it: JSON, with what JSON cannot say already said as text. */
137
201
  | {
@@ -141,14 +205,27 @@ export type FunctionCall = {
141
205
  op: 'emit';
142
206
  chunk: unknown;
143
207
  };
144
- /** How a call or an invocation ended: its value, or why not — never a thrown object crossing the boundary. */
208
+ /**
209
+ * How a call or an invocation ended: its value, or why not — never a thrown object crossing the boundary. A refusal
210
+ * (`refused`, with its `code`) stays one on the other side: the code that made the call catches what the platform threw.
211
+ */
145
212
  export type FunctionAnswer = {
146
213
  ok: true;
147
214
  value: unknown;
148
215
  } | {
149
216
  ok: false;
150
217
  error: string;
218
+ refused?: true;
219
+ code?: string;
151
220
  };
221
+ /** What a call that threw answers across a boundary: its message, and whether — and as what — it was a refusal. */
222
+ export declare const failedAnswerOf: (error: unknown) => Extract<FunctionAnswer, {
223
+ ok: false;
224
+ }>;
225
+ /** …and that answer thrown again on the side that made the call: a refusal as a refusal, anything else as an error. */
226
+ export declare const errorOfAnswer: ({ error, refused, code }: Extract<FunctionAnswer, {
227
+ ok: false;
228
+ }>) => Error;
152
229
  /** Why the runner stopped an invocation, when it was not the code's own error. */
153
230
  export type FunctionStopReason = 'cpu' | 'wall' | 'memory' | 'output' | 'calls' | 'aborted';
154
231
  /** What the platform asks a runner for: every runner implements this, and nothing else of it is assumed. */
@@ -156,8 +233,9 @@ export type FunctionRunner = {
156
233
  /** Loads a bundle and answers what it declares — when the space's functions are saved, never on a run. */
157
234
  describe: (bundle: FunctionsBundle) => Promise<unknown>;
158
235
  /**
159
- * Runs one task or route of a bundle. Each call the code makes is handed to `answer`, whose result goes back to it;
160
- * `signal` aborting ends the invocation. Resolves with what the code returned, and rejects with a
236
+ * Runs one task, route or slice of a job of a bundle. Each call the code makes is handed to `answer`, whose result
237
+ * goes back to it; `signal` aborting ends the invocation — its `reason` handed to the code as the signal's, and a
238
+ * job's slice given its `graceMs` to save before it is cut. Resolves with what the code returned, and rejects with a
161
239
  * {@link FunctionFailure}.
162
240
  */
163
241
  invoke: (request: FunctionInvokeRequest) => Promise<unknown>;
@@ -221,12 +299,25 @@ export type RunnerRequestMessage = {
221
299
  type: 'answer';
222
300
  id: number;
223
301
  answer: FunctionAnswer;
224
- } | {
302
+ }
303
+ /** The invocation is asked to end — for a job's slice, with why (a `FunctionJobStop`). */
304
+ | {
225
305
  type: 'abort';
306
+ reason?: string;
226
307
  };
227
308
  export type RunnerResponseMessage = {
228
309
  type: 'needBundle';
229
310
  }
311
+ /** A route answering as it writes: its head, then each `chunk` of its body, then `done`. */
312
+ | {
313
+ type: 'head';
314
+ status: number;
315
+ statusText: string;
316
+ headers: WireHeaders;
317
+ } | {
318
+ type: 'chunk';
319
+ chunk: WireBody;
320
+ }
230
321
  /** As the code sent it: the platform reads it, trusting no runner to have. */
231
322
  | {
232
323
  type: 'call';
@@ -1,3 +1,4 @@
1
+ import { ActionRefusal, isActionRefusal, refusalCodeOf } from "../actions/runtime/errors.js";
1
2
  //#region src/modules/functions/protocol.ts
2
3
  /**
3
4
  * The messages between the platform and whatever runs a space's code — the one protocol every runner speaks, whether
@@ -5,6 +6,19 @@
5
6
  * platform that calls it.
6
7
  */
7
8
  var FUNCTIONS_PROTOCOL = 1;
9
+ var isStreamedRouteAnswer = (value) => typeof value === "object" && value !== null && "streamed" in value && value.streamed === true && "body" in value && value.body instanceof ReadableStream;
10
+ /** What a call that threw answers across a boundary: its message, and whether — and as what — it was a refusal. */
11
+ var failedAnswerOf = (error) => {
12
+ const code = refusalCodeOf(error);
13
+ return {
14
+ ok: false,
15
+ error: error instanceof Error ? error.message : String(error),
16
+ ...isActionRefusal(error) ? { refused: true } : {},
17
+ ...code === void 0 ? {} : { code }
18
+ };
19
+ };
20
+ /** …and that answer thrown again on the side that made the call: a refusal as a refusal, anything else as an error. */
21
+ var errorOfAnswer = ({ error, refused, code }) => refused ? new ActionRefusal(error, code === void 0 ? {} : { code }) : new Error(error);
8
22
  /** An invocation that did not answer, and why ({@link FunctionFailureReason}). */
9
23
  var FunctionFailure = class extends Error {
10
24
  reason;
@@ -15,4 +29,4 @@ var FunctionFailure = class extends Error {
15
29
  }
16
30
  };
17
31
  //#endregion
18
- export { FUNCTIONS_PROTOCOL, FunctionFailure };
32
+ export { FUNCTIONS_PROTOCOL, FunctionFailure, errorOfAnswer, failedAnswerOf, isStreamedRouteAnswer };
@@ -15,9 +15,17 @@ export type RouteVisit = {
15
15
  origin?: string;
16
16
  signal: AbortSignal;
17
17
  };
18
+ /**
19
+ * What a route answered, and whether it is written as it comes: a runtime's route and the deployment's own code may
20
+ * stream, and are passed on as they are written; a sandbox's is whole, and sent as one.
21
+ */
22
+ export type RouteAnswer = {
23
+ response: Response;
24
+ streamed: boolean;
25
+ };
18
26
  export type RouteHandler = {
19
27
  key: string;
20
- handle: (request: Request) => Promise<Response>;
28
+ handle: (request: Request) => Promise<RouteAnswer>;
21
29
  };
22
30
  /** The first of `keys` that answers the request, with its params — declared order, as a space reads them. */
23
31
  export declare const matchRoute: (keys: readonly string[], method: string, path: string) => {
@@ -1,15 +1,20 @@
1
1
  import { serverLog } from "../../helpers/serverLog.js";
2
2
  import { isActionRefusal } from "../actions/runtime/errors.js";
3
- import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
4
3
  import { pluginOfPath } from "./scope.js";
5
- import { functionContextFor } from "./context.js";
6
- import { functionLimitsFor } from "./config.js";
7
4
  import { parseRouteKey, reservedRouteProblem } from "./manifest.js";
5
+ import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
6
+ import { functionContextFor } from "./context.js";
8
7
  import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
9
- import { FunctionFailure } from "./protocol.js";
8
+ import { functionLimitsFor } from "./config.js";
9
+ import { FunctionFailure, isStreamedRouteAnswer } from "./protocol.js";
10
+ import { jobsManifestOf } from "./jobs.js";
10
11
  import { PLUGIN_ROUTES_SEGMENT } from "@plitzi/sdk-shared/actions";
11
12
  import { randomUUID } from "node:crypto";
12
13
  //#region src/modules/functions/routes.ts
14
+ var whole = (response) => ({
15
+ response,
16
+ streamed: false
17
+ });
13
18
  /** A route key's params from a path it answers, or nothing when it does not answer it. */
14
19
  var matchKey = (key, method, path) => {
15
20
  const segments = path.replace(/^\/+/, "").split("/");
@@ -80,7 +85,8 @@ var routesOf = (definition) => Object.entries(definition.routes ?? {}).map(([key
80
85
  key,
81
86
  handler,
82
87
  hosts: definition.allow?.hosts ?? [],
83
- ...definition.oauth ? { oauth: definition.oauth } : {}
88
+ ...definition.oauth ? { oauth: definition.oauth } : {},
89
+ jobs: jobsManifestOf(definition)
84
90
  }));
85
91
  /**
86
92
  * The route a request reaches, if one does: under `/plugins/<type>/`, that plugin's — this server's own, then the one
@@ -102,7 +108,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
102
108
  ...visit.at ? { at: visit.at } : {},
103
109
  ...visit.origin ? { origin: visit.origin } : {}
104
110
  }, visit.signal, [`route:${key}`]);
105
- const contextOf = (visit, key, hosts, scope, oauth) => {
111
+ const contextOf = (visit, key, hosts, scope, oauth, jobs) => {
106
112
  const ctx = runOf(visit, key);
107
113
  return {
108
114
  ...functionContextFor({
@@ -110,7 +116,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
110
116
  log: (line) => {
111
117
  serverLog.info("Functions", `route ${key} of space ${String(visit.spaceId)}: ${line}`);
112
118
  }
113
- }, hosts, scope, oauth),
119
+ }, hosts, scope, oauth, jobs),
114
120
  trigger: "route"
115
121
  };
116
122
  };
@@ -124,12 +130,15 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
124
130
  key: match.key,
125
131
  handle: async (request) => {
126
132
  try {
127
- return withoutCookies(await handler(withoutCredentials(request), {
128
- ...contextOf(visit, match.key, route.hosts, scope, route.oauth),
129
- params: match.params
130
- }));
133
+ return {
134
+ response: withoutCookies(await handler(withoutCredentials(request), {
135
+ ...contextOf(visit, match.key, route.hosts, scope, route.oauth, route.jobs),
136
+ params: match.params
137
+ })),
138
+ streamed: true
139
+ };
131
140
  } catch (error) {
132
- return failed(visit, match.key, error);
141
+ return whole(failed(visit, match.key, error));
133
142
  }
134
143
  }
135
144
  };
@@ -144,10 +153,19 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
144
153
  key: match.key,
145
154
  handle: async (request) => {
146
155
  const refusal = await config.admit?.(visit.spaceId);
147
- if (refusal) return Response.json({ error: refusal }, { status: 429 });
148
- const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth);
156
+ if (refusal) return whole(Response.json({ error: refusal }, { status: 429 }));
157
+ const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth, functions.manifest.jobs);
149
158
  let ok = false;
150
159
  let spent;
160
+ let streaming = false;
161
+ const meter = (usage, done) => {
162
+ config.onUsage?.({
163
+ spaceId: visit.spaceId,
164
+ task: usageName,
165
+ ok: done,
166
+ usage
167
+ });
168
+ };
151
169
  try {
152
170
  const value = await runner.invoke({
153
171
  bundle: functions.bundle,
@@ -169,20 +187,27 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
169
187
  answer: (call) => answerCall(fnCtx, readCall(call)),
170
188
  signal: visit.signal,
171
189
  onUsage: (usage) => {
172
- spent = usage;
190
+ if (streaming) meter(usage, true);
191
+ else spent = usage;
173
192
  }
174
193
  });
175
194
  ok = true;
176
- return withoutCookies(responseOf(wireResponseFrom(value)));
195
+ if (isStreamedRouteAnswer(value)) {
196
+ streaming = true;
197
+ return {
198
+ response: withoutCookies(new Response(value.body, {
199
+ status: value.status,
200
+ statusText: value.statusText,
201
+ headers: value.headers
202
+ })),
203
+ streamed: true
204
+ };
205
+ }
206
+ return whole(withoutCookies(responseOf(wireResponseFrom(value))));
177
207
  } catch (error) {
178
- return failed(visit, match.key, error);
208
+ return whole(failed(visit, match.key, error));
179
209
  } finally {
180
- if (spent) config.onUsage?.({
181
- spaceId: visit.spaceId,
182
- task: usageName,
183
- ok,
184
- usage: spent
185
- });
210
+ if (spent) meter(spent, ok);
186
211
  }
187
212
  }
188
213
  };
@@ -202,9 +227,9 @@ routeFor: async (visit, method, path) => {
202
227
  handle: async (request) => {
203
228
  const run = runOf(visit, `GET ${OAUTH_CALLBACK_PATH}`);
204
229
  try {
205
- return await oauthCallback(run, new URL(request.url).searchParams);
230
+ return whole(await oauthCallback(run, new URL(request.url).searchParams));
206
231
  } catch (error) {
207
- return failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error);
232
+ return whole(failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error));
208
233
  }
209
234
  }
210
235
  };
@@ -1,5 +1,4 @@
1
1
  import { RunnerRequestMessage, RunnerResponseMessage } from '../protocol';
2
2
  /** What the platform sent the runner, or nothing when it is not one of the protocol's messages. */
3
3
  export declare const readRequestMessage: (data: string) => RunnerRequestMessage | undefined;
4
- /** What the runner sent the platform, or nothing when it is not one of the protocol's messages. */
5
4
  export declare const readResponseMessage: (data: string) => RunnerResponseMessage | undefined;
@@ -40,7 +40,7 @@ var limitsOf = (value) => {
40
40
  * what is checked here is what the runner itself acts on.
41
41
  */
42
42
  var invocationOf = (value) => {
43
- if (!isRecord(value) || !isRecord(value.context) || value.kind !== "task" && value.kind !== "route") return;
43
+ if (!isRecord(value) || !isRecord(value.context) || value.kind !== "task" && value.kind !== "route" && value.kind !== "job") return;
44
44
  const { context } = value;
45
45
  if (typeof context.spaceId !== "number" || typeof context.runId !== "string" || typeof context.trigger !== "string" || typeof context.callerId !== "string" || !isEnvironment(context.environment)) return;
46
46
  const facts = {
@@ -68,6 +68,22 @@ var invocationOf = (value) => {
68
68
  params: value.params,
69
69
  context: withUser
70
70
  } : void 0;
71
+ if (value.kind === "job") {
72
+ const job = isRecord(value.job) ? value.job : void 0;
73
+ const graceMs = limitOf(value.graceMs);
74
+ return typeof value.name === "string" && isRecord(value.input) && job && typeof job.id === "string" && typeof job.attempt === "number" && graceMs !== void 0 ? {
75
+ kind: "job",
76
+ name: value.name,
77
+ input: value.input,
78
+ job: {
79
+ id: job.id,
80
+ attempt: job.attempt,
81
+ ...job.state === void 0 ? {} : { state: job.state }
82
+ },
83
+ context: withUser,
84
+ graceMs
85
+ } : void 0;
86
+ }
71
87
  const request = isRecord(value.request) ? value.request : void 0;
72
88
  if (!request || typeof value.key !== "string" || typeof request.method !== "string" || typeof request.url !== "string") return;
73
89
  const params = isRecord(value.params) ? value.params : {};
@@ -91,10 +107,13 @@ var answerOf = (value) => {
91
107
  ok: true,
92
108
  value: value.value
93
109
  };
94
- return value.ok === false && typeof value.error === "string" ? {
110
+ if (value.ok !== false || typeof value.error !== "string") return;
111
+ return {
95
112
  ok: false,
96
- error: value.error
97
- } : void 0;
113
+ error: value.error,
114
+ ...value.refused === true ? { refused: true } : {},
115
+ ...typeof value.code === "string" ? { code: value.code } : {}
116
+ };
98
117
  };
99
118
  /** What the platform sent the runner, or nothing when it is not one of the protocol's messages. */
100
119
  var readRequestMessage = (data) => {
@@ -134,7 +153,10 @@ var readRequestMessage = (data) => {
134
153
  answer
135
154
  } : void 0;
136
155
  }
137
- case "abort": return { type: "abort" };
156
+ case "abort": return typeof message.reason === "string" ? {
157
+ type: "abort",
158
+ reason: message.reason
159
+ } : { type: "abort" };
138
160
  default: return;
139
161
  }
140
162
  };
@@ -161,10 +183,29 @@ var usageOf = (value) => {
161
183
  } } : {};
162
184
  };
163
185
  /** What the runner sent the platform, or nothing when it is not one of the protocol's messages. */
186
+ /** Headers as the wire carries them: name and value pairs, the rest left out. */
187
+ var headersOf = (value) => Array.isArray(value) ? value.flatMap((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string" ? [[pair[0], pair[1]]] : []) : [];
164
188
  var readResponseMessage = (data) => {
165
189
  const message = parse(data);
166
190
  switch (message?.type) {
167
191
  case "needBundle": return { type: "needBundle" };
192
+ case "head": return typeof message.status === "number" ? {
193
+ type: "head",
194
+ status: message.status,
195
+ statusText: typeof message.statusText === "string" ? message.statusText : "",
196
+ headers: headersOf(message.headers)
197
+ } : void 0;
198
+ case "chunk": {
199
+ const chunk = isRecord(message.chunk) ? message.chunk : void 0;
200
+ if (typeof chunk?.base64 === "string") return {
201
+ type: "chunk",
202
+ chunk: { base64: chunk.base64 }
203
+ };
204
+ return typeof chunk?.text === "string" ? {
205
+ type: "chunk",
206
+ chunk: { text: chunk.text }
207
+ } : void 0;
208
+ }
168
209
  case "call": return typeof message.id === "number" ? {
169
210
  type: "call",
170
211
  id: message.id,