@dasl/tile-loader 3.1.0 → 4.0.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 (92) hide show
  1. package/README.md +1463 -36
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +582 -90
  5. package/dist/at.js.map +1 -1
  6. package/dist/car.d.ts +21 -2
  7. package/dist/car.d.ts.map +1 -1
  8. package/dist/car.js +82 -15
  9. package/dist/car.js.map +1 -1
  10. package/dist/content-scheme.d.ts +17 -3
  11. package/dist/content-scheme.d.ts.map +1 -1
  12. package/dist/content-scheme.js +32 -6
  13. package/dist/content-scheme.js.map +1 -1
  14. package/dist/guard.d.ts +342 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +1544 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +416 -16
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +999 -74
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/cid.d.ts +25 -0
  23. package/dist/lib/cid.d.ts.map +1 -0
  24. package/dist/lib/cid.js +65 -0
  25. package/dist/lib/cid.js.map +1 -0
  26. package/dist/lib/defaults.d.ts +8 -0
  27. package/dist/lib/defaults.d.ts.map +1 -0
  28. package/dist/lib/defaults.js +14 -0
  29. package/dist/lib/defaults.js.map +1 -0
  30. package/dist/lib/destinations.d.ts +25 -0
  31. package/dist/lib/destinations.d.ts.map +1 -0
  32. package/dist/lib/destinations.js +94 -0
  33. package/dist/lib/destinations.js.map +1 -0
  34. package/dist/lib/drisl.d.ts +10 -0
  35. package/dist/lib/drisl.d.ts.map +1 -0
  36. package/dist/lib/drisl.js +169 -0
  37. package/dist/lib/drisl.js.map +1 -0
  38. package/dist/lib/errors.d.ts +80 -0
  39. package/dist/lib/errors.d.ts.map +1 -0
  40. package/dist/lib/errors.js +44 -0
  41. package/dist/lib/errors.js.map +1 -0
  42. package/dist/lib/fetching.d.ts +24 -0
  43. package/dist/lib/fetching.d.ts.map +1 -0
  44. package/dist/lib/fetching.js +135 -0
  45. package/dist/lib/fetching.js.map +1 -0
  46. package/dist/lib/limits.d.ts +34 -0
  47. package/dist/lib/limits.d.ts.map +1 -0
  48. package/dist/lib/limits.js +33 -0
  49. package/dist/lib/limits.js.map +1 -0
  50. package/dist/lib/pointer.d.ts +83 -0
  51. package/dist/lib/pointer.d.ts.map +1 -0
  52. package/dist/lib/pointer.js +244 -0
  53. package/dist/lib/pointer.js.map +1 -0
  54. package/dist/lib/tab-order.d.ts +16 -0
  55. package/dist/lib/tab-order.d.ts.map +1 -0
  56. package/dist/lib/tab-order.js +66 -0
  57. package/dist/lib/tab-order.js.map +1 -0
  58. package/dist/link.d.ts +110 -13
  59. package/dist/link.d.ts.map +1 -1
  60. package/dist/link.js +336 -43
  61. package/dist/link.js.map +1 -1
  62. package/dist/memory.d.ts +1 -0
  63. package/dist/memory.d.ts.map +1 -1
  64. package/dist/memory.js +5 -0
  65. package/dist/memory.js.map +1 -1
  66. package/dist/mount.d.ts +54 -0
  67. package/dist/mount.d.ts.map +1 -0
  68. package/dist/mount.js +289 -0
  69. package/dist/mount.js.map +1 -0
  70. package/dist/size.d.ts +43 -2
  71. package/dist/size.d.ts.map +1 -1
  72. package/dist/size.js +296 -15
  73. package/dist/size.js.map +1 -1
  74. package/package.json +13 -3
  75. package/src/at.ts +590 -84
  76. package/src/car.ts +79 -16
  77. package/src/content-scheme.ts +38 -7
  78. package/src/guard.ts +1659 -0
  79. package/src/index.ts +1124 -74
  80. package/src/lib/cid.ts +65 -0
  81. package/src/lib/defaults.ts +12 -0
  82. package/src/lib/destinations.ts +79 -0
  83. package/src/lib/drisl.ts +160 -0
  84. package/src/lib/errors.ts +111 -0
  85. package/src/lib/fetching.ts +138 -0
  86. package/src/lib/limits.ts +61 -0
  87. package/src/lib/pointer.ts +290 -0
  88. package/src/lib/tab-order.ts +66 -0
  89. package/src/link.ts +365 -48
  90. package/src/memory.ts +5 -0
  91. package/src/mount.ts +359 -0
  92. package/src/size.ts +304 -16
package/src/index.ts CHANGED
@@ -36,7 +36,8 @@ The tile-loading architecture has four levels that all communicate together:
36
36
  */
37
37
 
38
38
  import { el } from "./lib/el.js";
39
- import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
39
+ import { TileLoadError } from "./lib/errors.js";
40
+ import { tileResponseHeaders, dockPath, tileSandbox, refusableFeatures, isCidLabel } from "@dasl/tile-lexicon";
40
41
  import type { AnyMasl, MaslHeaders, MaslResponse } from "@dasl/tile-lexicon";
41
42
 
