@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/at.ts CHANGED
@@ -1,18 +1,80 @@
1
1
 
2
2
  import { Tile } from "./index.js";
3
- import type { TileMothership } from "./index.js";
3
+ import type { TileMothership, TileLoadOptions, TileIdentity } from "./index.js";
4
4
  import { NOT_FOUND, maslResponse } from "./lib/masl.js";
5
- import type { StoredMasl, MaslResponse } from "@dasl/tile-lexicon";
5
+ import type { StoredMasl, StoredResourceEntry, MaslResponse } from "@dasl/tile-lexicon";
6
6
  import type { LoaderOptions } from "./content-scheme.js";
7
+ import { publicHost, publicEndpoint } from "./lib/destinations.js";
8
+ import { DRISL, checkBytes, cidOf, parseCid, recordCid } from "./lib/cid.js";
9
+ import { encodeDRISL } from "./lib/drisl.js";
10
+ import { TileLoadError, failure, onPath } from "./lib/errors.js";
11
+ import { careful, get, parseJSON } from "./lib/fetching.js";
12
+ import type { Fetch } from "./lib/fetching.js";
13
+ import { limitsOf } from "./lib/limits.js";
14
+ import type { LoaderLimits } from "./lib/limits.js";
7
15
 
8
- type Fetch = typeof globalThis.fetch;
16
+ export { publicHost, publicEndpoint, localEndpoint } from "./lib/destinations.js";
17
+ export { recordCid } from "./lib/cid.js";
18
+ export { DEFAULT_LIMITS } from "./lib/limits.js";
19
+ export type { LoaderLimits } from "./lib/limits.js";
20
+
21
+ /**
22
+ * Which hosts the loader may be sent to. A tile's author writes the DID
23
+ * document that names them, and it is the viewer's browser that goes there.
24
+ */
25
+ export interface Destinations {
26
+ /** Whether a did:web's host may be asked for its document. `publicHost` unless given. */
27
+ did?: (host: string) => boolean;
28
+ /** The origin to fetch from for the PDS endpoint a DID document names, or false. `publicEndpoint` unless given. */
29
+ pds?: (endpoint: string) => string | false;
30
+ }
31
+
32
+ export interface ATLoaderOptions extends LoaderOptions {
33
+ /** The PLC directory, for a deployment with one of its own or a local one. `https://plc.directory` unless given. */
34
+ plcUrl?: string;
35
+ /**
36
+ * Which hosts to fetch from. Unless given, only https on public names, with
37
+ * no port and nothing else in the endpoint: see `publicEndpoint`. For local
38
+ * development, `{ pds: localEndpoint }` adds a PDS on this machine, over
39
+ * http and on any port. An embedder whose `fetch` goes through a proxy
40
+ * that makes checks of its own can pass its own rule; nobody else should.
41
+ */
42
+ destinations?: Destinations;
43
+ }
9
44
 
10
45
  interface DidDocument {
46
+ id?: string;
11
47
  alsoKnownAs?: string[];
12
48
  service?: Array<{ id?: string; type?: string; serviceEndpoint?: string }>;
13
49
  }
