@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.
- package/README.md +1463 -36
- package/dist/at.d.ts +126 -12
- package/dist/at.d.ts.map +1 -1
- package/dist/at.js +582 -90
- package/dist/at.js.map +1 -1
- package/dist/car.d.ts +21 -2
- package/dist/car.d.ts.map +1 -1
- package/dist/car.js +82 -15
- package/dist/car.js.map +1 -1
- package/dist/content-scheme.d.ts +17 -3
- package/dist/content-scheme.d.ts.map +1 -1
- package/dist/content-scheme.js +32 -6
- package/dist/content-scheme.js.map +1 -1
- package/dist/guard.d.ts +342 -0
- package/dist/guard.d.ts.map +1 -0
- package/dist/guard.js +1544 -0
- package/dist/guard.js.map +1 -0
- package/dist/index.d.ts +416 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +999 -74
- package/dist/index.js.map +1 -1
- package/dist/lib/cid.d.ts +25 -0
- package/dist/lib/cid.d.ts.map +1 -0
- package/dist/lib/cid.js +65 -0
- package/dist/lib/cid.js.map +1 -0
- package/dist/lib/defaults.d.ts +8 -0
- package/dist/lib/defaults.d.ts.map +1 -0
- package/dist/lib/defaults.js +14 -0
- package/dist/lib/defaults.js.map +1 -0
- package/dist/lib/destinations.d.ts +25 -0
- package/dist/lib/destinations.d.ts.map +1 -0
- package/dist/lib/destinations.js +94 -0
- package/dist/lib/destinations.js.map +1 -0
- package/dist/lib/drisl.d.ts +10 -0
- package/dist/lib/drisl.d.ts.map +1 -0
- package/dist/lib/drisl.js +169 -0
- package/dist/lib/drisl.js.map +1 -0
- package/dist/lib/errors.d.ts +80 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +44 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/fetching.d.ts +24 -0
- package/dist/lib/fetching.d.ts.map +1 -0
- package/dist/lib/fetching.js +135 -0
- package/dist/lib/fetching.js.map +1 -0
- package/dist/lib/limits.d.ts +34 -0
- package/dist/lib/limits.d.ts.map +1 -0
- package/dist/lib/limits.js +33 -0
- package/dist/lib/limits.js.map +1 -0
- package/dist/lib/pointer.d.ts +83 -0
- package/dist/lib/pointer.d.ts.map +1 -0
- package/dist/lib/pointer.js +244 -0
- package/dist/lib/pointer.js.map +1 -0
- package/dist/lib/tab-order.d.ts +16 -0
- package/dist/lib/tab-order.d.ts.map +1 -0
- package/dist/lib/tab-order.js +66 -0
- package/dist/lib/tab-order.js.map +1 -0
- package/dist/link.d.ts +110 -13
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +336 -43
- package/dist/link.js.map +1 -1
- package/dist/memory.d.ts +1 -0
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +5 -0
- package/dist/memory.js.map +1 -1
- package/dist/mount.d.ts +54 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +289 -0
- package/dist/mount.js.map +1 -0
- package/dist/size.d.ts +43 -2
- package/dist/size.d.ts.map +1 -1
- package/dist/size.js +296 -15
- package/dist/size.js.map +1 -1
- package/package.json +13 -3
- package/src/at.ts +590 -84
- package/src/car.ts +79 -16
- package/src/content-scheme.ts +38 -7
- package/src/guard.ts +1659 -0
- package/src/index.ts +1124 -74
- package/src/lib/cid.ts +65 -0
- package/src/lib/defaults.ts +12 -0
- package/src/lib/destinations.ts +79 -0
- package/src/lib/drisl.ts +160 -0
- package/src/lib/errors.ts +111 -0
- package/src/lib/fetching.ts +138 -0
- package/src/lib/limits.ts +61 -0
- package/src/lib/pointer.ts +290 -0
- package/src/lib/tab-order.ts +66 -0
- package/src/link.ts +365 -48
- package/src/memory.ts +5 -0
- package/src/mount.ts +359 -0
- package/src/size.ts +304 -16
package/src/lib/cid.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
|
|
2
|
+
import { fromString, toString } from '@atcute/cid';
|
|
3
|
+
import type { Cid } from '@atcute/cid';
|
|
4
|
+
import { encodeDRISL } from "./drisl.js";
|
|
5
|
+
import { TileLoadError } from "./errors.js";
|
|
6
|
+
|
|
7
|
+
const SHA256 = 0x12;
|
|
8
|
+
/** The codec of a CID that names DRISL: a record's, a manifest's. */
|
|
9
|
+
export const DRISL = 0x71;
|
|
10
|
+
|
|
11
|
+
/** A CID as DASL has them (CIDv1, raw or DRISL, SHA-256), parsed, or undefined for anything else. */
|
|
12
|
+
export function parseCid (cid: unknown): Cid | undefined {
|
|
13
|
+
if (typeof cid !== 'string') return undefined;
|
|
14
|
+
try { return fromString(cid); }
|
|
15
|
+
catch { return undefined; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// The hash is the browser's own: nothing here depends on how a library takes
|
|
19
|
+
// it. A page that is not a secure context has none, and then nothing can be
|
|
20
|
+
// checked, so nothing is served.
|
|
21
|
+
async function sha256 (bytes: Uint8Array): Promise<Uint8Array> {
|
|
22
|
+
const subtle = globalThis.crypto?.subtle;
|
|
23
|
+
if (!subtle) throw new TileLoadError('integrity', 'A tile\'s content cannot be checked in this page: it has no WebCrypto, which takes a secure context');
|
|
24
|
+
return new Uint8Array(await subtle.digest('SHA-256', bytes as BufferSource));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// A CID is its version, the codec of what it names, the hash's code and
|
|
28
|
+
// length, and the hash.
|
|
29
|
+
function cidString (codec: number, digest: Uint8Array): string {
|
|
30
|
+
const bytes = new Uint8Array(4 + digest.length);
|
|
31
|
+
bytes.set([1, codec, SHA256, digest.length]);
|
|
32
|
+
bytes.set(digest, 4);
|
|
33
|
+
return toString({ version: 1, codec, digest: { codec: SHA256, contents: bytes.subarray(4) }, bytes });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The CID of `bytes` under `codec` (0x55 for raw bytes, 0x71 for DRISL), as a string. */
|
|
37
|
+
export async function cidOf (codec: number, bytes: Uint8Array): Promise<string> {
|
|
38
|
+
return cidString(codec, await sha256(bytes));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The CID of `value` as a record has one: its DRISL encoding, hashed. For a
|
|
43
|
+
* record's CID, `value` is the whole of what `getRecord` gives as its `value`
|
|
44
|
+
* (`$type`, `cid`, `tile`, `createdAt`); for a manifest's, the manifest. This
|
|
45
|
+
* is the CID a strong reference to a record carries, computed here: what a
|
|
46
|
+
* server reports as a record's CID is never used. Throws for a value that
|
|
47
|
+
* cannot be encoded.
|
|
48
|
+
*/
|
|
49
|
+
export async function recordCid (value: unknown): Promise<string> {
|
|
50
|
+
return cidOf(DRISL, encodeDRISL(value));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Whether `bytes` are what `cid` names. `actual` is the CID they do have;
|
|
55
|
+
* there is none when `cid` is not a CID at all.
|
|
56
|
+
*/
|
|
57
|
+
export async function checkBytes (cid: string, bytes: Uint8Array): Promise<{ ok: boolean; actual?: string }> {
|
|
58
|
+
const want = parseCid(cid);
|
|
59
|
+
if (!want) return { ok: false };
|
|
60
|
+
const digest = await sha256(bytes);
|
|
61
|
+
const named = want.digest.contents;
|
|
62
|
+
let same = digest.length === named.length;
|
|
63
|
+
for (let i = 0; same && i < digest.length; i++) same = digest[i] === named[i];
|
|
64
|
+
return { ok: same, actual: same ? cid : cidString(want.codec, digest) };
|
|
65
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defaults`, with what `given` sets in their place. An option that is there
|
|
3
|
+
* but `undefined` is one that was not given: it does not take a default away.
|
|
4
|
+
*/
|
|
5
|
+
export function withDefaults<T extends object> (defaults: T, given: { [K in keyof T]?: T[K] } = {}): T {
|
|
6
|
+
const all = { ...defaults };
|
|
7
|
+
for (const key of Object.keys(defaults) as (keyof T)[]) {
|
|
8
|
+
const value = given[key];
|
|
9
|
+
if (value !== undefined) all[key] = value as T[keyof T];
|
|
10
|
+
}
|
|
11
|
+
return all;
|
|
12
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
|
|
2
|
+
// Which hosts a loader running in the viewer's browser may be sent to by a
|
|
3
|
+
// DID document, which anyone can write.
|
|
4
|
+
//
|
|
5
|
+
// This is a filter on names. It cannot know what a name resolves to: a public
|
|
6
|
+
// name that points at a private address passes it. What stops that is the
|
|
7
|
+
// browser, where it keeps public pages from the local network, or a proxy
|
|
8
|
+
// that resolves the name itself. The filter is there so that the plain cases
|
|
9
|
+
// never become a request at all, in any browser.
|
|
10
|
+
|
|
11
|
+
// Names that are never a public host: the special-use ones (RFC 6761, 6762,
|
|
12
|
+
// 8375, 9476, ICANN's reserved .internal) and the ones private networks use
|
|
13
|
+
// by habit.
|
|
14
|
+
const NOT_PUBLIC = new Set([
|
|
15
|
+
'localhost', 'localdomain', 'local', 'internal', 'intranet', 'lan', 'home', 'corp', 'private',
|
|
16
|
+
'test', 'invalid', 'example', 'onion', 'alt', 'arpa', 'i2p', 'bit',
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `hostname`, lowercased, if it is a public DNS name, and false otherwise. A
|
|
21
|
+
* public name has at least two labels of letters, digits and hyphens, is not
|
|
22
|
+
* an address, and does not end in a special-use name. The URL parser reads a
|
|
23
|
+
* host whose last label is a number as an IPv4 address, in decimal or in hex
|
|
24
|
+
* (`10.0.0.0x5` is 10.0.0.5, `2130706433` is 127.0.0.1): such a host is an
|
|
25
|
+
* address however it is spelled.
|
|
26
|
+
*/
|
|
27
|
+
export function publicHost (hostname: string): string | false {
|
|
28
|
+
if (typeof hostname !== 'string') return false;
|
|
29
|
+
let name = hostname.toLowerCase();
|
|
30
|
+
if (name.endsWith('.')) name = name.slice(0, -1);
|
|
31
|
+
if (!name || name.length > 253) return false;
|
|
32
|
+
if (name.startsWith('[') || name.includes(':')) return false; // IPv6
|
|
33
|
+
const labels = name.split('.');
|
|
34
|
+
if (labels.length < 2) return false;
|
|
35
|
+
if (!labels.every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))) return false;
|
|
36
|
+
const top = labels[labels.length - 1];
|
|
37
|
+
if (/^(?:[0-9]+|0x[0-9a-f]*)$/.test(top) || NOT_PUBLIC.has(top)) return false; // IPv4, or not public
|
|
38
|
+
return name;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// An endpoint as AT has it: a scheme, a host, perhaps a port, and nothing else.
|
|
42
|
+
function bareOrigin (endpoint: string): URL | false {
|
|
43
|
+
if (typeof endpoint !== 'string' || endpoint.length > 2048) return false;
|
|
44
|
+
let url: URL;
|
|
45
|
+
try { url = new URL(endpoint); }
|
|
46
|
+
catch { return false; }
|
|
47
|
+
if (url.username || url.password) return false;
|
|
48
|
+
if (url.pathname !== '/' || url.search || url.hash) return false;
|
|
49
|
+
return url;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The origin of a PDS endpoint as a DID document gives it, if it is one to
|
|
54
|
+
* fetch from, and false otherwise: an https URL on a public name with nothing
|
|
55
|
+
* else in it. A port is refused unless `allowPort`: no PDS in production needs
|
|
56
|
+
* one, and a port is how a document points a browser at any service it likes.
|
|
57
|
+
*/
|
|
58
|
+
export function publicEndpoint (endpoint: string, options: { allowPort?: boolean } = {}): string | false {
|
|
59
|
+
const url = bareOrigin(endpoint);
|
|
60
|
+
if (!url || url.protocol !== 'https:') return false;
|
|
61
|
+
if (url.port && !options.allowPort) return false;
|
|
62
|
+
if (!publicHost(url.hostname)) return false;
|
|
63
|
+
return url.origin;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* For local development: what `publicEndpoint` accepts, and a PDS on this
|
|
68
|
+
* machine, over http or https and on any port (`http://localhost:2583`).
|
|
69
|
+
* Only this machine: `localhost`, a name under it, `127.0.0.1` and `[::1]`.
|
|
70
|
+
*/
|
|
71
|
+
export function localEndpoint (endpoint: string): string | false {
|
|
72
|
+
const known = publicEndpoint(endpoint);
|
|
73
|
+
if (known) return known;
|
|
74
|
+
const url = bareOrigin(endpoint);
|
|
75
|
+
if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:')) return false;
|
|
76
|
+
const name = url.hostname.toLowerCase();
|
|
77
|
+
if (name !== 'localhost' && !name.endsWith('.localhost') && name !== '127.0.0.1' && name !== '[::1]') return false;
|
|
78
|
+
return url.origin;
|
|
79
|
+
}
|
package/src/lib/drisl.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
|
|
2
|
+
// DRISL (https://dasl.ing/drisl.html), one way: from what JSON gives us to the
|
|
3
|
+
// bytes a CID is taken of. It is what a record has to be put through to know
|
|
4
|
+
// its CID for ourselves, without taking a server's word for it.
|
|
5
|
+
|
|
6
|
+
import { fromString } from '@atcute/cid';
|
|
7
|
+
|
|
8
|
+
const utf8 = new TextEncoder();
|
|
9
|
+
|
|
10
|
+
// Bytes that grow as they are written.
|
|
11
|
+
class Writer {
|
|
12
|
+
#bytes = new Uint8Array(1024);
|
|
13
|
+
#length = 0;
|
|
14
|
+
#room (more: number): number {
|
|
15
|
+
const at = this.#length;
|
|
16
|
+
if (at + more > this.#bytes.length) {
|
|
17
|
+
const grown = new Uint8Array(Math.max(this.#bytes.length * 2, at + more));
|
|
18
|
+
grown.set(this.#bytes.subarray(0, at));
|
|
19
|
+
this.#bytes = grown;
|
|
20
|
+
}
|
|
21
|
+
this.#length = at + more;
|
|
22
|
+
return at;
|
|
23
|
+
}
|
|
24
|
+
// Room is made before the bytes are looked at: making it can move them.
|
|
25
|
+
byte (value: number) {
|
|
26
|
+
const at = this.#room(1);
|
|
27
|
+
this.#bytes[at] = value;
|
|
28
|
+
}
|
|
29
|
+
bytes (value: Uint8Array) {
|
|
30
|
+
const at = this.#room(value.length);
|
|
31
|
+
this.#bytes.set(value, at);
|
|
32
|
+
}
|
|
33
|
+
// A major type and its argument, in the fewest bytes that hold it: CBOR's
|
|
34
|
+
// head, and the one form DRISL allows.
|
|
35
|
+
head (major: number, argument: number) {
|
|
36
|
+
const type = major << 5;
|
|
37
|
+
if (argument < 24) return this.byte(type | argument);
|
|
38
|
+
if (argument < 0x100) return this.bytes(Uint8Array.of(type | 24, argument));
|
|
39
|
+
if (argument < 0x10000) return this.bytes(Uint8Array.of(type | 25, argument >>> 8, argument & 0xff));
|
|
40
|
+
const at = this.#room(argument < 0x100000000 ? 5 : 9);
|
|
41
|
+
const view = new DataView(this.#bytes.buffer);
|
|
42
|
+
if (argument < 0x100000000) {
|
|
43
|
+
view.setUint8(at, type | 26);
|
|
44
|
+
view.setUint32(at + 1, argument);
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
view.setUint8(at, type | 27);
|
|
48
|
+
view.setUint32(at + 1, Math.floor(argument / 0x100000000));
|
|
49
|
+
view.setUint32(at + 5, argument >>> 0);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
float (value: number) {
|
|
53
|
+
const at = this.#room(9);
|
|
54
|
+
const view = new DataView(this.#bytes.buffer);
|
|
55
|
+
view.setUint8(at, 0xfb);
|
|
56
|
+
view.setFloat64(at + 1, value);
|
|
57
|
+
}
|
|
58
|
+
done (): Uint8Array {
|
|
59
|
+
return this.#bytes.subarray(0, this.#length);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// DRISL's order for the keys of a map: shorter first, then by bytes.
|
|
64
|
+
function byLengthThenBytes (a: Uint8Array, b: Uint8Array): number {
|
|
65
|
+
if (a.length !== b.length) return a.length - b.length;
|
|
66
|
+
for (let i = 0; i < a.length; i++) {
|
|
67
|
+
if (a[i] !== b[i]) return a[i] - b[i];
|
|
68
|
+
}
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// A string in UTF-8. JSON can write half of a surrogate pair on its own,
|
|
73
|
+
// which is no character and has no UTF-8: an encoder puts U+FFFD in its
|
|
74
|
+
// place, and two strings that differ would then be hashed as the same.
|
|
75
|
+
function text (value: string): Uint8Array {
|
|
76
|
+
for (let i = 0; i < value.length; i++) {
|
|
77
|
+
const unit = value.charCodeAt(i);
|
|
78
|
+
if (unit < 0xd800 || unit > 0xdfff) continue;
|
|
79
|
+
// The first half of a pair, then the second, and neither without the other.
|
|
80
|
+
const next = unit < 0xdc00 ? value.charCodeAt(++i) : NaN;
|
|
81
|
+
if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError('a string that is not Unicode text');
|
|
82
|
+
}
|
|
83
|
+
return utf8.encode(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Standard base64, with or without its padding: AT writes bytes without. One
|
|
87
|
+
// way of writing each run of bytes and no other, as for all that is hashed:
|
|
88
|
+
// atob() alone would take a few.
|
|
89
|
+
function base64 (text: string): Uint8Array {
|
|
90
|
+
const bare = text.replace(/={1,2}$/, '');
|
|
91
|
+
if (!/^[A-Za-z0-9+/]*$/.test(bare) || bare.length % 4 === 1) throw new TypeError('not base64');
|
|
92
|
+
const binary = atob(text);
|
|
93
|
+
if (btoa(binary).replace(/=+$/, '') !== bare) throw new TypeError('not base64');
|
|
94
|
+
return Uint8Array.from(binary, c => c.charCodeAt(0));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function write (out: Writer, value: unknown) {
|
|
98
|
+
if (value === null) return out.byte(0xf6);
|
|
99
|
+
if (value === false) return out.byte(0xf4);
|
|
100
|
+
if (value === true) return out.byte(0xf5);
|
|
101
|
+
if (typeof value === 'number') {
|
|
102
|
+
// Integers in the range JSON can be trusted with, and floats at their
|
|
103
|
+
// full width. Anything larger has already lost digits on the way here.
|
|
104
|
+
if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER) throw new RangeError(`a number DRISL cannot hold: ${value}`);
|
|
105
|
+
if (!Number.isInteger(value)) return out.float(value);
|
|
106
|
+
return value < 0 ? out.head(1, -value - 1) : out.head(0, value);
|
|
107
|
+
}
|
|
108
|
+
if (typeof value === 'string') {
|
|
109
|
+
const bytes = text(value);
|
|
110
|
+
out.head(3, bytes.length);
|
|
111
|
+
return out.bytes(bytes);
|
|
112
|
+
}
|
|
113
|
+
if (Array.isArray(value)) {
|
|
114
|
+
out.head(4, value.length);
|
|
115
|
+
for (const item of value) write(out, item);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (typeof value === 'object') {
|
|
119
|
+
const map = value as Record<string, unknown>;
|
|
120
|
+
const keys = Object.keys(map).filter(key => map[key] !== undefined);
|
|
121
|
+
// The AT data model's two ways of writing in JSON what JSON does not have.
|
|
122
|
+
if (keys.length === 1 && keys[0] === '$link') {
|
|
123
|
+
if (typeof map.$link !== 'string') throw new TypeError('a link that is not a CID');
|
|
124
|
+
const cid = fromString(map.$link).bytes;
|
|
125
|
+
out.head(6, 42);
|
|
126
|
+
out.head(2, cid.length + 1);
|
|
127
|
+
out.byte(0);
|
|
128
|
+
return out.bytes(cid);
|
|
129
|
+
}
|
|
130
|
+
if (keys.length === 1 && keys[0] === '$bytes') {
|
|
131
|
+
if (typeof map.$bytes !== 'string') throw new TypeError('bytes that are not base64');
|
|
132
|
+
const bytes = base64(map.$bytes);
|
|
133
|
+
out.head(2, bytes.length);
|
|
134
|
+
return out.bytes(bytes);
|
|
135
|
+
}
|
|
136
|
+
const entries = keys.map(key => ({ key, name: text(key) })).sort((a, b) => byLengthThenBytes(a.name, b.name));
|
|
137
|
+
out.head(5, entries.length);
|
|
138
|
+
for (const { key, name } of entries) {
|
|
139
|
+
out.head(3, name.length);
|
|
140
|
+
out.bytes(name);
|
|
141
|
+
write(out, map[key]);
|
|
142
|
+
}
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
throw new TypeError(`not something DRISL holds: ${typeof value}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `value`, as JSON gives it, in DRISL: the deterministic CBOR that a record
|
|
150
|
+
* is hashed in. It is read in the AT data model, where an object whose only
|
|
151
|
+
* key is `$link` is a CID and one whose only key is `$bytes` is bytes. Map
|
|
152
|
+
* keys go in DRISL's order, integers in their shortest form, floats in 64
|
|
153
|
+
* bits. Throws for what DRISL does not hold: a number beyond the safe
|
|
154
|
+
* integers, a link that is not a CID, a string that is not Unicode text.
|
|
155
|
+
*/
|
|
156
|
+
export function encodeDRISL (value: unknown): Uint8Array {
|
|
157
|
+
const out = new Writer();
|
|
158
|
+
write(out, value);
|
|
159
|
+
return out.done();
|
|
160
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
|
|
2
|
+
import type { MaslResponseError } from '@dasl/tile-lexicon';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What went wrong:
|
|
6
|
+
*
|
|
7
|
+
* - `record-changed`: the tile is not the one its host expected (`expected`,
|
|
8
|
+
* `actual`, and `manifestCid` for what is there now).
|
|
9
|
+
* - `record-invalid`: not a tile's record, or not one that can be checked.
|
|
10
|
+
* - `not-found`: the DID, the record or a resource does not exist.
|
|
11
|
+
* - `integrity`: bytes are not what the CID that names them says (`path`,
|
|
12
|
+
* `expected`, `actual`).
|
|
13
|
+
* - `too-large`: an answer was longer than it is allowed to be (`limit`).
|
|
14
|
+
* - `over-budget`: the tile asks for more than a tile may have (`limit`, and
|
|
15
|
+
* `amount` for what it asks).
|
|
16
|
+
* - `destination`: a DID, a DID document or a PDS the loader does not fetch
|
|
17
|
+
* from.
|
|
18
|
+
* - `rate-limited`: a server said 429 (`retryAfter`, in seconds, when it
|
|
19
|
+
* says).
|
|
20
|
+
* - `upstream`: a server failed (5xx), or answered what is no answer.
|
|
21
|
+
* - `timeout`: no answer in time.
|
|
22
|
+
* - `network`: the request failed: unreachable, refused by the browser, or
|
|
23
|
+
* answered with a redirect.
|
|
24
|
+
*
|
|
25
|
+
* The last four may pass: `retryable` says so.
|
|
26
|
+
*/
|
|
27
|
+
export type TileLoadErrorCode =
|
|
28
|
+
| 'record-changed' | 'record-invalid' | 'not-found' | 'integrity' | 'too-large' | 'over-budget' | 'destination'
|
|
29
|
+
| 'rate-limited' | 'upstream' | 'timeout' | 'network';
|
|
30
|
+
|
|
31
|
+
const RETRYABLE: TileLoadErrorCode[] = ['rate-limited', 'upstream', 'timeout', 'network'];
|
|
32
|
+
|
|
33
|
+
/** What a TileLoadError can say besides its code. */
|
|
34
|
+
export interface TileLoadErrorDetails {
|
|
35
|
+
/** The resource it happened on, when it was one. */
|
|
36
|
+
path?: string;
|
|
37
|
+
/** The CID that was expected. */
|
|
38
|
+
expected?: string;
|
|
39
|
+
/** The CID that was found in its place. */
|
|
40
|
+
actual?: string;
|
|
41
|
+
/** The CID of the manifest that was found, when a tile is not the one expected. */
|
|
42
|
+
manifestCid?: string;
|
|
43
|
+
/** The HTTP status a server answered with. */
|
|
44
|
+
status?: number;
|
|
45
|
+
/** How long a server that is limiting requests asks to be left alone, in seconds. */
|
|
46
|
+
retryAfter?: number;
|
|
47
|
+
/** The limit that was passed. */
|
|
48
|
+
limit?: number;
|
|
49
|
+
/** How much there was of what the limit is on. */
|
|
50
|
+
amount?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Why a tile could not be loaded, or why something of it could not be had.
|
|
55
|
+
* `code` says which kind of failure it is, so that a host can tell a tile
|
|
56
|
+
* that is not what it should be from one that is simply not there.
|
|
57
|
+
*/
|
|
58
|
+
export class TileLoadError extends Error implements TileLoadErrorDetails {
|
|
59
|
+
code: TileLoadErrorCode;
|
|
60
|
+
/** Whether trying again later can help. */
|
|
61
|
+
retryable: boolean;
|
|
62
|
+
path?: string;
|
|
63
|
+
expected?: string;
|
|
64
|
+
actual?: string;
|
|
65
|
+
manifestCid?: string;
|
|
66
|
+
status?: number;
|
|
67
|
+
retryAfter?: number;
|
|
68
|
+
limit?: number;
|
|
69
|
+
amount?: number;
|
|
70
|
+
constructor (code: TileLoadErrorCode, message: string, details: TileLoadErrorDetails = {}) {
|
|
71
|
+
super(message);
|
|
72
|
+
this.name = 'TileLoadError';
|
|
73
|
+
this.code = code;
|
|
74
|
+
this.retryable = RETRYABLE.includes(code);
|
|
75
|
+
Object.assign(this, details);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The `error` event of a tile when something of it could not be had: `error`
|
|
81
|
+
* says why. It has no `reason`, which is what the other `error` of a tile has
|
|
82
|
+
* (TileErrorEvent, for a start that failed for some other cause).
|
|
83
|
+
*/
|
|
84
|
+
export interface TileLoadErrorEvent extends Event {
|
|
85
|
+
error: TileLoadError;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A resource that could not be served, with the reason. */
|
|
89
|
+
export interface TileLoadFailure extends MaslResponseError {
|
|
90
|
+
error: TileLoadError;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// What a tile is answered for one of its resources that could not be had.
|
|
94
|
+
// Never 404: that is for a path the tile does not have, and a resource its
|
|
95
|
+
// record lists and its PDS lacks is a broken tile, not an unknown path.
|
|
96
|
+
const STATUS: Partial<Record<TileLoadErrorCode, [number, string]>> = {
|
|
97
|
+
'rate-limited': [503, 'Service Unavailable'],
|
|
98
|
+
timeout: [504, 'Gateway Timeout'],
|
|
99
|
+
'over-budget': [507, 'Insufficient Storage'],
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** `error`, as it happened to the resource at `path`: a copy, since one failure can be several resources'. */
|
|
103
|
+
export function onPath (error: TileLoadError, path: string): TileLoadError {
|
|
104
|
+
return Object.assign(new TileLoadError(error.code, error.message), error, { path });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The answer for a resource that failed with `error`. */
|
|
108
|
+
export function failure (error: TileLoadError): TileLoadFailure {
|
|
109
|
+
const [status, statusText] = STATUS[error.code] ?? [502, 'Bad Gateway'];
|
|
110
|
+
return { ok: false, status, statusText, error };
|
|
111
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
|
|
2
|
+
import { TileLoadError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export type Fetch = typeof globalThis.fetch;
|
|
5
|
+
|
|
6
|
+
// How a loader asks. It follows no redirect: where it goes is checked before
|
|
7
|
+
// it asks, and a redirect is a server sending the viewer's browser on to
|
|
8
|
+
// somewhere that was not checked. Where a tile's author says where to go
|
|
9
|
+
// (`anonymous`), the page's own fetch also sends nothing of the viewer's but
|
|
10
|
+
// the request itself. A `fetch` the host gave us is the host's way to its own
|
|
11
|
+
// backend, which may need the session it has there, so that much is left to
|
|
12
|
+
// it.
|
|
13
|
+
export function careful (given?: Fetch, anonymous = true): Fetch {
|
|
14
|
+
if (given) return (input, init) => given(input, { ...init, redirect: 'error' });
|
|
15
|
+
if (!anonymous) return (input, init) => globalThis.fetch(input, { ...init, redirect: 'error' });
|
|
16
|
+
return (input, init) => globalThis.fetch(input, { ...init, redirect: 'error', credentials: 'omit', referrerPolicy: 'no-referrer' });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface Bounds {
|
|
20
|
+
/** The most bytes the answer may have. */
|
|
21
|
+
maxBytes: number;
|
|
22
|
+
/** How long it may take, headers and body, in milliseconds. */
|
|
23
|
+
ms: number;
|
|
24
|
+
/** What is being asked for, for the error that says it could not be had. */
|
|
25
|
+
what: string;
|
|
26
|
+
headers?: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// What an answer that is not a success means. A server that is busy or broken
|
|
30
|
+
// is not a server that says there is no such thing.
|
|
31
|
+
function refusal (res: Response, what: string): TileLoadError {
|
|
32
|
+
const { status } = res;
|
|
33
|
+
if (status === 429) {
|
|
34
|
+
// Retry-After is only readable across origins if the server exposes it;
|
|
35
|
+
// RateLimit-Reset is what a PDS exposes. A PDS gives it in seconds since
|
|
36
|
+
// the epoch; the header as it is being specified is in seconds from now,
|
|
37
|
+
// which no time since the epoch can be taken for.
|
|
38
|
+
const after = Number(res.headers?.get('retry-after'));
|
|
39
|
+
const reset = Number(res.headers?.get('ratelimit-reset'));
|
|
40
|
+
let retryAfter: number | undefined;
|
|
41
|
+
if (Number.isFinite(after) && after > 0) retryAfter = Math.ceil(after);
|
|
42
|
+
else if (Number.isFinite(reset) && reset > 0) retryAfter = Math.max(1, Math.ceil(reset > 1e9 ? reset - Date.now() / 1000 : reset));
|
|
43
|
+
return new TileLoadError('rate-limited', `${what}: the server is limiting requests (429)`, { status, retryAfter });
|
|
44
|
+
}
|
|
45
|
+
if (status >= 500) return new TileLoadError('upstream', `${what}: the server failed (${status})`, { status });
|
|
46
|
+
if (status >= 300 && status < 400) return new TileLoadError('network', `${what}: the answer is a redirect (${status}), and none is followed`, { status });
|
|
47
|
+
return new TileLoadError('not-found', `${what}: not found${status ? ` (${status})` : ''}`, { status });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The body, read no further than `maxBytes`.
|
|
51
|
+
async function read (res: Response, maxBytes: number, what: string): Promise<Uint8Array> {
|
|
52
|
+
const tooLarge = () => new TileLoadError('too-large', `${what}: more than the ${maxBytes} bytes allowed`, { limit: maxBytes });
|
|
53
|
+
// A length that is announced is the length on the wire, which for a
|
|
54
|
+
// compressed body is not the one counted below: it only serves to refuse at
|
|
55
|
+
// once what is far too long, with room for what compressing adds to
|
|
56
|
+
// something that does not compress.
|
|
57
|
+
const announced = Number(res.headers?.get('content-length'));
|
|
58
|
+
if (Number.isFinite(announced) && announced > maxBytes + 1024 + maxBytes / 64) {
|
|
59
|
+
res.body?.cancel().catch(() => {});
|
|
60
|
+
throw tooLarge();
|
|
61
|
+
}
|
|
62
|
+
const reader = res.body?.getReader?.();
|
|
63
|
+
if (!reader) {
|
|
64
|
+
// A fetch of the host's without streams: the length is known afterwards.
|
|
65
|
+
const all = new Uint8Array(await res.arrayBuffer());
|
|
66
|
+
if (all.byteLength > maxBytes) throw tooLarge();
|
|
67
|
+
return all;
|
|
68
|
+
}
|
|
69
|
+
const chunks: Uint8Array[] = [];
|
|
70
|
+
let length = 0;
|
|
71
|
+
for (;;) {
|
|
72
|
+
const { done, value } = await reader.read();
|
|
73
|
+
if (done) break;
|
|
74
|
+
length += value.byteLength;
|
|
75
|
+
if (length > maxBytes) {
|
|
76
|
+
reader.cancel().catch(() => {});
|
|
77
|
+
throw tooLarge();
|
|
78
|
+
}
|
|
79
|
+
chunks.push(value);
|
|
80
|
+
}
|
|
81
|
+
// What is returned has a buffer of its own, and only its own bytes in it: it
|
|
82
|
+
// is handed on to the tile, buffer and all.
|
|
83
|
+
const [only] = chunks;
|
|
84
|
+
if (chunks.length === 1 && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength) return only;
|
|
85
|
+
const all = new Uint8Array(length);
|
|
86
|
+
let at = 0;
|
|
87
|
+
for (const chunk of chunks) {
|
|
88
|
+
all.set(chunk, at);
|
|
89
|
+
at += chunk.byteLength;
|
|
90
|
+
}
|
|
91
|
+
return all;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* GETs `url` and gives its body, within a time and a size. What goes wrong
|
|
96
|
+
* is a TileLoadError that says what it was: `timeout`, `network` (the request
|
|
97
|
+
* failed: unreachable, refused by the browser, a redirect), `rate-limited`,
|
|
98
|
+
* `upstream` (a server error), `not-found`, `too-large`. `fetch` is expected
|
|
99
|
+
* to stop when its signal says so and to give a body that streams; one that
|
|
100
|
+
* does neither is still held to the time, and to the size once it has
|
|
101
|
+
* answered.
|
|
102
|
+
*/
|
|
103
|
+
export async function get (fetch: Fetch, url: string, { maxBytes, ms, what, headers }: Bounds): Promise<Uint8Array> {
|
|
104
|
+
const stop = new AbortController();
|
|
105
|
+
let late: ReturnType<typeof setTimeout> | undefined;
|
|
106
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
107
|
+
late = setTimeout(() => {
|
|
108
|
+
reject(new TileLoadError('timeout', `${what}: no answer within ${ms} ms`));
|
|
109
|
+
stop.abort();
|
|
110
|
+
}, Math.min(ms, 2 ** 31 - 1)); // as long as a timer can be set for
|
|
111
|
+
});
|
|
112
|
+
const answer = (async () => {
|
|
113
|
+
const res = await fetch(url, { signal: stop.signal, ...(headers ? { headers } : {}) });
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
res.body?.cancel().catch(() => {});
|
|
116
|
+
throw refusal(res, what);
|
|
117
|
+
}
|
|
118
|
+
return read(res, maxBytes, what);
|
|
119
|
+
})();
|
|
120
|
+
// Once the time is up the answer is nobody's: what it fails with then is not news.
|
|
121
|
+
answer.catch(() => {});
|
|
122
|
+
try {
|
|
123
|
+
return await Promise.race([answer, timeout]);
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
if (err instanceof TileLoadError) throw err;
|
|
127
|
+
throw new TileLoadError('network', `${what}: the request failed (${(err as Error)?.message ?? err})`);
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
clearTimeout(late);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** What `bytes` say as JSON. An answer that is not JSON is a server failing (`upstream`). */
|
|
135
|
+
export function parseJSON (bytes: Uint8Array, what: string): unknown {
|
|
136
|
+
try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
|
|
137
|
+
catch { throw new TileLoadError('upstream', `${what}: the answer is not JSON`); }
|
|
138
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
|
|
2
|
+
// How much a loader takes, and how long it waits. What a tile is made of
|
|
3
|
+
// comes from its author's servers, and a server can answer without end, or
|
|
4
|
+
// not at all. Every figure here is a first guess: a host that knows better
|
|
5
|
+
// replaces any of them with the `limits` option of a loader.
|
|
6
|
+
|
|
7
|
+
export interface LoaderLimits {
|
|
8
|
+
/** A DID document, in bytes. */
|
|
9
|
+
didDocumentBytes: number;
|
|
10
|
+
/** A record as a PDS gives it, in bytes. */
|
|
11
|
+
recordBytes: number;
|
|
12
|
+
/** Any one resource of a tile, in bytes. A resource whose record declares its size is held to that. */
|
|
13
|
+
resourceBytes: number;
|
|
14
|
+
/** How many resources a tile may have that are not the same bytes. */
|
|
15
|
+
resources: number;
|
|
16
|
+
/** All the resources of a tile together, in bytes: what a running tile holds in the host page's memory. */
|
|
17
|
+
tileBytes: number;
|
|
18
|
+
/** A resource asked for before the tile is run, in bytes: a card's picture, of which a feed draws many. */
|
|
19
|
+
cardBytes: number;
|
|
20
|
+
/** A tile that comes as one file (a .tile, a .xdc), whole, in bytes. */
|
|
21
|
+
archiveBytes: number;
|
|
22
|
+
/** How many requests for a tile's resources are under way at once. Resources whose record declares no size are asked for one at a time. */
|
|
23
|
+
concurrency: number;
|
|
24
|
+
/** One request, from asking to the last byte of the answer, in milliseconds. */
|
|
25
|
+
requestMs: number;
|
|
26
|
+
/** All of a tile, from the moment it is run to the moment everything it lists is here, in milliseconds. A tile that comes as one file has as long to arrive. */
|
|
27
|
+
prepareMs: number;
|
|
28
|
+
/** How many times a resource is asked for again after a server error or a failed request. Never after a 429. */
|
|
29
|
+
retries: number;
|
|
30
|
+
/** How long to wait before asking again, in milliseconds. Up to as much again is added, so that viewers do not all come back at once. */
|
|
31
|
+
retryMs: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_LIMITS: LoaderLimits = {
|
|
35
|
+
didDocumentBytes: 64 * 1024,
|
|
36
|
+
recordBytes: 1024 * 1024,
|
|
37
|
+
resourceBytes: 10 * 1024 * 1024,
|
|
38
|
+
resources: 256,
|
|
39
|
+
tileBytes: 25 * 1024 * 1024,
|
|
40
|
+
cardBytes: 2 * 1024 * 1024,
|
|
41
|
+
archiveBytes: 32 * 1024 * 1024,
|
|
42
|
+
concurrency: 6,
|
|
43
|
+
requestMs: 20_000,
|
|
44
|
+
prepareMs: 60_000,
|
|
45
|
+
retries: 1,
|
|
46
|
+
retryMs: 300,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The limits a loader works to: these, and what its host put in their place.
|
|
51
|
+
* A limit is a number that is not negative; `Infinity` is no limit, except
|
|
52
|
+
* for how often to ask again, which has to end.
|
|
53
|
+
*/
|
|
54
|
+
export function limitsOf (given: Partial<LoaderLimits> = {}): LoaderLimits {
|
|
55
|
+
const limits = { ...DEFAULT_LIMITS };
|
|
56
|
+
for (const key of Object.keys(limits) as Array<keyof LoaderLimits>) {
|
|
57
|
+
const value = given[key];
|
|
58
|
+
if (typeof value === 'number' && value >= 0 && (key !== 'retries' || Number.isFinite(value))) limits[key] = value;
|
|
59
|
+
}
|
|
60
|
+
return limits;
|
|
61
|
+
}
|