@dasl/tile-loader 3.2.0 → 5.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.
package/src/index.ts CHANGED
@@ -37,7 +37,7 @@ The tile-loading architecture has four levels that all communicate together:
37
37
 
38
38
  import { el } from "./lib/el.js";
39
39
  import { TileLoadError } from "./lib/errors.js";
40
- import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
40
+ import { tileResponseHeaders, dockPath, tileSandbox, refusableFeatures, isCidLabel } from "@dasl/tile-lexicon";
41
41
  import type { AnyMasl, MaslHeaders, MaslResponse } from "@dasl/tile-lexicon";
42
42
 
43
43
  export interface MothershipConfig {
@@ -57,6 +57,32 @@ export interface MothershipConfig {
57
57
  namedOrigin?: string;
58
58
  /** @deprecated The old name of `namedOrigin`. It goes in the next major version. */
59
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). The name says which tile runs there, and nothing more: what
65
+ * the tile stores there goes as it does on an origin made for one load.
66
+ * The origin is wiped when the tile is closed, and before it starts, so a
67
+ * run never finds what an earlier one left, closed or not; and its frame
68
+ * is credentialless. The one difference is that the same tile shown twice
69
+ * on a page is on the same origin twice, with one store: its wipes wait
70
+ * for the last of them to be closed, and the first to start. So does a
71
+ * run of it in another page of the site, where the browser keeps one
72
+ * store for the site (another tab, in Firefox or Safari, or with a plain
73
+ * frame in Chrome), or from another copy of the loader on this page,
74
+ * when the loading server's runtime holds each run there to a lock its
75
+ * wipes wait for (its dock says so): a tile that starts beside such a run
76
+ * shares what it has, and the last of them to be closed has it wiped.
77
+ *
78
+ * Anyone can name such an origin, so the loading server's runtime holds it
79
+ * to the one tile whose manifest it is named by, and the loader runs a
80
+ * tile there only when the loading server says that its runtime does. A
81
+ * tile its loader has no manifest bytes for (a webxdc tile, one in memory)
82
+ * runs on an origin made for the load, as without this. False when left
83
+ * out. Not with `namedOrigin`.
84
+ */
85
+ cidOrigins?: boolean;
60
86
  /**
61
87
  * Whether the shuttle spends the renderer's WebRTC budget before the tile
62
88
  * loads (the default). A host that blocks WebRTC itself (an Electron app with
@@ -124,6 +150,14 @@ export interface TileIdentity {
124
150
  manifestCid?: string;
125
151
  /** Whether it was checked against a CID its host expected. */
126
152
  pinned?: boolean;
153
+ /**
154
+ * The bytes of its manifest as its source holds them (DRISL), and their
155
+ * CID: the record's `tile` on AT (`manifestCid`), a .tile file's header
156
+ * (`cid`). What names the origin of a tile whose mothership runs tiles
157
+ * on the origin named by their CID (`cidOrigins`), and what the runtime
158
+ * there is handed to check it against.
159
+ */
160
+ manifestBytes?: { cid: string; bytes: Uint8Array };
127
161
  }
