@plitzi/sdk-server 0.38.24 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/CHANGELOG.md +152 -1
  2. package/README.md +55 -9
  3. package/dist/actions.d.ts +4 -1
  4. package/dist/actions.js +3 -2
  5. package/dist/auth.d.ts +2 -2
  6. package/dist/auth.js +5 -4
  7. package/dist/core/auth/api/accounts.d.ts +11 -0
  8. package/dist/core/auth/api/accounts.js +175 -0
  9. package/dist/core/auth/api/admin.d.ts +41 -0
  10. package/dist/core/auth/api/admin.js +146 -0
  11. package/dist/core/auth/api/context.d.ts +119 -0
  12. package/dist/core/auth/api/context.js +262 -0
  13. package/dist/core/auth/api/factors.d.ts +31 -0
  14. package/dist/core/auth/api/factors.js +209 -0
  15. package/dist/core/auth/api/index.d.ts +94 -0
  16. package/dist/core/auth/api/index.js +43 -0
  17. package/dist/core/auth/api/profile.d.ts +43 -0
  18. package/dist/core/auth/api/profile.js +243 -0
  19. package/dist/core/auth/api/session.d.ts +62 -0
  20. package/dist/core/auth/api/session.js +312 -0
  21. package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
  22. package/dist/core/auth/api/values.d.ts +67 -0
  23. package/dist/core/auth/api/values.js +90 -0
  24. package/dist/core/auth/createAuth.d.ts +49 -39
  25. package/dist/core/auth/createAuth.js +21 -1
  26. package/dist/core/auth/oauth/client.d.ts +2 -2
  27. package/dist/core/auth/oauth/client.js +6 -1
  28. package/dist/core/auth/oauth/index.d.ts +30 -7
  29. package/dist/core/auth/oauth/index.js +33 -14
  30. package/dist/core/auth/oauth/providers/github.js +1 -1
  31. package/dist/core/auth/oauth/providers/google.js +1 -1
  32. package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
  33. package/dist/core/auth/oauth/providers/oidc.js +197 -0
  34. package/dist/core/auth/oauth/state.d.ts +2 -0
  35. package/dist/core/auth/oauth/state.js +2 -0
  36. package/dist/core/auth/oauth/types.d.ts +21 -3
  37. package/dist/core/auth/oauth/types.js +4 -1
  38. package/dist/core/auth/routes.js +1 -1
  39. package/dist/core/auth/tokens.d.ts +3 -1
  40. package/dist/core/auth/tokens.js +2 -1
  41. package/dist/core/configSeam.d.ts +0 -4
  42. package/dist/core/configSeam.js +12 -1
  43. package/dist/core/createServer.js +16 -4
  44. package/dist/core/freePort.d.ts +10 -0
  45. package/dist/core/freePort.js +39 -1
  46. package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
  47. package/dist/core/handlers/socialRouteHandlers.js +46 -12
  48. package/dist/core/health.d.ts +1 -0
  49. package/dist/core/health.js +2 -1
  50. package/dist/core/http/stages/authRoutes.d.ts +6 -0
  51. package/dist/core/http/stages/authRoutes.js +42 -1
  52. package/dist/core/http/stages/images.js +5 -3
  53. package/dist/core/http/stages/livePages.js +1 -1
  54. package/dist/core/server/fleet/relay.js +9 -1
  55. package/dist/core/server/fleet/stores.d.ts +7 -0
  56. package/dist/core/server/fleet/stores.js +15 -2
  57. package/dist/core/server/pageServer.js +5 -1
  58. package/dist/core/services/realtime.js +4 -2
  59. package/dist/core/services/registry.js +7 -1
  60. package/dist/core/services/robotsTxt.d.ts +16 -0
  61. package/dist/core/services/robotsTxt.js +50 -0
  62. package/dist/core/services/servedSpace.d.ts +8 -0
  63. package/dist/core/services/servedSpace.js +16 -0
  64. package/dist/core/services/sitemapXml.d.ts +7 -0
  65. package/dist/core/services/sitemapXml.js +37 -0
  66. package/dist/functions-api.d.ts +69 -2
  67. package/dist/helpers/fileStore.d.ts +60 -0
  68. package/dist/helpers/fileStore.js +127 -0
  69. package/dist/helpers/outboundGuard.d.ts +32 -3
  70. package/dist/helpers/outboundGuard.js +50 -5
  71. package/dist/hosts/project/agentRuns.d.ts +24 -0
  72. package/dist/hosts/project/agentRuns.js +107 -0
  73. package/dist/hosts/project/laterAsks.d.ts +41 -0
  74. package/dist/hosts/project/laterAsks.js +117 -0
  75. package/dist/hosts/project/plugins.js +11 -4
  76. package/dist/hosts/project/serveProject.d.ts +8 -1
  77. package/dist/hosts/project/serveProject.js +81 -24
  78. package/dist/hosts/project/spaceFailure.d.ts +4 -0
  79. package/dist/hosts/project/spaceFailure.js +10 -0
  80. package/dist/hosts/project/watchSpace.d.ts +5 -5
  81. package/dist/hosts/project/watchSpace.js +15 -6
  82. package/dist/index.js +2 -2
  83. package/dist/kernel.js +1 -1
  84. package/dist/modules/actions/connectorWrite.js +3 -1
  85. package/dist/modules/actions/index.js +1 -1
  86. package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
  87. package/dist/modules/actions/jobs/fileQueue.js +72 -0
  88. package/dist/modules/actions/jobs/index.js +3 -3
  89. package/dist/modules/actions/jobs/memoryQueue.js +6 -215
  90. package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
  91. package/dist/modules/actions/jobs/queueDocument.js +22 -0
  92. package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
  93. package/dist/modules/actions/jobs/queueRules.js +270 -0
  94. package/dist/modules/actions/moduleFor.js +2 -0
  95. package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
  96. package/dist/modules/actions/runtime/fileKv.js +12 -98
  97. package/dist/modules/actions/runtime/guards.d.ts +19 -1
  98. package/dist/modules/actions/runtime/guards.js +10 -1
  99. package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
  100. package/dist/modules/actions/runtime/kvChange.js +23 -1
  101. package/dist/modules/actions/runtime/kvList.d.ts +4 -0
  102. package/dist/modules/actions/runtime/kvList.js +5 -1
  103. package/dist/modules/actions/runtime/kvStore.js +15 -1
  104. package/dist/modules/actions/runtime/namespaceKv.js +2 -0
  105. package/dist/modules/actions/runtime/renderResolver.js +31 -5
  106. package/dist/modules/actions/runtime/runAction.js +16 -6
  107. package/dist/modules/actions/runtime/scope.js +11 -0
  108. package/dist/modules/actions/runtime/taskContext.js +11 -32
  109. package/dist/modules/actions/tasks/auth.js +2 -0
  110. package/dist/modules/actions/tasks/connector.js +6 -2
  111. package/dist/modules/actions/tasks/flow.js +5 -0
  112. package/dist/modules/actions/tasks/http.js +2 -1
  113. package/dist/modules/actions/tasks/kv.js +5 -0
  114. package/dist/modules/actions/tasks/list.js +11 -2
  115. package/dist/modules/actions/tasks/transform.js +2 -0
  116. package/dist/modules/actions/transport/callHandler.js +25 -4
  117. package/dist/modules/actions/types.d.ts +46 -1
  118. package/dist/modules/connectors/engine.d.ts +7 -2
  119. package/dist/modules/connectors/engine.js +4 -4
  120. package/dist/modules/connectors/resolver.d.ts +2 -1
  121. package/dist/modules/connectors/resolver.js +3 -2
  122. package/dist/modules/functions/build.d.ts +7 -2
  123. package/dist/modules/functions/build.js +90 -6
  124. package/dist/modules/functions/capabilities.js +16 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +39 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +35 -0
  129. package/dist/modules/functions/load.d.ts +1 -1
  130. package/dist/modules/functions/load.js +2 -2
  131. package/dist/modules/functions/manifest.js +7 -1
  132. package/dist/modules/functions/oauth.d.ts +1 -1
  133. package/dist/modules/functions/oauth.js +4 -4
  134. package/dist/modules/functions/protocol.d.ts +6 -0
  135. package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
  136. package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
  137. package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
  138. package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
  139. package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
  140. package/dist/modules/functions/sandbox/guest/events.js +143 -0
  141. package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
  142. package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
  143. package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
  144. package/dist/modules/functions/sandbox/guest/index.js +130 -0
  145. package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
  146. package/dist/modules/functions/sandbox/isolate.js +20 -6
  147. package/dist/modules/functions/space.js +2 -8
  148. package/dist/modules/images/imageProxy.d.ts +3 -2
  149. package/dist/modules/images/imageProxy.js +2 -2
  150. package/dist/modules/mongo/jobQueue.js +0 -19
  151. package/dist/modules/mysql/accounts.js +12 -5
  152. package/dist/modules/mysql/jobs/index.d.ts +1 -1
  153. package/dist/modules/mysql/jobs/schema.d.ts +0 -6
  154. package/dist/modules/mysql/jobs/schema.js +2 -46
  155. package/dist/modules/mysql/schema.js +26 -1
  156. package/dist/modules/mysql/sessions.js +2 -1
  157. package/dist/modules/realtime/handlers.d.ts +9 -4
  158. package/dist/modules/realtime/handlers.js +20 -3
  159. package/dist/modules/realtime/hub.d.ts +4 -2
  160. package/dist/modules/realtime/hub.js +36 -4
  161. package/dist/modules/realtime/index.d.ts +14 -0
  162. package/dist/modules/realtime/index.js +14 -1
  163. package/dist/modules/realtime/presence.d.ts +33 -0
  164. package/dist/modules/realtime/presence.js +56 -0
  165. package/dist/modules/realtime/socket.d.ts +3 -1
  166. package/dist/modules/realtime/socket.js +2 -2
  167. package/dist/modules/rsc/connectorRscData.d.ts +6 -1
  168. package/dist/modules/rsc/connectorRscData.js +27 -6
  169. package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
  170. package/dist/modules/rsc/externalQueryReader.js +43 -0
  171. package/dist/modules/rsc/handler.js +1 -1
  172. package/dist/modules/rsc/resolveRscData.d.ts +11 -1
  173. package/dist/modules/rsc/resolveRscData.js +86 -16
  174. package/dist/modules/runtime/inside.js +1 -1
  175. package/dist/modules/runtime/runner.js +2 -1
  176. package/dist/modules/sqlite/jobQueue.d.ts +35 -0
  177. package/dist/modules/sqlite/jobQueue.js +56 -0
  178. package/dist/modules/sqlite/kv.d.ts +1 -1
  179. package/dist/modules/sqlite/kv.js +2 -10
  180. package/dist/modules/sqlite/open.d.ts +3 -0
  181. package/dist/modules/sqlite/open.js +13 -0
  182. package/dist/modules/ssr/Component.d.ts +5 -1
  183. package/dist/modules/ssr/Component.js +3 -1
  184. package/dist/modules/ssr/applySSRResult.d.ts +8 -1
  185. package/dist/modules/ssr/applySSRResult.js +23 -3
  186. package/dist/modules/ssr/handler.js +30 -5
  187. package/dist/modules/ssr/prepareRender.js +27 -5
  188. package/dist/modules/ssr/preview.d.ts +2 -0
  189. package/dist/modules/ssr/preview.js +6 -3
  190. package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
  191. package/dist/modules/ssr/registerExternalPlugins.js +2 -2
  192. package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
  193. package/dist/modules/ssr/resolvePageSeo.js +13 -2
  194. package/dist/modules/ssr/streamBody.js +2 -2
  195. package/dist/modules/ssr/views/template.ejs +21 -17
  196. package/dist/mysql.d.ts +1 -1
  197. package/dist/mysql.js +2 -2
  198. package/dist/plugins/manager.d.ts +5 -0
  199. package/dist/plugins/manager.js +9 -0
  200. package/dist/sqlite.d.ts +8 -1
  201. package/dist/sqlite.js +3 -1
  202. package/package.json +5 -5
  203. package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
  204. package/skills/plitzi-authoring/SKILL.md +4 -2
  205. package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
  206. package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
  207. package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
  208. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
  209. package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
  210. package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
  211. package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
  212. package/skills/plitzi-authoring/reference/accessibility.md +7 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
  215. package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
  216. package/skills/plitzi-authoring/reference/components.md +4 -1
  217. package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
  218. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  219. package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
  220. package/skills/plitzi-authoring/reference/flows.md +20 -8
  221. package/skills/plitzi-authoring/reference/kept-state.md +8 -0
  222. package/skills/plitzi-authoring/reference/layouts.md +18 -2
  223. package/skills/plitzi-authoring/reference/lists.md +20 -4
  224. package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
  225. package/skills/plitzi-authoring/reference/plugins.md +13 -2
  226. package/skills/plitzi-authoring/reference/realtime.md +8 -5
  227. package/skills/plitzi-authoring/reference/structure.md +17 -1
  228. package/skills/plitzi-authoring/reference/templates.md +11 -3
  229. package/skills/plitzi-authoring/reference/testing.md +82 -5
  230. package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
  231. package/skills/plitzi-authoring/reference/validation.md +1 -1
  232. package/dist/core/auth/api.js +0 -1323
  233. package/dist/modules/functions/sandbox/guest.js +0 -662
