@botiverse/porthole 0.5.1 → 0.7.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 (167) hide show
  1. package/README.md +41 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +208 -13
  4. package/dist/bridge/navigation.d.ts +1 -6
  5. package/dist/bridge/navigation.js +11 -0
  6. package/dist/bridge/refusal.d.ts +5 -1
  7. package/dist/bridge/refusal.js +16 -0
  8. package/dist/bridge/types.d.ts +41 -4
  9. package/dist/check/check.d.ts +19 -3
  10. package/dist/check/check.js +55 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/instrument.d.ts +3 -0
  14. package/dist/check/lint.js +31 -12
  15. package/dist/check/page-source.js +1 -1
  16. package/dist/check/page.js +14 -0
  17. package/dist/check/tools.d.ts +23 -0
  18. package/dist/check/tools.js +27 -3
  19. package/dist/compile/policy.d.ts +34 -0
  20. package/dist/compile/policy.js +74 -0
  21. package/dist/config/capabilities.d.ts +62 -3
  22. package/dist/config/capabilities.js +20 -0
  23. package/dist/config/schema.d.ts +32 -0
  24. package/dist/config/validate.d.ts +1 -1
  25. package/dist/config/validate.js +74 -5
  26. package/dist/conformance/harness-source.js +1 -1
  27. package/dist/conformance/index.d.ts +1 -0
  28. package/dist/conformance/index.js +2 -0
  29. package/dist/conformance/runtime.d.ts +58 -0
  30. package/dist/conformance/runtime.js +314 -0
  31. package/dist/files/paths.d.ts +99 -0
  32. package/dist/files/paths.js +263 -0
  33. package/dist/files/types.d.ts +24 -0
  34. package/dist/files/types.js +83 -0
  35. package/dist/guide/gates.d.ts +3 -0
  36. package/dist/guide/gates.js +19 -0
  37. package/dist/guide/guide.d.ts +2 -0
  38. package/dist/guide/guide.js +44 -32
  39. package/dist/guide/limits.js +4 -4
  40. package/dist/guide/runtime.d.ts +13 -0
  41. package/dist/guide/runtime.js +202 -0
  42. package/dist/host/create-host.js +45 -0
  43. package/dist/host/locate.js +8 -0
  44. package/dist/host/locator.js +7 -0
  45. package/dist/host/types.d.ts +18 -0
  46. package/dist/index.d.ts +13 -4
  47. package/dist/index.js +16 -3
  48. package/dist/isolation/types.d.ts +8 -0
  49. package/dist/presets/presets.d.ts +6 -0
  50. package/dist/presets/presets.js +1 -0
  51. package/dist/protocol/adapter.d.ts +4 -0
  52. package/dist/protocol/mcp-apps.d.ts +6 -0
  53. package/dist/protocol/mcp-apps.js +6 -0
  54. package/dist/protocol/runtime-calls.d.ts +28 -0
  55. package/dist/protocol/runtime-calls.js +113 -0
  56. package/dist/protocol/shell-adapter.js +52 -3
  57. package/dist/react/dialog.js +31 -0
  58. package/dist/react/frame.d.ts +13 -0
  59. package/dist/react/frame.js +6 -0
  60. package/dist/runtime/contract.d.ts +193 -0
  61. package/dist/runtime/contract.js +216 -0
  62. package/dist/runtime/db.d.ts +153 -0
  63. package/dist/runtime/db.js +398 -0
  64. package/dist/runtime/declaration.d.ts +86 -0
  65. package/dist/runtime/declaration.js +266 -0
  66. package/dist/runtime/levels.d.ts +33 -0
  67. package/dist/runtime/levels.js +41 -0
  68. package/dist/runtime/requests.d.ts +125 -0
  69. package/dist/runtime/requests.js +199 -0
  70. package/dist/runtime/segments.d.ts +8 -0
  71. package/dist/runtime/segments.js +14 -0
  72. package/dist/runtime/types.generated.d.ts +1 -0
  73. package/dist/runtime/types.generated.js +19 -0
  74. package/dist/server/files.d.ts +57 -0
  75. package/dist/server/files.js +338 -0
  76. package/dist/server/host.d.ts +44 -2
  77. package/dist/server/host.js +42 -2
  78. package/dist/server/index.d.ts +5 -2
  79. package/dist/server/index.js +5 -1
  80. package/dist/server/keys.d.ts +8 -0
  81. package/dist/server/keys.js +34 -0
  82. package/dist/server/pseudonym.d.ts +9 -0
  83. package/dist/server/pseudonym.js +20 -0
  84. package/dist/server/server.d.ts +0 -5
  85. package/dist/server/server.js +468 -24
  86. package/dist/server/types.d.ts +118 -5
  87. package/dist/shell/document.d.ts +27 -0
  88. package/dist/shell/document.js +46 -2
  89. package/dist/shell/legacy.d.ts +21 -0
  90. package/dist/shell/legacy.js +63 -0
  91. package/dist/shell/plan.d.ts +17 -1
  92. package/dist/shell/plan.js +13 -2
  93. package/dist/shell/runtime.d.ts +2 -1
  94. package/dist/shell/runtime.js +114 -46
  95. package/dist/shell/use.d.ts +15 -0
  96. package/dist/shell/use.js +235 -0
  97. package/docs/ADOPTING.md +142 -5
  98. package/docs/ARCHITECTURE.md +34 -5
  99. package/docs/DECISIONS.md +716 -7
  100. package/docs/DESIGN.md +97 -3
  101. package/package.json +3 -1
  102. package/src/bridge/bridge.ts +281 -17
  103. package/src/bridge/navigation.ts +12 -0
  104. package/src/bridge/refusal.ts +16 -0
  105. package/src/bridge/types.ts +46 -4
  106. package/src/check/check.ts +100 -14
  107. package/src/check/files.ts +384 -0
  108. package/src/check/instrument.ts +3 -0
  109. package/src/check/lint.ts +33 -12
  110. package/src/check/page.ts +14 -0
  111. package/src/check/tools.ts +52 -3
  112. package/src/compile/policy.ts +92 -0
  113. package/src/config/capabilities.ts +49 -2
  114. package/src/config/schema.ts +32 -0
  115. package/src/config/validate.ts +107 -5
  116. package/src/conformance/index.ts +7 -0
  117. package/src/conformance/runtime.ts +573 -0
  118. package/src/files/paths.ts +323 -0
  119. package/src/files/types.ts +101 -0
  120. package/src/guide/gates.ts +25 -0
  121. package/src/guide/guide.ts +78 -52
  122. package/src/guide/limits.ts +4 -4
  123. package/src/guide/runtime.ts +244 -0
  124. package/src/host/create-host.ts +55 -0
  125. package/src/host/locate.ts +10 -0
  126. package/src/host/locator.ts +11 -0
  127. package/src/host/types.ts +18 -0
  128. package/src/index.ts +121 -0
  129. package/src/isolation/types.ts +8 -0
  130. package/src/presets/presets.ts +7 -0
  131. package/src/protocol/adapter.ts +3 -1
  132. package/src/protocol/mcp-apps.ts +7 -0
  133. package/src/protocol/runtime-calls.ts +138 -0
  134. package/src/protocol/shell-adapter.ts +56 -2
  135. package/src/react/dialog.tsx +33 -0
  136. package/src/react/frame.tsx +19 -0
  137. package/src/runtime/contract.ts +305 -0
  138. package/src/runtime/db.ts +530 -0
  139. package/src/runtime/declaration.ts +378 -0
  140. package/src/runtime/levels.ts +69 -0
  141. package/src/runtime/requests.ts +339 -0
  142. package/src/runtime/segments.ts +17 -0
  143. package/src/runtime/types.generated.ts +19 -0
  144. package/src/server/files.ts +425 -0
  145. package/src/server/host.ts +84 -3
  146. package/src/server/index.ts +22 -0
  147. package/src/server/keys.ts +53 -0
  148. package/src/server/pseudonym.ts +21 -0
  149. package/src/server/server.ts +565 -26
  150. package/src/server/types.ts +124 -4
  151. package/src/shell/document.ts +74 -4
  152. package/src/shell/legacy.ts +64 -0
  153. package/src/shell/plan.ts +37 -3
  154. package/src/shell/runtime.ts +114 -46
  155. package/src/shell/use.ts +235 -0
  156. package/types/runtime/v1/artifact.d.ts +50 -0
  157. package/types/runtime/v1/assets.d.ts +43 -0
  158. package/types/runtime/v1/chat.d.ts +13 -0
  159. package/types/runtime/v1/clipboard.d.ts +14 -0
  160. package/types/runtime/v1/comments.d.ts +24 -0
  161. package/types/runtime/v1/context.d.ts +16 -0
  162. package/types/runtime/v1/data.d.ts +29 -0
  163. package/types/runtime/v1/db.d.ts +110 -0
  164. package/types/runtime/v1/downloads.d.ts +22 -0
  165. package/types/runtime/v1/links.d.ts +13 -0
  166. package/types/runtime/v1/porthole.d.ts +44 -0
  167. package/types/runtime/v1/user.d.ts +19 -0