42
43
  export interface MothershipConfig {
@@ -56,20 +57,108 @@ export interface MothershipConfig {
56
57
  namedOrigin?: string;
57
58
  /** @deprecated The old name of `namedOrigin`. It goes in the next major version. */
58
59
  tileHost?: string;
60
+ /**
61
+ * Whether a tile runs on the origin its own content names: `<cid>.<base>`,
62
+ * where `<cid>` is the CID of the tile's manifest, as its loader computed
63
+ * it from the bytes it loaded (the record's `tile` on AT, the header of a
64
+ * .tile file). Such an origin is kept: what the tile stores there it finds
65
+ * again the next time it runs, on any page of the same site. It is shared
66
+ * by every run of that tile on that site, and a new version of the tile,
67
+ * which has another manifest, starts on another origin, with nothing.
68
+ *
69
+ * Anyone can name such an origin, so the loading server's runtime holds it
70
+ * to the one tile whose manifest it is named by, and the loader runs a
71
+ * tile there only when the loading server says that its runtime does. A
72
+ * tile its loader has no manifest bytes for (a webxdc tile, one in memory)
73
+ * runs on an origin made for the load, as without this; `tile.ephemeral`
74
+ * says which. False when left out. Not with `namedOrigin`.
75
+ */
76
+ cidOrigins?: boolean;
59
77
  /**
60
78
  * Whether the shuttle spends the renderer's WebRTC budget before the tile
61
79
  * loads (the default). A host that blocks WebRTC itself (an Electron app with
62
80
  * the policy switches set, say) passes 'none' and skips the cost.
63
81
  */
64
82
  webrtcGuard?: 'exhaust' | 'none';
83
+ /**
84
+ * How long a tile gets to start, in milliseconds: counted from when its
85
+ * frame is attached, and again from when that frame loads; time that the
86
+ * frame spends out of the document is not counted. A tile whose root
87
+ * document has not been handed to its runtime by then fires an `error`
88
+ * event with the reason `timeout`. The deadline only reports: nothing is
89
+ * stopped, and a tile that was merely slow goes on to load. 15 seconds
90
+ * when left out; `0` for no deadline.
91
+ */
92
+ startDeadline?: number;
93
+ /** What one tile may ask of this page (see TileBudget). */
94
+ budget?: TileBudget;
95
+ }
96
+
97
+ /**
98
+ * What one tile may ask of the page that runs it. A tile's messages, and the
99
+ * resolving of its resources, are handled on the host page's main thread,
100
+ * which the page and every tile on it share: these keep one tile from taking
101
+ * it all. Each is for one tile, for as long as it is in one frame: rendered
102
+ * again, a tile starts afresh. `Infinity` lifts a limit.
103
+ */
104
+ export interface TileBudget {
105
+ /**
106
+ * How many messages a tile may send in a second, over time. Its requests
107
+ * for its own resources are not counted here. What is over is dropped.
108
+ * 200 when left out.
109
+ */
110
+ messagesPerSecond?: number;
111
+ /** How many it may send at once, before that rate holds it. 400. */
112
+ messageBurst?: number;
113
+ /** How many of a tile's resources are resolved at one time; further requests wait their turn. 16. */
114
+ requestsInFlight?: number;
115
+ /** How many requests may be waiting; a tile that asks for more is refused them. 2000. */
116
+ requestsQueued?: number;
117
+ /** How many lines a tile may have logged to the console. 10. */
118
+ logLines?: number;
65
119
  }
66
120
 
121
+ /**
122
+ * What a host can ask of a load: the tile it expects, by CID. A page that
123
+ * embeds a tile someone posted holds what was posted, and the tile's address
124
+ * only says where it is now. With a CID, a tile that is not the one expected
125
+ * is not loaded: the load fails with a TileLoadError, `record-changed`.
126
+ */
127
+ export interface TileLoadOptions {
128
+ /** The CID of the tile's record, as a strong reference to it carries. It changes whenever the record is written again, as it stands or not. */
129
+ cid?: string;
130
+ /** The CID of the tile's manifest alone: the content, whatever record carries it. With both, either will do. */
131
+ manifestCid?: string;
132
+ }
133
+ /**
134
+ * Which tile this is, as its loader worked it out from the bytes it was
135
+ * given, and never from what a server said they were.
136
+ */
137
+ export interface TileIdentity {
138
+ /** The CID of the record or file the tile was made from. */
139
+ cid?: string;
140
+ /** The CID of its manifest alone. */
141
+ manifestCid?: string;
142
+ /** Whether it was checked against a CID its host expected. */
143
+ pinned?: boolean;
144
+ /**
145
+ * The bytes of its manifest as its source holds them (DRISL), and their
146
+ * CID: the record's `tile` on AT (`manifestCid`), a .tile file's header
147
+ * (`cid`). What names the origin of a tile whose mothership runs tiles
148
+ * on the origin named by their CID (`cidOrigins`), and what the runtime
149
+ * there is handed to check it against.
150
+ */
151
+ manifestBytes?: { cid: string; bytes: Uint8Array };
152
+ }
67
153
  export interface TileLoader {
68
- load (url: string, mothership: TileMothership): Promise<Tile | false | undefined>;
154
+ load (url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false | undefined>;
69
155
  }
70
156
  export interface TilePathLoader {
71
157
  resolvePath (path: string): Promise<MaslResponse>;
72
158
  }
159
+ // What a loader says went wrong, for a host to tell one failure from another.
160
+ export { TileLoadError } from "./lib/errors.js";
161
+ export type { TileLoadErrorCode, TileLoadErrorDetails, TileLoadErrorEvent, TileLoadFailure } from "./lib/errors.js";
73
162
 
74
163
  const TILES_PFX = 'tiles-';
75
164
  const SHUTTLE_PFX = 'tiles-shuttle-';
@@ -81,6 +170,20 @@ const SND_SHUTTLE_CLOSE = `${SHUTTLE_PFX}close`; // we are done with this til
81
170
  const RCV_SHUTTLE_CLOSED = `${SHUTTLE_PFX}closed`; // it has
82
171
  // How long a runtime gets to clean up after itself before its frame goes anyway.
83
172
  const CLOSE_MS = 2500;
173
+ // How long the wiping of an origin gets when it is asked for from a frame of
174
+ // our own (TileMothership.wipeOrigin), before it is given up on and counted
175
+ // as not done. A guess, and a generous one: nothing waits on it but the
176
+ // promise close() returns, and it has to cover a slow network and a tile
177
+ // that holds its own pages up on their way out.
178
+ const WIPE_MS = 10000;
179
+ // How long after an origin was wiped it is wiped once more (Tile.close()).
180
+ // The first wipe comes after everything the tile's pages did, but a worker
181
+ // of the tile's has a thread of its own, and a browser can take a moment to
182
+ // stop one after its page is gone (up to two seconds, in Chromium): what it
183
+ // writes in that moment lands on an origin that was just wiped. A guess,
184
+ // with a margin over that. A wipe that did not go through the first time
185
+ // gets its second chance then too.
186
+ const WIPE_AGAIN_MS = 3000;
84
187
  const WORKER_PFX = 'tiles-worker-';
85
188
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
86
189
  const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
@@ -89,13 +192,63 @@ const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
89
192
  const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
90
193
  const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
91
194
  const RCV_DOCK_STOPPED = 'tiles-dock-stopped'; // the dock stopped the tile
195
+ const RCV_DOCK_READY = 'tiles-dock-ready'; // the dock is there, and of which generation
196
+ // The generations of the runtime this loader speaks: what a dock names when
197
+ // it says it is ready (see GENERATION in @dasl/tile-server's dock.js). A dock
198
+ // from before that message names none, and is taken as it comes.
199
+ const GENERATIONS: readonly unknown[] = [3];
92
200
  // Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
93
201
  // relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
94
202
  // `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
95
203
  const PROTOCOL_UP = 'tiles-protocol-up-';
96
204
  const PROTOCOL_DOWN = 'tiles-protocol-down-';
97
- // Warnings and errors come as a list; anything else is logged as it is.
98
- const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg : [msg]);
205
+ // Warnings and errors come as a list of things to log; anything else is
206
+ // logged as it is. The runtime's own lists are two or three texts, but the
207
+ // tile can have its runtime say anything, and a console writes out what it
208
+ // is handed: every entry, and some things in full each time they are there,
209
+ // however little it took to say them. So the first few entries are logged,
210
+ // however many the list says it has, and of those what is a text, a number
211
+ // or a boolean; anything else is named by its kind ("[object Array]").
212
+ const LOG_MAX = 8;
213
+ const loggable = (v: unknown): unknown => (
214
+ v === undefined || v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
215
+ ? v
216
+ : Object.prototype.toString.call(v)
217
+ );
218
+ const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg.slice(0, LOG_MAX) : [msg]).map(loggable);
219
+ // How long a tile gets to start before its host is told that it has not
220
+ // (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
221
+ // nothing wrong with it has been seen to take eight seconds.
222
+ const START_DEADLINE_MS = 15000;
223
+ // The sandbox of the frame renderContent() makes, when its host says none:
224
+ // what a tile needs to run, and forms to submit to itself. No dialogs and no
225
+ // downloads, which the runtime would grant (see renderContent()).
226
+ const FRAME_SANDBOX = 'allow-scripts allow-same-origin allow-forms';
227
+ // What the frame renderContent() makes refuses a tile when its host says
228
+ // nothing of it: synchronous requests. One holds up the thread the tile
229
+ // shares with its runtime and gets the tile nothing: its own files never
230
+ // come that way, since Chrome and Safari do not hand such a request to the
231
+ // tile's worker, and Firefox hands it to a worker whose answer has to come
232
+ // through that same thread. What is lost is a synchronous request for a
233
+ // blob: or data: address.
234
+ const FRAME_REFUSE: readonly string[] = ['sync-xhr'];
235
+ /**
236
+ * The features a host can refuse a tile (`FrameOptions.refuse`), by name:
237
+ * `refusableFeatures` in @dasl/tile-lexicon. They are those of its user's
238
+ * devices and attention that the runtime hands on to a tile whose host's
239
+ * frame allows them, and those a browser gives every frame unasked
240
+ * (picture-in-picture, the gamepad, synchronous requests, the client hints
241
+ * and more), which a tile keeps unless they are refused. `refuse: REFUSABLE`
242
+ * refuses all of them. Chrome knows every name; Firefox and Safari go by the
243
+ * names they know and pass over the others, so the same list refuses less
244
+ * there (the README says what, in each).
245
+ */
246
+ export const REFUSABLE: readonly string[] = refusableFeatures;
247
+ // A timer is set for no longer than this: a longer wait comes round to none.
248
+ const MAX_TIMER_MS = 2 ** 31 - 1;
249
+ // A frame that is out of the document when its deadline passes is looked at
250
+ // again later, and no sooner than this, however short the deadline.
251
+ const OUT_MS = 1000;
99
252
 