@@ -0,0 +1,127 @@
1
+ import { serverLog } from "./serverLog.js";
2
+ import { writeFileAtomic } from "./atomicFile.js";
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ //#region src/helpers/fileStore.ts
6
+ var holderIn = (lock) => {
7
+ try {
8
+ const parsed = JSON.parse(fs.readFileSync(lock, "utf8"));
9
+ return typeof parsed === "object" && parsed !== null && "pid" in parsed && typeof parsed.pid === "number" ? {
10
+ pid: parsed.pid,
11
+ since: "since" in parsed && typeof parsed.since === "string" ? parsed.since : "?",
12
+ ..."owner" in parsed && typeof parsed.owner === "string" ? { owner: parsed.owner } : {},
13
+ ..."serves" in parsed && typeof parsed.serves === "string" ? { serves: parsed.serves } : {}
14
+ } : void 0;
15
+ } catch {
16
+ return;
17
+ }
18
+ };
19
+ /** Whether a process is still running: signal 0 asks without sending anything, and `EPERM` is one that is not ours. */
20
+ var running = (pid) => {
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ } catch (error) {
25
+ return error.code === "EPERM";
26
+ }
27
+ };
28
+ /**
29
+ * A file another running process holds: its message is the whole report — who holds it and how to stop it — said as it
30
+ * is when the server starts (`serveProject`). Thrown plain, it was a stack ending on its cause's `EEXIST`, and the agent
31
+ * reading the end of it found no word of what to do.
32
+ */
33
+ var FileInUseError = class extends Error {
34
+ /** The process that holds it: a server says where it answers, for the one refused to point there. */
35
+ holder;
36
+ constructor(message, holder, options) {
37
+ super(message, options);
38
+ this.name = "FileInUseError";
39
+ this.holder = holder;
40
+ }
41
+ };
42
+ /** The files this process holds, let go of together when it exits — however it does. */
43
+ var held = /* @__PURE__ */ new Set();
44
+ /** Lets go of a file this process holds. */
45
+ var letGo = (lock) => {
46
+ held.delete(lock);
47
+ if (holderIn(lock)?.pid === process.pid) fs.rmSync(lock, { force: true });
48
+ };
49
+ process.once("exit", () => held.forEach(letGo));
50
+ /**
51
+ * Takes the file for this process, or says who has it — `store` names the store in what is said (`createFileKv`).
52
+ *
53
+ * Two processes on one file each load it and then write their whole document over it: every change one makes, the
54
+ * other erases with its next write, and nothing anywhere says so — a second server started beside the first, a
55
+ * `--watch` left running after a restart. So a file has one holder: a second is refused, naming the first. A lock whose
56
+ * process is gone — killed, crashed — is taken over.
57
+ */
58
+ var holdFile = (file, { owner, serves }, store) => {
59
+ const lock = `${file}.lock`;
60
+ fs.mkdirSync(path.dirname(file), { recursive: true });
61
+ const mine = {
62
+ pid: process.pid,
63
+ since: (/* @__PURE__ */ new Date()).toISOString(),
64
+ ...owner ? { owner } : {},
65
+ ...serves ? { serves } : {}
66
+ };
67
+ for (let attempt = 0; attempt < 2; attempt += 1) try {
68
+ fs.writeFileSync(lock, JSON.stringify(mine), { flag: "wx" });
69
+ held.add(lock);
70
+ return lock;
71
+ } catch (error) {
72
+ if (error.code !== "EEXIST") throw error;
73
+ const holder = holderIn(lock);
74
+ if (holder && running(holder.pid)) throw new FileInUseError(`${store}: ${file} is in use by process ${String(holder.pid)}${holder.owner ? ` — ${holder.owner}` : ""}, since ${holder.since}. Two processes on one file write over each other's changes: stop that one first, or point \`file\` elsewhere.`, holder, { cause: error });
75
+ fs.rmSync(lock, { force: true });
76
+ }
77
+ throw new Error(`${store}: ${lock} could not be taken`);
78
+ };
79
+ /**
80
+ * Writes `document()` to `file` whole after each change, through a temporary file renamed over the old one — changes
81
+ * that arrive while a write is under way are written together right after it, so a crash loses at most the changes of
82
+ * that instant and never leaves half a file. A write that failed is said in the log and tried again by the next change
83
+ * or `flush`, never in a loop against a disk that keeps refusing.
84
+ */
85
+ var documentWriter = ({ file, document, store, what }) => {
86
+ let dirty = false;
87
+ let failed = false;
88
+ /** The write under way, resolving to whether everything it took on reached the disk. */
89
+ let writing;
90
+ const drain = async () => {
91
+ while (dirty) {
92
+ dirty = false;
93
+ try {
94
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
95
+ await writeFileAtomic(file, document());
96
+ } catch (error) {
97
+ dirty = true;
98
+ failed = true;
99
+ serverLog.error("Actions", `${what} ${file} could not be written`, error);
100
+ return false;
101
+ }
102
+ }
103
+ return true;
104
+ };
105
+ const write = () => {
106
+ writing ??= new Promise((resolve) => {
107
+ queueMicrotask(resolve);
108
+ }).then(drain).finally(() => {
109
+ writing = void 0;
110
+ if (dirty && !failed) write();
111
+ });
112
+ return writing;
113
+ };
114
+ return {
115
+ changed: () => {
116
+ dirty = true;
117
+ failed = false;
118
+ write();
119
+ },
120
+ flush: async () => {
121
+ failed = false;
122
+ while (writing !== void 0 || dirty) if (!await (writing ?? write())) throw new Error(`${store}: ${file} could not be written; the reason is in the log.`);
123
+ }
124
+ };
125
+ };
126
+ //#endregion
127
+ export { FileInUseError, documentWriter, holdFile, letGo };
@@ -9,7 +9,25 @@ export type HostLookup = (hostname: string) => Promise<{
9
9
  address: string;
10
10
  }[]>;
