@botiverse/porthole 0.5.1 → 0.6.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 (73) hide show
  1. package/README.md +25 -0
  2. package/dist/bridge/bridge.js +8 -5
  3. package/dist/bridge/navigation.d.ts +1 -6
  4. package/dist/bridge/navigation.js +11 -0
  5. package/dist/check/check.d.ts +12 -3
  6. package/dist/check/check.js +54 -8
  7. package/dist/check/files.d.ts +26 -0
  8. package/dist/check/files.js +307 -0
  9. package/dist/check/lint.js +27 -10
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/tools.d.ts +23 -0
  12. package/dist/check/tools.js +25 -0
  13. package/dist/compile/policy.d.ts +15 -0
  14. package/dist/compile/policy.js +32 -0
  15. package/dist/config/schema.d.ts +8 -0
  16. package/dist/config/validate.js +8 -1
  17. package/dist/conformance/harness-source.js +1 -1
  18. package/dist/files/paths.d.ts +99 -0
  19. package/dist/files/paths.js +263 -0
  20. package/dist/files/types.d.ts +24 -0
  21. package/dist/files/types.js +83 -0
  22. package/dist/guide/guide.js +11 -1
  23. package/dist/host/create-host.js +21 -0
  24. package/dist/index.d.ts +6 -3
  25. package/dist/index.js +8 -3
  26. package/dist/protocol/adapter.d.ts +4 -0
  27. package/dist/protocol/mcp-apps.d.ts +6 -0
  28. package/dist/protocol/mcp-apps.js +6 -0
  29. package/dist/protocol/shell-adapter.js +5 -1
  30. package/dist/server/files.d.ts +44 -0
  31. package/dist/server/files.js +244 -0
  32. package/dist/server/host.d.ts +38 -1
  33. package/dist/server/host.js +37 -2
  34. package/dist/server/index.d.ts +4 -2
  35. package/dist/server/index.js +4 -1
  36. package/dist/server/keys.d.ts +8 -0
  37. package/dist/server/keys.js +34 -0
  38. package/dist/server/server.js +287 -22
  39. package/dist/server/types.d.ts +49 -5
  40. package/dist/shell/document.d.ts +19 -0
  41. package/dist/shell/document.js +30 -0
  42. package/dist/shell/runtime.d.ts +2 -1
  43. package/dist/shell/runtime.js +85 -4
  44. package/docs/ADOPTING.md +56 -4
  45. package/docs/ARCHITECTURE.md +13 -3
  46. package/docs/DECISIONS.md +304 -4
  47. package/docs/DESIGN.md +31 -3
  48. package/package.json +1 -1
  49. package/src/bridge/bridge.ts +8 -5
  50. package/src/bridge/navigation.ts +12 -0
  51. package/src/check/check.ts +92 -14
  52. package/src/check/files.ts +384 -0
  53. package/src/check/lint.ts +29 -10
  54. package/src/check/tools.ts +50 -0
  55. package/src/compile/policy.ts +38 -0
  56. package/src/config/schema.ts +8 -0
  57. package/src/config/validate.ts +8 -1
  58. package/src/files/paths.ts +323 -0
  59. package/src/files/types.ts +101 -0
  60. package/src/guide/guide.ts +20 -0
  61. package/src/host/create-host.ts +21 -0
  62. package/src/index.ts +32 -0
  63. package/src/protocol/adapter.ts +3 -1
  64. package/src/protocol/mcp-apps.ts +7 -0
  65. package/src/protocol/shell-adapter.ts +5 -0
  66. package/src/server/files.ts +312 -0
  67. package/src/server/host.ts +72 -3
  68. package/src/server/index.ts +19 -0
  69. package/src/server/keys.ts +53 -0
  70. package/src/server/server.ts +353 -24
  71. package/src/server/types.ts +56 -4
  72. package/src/shell/document.ts +53 -0
  73. package/src/shell/runtime.ts +85 -4