100
253
  /**
101
254
  * The dock stopped a tile, because its runtime tried to leave the frame it
@@ -107,11 +260,180 @@ export interface StoppedEvent extends Event {
107
260
  reason: 'blocked' | 'navigated';
108
261
  }
109
262
 
263
+ /**
264
+ * A tile is not starting. `reason` says what is known of why:
265
+ *
266
+ * - `timeout`: the deadline (`startDeadline`) passed before the tile's root
267
+ * document was handed to its runtime. `stage` says what the tile was
268
+ * waiting for: `dock` (nothing was heard from its frame at all: the loading
269
+ * server is down, or out of reach, or not answering), `shuttle` (the dock
270
+ * was there: the tile's origin refuses the connection or cannot be found,
271
+ * or the runtime on it never ran), `worker` (the runtime was there, its
272
+ * service worker had not said it was ready), `content` (the tile had
273
+ * loaded, in the sense of the `load` event, and its root document had not
274
+ * arrived). Two cases give no way to tell the first two apart, and are
275
+ * `dock`: a loading server from before its dock said it was ready, and a
276
+ * tile origin that takes the connection and never answers, as nothing is
277
+ * heard from a frame before it has loaded. Nothing is stopped: the tile
278
+ * may yet load, and fire `load` after its `error`.
279
+ * - `version`: the dock named a generation of the runtime that this loader
280
+ * does not speak (`generation`): the loader in the page and the loading
281
+ * server are too far apart. Nothing is stopped here either, but little
282
+ * can be expected of the tile. For a tile on the origin named by its CID
283
+ * (`cidOrigins`), also: the dock did not say that its runtime holds such
284
+ * an origin to its tile. That tile is not run there.
285
+ * - `worker`: the runtime could not start the tile's service worker. Some
286
+ * browsers refuse one to a frame of another site once the user blocks
287
+ * cross-site storage.
288
+ * - `unsupported`: the browser lacks what the runtime needs.
289
+ * - `content`: the tile's root document is not to be had: resolving it
290
+ * failed, or the tile's worker gave up waiting for it (after a minute: a
291
+ * deadline shorter than that has reported it first, as `timeout`).
292
+ * - `integrity`: the runtime on the origin named by the tile's CID refused
293
+ * the manifest it was handed: it is not the one that CID names, or not
294
+ * one it could read (a .tile file whose header is not in DRISL's one
295
+ * form). Nothing is served there.
296
+ *
297
+ * A start (a frame the tile is attached to, each time it loads) fires one at
298
+ * most. `worker` and `unsupported` are the runtime's own account, which
299
+ * passes through the tile's origin on its way here, and a dock passes on what
300
+ * its frame says under any name: what runs on that origin can have the start
301
+ * reported as failed, for any of these reasons. On an origin made for the
302
+ * one load nothing of the tile's runs before it has started, and no other
303
+ * tile is there; tiles that share a named origin can do it to one another.
304
+ */
305
+ export interface TileErrorEvent extends Event {
306
+ reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content' | 'integrity';
307
+ /** With `timeout`: what the tile was still waiting for. */
308
+ stage?: 'dock' | 'shuttle' | 'worker' | 'content';
309
+ /** With `version`: the generation the dock named, when it named a number. */
310
+ generation?: number;
311
+ }
312
+ // What a tile's runtime comes up through, in order: what a start is waiting
313
+ // for, until it waits for nothing.
314
+ const STAGES: readonly TileErrorEvent['stage'][] = ['dock', 'shuttle', 'worker', 'content'];
315
+
316
+ // What a tile may ask of the page it runs in, when the host does not say
317
+ // (MothershipConfig.budget). Guesses, every one, at what an ordinary tile
318
+ // never comes near and a page can bear from each tile it shows.
319
+ const BUDGET: Required<TileBudget> = {
320
+ // A tile that tells its host of every frame it draws, or of the pointer as
321
+ // it moves, sends 60 to 120 messages a second.
322
+ messagesPerSecond: 200,
323
+ messageBurst: 400,
324
+ // More than a browser asks of one server at once over HTTP/1.1 (six), so
325
+ // that a loader which fetches is not slowed much; few enough that what a
326
+ // loader is at work on for one tile stays small. (An answer counts until
327
+ // it is posted, not until the tile has it: what is on its way down, copied
328
+ // at every hop, is as much as the tile asked for faster than it reads.)
329
+ requestsInFlight: 16,
330
+ requestsQueued: 2000,
331
+ logLines: 10,
332
+ };
333
+ // A resource that has been resolving for this long no longer counts as in
334
+ // flight: a server that stalls on some of a tile's resources does not get to
335
+ // keep the others waiting behind them for good.
336
+ const HOLD_MS = 10000;
337
+ // No resource of a tile's has a path longer than this. A request for one is
338
+ // answered without being kept: what waits its turn has to stay small.
339
+ const MAX_PATH = 8192;
340
+ // Requests that waited their turn are started this many at a time, and the
341
+ // page's thread is given back before the next lot. A loader that answers
342
+ // some resources at once would otherwise have each one start the next as it
343
+ // ended, and all that waited would be resolved in one go.
344
+ const RUN = 16;
345
+ // What a tile's runtime says for itself (that it is ready, that the tile was
346
+ // closed, or stopped) is counted apart from what the tile says, and each
347
+ // kind apart from the others. A tile can spend its own budget, and it can
348
+ // have its runtime say any of these as often as it likes: neither may keep
349
+ // its host from hearing that it was stopped. (What is left to a tile is to
350
+ // have its runtime say that very thing, and then the host has heard it.)
351
+ // There are a few of each in a tile's life, and a few are all that is heard.
352
+ const OWN = new Set([RCV_DOCK_READY, RCV_DOCK_STOPPED, RCV_SHUTTLE_READY, RCV_SHUTTLE_CLOSED, RCV_WORKER_READY]);
353
+ const OWN_BURST = 20;
354
+ const OWN_PER_SECOND = 2;
355
+
356
+ // The budget a host gave, with ours wherever it gave none we can use.
357
+ function budgetFrom (given?: TileBudget | null): Required<TileBudget> {
358
+ const budget = { ...BUDGET };
359
+ for (const name of Object.keys(BUDGET) as (keyof TileBudget)[]) {
360
+ const n = given?.[name];
361
+ // (Nothing is ever resolved with no request in flight.)
362
+ if (typeof n === 'number' && n >= (name === 'requestsInFlight' ? 1 : 0)) budget[name] = n;
363
+ }
364
+ return budget;
365
+ }
366
+
367
+ // So many at once, and so many a second from then on.
368
+ class Allowance {
369
+ #burst: number;
370
+ #perSecond: number;
371
+ #left: number;
372
+ #at = performance.now();
373
+ constructor (burst: number, perSecond: number) {
374
+ this.#burst = this.#left = burst;
375
+ this.#perSecond = perSecond;
376
+ }
377
+ // Takes one, if there is one to take.
378
+ spend (): boolean {
379
+ const now = performance.now();
380
+ if (now > this.#at) this.#left = Math.min(this.#burst, this.#left + (now - this.#at) * this.#perSecond / 1000);
381
+ this.#at = now;
382
+ if (this.#left < 1) return false;
383
+ this.#left--;
384
+ return true;
385
+ }
386
+ }
387
+
388
+ // What a tile has used of its budget, in the frame it is in.
389
+ interface Usage {
390
+ id: string | undefined; // the frame, by the id the tile's runtime has in it
391
+ said: Allowance; // messages: the tile's
392
+ own: Map<string, Allowance>; // and its runtime's own, each kind for itself
393
+ over: boolean; // it has been said that the tile is over its budget
394
+ inFlight: number; // resources being resolved
395
+ waiting: { path: string, requestId: number }[]; // requests that wait their turn
396
+ run: number; // how many of those were started since the page's thread was last given back
397
+ paused: boolean; // it is being given back now
398
+ logged: number; // lines in the console
399
+ }
400
+
401
+ /**
402
+ * What a host can ask of the frame `renderContent()` makes for a tile. Each
403
+ * is checked, and one the loader cannot honour throws: a host is never left
404
+ * believing in a frame it does not have.
405
+ */
406
+ export interface FrameOptions {
407
+ /** The frame's sandbox attribute in full: `allow-scripts allow-same-origin allow-forms` when left out. */
408
+ sandbox?: string;
409
+ /** Whether the frame is credentialless: `true` or `false`; when left out, it is on an origin made for the load, and not on a named origin or the origin named by the tile's CID (`tile.ephemeral`). */
410
+ credentialless?: boolean;
411
+ /** The frame's tabindex, a whole number from -32767 to 32767: `-1` has the Tab key pass over the tile. None when left out. The focus guard takes a frame it guards out of the tab order whatever this says (see `tabOrder` in @dasl/tile-loader/guard). */
412
+ tabindex?: number;
413
+ /** Features to take from the tile, by name (`['sync-xhr', 'picture-in-picture', 'gamepad']`), among those of `REFUSABLE`: the list in full, as `sandbox` is the attribute in full. `['sync-xhr']` when left out; `[]` refuses nothing. */
414
+ refuse?: readonly string[];
415
+ }
416
+
110
417
  /** A tiles-protocol message from a tile: `protocol` ("data"), `kind` ("payload", "ready"), and its `payload`. The mothership attaches no meaning to any of them. */
111
418
  export interface ProtocolEvent extends Event {
112
419
  protocol: string;
113
420
  kind: string;
114
421
  payload: unknown;
422
+ /** What the tile's dock said as it passed the message on; left out when it said nothing. */
423
+ dock?: DockStamp;
424
+ }
425
+
426
+ /**
427
+ * What a tile's dock says of the user and that tile: `activated` when the
428
+ * user has just pressed or typed inside the tile itself, not elsewhere on the
429
+ * page and not in another tile. The dock is the loading server's page, which
430
+ * the tile cannot script, so this is not the tile's to say.
431
+ *
432
+ * Read it to refuse, never to grant: a loading server from before its dock
433
+ * said this passes on whatever came from below under that name.
434
+ */
435
+ export interface DockStamp {
436
+ activated: boolean;
115
437
  }
116
438
 
117
439
  export class TileMothership {
@@ -124,11 +446,28 @@ export class TileMothership {
124
446
  // loader, for some loaders the tile's whole content) is the host's alone to
125
447
  // keep or drop. Nothing has to be called for that.
126
448
  #tiles = new WeakMap<object, Tile>();
449
+ // What each tile has used of its budget: weakly too.
450
+ #budget: Required<TileBudget>;
451
+ #usage = new WeakMap<Tile, Usage>();
127
452
  constructor (conf: MothershipConfig = {}) {
128
453
  this.#conf = conf;
454
+ this.#budget = budgetFrom(conf.budget);
455
+ // An origin named by a tile's CID is its tile's: no configuration names
456
+ // it, and a mothership runs a tile either there or on the one it names.
457
+ const named = this.#namedHost();
458
+ if (named && conf.cidOrigins) throw new Error('A mothership runs tiles on a named origin (namedOrigin) or on the origins named by their CID (cidOrigins), not both.');
459
+ if (named && isCidLabel(named.split('.')[0].toLowerCase())) throw new Error(`The origin named by a tile's CID is that tile's, and is not named: ${named}. Run tiles there with cidOrigins.`);
129
460
  }
461
+ // What init() has listening, kept so that destroy() can take it away.
462
+ #listener: ((ev: MessageEvent) => void) | undefined;
463
+ /**
464
+ * Starts listening to the tiles' docks. Once is enough, and once is all it
465
+ * does: called again it changes nothing, where a second listener would
466
+ * answer every request twice.
467
+ */
130
468
  init () {
131
- window.addEventListener('message', async (ev: MessageEvent) => {
469
+ if (this.#listener) return;
470
+ this.#listener = async (ev: MessageEvent) => {
132
471
  const { action } = ev.data || {};
133
472
  if (typeof action !== 'string') return;
134
473
  // Any frame can post a message, and say anything in it: the window
@@ -139,46 +478,71 @@ export class TileMothership {
139
478
  const tile = this.tileForWindow(ev.source);
140
479
  if (!tile || ev.origin !== this.getLoadOrigin()) return;
141
480
  const id = tile.runtimeId;
481
+ // A tile says as much as it likes, and can have its runtime say the
482
+ // same: what is listened to is bounded. Requests for its resources
483
+ // have a bound of their own, below.
484
+ const used = this.#used(tile);
485
+ if (action !== RCV_WORKER_REQUEST && !this.#admit(used, action)) return;
142
486
  if (action === TILES_WARNING) {
143
- console.warn(`[W:${id}]`, ...asList(ev.data.msg));
487
+ this.#log(used, 'warn', `[W:${id}]`, ...asList(ev.data.msg));
488
+ // The worker gave up on a request of its tile's that we never
489
+ // answered. Before the tile is up, that is its root document.
490
+ if (ev.data.code === 'unanswered') tile.failed('content');
491
+ // The runtime on the origin named by the tile's CID refused what it
492
+ // was handed for the tile's manifest.
493
+ if (ev.data.code === 'integrity') tile.failed('integrity');
144
494
  }
145
495
  else if (action === TILES_ERROR) {
146
- console.error(`[S:${id}]`, ...asList(ev.data.msg));
496
+ this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
497
+ // With a code, it is what kept the runtime from starting the tile.
498
+ const { code } = ev.data;
499
+ if (code === 'worker' || code === 'unsupported') tile.failed(code);
147
500
  }
148
501
  else if (action === RCV_DOCK_STOPPED) {
149
502
  const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
150
- console.error(`[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
503
+ this.#log(used, 'error', `[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
151
504
  tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
505
+ // The host has been told what became of it: it is waited for no longer.
506
+ tile.awaits();
152
507
  }
153
508
  else if (action === RCV_SHUTTLE_CLOSED) {
154
509
  tile.runtimeClosed();
155
510
  }
511
+ else if (action === RCV_DOCK_READY) {
512
+ // The loading server is there. Whether we can talk to what it runs
513
+ // is in the generation it names; a number we do not know is said to
514
+ // the host, and the rest is left to happen or not.
515
+ const generation = ev.data.payload?.generation;
516
+ // And a tile on the origin named by its CID is run there only by a
517
+ // runtime that holds that origin to it, which the dock says.
518
+ tile.dockSaid(ev.data.payload?.cid === true);
519
+ if (!GENERATIONS.includes(generation)) tile.failed('version', typeof generation === 'number' ? { generation } : {});
520
+ else if (tile.cidOrigin && !tile.bound) tile.failed('version');
521
+ else tile.awaits('shuttle');
522
+ }
156
523
  else if (action === RCV_SHUTTLE_READY) {
157
- tile.post(SND_WORKER_LOAD, { id });
524
+ // The runtime on the origin named by the tile's CID is handed the
525
+ // manifest that CID names, and nothing if it does not hold it.
526
+ const manifest = tile.cidOrigin;
527
+ if (manifest && !tile.bound) return tile.failed('version');
528
+ tile.awaits('worker');
529
+ tile.post(SND_WORKER_LOAD, { id, ...(manifest ? { manifest } : {}) });
158
530
  }
159
531
  else if (action === RCV_WORKER_READY) {
160
532
  tile.dispatchEvent(new Event('load'));
533
+ tile.awaits('content');
161
534
  }
162
535
  else if (action === RCV_WORKER_REQUEST) {
163
536
  const { type, payload } = ev.data;
164
537
  if (type === 'resolve-path') {
538
+ // The worker always sends one; without it there is no request to answer.
539
+ if (!payload || typeof payload !== 'object') return;
165
540
  const { path, requestId } = payload;
166
- let res: MaslResponse;
167
- try {
168
- res = await tile.resolvePath(path);
169
- }
170
- catch (err) {
171
- // Answer all the same, or the worker waits for ever.
172
- console.error(`Could not resolve ${path}:`, err);
173
- res = { ok: false, status: 502, statusText: 'Bad Gateway' };
174
- }
175
- // Every document the worker serves, 404s included, carries the
176
- // policy: the tile can script anything on its origin, so nothing
177
- // on it may be unconfined.
178
- const response = res.ok
179
- ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
180
- : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
181
- tile.post(SND_WORKER_RESPONSE, { requestId, response });
541
+ // Nor is there one without a path, which is a string, and a number
542
+ // to answer it by: nothing else is the worker's, and nothing else is
543
+ // ours to resolve or spell out.
544
+ if (typeof path !== 'string' || typeof requestId !== 'number') return;
545
+ this.#request(tile, used, path, requestId);
182
546
  }
183
547
  }
184
548
  else if (action.startsWith(PROTOCOL_UP)) {
@@ -188,9 +552,169 @@ export class TileMothership {
188
552
  const protocol = rest.slice(0, dash);
189
553
  const kind = rest.slice(dash + 1);
190
554
  const { payload } = ev.data;
191
- tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload }));
555
+ // What the dock said of the user as it passed this on, when it said.
556
+ const activated = ev.data.dock?.activated;
557
+ const dock = typeof activated === 'boolean' ? { dock: { activated } } : {};
558
+ tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload, ...dock }));
192
559
  }
193
- });
560
+ };
561
+ window.addEventListener('message', this.#listener);
562
+ }
563
+ /**
564
+ * Stops listening: what init() did, undone. The page's listener is what
565
+ * keeps a mothership, with its loaders and all they hold, for as long as
566
+ * the page lives; without it they are the host's to keep or drop. Tiles
567
+ * that are still running get no more answers, so close them first.
568
+ * init() starts it again.
569
+ */
570
+ destroy () {
571
+ if (!this.#listener) return;
572
+ window.removeEventListener('message', this.#listener);
573
+ this.#listener = undefined;
574
+ }
575
+ // What a tile has used of its budget. A tile that is rendered again starts
576
+ // again, and its budget with it.
577
+ #used (tile: Tile): Usage {
578
+ let used = this.#usage.get(tile);
579
+ if (!used || used.id !== tile.runtimeId) {
580
+ const { messageBurst, messagesPerSecond } = this.#budget;
581
+ used = {
582
+ id: tile.runtimeId,
583
+ said: new Allowance(messageBurst, messagesPerSecond),
584
+ own: new Map(),
585
+ over: false,
586
+ inFlight: 0,
587
+ waiting: [],
588
+ run: 0,
589
+ paused: false,
590
+ logged: 0,
591
+ };
592
+ this.#usage.set(tile, used);
593
+ }
594
+ return used;
595
+ }
596
+ // Whether a message is within what its tile may send. One that is not is
597
+ // dropped, and the first time that is said.
598
+ #admit (used: Usage, action: string): boolean {
599
+ let allowance = used.said;
600
+ if (OWN.has(action)) {
601
+ allowance = used.own.get(action) ?? new Allowance(OWN_BURST, OWN_PER_SECOND);
602
+ used.own.set(action, allowance);
603
+ }
604
+ if (allowance.spend()) return true;
605
+ this.#over(used, 'sends more messages');
606
+ return false;
607
+ }
608
+ #over (used: Usage, how: string) {
609
+ if (used.over) return;
610
+ used.over = true;
611
+ this.#log(used, 'warn', `[M:${used.id}] This tile ${how} than its budget allows: what is over is dropped.`);
612
+ }
613
+ // What a tile has logged is logged a few times and then no more. A tile's
614
+ // runtime can be made to say anything, as often as the tile likes, and so
615
+ // can its requests be made to fail.
616
+ #log (used: Usage, level: 'warn' | 'error', ...args: unknown[]) {
617
+ const { logLines } = this.#budget;
618
+ if (used.logged >= logLines) return;
619
+ used.logged++;
620
+ console[level](...args);
621
+ if (used.logged >= logLines) console.warn(`[M:${used.id}] Nothing more of this tile is logged.`);
622
+ }
623
+ // A tile's requests for its resources are resolved a few at a time, in the
624
+ // order they came, and the rest wait: resolving is the loader's work (a
625
+ // fetch, for some), and every answer is copied at each hop on its way to
626
+ // the tile. So that what is in flight is what the page chose, not what the
627
+ // tile asked for.
628
+ #request (tile: Tile, used: Usage, path: string, requestId: number) {
629
+ const { requestsInFlight, requestsQueued } = this.#budget;
630
+ if (path.length > MAX_PATH) return this.#turnDown(tile, used, requestId, 404);
631
+ if (used.inFlight < requestsInFlight) return void this.#resolve(tile, used, path, requestId);
632
+ if (used.waiting.length < requestsQueued) return void used.waiting.push({ path, requestId });
633
+ // More at once than a tile has any use for.
634
+ this.#over(used, 'asks for more of its resources at once');
635
+ this.#turnDown(tile, used, requestId, 503);
636
+ }
637
+ // A request that is not resolved is answered all the same, so that a worker
638
+ // does not wait for nothing: for as long as its tile has messages to
639
+ // spend, as each answer is one more that the tile has us send.
640
+ #turnDown (tile: Tile, used: Usage, requestId: number, status: number) {
641
+ if (!used.said.spend()) return;
642
+ tile.post(SND_WORKER_RESPONSE, { requestId, response: { status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined } });
643
+ }
644
+ // The next of the requests that wait, while there is room for them: a few
645
+ // (RUN), and then the page's thread is given back before any more. Those
646
+ // of a frame the tile has left are for a worker that is gone.
647
+ #next (tile: Tile, used: Usage) {
648
+ if (tile.runtimeId !== used.id) used.waiting.length = 0;
649
+ while (used.waiting.length && used.inFlight < this.#budget.requestsInFlight) {
650
+ if (used.run >= RUN) return this.#pause(tile, used);
651
+ used.run++;
652
+ const { path, requestId } = used.waiting.shift()!;
653
+ void this.#resolve(tile, used, path, requestId);
654
+ }
655
+ }
656
+ // Lets the page get on with whatever else it has to do, then goes on with
657
+ // the requests that wait: in a task of its own, by a message to ourselves.
658
+ // (Not by a timer: a browser holds those back in a page that is not in
659
+ // view, and a tile that loads there would get its resources a few a second.)
660
+ #pause (tile: Tile, used: Usage) {
661
+ if (used.paused) return;
662
+ used.paused = true;
663
+ const { port1, port2 } = new MessageChannel();
664
+ port1.onmessage = () => {
665
+ port1.close();
666
+ used.paused = false;
667
+ used.run = 0;
668
+ this.#next(tile, used);
669
+ };
670
+ port2.postMessage(null);
671
+ }
672
+ async #resolve (tile: Tile, used: Usage, path: string, requestId: number) {
673
+ // In flight until it is answered, or has been long enough at it.
674
+ used.inFlight++;
675
+ let held = true;
676
+ const release = () => {
677
+ if (!held) return;
678
+ held = false;
679
+ used.inFlight--;
680
+ this.#next(tile, used);
681
+ };
682
+ const hold = setTimeout(release, HOLD_MS);
683
+ // (Under Node, where the tests run, a timer would keep the process up.)
684
+ (hold as { unref?: () => void }).unref?.();
685
+ try {
686
+ let response;
687
+ let served = false;
688
+ try {
689
+ const res = await tile.resolvePath(path);
690
+ // Every document the worker serves, 404s included, carries the
691
+ // policy: the tile can script anything on its origin, so nothing
692
+ // on it may be unconfined.
693
+ response = res.ok
694
+ ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
695
+ : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
696
+ served = res.ok;
697
+ }
698
+ catch (err) {
699
+ // Answer all the same, or the worker waits for ever. Resolving the
700
+ // path can throw, and so can hardening what it resolved to: a
701
+ // resource's headers are the tile's to write.
702
+ this.#log(used, 'error', `Could not resolve ${path}:`, err);
703
+ response = { status: 502, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
704
+ }
705
+ tile.post(SND_WORKER_RESPONSE, { requestId, response });
706
+ // The root document is what a tile starts with: once it is on its
707
+ // way the tile is up, and when it is not to be had the host hears.
708
+ // (Unless the tile has left that frame while we were resolving.)
709
+ if (path === '/' && tile.runtimeId === used.id) {
710
+ if (served) tile.awaits();
711
+ else tile.failed('content');
712
+ }
713
+ }
714
+ finally {
715
+ clearTimeout(hold);
716
+ release();
717
+ }
194
718
  }