11
11
  /**
12
- * Checks the URL an authored document asked for, including what its hostname RESOLVES to.
12
+ * What the deployment says of the requests its spaces write.
13
+ *
14
+ * `privateOrigins` are the origins on its own network an authored request may reach all the same — its storage, its
15
+ * CDN, its API, put there by whoever runs it and named in its configuration, never by a document. Every other private
16
+ * address stays closed: a self-hosted server whose files live on a local S3 serves them to its pages without opening
17
+ * the network they sit in. `lookup` is how a name is resolved, a test's to replace.
18
+ */
19
+ export type OutboundOptions = {
20
+ lookup?: HostLookup;
21
+ privateOrigins?: readonly string[];
22
+ };
23
+ /**
24
+ * The deployment's own origins as `new URL(…).origin` writes them, refusing what is not one — said when the server is
25
+ * built, rather than as every request that should have reached it failing.
26
+ */
27
+ export declare const privateOriginsOf: (origins: readonly string[] | undefined) => string[];
28
+ /**
29
+ * Checks the URL an authored document asked for, including what its hostname RESOLVES to — unless it is one of the
30
+ * origins the deployment names as its own (`privateOrigins`).
13
31
  *
14
32
  * The literal check alone was never enough and said so: `http://metadata.example.com/` is a public-looking name
15
33
  * whose A record can be `169.254.169.254`, and nothing about the string gives that away. So the name is resolved
@@ -21,7 +39,7 @@ export type HostLookup = (hostname: string) => Promise<{
21
39
  * answering a public address here and a private one when the socket is opened a moment later — which is closed
22
40
  * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
23
41
  */