@@ -0,0 +1,99 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * A version made of files (P081): the rules a published path follows, the limits a version is
4
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
5
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
6
+ * only, never on a filesystem.
7
+ */
8
+ /** The most files a version holds, by default. */
9
+ export declare const DEFAULT_MAX_FILES = 1000;
10
+ /** The largest file of a version, bytes, by default (25 MiB). */
11
+ export declare const DEFAULT_MAX_FILE_BYTES: number;
12
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
13
+ export declare const DEFAULT_MAX_VERSION_BYTES: number;
14
+ /** The longest path, characters, and the longest segment of one. */
15
+ export declare const MAX_FILE_PATH_CHARS = 512;
16
+ export declare const MAX_SEGMENT_CHARS = 255;
17
+ /** The page a version opens at by default. */
18
+ export declare const DEFAULT_ENTRY = "index.html";
19
+ /**
20
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
21
+ * origin of its own. Opaque frames have no origin to serve them from.
22
+ */
23
+ export declare const servesFiles: (config: PortholeConfig) => boolean;
24
+ export interface FileLimits {
25
+ readonly maxFiles: number;
26
+ readonly maxFileBytes: number;
27
+ readonly maxVersionBytes: number;
28
+ }
29
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
30
+ export declare function fileLimits(limits?: Partial<Limits> | null): FileLimits;
31
+ /**
32
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
33
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
34
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
35
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
36
+ */
37
+ export declare function filePathProblem(path: unknown): string | null;
38
+ /** A published path's metadata, as far as the checks read it. */
39
+ export interface FileSetEntryLike {
40
+ readonly size: number;
41
+ }
42
+ export interface FileSetProblem {
43
+ /** The path it is about, where it is about one. */
44
+ readonly path?: string;
45
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
46
+ /** What to change, for the agent or the person publishing. */
47
+ readonly message: string;
48
+ }
49
+ /**
50
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
51
+ * two paths that differ only in case, and no path that is both a file and a directory; the
52
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
53
+ * `fileLimits`). Empty when it may be published.
54
+ */
55
+ export declare function checkFileSet(files: Readonly<Record<string, FileSetEntryLike>>, options?: {
56
+ readonly entry?: string;
57
+ readonly limits?: FileLimits;
58
+ }): FileSetProblem[];
59
+ /**
60
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
61
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
62
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
63
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
64
+ * `/` stays (a directory).
65
+ */
66
+ export declare function requestFilePath(raw: string): string | null;
67
+ /** What a request's path finds in a version's manifest. */
68
+ export type FileLookup =
69
+ /** The file to answer with, and its status (404 for a `404.html`). */
70
+ {
71
+ readonly kind: "file";
72
+ readonly path: string;
73
+ readonly status: 200 | 404;
74
+ }
75
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
76
+ | {
77
+ readonly kind: "redirect";
78
+ readonly to: string;
79
+ }
80
+ /** Nothing: a plain 404. */
81
+ | {
82
+ readonly kind: "none";
83
+ };
84
+ export interface LookupOptions {
85
+ /** The page the version opens at (default `index.html`). */
86
+ readonly entry?: string;
87
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
88
+ readonly spa?: boolean;
89
+ /** Whether the request is a navigation (a page loading), not a subresource. */
90
+ readonly navigation: boolean;
91
+ }
92
+ /**
93
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
94
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
95
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
96
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
97
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
98
+ */
99
+ export declare function lookupFile(has: (path: string) => boolean, path: string, options: LookupOptions): FileLookup;
@@ -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);
@@ -1,6 +1,7 @@
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";
@@ -54,6 +55,15 @@ const sourcesFor = (config, kind) => [
54
55
  ];
55
56
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
56
57
  const servesLibraries = (config) => librarySources(config).length > 0;
58
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
59
+ function files(config) {
60
+ if (!servesFiles(config)) {
61
+ return null;
62
+ }
63
+ const limits = fileLimits(config.limits);
64
+ const downloads = config.capabilities.downloadFile !== undefined;
65
+ 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 downloadFile" : ""}. 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.`);
66
+ }
57
67
  /** What content may load, in prose, from the same origins the CSP lists. */