128
162
  export interface TileLoader {
129
163
  load (url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false | undefined>;
@@ -148,8 +182,9 @@ const CLOSE_MS = 2500;
148
182
  // How long the wiping of an origin gets when it is asked for from a frame of
149
183
  // our own (TileMothership.wipeOrigin), before it is given up on and counted
150
184
  // as not done. A guess, and a generous one: nothing waits on it but the
151
- // promise close() returns, and it has to cover a slow network and a tile
152
- // that holds its own pages up on their way out.
185
+ // promise close() returns, and a tile that starts on the origin its CID
186
+ // names, and it has to cover a slow network and a tile that holds its own
187
+ // pages up on their way out.
153
188
  const WIPE_MS = 10000;
154
189
  // How long after an origin was wiped it is wiped once more (Tile.close()).
155
190
  // The first wipe comes after everything the tile's pages did, but a worker
@@ -157,7 +192,12 @@ const WIPE_MS = 10000;
157
192
  // stop one after its page is gone (up to two seconds, in Chromium): what it
158
193
  // writes in that moment lands on an origin that was just wiped. A guess,
159
194
  // with a margin over that. A wipe that did not go through the first time
160
- // gets its second chance then too.
195
+ // gets its second chance then too. On an origin named by a tile's CID, which
196
+ // the next run of that tile on the page is on too, that run waits for this
197
+ // second wipe before it starts: it is the wipe it starts after. And the wipe
198
+ // before a tile starts there, which a worker of a run that was never closed
199
+ // can be writing through in the same way, gets its second chance then too,
200
+ // before the tile is given up on.
161
201
  const WIPE_AGAIN_MS = 3000;
162
202
  const WORKER_PFX = 'tiles-worker-';
163
203
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
@@ -195,6 +235,42 @@ const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg.slice(0, L
195
235
  // (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
196
236
  // nothing wrong with it has been seen to take eight seconds.
197
237
  const START_DEADLINE_MS = 15000;
238
+ // The sandbox of the frame renderContent() makes, when its host says none:
239
+ // what a tile needs to run, and forms to submit to itself. No dialogs and no
240
+ // downloads, which the runtime would grant (see renderContent()).
241
+ const FRAME_SANDBOX = 'allow-scripts allow-same-origin allow-forms';
242
+ // What the frame renderContent() makes refuses a tile when its host says
243
+ // nothing of it: synchronous requests. One holds up the thread the tile
244
+ // shares with its runtime and gets the tile nothing: its own files never
245
+ // come that way, since Chrome and Safari do not hand such a request to the
246
+ // tile's worker, and Firefox hands it to a worker whose answer has to come
247
+ // through that same thread. What is lost is a synchronous request for a
248
+ // blob: or data: address.
249
+ const FRAME_REFUSE: readonly string[] = ['sync-xhr'];
250
+ /**
251
+ * The features a host can refuse a tile (`FrameOptions.refuse`), by name:
252
+ * `refusableFeatures` in @dasl/tile-lexicon. They are those of its user's
253
+ * devices and attention that the runtime hands on to a tile whose host's
254
+ * frame allows them, and those a browser gives every frame unasked
255
+ * (picture-in-picture, the gamepad, synchronous requests, the client hints
256
+ * and more), which a tile keeps unless they are refused. `refuse: REFUSABLE`
257
+ * refuses all of them. Chrome knows every name; Firefox and Safari go by the
258
+ * names they know and pass over the others, so the same list refuses less
259
+ * there (the README says what, in each).
260
+ */
261
+ export const REFUSABLE: readonly string[] = refusableFeatures;
262
+ // Whether a frame's window still shows the empty document a frame starts
263
+ // with, which is this page's own: about:blank, which only a window of this
264
+ // page's origin lets us read. (A window we can read that shows anything
265
+ // else is not that one: a page of this origin, as the dock would be for a
266
+ // host on the loading server's own origin.)
267
+ function initial (win: Window): boolean {
268
+ try { return win.location.href === 'about:blank'; }
269
+ catch { return false; }
270
+ }
271
+ // How many messages are kept for a frame that has not loaded yet (see
272
+ // Tile.post()): more than any host sends that soon, and few enough to hold.
273
+ const EARLY_MAX = 256;
198
274
  // A timer is set for no longer than this: a longer wait comes round to none.
199
275
  const MAX_TIMER_MS = 2 ** 31 - 1;
200
276
  // A frame that is out of the document when its deadline passes is looked at
@@ -230,14 +306,29 @@ export interface StoppedEvent extends Event {
230
306
  * - `version`: the dock named a generation of the runtime that this loader
231
307
  * does not speak (`generation`): the loader in the page and the loading
232
308
  * server are too far apart. Nothing is stopped here either, but little
233
- * can be expected of the tile.
309
+ * can be expected of the tile. For a tile on the origin named by its CID
310
+ * (`cidOrigins`), also: the dock did not say that its runtime holds such
311
+ * an origin to its tile. That tile is not run there.
234
312
  * - `worker`: the runtime could not start the tile's service worker. Some
235
313
  * browsers refuse one to a frame of another site once the user blocks
236
314
  * cross-site storage.
237
- * - `unsupported`: the browser lacks what the runtime needs.
315
+ * - `unsupported`: the browser lacks what the runtime needs (on the origin
316
+ * named by the tile's CID, Web Locks with the rest).
238
317
  * - `content`: the tile's root document is not to be had: resolving it
239
318
  * failed, or the tile's worker gave up waiting for it (after a minute: a
240
319
  * deadline shorter than that has reported it first, as `timeout`).
320
+ * - `integrity`: the runtime on the origin named by the tile's CID refused
321
+ * the manifest it was handed: it is not the one that CID names, or not
322
+ * one it could read (a .tile file whose header is not in DRISL's one
323
+ * form). Nothing is served there.
324
+ * - `wipe`: the origin named by the tile's CID could not be wiped before the
325
+ * tile started there, twice, a few seconds apart (the loading server said
326
+ * it was not, or did not answer in time): what an earlier run left could
327
+ * still be there, so the tile is not run. Rendered again, it is tried
328
+ * again. A wipe that a run of the tile in another page there holds off
329
+ * is not one: the tile starts beside that run. (Only a runtime whose dock
330
+ * says that it holds runs to a lock holds a wipe off, and only its word
331
+ * that it did is taken.)
241
332
  *
242
333
  * A start (a frame the tile is attached to, each time it loads) fires one at
243
334
  * most. `worker` and `unsupported` are the runtime's own account, which
@@ -245,10 +336,11 @@ export interface StoppedEvent extends Event {
245
336
  * its frame says under any name: what runs on that origin can have the start
246
337
  * reported as failed, for any of these reasons. On an origin made for the
247
338
  * one load nothing of the tile's runs before it has started, and no other
248
- * tile is there; tiles that share a named origin can do it to one another.
339
+ * tile is there; tiles that share a named origin can do it to one another,
340
+ * and so can the runs of one tile on the origin its CID names.
249
341
  */
250
342
  export interface TileErrorEvent extends Event {
251
- reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content';
343
+ reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content' | 'integrity' | 'wipe';
252
344
  /** With `timeout`: what the tile was still waiting for. */
253
345
  stage?: 'dock' | 'shuttle' | 'worker' | 'content';
254
346
  /** With `version`: the generation the dock named, when it named a number. */
@@ -343,6 +435,22 @@ interface Usage {
343
435
  logged: number; // lines in the console
344
436
  }
345
437
 
438
+ /**
439
+ * What a host can ask of the frame `renderContent()` makes for a tile. Each
440
+ * is checked, and one the loader cannot honour throws: a host is never left
441
+ * believing in a frame it does not have.
442
+ */
443
+ export interface FrameOptions {
444
+ /** The frame's sandbox attribute in full: `allow-scripts allow-same-origin allow-forms` when left out. */
445
+ sandbox?: string;
446
+ /** Whether the frame is credentialless: `true` or `false`; when left out, it is unless the tile runs on a named origin (`tile.ephemeral`). */
447
+ credentialless?: boolean;
448
+ /** 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). */
449
+ tabindex?: number;
450
+ /** 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. */
451
+ refuse?: readonly string[];
452
+ }
453
+
346
454
  /** A tiles-protocol message from a tile: `protocol` ("data"), `kind` ("payload", "ready"), and its `payload`. The mothership attaches no meaning to any of them. */
347
455
  export interface ProtocolEvent extends Event {
348
456
  protocol: string;
@@ -381,6 +489,11 @@ export class TileMothership {
381
489
  constructor (conf: MothershipConfig = {}) {
382
490
  this.#conf = conf;
383
491
  this.#budget = budgetFrom(conf.budget);
492
+ // An origin named by a tile's CID is its tile's: no configuration names
493
+ // it, and a mothership runs a tile either there or on the one it names.
494
+ const named = this.#namedHost();
495
+ 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.');
496
+ 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.`);
384
497
  }
385
498
  // What init() has listening, kept so that destroy() can take it away.
386
499
  #listener: ((ev: MessageEvent) => void) | undefined;
@@ -412,6 +525,9 @@ export class TileMothership {
412
525
  // The worker gave up on a request of its tile's that we never
413
526
  // answered. Before the tile is up, that is its root document.
414
527
  if (ev.data.code === 'unanswered') tile.failed('content');
528
+ // The runtime on the origin named by the tile's CID refused what it
529
+ // was handed for the tile's manifest.
530
+ if (ev.data.code === 'integrity') tile.failed('integrity');
415
531
  }
416
532
  else if (action === TILES_ERROR) {
417
533
  this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
@@ -434,12 +550,20 @@ export class TileMothership {
434
550
  // is in the generation it names; a number we do not know is said to
435
551
  // the host, and the rest is left to happen or not.
436
552
  const generation = ev.data.payload?.generation;
437
- if (GENERATIONS.includes(generation)) tile.awaits('shuttle');
438
- else tile.failed('version', typeof generation === 'number' ? { generation } : {});
553
+ // And a tile on the origin named by its CID is run there only by a
554
+ // runtime that holds that origin to it, which the dock says.
555
+ tile.dockSaid(ev.data.payload?.cid === true);
556
+ if (!GENERATIONS.includes(generation)) tile.failed('version', typeof generation === 'number' ? { generation } : {});
557
+ else if (tile.cidOrigin && !tile.bound) tile.failed('version');
558
+ else tile.awaits('shuttle');
439
559
  }
440
560
  else if (action === RCV_SHUTTLE_READY) {
561
+ // The runtime on the origin named by the tile's CID is handed the
562
+ // manifest that CID names, and nothing if it does not hold it.
563
+ const manifest = tile.cidOrigin;
564
+ if (manifest && !tile.bound) return tile.failed('version');
441
565
  tile.awaits('worker');
442
- tile.post(SND_WORKER_LOAD, { id });
566
+ tile.post(SND_WORKER_LOAD, { id, ...(manifest ? { manifest } : {}) });
443
567
  }
444
568
  else if (action === RCV_WORKER_READY) {
445
569
  tile.dispatchEvent(new Event('load'));
@@ -654,13 +778,16 @@ export class TileMothership {
654
778
  * `sizing` goes along: the shuttle measures the content of a tile that
655
779
  * declares `fit` (see @dasl/tile-loader/size). So does whether its origin
656
780
  * is its own, made for this load: one that is can be thrown away with it.
781
+ * The origin named by a tile's CID is wiped too, but by us, and not under
782
+ * another run of the tile there, which needs its worker: it is not this
783
+ * run's to throw away on its own.
657
784
  */
658
785
  loadPayload (tile: Tile): Record<string, unknown> {
659
786
  const sizing = tile.manifest?.sizing;
660
787
  return {
661
788
  id: tile.runtimeId,
662
789
  webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
663
- ephemeral: this.ephemeral,
790
+ ephemeral: tile.ephemeral && !tile.sharedOrigin,
664
791
  ...(sizing ? { sizing } : {}),
665
792
  };
666
793
  }
@@ -670,10 +797,25 @@ export class TileMothership {
670
797
  if (typeof ms !== 'number' || Number.isNaN(ms) || ms < 0) return START_DEADLINE_MS;
671
798
  return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
672
799
  }
673
- /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
800
+ /**
801
+ * Whether what tiles store goes with each run, their origins wiped (no
802
+ * `namedOrigin`): an origin of their own for every load, or, with
803
+ * `cidOrigins`, the one their CID names. See `tile.ephemeral`.
804
+ */
674
805
  get ephemeral (): boolean {
675
806
  return !this.#namedHost();
676
807
  }
808
+ /**
809
+ * @internal The host of the origin named by a tile's CID: when tiles run
810
+ * there (`cidOrigins`), the tile has a CID to be named by, and the loading
811
+ * server's tile origins are under its own host (`load.<base>`).
812
+ */
813
+ cidHost (tile: Tile): string | undefined {
814
+ const cid = tile.manifestBytes?.cid;
815
+ if (this.#conf.cidOrigins !== true || !isCidLabel(cid)) return undefined;
816
+ const { host } = new URL(this.getLoadOrigin());
817
+ return host.startsWith(LOAD_LABEL) ? `${cid}.${host.slice(LOAD_LABEL.length)}` : undefined;
818
+ }
677
819
  // The named origin's host, if the configuration names one.
678
820
  #namedHost (): string | undefined {
679
821
  const named = this.#conf.namedOrigin ?? this.#conf.tileHost;
@@ -705,7 +847,8 @@ export class TileMothership {
705
847
  }
706
848
  /**
707
849
  * @internal Has a tile origin wiped, from a frame of our own making: what
708
- * closing a tile comes down to once its frame is out of the document.
850
+ * closing a tile comes down to once its frame is out of the document, and
851
+ * what a tile on the origin named by its CID starts after.
709
852
  *
710
853
  * The wipe answers a page of the origin it empties and no one else, and
711
854
  * this page is not one. So a frame is made, out of sight, that loads the
@@ -726,10 +869,29 @@ export class TileMothership {
726
869
  * false when it says not, or says nothing for WIPE_MS.
727
870
  */
728
871
  wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
872
+ return this.clearOrigin(origin, credentialless).then(answer => answer === 'wiped');
873
+ }
874
+ /**
875
+ * @internal Has a tile origin wiped, as wipeOrigin() does, and says how it
876
+ * went: `wiped`; `held`, not wiped because a run of the tile there holds
877
+ * the run's lock; or `failed`, not wiped, or not as far as can be told.
878
+ *
879
+ * On an origin named by a tile's CID the runs of that tile share one store
880
+ * with whatever other page of the site runs it, where the browser keeps
881
+ * one store for the site: another tab, another copy of the loader on this
882
+ * page. Each holds the run's lock for as long as it runs, and the runtime
883
+ * wipes nothing while one does (see the run's lock in @dasl/tile-server's
884
+ * dock/dock.js): the last of them to be closed has it wiped. Only a runtime
885
+ * whose dock says that it holds runs to the lock (`lock` in its ready
886
+ * message, which that of @dasl/tile-server 4.0.0 does not say) is taken
887
+ * at its word that one does: from any other, a wipe that was not done is
888
+ * one that failed.
889
+ */
890
+ clearOrigin (origin: string, credentialless = false): Promise<'wiped' | 'held' | 'failed'> {
729
891
  const loadOrigin = this.getLoadOrigin();
730
892
  const url = new URL(dockPath, loadOrigin);
731
893
  url.searchParams.set('tile', new URL(origin).host);
732
- return new Promise<boolean>((resolve) => {
894
+ return new Promise<'wiped' | 'held' | 'failed'>((resolve) => {
733
895
  const ifr = el('iframe', {
734
896
  src: url.href,
735
897
  // The dock and the runtime need no more than this to wipe.
@@ -739,18 +901,23 @@ export class TileMothership {
739
901
  hidden: '',
740
902
  style: { display: 'none' },
741
903
  }) as HTMLIFrameElement;
742
- const done = (wiped: boolean) => {
904
+ const done = (answer: 'wiped' | 'held' | 'failed') => {
743
905
  clearTimeout(timer);
744
906
  window.removeEventListener('message', onMessage);
745
907
  ifr.remove();
746
- resolve(wiped);
908
+ resolve(answer);
747
909
  };
910
+ // Whether that frame's dock said its runtime holds runs to the lock.
911
+ let locks = false;
748
912
  // Only that frame's window, on the loading server, speaks for it.
749
913
  const onMessage = (ev: MessageEvent) => {
750
914
  if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin) return;
751
- if (ev.data?.action === RCV_SHUTTLE_CLOSED) done(ev.data.payload?.wiped !== false);
915
+ if (ev.data?.action === RCV_DOCK_READY) locks = ev.data.payload?.lock === true;
916
+ if (ev.data?.action !== RCV_SHUTTLE_CLOSED) return;
917
+ const { wiped, held } = ev.data.payload ?? {};
918
+ done(wiped !== false ? 'wiped' : locks && held === true ? 'held' : 'failed');
752
919
  };
753
- const timer = setTimeout(() => done(false), WIPE_MS);
920
+ const timer = setTimeout(() => done('failed'), WIPE_MS);
754
921
  window.addEventListener('message', onMessage);
755
922
  ifr.addEventListener('load', () => {
756
923
  ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
@@ -780,11 +947,13 @@ export class TileMothership {
780
947
  * loading server would make it, so an address is for one frame. Named
781
948
  * here, the origin is one the page knows, which is what lets it be wiped
782
949
  * once the frame its tile ran in is gone (see Tile.close()); and it saves
783
- * the redirect in which the loading server would have picked it.
950
+ * the redirect in which the loading server would have picked it. With
951
+ * `cidOrigins`, for a `tile` that has a CID to be named by, it is the
952
+ * origin that CID names.
784
953
  */
785
- getLoadSource (): string {
954
+ getLoadSource (tile?: Tile): string {
786
955
  const url = new URL(dockPath, this.getLoadOrigin());
787
- const named = this.#namedHost() ?? this.#freshHost();
956
+ const named = this.#namedHost() ?? (tile && this.cidHost(tile)) ?? this.#freshHost();
788
957
  if (named) url.searchParams.set('tile', named);
789
958
  return url.href;
790
959
  }
@@ -827,6 +996,60 @@ export class TileMothership {
827
996
  }
828
997
  }
829
998
 
999
+ // The origins named by a tile's CID that tiles of this page run on. Such an
1000
+ // origin is not one run's, as an origin made for the load is: every run of
1001
+ // that tile on the page is there, at once, with one store and one worker
1002
+ // between them. So it is wiped as an origin made for the load is, when the
1003
+ // tile is closed and before it starts, but never under a tile of the page
1004
+ // that still runs there: a tile closed there has it wiped only when it was
1005
+ // the last, and a tile that starts there only when it is the first, after
1006
+ // any wipe that is still to come there. Kept here, for every mothership of
1007
+ // the page made by this copy of the loader: two motherships of one loading
1008
+ // server run a tile on one origin. (Another copy of the loader on the page,
1009
+ // in a bundle of its own, keeps its own, and knows nothing of these; nor
1010
+ // does a page in another tab. What keeps their wipes off our tiles' store,
1011
+ // and ours off theirs, is the lock each run holds there, which the runtime
1012
+ // does not wipe under: see clearOrigin().) The
1013
+ // tiles are held weakly, as the mothership holds them: one whose host has
1014
+ // dropped it without closing it no longer counts, as one whose frame is out
1015
+ // of the document does not.
1016
+ //
1017
+ // One store, that is: Chromium keeps what a credentialless frame stores, and
1018
+ // its worker, apart from what a plain frame of the same origin has, for the
1019
+ // page (see FrameOptions.credentialless). There the same tile in a frame of
1020
+ // each kind is on two stores, each with its own tiles and its own wipes, and
1021
+ // each wiped from a frame of its kind. A browser that ignores the attribute
1022
+ // has no such property on its frames, and one store for both.
1023
+ interface SharedOrigin {
1024
+ origin: string;
1025
+ credentialless: boolean; // the store of the credentialless frames there
1026
+ tiles: Set<WeakRef<Tile>>; // the tiles there, or on their way
1027
+ ready: Promise<boolean>; // the last wipe asked for there, which a tile that starts there waits for
1028
+ again: boolean; // that wipe is the second of a close, and every tile there is gone
1029
+ }
1030
+ const SHARED = new Map<string, SharedOrigin>();
1031
+ function sharedOrigin (origin: string, credentialless: boolean): SharedOrigin {
1032
+ const key = credentialless ? `${origin} credentialless` : origin;
1033
+ let shared = SHARED.get(key);
1034
+ if (!shared) SHARED.set(key, shared = { origin, credentialless, tiles: new Set(), ready: Promise.resolve(true), again: false });
1035
+ return shared;
1036
+ }
1037
+ // How many other tiles of the page run on that store now, `tile` left out
1038
+ // (and taken out); those that no longer run there are forgotten, and one
1039
+ // that comes back there joins it again (see Tile.start()).
1040
+ function othersOn (shared: SharedOrigin, tile: Tile): number {
1041
+ for (const ref of shared.tiles) {
1042
+ const other = ref.deref();
1043
+ if (!other || other === tile || !other.runsOn(shared)) shared.tiles.delete(ref);
1044
+ }
1045
+ return shared.tiles.size;
1046
+ }
1047
+ // An origin a tile shares with the other tiles of the page there: one named
1048
+ // by a CID, as the address of its frame names it.
1049
+ function sharedName (origin: string | undefined): string | undefined {
1050
+ return origin && isCidLabel(new URL(origin).hostname.split('.')[0]) ? origin : undefined;
1051
+ }
1052
+
830
1053
  // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
831
1054
  const LOAD_LABEL = 'load.';
832
1055
  const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
@@ -917,11 +1140,76 @@ export class Tile extends EventTarget {
917
1140
  get pinned (): boolean {
918
1141
  return this.#identity.pinned === true;
919
1142
  }
1143
+ /** @internal The bytes of its manifest, and their CID, where its loader has them. */
1144
+ get manifestBytes (): TileIdentity['manifestBytes'] {
1145
+ return this.#identity.manifestBytes;
1146
+ }
1147
+ /**
1148
+ * Whether what this tile stores goes with each run of it: the origin it
1149
+ * runs on is wiped when it is closed, and holds nothing from before when
1150
+ * it starts. It is, on an origin made for one load and on the origin named
1151
+ * by its CID (`cidOrigins`), unless its mothership names an origin for its
1152
+ * tiles (`namedOrigin`): that one is kept, for a tile to find what it
1153
+ * stored there again.
1154
+ */
1155
+ get ephemeral (): boolean {
1156
+ return this.#mothership.ephemeral;
1157
+ }
1158
+ // The store of an origin named by a CID that this run of the tile is on,
1159
+ // with whatever other tiles of the page are there (see SHARED), once it
1160
+ // has started there; the wipe it waits for before its runtime is told to
1161
+ // load it; how it is known there; and which start, or close, came last: a
1162
+ // start that waits goes no further once another has come.
1163
+ #joined: SharedOrigin | undefined;
1164
+ #ready: Promise<boolean> | undefined;
1165
+ #ref = new WeakRef(this);
1166
+ #turn = 0;
1167
+ /** @internal The origin named by a CID this run of the tile shares with the page's other tiles there, if it has started there. */
1168
+ get sharedOrigin (): string | undefined {
1169
+ return this.#joined?.origin;
1170
+ }
1171
+ /** @internal Whether this tile runs on that store now: it has started there, in a frame that is in the document. */
1172
+ runsOn (shared: SharedOrigin): boolean {
1173
+ return this.#joined === shared && this.#frame?.deref()?.isConnected === true;
1174
+ }
1175
+ // The store of the origin named by a CID that a frame's address names, if
1176
+ // it names one, of the kind of frame it is.
1177
+ #sharedIn (ifr: HTMLIFrameElement | undefined): SharedOrigin | undefined {
1178
+ const origin = this.ephemeral ? sharedName(this.#mothership.originNamedIn(ifr?.src)) : undefined;
1179
+ return origin ? sharedOrigin(origin, (ifr as { credentialless?: boolean } | undefined)?.credentialless === true) : undefined;
1180
+ }
1181
+ /**
1182
+ * @internal The bytes of the manifest that names this tile's origin, when
1183
+ * it runs on the origin named by its CID: what that origin's runtime is
1184
+ * handed, to check it against its name.
1185
+ */
1186
+ get cidOrigin (): Uint8Array | undefined {
1187
+ return this.#mothership.cidHost(this) ? this.#identity.manifestBytes?.bytes : undefined;
1188
+ }
1189
+ // Whether the dock of the frame the tile is in now said that its runtime
1190
+ // holds an origin named by a CID to its tile.
1191
+ #bound = false;
1192
+ /** @internal What the dock said of itself: whether its runtime holds an origin named by a CID to its tile. */
1193
+ dockSaid (bound: boolean) {
1194
+ this.#bound = bound;
1195
+ }
1196
+ /** @internal Whether it said so. */
1197
+ get bound (): boolean {
1198
+ return this.#bound;
1199
+ }
920
1200
  async resolvePath (path: string): Promise<MaslResponse> {
921
1201
  const u = new URL(`fake:${path}`);
922
1202
  return this.#pathLoader.resolvePath(u.pathname);
923
1203
  }
924
- async renderCard (options?: { contentHeight?: number }): Promise<HTMLElement> {
1204
+ /**
1205
+ * A card for the tile: what its manifest says of it, and its pictures,
1206
+ * which runs the tile when it is clicked. `options.contentHeight` presets
1207
+ * the height of the tile's frame, and `options.frame` is what the host
1208
+ * asks of that frame, as with `renderContent()`: it is checked now, and
1209
+ * the card is refused if the frame could not be made as asked.
1210
+ */
1211
+ async renderCard (options?: { contentHeight?: number, frame?: FrameOptions }): Promise<HTMLElement> {
1212
+ this.#frameAttributes(options?.frame);
925
1213
  const card = el('div', { style: {
926
1214
  border: '1px solid lightgrey',
927
1215
  'border-radius': '3px',
@@ -931,7 +1219,8 @@ export class Tile extends EventTarget {
931
1219
  const tileRenderer = await this.renderContent(
932
1220
  options?.contentHeight ||
933
1221
  this.#manifest?.sizing?.height ||
934
- Math.max(card.offsetHeight, 300)
1222
+ Math.max(card.offsetHeight, 300),
1223
+ options?.frame,
935
1224
  );
936
1225
  card.replaceWith(tileRenderer);
937
1226
  });
@@ -982,10 +1271,11 @@ export class Tile extends EventTarget {
982
1271
  * this one run of the tile. It is the same address every time it is asked
983
1272
  * for, so that it can sit in a template that is rendered again and again,
984
1273
  * until the tile is closed: after that it is another run, on another
985
- * origin.
1274
+ * origin. (With `cidOrigins`, the origin its CID names, every run: the
1275
+ * next one finds it wiped.)
986
1276
  */
987
1277
  getLoadSource (): string {
988
- this.#source ??= this.#mothership.getLoadSource();
1278
+ this.#source ??= this.#mothership.getLoadSource(this);
989
1279
  return this.#source;
990
1280
  }
991
1281
  /**
@@ -1008,8 +1298,42 @@ export class Tile extends EventTarget {
1008
1298
  * with it. A tile whose frame is gone says nothing.
1009
1299
  */
1010
1300
  post (action: string, payload?: unknown) {
1011
- const win = this.#frame?.deref()?.contentWindow;
1012
- win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1301
+ this.#track();
1302
+ const ifr = this.#frame?.deref();
1303
+ const win = ifr?.contentWindow;
1304
+ if (!win) return;
1305
+ // A frame shows the empty document it starts with, which is this page's
1306
+ // own, until what it loads arrives: a message posted to the dock's
1307
+ // origin before that is dropped (Chrome says so in the console). The
1308
+ // size a host's tileSize() grants as the frame goes into the document
1309
+ // is one, and so is anything a host sends that soon. Those are kept, and
1310
+ // posted when the frame loads, in the order they came: the dock holds
1311
+ // what it is told before its runtime is up.
1312
+ if (initial(win)) {
1313
+ if (this.#early.length < EARLY_MAX) this.#early.push({ action, payload });
1314
+ return;
1315
+ }
1316
+ win.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1317
+ }
1318
+ // What was posted to the frame before it had anything but its empty
1319
+ // document in it, to be posted once it loads.
1320
+ #early: { action: string, payload?: unknown }[] = [];
1321
+ #postEarly () {
1322
+ for (const { action, payload } of this.#early.splice(0)) this.post(action, payload);
1323
+ }
1324
+ // The frame's window is how the tile's messages are known for its own. It
1325
+ // is there once the frame is in a document, and it is a new one if the
1326
+ // frame is taken out and put back, so it is taken down at each load, and
1327
+ // whenever something is posted to it: the dock answers the first thing it
1328
+ // is told, which can come before its frame's load event (what the host
1329
+ // sends the tile meanwhile, its size say), with its word on what its
1330
+ // runtime holds (see RCV_DOCK_READY), and that must not go unheard.
1331
+ #track () {
1332
+ const win = this.#frame?.deref()?.contentWindow as object | null | undefined;
1333
+ if (!win || win === this.#window) return;
1334
+ if (this.#window) this.#mothership.undock(this.#window);
1335
+ this.#window = win;
1336
+ this.#mothership.dock(win, this);
1013
1337
  }
1014
1338
  // --- Starting
1015
1339
  // What the host hears of a tile that does not start. A start is a frame
@@ -1102,15 +1426,72 @@ export class Tile extends EventTarget {
1102
1426
  clearTimeout(this.#deadline);
1103
1427
  this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
1104
1428
  }
1105
- /** @internal Tells the runtime in the frame to load the tile. */
1429
+ /**
1430
+ * @internal Tells the runtime in the frame to load the tile. On an origin
1431
+ * named by a CID, the first tile of the page to start there has it wiped
1432
+ * first, whatever an earlier run left there, closed or not (a page that
1433
+ * went without closing it, one that crashed): the runtime is told once
1434
+ * that is done, and is not told at all if it was not, the second time it
1435
+ * was tried either (`wipe`). A tile that starts there while another of
1436
+ * the page runs there finds what that one has: they share the origin, and
1437
+ * wiping it would take it from that one.
1438
+ * A frame that loads again goes on with the run it is in, unless it was
1439
+ * out of the document while the others there went on without it (they
1440
+ * may have had the origin wiped meanwhile, or be about to): then it
1441
+ * starts there as any other tile does.
1442
+ */
1106
1443
  start () {
1107
1444
  this.#started = true;
1445
+ const turn = ++this.#turn;
1446
+ const ifr = this.#frame?.deref();
1447
+ const shared = this.#sharedIn(ifr);
1448
+ if (shared && (this.#joined !== shared || !shared.tiles.has(this.#ref))) this.#ready = this.#join(shared);
1449
+ const ready = this.#ready;
1450
+ if (!ready) return this.#launch();
1451
+ void ready.then((wiped) => {
1452
+ // Still this start: the host may have closed the tile meanwhile, or
1453
+ // rendered it again, or its frame loaded again.
1454
+ if (this.#turn !== turn) return;
1455
+ if (wiped) return this.#launch();
1456
+ // It runs there no more: the next to start there has it wiped again.
1457
+ shared?.tiles.delete(this.#ref);
1458
+ this.#joined = this.#ready = undefined;
1459
+ this.failed('wipe');
1460
+ });
1461
+ }
1462
+ #launch () {
1108
1463
  // A start, and its time, from here: what a tile does before it has its
1109
- // runtime load it (one that fetches its content first, say) is not the
1110
- // runtime being late.
1464
+ // runtime load it (one that fetches its content first, say, or waits
1465
+ // for its origin to be wiped) is not the runtime being late.
1111
1466
  this.#watch();
1112
1467
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
1113
1468
  }
1469
+ // This run of the tile is on that store of an origin named by a CID, with
1470
+ // the other tiles of the page there. Resolves to whether it may start:
1471
+ // once the origin is wiped, if this is the first of them, or at once with
1472
+ // what the others started with.
1473
+ #join (shared: SharedOrigin): Promise<boolean> {
1474
+ // The first of the page there has it wiped, after whatever wipe is still
1475
+ // to come there; unless what is still to come is the second wipe of the
1476
+ // last close there, which comes after all that the tiles closed there
1477
+ // did, and is the wipe it starts after.
1478
+ if (!othersOn(shared, this) && !shared.again) shared.ready = shared.ready.then(() => this.#wipeFirst(shared));
1479
+ shared.again = false;
1480
+ shared.tiles.add(this.#ref);
1481
+ this.#joined = shared;
1482
+ return shared.ready;
1483
+ }
1484
+ // The wipe the first tile of the page there starts after; once more a few
1485
+ // seconds later if it did not go through (see WIPE_AGAIN_MS). Held is as
1486
+ // good: a run of another page is there (another tab of the site, another
1487
+ // copy of the loader), and the tile starts beside it, on what it has, as
1488
+ // the second tile of a page does.
1489
+ async #wipeFirst (shared: SharedOrigin): Promise<boolean> {
1490
+ const wipe = () => this.#mothership.clearOrigin(shared.origin, shared.credentialless).then(answer => answer !== 'failed');
1491
+ return await wipe() || new Promise<boolean>((resolve) => {
1492
+ setTimeout(() => { void wipe().then(resolve); }, WIPE_AGAIN_MS);
1493
+ });
1494
+ }
1114
1495
  /** @internal The runtime says it has cleaned up. */
1115
1496
  runtimeClosed () {
1116
1497
  this.#runtimeDone?.();
@@ -1124,19 +1505,10 @@ export class Tile extends EventTarget {
1124
1505
  this.#letGo();
1125
1506
  this.#runtimeId = crypto.randomUUID(); // we might want to make that pluggable
1126
1507
  this.#frame = new WeakRef(ifr);
1127
- // The frame's window is how the tile's messages are known for its own.
1128
- // It is there once the frame is in a document, and it is a new one if
1129
- // the frame is taken out and put back, so it is taken down at each load.
1130
- const track = () => {
1131
- const win = ifr.contentWindow as object | null;
1132
- if (!win || win === this.#window) return;
1133
- if (this.#window) this.#mothership.undock(this.#window);
1134
- this.#window = win;
1135
- this.#mothership.dock(win, this);
1136
- };
1137
- track();
1508
+ this.#track();
1138
1509
  this.#onFrameLoad = () => {
1139
- track();
1510
+ this.#track();
1511
+ this.#postEarly();
1140
1512
  // The frame has loaded: the time a start is given runs from when the
1141
1513
  // runtime in it is told to load the tile (see start()).
1142
1514
  clearTimeout(this.#deadline);
@@ -1158,7 +1530,11 @@ export class Tile extends EventTarget {
1158
1530
  if (ifr && this.#onFrameLoad) ifr.removeEventListener?.('load', this.#onFrameLoad);
1159
1531
  if (this.#window) this.#mothership.undock(this.#window);
1160
1532
  this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
1533
+ this.#early.length = 0;
1161
1534
  this.#started = false;
1535
+ this.#bound = false;
1536
+ this.#joined = this.#ready = undefined;
1537
+ this.#turn++;
1162
1538
  }
1163
1539
  /**
1164
1540
  * Closes the tile: its frame is removed from the document, the tile
@@ -1171,7 +1547,11 @@ export class Tile extends EventTarget {
1171
1547
  * reach is what the tile left in the browser. Every tile runs on an origin
1172
1548
  * made for that one load, and its worker's registration, and anything the
1173
1549
  * tile stored, would stay there for good. `close()` has that origin wiped
1174
- * (not a named origin, `namedOrigin`, which is kept on purpose).
1550
+ * (not a named origin, `namedOrigin`, which is kept on purpose: see
1551
+ * `tile.ephemeral`). So it does the origin named by the tile's CID
1552
+ * (`cidOrigins`), but only once the last tile of the page there is
1553
+ * closed: the same tile shown twice on a page is on it twice, and the
1554
+ * other still needs what is there.
1175
1555
  *
1176
1556
  * It does not matter what became of the frame first, nor what the tile
1177
1557
  * did. The frame's address names the origin (getLoadSource() does, and so
@@ -1189,9 +1569,13 @@ export class Tile extends EventTarget {
1189
1569
  * CLOSE_MS to answer. Out of the document, there is no one to ask.
1190
1570
  *
1191
1571
  * What it resolves to: true when the origin was wiped, and when the tile
1192
- * never started (there was nothing to wipe); false for a named origin, and
1193
- * when the wipe could not be done or was not confirmed, which is also
1194
- * logged as a warning.
1572
+ * never started (there was nothing to wipe); false for a named origin,
1573
+ * which is kept; for the origin named by the tile's CID while another tile
1574
+ * of the page still runs there, whose close has it wiped, or a run of
1575
+ * another page (another tab of the site, another copy of the loader)
1576
+ * holds it to its lock, which the runtime does not wipe under; and when the
1577
+ * wipe could not be done or was not confirmed, which is also logged as a
1578
+ * warning.
1195
1579
  */
1196
1580
  close (): Promise<boolean> {
1197
1581
  const ifr = this.#frame?.deref();
@@ -1213,18 +1597,29 @@ export class Tile extends EventTarget {
1213
1597
  // expected of it, and a deadline that runs out while its runtime is
1214
1598
  // asked to close is not the tile failing to start.
1215
1599
  this.awaits();
1600
+ // And a start that waits for its origin to be wiped goes no further.
1601
+ this.#turn++;
1216
1602
  const ifr = this.#frame?.deref();
1217
1603
  // There is something to wipe once a runtime was started on an origin
1218
- // made for this load: nothing was put there before that.
1604
+ // made for this load: nothing was put there before that. On the origin
1605
+ // named by a CID, not while another tile of the page runs there: the
1606
+ // last of them to be closed has it wiped. Its store is the one this run
1607
+ // joined; or, for a run that never got that far (its wipe did not go
1608
+ // through), the one its frame's address names.
1219
1609
  const started = this.#started;
1220
- const wipe = this.#mothership.ephemeral && started;
1610
+ const shared = this.#joined ?? this.#sharedIn(ifr);
1611
+ const held = shared ? othersOn(shared, this) > 0 : false;
1612
+ const wipe = this.ephemeral && started && !held;
1221
1613
  // Which origin, the frame's address says, when it is one of ours.
1222
- const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
1223
- const credentialless = (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
1614
+ const origin = wipe ? shared?.origin ?? this.#mothership.originNamedIn(ifr?.src) : undefined;
1615
+ const credentialless = shared?.credentialless ?? (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
1616
+ // Whether the wipe was held by a run of another page there.
1617
+ let elsewhere = false;
1224
1618
  {
1225
1619
  // The runtime in the frame is only asked when we cannot do without it:
1226
- // for an origin we were not told of, and for a named origin, where
1227
- // there is nothing to wipe and it just closes.
1620
+ // for an origin we were not told of, and for a named origin, or one
1621
+ // named by a CID that another tile still runs on, where there is
1622
+ // nothing to wipe and it just closes.
1228
1623
  if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1229
1624
  const win = ifr.contentWindow;
1230
1625
  const loadOrigin = this.#mothership.getLoadOrigin();
@@ -1246,7 +1641,7 @@ export class Tile extends EventTarget {
1246
1641
  setTimeout(resolve);
1247
1642
  };
1248
1643
  setTimeout(resolve, CLOSE_MS);
1249
- this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
1644
+ this.post(SND_SHUTTLE_CLOSE, { wipe });
1250
1645
  });
1251
1646
  window.removeEventListener('message', onAnswer);
1252
1647
  this.#runtimeDone = undefined;
@@ -1260,7 +1655,26 @@ export class Tile extends EventTarget {
1260
1655
  this.#source = undefined;
1261
1656
  }
1262
1657
  ifr?.remove?.();
1263
- if (origin) {
1658
+ if (origin && shared) {
1659
+ // After any wipe still to come there (a tile that started there and
1660
+ // was closed before its wipe was done); and the second, in a moment,
1661
+ // is what the next tile of the page to start there waits for. Either
1662
+ // may be held by a run of another page there, which still needs what
1663
+ // is there: the last of them has it wiped, and a tile of this page
1664
+ // that starts meanwhile starts beside it.
1665
+ const clear = () => this.#mothership.clearOrigin(origin, credentialless);
1666
+ const first = shared.ready.then(clear);
1667
+ const second = first.then(() => new Promise<boolean>((resolve) => {
1668
+ setTimeout(() => { void clear().then(answer => resolve(answer !== 'failed')); }, WIPE_AGAIN_MS);
1669
+ }));
1670
+ shared.ready = second;
1671
+ shared.again = true;
1672
+ void second.then(() => { if (shared.ready === second) shared.again = false; });
1673
+ const answer = await first;
1674
+ outcome.wiped = answer === 'wiped';
1675
+ elsewhere = answer === 'held';
1676
+ }
1677
+ else if (origin) {
1264
1678
  outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1265
1679
  // And once more in a moment, for what a worker of the tile's may
1266
1680
  // have written since (see WIPE_AGAIN_MS), and for a wipe that did
@@ -1268,8 +1682,8 @@ export class Tile extends EventTarget {
1268
1682
  // nothing is said of how it went.
1269
1683
  setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1270
1684
  }
1271
- else if (!started) outcome.wiped = this.#mothership.ephemeral;
1272
- if (wipe && !outcome.wiped) {
1685
+ else if (!started) outcome.wiped = this.ephemeral;
1686
+ if (wipe && !outcome.wiped && !elsewhere) {
1273
1687
  console.warn(origin
1274
1688
  ? `[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}).`
1275
1689
  : '[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.');
@@ -1277,9 +1691,73 @@ export class Tile extends EventTarget {
1277
1691
  this.dispatchEvent(new Event('close'));
1278
1692
  }
1279
1693
  }
1280
- renderContent (height = 300): HTMLIFrameElement {
1694
+ /**
1695
+ * The frame that runs the tile, for the host to put in its document.
1696
+ *
1697
+ * The frame is sandboxed. The runtime in it has a sandbox of its own
1698
+ * (`tileSandbox` in @dasl/tile-lexicon), and a frame's sandbox only ever
1699
+ * takes away: a tile gets what both grant. It needs scripts and its own
1700
+ * origin to run at all (its worker cannot be registered without them), and
1701
+ * forms to submit to itself. The runtime grants dialogs (`allow-modals`:
1702
+ * alert, confirm, prompt, print) and downloads (`allow-downloads`) besides;
1703
+ * a tile in someone else's page has no call for either, so the frame
1704
+ * leaves them out.
1705
+ *
1706
+ * `options.sandbox` is the frame's sandbox attribute in full, for a host
1707
+ * that wants it otherwise: wider where its user runs one tile on purpose,
1708
+ * narrower (no forms) if it likes. `allow-scripts` and `allow-same-origin`
1709
+ * have to be in it, and nothing can be that the runtime does not grant,
1710
+ * since it would be there for nothing. Either mistake throws.
1711
+ *
1712
+ * `options.credentialless` makes the frame credentialless. A tile's origin
1713
+ * is a subdomain of the loading server's site, and cookies go by site: in
1714
+ * a plain frame a tile reads the cookies the site keeps for its whole
1715
+ * domain, and sets some there. In a credentialless frame Chromium gives
1716
+ * everything inside cookies and storage of its own, empty to begin with
1717
+ * and gone with the page, and keeps its password manager out. Other
1718
+ * browsers ignore the attribute. When nothing is said, the frame is
1719
+ * credentialless if what the tile stores goes with its run
1720
+ * (`tile.ephemeral`), on an origin made for this one load or on the one
1721
+ * its CID names: nothing is lost by its storage going with the page. A
1722
+ * named origin is there for a tile to find its storage again, which such
1723
+ * a frame loses with every page, so its frame is a plain one. `true` or
1724
+ * `false` for a host that wants it otherwise, either way, and anything
1725
+ * else throws.
1726
+ *
1727
+ * `options.tabindex` is the frame's tabindex: `-1` has the Tab key pass
1728
+ * over the tile. Whoever has the focus in a tile types into the tile,
1729
+ * every key, Tab and Escape with the rest, and the host hears none of
1730
+ * them: a tile can keep the keyboard it is given, and each key counts as
1731
+ * its user having acted in it. A page with more on it than tiles may want
1732
+ * no one to end up there by tabbing down it, and then gives its user a
1733
+ * way in of its own. The focus guard (`guardFocus` in
1734
+ * @dasl/tile-loader/guard) does both for a frame it guards, whatever this
1735
+ * says: it takes the frame out of the tab order and puts a stop of its own
1736
+ * in its place, unless its host tells it otherwise. This is about the Tab
1737
+ * key and no more: a tile's script can still take the focus itself. A
1738
+ * whole number from -32767 to 32767, or it throws; the frame has no
1739
+ * tabindex, and is in the tab order as any frame is, when nothing is said.
1740
+ *
1741
+ * `options.refuse` names features to take from the tile, among REFUSABLE:
1742
+ * those a browser gives every frame unasked (picture-in-picture, the
1743
+ * gamepad, synchronous requests, the client hints and more), and those the
1744
+ * runtime hands on to a tile when its host's frame allows them. Each is
1745
+ * written into the frame's `allow` attribute as `'none'`, which binds
1746
+ * everything inside the frame, the runtime and every frame the tile makes.
1747
+ * It only ever takes away, and only where the browser knows the name:
1748
+ * Chrome knows them all, Firefox and Safari far fewer, and pass over the
1749
+ * others. A name the loader does not know throws, since it would take
1750
+ * nothing away anywhere. When nothing is said, the frame refuses
1751
+ * synchronous requests (`sync-xhr`), which hold up the tile and its
1752
+ * runtime and never bring a tile its own files. A host's list is the list
1753
+ * in full, as `options.sandbox` is the attribute: it replaces that one, so
1754
+ * a host that refuses more names `sync-xhr` in it to keep that refused,
1755
+ * and `[]` refuses nothing and leaves the frame with no `allow` attribute.
1756
+ */
1757
+ renderContent (height = 300, options?: FrameOptions): HTMLIFrameElement {
1281
1758
  const ifr = el('iframe', {
1282
- src: this.#mothership.getLoadSource(),
1759
+ src: this.#mothership.getLoadSource(this),
1760
+ ...this.#frameAttributes(options),
1283
1761
  style: {
1284
1762
  display: 'block',
1285
1763
  width: '100%',
@@ -1290,4 +1768,52 @@ export class Tile extends EventTarget {
1290
1768
  this.attachIframe(ifr);
1291
1769
  return ifr;
1292
1770
  }
1771
+ // The attributes of the frame renderContent() makes, from what its host
1772
+ // asked, each checked: one that cannot be honoured throws (see
1773
+ // renderContent()).
1774
+ #frameAttributes (options?: FrameOptions): Record<string, string | number | undefined> {
1775
+ // The first two no tile runs without; the rest of what the runtime
1776
+ // grants is the host's to keep or leave out.
1777
+ const needed = ['allow-scripts', 'allow-same-origin'];
1778
+ const granted = tileSandbox.split(' ');
1779
+ const asked = options?.sandbox ?? FRAME_SANDBOX;
1780
+ 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.`);
1781
+ // Read as HTML reads the attribute: any case, any spacing.
1782
+ const sandbox = asked.toLowerCase().split(/\s+/).filter(Boolean);
1783
+ const refused = sandbox.filter(token => !granted.includes(token));
1784
+ if (refused.length) throw new Error(`A tile's frame cannot be given ${refused.join(', ')}: the runtime grants ${granted.join(', ')} and nothing else.`);
1785
+ if (!needed.every(token => sandbox.includes(token))) throw new Error(`A tile's frame needs ${needed.join(' and ')}: no tile runs without them.`);
1786
+ // An origin made for this load is thrown away after it, and so is the
1787
+ // one named by the tile's CID, so nothing is lost by the frame's storage
1788
+ // going with the page. A host that says
1789
+ // otherwise says true or false, and nothing else: any other value would
1790
+ // decide it unnoticed, and the empty text an HTML attribute has when it
1791
+ // is there would count as false.
1792
+ const credentialless = options?.credentialless ?? this.ephemeral;
1793
+ if (typeof credentialless !== 'boolean') throw new Error(`A tile's frame is credentialless or it is not: the option takes true or false.`);
1794
+ // A tabindex the browser cannot read is no tabindex: the frame would be
1795
+ // in the tab order and its host none the wiser. Only a whole number will
1796
+ // do, and not too large a one: Chromium takes a number it cannot hold for
1797
+ // no tabindex either, and the largest are not even written in digits
1798
+ // ("1e+21", which reads as 1). 32767 is as far as HTML ever said one goes.
1799
+ const tabindex = options?.tabindex ?? undefined;
1800
+ 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.`);
1801
+ // Names, each one the loader knows, and each refused once. Read with its
1802
+ // holes, which every way of going through a list but this one passes
1803
+ // over: a list with a hole in it is not a list of names, and one that
1804
+ // is all holes would refuse nothing, its host none the wiser.
1805
+ const listed = options?.refuse ?? FRAME_REFUSE;
1806
+ const refuse = Array.isArray(listed) ? Array.from(listed) : listed;
1807
+ 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.`);
1808
+ const unknown = refuse.filter(name => !REFUSABLE.includes(name));
1809
+ 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(', ')}.`);
1810
+ const allow = [...new Set(refuse)].map(name => `${name} 'none'`).join('; ');
1811
+ return {
1812
+ sandbox: sandbox.join(' '),
1813
+ // The attribute is there or it is not; it has no value.
1814
+ credentialless: credentialless ? '' : undefined,
1815
+ tabindex,
1816
+ allow: allow || undefined,
1817
+ };
1818
+ }
1293
1819
  }