@@ -0,0 +1,263 @@
1
+ /**
2
+ * A version made of files (P081): the rules a published path follows, the limits a version is
3
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
4
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
5
+ * only, never on a filesystem.
6
+ */
7
+ /** The most files a version holds, by default. */
8
+ export const DEFAULT_MAX_FILES = 1_000;
9
+ /** The largest file of a version, bytes, by default (25 MiB). */
10
+ export const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
11
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
12
+ export const DEFAULT_MAX_VERSION_BYTES = 100 * 1024 * 1024;
13
+ /** The longest path, characters, and the longest segment of one. */
14
+ export const MAX_FILE_PATH_CHARS = 512;
15
+ export const MAX_SEGMENT_CHARS = 255;
16
+ /** The page a version opens at by default. */
17
+ export const DEFAULT_ENTRY = "index.html";
18
+ /**
19
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
20
+ * origin of its own. Opaque frames have no origin to serve them from.
21
+ */
22
+ export const servesFiles = (config) => config.mode === "artifact" && config.isolation === "domain";
23
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
24
+ export function fileLimits(limits) {
25
+ return {
26
+ maxFiles: limits?.maxFiles ?? DEFAULT_MAX_FILES,
27
+ maxFileBytes: limits?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
28
+ maxVersionBytes: limits?.maxVersionBytes ?? DEFAULT_MAX_VERSION_BYTES,
29
+ };
30
+ }
31
+ /**
32
+ * What a request's path can never hold once decoded, and a published path never holds: control
33
+ * and format characters (`Cc`, `Cf`: a right-to-left override, a zero-width space, a BOM would make
34
+ * a path read as another), and `\ % ? #`.
35
+ */
36
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
37
+ const FORBIDDEN = /[\p{Cc}\p{Cf}\\%?#]/u;
38
+ /**
39
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
40
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
41
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
42
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
43
+ */
44
+ export function filePathProblem(path) {
45
+ if (typeof path !== "string" || path.length === 0) {
46
+ return "a path is a non-empty string";
47
+ }
48
+ if (path.length > MAX_FILE_PATH_CHARS) {
49
+ return `a path is at most ${MAX_FILE_PATH_CHARS} characters`;
50
+ }
51
+ if (path.startsWith("/")) {
52
+ return "a path is relative: no leading /";
53
+ }
54
+ if (path.endsWith("/")) {
55
+ return "a path names a file: no trailing /";
56
+ }
57
+ const forbidden = FORBIDDEN.exec(path);
58
+ if (forbidden !== null) {
59
+ const char = forbidden[0];
60
+ return `a path holds no ${char === "\\" || char === "%" || char === "?" || char === "#" ? char : "control or format character"}`;
61
+ }
62
+ if (path.normalize("NFC") !== path) {
63
+ return "a path is in Unicode NFC";
64
+ }
65
+ const segments = path.split("/");
66
+ for (const segment of segments) {
67
+ if (segment === "") {
68
+ return "a path has no empty segment (//)";
69
+ }
70
+ if (segment === "." || segment === "..") {
71
+ return `a path has no ${segment} segment`;
72
+ }
73
+ if (segment.length > MAX_SEGMENT_CHARS) {
74
+ return `a path's segment is at most ${MAX_SEGMENT_CHARS} characters`;
75
+ }
76
+ if (segment.startsWith(" ") || segment.endsWith(" ")) {
77
+ return "a path's segment doesn't start or end with a space";
78
+ }
79
+ }
80
+ if (segments[0] === "__porthole") {
81
+ return "__porthole/ is Porthole's own";
82
+ }
83
+ return null;
84
+ }
85
+ const sizeOf = (bytes) => bytes >= 1024 * 1024
86
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`
87
+ : bytes >= 1024
88
+ ? `${Math.round(bytes / 1024)} KiB`
89
+ : `${bytes} bytes`;
90
+ /**
91
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
92
+ * two paths that differ only in case, and no path that is both a file and a directory; the
93
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
94
+ * `fileLimits`). Empty when it may be published.
95
+ */
96
+ export function checkFileSet(files, options = {}) {
97
+ const limits = options.limits ?? fileLimits();
98
+ const problems = [];
99
+ const paths = Object.keys(files);
100
+ if (paths.length > limits.maxFiles) {
101
+ problems.push({
102
+ code: "count",
103
+ message: `${paths.length} files: a version holds at most ${limits.maxFiles}`,
104
+ });
105
+ }
106
+ const folded = new Map();
107
+ const directories = new Set();
108
+ let total = 0;
109
+ for (const path of paths) {
110
+ const problem = filePathProblem(path);
111
+ if (problem !== null) {
112
+ problems.push({ path, code: "path", message: `${JSON.stringify(path)}: ${problem}` });
113
+ continue;
114
+ }
115
+ const lower = path.toLowerCase();
116
+ const other = folded.get(lower);
117
+ if (other !== undefined) {
118
+ problems.push({
119
+ path,
120
+ code: "collision",
121
+ message: `${JSON.stringify(path)} and ${JSON.stringify(other)} differ only in case: rename one`,
122
+ });
123
+ }
124
+ else {
125
+ folded.set(lower, path);
126
+ }
127
+ const segments = path.split("/");
128
+ for (let index = 1; index < segments.length; index += 1) {
129
+ directories.add(segments.slice(0, index).join("/"));
130
+ }
131
+ const size = files[path]?.size;
132
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) {
133
+ problems.push({ path, code: "size", message: `${JSON.stringify(path)}: no size` });
134
+ continue;
135
+ }
136
+ if (size > limits.maxFileBytes) {
137
+ problems.push({
138
+ path,
139
+ code: "size",
140
+ message: `${JSON.stringify(path)} is ${sizeOf(size)}: a file is at most ${sizeOf(limits.maxFileBytes)}`,
141
+ });
142
+ }
143
+ total += size;
144
+ }
145
+ for (const path of paths) {
146
+ if (directories.has(path)) {
147
+ problems.push({
148
+ path,
149
+ code: "collision",
150
+ message: `${JSON.stringify(path)} is a file and a directory: rename one`,
151
+ });
152
+ }
153
+ }
154
+ if (total > limits.maxVersionBytes) {
155
+ problems.push({
156
+ code: "total",
157
+ message: `The files are ${sizeOf(total)} together: a version holds at most ${sizeOf(limits.maxVersionBytes)}`,
158
+ });
159
+ }
160
+ const entry = options.entry ?? DEFAULT_ENTRY;
161
+ if (!Object.hasOwn(files, entry)) {
162
+ problems.push({
163
+ path: entry,
164
+ code: "entry",
165
+ message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
166
+ });
167
+ }
168
+ return problems;
169
+ }
170
+ /**
171
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
172
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
173
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
174
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
175
+ * `/` stays (a directory).
176
+ */
177
+ export function requestFilePath(raw) {
178
+ if (raw.length > MAX_FILE_PATH_CHARS * 3 + 1) {
179
+ return null;
180
+ }
181
+ const segments = raw.split("/");
182
+ const decoded = [];
183
+ for (const [index, segment] of segments.entries()) {
184
+ if (segment === "") {
185
+ // Only the last segment may be empty: a directory's trailing slash (or the base itself).
186
+ if (index !== segments.length - 1) {
187
+ return null;
188
+ }
189
+ decoded.push("");
190
+ continue;
191
+ }
192
+ let value;
193
+ try {
194
+ value = decodeURIComponent(segment);
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ if (value === "." || value === ".." || value.includes("/") || FORBIDDEN.test(value)) {
200
+ return null;
201
+ }
202
+ decoded.push(value);
203
+ }
204
+ return decoded.join("/");
205
+ }
206
+ /**
207
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
208
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
209
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
210
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
211
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
212
+ */
213
+ export function lookupFile(has, path, options) {
214
+ const entry = options.entry ?? DEFAULT_ENTRY;
215
+ if (path === "") {
216
+ if (!has(entry)) {
217
+ return notFound(has, "", options);
218
+ }
219
+ // An entry in a directory opens there, so its relative addresses are its directory's.
220
+ return entry.includes("/")
221
+ ? { kind: "redirect", to: entry }
222
+ : { kind: "file", path: entry, status: 200 };
223
+ }
224
+ if (path.endsWith("/")) {
225
+ const index = `${path}index.html`;
226
+ if (has(index)) {
227
+ return { kind: "file", path: index, status: 200 };
228
+ }
229
+ const page = `${path.slice(0, -1)}.html`;
230
+ if (has(page)) {
231
+ return { kind: "redirect", to: path.slice(0, -1) };
232
+ }
233
+ return notFound(has, path, options);
234
+ }
235
+ if (has(path)) {
236
+ return { kind: "file", path, status: 200 };
237
+ }
238
+ if (has(`${path}.html`)) {
239
+ return { kind: "file", path: `${path}.html`, status: 200 };
240
+ }
241
+ if (has(`${path}/index.html`)) {
242
+ return { kind: "redirect", to: `${path}/` };
243
+ }
244
+ return notFound(has, path, options);
245
+ }
246
+ function notFound(has, path, options) {
247
+ if (!options.navigation) {
248
+ return { kind: "none" };
249
+ }
250
+ const entry = options.entry ?? DEFAULT_ENTRY;
251
+ if (options.spa === true && has(entry)) {
252
+ return { kind: "file", path: entry, status: 200 };
253
+ }
254
+ // The nearest 404.html: in the request's directory, then each one above it.
255
+ const segments = path.split("/").slice(0, -1);
256
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
257
+ const candidate = [...segments.slice(0, depth), "404.html"].join("/");
258
+ if (has(candidate)) {
259
+ return { kind: "file", path: candidate, status: 404 };
260
+ }
261
+ }
262
+ return { kind: "none" };
263
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The media type a file of a set is served with (P081): Porthole's own table, by the path's
3
+ * extension, never the uploader's word and never sniffed. A file whose extension isn't here is
4
+ * `application/octet-stream`, served as a download. Pure: any runtime.
5
+ */
6
+ /** How a type is served: a page (in the shell), a script (it may run as a worker), or a file. */
7
+ export type FileRole = "page" | "script" | "file";
8
+ export interface FileType {
9
+ /** The `content-type` header. */
10
+ readonly type: string;
11
+ readonly role: FileRole;
12
+ }
13
+ /** What a file whose extension isn't in the table is served as: a download. */
14
+ export declare const UNKNOWN_TYPE = "application/octet-stream";
15
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
16
+ export declare function extensionOf(path: string): string;
17
+ /** The type a path is served with, and how. */
18
+ export declare function fileTypeOf(path: string): FileType;
19
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
20
+ export declare const knownType: (path: string) => boolean;
21
+ /** Whether a path names a page: an `.html` file. */
22
+ export declare const isPagePath: (path: string) => boolean;
23
+ /** Every extension the table knows, for the manual and tests. */
24
+ export declare const KNOWN_EXTENSIONS: readonly string[];
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The media type a file of a set is served with (P081): Porthole's own table, by the path's
3
+ * extension, never the uploader's word and never sniffed. A file whose extension isn't here is
4
+ * `application/octet-stream`, served as a download. Pure: any runtime.
5
+ */
6
+ const UTF8 = "; charset=utf-8";
7
+ /** Extension (lowercase, no dot) to media type. Standard web types only. */
8
+ const TABLE = {
9
+ html: `text/html${UTF8}`,
10
+ htm: `text/html${UTF8}`,
11
+ css: `text/css${UTF8}`,
12
+ js: `text/javascript${UTF8}`,
13
+ mjs: `text/javascript${UTF8}`,
14
+ cjs: `text/javascript${UTF8}`,
15
+ json: `application/json${UTF8}`,
16
+ map: `application/json${UTF8}`,
17
+ webmanifest: `application/manifest+json${UTF8}`,
18
+ txt: `text/plain${UTF8}`,
19
+ md: `text/markdown${UTF8}`,
20
+ markdown: `text/markdown${UTF8}`,
21
+ csv: `text/csv${UTF8}`,
22
+ tsv: `text/tab-separated-values${UTF8}`,
23
+ xml: `application/xml${UTF8}`,
24
+ vtt: `text/vtt${UTF8}`,
25
+ svg: "image/svg+xml",
26
+ png: "image/png",
27
+ jpg: "image/jpeg",
28
+ jpeg: "image/jpeg",
29
+ gif: "image/gif",
30
+ webp: "image/webp",
31
+ avif: "image/avif",
32
+ ico: "image/x-icon",
33
+ bmp: "image/bmp",
34
+ woff: "font/woff",
35
+ woff2: "font/woff2",
36
+ ttf: "font/ttf",
37
+ otf: "font/otf",
38
+ mp3: "audio/mpeg",
39
+ wav: "audio/wav",
40
+ ogg: "audio/ogg",
41
+ oga: "audio/ogg",
42
+ opus: "audio/ogg",
43
+ m4a: "audio/mp4",
44
+ flac: "audio/flac",
45
+ aac: "audio/aac",
46
+ mp4: "video/mp4",
47
+ m4v: "video/mp4",
48
+ webm: "video/webm",
49
+ ogv: "video/ogg",
50
+ wasm: "application/wasm",
51
+ pdf: "application/pdf",
52
+ glb: "model/gltf-binary",
53
+ gltf: `model/gltf+json${UTF8}`,
54
+ zip: "application/zip",
55
+ };
56
+ /** What a file whose extension isn't in the table is served as: a download. */
57
+ export const UNKNOWN_TYPE = "application/octet-stream";
58
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
59
+ export function extensionOf(path) {
60
+ const last = path.slice(path.lastIndexOf("/") + 1);
61
+ const dot = last.lastIndexOf(".");
62
+ return dot <= 0 ? "" : last.slice(dot + 1).toLowerCase();
63
+ }
64
+ /** The type a path is served with, and how. */
65
+ export function fileTypeOf(path) {
66
+ const extension = extensionOf(path);
67
+ const type = Object.hasOwn(TABLE, extension) ? TABLE[extension] : undefined;
68
+ if (type === undefined) {
69
+ return { type: UNKNOWN_TYPE, role: "file" };
70
+ }
71
+ const role = extension === "html" || extension === "htm"
72
+ ? "page"
73
+ : type.startsWith("text/javascript")
74
+ ? "script"
75
+ : "file";
76
+ return { type, role };
77
+ }
78
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
79
+ export const knownType = (path) => fileTypeOf(path).type !== UNKNOWN_TYPE;
80
+ /** Whether a path names a page: an `.html` file. */
81
+ export const isPagePath = (path) => fileTypeOf(path).role === "page";
82
+ /** Every extension the table knows, for the manual and tests. */
83
+ export const KNOWN_EXTENSIONS = Object.keys(TABLE);
@@ -0,0 +1,3 @@
1
+ import type { Gate } from "../config/capabilities.ts";
2
+ /** How a capability's gates read to the author: one sentence each. */
3
+ export declare function gateWords(gates: readonly Gate[], effect: string): string;
@@ -0,0 +1,19 @@
1
+ /** How a capability's gates read to the author: one sentence each. */
2
+ export function gateWords(gates, effect) {
3
+ const sentences = [];
4
+ if (gates.includes("consent")) {
5
+ sentences.push("The first data call asks the person to allow it; if they don't, every one fails with code denied (show that the data isn't allowed, not an error).");
6
+ }
7
+ if (gates.includes("confirm")) {
8
+ sentences.push(`The app shows the person ${effect} first, and nothing happens unless they confirm.`);
9
+ }
10
+ if (gates.includes("user-activation")) {
11
+ sentences.push("Call it from a click (it needs one).");
12
+ }
13
+ for (const gate of gates) {
14
+ if (typeof gate === "object") {
15
+ sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
16
+ }
17
+ }
18
+ return sentences.join(" ");
19
+ }
@@ -14,6 +14,8 @@ export type GuideTopic = BuiltInTopic | (string & {});
14
14
  export declare const ANY_HTTPS_SITE = "any https site";
15
15
  /** The copy of Plotly's map shapes (topojson) to give it, on jsDelivr (P078). */
16
16
  export declare const PLOTLY_TOPOJSON_URL = "https://cdn.jsdelivr.net/npm/plotly.js@3.4.0/dist/topojson/";
17
+ /** The built-in topics a config has: the capabilities topic only with a runtime (P085). */
18
+ export declare function builtInTopics(config: PortholeConfig): readonly BuiltInTopic[];
17
19
  /** The manual for `topics`, in the order asked (all built-in topics by default). */
18
20
  export declare function generateGuide(config: PortholeConfig, topics?: readonly GuideTopic[]): string;
19
21
  /** The description of the host's show tool, for the agent's tool list. */
@@ -1,11 +1,14 @@
1
1
  import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { BUILT_IN_TOPICS } from "../config/validate.js";
3
3
  import { anyHttps, declaredCapabilities, effectiveGates, egressOrigins, librarySources, } from "../compile/policy.js";
4
+ import { fileLimits, servesFiles } from "../files/paths.js";
4
5
  import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.js";
5
6
  import { shellPlan } from "../shell/plan.js";
6
7
  import { themeDefault } from "../theme/variables.js";
7
8
  import { GUIDE_EXAMPLES } from "./examples.js";
8
9
  import { manualLimits, sizeWords } from "./limits.js";
10
+ import { gateWords } from "./gates.js";
11
+ import { capabilitiesTopic, runtimeEntries, runtimeToolWords } from "./runtime.js";
9
12
  const VARIABLE = /--[a-z0-9]+(?:-[a-z0-9]+)*/gu;
10
13
  function context(config) {
11
14
  const variables = Object.keys(config.theme.variables);
@@ -54,6 +57,15 @@ const sourcesFor = (config, kind) => [
54
57
  ];
55
58
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
56
59
  const servesLibraries = (config) => librarySources(config).length > 0;
60
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
61
+ function files(config) {
62
+ if (!servesFiles(config)) {
63
+ return null;
64
+ }
65
+ const limits = fileLimits(config.limits);
66
+ const downloads = config.capabilities.downloadFile !== undefined;
67
+ return lines("Files: a page may come with files of its own (stylesheets, scripts and modules, images, fonts, data, workers, other pages), published beside it, with index.html the page it opens at.", '- Name them by relative path (./style.css, assets/app.js, data.json), never with a leading / or a full address: a page loads only its own version\'s files. fetch("./data.json") works; a module\'s imports and a worker\'s script resolve from the module (new Worker(new URL("./worker.js", import.meta.url))).', `- A link to another of your pages (about.html, or about; docs/ for docs/index.html) opens it in place. A link to any other file doesn't open: show an image with <img>${downloads ? `, offer a file with ${config.runtime === undefined ? "downloadFile" : "downloads.save"}` : ""}. A missing path shows your 404.html, if you publish one.`, "- Paths are case-sensitive, relative, with no .., //, \\, %, ? or #. Each file is served as its extension says (.html a page, .js and .mjs scripts, .css, .json, .txt, .svg, .png, .woff2, .mp4, …), never as what it holds; an extension the server doesn't know is a download.", '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.', `- At most ${limits.maxFiles.toLocaleString("en-US")} files, ${sizeWords(limits.maxFileBytes)} each (a page under ${sizeWords(config.limits.maxBytes)}) and ${sizeWords(limits.maxVersionBytes)} in all.`);
68
+ }
57
69
  /** What content may load, in prose, from the same origins the CSP lists. */