24
- export declare const assertOutboundAllowed: (url: URL, lookup?: HostLookup) => Promise<void>;
42
+ export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins }?: OutboundOptions) => Promise<void>;
25
43
  /**
26
44
  * Sends an authored request, judging EVERY hop it takes by `assertOutboundAllowed`.
27
45
  *
@@ -32,4 +50,15 @@ export declare const assertOutboundAllowed: (url: URL, lookup?: HostLookup) => P
32
50
  * `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
33
51
  * against whatever that transport enforces.
34
52
  */
35
- export declare const fetchOutbound: (base: typeof fetch, url: URL, init?: RequestInit, lookup?: HostLookup) => Promise<Response>;
53
+ export declare const fetchOutbound: (base: typeof fetch, url: URL, init?: RequestInit, options?: OutboundOptions) => Promise<Response>;
54
+ /**
55
+ * Holds an answer to what its reader is allowed to carry — an action's run, a page server's read of another site.
56
+ *
57
+ * Two checks rather than one, because a body arrives in two ways. `Content-Length` is refused before a byte is
58
+ * read, which is the cheap half; a chunked answer that declares nothing is counted AS it streams and errored the
59
+ * moment it goes over — so the ceiling holds for a backend that lies about its size or never states one.
60
+ *
61
+ * The cap is on one response and not on the run or the page: it exists so that a single answer cannot be unbounded, which is
62
+ * a different failure from a flow that makes many small calls (that is `maxRequests`).
63
+ */
64
+ export declare const cappedResponse: (response: Response, maxBytes: number, refuse: (message: string) => Error) => Response;
@@ -73,7 +73,22 @@ var resolveAll = (hostname) => lookup(hostname, {
73
73
  verbatim: true
74
74
  });