195
719
  /**
196
720
  * The headers a tile document ships with: the resource's own, plus the
@@ -223,20 +747,119 @@ export class TileMothership {
223
747
  return {
224
748
  id: tile.runtimeId,
225
749
  webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
226
- ephemeral: this.ephemeral,
750
+ ephemeral: tile.ephemeral,
227
751
  ...(sizing ? { sizing } : {}),
228
752
  };
229
753
  }
230
- /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
754
+ /** @internal How long a tile gets to start, in milliseconds; 0 for no deadline. */
755
+ get startDeadline (): number {
756
+ const ms = this.#conf.startDeadline;
757
+ if (typeof ms !== 'number' || Number.isNaN(ms) || ms < 0) return START_DEADLINE_MS;
758
+ return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
759
+ }
760
+ /**
761
+ * Whether tiles get an origin of their own for every load (no
762
+ * `namedOrigin`). With `cidOrigins`, those that have a CID to be named by
763
+ * do not: see `tile.ephemeral`.
764
+ */
231
765
  get ephemeral (): boolean {
232
766
  return !this.#namedHost();
233
767
  }
768
+ /**
769
+ * @internal The host of the origin named by a tile's CID: when tiles run
770
+ * there (`cidOrigins`), the tile has a CID to be named by, and the loading
771
+ * server's tile origins are under its own host (`load.<base>`).
772
+ */
773
+ cidHost (tile: Tile): string | undefined {
774
+ const cid = tile.manifestBytes?.cid;
775
+ if (this.#conf.cidOrigins !== true || !isCidLabel(cid)) return undefined;
776
+ const { host } = new URL(this.getLoadOrigin());
777
+ return host.startsWith(LOAD_LABEL) ? `${cid}.${host.slice(LOAD_LABEL.length)}` : undefined;
778
+ }
234
779
  // The named origin's host, if the configuration names one.
235
780
  #namedHost (): string | undefined {
236
781
  const named = this.#conf.namedOrigin ?? this.#conf.tileHost;
237
782
  if (!named) return undefined;
238
783
  return /^https?:\/\//.test(named) ? new URL(named).host : named;
239
784
  }