58
68
  function network(config) {
59
69
  const kinds = ["script", "style", "font", "img", "media", "connect"];
@@ -148,7 +158,7 @@ function widget(c) {
148
158
  const textSize = themeDefault(config.theme.variables["--font-text-md-size"] ?? "14px", "light").replace(/^(\d+(?:\.\d+)?)px$/u, "$1 px");
149
159
  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
160
  ? 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)
161
+ : "- 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
162
  ? "\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
163
  : null, ...ownCdns(config), ...ownLibraries(config), "", themeless
154
164
  ? `Colors: these variables hold the app's palette; use them, or colors of your own. Give the ${noun} its own background.`
@@ -2,6 +2,7 @@ import { ANNOTATE_METHODS, } from "../annotate/types.js";
2
2
  import { annotateMode, checkMarks, parseReport } from "../annotate/validate.js";
3
3
  import { createBridge, onceConsent } from "../bridge/bridge.js";
4
4
  import { compile } from "../compile/compile.js";
5
+ import { servesFiles } from "../files/paths.js";
5
6
  import { declaredCapabilities, effectiveGates } from "../compile/policy.js";
6
7
  import { isRefused } from "../bridge/refusal.js";
7
8
  import { capabilitySpec } from "../config/capabilities.js";
@@ -13,6 +14,8 @@ import { shellAdapter } from "../protocol/shell-adapter.js";
13
14
  import { resolveTheme } from "../theme/variables.js";
14
15
  /** How long a display may take to load before its outcome is a timeout, by default. */
15
16
  const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
17
+ /** How long a set's page said its next load is another of its pages (P084), ms. */
18
+ const PAGE_OF_SET_MS = 10_000;
16
19
  /** How many times a display is started again after its content navigated its frame away. */
17
20
  const MAX_RESTARTS = 3;
18
21
  const BASE_KEYS = new Set(["hostContextChanged", "teardown", "close"]);
@@ -80,6 +83,8 @@ export function createHost(config, options = {}) {
80
83
  let connection = null;
81
84
  let destroyed = false;
82
85
  let restarts = 0;
86
+ // Until when the frame's next load is another page of its own set, as its content said (P084).
87
+ let pageOfSetUntil = 0;
83
88
  let generation = 0;
84
89
  // The viewer's answer for this display (P079): asked once, kept across its frames; or the
85
90
  // host's refusal of them all (P080).
@@ -268,6 +273,7 @@ export function createHost(config, options = {}) {
268
273
  };
269
274
  const stop = () => {
270
275
  handshaken = false;
276
+ pageOfSetUntil = 0;
271
277
  abort?.abort();
272
278
  abort = null;
273
279
  outcomeWatch?.stop();
@@ -337,6 +343,14 @@ export function createHost(config, options = {}) {
337
343
  hostInfo,
338
344
  hostContext,
339
345
  emit: (event) => {
346
+ if (event.type === "navigating") {
347
+ // Only a display whose pages may come with files (P084), for the next load only, and
348
+ // only soon: content can't bank it to skip a restart later (P031).
349
+ if (servesFiles(config)) {
350
+ pageOfSetUntil = Date.now() + PAGE_OF_SET_MS;
351
+ }
352
+ return;
353
+ }
340
354
  if (event.type === "initialized") {
341
355
  watch.initialized();
342
356
  if (!handshaken) {
@@ -353,6 +367,13 @@ export function createHost(config, options = {}) {
353
367
  opened[name]?.(...args);
354
368
  }
355
369
  created.onNavigated(() => {
370
+ // Another page of the content's own set (P084): the same content, still connected (the
371
+ // new page's shell says hello again on the same transport). Not a restart.
372
+ const ofSet = pageOfSetUntil > Date.now();
373
+ pageOfSetUntil = 0;
374
+ if (ofSet) {
375
+ return;
376
+ }
356
377
  emit("navigated", undefined);
357
378
  if (restarts < MAX_RESTARTS) {
358
379
  restarts += 1;
package/dist/index.d.ts CHANGED
@@ -11,8 +11,10 @@ export { hostOriginProblem, isHostOrigin } from "./isolation/served.ts";
11
11
  export { FRAME_STATUS_METHOD } from "./isolation/types.ts";
12
12
  export { LIBRARY_CDNS, presets, type PresetName, type LiveWidgetOptions, type PresetOptions, type UrlPresetOptions, } from "./presets/presets.ts";
13
13
  export { LIBRARY_PATH, VENDORED_LIBRARIES, libraryPath, licensePath, type VendoredLibrary, } from "./libraries/libraries.ts";
14
+ export { checkFileSet, DEFAULT_ENTRY, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_FILES, DEFAULT_MAX_VERSION_BYTES, fileLimits, filePathProblem, lookupFile, requestFilePath, servesFiles, type FileLimits, type FileLookup, type FileSetProblem, } from "./files/paths.ts";
15
+ export { fileTypeOf, KNOWN_EXTENSIONS, UNKNOWN_TYPE, type FileRole, type FileType, } from "./files/types.ts";
14
16
  export { compile, type CompiledConfig } from "./compile/compile.ts";
15
- export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, type CspDirective, type EgressKind, } from "./compile/policy.ts";
17
+ export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, FILE_SET_DIRECTIVES, fileSetCspDirectives, INERT_FILE_CSP, type CspDirective, type EgressKind, } from "./compile/policy.ts";
16
18
  export { shellPlan, type ShellPlan } from "./shell/plan.ts";
17
19
  export type { ShellDocumentOptions } from "./shell/document.ts";
18
20
  export { generateGuide, generateToolDescription, type BuiltInTopic, type GuideTopic, } from "./guide/guide.ts";
@@ -22,14 +24,15 @@ export type { FrameLocation, FrameSource, InstanceLocator, InstanceRef, ServedDo
22
24
  export type { PlatformHost, Surface, SurfaceSpec } from "./platform/types.ts";
23
25
  export type { Transport } from "./transport/types.ts";
24
26
  export type { AdapterConnection, AdapterEvent, AdapterSession, ProtocolAdapter, ShellConnection, } from "./protocol/adapter.ts";
25
- export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, NAVIGATION_BLOCKED_METHOD, PORTHOLE_STYLES, STALE_META, type HostContext, } from "./protocol/mcp-apps.ts";
27
+ export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, NAVIGATING_METHOD, NAVIGATION_BLOCKED_METHOD, PORTHOLE_STYLES, STALE_META, type HostContext, } from "./protocol/mcp-apps.ts";
26
28
  export { REFUSAL_CODES, Refused, isRefused, type RefusalCode, type RefusalReason, } from "./bridge/refusal.ts";
27
29
  export type { CallContext, CallOptions, CallOutcome, CapabilityHandler, CapabilityHandlers, Confirm, ConfirmAnswer, ConfirmDisplay, ConfirmRequest, Consent, DataCache, Proceed, HostFunctionBridge, Refusal, SubscriptionContext, } from "./bridge/types.ts";
28
30
  export { createHost } from "./host/create-host.ts";
29
31
  export { entryTarget, frameFallback, portholeClient, type ContentClientMeta, type FrameFallback, type PortholeClient, type PortholeClientOptions, } from "./host/client.ts";
30
32
  export { defineDisplays, type DisplayKind, type Displays } from "./displays/displays.ts";
31
33
  export { fragmentOf, lintContent, type Finding, type LintRule } from "./check/lint.ts";
32
- export { admitContent, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, type AdmitResult, type JsonSchema, type ToolDefinition, } from "./check/tools.ts";
34
+ export { lintFiles, type FileContents, type FileFinding } from "./check/files.ts";
35
+ export { admitContent, admitFiles, type AdmitFilesResult, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, type AdmitResult, type JsonSchema, type ToolDefinition, } from "./check/tools.ts";
33
36
  export { writeClipboard } from "./host/clipboard.ts";
34
37
  export { httpLocator, LocateError, servedOrOpaque, type HttpLocatorOptions, type ServedMeta, } from "./host/locator.ts";
35
38
  export type { AnnotationControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
package/dist/index.js CHANGED
@@ -12,15 +12,18 @@ export { FRAME_STATUS_METHOD } from "./isolation/types.js";
12
12
  // Presets.
13
13
  export { LIBRARY_CDNS, presets, } from "./presets/presets.js";
14
14
  export { LIBRARY_PATH, VENDORED_LIBRARIES, libraryPath, licensePath, } from "./libraries/libraries.js";
15
+ // A version made of files (P081): the rules its paths follow, its limits and its types.
16
+ export { checkFileSet, DEFAULT_ENTRY, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_FILES, DEFAULT_MAX_VERSION_BYTES, fileLimits, filePathProblem, lookupFile, requestFilePath, servesFiles, } from "./files/paths.js";
17
+ export { fileTypeOf, KNOWN_EXTENSIONS, UNKNOWN_TYPE, } from "./files/types.js";
15
18
  // The compiler.
16
19
  export { compile } from "./compile/compile.js";
17
- export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, } from "./compile/policy.js";
20
+ export { allEgressOrigins, anyHttps, declaredCapabilities, effectiveGates, egressOrigins, embedderCsp, embedderFrameSourcesOf, FILE_SET_DIRECTIVES, fileSetCspDirectives, INERT_FILE_CSP, } from "./compile/policy.js";
18
21
  export { shellPlan } from "./shell/plan.js";
19
22
  export { generateGuide, generateToolDescription, } from "./guide/guide.js";
20
23
  export { GUIDE_EXAMPLES } from "./guide/examples.js";
21
24
  // Theme.
22
25
  export { CHART_PALETTE, DEFAULT_THEME, DEFAULT_THEME_EVENT, DEFAULT_THEME_VARIABLES, resolveTheme, themeDefault, } from "./theme/variables.js";
23
- export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, NAVIGATION_BLOCKED_METHOD, PORTHOLE_STYLES, STALE_META, } from "./protocol/mcp-apps.js";
26
+ export { COPY_TEXT_METHOD, MCP_APPS_METHODS, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_STYLE_VARIABLES, NAVIGATING_METHOD, NAVIGATION_BLOCKED_METHOD, PORTHOLE_STYLES, STALE_META, } from "./protocol/mcp-apps.js";
24
27
  // Why a call was refused, as content is told it, and the host's own refusals (P080).
25
28
  export { REFUSAL_CODES, Refused, isRefused, } from "./bridge/refusal.js";
26
29
  export { createHost } from "./host/create-host.js";
@@ -29,7 +32,9 @@ export { entryTarget, frameFallback, portholeClient, } from "./host/client.js";
29
32
  export { defineDisplays } from "./displays/displays.js";
30
33
  // The agent's side: what content can be told without running it, and its tools (P073).
31
34
  export { fragmentOf, lintContent } from "./check/lint.js";
32
- export { admitContent, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, } from "./check/tools.js";
35
+ // A page that comes with files (P081): its lint, without running it.
36
+ export { lintFiles } from "./check/files.js";
37
+ export { admitContent, admitFiles, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, } from "./check/tools.js";
33
38
  export { writeClipboard } from "./host/clipboard.js";
34
39
  export { httpLocator, LocateError, servedOrOpaque, } from "./host/locator.js";
35
40
  // Annotations (P053): anchors, what a frame reports, and the host's checks on both.
@@ -47,6 +47,10 @@ export type AdapterEvent =
47
47
  /** The view asked to be closed. */
48
48
  | {
49
49
  readonly type: "teardown-requested";
50
+ }
51
+ /** A page that came with files is opening another page of its set in the frame (P084). */
52
+ | {
53
+ readonly type: "navigating";
50
54
  };
51
55
  /** What the framework drives on every adapter. Adapters add their protocol's own operations. */
52
56
  export interface AdapterConnection {