75
75
  /**
76
- * Checks the URL an authored document asked for, including what its hostname RESOLVES to.
76
+ * The deployment's own origins as `new URL(…).origin` writes them, refusing what is not one — said when the server is
77
+ * built, rather than as every request that should have reached it failing.
78
+ */
79
+ var privateOriginsOf = (origins) => (origins ?? []).map((origin) => {
80
+ let url;
81
+ try {
82
+ url = new URL(origin);
83
+ } catch {
84
+ throw new Error(`outbound.privateOrigins: "${origin}" is not an origin — write it as http://host:port`);
85
+ }
86
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) throw new Error(`outbound.privateOrigins: "${origin}" is not an origin — write it as http://host:port, no path`);
87
+ return url.origin;
88
+ });
89
+ /**
90
+ * Checks the URL an authored document asked for, including what its hostname RESOLVES to — unless it is one of the
91
+ * origins the deployment names as its own (`privateOrigins`).
77
92
  *
78
93
  * The literal check alone was never enough and said so: `http://metadata.example.com/` is a public-looking name
79
94
  * whose A record can be `169.254.169.254`, and nothing about the string gives that away. So the name is resolved
@@ -85,8 +100,9 @@ var resolveAll = (hostname) => lookup(hostname, {
85
100
  * answering a public address here and a private one when the socket is opened a moment later — which is closed
86
101
  * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
87
102
  */