785
+ // The host of a tile origin for one load, as the loading server makes them:
786
+ // twenty random letters under its base host, which is its own host without
787
+ // the `load.` it starts with (and with its port). A loading server that is
788
+ // somewhere else does not say where its tile origins are: it is then left
789
+ // to pick the origin itself, in a redirect, as it always could.
790
+ #freshHost (): string | undefined {
791
+ const { host } = new URL(this.getLoadOrigin());
792
+ return host.startsWith(LOAD_LABEL) ? `${randomLabel()}.${host.slice(LOAD_LABEL.length)}` : undefined;
793
+ }
794
+ /**
795
+ * @internal The tile origin a frame's address names, when the address is
796
+ * the dock's on our loading server and names one (getLoadSource() does).
797
+ */
798
+ originNamedIn (src: unknown): string | undefined {
799
+ if (typeof src !== 'string' || !src) return undefined;
800
+ let url: URL;
801
+ try { url = new URL(src); }
802
+ catch { return undefined; }
803
+ if (url.origin !== this.getLoadOrigin() || url.pathname !== dockPath) return undefined;
804
+ const [host, ...more] = url.searchParams.getAll('tile');
805
+ if (!host || more.length || !/^[a-z0-9.-]+(?::\d+)?$/.test(host)) return undefined;
806
+ return `${url.protocol}//${host}`;
807
+ }
808
+ /**
809
+ * @internal Has a tile origin wiped, from a frame of our own making: what
810
+ * closing a tile comes down to once its frame is out of the document.
811
+ *
812
+ * The wipe answers a page of the origin it empties and no one else, and
813
+ * this page is not one. So a frame is made, out of sight, that loads the
814
+ * dock for that origin again; the dock frames the runtime there, a shuttle
815
+ * that never had a tile in it, and is told to close and wipe, in the words
816
+ * a tile's own frame is told. That shuttle lets the worker go and has the
817
+ * loading server wipe the origin, and the answer comes back up. Nothing in
818
+ * that frame was ever within the tile's reach, so its answer is not the
819
+ * tile's to give; and the shuttle only gets to run once the tile's own
820
+ * pages, which share its origin, are done with whatever they do on their
821
+ * way out, so it does not come too soon.
822
+ *
823
+ * `credentialless` is for a tile that ran in a credentialless frame: the
824
+ * browser keeps what such a frame stores apart, and only another one
825
+ * reaches it.
826
+ *
827
+ * Resolves to whether the origin was wiped: true when the runtime says so,
828
+ * false when it says not, or says nothing for WIPE_MS.
829
+ */
830
+ wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
831
+ const loadOrigin = this.getLoadOrigin();
832
+ const url = new URL(dockPath, loadOrigin);
833
+ url.searchParams.set('tile', new URL(origin).host);
834
+ return new Promise<boolean>((resolve) => {
835
+ const ifr = el('iframe', {
836
+ src: url.href,
837
+ // The dock and the runtime need no more than this to wipe.
838
+ sandbox: 'allow-scripts allow-same-origin',
839
+ // The attribute is there or it is not; it has no value.
840
+ credentialless: credentialless ? '' : undefined,
841
+ hidden: '',
842
+ style: { display: 'none' },
843
+ }) as HTMLIFrameElement;
844
+ const done = (wiped: boolean) => {
845
+ clearTimeout(timer);
846
+ window.removeEventListener('message', onMessage);
847
+ ifr.remove();
848
+ resolve(wiped);
849
+ };
850
+ // Only that frame's window, on the loading server, speaks for it.
851
+ const onMessage = (ev: MessageEvent) => {
852
+ if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin) return;
853
+ if (ev.data?.action === RCV_SHUTTLE_CLOSED) done(ev.data.payload?.wiped !== false);
854
+ };
855
+ const timer = setTimeout(() => done(false), WIPE_MS);
856
+ window.addEventListener('message', onMessage);
857
+ ifr.addEventListener('load', () => {
858
+ ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
859
+ }, { once: true });
860
+ (document.body ?? document.documentElement).append(ifr);
861
+ });
862
+ }
240
863
  // Adds a loader that will handle matching requests to load a tile.
241
864
  // - `loader` is an object that knows how to load a tile for a specific scheme
242
865
  // (and types)
@@ -253,25 +876,77 @@ export class TileMothership {
253
876
  return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
254
877
  }
255
878
  /**
256
- * What a tile's frame loads: the dock, on the loading server. Asked like
257
- * this it picks a fresh origin for the tile and frames the runtime there.
879
+ * What a tile's frame loads: the dock, on the loading server, for a tile
880
+ * origin that the address names. Unless the configuration names one
881
+ * (`namedOrigin`), that is a fresh origin at every call, made here as the
882
+ * loading server would make it, so an address is for one frame. Named
883
+ * here, the origin is one the page knows, which is what lets it be wiped
884
+ * once the frame its tile ran in is gone (see Tile.close()); and it saves
885
+ * the redirect in which the loading server would have picked it. With
886
+ * `cidOrigins`, for a `tile` that has a CID to be named by, it is the
887
+ * origin that CID names.
258
888
  */
