@dasl/tile-loader 2.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/dist/lib/el.js ADDED
@@ -0,0 +1,31 @@
1
+ export function el(n, attrs, kids, p) {
2
+ const e = document.createElement(n);
3
+ Object.entries(attrs || {}).forEach(([k, v]) => {
4
+ if (v == null)
5
+ return;
6
+ if (k === 'style') {
7
+ Object.entries(v).forEach(([prop, value]) => {
8
+ const snake = prop
9
+ .split('-')
10
+ .map((part, idx) => idx ? part.charAt(0).toUpperCase() + part.slice(1) : part)
11
+ .join('');
12
+ e.style[snake] = value;
13
+ });
14
+ return;
15
+ }
16
+ e.setAttribute(k, String(v));
17
+ });
18
+ (kids || []).forEach((n) => {
19
+ if (typeof n === 'string')
20
+ e.append(txt(n));
21
+ else
22
+ e.append(n);
23
+ });
24
+ if (p)
25
+ p.append(e);
26
+ return e;
27
+ }
28
+ function txt(str) {
29
+ return document.createTextNode(str);
30
+ }
31
+ //# sourceMappingURL=el.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"el.js","sourceRoot":"","sources":["../../src/lib/el.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,EAAE,CAAE,CAAS,EAAE,KAAmC,EAAE,IAAwB,EAAE,CAAkB;IAC9G,MAAM,CAAC,GAAG,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE;QAC7C,IAAI,CAAC,IAAI,IAAI;YAAE,OAAO;QACtB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;YAClB,MAAM,CAAC,OAAO,CAAC,CAA2B,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE;gBACpE,MAAM,KAAK,GAAG,IAAI;qBACf,KAAK,CAAC,GAAG,CAAC;qBACV,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;qBAC7E,IAAI,CAAC,EAAE,CAAC,CAAC;gBACX,CAAC,CAAC,KAA2C,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;YAChE,CAAC,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,CAAC,CAAC,YAAY,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;IACH,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;QACzB,IAAI,OAAO,CAAC,KAAK,QAAQ;YAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;;YACvC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACnB,CAAC,CAAC,CAAC;IACH,IAAI,CAAC;QAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACnB,OAAO,CAAC,CAAC;AACX,CAAC;AAED,SAAS,GAAG,CAAE,GAAW;IACvB,OAAO,QAAQ,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { MaslHeaders, MaslResponse, MaslResponseError } from '@dasl/tile-lexicon';
2
+ export declare const NOT_FOUND: MaslResponseError;
3
+ export declare const maslHeaders: readonly ["content-disposition", "content-encoding", "content-language", "content-security-policy", "content-type", "link", "permissions-policy", "referrer-policy", "service-worker-allowed", "sourcemap", "speculation-rules", "supports-loading-mode", "x-content-type-options"];
4
+ export declare function maslResponse(masl: MaslHeaders, body: ArrayBuffer | Uint8Array | string | null | undefined): MaslResponse;
5
+ //# sourceMappingURL=masl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masl.d.ts","sourceRoot":"","sources":["../../src/lib/masl.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvF,eAAO,MAAM,SAAS,EAAE,iBAAuE,CAAC;AAEhG,eAAO,MAAM,WAAW,qRAcd,CAAC;AAEX,wBAAgB,YAAY,CAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,YAAY,CAQzH"}
@@ -0,0 +1,29 @@
1
+ export const NOT_FOUND = { ok: false, status: 404, statusText: 'Not found' };
2
+ export const maslHeaders = [
3
+ 'content-disposition',
4
+ 'content-encoding',
5
+ 'content-language',
6
+ 'content-security-policy',
7
+ 'content-type',
8
+ 'link',
9
+ 'permissions-policy',
10
+ 'referrer-policy',
11
+ 'service-worker-allowed',
12
+ 'sourcemap',
13
+ 'speculation-rules',
14
+ 'supports-loading-mode',
15
+ 'x-content-type-options',
16
+ ];
17
+ export function maslResponse(masl, body) {
18
+ if (!body)
19
+ return NOT_FOUND;
20
+ const headers = {};
21
+ maslHeaders.forEach(k => {
22
+ if (typeof masl[k] !== 'undefined')
23
+ headers[k] = masl[k];
24
+ });
25
+ if (typeof body === 'string')
26
+ body = (new TextEncoder()).encode(body);
27
+ return { ok: true, status: 200, statusText: 'Ok', headers, body };
28
+ }
29
+ //# sourceMappingURL=masl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"masl.js","sourceRoot":"","sources":["../../src/lib/masl.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,SAAS,GAAsB,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;AAEhG,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,qBAAqB;IACrB,kBAAkB;IAClB,kBAAkB;IAClB,yBAAyB;IACzB,cAAc;IACd,MAAM;IACN,oBAAoB;IACpB,iBAAiB;IACjB,wBAAwB;IACxB,WAAW;IACX,mBAAmB;IACnB,uBAAuB;IACvB,wBAAwB;CAChB,CAAC;AAEX,MAAM,UAAU,YAAY,CAAE,IAAiB,EAAE,IAA0D;IACzG,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,MAAM,OAAO,GAAgB,EAAE,CAAC;IAChC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QACtB,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW;YAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;IACH,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,IAAI,GAAG,CAAC,IAAI,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpE,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { Tile } from "./index.js";
2
+ import type { TileMothership } from "./index.js";
3
+ import type { InMemoryMasl, MaslResponse } from "@dasl/tile-lexicon";
4
+ export declare class MemoryTileLoader {
5
+ #private;
6
+ addTile(id: string, manifest: InMemoryMasl): void;
7
+ load(url: string, mothership: TileMothership): Promise<Tile | false>;
8
+ }
9
+ export declare class MemoryPathLoader {
10
+ #private;
11
+ constructor(manifest: InMemoryMasl);
12
+ resolvePath(path: string): Promise<MaslResponse>;
13
+ }
14
+ //# sourceMappingURL=memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAMrE,qBAAa,gBAAgB;;IAE3B,OAAO,CAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY;IAGrC,IAAI,CAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;CAW5E;AAED,qBAAa,gBAAgB;;gBAEd,QAAQ,EAAE,YAAY;IAG7B,WAAW,CAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;CAKxD"}
package/dist/memory.js ADDED
@@ -0,0 +1,42 @@
1
+ import { Tile } from "./index.js";
2
+ import { NOT_FOUND, maslResponse } from "./lib/masl.js";
3
+ // ### Memory Loader
4
+ // This is mostly for debugging, experimentation.
5
+ // You create a loader that maps IDs to manifest-like structures. Then load(memory://ID)
6
+ // and the values in the manifest provide the content directly.
7
+ export class MemoryTileLoader {
8
+ #tiles = {};
9
+ addTile(id, manifest) {
10
+ this.#tiles[id] = manifest;
11
+ }
12
+ async load(url, mothership) {
13
+ let u;
14
+ try {
15
+ u = new URL(url);
16
+ }
17
+ catch {
18
+ return false;
19
+ } // not a URL we understand; let another loader try
20
+ if (u.protocol !== 'memory:')
21
+ return false;
22
+ const id = u.hostname;
23
+ if (!this.#tiles[id])
24
+ return false; // XXX an error would be better
25
+ const manifest = this.#tiles[id];
26
+ const loader = new MemoryPathLoader(manifest);
27
+ return new Tile(mothership, url, manifest, loader);
28
+ }
29
+ }
30
+ export class MemoryPathLoader {
31
+ #manifest;
32
+ constructor(manifest) {
33
+ this.#manifest = manifest;
34
+ }
35
+ async resolvePath(path) {
36
+ const entry = this.#manifest?.resources?.[path];
37
+ if (!entry?.src)
38
+ return NOT_FOUND;
39
+ return maslRes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,GAAG,QAAQ,CAAC;IAC5B,CAAC;IACD,KAAK,CAAC,WAAW,CAAE,IAAY;QAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,CAAC;QAChD,IAAI,CAAC,KAAK,EAAE,GAAG;YAAE,OAAO,SAAS,CAAC;QAClC,OAAO,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACxC,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ import { Tile } from "./index.js";
2
+ import type { TileMothership } from "./index.js";
3
+ import { ContentSchemeTileLoader } from "./content-scheme.js";
4
+ export declare class WebXDCTileLoader extends ContentSchemeTileLoader {
5
+ constructor(schemes?: string[]);
6
+ processContent(zipData: ArrayBuffer, _: string, url: string, mothership: TileMothership): Promise<Tile | false>;
7
+ }
8
+ //# sourceMappingURL=webxdc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webxdc.d.ts","sourceRoot":"","sources":["../src/webxdc.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAW9D,qBAAa,gBAAiB,SAAQ,uBAAuB;gBAC9C,OAAO,CAAC,EAAE,MAAM,EAAE;IAGzB,cAAc,CAAE,OAAO,EAAE,WAAW,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC;CAsCvH"}
package/dist/webxdc.js ADDED
@@ -0,0 +1,159 @@
1
+ import JSZip from "jszip";
2
+ import mime from 'mime/lite';
3
+ import { parse } from 'smol-toml';
4
+ import { Tile } from "./index.js";
5
+ import { ContentSchemeTileLoader } from "./content-scheme.js";
6
+ import { MemoryPathLoader } from './memory.js';
7
+ // ### WebXDC (DeltaChat) Loader
8
+ // WebXDC works this way:
9
+ // - It's a zip file with a bunch of files, you have to guess the media type.
10
+ // - It must have an index.html at the root, which is the /.
11
+ // - It may have icon.{png,jpg} at the root.
12
+ // - It may have a manifest.toml (seriously), that may have a name entry and
13
+ // one pointing to the source.
14
+ export class WebXDCTileLoader extends ContentSchemeTileLoader {
15
+ constructor(schemes) {
16
+ super(schemes);
17
+ }
18
+ async processContent(zipData, _, url, mothership) {
19
+ const zip = new JSZip();
20
+ try {
21
+ await zip.loadAsync(zipData);
22
+ }
23
+ catch (e) {
24
+ return false;
25
+ }
26
+ const manifest = {
27
+ resources: {},
28
+ };
29
+ // We could extract a description from index.html
30
+ for (const path of Object.keys(zip.files)) {
31
+ if (zip.files[path].dir)
32
+ continue;
33
+ const keyPath = (path === 'index.html') ? '/' : `/${path}`;
34
+ if (/^icon\.(png|jpg)$/.test(path)) {
35
+ if (!manifest.icons)
36
+ manifest.icons = [];
37
+ manifest.icons.push({ src: keyPath });
38
+ }
39
+ else if (path === 'manifest.toml') {
40
+ const toml = parse(await zip.files[path].async('text'));
41
+ manifest.name = toml.name;
42
+ }
43
+ const mediaType = mime.getType(path);
44
+ manifest.resources[keyPath] = {
45
+ src: await zip.files[path].async('arraybuffer'),
46
+ 'content-type': mediaType || undefined,
47
+ };
48
+ }
49
+ // Add webxdc.js. NOTE: we need to make this pluggable so that it can actually
50
+ // do some useful work.
51
+ manifest.resources['/webxdc.js'] = {
52
+ src: makeWebXDCAPI(),
53
+ 'content-type': 'application/javascript',
54
+ };
55
+ const loader = new MemoryPathLoader(manifest);
56
+ return new Tile(mothership, url, manifest, loader);
57
+ }
58
+ }
59
+ // This is the resource that implements webxdc.js. (Based on webxdc/hello.)
60
+ // Note that joinRealtimeChannel() is marked as optional, so we skip it.
61
+ // These are mostly stubs, e.g. sendToChat() just dumps to the console.
62
+ function makeWebXDCAPI({ selfName = 'Dazzling Kitten', selfAddr } = {}) {
63
+ return [
64
+ // self-func
65
+ `window.webxdc = (() => {`,
66
+ // utils
67
+ `let updateListener = (_) => {};
68
+ function getUpdates() {
69
+ const updatesJSON = window.localStorage.getItem(updatesKey);
70
+ return updatesJSON ? JSON.parse(updatesJSON) : [];
71
+ }
72
+ const updatesKey = "__xdcUpdatesKey__";
73
+ window.addEventListener("storage", (event) => {
74
+ if (event.key == null) {
75
+ window.location.reload();
76
+ } else if (event.key === updatesKey) {
77
+ const updates = JSON.parse(event.newValue);
78
+ const update = updates[updates.length - 1];
79
+ update.max_serial = updates.length;
80
+ console.log("[Webxdc] " + JSON.stringify(update));
81
+ updateListener(update);
82
+ } else if (event.key === ephemeralUpdateKey) {
83
+ const [sender, update] = JSON.parse(event.newValue);
84
+ // @ts-ignore: is_trashed() is private
85
+ if (
86
+ window.webxdc.selfAddr !== sender &&
87
+ realtimeListener &&
88
+ !realtimeListener.is_trashed()
89
+ ) {
90
+ realtimeListener.receive(Uint8Array.from(update));
91
+ }
92
+ }
93
+ });`,
94
+ // returned object
95
+ `return {`,
96
+ // selfies
97
+ `selfAddr: "${selfAddr || crypto.randomUUID()}",
98
+ selfName: "${selfName}",`,
99
+ // updates
100
+ `sendUpdate: (update) => {
101
+ console.log('sendUpdate', update);
102
+ },
103
+ setUpdateListener: () => {
104
+ },
105
+ getAllUpdates: () => {
106
+ console.log("[Webxdc] WARNING: getAllUpdates() is deprecated.");
107
+ return Promise.resolve([]);
108
+ },
109
+ setUpdateListener: (cb, serial = 0) => {
110
+ const updates = getUpdates();
111
+ const maxSerial = updates.length;
112
+ updates.forEach((update) => {
113
+ if (update.serial > serial) {
114
+ update.max_serial = maxSerial;
115
+ cb(update);
116
+ }
117
+ });
118
+ updateListener = cb;
119
+ return Promise.resolve();
120
+ },`,
121
+ // sendToChat
122
+ `sendToChat: async (content) => {
123
+ if (!content.file && !content.text) {
124
+ alert("🚨 Error: either file or text need to be set. (or both)");
125
+ return Promise.reject(
126
+ "Error from sendToChat: either file or text need to be set",
127
+ );
128
+ }
129
+ console.info('sendToChat', content);
130
+ },`,
131
+ // importFiles
132
+ `importFiles: (filters) => {
133
+ const accept = [
134
+ ...(filters.extensions || []),
135
+ ...(filters.mimeTypes || []),
136
+ ].join(",");
137
+ const element = document.createElement("input");
138
+ element.setAttribute('type', 'file');
139
+ element.setAttribute('accept', accept);
140
+ if (filters.multiple) element.setAttribute('multiple', 'multiple');
141
+ const promise = new Promise((resolve) => {
142
+ element.onchange = () => {
143
+ const files = Array.from(element.files || []);
144
+ document.body.removeChild(element);
145
+ resolve(files);
146
+ };
147
+ });
148
+ element.style.display = "none";
149
+ document.body.appendChild(element);
150
+ element.click();
151
+ return promise;
152
+ },`,
153
+ // close object
154
+ `};`,
155
+ // close self-func
156
+ `})();`
157
+ ].join('\n');
158
+ }
159
+ //# sourceMappingURL=webxdc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webxdc.js","sourceRoot":"","sources":["../src/webxdc.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,gCAAgC;AAChC,yBAAyB;AACzB,8EAA8E;AAC9E,6DAA6D;AAC7D,6CAA6C;AAC7C,6EAA6E;AAC7E,iCAAiC;AACjC,MAAM,OAAO,gBAAiB,SAAQ,uBAAuB;IAC3D,YAAa,OAAkB;QAC7B,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;IACD,KAAK,CAAC,cAAc,CAAE,OAAoB,EAAE,CAAS,EAAE,GAAW,EAAE,UAA0B;QAC5F,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC;YAC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C;QACD,8EAA8E;QAC9E,uBAAuB;QACvB,QAAQ,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG;YACjC,GAAG,EAAE,aAAa,EAAE;YACpB,cAAc,EAAE,wBAAwB;SACzC,CAAC;QACF,MAAM,MAAM,GAAG,IAAI,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QAC9C,OAAO,IAAI,IAAI,CAAC,UAAU,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IACrD,CAAC;CACF;AAED,2EAA2E;AAC3E,wEAAwE;AACxE,uEAAuE;AACvE,SAAS,aAAa,CAAE,EAAE,QAAQ,GAAG,iBAAiB,EAAE,QAAQ,KAA+C,EAAE;IAC/G,OAAO;QACL,YAAY;QACZ,0BAA0B;QAE1B,QAAQ;QACR;;;;;;;;;;;;;;;;;;;;;;;;;;QA0BI;QAEJ,kBAAkB;QAClB,UAAU;QACV,UAAU;QACV,cAAc,QAAQ,IAAI,MAAM,CAAC,UAAU,EAAE;iBAChC,QAAQ,IAAI;QAEzB,UAAU;QACV;;;;;;;;;;;;;;;;;;;;OAoBG;QAEH,aAAa;QACb;;;;;;;;OAQG;QAEH,cAAc;QACd;;;;;;;;;;;;;;;;;;;;OAoBG;QACH,eAAe;QACf,IAAI;QACJ,kBAAkB;QAClB,OAAO;KACR,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC"}
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@dasl/tile-loader",
3
+ "type": "module",
4
+ "version": "2.0.0",
5
+ "description": "Browser architecture for safely loading DASL tiles (mothership, shuttle, worker)",
6
+ "author": "Robin Berjon <robin@berjon.com>",
7
+ "license": "Apache-2.0",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "main": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./at": {
20
+ "types": "./dist/at.d.ts",
21
+ "import": "./dist/at.js",
22
+ "default": "./dist/at.js"
23
+ },
24
+ "./car": {
25
+ "types": "./dist/car.d.ts",
26
+ "import": "./dist/car.js",
27
+ "default": "./dist/car.js"
28
+ },
29
+ "./memory": {
30
+ "types": "./dist/memory.d.ts",
31
+ "import": "./dist/memory.js",
32
+ "default": "./dist/memory.js"
33
+ },
34
+ "./content-scheme": {
35
+ "types": "./dist/content-scheme.d.ts",
36
+ "import": "./dist/content-scheme.js",
37
+ "default": "./dist/content-scheme.js"
38
+ },
39
+ "./webxdc": {
40
+ "types": "./dist/webxdc.d.ts",
41
+ "import": "./dist/webxdc.js",
42
+ "default": "./dist/webxdc.js"
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "src"
48
+ ],
49
+ "scripts": {
50
+ "build": "tsc",
51
+ "prepublishOnly": "npm run build",
52
+ "test": "mocha"
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "https://github.com/darobin/dasl-tiles.git",
57
+ "directory": "tile-loader"
58
+ },
59
+ "devDependencies": {
60
+ "global-jsdom": "^24.0.0",
61
+ "jsdom": "^24.1.3",
62
+ "mocha": "^11.7.6"
63
+ },
64
+ "dependencies": {
65
+ "@atcute/car": "^6.0.0",
66
+ "@atcute/cid": "^2.4.1",
67
+ "@dasl/tile-lexicon": "^2.0.0",
68
+ "jszip": "^3.10.1",
69
+ "mime": "^4.1.0",
70
+ "smol-toml": "^1.6.1"
71
+ }
72
+ }
package/src/at.ts ADDED
@@ -0,0 +1,73 @@
1
+
2
+ import { Tile } from "./index.js";
3
+ import type { TileMothership } from "./index.js";
4
+ import { NOT_FOUND, maslResponse } from "./lib/masl.js";
5
+ import type { StoredMasl, MaslResponse } from "@dasl/tile-lexicon";
6
+
7
+ interface DidDocument {
8
+ service?: Array<{ id?: string; type?: string; serviceEndpoint?: string }>;
9
+ }
10
+ interface ATRecord {
11
+ value?: { tile?: StoredMasl };
12
+ }
13
+
14
+ async function did2pds (did: string): Promise<string | false | undefined> {
15
+ if (!/^did:plc:/.test(did)) return false; // we should add did:web
16
+ const res = await fetch(`https://plc.directory/${did}`);
17
+ if (!res.ok) return false;
18
+ const doc = await res.json() as DidDocument;
19
+ const pds = doc.service?.find(s => s.id === '#atproto_pds')?.serviceEndpoint;
20
+ return pds;
21
+ }
22
+ async function fetchFromPDS (did: string, query: string, params: Record<string, string>): Promise<Response | undefined> {
23
+ const pds = await did2pds(did);
24
+ if (!pds) return;
25
+ const url = new URL(pds);
26
+ url.pathname = `/xrpc/${query}`;
27
+ const prm = url.searchParams;
28
+ Object.entries(params).forEach(([k, v]) => prm.set(k, v));
29
+ return await fetch(url.toString());
30
+ }
31
+ async function getRecord (repo: string, collection: string, rkey: string): Promise<ATRecord | false> {
32
+ const res = await fetchFromPDS(repo, 'com.atproto.repo.getRecord', { repo, collection, rkey })
33
+ if (!res || !res.ok) return false;
34
+ return await res.json() as ATRecord;
35
+ }
36
+ async function getBlob (did: string, cid: string): Promise<ArrayBuffer | false> {
37
+ const res = await fetchFromPDS(did, 'com.atproto.sync.getBlob', { did, cid })
38
+ if (!res || !res.ok) return false;
39
+ return await res.arrayBuffer();
40
+ }
41
+
42
+ // ### AT Loader
43
+ // at://did:plc:izttpdp3l6vss5crelt5kcux/ing.dasl.masl/3mceykgxbkk2r
44
+ export class ATTileLoader {
45
+ async load (url: string, mothership: TileMothership): Promise<Tile | false | undefined> {
46
+ if (!/^at:\/\//.test(url)) return false;
47
+ const [repo, collection, rkey] = url.replace(/^at:\/\//, '').split('/');
48
+ if (collection !== 'ing.dasl.masl') return;
49
+ const res = await getRecord(repo, collection, rkey);
50
+ if (!res) return false;
51
+ const manifest = res.value?.tile;
52
+ if (!manifest) return false;
53
+ const loader = new ATPathLoader(repo, manifest);
54
+ return new Tile(mothership, url, manifest, loader);
55
+ }
56
+ }
57
+ export class ATPathLoader {
58
+ #did: string;
59
+ #manifest: StoredMasl;
60
+ constructor (did: string, manifest: StoredMasl) {
61
+ this.#did = did;
62
+ this.#manifest = manifest;
63
+ }
64
+ async resolvePath (path: string): Promise<MaslResponse> {
65
+ const entry = this.#manifest?.resources?.[path];
66
+ if (!entry?.src) return NOT_FOUND;
67
+ const src = entry.src;
68
+ const cid = '$link' in src ? src.$link : src.ref.$link;
69
+ const data = await getBlob(this.#did, cid);
70
+ if (!data) return NOT_FOUND;
71
+ return maslResponse(entry, data);
72
+ }
73
+ }
package/src/car.ts ADDED
@@ -0,0 +1,62 @@
1
+
2
+ import { fromUint8Array } from '@atcute/car';
3
+ import { toCidLink, toString as stringifyCID } from '@atcute/cid';
4
+ import { ContentSchemeTileLoader } from "./content-scheme.js";
5
+ import { Tile } from "./index.js";
6
+ import type { TileMothership } from "./index.js";
7
+ import { NOT_FOUND, maslResponse } from "./lib/masl.js";
8
+ import type { StoredMasl, MaslResponse, CidLink } from "@dasl/tile-lexicon";
9
+
10
+ // ### CAR Tiles
11
+ export class CARTileLoader extends ContentSchemeTileLoader {
12
+ constructor (schemes?: string[]) {
13
+ super(schemes);
14
+ }
15
+ // NOTE: ignoring scheme for now, this is pure HTTP
16
+ async processContent (carData: ArrayBuffer, scheme: string, url: string, mothership: TileMothership): Promise<Tile | false> {
17
+ let car;
18
+ try {
19
+ car = fromUint8Array(new Uint8Array(carData));
20
+ }
21
+ catch (e) {
22
+ return false;
23
+ }
24
+ console.warn(`car`, car);
25
+ const { data } = car.header;
26
+ const manifest = data as StoredMasl;
27
+ delete manifest.version;
28
+ delete manifest.roots;
29
+ Object.keys(manifest.resources).forEach(k => {
30
+ manifest.resources[k].src = (toCidLink(manifest.resources[k].src as never) as unknown as { toJSON(): unknown }).toJSON() as CidLink;
31
+ });
32
+ // This isn't efficient in that it reads the bytes and we throw them away.
33
+ // We could replace it with a version that skips, but that'd be copying a
34
+ // lot of work from @atcute; we can optimise later.
35
+ const offsets: Record<string, [number, number]> = {};
36
+ for await (const entry of car) {
37
+ const { cid, bytesStart, bytesEnd } = entry;
38
+ offsets[stringifyCID(cid)] = [bytesStart, bytesEnd];
39
+ }
40
+ const loader = new CARPathLoader(manifest, carData, offsets);
41
+ return new Tile(mothership, url, manifest, loader);
42
+ }
43
+ }
44
+
45
+ export class CARPathLoader {
46
+ #manifest: StoredMasl;
47
+ #carData: ArrayBuffer;
48
+ #offsets: Record<string, [number, number]>;
49
+ constructor (manifest: StoredMasl, carData: ArrayBuffer, offsets: Record<string, [number, number]>) {
50
+ this.#manifest = manifest;
51
+ this.#carData = carData;
52
+ this.#offsets = offsets;
53
+ }
54
+ async resolvePath (path: string): Promise<MaslResponse> {
55
+ const entry = this.#manifest?.resources?.[path];
56
+ if (!entry?.src) return NOT_FOUND;
57
+ const src = entry.src;
58
+ const cid = '$link' in src ? src.$link : src.ref.$link;
59
+ const [start, end] = this.#offsets[cid];
60
+ return maslResponse(entry, this.#carData.slice(start, end));
61
+ }
62
+ }
@@ -0,0 +1,31 @@
1
+
2
+ import type { Tile, TileMothership } from "./index.js";
3
+
4
+ // ### Base Class for HTTP, file, etc. loaders
5
+ // Here the idea is that you can load from multiple schemes, but you might not
6
+ // want to.
7
+ export abstract class ContentSchemeTileLoader {
8
+ #schemes: Set<string>;
9
+ constructor (schemes: string[] = ['http', 'file']) {
10
+ this.#schemes = new Set(schemes);
11
+ }
12
+ async load (url: string, mothership: TileMothership): Promise<Tile | false | undefined> {
13
+ let u: URL;
14
+ try { u = new URL(url); }
15
+ catch { return false; } // not a URL we understand; let another loader try
16
+ if (u.protocol === 'https:' || u.protocol === 'http:') {
17
+ if (!this.#schemes.has('http')) return false;
18
+ const res = await fetch(url);
19
+ if (!res.ok) return false;
20
+ return await this.processContent(await res.arrayBuffer(), u.protocol, url, mothership);
21
+ }
22
+ if (u.protocol === 'file:') {
23
+ if (!this.#schemes.has('file')) return false;
24
+ // XXX
25
+ // - get the data
26
+ // - give it to processContent
27
+ }
28
+ return undefined;
29
+ }
30
+ abstract processContent (data: ArrayBuffer, scheme: string, url: string, mothership: TileMothership): Promise<Tile | false>;
31
+ }