58
70
  function network(config) {
59
71
  const kinds = ["script", "style", "font", "img", "media", "connect"];
@@ -63,7 +75,7 @@ function network(config) {
63
75
  if (open.length === 0) {
64
76
  // A live widget's data comes from the app alone (P079), and its scripts from Porthole's copies.
65
77
  const data = declaredCapabilities(config).includes("readData")
66
- ? " Your data comes only from the app (readData)."
78
+ ? ` Your data comes only from the app (${config.runtime === undefined ? "readData" : "data.read"}).`
67
79
  : "";
68
80
  return servesLibraries(config)
69
81
  ? `Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline; the only scripts that load are the libraries below, from this frame's own address.${data}`
@@ -148,7 +160,7 @@ function widget(c) {
148
160
  const textSize = themeDefault(config.theme.variables["--font-text-md-size"] ?? "14px", "light").replace(/^(\d+(?:\.\d+)?)px$/u, "$1 px");
149
161
  return lines(`# ${title}${tool}`, "", what, "", `Where it runs: ${fills ? `in a sandboxed frame that fills the app's viewer (often smaller than the window: toolbars and side panels take room), about ${layout.narrowWidthPx} px wide on a phone (${layout.minWidthPx} on a small one) and wider on a desktop` : `in a sandboxed frame as wide as the column it sits in, about ${layout.narrowWidthPx} px on a phone (${layout.minWidthPx} on a small one) and ${layout.wideWidthPx} on a desktop`}; the same ${noun} is read on both, so never write for one of them. Design for ${layout.narrowWidthPx} first; where the layout depends on the width, read it as it runs (the ${fills ? "frame's own innerWidth, again on resize" : "box's clientWidth, again from a ResizeObserver"}). ${said("layout")} ${said("theme")} It runs again each time it is shown${loadsScripts(config) ? ": pin library versions" : ""}.`, "", "Sizes that read on a phone:", c.when(`- Words go in HTML (titles, notes, legends, readouts): it keeps its size and wraps. The frame's text is already ${textSize} --font-sans in --color-text-primary; notes --font-text-sm-size, never under 12 px.`), `- An SVG scales with the frame: its text shows at font-size × frame width ÷ viewBox width, so a 680-wide viewBox turns 12 into 5 px on a phone. Draw it for the phone: viewBox="0 0 ${viewBox} H", no text under 13, width="100%" style="max-width: 400px"; its text then shows at ${smallest} to ${largest} px on every screen. Or draw it 1 unit = 1 px with a script (topic chart).`, `- The frame never scrolls sideways: nothing fixed wider than ${layout.minWidthPx} px; images max-width: 100%; a grid or flex child with long text min-width: 0; a wide table or code block in its own box with overflow-x: auto.`, "- Cards in a row wrap (flex-wrap: wrap; flex: 1 1 100px), or a grid of repeat(auto-fit, minmax(160px, 1fr)): at most 2 columns under 500 px, never a fixed repeat(3, …).", "- Touch: anything clickable is at least 44 px tall. Phones don't hover: what a hover shows, a tap (click) shows too.", fills
150
162
  ? null
151
- : "- No position: fixed: the frame grows with its content, so a fixed element covers it.", "", "The sandbox:", ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`), `Keep it under ${sizeWords(limits.maxBytes)}.`, loadsScripts(config)
163
+ : "- No position: fixed: the frame grows with its content, so a fixed element covers it.", "", "The sandbox:", ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`), `Keep it under ${sizeWords(limits.maxBytes)}.`, servesFiles(config) ? "" : null, files(config), loadsScripts(config)
152
164
  ? "\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time."
153
165
  : null, ...ownCdns(config), ...ownLibraries(config), "", themeless
154
166
  ? `Colors: these variables hold the app's palette; use them, or colors of your own. Give the ${noun} its own background.`
@@ -214,25 +226,6 @@ function chart(c) {
214
226
  ? `\nBars in HTML, under a title like the line chart's:\n${GUIDE_EXAMPLES.bars}`
215
227
  : null);
216
228
  }
217
- /** How a capability's gates read to the author: one sentence each. */
218
- function gateWords(gates, effect) {
219
- const sentences = [];
220
- if (gates.includes("consent")) {
221
- sentences.push("The first data call asks the person to allow it; if they don't, every one fails with code denied (show that the data isn't allowed, not an error).");
222
- }
223
- if (gates.includes("confirm")) {
224
- sentences.push(`The app shows the person ${effect} first, and nothing happens unless they confirm.`);
225
- }
226
- if (gates.includes("user-activation")) {
227
- sentences.push("Call it from a click (it needs one).");
228
- }
229
- for (const gate of gates) {
230
- if (typeof gate === "object") {
231
- sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
232
- }
233
- }
234
- return sentences.join(" ");
235
- }
236
229
  /**
237
230
  * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
238
231
  * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
@@ -265,15 +258,28 @@ const ENTRIES = {
265
258
  annotate: (c) => `- Comments: the person may point at parts of the ${c.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${c.noun} is written again.`,
266
259
  reportError: (c) => `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
267
260
  resize: () => "",
261
+ // The runtime's own: taught as porthole.use's methods (runtimeEntries), never alone.
262
+ user: () => "",
263
+ comments: () => "",
264
+ artifact: () => "",
265
+ assets: () => "",
266
+ db: () => "",
268
267
  };
268
+ /** The shell's own capabilities, which content never calls by name: taught as they are. */
269
+ const SHELL_OWN = ["annotate", "reportError", "resize"];
269
270
  function interactive(c) {
270
271
  const { config, noun } = c;
271
- const entries = declaredCapabilities(config)
272
- .map((name) => {
273
- const own = config.capabilities[name]?.guide;
274
- return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
275
- })
276
- .filter((entry) => entry !== "");
272
+ // Under the capability runtime (P085), what content calls is porthole.use's methods.
273
+ const runtime = config.runtime !== undefined;
274
+ const entries = [
275
+ ...(runtime ? runtimeEntries(config) : []),
276
+ ...declaredCapabilities(config)
277
+ .filter((name) => !runtime || SHELL_OWN.includes(name) || config.capabilities[name]?.guide !== undefined)
278
+ .map((name) => {
279
+ const own = config.capabilities[name]?.guide;
280
+ return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
281
+ }),
282
+ ].filter((entry) => entry !== "");
277
283
  const stated = manualLimits(config, "");
278
284
  const stored = stated.find((limit) => limit.id === "storage");
279
285
  const state = stored === undefined ? null : `- ${stored.text}`;
@@ -290,17 +296,23 @@ const TOPICS = {
290
296
  widget,
291
297
  chart,
292
298
  interactive,
299
+ capabilities: (c) => capabilitiesTopic(c.config, c.noun),
293
300
  };
301
+ /** The built-in topics a config has: the capabilities topic only with a runtime (P085). */
302
+ export function builtInTopics(config) {
303
+ return BUILT_IN_TOPICS.filter((topic) => topic !== "capabilities" || config.runtime !== undefined);
304
+ }
294
305
  /** The manual for `topics`, in the order asked (all built-in topics by default). */
295
306
  export function generateGuide(config, topics) {
296
307
  const c = context(config);
297
308
  const own = config.guide.topics ?? {};
298
- return (topics ?? BUILT_IN_TOPICS)
309
+ return (topics ?? builtInTopics(config))
299
310
  .map((topic) => {
300
- if (Object.hasOwn(TOPICS, topic)) {
311
+ // A built-in topic the config has; a 0.6 config's own `capabilities` stays its own.
312
+ if (Object.hasOwn(TOPICS, topic) && builtInTopics(config).includes(topic)) {
301
313
  return TOPICS[topic](c);
302
314
  }
303
- const text = own[topic];
315
+ const text = Object.hasOwn(own, topic) ? own[topic] : undefined;
304
316
  if (text === undefined) {
305
317
  throw new RangeError(`No guide topic ${JSON.stringify(topic)}`);
306
318
  }
@@ -330,7 +342,7 @@ export function generateToolDescription(config) {
330
342
  : origins.length === 0
331
343
  ? `loading only ${fromAnywhere}`
332
344
  : `loading only from ${origins.join(", ")}${fromAnywhere === "" ? "" : `, and ${fromAnywhere}`}`;
333
- const globals = declaredCapabilities(config).flatMap((name) => {
345
+ const globals = (config.runtime === undefined ? declaredCapabilities(config) : []).flatMap((name) => {
334
346
  const spec = capabilitySpec(name);
335
347
  if (spec.global === undefined || !c.global(spec.global)) {
336
348
  return [];
@@ -357,5 +369,5 @@ export function generateToolDescription(config) {
357
369
  const theme = config.theme.documents === "never"
358
370
  ? "always in light (the app doesn't theme it)"
359
371
  : "in the person's light or dark theme through CSS variables";
360
- return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")}${read} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu, " ");
372
+ return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")} ${runtimeToolWords(config)}${read} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu, " ");
361
373
  }
@@ -114,15 +114,15 @@ export function manualLimits(config, network) {
114
114
  add("print", "window.print() does nothing.");
115
115
  }
116
116
  if (!tokens.includes("allow-downloads")) {
117
- add("downloads", `Downloads don't work: <a download>, data: and blob: links, saves from script.${declared.has("downloadFile") ? " To give the person a file, ask the app (ui/download-file; with the App SDK, app.downloadFile)." : ""}`);
117
+ add("downloads", `Downloads don't work: <a download>, data: and blob: links, saves from script.${!declared.has("downloadFile") ? "" : config.runtime !== undefined ? " To give the person a file: downloads.save (topic capabilities)." : " To give the person a file, ask the app (ui/download-file; with the App SDK, app.downloadFile)."}`);
118
118
  }
119
119
  if (!tokens.includes("allow-forms")) {
120
120
  add("forms", 'Forms never submit, and some browsers fire no submit event: use them as UI, give buttons type="button" and handle their click.');
121
121
  }
122
- add("link-schemes", `mailto:, tel: and sms: links open nothing: show the address or number as text${globals.has("copyText") ? " (with a copy button)" : ""}.`);
122
+ add("link-schemes", `mailto:, tel: and sms: links open nothing: show the address or number as text${globals.has("copyText") || (config.runtime !== undefined && declared.has("copyText")) ? " (with a copy button)" : ""}.`);
123
123
  if (!tokens.includes("allow-popups")) {
124
124
  add("windows", globals.has("openLink") || declared.has("openLink")
125
- ? "window.open and target=_blank open no window (window.open returns null or throws): links open in a new tab through the app (openLink; a click on <a href> does it)."
125
+ ? `window.open and target=_blank open no window (window.open returns null or throws): links open in a new tab through the app (${config.runtime === undefined ? "openLink" : "links.open"}; a click on <a href> does it).`
126
126
  : "Links to other pages, window.open and target=_blank open nothing (window.open returns null or throws).");
127
127
  }
128
128
  add("devices", "Camera, microphone, location and sharing are denied without asking (they reject, or aren't there); file inputs and FileReader work.");
@@ -131,7 +131,7 @@ export function manualLimits(config, network) {
131
131
  add("address", config.isolation === "opaque"
132
132
  ? `The ${it}'s address is about:srcdoc: it has no query string or hash to read.`
133
133
  : `The ${it}'s address is its own (with Porthole's one-time ticket), never the app's: read no parameters from it.`);
134
- add("shell", `document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : ""}.`);
134
+ add("shell", `document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : config.runtime !== undefined && declared.has("copyText") ? " (copy buttons call clipboard.copy)" : ""}.`);
135
135
  add("storage", config.isolation === "opaque"
136
136
  ? `State isn't saved: localStorage works but lasts only while the ${it} is on screen, and a reload or another device starts fresh. Keep what matters in the ${it}'s code.`
137
137
  : config.storage?.scope !== undefined
@@ -0,0 +1,13 @@
1
+ import { type CapabilityName } from "../config/capabilities.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ /** The prefix of the manual's line for a host function under the runtime (the agreement test's). */
4
+ export declare function runtimeEntryPrefix(serves: CapabilityName): string | null;
5
+ /**
6
+ * The interactive topic's lines under the runtime: one per host function the config serves to
7
+ * pages, as `porthole.use`'s methods, each with its level, whether it is declared, and its gates.
8
+ */
9
+ export declare function runtimeEntries(config: PortholeConfig): string[];
10
+ /** The tool description's words on the runtime. */
11
+ export declare function runtimeToolWords(config: PortholeConfig): string;
12
+ /** The capabilities topic: the call contract, declaring, levels, state, and each one's types. */
13
+ export declare function capabilitiesTopic(config: PortholeConfig, noun: string): string;