88
- var assertOutboundAllowed = async (url, lookup = resolveAll) => {
103
+ var assertOutboundAllowed = async (url, { lookup = resolveAll, privateOrigins = [] } = {}) => {
89
104
  if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Request protocol "${url.protocol}" is not allowed`);
105
+ if (privateOrigins.includes(url.origin)) return;
90
106
  if (isBlockedHost(url.hostname)) throw new Error("Request host is not allowed");
91
107
  let addresses;
92
108
  try {
@@ -151,11 +167,11 @@ var redirectedInit = (init, status, crossOrigin) => {
151
167
  * `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
152
168
  * against whatever that transport enforces.
153
169
  */
154
- var fetchOutbound = async (base, url, init = {}, lookup = resolveAll) => {
170
+ var fetchOutbound = async (base, url, init = {}, options = {}) => {
155
171
  let target = url;
156
172
  let request = init;
157
173
  for (let hop = 0;; hop += 1) {
158
- await assertOutboundAllowed(target, lookup);
174
+ await assertOutboundAllowed(target, options);
159
175
  const response = await base(target.toString(), {
160
176
  ...request,
161
177
  redirect: "manual"
@@ -169,5 +185,34 @@ var fetchOutbound = async (base, url, init = {}, lookup = resolveAll) => {
169
185
  target = next;
170
186
  }
171
187
  };
188
+ /**
189
+ * Holds an answer to what its reader is allowed to carry — an action's run, a page server's read of another site.
190
+ *
191
+ * Two checks rather than one, because a body arrives in two ways. `Content-Length` is refused before a byte is
192
+ * read, which is the cheap half; a chunked answer that declares nothing is counted AS it streams and errored the
193
+ * moment it goes over — so the ceiling holds for a backend that lies about its size or never states one.
194
+ *
195
+ * The cap is on one response and not on the run or the page: it exists so that a single answer cannot be unbounded, which is
196
+ * a different failure from a flow that makes many small calls (that is `maxRequests`).
197
+ */
198
+ var cappedResponse = (response, maxBytes, refuse) => {
199
+ const declared = Number(response.headers.get("content-length") ?? "");
200
+ if (Number.isFinite(declared) && declared > maxBytes) throw refuse(`Response is larger than the ${String(maxBytes)} byte budget`);
201
+ if (!response.body) return response;
202
+ let seen = 0;
203
+ const counted = response.body.pipeThrough(new TransformStream({ transform: (chunk, controller) => {
204
+ seen += chunk.byteLength;
205
+ if (seen > maxBytes) {
206
+ controller.error(refuse(`Response exceeded the ${String(maxBytes)} byte budget`));
207
+ return;
208
+ }
209
+ controller.enqueue(chunk);
210
+ } }));
211
+ return new Response(counted, {
212
+ status: response.status,
213
+ statusText: response.statusText,
214
+ headers: response.headers
215
+ });
216
+ };
172
217
  //#endregion
173
- export { assertOutboundAllowed, fetchOutbound, isBlockedHost };
218
+ export { assertOutboundAllowed, cappedResponse, fetchOutbound, isBlockedHost, privateOriginsOf };
@@ -0,0 +1,24 @@
1
+ import { Stage } from '../../core/http/types';
2
+ /**
3
+ * A run of agents (`plitzi run`) open in the project, said on this server's console while developing: this server
4
+ * serves the project as it is, and a run writes nothing into it until its finish — so a person looking here for the
5
+ * agents' work is told where it is (`npm run start:preview`). Said when the server starts with one open, when one opens,
6
+ * and when it ends. Answers what stops looking.
7
+ */
8
+ export declare const watchAgentRuns: (root: string, { say, everyMs }?: {
9
+ say?: (line: string) => void;
10
+ everyMs?: number;
11
+ }) => (() => void);
12
+ /**
13
+ * The run a preview serves, answered at `RUN_STATUS_PATH` for the page's dev tools (their Run tab): the snapshot `plitzi
14
+ * run preview` keeps in `file` and names in `RUN_STATUS_ENV`. Read on each request — the CLI rewrites it as the run goes —
15
+ * and answered as it is: none yet (the preview just started) is a 404 that says so. Only on a preview's server — and every
16
+ * request it lets by is marked as one (`runStatus`), so the page tells its dev tools there is a run to ask for.
17
+ */
18
+ export declare const runStatusStage: (file: string) => Stage;
19
+ /**
20
+ * What the person watching a run's preview reports from its page (`RUN_REPORT_PATH`, the dev tools' Run tab): checked,
21
+ * and left as a file of its own in `dir` — the folder `plitzi run preview` names in `RUN_REPORTS_ENV` and hands on to
22
+ * the run's lead. Answered 202: the lead reads it with its next command, not now. Only on a preview's server.
23
+ */
24
+ export declare const runReportStage: (dir: string) => Stage;
@@ -0,0 +1,107 @@
1
+ import { readRawBody } from "../../core/requestParser.js";
2
+ import { refusedCrossSite } from "../../core/http/stages/crossSiteWrites.js";
3
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
4
+ import { randomBytes } from "node:crypto";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { readFileSync } from "node:fs";
8
+ import { ACTIVE_RUN_FILE } from "@plitzi/sdk-shared/project";
9
+ import { RUN_REPORT_PATH, RUN_STATUS_PATH, runReportProblems } from "@plitzi/sdk-shared/runs";
10
+ //#region src/hosts/project/agentRuns.ts
11
+ /** How often the project is looked at for a run opening or ending: a stat, cheap enough to do while developing. */
12
+ var EVERY_MS = 5e3;
13
+ /** The open run's name, as `plitzi run open` wrote it — none open, or a file that does not say one, undefined. */
14
+ var openRun = (root) => {
15
+ try {
16
+ const claim = JSON.parse(readFileSync(path.join(root, ACTIVE_RUN_FILE), "utf-8"));
17
+ return isRecord(claim) && typeof claim.runId === "string" ? claim.runId : void 0;
18
+ } catch {
19
+ return;
20
+ }
21
+ };
22
+ /**
23
+ * A run of agents (`plitzi run`) open in the project, said on this server's console while developing: this server
24
+ * serves the project as it is, and a run writes nothing into it until its finish — so a person looking here for the
25
+ * agents' work is told where it is (`npm run start:preview`). Said when the server starts with one open, when one opens,
26
+ * and when it ends. Answers what stops looking.
27
+ */
28
+ var watchAgentRuns = (root, { say = console.log, everyMs = EVERY_MS } = {}) => {
29
+ let told;
30
+ const look = () => {
31
+ const runId = openRun(root);
32
+ if (runId !== void 0 && runId !== told) say(`[runs] agents are working run "${runId}": this server serves the project as it is, and their approved work reaches it at the run's finish — to watch it as they go: npm run start:preview`);
33
+ else if (runId === void 0 && told !== void 0) say(`[runs] run "${told}" is closed: what it wrote, if it was finished, is in the project now`);
34
+ told = runId;
35
+ };
36
+ look();
37
+ const timer = setInterval(look, everyMs);
38
+ timer.unref();
39
+ return () => clearInterval(timer);
40
+ };
41
+ /**
42
+ * The run a preview serves, answered at `RUN_STATUS_PATH` for the page's dev tools (their Run tab): the snapshot `plitzi
43
+ * run preview` keeps in `file` and names in `RUN_STATUS_ENV`. Read on each request — the CLI rewrites it as the run goes —
44
+ * and answered as it is: none yet (the preview just started) is a 404 that says so. Only on a preview's server — and every
45
+ * request it lets by is marked as one (`runStatus`), so the page tells its dev tools there is a run to ask for.
46
+ */
47
+ var runStatusStage = (file) => (ctx) => {
48
+ if (ctx.req.path !== RUN_STATUS_PATH) {
49
+ ctx.req.ctx.runStatus = true;
50
+ return Promise.resolve(false);
51
+ }
52
+ let text;
53
+ try {
54
+ text = readFileSync(file, "utf-8");
55
+ } catch {
56
+ text = void 0;
57
+ }
58
+ ctx.res.setHeader("Cache-Control", "no-store");
59
+ ctx.res.setHeader("Content-Type", "application/json; charset=utf-8");
60
+ if (text === void 0) {
61
+ ctx.res.setStatus(404);
62
+ ctx.res.send(JSON.stringify({ error: "The run has no snapshot yet: its preview writes one as it starts" }));
63
+ } else ctx.res.send(text);
64
+ return Promise.resolve(true);
65
+ };
66
+ /**
67
+ * What the person watching a run's preview reports from its page (`RUN_REPORT_PATH`, the dev tools' Run tab): checked,
68
+ * and left as a file of its own in `dir` — the folder `plitzi run preview` names in `RUN_REPORTS_ENV` and hands on to
69
+ * the run's lead. Answered 202: the lead reads it with its next command, not now. Only on a preview's server.
70
+ */
71
+ var runReportStage = (dir) => async (ctx) => {
72
+ const { req, res, raw } = ctx;
73
+ if (req.path !== RUN_REPORT_PATH) return false;
74
+ res.setHeader("Cache-Control", "no-store");
75
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
76
+ if (req.method !== "POST") {
77
+ res.setStatus(405);
78
+ res.send(JSON.stringify({ error: `A report is sent with POST to ${RUN_REPORT_PATH}` }));
79
+ return true;
80
+ }
81
+ if (refusedCrossSite(ctx)) return true;
82
+ let body;
83
+ try {
84
+ body = JSON.parse(await readRawBody(raw));
85
+ } catch {
86
+ body = void 0;
87
+ }
88
+ const problems = runReportProblems(body);
89
+ if (problems.length > 0) {
90
+ res.setStatus(400);
91
+ res.send(JSON.stringify({
92
+ error: `The report was not kept: ${problems.join("; ")}`,
93
+ problems
94
+ }));
95
+ return true;
96
+ }
97
+ await mkdir(dir, { recursive: true });
98
+ await writeFile(path.join(dir, `${String(Date.now())}-${randomBytes(4).toString("hex")}.json`), `${JSON.stringify(body)}\n`);
99
+ res.setStatus(202);
100
+ res.send(JSON.stringify({
101
+ received: true,
102
+ note: "The run’s lead gets it with its next command"
103
+ }));
104
+ return true;
105
+ };
106
+ //#endregion
107
+ export { runReportStage, runStatusStage, watchAgentRuns };
@@ -0,0 +1,41 @@
1
+ import { JobQueue } from '@plitzi/sdk-shared';
2
+ /**
3
+ * `plitzi functions later` while the project is served: what waits to run later (`ctx.later`), and one of them started
4
+ * now. The server holds its queue's file, so the CLI asks it through a file of the project's `tmp/` and reads the answer
5
+ * beside it — a spec of a show that starts in five minutes waited the five, every pass (a run's test-1, ~6 min each).
6
+ * Only while developing: a deployment's queue is an operator's (`createJobControl`).
7
+ */
8
+ /** A run set for later, as the CLI says it. */
9
+ export type LaterWaiting = {
10
+ job: string;
11
+ action: string;
12
+ key?: string;
13
+ dueAt: number;
14
+ };
15
+ export type LaterAsk = {
16
+ id: string;
17
+ ask: 'list';
18
+ } | {
19
+ id: string;
20
+ ask: 'now';
21
+ key: string;
22
+ };
23
+ export type LaterAnswer = {
24
+ id: string;
25
+ waiting: LaterWaiting[];
26
+ } | {
27
+ id: string;
28
+ started: LaterWaiting;
29
+ } | {
30
+ id: string;
31
+ problem: string;
32
+ };
33
+ /**
34
+ * Answers one ask. Started now, a run set for later is set again under its key, due now — `ctx.later`'s own rule
35
+ * replaces the one waiting — so the worker takes it at its next look, as it would have at its time.
36
+ */
37
+ export declare const answerLaterAsk: (queue: JobQueue, spaceId: number, ask: LaterAsk) => Promise<LaterAnswer>;
38
+ /** Looks for an ask every so often and answers it: what stops looking. */
39
+ export declare const watchLaterAsks: (root: string, queue: () => JobQueue | undefined, spaceId: number, { everyMs }?: {
40
+ everyMs?: number;
41
+ }) => (() => void);
@@ -0,0 +1,117 @@
1
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
2
+ import path from "node:path";
3
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { LATER_ANSWER_FILE, LATER_ASK_FILE } from "@plitzi/sdk-shared/project";
5
+ //#region src/hosts/project/laterAsks.ts
6
+ var said = (job) => ({
7
+ job: job.id,
8
+ action: job.target.name,
9
+ ...job.key === void 0 ? {} : { key: job.key },
10
+ dueAt: job.dueAt
11
+ });
12
+ var waitingOf = async (queue, spaceId) => (await queue.listJobs({
13
+ spaceIds: [spaceId],
14
+ status: "pending",
15
+ kind: "action",
16
+ limit: 500,
17
+ offset: 0
18
+ })).jobs.filter((job) => job.target.kind === "action" && job.target.trigger === "later");
19
+ /**
20
+ * Answers one ask. Started now, a run set for later is set again under its key, due now — `ctx.later`'s own rule
21
+ * replaces the one waiting — so the worker takes it at its next look, as it would have at its time.
22
+ */
23
+ var answerLaterAsk = async (queue, spaceId, ask) => {
24
+ const waiting = await waitingOf(queue, spaceId);
25
+ if (ask.ask === "list") return {
26
+ id: ask.id,
27
+ waiting: waiting.map(said)
28
+ };
29
+ const job = waiting.find((each) => each.key === ask.key);
30
+ if (!job) {
31
+ const keys = waiting.flatMap((each) => each.key === void 0 ? [] : [each.key]);
32
+ return {
33
+ id: ask.id,
34
+ problem: `Nothing waits to run later under "${ask.key}"${keys.length > 0 ? `: what waits is ${keys.join(", ")}` : ": nothing waits at all"}`
35
+ };
36
+ }
37
+ const now = (await queue.now()).getTime();
38
+ const id = `${job.id}:now:${String(now)}`;
39
+ await queue.enqueue({
40
+ id,
41
+ spaceId,
42
+ environment: job.environment,
43
+ target: job.target,
44
+ input: job.input,
45
+ dueAt: now,
46
+ maxAttempts: job.maxAttempts,
47
+ key: ask.key
48
+ });
49
+ await queue.cancelPending({
50
+ spaceId,
51
+ key: ask.key,
52
+ olderThan: id
53
+ });
54
+ return {
55
+ id: ask.id,
56
+ started: {
57
+ ...said(job),
58
+ job: id,
59
+ dueAt: now
60
+ }
61
+ };
62
+ };
63
+ var askOf = (value) => {
64
+ if (!isRecord(value) || typeof value.id !== "string") return;
65
+ if (value.ask === "list") return {
66
+ id: value.id,
67
+ ask: "list"
68
+ };
69
+ return value.ask === "now" && typeof value.key === "string" ? {
70
+ id: value.id,
71
+ ask: "now",
72
+ key: value.key
73
+ } : void 0;
74
+ };
75
+ /** Looks for an ask every so often and answers it: what stops looking. */
76
+ var watchLaterAsks = (root, queue, spaceId, { everyMs = 500 } = {}) => {
77
+ const asked = path.join(root, LATER_ASK_FILE);
78
+ const answered = path.join(root, LATER_ANSWER_FILE);
79
+ let busy = false;
80
+ const answer = (said) => {
81
+ const writing = `${answered}.${String(process.pid)}`;
82
+ writeFileSync(writing, JSON.stringify(said));
83
+ renameSync(writing, answered);
84
+ };
85
+ const look = async () => {
86
+ if (busy || !existsSync(asked)) return;
87
+ busy = true;
88
+ let ask;
89
+ try {
90
+ ask = askOf(JSON.parse(readFileSync(asked, "utf-8")));
91
+ rmSync(asked, { force: true });
92
+ if (ask === void 0) return;
93
+ const jobs = queue();
94
+ answer(jobs === void 0 ? {
95
+ id: ask.id,
96
+ problem: "This server runs no jobs: its actions have no queue (`action.jobs: false`)"
97
+ } : await answerLaterAsk(jobs, spaceId, ask));
98
+ } catch (error) {
99
+ rmSync(asked, { force: true });
100
+ if (ask !== void 0) answer({
101
+ id: ask.id,
102
+ problem: error instanceof Error ? error.message : String(error)
103
+ });
104
+ } finally {
105
+ busy = false;
106
+ }
107
+ };
108
+ const timer = setInterval(() => {
109
+ look().catch((error) => {
110
+ console.warn(`[later] an ask of plitzi functions later went unanswered: ${String(error)}`);
111
+ });
112
+ }, everyMs);
113
+ timer.unref();
114
+ return () => clearInterval(timer);
115
+ };
116
+ //#endregion
117
+ export { answerLaterAsk, watchLaterAsks };
@@ -1,5 +1,5 @@
1
1
  import { loadFunctions, loadFunctionsSource } from "../../modules/functions/load.js";
2
- import { PLUGIN_FUNCTIONS_SOURCE } from "@plitzi/sdk-shared/actions";
2
+ import { PLUGIN_FUNCTIONS_SOURCE, isFunctionsDefinitionFile } from "@plitzi/sdk-shared/actions";
3
3
  import { isRecord } from "@plitzi/sdk-shared/helpers";
4
4
  import path from "node:path";
5
5
  import { existsSync, readFileSync, readdirSync, unwatchFile, watch, watchFile } from "node:fs";
@@ -34,11 +34,11 @@ var pluginFolders = (root) => {
34
34
  * A plugin's server half: its `functions/` folder (`src/plugins/Board/functions/index.ts`), written like the project's
35
35
  * own `src/functions/` and loaded with what a plugin may reach — its own corner of `kv`, its routes under
36
36
  * `/fn/plugins/<name>/`, its tasks named `<name>.<action>`. A folder without one is a component and nothing else; one
37
- * with code and no `index.ts` is the layout check's to say (`plugin-functions-entry-missing`).
37
+ * with code and no file at its top is the layout check's to say (`plugin-functions-entry-missing`).
38
38
  */
39
39
  var folderFunctions = async (root, folder) => {
40
40
  const functions = path.join(root, PLUGINS_DIR, folder, PLUGIN_FUNCTIONS_DIR);
41
- return existsSync(path.join(functions, "index.ts")) ? (await loadFunctions(functions)).at(0) : void 0;
41
+ return (existsSync(functions) ? readdirSync(functions).filter(isFunctionsDefinitionFile) : []).length > 0 ? (await loadFunctions(functions)).at(0) : void 0;
42
42
  };
43
43
  /** A plugin of `vendor/plugins`, from the manifest `plitzi plugin pack` wrote beside its bundle when it was published. */
44
44
  var builtPlugin = (root, type) => {
@@ -127,14 +127,19 @@ var watchPluginsFolder = (root, dir, server, plugins, late) => {
127
127
  else console.warn(line);
128
128
  }
129
129
  };
130
+ const failed = /* @__PURE__ */ new Map();
130
131
  const reloadFunctions = (folder) => {
131
132
  const name = pluginTypeOf(folder);
132
133
  sayOf(folder);
133
134
  folderFunctions(root, folder).then((definition) => {
135
+ failed.delete(folder);
134
136
  server.functions.setPlugin(name, definition);
135
137
  if (definition) console.log(`[plugins] ${name}: its functions, loaded again`);
136
138
  }).catch((error) => {
137
- console.error(`[plugins] ${name}: its functions were not loaded again:`, error instanceof Error ? error.message : error);
139
+ const message = error instanceof Error ? error.message : String(error);
140
+ if (failed.get(folder) === message) return;
141
+ failed.set(folder, message);
142
+ console.error(`[plugins] ${name}: its functions were not loaded again:`, message);
138
143
  });
139
144
  };
140
145
  const sync = () => {
@@ -154,6 +159,8 @@ var watchPluginsFolder = (root, dir, server, plugins, late) => {
154
159
  fromFolders.delete(name);
155
160
  names.splice(names.indexOf(name), 1);
156
161
  server.functions.setPlugin(name, void 0);
162
+ server.plugins.unregister(name);
163
+ console.log(`[plugins] ${name}: its folder is gone — no longer served`);
157
164
  }
158
165
  if (added.length > 0 || removed.length > 0) server.reloadPages();
159
166
  };
@@ -29,6 +29,13 @@ export type ProjectSpace = AuthoredDocuments & {
29
29
  message: string;
30
30
  }[];
31
31
  };
32
+ export declare const isStartupReport: (error: unknown) => error is Error;
33
+ /**
34
+ * A second server of the project, started while the first runs, said as what it is: the project already served, where,
35
+ * since when, and how to stop it — where it said a state file was in use by a process, with a stack (the maintainer: "debería
36
+ * ser más amigable"). Undefined for a holder that serves nothing, whose own report is said as it is.
37
+ */
38
+ export declare const alreadyServed: (error: Error) => string | undefined;
32
39
  type ServeProjectBase = {
33
40
  /** The space's server actions (`src/actions/`), found by their id. Left out, the server runs none. */
34
41
  actions?: readonly ActionEntry[];
@@ -82,7 +89,7 @@ export type ServedProject = {
82
89
  * - a signal closes it, finishing what runs.
83
90
  *
84
91
  * While developing (`NODE_ENV` other than `production`), a save to the space is authored again by the project's
85
- * `plitzi/author.ts`, in a process of its own, which hands the documents back over IPC: the server swaps them in memory
92
+ * `.plitzi/author.ts`, in a process of its own, which hands the documents back over IPC: the server swaps them in memory
86
93
  * and every open page loads again. A plugin folder added is registered, one removed turned off, and a plugin's
87
94
  * `functions/` loaded again; a folder it cannot build is said in the terminal, and the server goes on.
88
95
  */