259
- getLoadSource (): string {
889
+ getLoadSource (tile?: Tile): string {
260
890
  const url = new URL(dockPath, this.getLoadOrigin());
261
- const named = this.#namedHost();
891
+ const named = this.#namedHost() ?? (tile && this.cidHost(tile)) ?? this.#freshHost();
262
892
  if (named) url.searchParams.set('tile', named);
263
893
  return url.href;
264
894
  }
265
- // Load a tile.
266
- async loadTile (url: string): Promise<Tile | false> {
267
- for (const ldr of this.#loaders) {
268
- const tile = await ldr.load(url, this);
269
- if (tile) return tile;
895
+ /**
896
+ * Loads a tile: the first loader that has one for `url` gives it, and it
897
+ * is `false` when none does.
898
+ *
899
+ * `options` say which tile is expected (see TileLoadOptions), and a tile
900
+ * that is not that one is not returned. With options, even none of them
901
+ * (`{}`), a tile that could not be loaded is a rejection, with the
902
+ * TileLoadError that says why. With the URL alone, which is all there was
903
+ * to call this with before, it is `false` as it is for a URL no loader
904
+ * knows, and the error is logged: a host that only looks for a tile keeps
905
+ * working.
906
+ */
907
+ async loadTile (url: string, options?: TileLoadOptions): Promise<Tile | false> {
908
+ try {
909
+ for (const ldr of this.#loaders) {
910
+ const tile = await ldr.load(url, this, options);
911
+ if (!tile) continue;
912
+ // A loader that knows nothing of expected CIDs must not pass for one
913
+ // that checked: whatever made the tile, it has to be one asked for.
914
+ const { cid, manifestCid } = options ?? {};
915
+ const expected = cid !== undefined || manifestCid !== undefined;
916
+ if (expected && !(cid !== undefined && tile.cid === cid) && !(manifestCid !== undefined && tile.manifestCid === manifestCid)) {
917
+ throw new TileLoadError('record-changed', `The tile at ${url} is not the one expected, or has no CID to tell by.`, {
918
+ expected: cid ?? manifestCid,
919
+ actual: cid !== undefined ? tile.cid : tile.manifestCid,
920
+ manifestCid: tile.manifestCid,
921
+ });
922
+ }
923
+ return tile;
924
+ }
925
+ }
926
+ catch (err) {
927
+ if (options || !(err instanceof TileLoadError)) throw err;
928
+ console.error(`Could not load ${url}:`, err);
270
929
  }
271
930
  return false;
272
931
  }
273
932
  }
274
933
 
934
+ // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
935
+ const LOAD_LABEL = 'load.';
936
+ const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
937
+ // Twenty random letters: the name of a tile origin that no one can guess, and
938
+ // that is not made twice.
939
+ function randomLabel (): string {
940
+ let label = '';
941
+ while (label.length < 20) {
942
+ for (const byte of crypto.getRandomValues(new Uint8Array(32))) {
943
+ // 234 is nine times 26: the bytes from there up would favour the first letters.
944
+ if (byte < 234 && label.length < 20) label += LETTERS[byte % 26];
945
+ }
946
+ }
947
+ return label;
948
+ }
949
+
275
950
  // Loads a picture once so that it is decoded and cached, then revokes its
276
951
  // object URL. For pictures set where no load event says when they are in.
277
952
  function releaseWhenLoaded (url: string) {
@@ -288,6 +963,11 @@ export class Tile extends EventTarget {
288
963
  #url: string;
289
964
  #manifest: AnyMasl;
290
965
  #pathLoader: TilePathLoader;
966
+ // The address a frame of the host's own making loads for this run (getLoadSource()).
967
+ #source: string | undefined;
968
+ // What the close under way will resolve to, and the frame it is closing.
969
+ #closed: Promise<boolean> | undefined;
970
+ #closingFrame: HTMLIFrameElement | undefined;
291
971
  // The frame the tile runs in, and the id its runtime knows it by. The frame
292
972
  // is held weakly: it is the host's, in the host's document.
293
973
  #runtimeId: string | undefined;
@@ -297,12 +977,14 @@ export class Tile extends EventTarget {
297
977
  #started = false;
298
978
  #closing: Promise<void> | undefined;
299
979
  #runtimeDone: (() => void) | undefined;
300
- constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader) {
980
+ #identity: TileIdentity;
981
+ constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader, identity: TileIdentity = {}) {
301
982
  super();
302
983
  this.#mothership = mothership;
303
984
  this.#url = url;
304
985
  this.#manifest = manifest;
305
986
  this.#pathLoader = pathLoader;
987
+ this.#identity = identity;
306
988
  this.addEventListener('load', () => {
307
989
  if (this.#manifest?.name) {
308
990
  const title = this.#manifest?.name;
@@ -323,11 +1005,68 @@ export class Tile extends EventTarget {
323
1005
  get manifest (): AnyMasl {
324
1006
  return this.#manifest;
325
1007
  }
1008
+ /**
1009
+ * The CID of the record or file this tile was made from, computed by its
1010
+ * loader from the bytes it was given: what a host keeps to know the tile
1011
+ * again (see TileLoadOptions). Undefined where a loader has none to give.
1012
+ */
1013
+ get cid (): string | undefined {
1014
+ return this.#identity.cid;
1015
+ }
1016
+ /** The CID of the tile's manifest alone: its content, whatever record carries it. */
1017
+ get manifestCid (): string | undefined {
1018
+ return this.#identity.manifestCid;
1019
+ }
1020
+ /** Whether the tile was checked against a CID its host expected. */
1021
+ get pinned (): boolean {
1022
+ return this.#identity.pinned === true;
1023
+ }
1024
+ /** @internal The bytes of its manifest, and their CID, where its loader has them. */
1025
+ get manifestBytes (): TileIdentity['manifestBytes'] {
1026
+ return this.#identity.manifestBytes;
1027
+ }
1028
+ /**
1029
+ * Whether the origin this tile runs on is made for one load and wiped when
1030
+ * it is closed. It is unless its mothership names an origin for its tiles
1031
+ * (`namedOrigin`), or runs them on the origin named by their CID
1032
+ * (`cidOrigins`) and this tile has a CID to be named by: such an origin is
1033
+ * kept, for the tile to find what it stored there again.
1034
+ */
1035
+ get ephemeral (): boolean {
1036
+ return this.#mothership.ephemeral && !this.#mothership.cidHost(this);
1037
+ }
1038
+ /**
1039
+ * @internal The bytes of the manifest that names this tile's origin, when
1040
+ * it runs on the origin named by its CID: what that origin's runtime is
1041
+ * handed, to check it against its name.
1042
+ */
1043
+ get cidOrigin (): Uint8Array | undefined {
1044
+ return this.#mothership.cidHost(this) ? this.#identity.manifestBytes?.bytes : undefined;
1045
+ }
1046
+ // Whether the dock of the frame the tile is in now said that its runtime
1047
+ // holds an origin named by a CID to its tile.
1048
+ #bound = false;
1049
+ /** @internal What the dock said of itself: whether its runtime holds an origin named by a CID to its tile. */
1050
+ dockSaid (bound: boolean) {
1051
+ this.#bound = bound;
1052
+ }
1053
+ /** @internal Whether it said so. */
1054
+ get bound (): boolean {
1055
+ return this.#bound;
1056
+ }
326
1057
  async resolvePath (path: string): Promise<MaslResponse> {
327
1058
  const u = new URL(`fake:${path}`);
328
1059
  return this.#pathLoader.resolvePath(u.pathname);
329
1060
  }
330
- async renderCard (options?: { contentHeight?: number }): Promise<HTMLElement> {
1061
+ /**
1062
+ * A card for the tile: what its manifest says of it, and its pictures,
1063
+ * which runs the tile when it is clicked. `options.contentHeight` presets
1064
+ * the height of the tile's frame, and `options.frame` is what the host
1065
+ * asks of that frame, as with `renderContent()`: it is checked now, and
1066
+ * the card is refused if the frame could not be made as asked.
1067
+ */
1068
+ async renderCard (options?: { contentHeight?: number, frame?: FrameOptions }): Promise<HTMLElement> {
1069
+ this.#frameAttributes(options?.frame);
331
1070
  const card = el('div', { style: {
332
1071
  border: '1px solid lightgrey',
333
1072
  'border-radius': '3px',
@@ -337,7 +1076,8 @@ export class Tile extends EventTarget {
337
1076
  const tileRenderer = await this.renderContent(
338
1077
  options?.contentHeight ||
339
1078
  this.#manifest?.sizing?.height ||
340
- Math.max(card.offsetHeight, 300)
1079
+ Math.max(card.offsetHeight, 300),
1080
+ options?.frame,
341
1081
  );
342
1082
  card.replaceWith(tileRenderer);
343
1083
  });
@@ -382,8 +1122,17 @@ export class Tile extends EventTarget {
382
1122
  }
383
1123
  return card;
384
1124
  }
1125
+ /**
1126
+ * What a frame of the host's own making loads to run this tile (the frame
1127
+ * is then handed to `attachIframe()`): the dock, for an origin made for
1128
+ * this one run of the tile. It is the same address every time it is asked
1129
+ * for, so that it can sit in a template that is rendered again and again,
1130
+ * until the tile is closed: after that it is another run, on another
1131
+ * origin.
1132
+ */
385
1133
  getLoadSource (): string {
386
- return this.#mothership.getLoadSource();
1134
+ this.#source ??= this.#mothership.getLoadSource(this);
1135
+ return this.#source;
387
1136
  }
388
1137
  /**
389
1138
  * Sends a tiles-protocol message down to the rendered tile. Messages the
@@ -405,12 +1154,122 @@ export class Tile extends EventTarget {
405
1154
  * with it. A tile whose frame is gone says nothing.
406
1155
  */
407
1156
  post (action: string, payload?: unknown) {
1157
+ this.#track();
408
1158
  const win = this.#frame?.deref()?.contentWindow;
409
1159
  win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
410
1160
  }
1161
+ // The frame's window is how the tile's messages are known for its own. It
1162
+ // is there once the frame is in a document, and it is a new one if the
1163
+ // frame is taken out and put back, so it is taken down at each load, and
1164
+ // whenever something is posted to it: the dock answers the first thing it
1165
+ // is told, which can come before its frame's load event (what the host
1166
+ // sends the tile meanwhile, its size say), with its word on what its
1167
+ // runtime holds (see RCV_DOCK_READY), and that must not go unheard.
1168
+ #track () {
1169
+ const win = this.#frame?.deref()?.contentWindow as object | null | undefined;
1170
+ if (!win || win === this.#window) return;
1171
+ if (this.#window) this.#mothership.undock(this.#window);
1172
+ this.#window = win;
1173
+ this.#mothership.dock(win, this);
1174
+ }
1175
+ // --- Starting
1176
+ // What the host hears of a tile that does not start. A start is a frame
1177
+ // the tile is attached to, and each time that frame loads (which is when
1178
+ // the runtime in it is told to load the tile: see start()). The runtime in
1179
+ // it comes up in steps the mothership hears of, and `#waiting` is the one
1180
+ // that has not happened yet (see TileErrorEvent); it is nothing before
1181
+ // there is a frame, and nothing again once the root document is on its
1182
+ // way. A start that fails is reported once: by the runtime, when it knows
1183
+ // what stopped it; when the root document is not to be had; or by the
1184
+ // deadline, which reports and does nothing else.
1185
+ #waiting: TileErrorEvent['stage'];
1186
+ #reported = false;
1187
+ #rootFailed = false;
1188
+ #deadline: ReturnType<typeof setTimeout> | undefined;
1189
+ // A start, and the time it is given.
1190
+ #watch () {
1191
+ this.#waiting = STAGES[0];
1192
+ this.#reported = this.#rootFailed = false;
1193
+ this.#clock();
1194
+ }
1195
+ // Sets the deadline, for the frame the tile is in now. `out`: that frame
1196
+ // was not in the document when it was last looked at (see #late).
1197
+ #clock (out = false) {
1198
+ clearTimeout(this.#deadline);
1199
+ const ms = this.#mothership.startDeadline;
1200
+ if (!ms) return;
1201
+ // By a weak reference, the way the mothership knows a tile: a deadline
1202
+ // keeps none alive.
1203
+ const weak = new WeakRef(this);
1204
+ const id = this.#runtimeId;
1205
+ this.#deadline = setTimeout(() => {
1206
+ const tile = weak.deref();
1207
+ if (tile) tile.#late(id, out);
1208
+ }, out ? Math.max(ms, OUT_MS) : ms);
1209
+ // (Under Node, where the tests run, a timer would keep the process up.)
1210
+ (this.#deadline as { unref?: () => void }).unref?.();
1211
+ }
1212
+ // The deadline has passed: for the frame the tile was in when it was set,
1213
+ // which it may have left since. A frame that is not in the document loads
1214
+ // nothing, and a host may make one well before it shows it. That time is
1215
+ // not held against the tile, and it must not use the deadline up either,
1216
+ // or a frame put in the page late would never be watched. So a frame that
1217
+ // is out is looked at again later, and one that is found back in is given
1218
+ // its time from there: what is reported is a whole deadline spent in the
1219
+ // document.
1220
+ #late (id: string | undefined, wasOut: boolean) {
1221
+ const ifr = this.#frame?.deref();
1222
+ if (id !== this.#runtimeId || !ifr) return;
1223
+ const out = !ifr.isConnected;
1224
+ if (out || wasOut) return this.#clock(out);
1225
+ this.failed('timeout', { stage: this.#waiting });
1226
+ }
1227
+ /**
1228
+ * @internal What this start is waiting for now: a later step than before,
1229
+ * or nothing more, because the tile is up or because it was stopped.
1230
+ */
1231
+ awaits (stage?: TileErrorEvent['stage']) {
1232
+ if (!this.#waiting) return;
1233
+ if (stage && STAGES.indexOf(stage) <= STAGES.indexOf(this.#waiting)) return;
1234
+ this.#waiting = stage;
1235
+ if (!stage) clearTimeout(this.#deadline);
1236
+ else if (stage === 'content' && this.#rootFailed) this.failed('content');
1237
+ }
1238
+ /**
1239
+ * @internal A start, and the time it is given, from now: for a tile that
1240
+ * had more to do before its runtime could be told to load (one from AT
1241
+ * fetches all of itself first), and was waiting for nothing meanwhile
1242
+ * (`awaits()`). What that took is not the runtime being late.
1243
+ */
1244
+ watch () {
1245
+ this.#watch();
1246
+ }
1247
+ /**
1248
+ * @internal This start of the tile has failed, or is late: the host is
1249
+ * told, once, with what there is to say of it (`stage`, `generation`). Not
1250
+ * of a frame it has taken out of the document: nothing is expected of that
1251
+ * one.
1252
+ */
1253
+ failed (reason: TileErrorEvent['reason'], detail: Pick<TileErrorEvent, 'stage' | 'generation'> = {}) {
1254
+ if (!this.#waiting || this.#reported || !this.#frame?.deref()?.isConnected) return;
1255
+ // A worker asks for the root document as soon as it knows its tile,
1256
+ // which can be before it has said that it is ready. A root document that
1257
+ // fails that early is kept until then: `load` first, as when it is late.
1258
+ if (reason === 'content' && this.#waiting !== 'content') {
1259
+ this.#rootFailed = true;
1260
+ return;
1261
+ }
1262
+ this.#reported = true;
1263
+ clearTimeout(this.#deadline);
1264
+ this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
1265
+ }
411
1266
  /** @internal Tells the runtime in the frame to load the tile. */
412
1267
  start () {
413
1268
  this.#started = true;
1269
+ // A start, and its time, from here: what a tile does before it has its
1270
+ // runtime load it (one that fetches its content first, say) is not the
1271
+ // runtime being late.
1272
+ this.#watch();
414
1273
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
415
1274
  }
416
1275
  /** @internal The runtime says it has cleaned up. */
@@ -426,22 +1285,23 @@ export class Tile extends EventTarget {
426
1285
  this.#letGo();
427
1286
  this.#runtimeId = crypto.randomUUID(); // we might want to make that pluggable
428
1287
  this.#frame = new WeakRef(ifr);
429
- // The frame's window is how the tile's messages are known for its own.
430
- // It is there once the frame is in a document, and it is a new one if
431
- // the frame is taken out and put back, so it is taken down at each load.
432
- const track = () => {
433
- const win = ifr.contentWindow as object | null;
434
- if (!win || win === this.#window) return;
435
- if (this.#window) this.#mothership.undock(this.#window);
436
- this.#window = win;
437
- this.#mothership.dock(win, this);
438
- };
439
- track();
1288
+ this.#track();
440
1289
  this.#onFrameLoad = () => {
441
- track();
1290
+ this.#track();
1291
+ // The frame has loaded: the time a start is given runs from when the
1292
+ // runtime in it is told to load the tile (see start()).
1293
+ clearTimeout(this.#deadline);
442
1294
  this.start();
443
1295
  };
444
1296
  ifr.addEventListener('load', this.#onFrameLoad);
1297
+ // The frame may never load (a loading server that does not answer), so
1298
+ // the time a start is given runs from here: if the frame is in the
1299
+ // document by the time the host's code that made it has run (it places
1300
+ // what renderContent() hands it), and from when it is put there if not.
1301
+ this.#watch();
1302
+ queueMicrotask(() => {
1303
+ if (this.#frame?.deref() === ifr && this.#waiting && !ifr.isConnected) this.#clock(true);
1304
+ });
445
1305
  }
446
1306
  // Forgets the frame the tile was in, without touching the frame.
447
1307
  #letGo () {
@@ -450,51 +1310,194 @@ export class Tile extends EventTarget {
450
1310
  if (this.#window) this.#mothership.undock(this.#window);
451
1311
  this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
452
1312
  this.#started = false;
1313
+ this.#bound = false;
453
1314
  }
454
1315
  /**
455
- * Closes the tile: its runtime is told to clean up after itself, then its
456
- * frame is removed from the document and the tile forgets it. Resolves when
457
- * that is done. The tile can be rendered again afterwards.
1316
+ * Closes the tile: its frame is removed from the document, the tile
1317
+ * forgets it, and the origin it ran on is wiped. Resolves when that is
1318
+ * done, to whether the origin was wiped. The tile can be rendered again
1319
+ * afterwards.
458
1320
  *
459
1321
  * Removing the frame yourself and dropping the tile is enough for the
460
1322
  * page's memory: the mothership keeps nothing alive. What that cannot
461
1323
  * reach is what the tile left in the browser. Every tile runs on an origin
462
1324
  * made for that one load, and its worker's registration, and anything the
463
- * tile stored, would stay there for good. `close()` gives the runtime the
464
- * moment it needs to unregister the worker and have the origin wiped (not
465
- * for a named origin, `namedOrigin`, which is kept on purpose). A runtime
466
- * that does not answer in time is removed all the same.
1325
+ * tile stored, would stay there for good. `close()` has that origin wiped
1326
+ * (not a named origin, `namedOrigin`, nor the origin named by the tile's
1327
+ * CID, `cidOrigins`: both are kept on purpose, see `tile.ephemeral`).
1328
+ *
1329
+ * It does not matter what became of the frame first, nor what the tile
1330
+ * did. The frame's address names the origin (getLoadSource() does, and so
1331
+ * every frame renderContent() makes), and that is all it takes: the frame
1332
+ * is removed, if the host has not removed it already, and the origin is
1333
+ * wiped from a frame of the loader's own (TileMothership.wipeOrigin). So
1334
+ * `close()` can be called before the frame is taken out of the document,
1335
+ * or after. A few seconds later the origin is wiped a second time, the
1336
+ * same way, without anyone waiting for it: a worker of the tile's can
1337
+ * outlive its pages for a moment, and write.
1338
+ *
1339
+ * Only a frame whose address does not name the origin, which a host that
1340
+ * builds the address itself can make, has to be asked while it is there:
1341
+ * the runtime in it is told to close, as it always was, and given
1342
+ * CLOSE_MS to answer. Out of the document, there is no one to ask.
1343
+ *
1344
+ * What it resolves to: true when the origin was wiped, and when the tile
1345
+ * never started (there was nothing to wipe); false for a named origin and
1346
+ * for the origin named by the tile's CID, which are kept, and when the
1347
+ * wipe could not be done or was not confirmed, which is also logged as a
1348
+ * warning.
467
1349
  */
468
- close (): Promise<void> {
469
- if (this.#closing) return this.#closing;
470
- // Kept until it settles, so that closing twice is closing once.
471
- const closing = this.#close().finally(() => {
472
- if (this.#closing === closing) this.#closing = undefined;
1350
+ close (): Promise<boolean> {
1351
+ const ifr = this.#frame?.deref();
1352
+ // Kept until it settles, so that closing twice is closing once. Unless
1353
+ // the tile was rendered again meanwhile: it is in another frame then,
1354
+ // and closing that one is another close.
1355
+ if (this.#closed && (!ifr || ifr === this.#closingFrame)) return this.#closed;
1356
+ const outcome = { wiped: false };
1357
+ const closing = this.#close(outcome).finally(() => {
1358
+ if (this.#closing === closing) this.#closing = this.#closed = this.#closingFrame = undefined;
473
1359
  });
474
1360
  this.#closing = closing;
475
- return closing;
1361
+ this.#closingFrame = ifr;
1362
+ this.#closed = closing.then(() => outcome.wiped);
1363
+ return this.#closed;
476
1364
  }
477
- async #close (): Promise<void> {
1365
+ async #close (outcome: { wiped: boolean }): Promise<void> {
1366
+ // The host is done with this start, however far it got: nothing more is
1367
+ // expected of it, and a deadline that runs out while its runtime is
1368
+ // asked to close is not the tile failing to start.
1369
+ this.awaits();
478
1370
  const ifr = this.#frame?.deref();
1371
+ // There is something to wipe once a runtime was started on an origin
1372
+ // made for this load: nothing was put there before that.
1373
+ const started = this.#started;
1374
+ const wipe = this.ephemeral && started;
1375
+ // Which origin, the frame's address says, when it is one of ours.
1376
+ const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
1377
+ const credentialless = (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
479
1378
  {
480
- if (ifr?.isConnected && ifr.contentWindow && this.#started) {
1379
+ // The runtime in the frame is only asked when we cannot do without it:
1380
+ // for an origin we were not told of, and for a named origin, where
1381
+ // there is nothing to wipe and it just closes.
1382
+ if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1383
+ const win = ifr.contentWindow;
1384
+ const loadOrigin = this.#mothership.getLoadOrigin();
1385
+ let answered = false;
1386
+ // What the runtime's answer says of the wipe. A runtime whose dock
1387
+ // carries a close out itself says whether the origin was wiped; one
1388
+ // from before that says only that it has closed, and is taken at its
1389
+ // word.
1390
+ let wipedThere = true;
1391
+ const onAnswer = (ev: MessageEvent) => {
1392
+ if (ev.source === win && ev.origin === loadOrigin && ev.data?.action === RCV_SHUTTLE_CLOSED) wipedThere = ev.data.payload?.wiped !== false;
1393
+ };
1394
+ window.addEventListener('message', onAnswer);
481
1395
  await new Promise<void>((resolve) => {
482
- this.#runtimeDone = resolve;
1396
+ this.#runtimeDone = () => {
1397
+ answered = true;
1398
+ // In a moment: the listener above is handed the same message,
1399
+ // and may be handed it after the one that calls us.
1400
+ setTimeout(resolve);
1401
+ };
483
1402
  setTimeout(resolve, CLOSE_MS);
484
- this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
1403
+ this.post(SND_SHUTTLE_CLOSE, { wipe: this.ephemeral });
485
1404
  });
1405
+ window.removeEventListener('message', onAnswer);
486
1406
  this.#runtimeDone = undefined;
1407
+ outcome.wiped = wipe && answered && wipedThere;
487
1408
  }
488
1409
  // Only if it is still the frame we had: the host may have rendered the
489
1410
  // tile again while the old runtime was tidying up.
490
- if (this.#frame?.deref() === ifr) this.#letGo();
1411
+ if (this.#frame?.deref() === ifr) {
1412
+ this.#letGo();
1413
+ // That run is over: the next has an address, and an origin, of its own.
1414
+ this.#source = undefined;
1415
+ }
491
1416
  ifr?.remove?.();
1417
+ if (origin) {
1418
+ outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1419
+ // And once more in a moment, for what a worker of the tile's may
1420
+ // have written since (see WIPE_AGAIN_MS), and for a wipe that did
1421
+ // not go through the first time. No one waits for that one, and
1422
+ // nothing is said of how it went.
1423
+ setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1424
+ }
1425
+ else if (!started) outcome.wiped = this.ephemeral;
1426
+ if (wipe && !outcome.wiped) {
1427
+ console.warn(origin
1428
+ ? `[tiles] A closed tile's origin was not wiped, as far as can be told: its loading server said so, or did not answer in time (${origin}).`
1429
+ : '[tiles] A closed tile\'s origin was not wiped: its frame was out of the document, or did not answer, or said that it could not, and its address does not name the origin. Load tile.getLoadSource() in a frame of your own, or close the tile before removing the frame.');
1430
+ }
492
1431
  this.dispatchEvent(new Event('close'));
493
1432
  }
494
1433
  }
495
- renderContent (height = 300): HTMLIFrameElement {
1434
+ /**
1435
+ * The frame that runs the tile, for the host to put in its document.
1436
+ *
1437
+ * The frame is sandboxed. The runtime in it has a sandbox of its own
1438
+ * (`tileSandbox` in @dasl/tile-lexicon), and a frame's sandbox only ever
1439
+ * takes away: a tile gets what both grant. It needs scripts and its own
1440
+ * origin to run at all (its worker cannot be registered without them), and
1441
+ * forms to submit to itself. The runtime grants dialogs (`allow-modals`:
1442
+ * alert, confirm, prompt, print) and downloads (`allow-downloads`) besides;
1443
+ * a tile in someone else's page has no call for either, so the frame
1444
+ * leaves them out.
1445
+ *
1446
+ * `options.sandbox` is the frame's sandbox attribute in full, for a host
1447
+ * that wants it otherwise: wider where its user runs one tile on purpose,
1448
+ * narrower (no forms) if it likes. `allow-scripts` and `allow-same-origin`
1449
+ * have to be in it, and nothing can be that the runtime does not grant,
1450
+ * since it would be there for nothing. Either mistake throws.
1451
+ *
1452
+ * `options.credentialless` makes the frame credentialless. A tile's origin
1453
+ * is a subdomain of the loading server's site, and cookies go by site: in
1454
+ * a plain frame a tile reads the cookies the site keeps for its whole
1455
+ * domain, and sets some there. In a credentialless frame Chromium gives
1456
+ * everything inside cookies and storage of its own, empty to begin with
1457
+ * and gone with the page, and keeps its password manager out. Other
1458
+ * browsers ignore the attribute. When nothing is said, the frame is
1459
+ * credentialless if the tile's origin was made for this one load
1460
+ * (`tile.ephemeral`): nothing is lost by its storage going with the page.
1461
+ * A named origin, or the origin named by the tile's CID, is there for a
1462
+ * tile to find its storage again, which such a frame loses with every
1463
+ * page, so its frame is a plain one. `true` or
1464
+ * `false` for a host that wants it otherwise, either way, and anything
1465
+ * else throws.
1466
+ *
1467
+ * `options.tabindex` is the frame's tabindex: `-1` has the Tab key pass
1468
+ * over the tile. Whoever has the focus in a tile types into the tile,
1469
+ * every key, Tab and Escape with the rest, and the host hears none of
1470
+ * them: a tile can keep the keyboard it is given, and each key counts as
1471
+ * its user having acted in it. A page with more on it than tiles may want
1472
+ * no one to end up there by tabbing down it, and then gives its user a
1473
+ * way in of its own. The focus guard (`guardFocus` in
1474
+ * @dasl/tile-loader/guard) does both for a frame it guards, whatever this
1475
+ * says: it takes the frame out of the tab order and puts a stop of its own
1476
+ * in its place, unless its host tells it otherwise. This is about the Tab
1477
+ * key and no more: a tile's script can still take the focus itself. A
1478
+ * whole number from -32767 to 32767, or it throws; the frame has no
1479
+ * tabindex, and is in the tab order as any frame is, when nothing is said.
1480
+ *
1481
+ * `options.refuse` names features to take from the tile, among REFUSABLE:
1482
+ * those a browser gives every frame unasked (picture-in-picture, the
1483
+ * gamepad, synchronous requests, the client hints and more), and those the
1484
+ * runtime hands on to a tile when its host's frame allows them. Each is
1485
+ * written into the frame's `allow` attribute as `'none'`, which binds
1486
+ * everything inside the frame, the runtime and every frame the tile makes.
1487
+ * It only ever takes away, and only where the browser knows the name:
1488
+ * Chrome knows them all, Firefox and Safari far fewer, and pass over the
1489
+ * others. A name the loader does not know throws, since it would take
1490
+ * nothing away anywhere. When nothing is said, the frame refuses
1491
+ * synchronous requests (`sync-xhr`), which hold up the tile and its
1492
+ * runtime and never bring a tile its own files. A host's list is the list
1493
+ * in full, as `options.sandbox` is the attribute: it replaces that one, so
1494
+ * a host that refuses more names `sync-xhr` in it to keep that refused,
1495
+ * and `[]` refuses nothing and leaves the frame with no `allow` attribute.
1496
+ */
1497
+ renderContent (height = 300, options?: FrameOptions): HTMLIFrameElement {
496
1498
  const ifr = el('iframe', {
497
- src: this.#mothership.getLoadSource(),
1499
+ src: this.#mothership.getLoadSource(this),
1500
+ ...this.#frameAttributes(options),
498
1501
  style: {
499
1502
  display: 'block',
500
1503
  width: '100%',
@@ -505,4 +1508,51 @@ export class Tile extends EventTarget {
505
1508
  this.attachIframe(ifr);
506
1509
  return ifr;
507
1510
  }
1511
+ // The attributes of the frame renderContent() makes, from what its host
1512
+ // asked, each checked: one that cannot be honoured throws (see
1513
+ // renderContent()).
1514
+ #frameAttributes (options?: FrameOptions): Record<string, string | number | undefined> {
1515
+ // The first two no tile runs without; the rest of what the runtime
1516
+ // grants is the host's to keep or leave out.
1517
+ const needed = ['allow-scripts', 'allow-same-origin'];
1518
+ const granted = tileSandbox.split(' ');
1519
+ const asked = options?.sandbox ?? FRAME_SANDBOX;
1520
+ if (typeof asked !== 'string') throw new Error(`A tile's frame takes its sandbox as the text of the attribute: ${FRAME_SANDBOX} when nothing is said.`);
1521
+ // Read as HTML reads the attribute: any case, any spacing.
1522
+ const sandbox = asked.toLowerCase().split(/\s+/).filter(Boolean);
1523
+ const refused = sandbox.filter(token => !granted.includes(token));
1524
+ if (refused.length) throw new Error(`A tile's frame cannot be given ${refused.join(', ')}: the runtime grants ${granted.join(', ')} and nothing else.`);
1525
+ if (!needed.every(token => sandbox.includes(token))) throw new Error(`A tile's frame needs ${needed.join(' and ')}: no tile runs without them.`);
1526
+ // An origin made for this load is thrown away after it, so nothing is
1527
+ // lost by the frame's storage going with the page. A host that says
1528
+ // otherwise says true or false, and nothing else: any other value would
1529
+ // decide it unnoticed, and the empty text an HTML attribute has when it
1530
+ // is there would count as false.
1531
+ const credentialless = options?.credentialless ?? this.ephemeral;
1532
+ if (typeof credentialless !== 'boolean') throw new Error(`A tile's frame is credentialless or it is not: the option takes true or false.`);
1533
+ // A tabindex the browser cannot read is no tabindex: the frame would be
1534
+ // in the tab order and its host none the wiser. Only a whole number will
1535
+ // do, and not too large a one: Chromium takes a number it cannot hold for
1536
+ // no tabindex either, and the largest are not even written in digits
1537
+ // ("1e+21", which reads as 1). 32767 is as far as HTML ever said one goes.
1538
+ const tabindex = options?.tabindex ?? undefined;
1539
+ if (tabindex !== undefined && (!Number.isInteger(tabindex) || Math.abs(tabindex) > 32767)) throw new Error(`A tile's frame takes a whole number for its tabindex, from -32767 to 32767: -1 has the Tab key pass over the tile, 0 lets it in.`);
1540
+ // Names, each one the loader knows, and each refused once. Read with its
1541
+ // holes, which every way of going through a list but this one passes
1542
+ // over: a list with a hole in it is not a list of names, and one that
1543
+ // is all holes would refuse nothing, its host none the wiser.
1544
+ const listed = options?.refuse ?? FRAME_REFUSE;
1545
+ const refuse = Array.isArray(listed) ? Array.from(listed) : listed;
1546
+ if (!Array.isArray(refuse) || refuse.some(name => typeof name !== 'string')) throw new Error(`A tile's frame takes a list of the names of features to refuse the tile: ${JSON.stringify(FRAME_REFUSE)} when nothing is said, [] to refuse nothing.`);
1547
+ const unknown = refuse.filter(name => !REFUSABLE.includes(name));
1548
+ if (unknown.length) throw new Error(`A tile's frame cannot refuse ${unknown.map(name => JSON.stringify(name)).join(', ')}: the names it knows are those of REFUSABLE, ${REFUSABLE.join(', ')}.`);
1549
+ const allow = [...new Set(refuse)].map(name => `${name} 'none'`).join('; ');
1550
+ return {
1551
+ sandbox: sandbox.join(' '),
1552
+ // The attribute is there or it is not; it has no value.
1553
+ credentialless: credentialless ? '' : undefined,
1554
+ tabindex,
1555
+ allow: allow || undefined,
1556
+ };
1557
+ }
508
1558
  }