@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/README.md +109 -0
- package/dist/at.d.ts +12 -0
- package/dist/at.d.ts.map +1 -0
- package/dist/at.js +73 -0
- package/dist/at.js.map +1 -0
- package/dist/car.d.ts +14 -0
- package/dist/car.d.ts.map +1 -0
- package/dist/car.js +59 -0
- package/dist/car.js.map +1 -0
- package/dist/content-scheme.d.ts +8 -0
- package/dist/content-scheme.d.ts.map +1 -0
- package/dist/content-scheme.js +35 -0
- package/dist/content-scheme.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +230 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/el.d.ts +4 -0
- package/dist/lib/el.d.ts.map +1 -0
- package/dist/lib/el.js +31 -0
- package/dist/lib/el.js.map +1 -0
- package/dist/lib/masl.d.ts +5 -0
- package/dist/lib/masl.d.ts.map +1 -0
- package/dist/lib/masl.js +29 -0
- package/dist/lib/masl.js.map +1 -0
- package/dist/memory.d.ts +14 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +42 -0
- package/dist/memory.js.map +1 -0
- package/dist/webxdc.d.ts +8 -0
- package/dist/webxdc.d.ts.map +1 -0
- package/dist/webxdc.js +159 -0
- package/dist/webxdc.js.map +1 -0
- package/package.json +72 -0
- package/src/at.ts +73 -0
- package/src/car.ts +62 -0
- package/src/content-scheme.ts +31 -0
- package/src/index.ts +240 -0
- package/src/lib/el.ts +30 -0
- package/src/lib/masl.ts +30 -0
- package/src/memory.ts +39 -0
- package/src/webxdc.ts +166 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
|
|
2
|
+
/*
|
|
3
|
+
████████╗██╗██╗ ███████╗███████╗
|
|
4
|
+
╚══██╔══╝██║██║ ██╔════╝██╔════╝
|
|
5
|
+
██║ ██║██║ █████╗ ███████╗
|
|
6
|
+
██║ ██║██║ ██╔══╝ ╚════██║
|
|
7
|
+
██║ ██║███████╗███████╗███████║
|
|
8
|
+
╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝
|
|
9
|
+
•--~~~## MOTHERSHIP ##~~~--•
|
|
10
|
+
|
|
11
|
+
The tile-loading architecture has three levels that all communicate together:
|
|
12
|
+
|
|
13
|
+
- At the top, the MOTHERSHIP. This has access to things in the real world like
|
|
14
|
+
fetching from the internet or reading from the file system. It's the interface
|
|
15
|
+
to tile loading, it gets configured in ways that are appropriate for its
|
|
16
|
+
context. This is the entry point: you give it a URL and it'll instantiate that
|
|
17
|
+
tile. To the extent possible, this should contain all the intelligence and all
|
|
18
|
+
the configurability so that the other components can be deployed in entirely
|
|
19
|
+
generic ways.
|
|
20
|
+
- The mothership instantiates tiles by creating insulated contexts (a sandboxed
|
|
21
|
+
iframe, an incognito window…) and loading a SHUTTLE in it. The role of the
|
|
22
|
+
shuttle is to set up a service worker and an iframe to load the root of the
|
|
23
|
+
tile into. It only exists because you need something to carry a service worker
|
|
24
|
+
in. The only other thing that it does is (*drumroll*) shuttle messages back
|
|
25
|
+
and forth between the worker and the mothership.
|
|
26
|
+
- The WORKER is dispatched on a shuttle to handle resource loading for a tile.
|
|
27
|
+
Apart from allow-listing some paths for itself and the shuttle, it passes all
|
|
28
|
+
requests up, which the shuttle then hands over to the mothership.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { el } from "./lib/el.js";
|
|
32
|
+
import type { AnyMasl, MaslResponse } from "@dasl/tile-lexicon";
|
|
33
|
+
|
|
34
|
+
export interface TileLoader {
|
|
35
|
+
load (url: string, mothership: TileMothership): Promise<Tile | false | undefined>;
|
|
36
|
+
}
|
|
37
|
+
export interface TilePathLoader {
|
|
38
|
+
resolvePath (path: string): Promise<MaslResponse>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const TILES_PFX = 'tiles-';
|
|
42
|
+
const SHUTTLE_PFX = 'tiles-shuttle-';
|
|
43
|
+
const SND_SHUTTLE_LOAD = `${SHUTTLE_PFX}load`; // tell worker to roll
|
|
44
|
+
const RCV_SHUTTLE_READY = `${SHUTTLE_PFX}ready`; // worker ready
|
|
45
|
+
const SND_SET_TITLE = `${SHUTTLE_PFX}set-title`; // set the title
|
|
46
|
+
const SND_SET_ICON = `${SHUTTLE_PFX}set-icon`; // set the icon
|
|
47
|
+
const WORKER_PFX = 'tiles-worker-';
|
|
48
|
+
const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
|
|
49
|
+
const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
|
|
50
|
+
const RCV_WORKER_REQUEST = `${WORKER_PFX}request`; // worker requested something
|
|
51
|
+
const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
|
|
52
|
+
const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
|
|
53
|
+
const TILES_ERROR = `${TILES_PFX}error`; // shuttle errors
|
|
54
|
+
|
|
55
|
+
export class TileMothership {
|
|
56
|
+
#loaders: TileLoader[] = [];
|
|
57
|
+
#conf: { loadDomain?: string };
|
|
58
|
+
#id2shuttle = new Map<string, HTMLIFrameElement>();
|
|
59
|
+
#id2tile = new Map<string, Tile>();
|
|
60
|
+
constructor (conf: { loadDomain?: string } = {}) {
|
|
61
|
+
this.#conf = conf;
|
|
62
|
+
}
|
|
63
|
+
init () {
|
|
64
|
+
window.addEventListener('message', async (ev: MessageEvent) => {
|
|
65
|
+
const { action } = ev.data || {};
|
|
66
|
+
if (action === TILES_WARNING) {
|
|
67
|
+
const { msg, id } = ev.data;
|
|
68
|
+
console.warn(`[W:${id}]`, ...msg);
|
|
69
|
+
}
|
|
70
|
+
if (action === TILES_ERROR) {
|
|
71
|
+
const { msg, id } = ev.data;
|
|
72
|
+
console.error(`[S:${id}]`, ...msg);
|
|
73
|
+
}
|
|
74
|
+
else if (action === RCV_SHUTTLE_READY) {
|
|
75
|
+
const { id } = ev.data;
|
|
76
|
+
this.sendToShuttle(id, SND_WORKER_LOAD, { id });
|
|
77
|
+
}
|
|
78
|
+
else if (action === RCV_WORKER_READY) {
|
|
79
|
+
const { id } = ev.data;
|
|
80
|
+
const tile = this.#id2tile.get(id);
|
|
81
|
+
if (!tile) throw new Error(`No tile shuttle with ID ${id}`);
|
|
82
|
+
tile.dispatchEvent(new Event('load'));
|
|
83
|
+
}
|
|
84
|
+
else if (action === RCV_WORKER_REQUEST) {
|
|
85
|
+
const { type, id, payload } = ev.data;
|
|
86
|
+
if (type === 'resolve-path') {
|
|
87
|
+
const { path, requestId } = payload;
|
|
88
|
+
const tile = this.#id2tile.get(id);
|
|
89
|
+
if (!tile) throw new Error(`No tile shuttle with ID ${id}`);
|
|
90
|
+
const res = await tile.resolvePath(path);
|
|
91
|
+
const response = res.ok
|
|
92
|
+
? { status: res.status, headers: res.headers, body: res.body }
|
|
93
|
+
: { status: res.status, headers: undefined, body: undefined };
|
|
94
|
+
this.sendToShuttle(id, SND_WORKER_RESPONSE, { requestId, response });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
sendToShuttle (id: string, action: string, payload: unknown) {
|
|
100
|
+
const ifr = this.#id2shuttle.get(id);
|
|
101
|
+
if (!ifr) return console.error(`No shuttle for ID ${id}`);
|
|
102
|
+
ifr.contentWindow?.postMessage({ id, action, payload }, '*');
|
|
103
|
+
}
|
|
104
|
+
registerShuttleFrame (ifr: HTMLIFrameElement, tile: Tile) {
|
|
105
|
+
const id = crypto.randomUUID(); // we might want to make that pluggable
|
|
106
|
+
this.#id2shuttle.set(id, ifr);
|
|
107
|
+
this.#id2tile.set(id, tile);
|
|
108
|
+
return id;
|
|
109
|
+
}
|
|
110
|
+
startShuttle (id: string) {
|
|
111
|
+
this.sendToShuttle(id, SND_SHUTTLE_LOAD, { id });
|
|
112
|
+
}
|
|
113
|
+
// Adds a loader that will handle matching requests to load a tile.
|
|
114
|
+
// - `loader` is an object that knows how to load a tile for a specific scheme
|
|
115
|
+
// (and types)
|
|
116
|
+
addLoader (loader: TileLoader) {
|
|
117
|
+
this.#loaders.push(loader);
|
|
118
|
+
}
|
|
119
|
+
// Remove using same reference.
|
|
120
|
+
removeLoader (loader: TileLoader) {
|
|
121
|
+
this.#loaders = this.#loaders.filter(ldr => ldr !== loader);
|
|
122
|
+
}
|
|
123
|
+
getLoadSource () {
|
|
124
|
+
return `https://${this.#conf?.loadDomain || 'load.webtil.es'}/.well-known/web-tiles/`;
|
|
125
|
+
}
|
|
126
|
+
// Load a tile.
|
|
127
|
+
async loadTile (url: string): Promise<Tile | false> {
|
|
128
|
+
for (const ldr of this.#loaders) {
|
|
129
|
+
const tile = await ldr.load(url, this);
|
|
130
|
+
if (tile) return tile;
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export class Tile extends EventTarget {
|
|
137
|
+
#mothership: TileMothership;
|
|
138
|
+
#url: string;
|
|
139
|
+
#manifest: AnyMasl;
|
|
140
|
+
#pathLoader: TilePathLoader;
|
|
141
|
+
#shuttleId: string | undefined;
|
|
142
|
+
constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader) {
|
|
143
|
+
super();
|
|
144
|
+
this.#mothership = mothership;
|
|
145
|
+
this.#url = url;
|
|
146
|
+
this.#manifest = manifest;
|
|
147
|
+
this.#pathLoader = pathLoader;
|
|
148
|
+
this.addEventListener('load', () => {
|
|
149
|
+
if (this.#manifest?.name) {
|
|
150
|
+
const title = this.#manifest?.name;
|
|
151
|
+
this.#mothership.sendToShuttle(this.#shuttleId!, SND_SET_TITLE, { title });
|
|
152
|
+
const ev = new Event('title-change') as Event & { title?: string };
|
|
153
|
+
ev.title = title;
|
|
154
|
+
this.dispatchEvent(ev);
|
|
155
|
+
}
|
|
156
|
+
const icon = this.#manifest?.icons?.[0]?.src;
|
|
157
|
+
if (icon) {
|
|
158
|
+
this.#mothership.sendToShuttle(this.#shuttleId!, SND_SET_ICON, { path: icon });
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
get url (): string {
|
|
163
|
+
return this.#url;
|
|
164
|
+
}
|
|
165
|
+
get manifest (): AnyMasl {
|
|
166
|
+
return this.#manifest;
|
|
167
|
+
}
|
|
168
|
+
async resolvePath (path: string): Promise<MaslResponse> {
|
|
169
|
+
const u = new URL(`fake:${path}`);
|
|
170
|
+
return this.#pathLoader.resolvePath(u.pathname);
|
|
171
|
+
}
|
|
172
|
+
async renderCard (options?: { contentHeight?: number }): Promise<HTMLElement> {
|
|
173
|
+
const card = el('div', { style: {
|
|
174
|
+
border: '1px solid lightgrey',
|
|
175
|
+
'border-radius': '3px',
|
|
176
|
+
cursor: 'pointer',
|
|
177
|
+
}});
|
|
178
|
+
card.addEventListener('click', async () => {
|
|
179
|
+
const tileRenderer = await this.renderContent(
|
|
180
|
+
options?.contentHeight ||
|
|
181
|
+
this.#manifest?.sizing?.height ||
|
|
182
|
+
Math.max(card.offsetHeight, 300)
|
|
183
|
+
);
|
|
184
|
+
card.replaceWith(tileRenderer);
|
|
185
|
+
});
|
|
186
|
+
// XXX we always take the first, we could be smarter with sizes
|
|
187
|
+
if (this.#manifest?.screenshots?.[0]?.src) {
|
|
188
|
+
const res = await this.resolvePath(this.#manifest.screenshots[0].src);
|
|
189
|
+
if (res.ok) {
|
|
190
|
+
const blob = new Blob([res.body as BlobPart], { type: res.headers?.['content-type'] });
|
|
191
|
+
const url = URL.createObjectURL(blob);
|
|
192
|
+
el('div', { style: {
|
|
193
|
+
'background-image': `url(${url})`,
|
|
194
|
+
'background-size': 'cover',
|
|
195
|
+
'background-position': '50%',
|
|
196
|
+
'aspect-ratio': '16/9',
|
|
197
|
+
}}, [], card);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const title = el('div', { style: {
|
|
201
|
+
padding: '0.5rem 1rem',
|
|
202
|
+
display: 'flex',
|
|
203
|
+
'align-items': 'center',
|
|
204
|
+
}}, [], card);
|
|
205
|
+
// XXX we always take the first, we could be smarter with sizes
|
|
206
|
+
if (this.#manifest?.icons?.[0]?.src) {
|
|
207
|
+
const res = await this.resolvePath(this.#manifest.icons[0].src);
|
|
208
|
+
if (res.ok) {
|
|
209
|
+
const blob = new Blob([res.body as BlobPart], { type: res.headers?.['content-type'] });
|
|
210
|
+
const url = URL.createObjectURL(blob);
|
|
211
|
+
el('img', { src: url, width: '48', height: '48', alt: 'icon', style: { 'padding-right': '0.5rem' } }, [], title);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
el('span', { style: { 'font-weight': 'bold' } }, [this.#manifest.name || 'Untitled Tile'], title);
|
|
215
|
+
if (this.#manifest.description) {
|
|
216
|
+
el('p', { style: { 'margin': '0.5rem 1rem 1rem 1rem' } }, [this.#manifest.description], card);
|
|
217
|
+
}
|
|
218
|
+
return card;
|
|
219
|
+
}
|
|
220
|
+
getLoadSource (): string {
|
|
221
|
+
return this.#mothership.getLoadSource();
|
|
222
|
+
}
|
|
223
|
+
attachIframe (ifr: HTMLIFrameElement) {
|
|
224
|
+
this.#shuttleId = this.#mothership.registerShuttleFrame(ifr, this);
|
|
225
|
+
ifr.addEventListener('load', () => this.#mothership.startShuttle(this.#shuttleId!));
|
|
226
|
+
}
|
|
227
|
+
renderContent (height = 300): HTMLIFrameElement {
|
|
228
|
+
const ifr = el('iframe', {
|
|
229
|
+
src: this.#mothership.getLoadSource(),
|
|
230
|
+
style: {
|
|
231
|
+
display: 'block',
|
|
232
|
+
width: '100%',
|
|
233
|
+
height: `${height}px`,
|
|
234
|
+
border: 'none',
|
|
235
|
+
}
|
|
236
|
+
}) as HTMLIFrameElement;
|
|
237
|
+
this.attachIframe(ifr);
|
|
238
|
+
return ifr;
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/lib/el.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
|
|
2
|
+
type ElAttrValue = string | number | null | undefined | Record<string, string>;
|
|
3
|
+
|
|
4
|
+
export function el (n: string, attrs?: Record<string, ElAttrValue>, kids?: (Node | string)[], p?: Element | null): HTMLElement {
|
|
5
|
+
const e = document.createElement(n);
|
|
6
|
+
Object.entries(attrs || {}).forEach(([k, v]) => {
|
|
7
|
+
if (v == null) return;
|
|
8
|
+
if (k === 'style') {
|
|
9
|
+
Object.entries(v as Record<string, string>).forEach(([prop, value]) => {
|
|
10
|
+
const snake = prop
|
|
11
|
+
.split('-')
|
|
12
|
+
.map((part, idx) => idx ? part.charAt(0).toUpperCase() + part.slice(1) : part)
|
|
13
|
+
.join('');
|
|
14
|
+
(e.style as unknown as Record<string, string>)[snake] = value;
|
|
15
|
+
});
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
e.setAttribute(k, String(v));
|
|
19
|
+
});
|
|
20
|
+
(kids || []).forEach((n) => {
|
|
21
|
+
if (typeof n === 'string') e.append(txt(n));
|
|
22
|
+
else e.append(n);
|
|
23
|
+
});
|
|
24
|
+
if (p) p.append(e);
|
|
25
|
+
return e;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function txt (str: string) {
|
|
29
|
+
return document.createTextNode(str);
|
|
30
|
+
}
|
package/src/lib/masl.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
|
|
2
|
+
import type { MaslHeaders, MaslResponse, MaslResponseError } from '@dasl/tile-lexicon';
|
|
3
|
+
|
|
4
|
+
export const NOT_FOUND: MaslResponseError = { ok: false, status: 404, statusText: 'Not found' };
|
|
5
|
+
|
|
6
|
+
export const maslHeaders = [
|
|
7
|
+
'content-disposition',
|
|
8
|
+
'content-encoding',
|
|
9
|
+
'content-language',
|
|
10
|
+
'content-security-policy',
|
|
11
|
+
'content-type',
|
|
12
|
+
'link',
|
|
13
|
+
'permissions-policy',
|
|
14
|
+
'referrer-policy',
|
|
15
|
+
'service-worker-allowed',
|
|
16
|
+
'sourcemap',
|
|
17
|
+
'speculation-rules',
|
|
18
|
+
'supports-loading-mode',
|
|
19
|
+
'x-content-type-options',
|
|
20
|
+
] as const;
|
|
21
|
+
|
|
22
|
+
export function maslResponse (masl: MaslHeaders, body: ArrayBuffer | Uint8Array | string | null | undefined): MaslResponse {
|
|
23
|
+
if (!body) return NOT_FOUND;
|
|
24
|
+
const headers: MaslHeaders = {};
|
|
25
|
+
maslHeaders.forEach(k => {
|
|
26
|
+
if (typeof masl[k] !== 'undefined') headers[k] = masl[k];
|
|
27
|
+
});
|
|
28
|
+
if (typeof body === 'string') body = (new TextEncoder()).encode(body);
|
|
29
|
+
return { ok: true, status: 200, statusText: 'Ok', headers, body };
|
|
30
|
+
}
|
package/src/memory.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
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 { InMemoryMasl, MaslResponse } from "@dasl/tile-lexicon";
|
|
6
|
+
|
|
7
|
+
// ### Memory Loader
|
|
8
|
+
// This is mostly for debugging, experimentation.
|
|
9
|
+
// You create a loader that maps IDs to manifest-like structures. Then load(memory://ID)
|
|
10
|
+
// and the values in the manifest provide the content directly.
|
|
11
|
+
export class MemoryTileLoader {
|
|
12
|
+
#tiles: Record<string, InMemoryMasl> = {};
|
|
13
|
+
addTile (id: string, manifest: InMemoryMasl) {
|
|
14
|
+
this.#tiles[id] = manifest;
|
|
15
|
+
}
|
|
16
|
+
async load (url: string, mothership: TileMothership): Promise<Tile | false> {
|
|
17
|
+
let u: URL;
|
|
18
|
+
try { u = new URL(url); }
|
|
19
|
+
catch { return false; } // not a URL we understand; let another loader try
|
|
20
|
+
if (u.protocol !== 'memory:') return false;
|
|
21
|
+
const id = u.hostname;
|
|
22
|
+
if (!this.#tiles[id]) return false; // XXX an error would be better
|
|
23
|
+
const manifest = this.#tiles[id];
|
|
24
|
+
const loader = new MemoryPathLoader(manifest);
|
|
25
|
+
return new Tile(mothership, url, manifest, loader);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class MemoryPathLoader {
|
|
30
|
+
#manifest: InMemoryMasl;
|
|
31
|
+
constructor (manifest: InMemoryMasl) {
|
|
32
|
+
this.#manifest = manifest;
|
|
33
|
+
}
|
|
34
|
+
async resolvePath (path: string): Promise<MaslResponse> {
|
|
35
|
+
const entry = this.#manifest?.resources?.[path];
|
|
36
|
+
if (!entry?.src) return NOT_FOUND;
|
|
37
|
+
return maslResponse(entry, entry.src);
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/webxdc.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
|
|
2
|
+
import JSZip from "jszip";
|
|
3
|
+
import mime from 'mime/lite';
|
|
4
|
+
import { parse } from 'smol-toml';
|
|
5
|
+
import { Tile } from "./index.js";
|
|
6
|
+
import type { TileMothership } from "./index.js";
|
|
7
|
+
import { ContentSchemeTileLoader } from "./content-scheme.js";
|
|
8
|
+
import { MemoryPathLoader } from './memory.js';
|
|
9
|
+
import type { InMemoryMasl } from "@dasl/tile-lexicon";
|
|
10
|
+
|
|
11
|
+
// ### WebXDC (DeltaChat) Loader
|
|
12
|
+
// WebXDC works this way:
|
|
13
|
+
// - It's a zip file with a bunch of files, you have to guess the media type.
|
|
14
|
+
// - It must have an index.html at the root, which is the /.
|
|
15
|
+
// - It may have icon.{png,jpg} at the root.
|
|
16
|
+
// - It may have a manifest.toml (seriously), that may have a name entry and
|
|
17
|
+
// one pointing to the source.
|
|
18
|
+
export class WebXDCTileLoader extends ContentSchemeTileLoader {
|
|
19
|
+
constructor (schemes?: string[]) {
|
|
20
|
+
super(schemes);
|
|
21
|
+
}
|
|
22
|
+
async processContent (zipData: ArrayBuffer, _: string, url: string, mothership: TileMothership): Promise<Tile | false> {
|
|
23
|
+
const zip = new JSZip();
|
|
24
|
+
try {
|
|
25
|
+
await zip.loadAsync(zipData);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const manifest: InMemoryMasl = {
|
|
31
|
+
resources: {},
|
|
32
|
+
};
|
|
33
|
+
// We could extract a description from index.html
|
|
34
|
+
for (const path of Object.keys(zip.files)) {
|
|
35
|
+
if (zip.files[path].dir) continue;
|
|
36
|
+
const keyPath = (path === 'index.html') ? '/' : `/${path}`;
|
|
37
|
+
if (/^icon\.(png|jpg)$/.test(path)) {
|
|
38
|
+
if (!manifest.icons) manifest.icons = [];
|
|
39
|
+
manifest.icons.push({ src: keyPath });
|
|
40
|
+
}
|
|
41
|
+
else if (path === 'manifest.toml') {
|
|
42
|
+
const toml = parse(await zip.files[path].async('text'));
|
|
43
|
+
manifest.name = (toml as { name?: string }).name;
|
|
44
|
+
}
|
|
45
|
+
const mediaType = mime.getType(path);
|
|
46
|
+
manifest.resources[keyPath] = {
|
|
47
|
+
src: await zip.files[path].async('arraybuffer'),
|
|
48
|
+
'content-type': mediaType || undefined,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
// Add webxdc.js. NOTE: we need to make this pluggable so that it can actually
|
|
52
|
+
// do some useful work.
|
|
53
|
+
manifest.resources['/webxdc.js'] = {
|
|
54
|
+
src: makeWebXDCAPI(),
|
|
55
|
+
'content-type': 'application/javascript',
|
|
56
|
+
};
|
|
57
|
+
const loader = new MemoryPathLoader(manifest);
|
|
58
|
+
return new Tile(mothership, url, manifest, loader);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// This is the resource that implements webxdc.js. (Based on webxdc/hello.)
|
|
63
|
+
// Note that joinRealtimeChannel() is marked as optional, so we skip it.
|
|
64
|
+
// These are mostly stubs, e.g. sendToChat() just dumps to the console.
|
|
65
|
+
function makeWebXDCAPI ({ selfName = 'Dazzling Kitten', selfAddr }: { selfName?: string; selfAddr?: string } = {}): string {
|
|
66
|
+
return [
|
|
67
|
+
// self-func
|
|
68
|
+
`window.webxdc = (() => {`,
|
|
69
|
+
|
|
70
|
+
// utils
|
|
71
|
+
`let updateListener = (_) => {};
|
|
72
|
+
function getUpdates() {
|
|
73
|
+
const updatesJSON = window.localStorage.getItem(updatesKey);
|
|
74
|
+
return updatesJSON ? JSON.parse(updatesJSON) : [];
|
|
75
|
+
}
|
|
76
|
+
const updatesKey = "__xdcUpdatesKey__";
|
|
77
|
+
window.addEventListener("storage", (event) => {
|
|
78
|
+
if (event.key == null) {
|
|
79
|
+
window.location.reload();
|
|
80
|
+
} else if (event.key === updatesKey) {
|
|
81
|
+
const updates = JSON.parse(event.newValue);
|
|
82
|
+
const update = updates[updates.length - 1];
|
|
83
|
+
update.max_serial = updates.length;
|
|
84
|
+
console.log("[Webxdc] " + JSON.stringify(update));
|
|
85
|
+
updateListener(update);
|
|
86
|
+
} else if (event.key === ephemeralUpdateKey) {
|
|
87
|
+
const [sender, update] = JSON.parse(event.newValue);
|
|
88
|
+
// @ts-ignore: is_trashed() is private
|
|
89
|
+
if (
|
|
90
|
+
window.webxdc.selfAddr !== sender &&
|
|
91
|
+
realtimeListener &&
|
|
92
|
+
!realtimeListener.is_trashed()
|
|
93
|
+
) {
|
|
94
|
+
realtimeListener.receive(Uint8Array.from(update));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});`,
|
|
98
|
+
|
|
99
|
+
// returned object
|
|
100
|
+
`return {`,
|
|
101
|
+
// selfies
|
|
102
|
+
`selfAddr: "${selfAddr || crypto.randomUUID()}",
|
|
103
|
+
selfName: "${selfName}",`,
|
|
104
|
+
|
|
105
|
+
// updates
|
|
106
|
+
`sendUpdate: (update) => {
|
|
107
|
+
console.log('sendUpdate', update);
|
|
108
|
+
},
|
|
109
|
+
setUpdateListener: () => {
|
|
110
|
+
},
|
|
111
|
+
getAllUpdates: () => {
|
|
112
|
+
console.log("[Webxdc] WARNING: getAllUpdates() is deprecated.");
|
|
113
|
+
return Promise.resolve([]);
|
|
114
|
+
},
|
|
115
|
+
setUpdateListener: (cb, serial = 0) => {
|
|
116
|
+
const updates = getUpdates();
|
|
117
|
+
const maxSerial = updates.length;
|
|
118
|
+
updates.forEach((update) => {
|
|
119
|
+
if (update.serial > serial) {
|
|
120
|
+
update.max_serial = maxSerial;
|
|
121
|
+
cb(update);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
updateListener = cb;
|
|
125
|
+
return Promise.resolve();
|
|
126
|
+
},`,
|
|
127
|
+
|
|
128
|
+
// sendToChat
|
|
129
|
+
`sendToChat: async (content) => {
|
|
130
|
+
if (!content.file && !content.text) {
|
|
131
|
+
alert("🚨 Error: either file or text need to be set. (or both)");
|
|
132
|
+
return Promise.reject(
|
|
133
|
+
"Error from sendToChat: either file or text need to be set",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
console.info('sendToChat', content);
|
|
137
|
+
},`,
|
|
138
|
+
|
|
139
|
+
// importFiles
|
|
140
|
+
`importFiles: (filters) => {
|
|
141
|
+
const accept = [
|
|
142
|
+
...(filters.extensions || []),
|
|
143
|
+
...(filters.mimeTypes || []),
|
|
144
|
+
].join(",");
|
|
145
|
+
const element = document.createElement("input");
|
|
146
|
+
element.setAttribute('type', 'file');
|
|
147
|
+
element.setAttribute('accept', accept);
|
|
148
|
+
if (filters.multiple) element.setAttribute('multiple', 'multiple');
|
|
149
|
+
const promise = new Promise((resolve) => {
|
|
150
|
+
element.onchange = () => {
|
|
151
|
+
const files = Array.from(element.files || []);
|
|
152
|
+
document.body.removeChild(element);
|
|
153
|
+
resolve(files);
|
|
154
|
+
};
|
|
155
|
+
});
|
|
156
|
+
element.style.display = "none";
|
|
157
|
+
document.body.appendChild(element);
|
|
158
|
+
element.click();
|
|
159
|
+
return promise;
|
|
160
|
+
},`,
|
|
161
|
+
// close object
|
|
162
|
+
`};`,
|
|
163
|
+
// close self-func
|
|
164
|
+
`})();`
|
|
165
|
+
].join('\n');
|
|
166
|
+
}
|