14
50
  interface ATRecord {
15
- value?: { tile?: StoredMasl };
51
+ value?: Record<string, unknown> & { tile?: StoredMasl };
52
+ }
53
+
54
+ // at://<a DID or a handle>/<collection>/<record key>, and after a `?` the
55
+ // CIDs that are expected, for a caller that has only a string to say it in.
56
+ const AT_URI = /^at:\/\/([^/?#\s]+)\/([^/?#\s]+)\/([A-Za-z0-9._:~-]{1,512})(?:\?([^#\s]*))?$/;
57
+
58
+ // What a loader and the tiles it loaded have in common: how they ask, how
59
+ // much they take, and the requests of theirs that are on their way.
60
+ interface Shared {
61
+ fetch: Fetch;
62
+ options: ATLoaderOptions;
63
+ limits: LoaderLimits;
64
+ flights: Map<string, Promise<Uint8Array>>;
65
+ }
66
+ function sharing (options: ATLoaderOptions): Shared {
67
+ return { fetch: careful(options.fetch), options, limits: limitsOf(options.limits), flights: new Map() };
68
+ }
69
+
70
+ // One request for one thing, however many are waiting for it: the same tile
71
+ // twice on a page, ten tiles of one author. What they share is the bytes.
72
+ function once (shared: Shared, key: string, ask: () => Promise<Uint8Array>): Promise<Uint8Array> {
73
+ const flying = shared.flights.get(key);
74
+ if (flying) return flying;
75
+ const flight = ask().finally(() => { shared.flights.delete(key); });
76
+ shared.flights.set(key, flight);
77
+ return flight;
16
78
  }
17
79
 
18
80
  /**
@@ -20,21 +82,32 @@ interface ATRecord {
20
82
  * we do not resolve. `did:plc` documents come from the PLC directory.
21
83
  * `did:web` as AT allows it names a host and nothing more: no path, and no
22
84
  * port (AT keeps ports for local development, which a tile host is not), so
23
- * the document is that host's `/.well-known/did.json`.
85
+ * the document is that host's `/.well-known/did.json`. The host has to be one
86
+ * to fetch from: a public name, unless `options.destinations` says otherwise.
24
87
  */
25
- export function didDocumentUrl (did: string): string | false {
26
- if (/^did:plc:[a-z2-7]{24}$/.test(did)) return `https://plc.directory/${did}`;
88
+ export function didDocumentUrl (did: string, options: ATLoaderOptions = {}): string | false {
89
+ if (/^did:plc:[a-z2-7]{24}$/.test(did)) return `${(options.plcUrl ?? 'https://plc.directory').replace(/\/$/, '')}/${did}`;
27
90
  const web = did.match(/^did:web:([a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)$/i);
28
- if (web) return `https://${web[1].toLowerCase()}/.well-known/did.json`;
29
- return false;
91
+ if (!web) return false;
92
+ // The host as the URL parser reads it is the one the request goes to.
93
+ let url: URL;
94
+ try { url = new URL(`https://${web[1]}/.well-known/did.json`); }
95
+ catch { return false; }
96
+ if (!(options.destinations?.did ?? publicHost)(url.hostname)) return false;
97
+ return url.href;
30
98
  }
31
99
 
32
- async function didDocument (fetch: Fetch, did: string): Promise<DidDocument | false> {
33
- const where = didDocumentUrl(did);
34
- if (!where) return false;
35
- const res = await fetch(where);
36
- if (!res.ok) return false;
37
- return await res.json() as DidDocument;
100
+ // A DID's document. What stands in the way is a TileLoadError that says what.
101
+ async function didDocument (shared: Shared, did: string): Promise<DidDocument> {
102
+ const where = didDocumentUrl(did, shared.options);
103
+ if (!where) throw new TileLoadError('destination', `${did} is not a DID this loader resolves`);
104
+ const what = `the DID document of ${did}`;
105
+ const { fetch, limits } = shared;
106
+ const bytes = await once(shared, `GET ${where}`, () => get(fetch, where, { maxBytes: limits.didDocumentBytes, ms: limits.requestMs, what }));
107
+ const doc = parseJSON(bytes, what) as DidDocument;
108
+ // A document is the DID's only if it says so itself.
109
+ if (!doc || typeof doc !== 'object' || doc.id !== did) throw new TileLoadError('not-found', `${what}: what was found is not its own`);
110
+ return doc;
38
111
  }
39
112
 
40
113
  /** The resolver handles are looked up with unless a loader is told otherwise. */
@@ -55,23 +128,37 @@ const DID = /^did:[a-z]+:[A-Za-z0-9._:%-]+$/;
55
128
  * that, anyone with a domain could point at somebody else's repo, or a
56
129
  * resolver could.
57
130
  */
58
- export async function resolveHandle (handle: string, options: { fetch?: Fetch; dnsOverHttps?: string | false } = {}): Promise<string | false> {
59
- const fetch: Fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
131
+ export async function resolveHandle (handle: string, options: ATLoaderOptions = {}): Promise<string | false> {
132
+ try { return (await handleDid(sharing(options), handle)).did; }
133
+ catch { return false; }
134
+ }
135
+
136
+ // The DID a handle names, with the document in which the DID says so too,
137
+ // or a TileLoadError that says why there is none.
138
+ async function handleDid (shared: Shared, handle: string): Promise<{ did: string; doc: DidDocument }> {
60
139
  const name = handle.toLowerCase();
61
- if (!HANDLE.test(name) || name.length > 253) return false;
140
+ const none = () => new TileLoadError('not-found', `No DID for ${handle}`);
141
+ if (!HANDLE.test(name) || name.length > 253) throw none();
142
+ const { fetch, options, limits } = shared;
143
+ const bounds = (what: string) => ({ maxBytes: limits.didDocumentBytes, ms: limits.requestMs, what });
62
144
  const doh = options.dnsOverHttps === undefined ? DEFAULT_DNS_OVER_HTTPS : options.dnsOverHttps;
145
+ // A lookup that failed in a way that may pass. If nothing else finds the
146
+ // DID, that is what went wrong, and not that there is none.
147
+ let failed: TileLoadError | undefined;
148
+ const mayPass = (err: unknown) => { if (err instanceof TileLoadError && err.retryable) failed = err; };
63
149
  const claims: Array<() => Promise<string | undefined>> = [];
64
150
  if (doh) {
65
151
  claims.push(async () => {
66
152
  const url = new URL(doh);
67
153
  url.searchParams.set('name', `_atproto.${name}`);
68
154
  url.searchParams.set('type', 'TXT');
69
- const res = await fetch(url.toString(), { headers: { accept: 'application/dns-json' } });
70
- if (!res.ok) return;
71
- const { Answer } = await res.json() as { Answer?: Array<{ type?: number; data?: string }> };
155
+ const what = `the DNS record of ${name}`;
156
+ let answer: { Answer?: Array<{ type?: number; data?: string }> };
157
+ try { answer = parseJSON(await get(fetch, url.toString(), { ...bounds(what), headers: { accept: 'application/dns-json' } }), what) as typeof answer; }
158
+ catch (err) { mayPass(err); return; }
72
159
  // TXT data comes quoted, and split into quoted chunks when long.
73
- const found = (Answer ?? [])
74
- .filter(a => a.type === 16 && typeof a.data === 'string')
160
+ const found = (Array.isArray(answer?.Answer) ? answer.Answer : [])
161
+ .filter(a => a?.type === 16 && typeof a.data === 'string')
75
162
  .map(a => (a.data as string).replace(/"\s*"/g, '').replace(/^"|"$/g, ''))
76
163
  .filter(txt => txt.startsWith('did='))
77
164
  .map(txt => txt.slice(4));
@@ -79,49 +166,89 @@ export async function resolveHandle (handle: string, options: { fetch?: Fetch; d
79
166
  return found.length === 1 ? found[0] : undefined;
80
167
  });
81
168
  }
82
- claims.push(async () => {
83
- const res = await fetch(`https://${name}/.well-known/atproto-did`);
84
- if (!res.ok) return;
85
- return (await res.text()).trim();
86
- });
169
+ // The handle's own host is one more that a tile's address names, and it is
170
+ // asked only if it is one to fetch from.
171
+ if ((options.destinations?.did ?? publicHost)(name)) {
172
+ claims.push(async () => {
173
+ // Unreachable, or not readable from here: that is most hosts, and no failure.
174
+ return new TextDecoder().decode(await get(fetch, `https://${name}/.well-known/atproto-did`, bounds(`${name}'s own word for its DID`))).trim();
175
+ });
176
+ }
87
177
  for (const claim of claims) {
88
178
  let did: string | undefined;
89
179
  try { did = await claim(); }
90
- catch { continue; } // unreachable, or not readable from here: try the other
180
+ catch { continue; } // try the other
91
181
  if (!did || !DID.test(did)) continue;
92
- let doc: DidDocument | false;
93
- try { doc = await didDocument(fetch, did); }
94
- catch { continue; }
95
- if (doc && Array.isArray(doc.alsoKnownAs) && doc.alsoKnownAs.some(aka => typeof aka === 'string' && aka.toLowerCase() === `at://${name}`)) return did;
182
+ let doc: DidDocument;
183
+ try { doc = await didDocument(shared, did); }
184
+ catch (err) { mayPass(err); continue; }
185
+ if (Array.isArray(doc.alsoKnownAs) && doc.alsoKnownAs.some(aka => typeof aka === 'string' && aka.toLowerCase() === `at://${name}`)) return { did, doc };
96
186
  }
97
- return false;
187
+ throw failed ?? none();
98
188
  }
99
189
 
100
- async function did2pds (fetch: Fetch, did: string): Promise<string | false | undefined> {
101
- const doc = await didDocument(fetch, did);
102
- if (!doc) return false;
190
+ // The origin of a DID's PDS, if its document names one we fetch from. It is
191
+ // asked for once for a tile, and all of the tile then comes from there:
192
+ // whatever the document says later, a running tile's requests go nowhere new.
193
+ // `known` is the document when it was read already, for a handle: the one in
194
+ // which the DID claims the handle is the one its PDS is taken from.
195
+ async function pdsOf (shared: Shared, did: string, known?: DidDocument): Promise<string> {
196
+ const doc = known ?? await didDocument(shared, did);
103
197
  // The id is "#atproto_pds", or the same spelled out with the DID in front.
104
- const pds = doc.service?.find(s => s.id === '#atproto_pds' || s.id === `${did}#atproto_pds`)?.serviceEndpoint;
105
- return typeof pds === 'string' ? pds : false;
198
+ const endpoint = (Array.isArray(doc.service) ? doc.service : [])
199
+ .find(s => (s?.id === '#atproto_pds' || s?.id === `${did}#atproto_pds`) && s.type === 'AtprotoPersonalDataServer')?.serviceEndpoint;
200
+ if (typeof endpoint !== 'string') throw new TileLoadError('not-found', `${did} names no PDS`);
201
+ const pds = (shared.options.destinations?.pds ?? publicEndpoint)(endpoint);
202
+ // An origin that is no URL to this browser is not one to fetch from either.
203
+ if (!pds || !originOf(pds)) throw new TileLoadError('destination', `${did} names a PDS this loader does not fetch from (${originOf(endpoint) || 'no URL'})`);
204
+ return pds;
106
205
  }
107
- async function fetchFromPDS (fetch: Fetch, did: string, query: string, params: Record<string, string>): Promise<Response | undefined> {
108
- const pds = await did2pds(fetch, did);
109
- if (!pds) return;
110
- const url = new URL(pds);
111
- url.pathname = `/xrpc/${query}`;
112
- const prm = url.searchParams;
113
- Object.entries(params).forEach(([k, v]) => prm.set(k, v));
114
- return await fetch(url.toString());
206
+
207
+ // Where a URL points: its origin, or its scheme where it has none, and
208
+ // nothing if it is no URL. For an error that says where a DID document
209
+ // points: an error is something a host may show its user, and the rest of
210
+ // the URL is the document's author's to write.
211
+ function originOf (url: string): string {
212
+ try {
213
+ const { origin, protocol } = new URL(url);
214
+ return (origin === 'null' ? protocol : origin).slice(0, 100);
215
+ }
216
+ catch { return ''; }
115
217
  }
116
- async function getRecord (fetch: Fetch, repo: string, collection: string, rkey: string): Promise<ATRecord | false> {
117
- const res = await fetchFromPDS(fetch, repo, 'com.atproto.repo.getRecord', { repo, collection, rkey })
118
- if (!res || !res.ok) return false;
119
- return await res.json() as ATRecord;
218
+
219
+ // Where to ask a PDS one of its queries.
220
+ function xrpc (pds: string, query: string, params: Record<string, string>): string {
221
+ const url = new URL(`/xrpc/${query}`, pds);
222
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
223
+ return url.toString();
120
224
  }
121
- async function getBlob (fetch: Fetch, did: string, cid: string): Promise<ArrayBuffer | false> {
122
- const res = await fetchFromPDS(fetch, did, 'com.atproto.sync.getBlob', { did, cid })
123
- if (!res || !res.ok) return false;
124
- return await res.arrayBuffer();
225
+
226
+ // A blob, from the PDS, checked against the CID that names it before anyone
227
+ // has a byte of it. `exactly` says that `maxBytes` is the size its record
228
+ // declares for it, which it then has to have.
229
+ async function verifiedBlob (shared: Shared, where: string, cid: string, maxBytes: number, exactly: boolean): Promise<Uint8Array> {
230
+ const { fetch, limits } = shared;
231
+ const what = `the blob ${cid}`;
232
+ let bytes: Uint8Array;
233
+ for (let asked = 1; ; asked++) {
234
+ try {
235
+ bytes = await get(fetch, where, { maxBytes, ms: limits.requestMs, what });
236
+ break;
237
+ }
238
+ catch (err) {
239
+ // A server error or a failed request may pass, and is worth asking
240
+ // again. A server that says it is busy is taken at its word.
241
+ const again = err instanceof TileLoadError && (err.code === 'upstream' || err.code === 'network') && asked <= limits.retries;
242
+ if (!again) throw err;
243
+ await new Promise(resolve => setTimeout(resolve, limits.retryMs * (1 + Math.random())));
244
+ }
245
+ }
246
+ if (exactly && bytes.byteLength !== maxBytes) {
247
+ throw new TileLoadError('integrity', `${what} is ${bytes.byteLength} bytes long, and its record says ${maxBytes}`, { expected: cid });
248
+ }
249
+ const { ok, actual } = await checkBytes(cid, bytes);
250
+ if (!ok) throw new TileLoadError('integrity', `${what}: the bytes are not what the CID names`, { expected: cid, actual });
251
+ return bytes;
125
252
  }
126
253
 
127
254
  // ### AT Loader
@@ -129,44 +256,423 @@ async function getBlob (fetch: Fetch, did: string, cid: string): Promise<ArrayBu
129
256
  // at://did:web:example.com/ing.dasl.masl/3mceykgxbkk2r
130
257
  // at://robin.berjon.com/ing.dasl.masl/3mceykgxbkk2r (a handle: see resolveHandle)
131
258
  export class ATTileLoader {
132
- #fetch: Fetch;
133
- #dnsOverHttps: string | false | undefined;
134
- constructor (options: LoaderOptions = {}) {
135
- this.#fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
136
- this.#dnsOverHttps = options.dnsOverHttps;
137
- }
138
- async load (url: string, mothership: TileMothership): Promise<Tile | false | undefined> {
139
- if (!/^at:\/\//.test(url)) return false;
140
- const [authority, collection, rkey] = url.replace(/^at:\/\//, '').split('/');
259
+ #shared: Shared;
260
+ constructor (options: ATLoaderOptions = {}) {
261
+ this.#shared = sharing(options);
262
+ loaders.set(this, this.#shared);
263
+ }
264
+ /**
265
+ * The tile at `url`: false for what is not an AT address, undefined for one
266
+ * that is not a tile's. A tile that could not be had is a rejection with a
267
+ * TileLoadError, whose `code` says what stood in the way: the handle or the
268
+ * DID has no answer (`not-found`), the record is not there (`not-found`),
269
+ * is not a tile's that can be run (`record-invalid`) or lists more than a
270
+ * tile may have (`over-budget`), a server is busy (`rate-limited`) or
271
+ * failing (`upstream`), did not answer in time (`timeout`) or could not be
272
+ * reached (`network`), or is not one to fetch from (`destination`).
273
+ *
274
+ * Loading a tile fetches its record and nothing else. Its resources are
275
+ * fetched when the host runs it, all of them and before it runs: see
276
+ * ATPathLoader.
277
+ *
278
+ * `options.cid` and `options.manifestCid` say which tile is expected: the
279
+ * CID of its record, the CID of its manifest alone, or both, of which
280
+ * either will do. A caller with only a string to say it in can give them
281
+ * at the end of the address, as `?cid=…&manifestCid=…`: they are read when
282
+ * the options give neither, and never beside them, since an address is
283
+ * often not the host's own writing. The record's CID is computed here, from
284
+ * the record as it came, and so is the manifest's: what the PDS says a
285
+ * record's CID is plays no part. A tile that is not the one expected is not
286
+ * loaded: the load fails with a TileLoadError, `record-changed`, which
287
+ * carries the CID that was `expected`, the `actual` one, and the
288
+ * `manifestCid` of what is there now. The tile that loads has its CIDs
289
+ * (`cid`, `manifestCid`) for a host to keep.
290
+ *
291
+ * The same content published again is a new record, with a new date and so
292
+ * a new CID, and the same manifest: a host that keeps the manifest's CID
293
+ * does not see a change where there is none.
294
+ */
295
+ async load (url: string, mothership: TileMothership, options: TileLoadOptions = {}): Promise<Tile | false | undefined> {
296
+ const address = url.match(AT_URI);
297
+ if (!address) return false;
298
+ const [, authority, collection, rkey, query] = address;
141
299
  if (collection !== 'ing.dasl.masl') return;
300
+ const asked = new URLSearchParams(query ?? '');
301
+ if ([...asked.keys()].some(key => key !== 'cid' && key !== 'manifestCid')) return false;
302
+ // What is expected is the host's to say. An address often comes from
303
+ // whoever posted the tile, so what it says is read only when the host
304
+ // says nothing: it never adds to what the host expects.
305
+ const hosts = options.cid != null || options.manifestCid != null;
306
+ const cid = (hosts ? options.cid : asked.get('cid')) ?? undefined;
307
+ const manifestCid = (hosts ? options.manifestCid : asked.get('manifestCid')) ?? undefined;
308
+ const expected = cid !== undefined || manifestCid !== undefined;
309
+ // What is expected is a record's CID or a manifest's: both are of DRISL.
310
+ for (const given of [cid, manifestCid]) {
311
+ if (given !== undefined && parseCid(given)?.codec !== DRISL) throw new TileLoadError('record-invalid', 'The CID that was expected is not one a record or a manifest can have.', { expected: given });
312
+ }
313
+ // A record holds its manifest, so the two never have one CID. A host that
314
+ // gives one for both does not know which it holds, and a manifest's CID
315
+ // taken for a record's is met by a record made of that manifest.
316
+ if (cid !== undefined && cid === manifestCid) throw new TileLoadError('record-invalid', 'One CID was given as the record\'s and as the manifest\'s, and they are never the same: give it as the one it is.', { expected: cid });
317
+ // The tile's address is the record's: what was expected is not part of it.
318
+ const bare = `at://${authority}/${collection}/${rkey}`;
142
319
  // The repo is a DID; a handle is a name for one. The tile keeps the URL
143
320
  // it was asked for by, and everything of it is fetched by DID.
144
- const repo = authority.startsWith('did:') ? authority : await resolveHandle(authority, { fetch: this.#fetch, dnsOverHttps: this.#dnsOverHttps });
145
- if (!repo) return false;
146
- const res = await getRecord(this.#fetch, repo, collection, rkey);
147
- if (!res) return false;
148
- const manifest = res.value?.tile;
149
- if (!manifest) return false;
150
- const loader = new ATPathLoader(repo, manifest, this.#fetch);
151
- return new Tile(mothership, url, manifest, loader);
321
+ const shared = this.#shared;
322
+ const named = authority.startsWith('did:') ? undefined : await handleDid(shared, authority);
323
+ const repo = named?.did ?? authority;
324
+ const pds = await pdsOf(shared, repo, named?.doc);
325
+ const where = xrpc(pds, 'com.atproto.repo.getRecord', { repo, collection, rkey });
326
+ const what = `the record at ${bare}`;
327
+ const res = parseJSON(await once(shared, `GET ${where}`, () => get(shared.fetch, where, { maxBytes: shared.limits.recordBytes, ms: shared.limits.requestMs, what })), what) as ATRecord;
328
+ const manifest = res?.value?.tile;
329
+ if (!manifest || typeof manifest !== 'object') throw new TileLoadError('record-invalid', `${what} is not a tile's`);
330
+ let found: { cid: string; manifestCid: string } | undefined;
331
+ // The bytes the manifest's CID is taken of, kept: they are what names
332
+ // the tile's origin where tiles run on the origin named by their CID,
333
+ // and what the runtime there checks against it. (A copy of its own: the
334
+ // encoder writes into a larger buffer, all of which would go with them.)
335
+ let manifestBytes: TileIdentity['manifestBytes'];
336
+ try {
337
+ const bytes = encodeDRISL(manifest).slice();
338
+ found = { cid: await recordCid(res.value), manifestCid: await cidOf(DRISL, bytes) };
339
+ manifestBytes = { cid: found.manifestCid, bytes };
340
+ }
341
+ catch (err) {
342
+ // A record that cannot be encoded has no CID to compare: without one
343
+ // expected it is loaded as it always was, and has none to show.
344
+ if (expected) throw new TileLoadError('record-invalid', `The record at ${bare} cannot be encoded for its CID to be checked: ${(err as Error).message}.`);
345
+ }
346
+ if (found && expected && !(cid !== undefined && found.cid === cid) && !(manifestCid !== undefined && found.manifestCid === manifestCid)) {
347
+ throw new TileLoadError('record-changed', `The tile at ${bare} is not the one expected: its record has changed.`, {
348
+ expected: cid ?? manifestCid,
349
+ actual: cid !== undefined ? found.cid : found.manifestCid,
350
+ manifestCid: found.manifestCid,
351
+ });
352
+ }
353
+ const loader = new ATPathLoader(repo, manifest, this, pds);
354
+ return new ATTile(mothership, bare, manifest, loader, { ...found, manifestBytes, pinned: expected });
355
+ }
356
+ }
357
+ // What each loader shares with the path loaders of the tiles it made.
358
+ const loaders = new WeakMap<ATTileLoader, Shared>();
359
+
360
+ // A tile from an AT record is fetched whole before it runs. Rendering it
361
+ // starts the fetching, and its runtime is only started once everything it
362
+ // lists is in memory; if that cannot be had, the runtime is not started at
363
+ // all. The host is told which it was: a `ready` event, or an `error` event
364
+ // whose `error` is the TileLoadError that says why. Rendering it again tries
365
+ // again.
366
+ class ATTile extends Tile {
367
+ #paths: ATPathLoader;
368
+ #whole: Promise<void> | undefined;
369
+ #starts = 0;
370
+ constructor (mothership: TileMothership, url: string, manifest: StoredMasl, paths: ATPathLoader, identity: TileIdentity) {
371
+ super(mothership, url, manifest, paths, identity);
372
+ this.#paths = paths;
373
+ // A tile that is closed while it is being fetched asks for nothing more.
374
+ this.addEventListener('close', () => paths.stop());
152
375
  }
376
+ attachIframe (ifr: HTMLIFrameElement) {
377
+ super.attachIframe(ifr);
378
+ // Asked for now, while the frame loads the runtime. What is said of it is
379
+ // for the frame the tile is in when it is said.
380
+ const id = this.runtimeId;
381
+ // The time a start is given (startDeadline) does not run while the tile
382
+ // is fetched, which can take longer: it runs from when all of it is
383
+ // here, and again from when its runtime is told to load (see start()).
384
+ // A tile that could not be had says so itself, as its one `error`.
385
+ this.awaits();
386
+ const whole = this.#whole = this.#paths.prepare();
387
+ whole.then(
388
+ () => {
389
+ if (this.runtimeId !== id) return;
390
+ this.watch();
391
+ this.dispatchEvent(new Event('ready'));
392
+ },
393
+ (error) => {
394
+ if (error instanceof TileLoadError) {
395
+ if (this.runtimeId === id) this.dispatchEvent(Object.assign(new Event('error'), { error }));
396
+ }
397
+ // A tile that was closed meanwhile is no failure. Anything else is ours.
398
+ else if (!(error instanceof Stopped)) console.error(`Could not fetch ${this.url}:`, error);
399
+ },
400
+ );
401
+ }
402
+ start () {
403
+ const id = this.runtimeId;
404
+ // A frame can load again while its tile is still being fetched (one that
405
+ // is moved in the document does). The runtime that is in it once the
406
+ // tile is here is started once, for the last of those loads.
407
+ const mine = ++this.#starts;
408
+ this.#whole?.then(() => { if (this.runtimeId === id && this.#starts === mine) super.start(); }, () => {});
409
+ }
410
+ }
411
+
412
+ // The CID a resource's `src` names, and the size it declares with it: a blob
413
+ // reference has one, a bare link does not. A record can hold anything there.
414
+ function named (src: unknown): { cid?: unknown; size?: unknown } {
415
+ if (!src || typeof src !== 'object') return {};
416
+ const { $link, ref, size } = src as { $link?: unknown; ref?: { $link?: unknown }; size?: unknown };
417
+ return $link !== undefined ? { cid: $link } : { cid: ref?.$link, size };
418
+ }
419
+
420
+ // What a manifest asks for.
421
+ interface Plan {
422
+ /** Every path it lists, with its entry (for the headers) and the CID of its bytes. */
423
+ paths: Map<string, { entry: StoredResourceEntry; cid: string }>;
424
+ /** Every blob it names, once, in the order they are fetched in, with the size declared for it and a path that names it. */
425
+ blobs: Array<{ cid: string; size?: number; path: string }>;
426
+ /** The sizes it declares, together. */
427
+ declared: number;
428
+ }
429
+
430
+ const utf8 = new TextEncoder();
431
+ // DRISL's order for the keys of a map: shorter first, then by bytes. It is
432
+ // the order a record has its paths in, whatever order a server lists them in.
433
+ function recordOrder (a: string, b: string): number {
434
+ const x = utf8.encode(a);
435
+ const y = utf8.encode(b);
436
+ if (x.length !== y.length) return x.length - y.length;
437
+ for (let i = 0; i < x.length; i++) {
438
+ if (x[i] !== y[i]) return x[i] - y[i];
439
+ }
440
+ return 0;
153
441
  }
442
+
443
+ // Reads a manifest for what it asks, before any of it is asked for: every
444
+ // resource has to name a CID, and what they add up to has to be within what
445
+ // a tile may have, going by the sizes the record declares. Throws a
446
+ // TileLoadError otherwise (`record-invalid`, `over-budget`).
447
+ function plan (manifest: StoredMasl, limits: LoaderLimits): Plan {
448
+ const invalid = (why: string) => new TileLoadError('record-invalid', `Not a tile that can be run: ${why}`);
449
+ const resources = manifest?.resources;
450
+ if (!resources || typeof resources !== 'object' || Array.isArray(resources)) throw invalid('it has no resources');
451
+ const paths: Plan['paths'] = new Map();
452
+ const blobs = new Map<string, Plan['blobs'][number]>();
453
+ for (const path of Object.keys(resources).sort(recordOrder)) {
454
+ const entry = resources[path];
455
+ const shown = JSON.stringify(path.slice(0, 80));
456
+ if (!path.startsWith('/')) throw invalid(`the path ${shown} does not start with a slash`);
457
+ if (!entry || typeof entry !== 'object') throw invalid(`${shown} is not a resource`);
458
+ const { cid, size } = named(entry.src);
459
+ if (typeof cid !== 'string' || !parseCid(cid)) throw invalid(`${shown} does not name a CID its bytes can be checked against`);
460
+ if (size !== undefined && !(Number.isSafeInteger(size) && (size as number) >= 0)) throw invalid(`${shown} declares a size that is not one`);
461
+ paths.set(path, { entry, cid });
462
+ const known = blobs.get(cid);
463
+ if (!known) blobs.set(cid, { cid, size: size as number | undefined, path });
464
+ else if (known.size === undefined) known.size = size as number | undefined;
465
+ else if (size !== undefined && size !== known.size) throw invalid(`${cid} is declared with two sizes`);
466
+ }
467
+ if (!paths.has('/')) throw invalid('it has no "/"');
468
+ const all = [...blobs.values()];
469
+ const declared = all.reduce((sum, blob) => sum + (blob.size ?? 0), 0);
470
+ const over = (why: string, limit: number, amount: number, path?: string) => new TileLoadError('over-budget', `More than a tile may have: ${why}`, { limit, amount, ...(path ? { path } : {}) });
471
+ if (all.length > limits.resources) throw over(`${all.length} resources, and ${limits.resources} are allowed`, limits.resources, all.length);
472
+ const large = all.find(blob => (blob.size ?? 0) > limits.resourceBytes);
473
+ if (large) throw over(`${JSON.stringify(large.path.slice(0, 80))} is ${large.size} bytes, and a resource may be ${limits.resourceBytes}`, limits.resourceBytes, large.size as number, large.path);
474
+ if (declared > limits.tileBytes) throw over(`${declared} bytes in all, and ${limits.tileBytes} are allowed`, limits.tileBytes, declared);
475
+ return { paths, blobs: all, declared };
476
+ }
477
+
478
+ // What a fetch that was called off is rejected with: the tile was closed.
479
+ class Stopped extends Error {
480
+ constructor () {
481
+ super('The tile was closed before all of it was here.');
482
+ }
483
+ }
484
+
485
+ /**
486
+ * The resources of a tile on AT, from its author's PDS, each checked against
487
+ * the CID its record names before any of it is served.
488
+ *
489
+ * What a tile asks for, and when, would be a message to its author's server
490
+ * if each request went there as it was made. So when the host runs the tile
491
+ * everything its record lists is fetched once (`prepare()`), in an order the
492
+ * record alone decides, and the tile is answered from memory: what it asks
493
+ * for after that reaches nobody, and what the PDS is asked depends on the
494
+ * record alone. The fetch is refused, not narrowed, when the record lists
495
+ * more than a tile may have: fetching the rest as the tile asked would bring
496
+ * the message back.
497
+ *
498
+ * Before the tile is run only the host can be asking, for a card's picture:
499
+ * that one resource is fetched by itself, within a size fit for a card.
500
+ *
501
+ * It is the tile the AT loader makes that calls `prepare()` when it is run.
502
+ * A host that makes a path loader of its own and runs it under a Tile of its
503
+ * own has to call `prepare()` itself, and run the tile once that has
504
+ * resolved: until it is called, every resource is fetched as it is asked
505
+ * for, the tile's requests among them.
506
+ */
154
507
  export class ATPathLoader {
155
508
  #did: string;
156
- #manifest: StoredMasl;
157
- #fetch: Fetch;
158
- constructor (did: string, manifest: StoredMasl, fetch: Fetch = (...args) => globalThis.fetch(...args)) {
509
+ #shared: Shared;
510
+ #pds: Promise<string> | undefined;
511
+ #plan: Plan;
512
+ // The resources that are here, checked, by CID.
513
+ #have = new Map<string, Uint8Array>();
514
+ // The fetching of all of them, from the moment the host runs the tile:
515
+ // whether all of it is here, whether it could not be had, and how to call
516
+ // it off.
517
+ #attempt: { whole: Promise<void>; done: boolean; failed: boolean; stop: (why: unknown) => void } | undefined;
518
+ /**
519
+ * `from` is the loader that made the tile, whose limits and requests in
520
+ * flight it shares, or the options for one on its own (a function is taken
521
+ * for its `fetch`, which is what this argument used to be). `pds` is the
522
+ * origin of the repo's PDS when it is known already: the loader has just
523
+ * asked, and a tile does not ask again. Throws a TileLoadError for a
524
+ * manifest that cannot be run (`record-invalid`) or that lists more than a
525
+ * tile may have (`over-budget`).
526
+ */
527
+ constructor (did: string, manifest: StoredMasl, from: ATTileLoader | ATLoaderOptions | Fetch = {}, pds?: string) {
159
528
  this.#did = did;
160
- this.#manifest = manifest;
161
- this.#fetch = fetch;
529
+ this.#shared = (from instanceof ATTileLoader && loaders.get(from)) || sharing(typeof from === 'function' ? { fetch: from } : from as ATLoaderOptions);
530
+ this.#plan = plan(manifest, this.#shared.limits);
531
+ if (pds) this.#pds = Promise.resolve(pds);
162
532
  }
533
+ /**
534
+ * Fetches everything the tile lists, once, checked, in the order of the
535
+ * record: first what the record declares the size of, `concurrency`
536
+ * requests at a time, then what it declares no size for, one at a time and
537
+ * each no further than what the tile has left. Resolves when all of it is
538
+ * in memory. Rejects with a TileLoadError when any of it could not be had,
539
+ * or was not all here within `prepareMs`; calling again then tries again,
540
+ * for what is still missing. The host's rendering the tile calls this;
541
+ * from then on `resolvePath()` asks nobody.
542
+ */
543
+ prepare (): Promise<void> {
544
+ if (this.#attempt && !this.#attempt.failed) return this.#attempt.whole;
545
+ const { limits } = this.#shared;
546
+ let stop!: (why: unknown) => void;
547
+ const calledOff = new Promise<never>((_, reject) => { stop = reject; });
548
+ const late = setTimeout(() => stop(new TileLoadError('timeout', `The tile was not all here within ${limits.prepareMs} ms`)), Math.min(limits.prepareMs, 2 ** 31 - 1));
549
+ const attempt = { done: false, failed: false, stop, whole: undefined as unknown as Promise<void> };
550
+ attempt.whole = Promise.race([this.#fetchAll(() => attempt.failed), calledOff])
551
+ .then(
552
+ () => { attempt.done = true; },
553
+ (err) => {
554
+ attempt.failed = true;
555
+ throw err;
556
+ },
557
+ )
558
+ .finally(() => clearTimeout(late));
559
+ // Whoever asked hears of it. Nobody asking is not an error.
560
+ attempt.whole.catch(() => {});
561
+ this.#attempt = attempt;
562
+ return attempt.whole;
563
+ }
564
+ /**
565
+ * Calls off a fetch of everything that has not come to its end: nothing
566
+ * more is asked for. What is here stays, and the requests already made run
567
+ * their course, since another tile may be waiting on them. For a tile that
568
+ * is closed before it could run, which is then as it was before the host
569
+ * ran it. A tile that is all here is left as it is.
570
+ */
571
+ stop () {
572
+ const attempt = this.#attempt;
573
+ if (!attempt || attempt.done) return;
574
+ attempt.failed = true;
575
+ attempt.stop(new Stopped());
576
+ this.#attempt = undefined;
577
+ }
578
+ // Every blob of the plan that is not here yet. `over` says when to stop
579
+ // asking: something failed, the time is up, or the tile was closed.
580
+ async #fetchAll (over: () => boolean): Promise<void> {
581
+ const { limits } = this.#shared;
582
+ const { blobs, declared } = this.#plan;
583
+ let failed: unknown;
584
+ const fail = (err: unknown, blob: Plan['blobs'][number]) => { failed ??= err instanceof TileLoadError ? onPath(err, blob.path) : err; };
585
+ // What the record declares the size of, which the plan has counted: a
586
+ // few at a time.
587
+ const queue = blobs.filter(blob => blob.size !== undefined);
588
+ const lane = async () => {
589
+ while (queue.length && !failed && !over()) {
590
+ const blob = queue.shift() as Plan['blobs'][number];
591
+ try { await this.#blob(blob, 0); }
592
+ catch (err) { fail(err, blob); }
593
+ }
594
+ };
595
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limits.concurrency, queue.length)) }, lane));
596
+ // A blob that declares no size is counted as it arrives. These come one
597
+ // after the other, each read no further than a resource may be and than
598
+ // the tile has left: several at once would each be read that far, and a
599
+ // record that declares nothing would have the page take more than one
600
+ // that declares it all.
601
+ let left = limits.tileBytes - declared;
602
+ // `amount` is what the tile comes to, where a blob was read to its end.
603
+ const tooMuch = (amount?: number) => new TileLoadError('over-budget', `More than a tile may have: over ${limits.tileBytes} bytes in all`, { limit: limits.tileBytes, ...(amount === undefined ? {} : { amount }) });
604
+ for (const blob of blobs) {
605
+ if (blob.size !== undefined) continue;
606
+ if (failed || over()) break;
607
+ const room = Math.max(0, Math.min(limits.resourceBytes, left));
608
+ try {
609
+ left -= (await this.#blob(blob, room)).byteLength;
610
+ // (What was here already, for a card, was read to a limit of its own.)
611
+ if (left < 0) throw tooMuch(limits.tileBytes - left);
612
+ }
613
+ catch (err) {
614
+ // Longer than the tile has left, where a resource may be longer: it
615
+ // is the tile that is too large, and not this one resource.
616
+ const tiles = err instanceof TileLoadError && err.code === 'too-large' && room < limits.resourceBytes;
617
+ fail(tiles ? tooMuch() : err, blob);
618
+ }
619
+ }
620
+ if (failed) throw failed;
621
+ }
622
+ /**
623
+ * The resource at `path`. A path the tile does not list is a 404, and
624
+ * nobody is asked. Once the host has run the tile the answer comes from
625
+ * memory, when all of the tile is there; if it could not all be had, every
626
+ * path is answered with that failure (a 502, a 503 when the PDS is busy, a
627
+ * 504 when it took too long, a 507 when it is more than a tile may have),
628
+ * which carries the TileLoadError that says why. Before that, the one
629
+ * resource is fetched and checked by itself, if it is no larger than
630
+ * `cardBytes`.
631
+ */
163
632
  async resolvePath (path: string): Promise<MaslResponse> {
164
- const entry = this.#manifest?.resources?.[path];
165
- if (!entry?.src) return NOT_FOUND;
166
- const src = entry.src;
167
- const cid = '$link' in src ? src.$link : src.ref.$link;
168
- const data = await getBlob(this.#fetch, this.#did, cid);
169
- if (!data) return NOT_FOUND;
170
- return maslResponse(entry, data);
633
+ const listed = this.#plan.paths.get(path);
634
+ if (!listed) return NOT_FOUND;
635
+ const { entry, cid } = listed;
636
+ try {
637
+ if (this.#attempt) {
638
+ await this.#attempt.whole;
639
+ return maslResponse(entry, this.#have.get(cid));
640
+ }
641
+ // The tile is not running, so it is the host asking, to draw a card.
642
+ const blob = this.#plan.blobs.find(b => b.cid === cid) as Plan['blobs'][number];
643
+ const { cardBytes } = this.#shared.limits;
644
+ if ((blob.size ?? 0) > cardBytes) {
645
+ throw new TileLoadError('too-large', `${JSON.stringify(path.slice(0, 80))} is ${blob.size} bytes, and ${cardBytes} are allowed before a tile is run`, { limit: cardBytes });
646
+ }
647
+ return maslResponse(entry, await this.#blob(blob, cardBytes));
648
+ }
649
+ catch (err) {
650
+ if (!(err instanceof TileLoadError)) throw err;
651
+ // The error may be one that several are being told of: each gets its own.
652
+ return failure(onPath(err, err.path ?? path));
653
+ }
654
+ }
655
+ // The bytes of a blob, checked: from memory, or from the PDS, where one
656
+ // request serves all who ask for the same at the same time. `room` is how
657
+ // much of one that declares no size is read.
658
+ async #blob (blob: Plan['blobs'][number], room: number): Promise<Uint8Array> {
659
+ const here = this.#have.get(blob.cid);
660
+ if (here) return here;
661
+ const declared = blob.size !== undefined;
662
+ const maxBytes = declared ? blob.size as number : room;
663
+ const pds = await this.#resolved();
664
+ const where = xrpc(pds, 'com.atproto.sync.getBlob', { did: this.#did, cid: blob.cid });
665
+ const bytes = await once(this.#shared, `GET ${where} ${declared ? 'of' : 'within'} ${maxBytes}`, () => verifiedBlob(this.#shared, where, blob.cid, maxBytes, declared));
666
+ this.#have.set(blob.cid, bytes);
667
+ return bytes;
668
+ }
669
+ // The PDS, asked for once. A lookup that failed is not kept: the next
670
+ // request for a resource asks again.
671
+ #resolved (): Promise<string> {
672
+ this.#pds ??= pdsOf(this.#shared, this.#did).catch((err) => {
673
+ this.#pds = undefined;
674
+ throw err;
675
+ });
676
+ return this.#pds;
171
677
  }
172
678
  }