@silkui/core 0.1.12 → 0.1.13

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.
@@ -0,0 +1,198 @@
1
+ // `location` and `history` for an app in one window: a session history of entries in memory,
2
+ // as a page's is. There is no page to load, so a navigation to another address of the app
3
+ // changes the entry and sends `popstate`, the event routers follow.
4
+
5
+ export class PopStateEvent extends (globalThis.Event ?? class {}) {
6
+ constructor(type, init = {}) {
7
+ super(type, init);
8
+ Object.defineProperty(this, "state", { value: init.state ?? null, enumerable: true });
9
+ }
10
+ }
11
+
12
+ export class HashChangeEvent extends (globalThis.Event ?? class {}) {
13
+ constructor(type, init = {}) {
14
+ super(type, init);
15
+ Object.defineProperty(this, "oldURL", { value: init.oldURL ?? "", enumerable: true });
16
+ Object.defineProperty(this, "newURL", { value: init.newURL ?? "", enumerable: true });
17
+ }
18
+ }
19
+
20
+ // The embedded engine has no `URL`: a small one for the parts `location` has.
21
+ class AppURL {
22
+ constructor(text, base) {
23
+ text = String(text);
24
+ const match = /^([a-z][a-z0-9+.-]*:)\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(#.*)?$/i.exec(text);
25
+ if (match) {
26
+ this.protocol = match[1].toLowerCase();
27
+ this.host = match[2].toLowerCase();
28
+ this.pathname = match[3] || "/";
29
+ this.search = match[4] && match[4] !== "?" ? match[4] : "";
30
+ this.hash = match[5] && match[5] !== "#" ? match[5] : "";
31
+ return;
32
+ }
33
+ if (!base) throw new TypeError("'" + text + "' is not an absolute address");
34
+ const from = new AppURL(String(base));
35
+ Object.assign(this, { protocol: from.protocol, host: from.host, pathname: from.pathname, search: from.search, hash: "" });
36
+ const [, path = "", search, hash] = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(text);
37
+ if (path) {
38
+ this.pathname = path.startsWith("/") ? path : from.pathname.replace(/[^/]*$/, "") + path;
39
+ this.search = "";
40
+ }
41
+ if (search !== undefined) this.search = search === "?" ? "" : search;
42
+ if (hash !== undefined) this.hash = hash === "#" ? "" : hash;
43
+ }
44
+ get hostname() { return this.host.replace(/:\d+$/, ""); }
45
+ set hostname(value) { this.host = value + (this.port ? ":" + this.port : ""); }
46
+ get port() { return /:(\d+)$/.exec(this.host)?.[1] ?? ""; }
47
+ set port(value) { this.host = this.hostname + (value ? ":" + value : ""); }
48
+ get origin() { return this.protocol + "//" + this.host; }
49
+ get href() { return this.origin + this.pathname + this.search + this.hash; }
50
+ toString() { return this.href; }
51
+ }
52
+ const URL = globalThis.URL ?? AppURL;
53
+
54
+ const url = Symbol("url");
55
+ const historyOf = Symbol("history");
56
+
57
+ export class Location {
58
+ constructor(href, document) {
59
+ this[url] = new URL(href);
60
+ this[historyOf] = null;
61
+ void document;
62
+ }
63
+
64
+ get href() { return this[url].href; }
65
+ set href(value) { this.assign(value); }
66
+ get origin() { return this[url].origin; }
67
+ get protocol() { return this[url].protocol; }
68
+ set protocol(value) { this.#with("protocol", value); }
69
+ get host() { return this[url].host; }
70
+ set host(value) { this.#with("host", value); }
71
+ get hostname() { return this[url].hostname; }
72
+ set hostname(value) { this.#with("hostname", value); }
73
+ get port() { return this[url].port; }
74
+ set port(value) { this.#with("port", value); }
75
+ get pathname() { return this[url].pathname; }
76
+ set pathname(value) { this.#with("pathname", value); }
77
+ get search() { return this[url].search; }
78
+ set search(value) { this.#with("search", value); }
79
+ get hash() { return this[url].hash; }
80
+ set hash(value) { this.#with("hash", value); }
81
+ get ancestorOrigins() { return []; }
82
+
83
+ #with(part, value) {
84
+ const next = new URL(this[url].href);
85
+ next[part] = value;
86
+ this.assign(next.href);
87
+ }
88
+
89
+ assign(value) {
90
+ this[historyOf]._navigate(new URL(String(value), this[url]), false);
91
+ }
92
+
93
+ replace(value) {
94
+ this[historyOf]._navigate(new URL(String(value), this[url]), true);
95
+ }
96
+
97
+ reload() {
98
+ console.warn("location.reload: a Silk UI window has no page to load again");
99
+ }
100
+
101
+ toString() { return this.href; }
102
+ valueOf() { return this; }
103
+ }
104
+
105
+ export class History {
106
+ #location;
107
+ #window;
108
+ #entries;
109
+ #index = 0;
110
+
111
+ constructor(location, windowTarget) {
112
+ this.#location = location;
113
+ this.#window = windowTarget;
114
+ this.#entries = [{ url: location[url], state: null }];
115
+ location[historyOf] = this;
116
+ }
117
+
118
+ get length() { return this.#entries.length; }
119
+ get state() { return this.#entries[this.#index].state; }
120
+ get scrollRestoration() { return "manual"; }
121
+ set scrollRestoration(_) {}
122
+
123
+ pushState(state, _title, address) {
124
+ this.#add(state, address, false);
125
+ }
126
+
127
+ replaceState(state, _title, address) {
128
+ this.#add(state, address, true);
129
+ }
130
+
131
+ back() { this.go(-1); }
132
+ forward() { this.go(1); }
133
+
134
+ go(delta = 0) {
135
+ const index = this.#index + (Number(delta) | 0);
136
+ if (delta === 0 || index < 0 || index >= this.#entries.length) return;
137
+ const old = this.#location[url];
138
+ this.#index = index;
139
+ const entry = this.#entries[index];
140
+ this.#location[url] = entry.url;
141
+ // As in a browser, the traversal's events come in a later task.
142
+ setTimeout(() => this.#traversed(old, entry), 0);
143
+ }
144
+
145
+ #traversed(old, entry) {
146
+ this.#window.dispatchEvent(new PopStateEvent("popstate", { state: entry.state }));
147
+ if (old.hash !== entry.url.hash && sameDocument(old, entry.url)) this.#hashChanged(old, entry.url);
148
+ }
149
+
150
+ #hashChanged(old, next) {
151
+ this.#window.dispatchEvent(new HashChangeEvent("hashchange", { oldURL: old.href, newURL: next.href }));
152
+ }
153
+
154
+ #add(state, address, replace) {
155
+ const current = this.#location[url];
156
+ const next = address == null ? current : new URL(String(address), current);
157
+ if (next.origin !== current.origin) {
158
+ throw new (globalThis.DOMException ?? Error)("a history entry must have the window's origin, not " + next.origin, "SecurityError");
159
+ }
160
+ const entry = { url: next, state: state === undefined ? null : structuredCopy(state) };
161
+ if (replace) this.#entries[this.#index] = entry;
162
+ else {
163
+ this.#entries.length = this.#index + 1;
164
+ this.#entries.push(entry);
165
+ this.#index++;
166
+ }
167
+ this.#location[url] = next;
168
+ }
169
+
170
+ // A navigation by `location`: a new hash only scrolls in a browser, which sends `hashchange`;
171
+ // another address of the app becomes the entry, with `popstate` for the router.
172
+ _navigate(next, replace) {
173
+ const old = this.#location[url];
174
+ if (next.origin !== old.origin) {
175
+ globalThis.open?.(next.href);
176
+ return;
177
+ }
178
+ if (next.href === old.href) return;
179
+ this.#add(null, next.href, replace);
180
+ if (sameDocument(old, next) && old.hash !== next.hash) {
181
+ setTimeout(() => this.#hashChanged(old, next), 0);
182
+ } else {
183
+ setTimeout(() => this.#window.dispatchEvent(new PopStateEvent("popstate", { state: null })), 0);
184
+ }
185
+ }
186
+ }
187
+
188
+ function sameDocument(a, b) {
189
+ return a.origin === b.origin && a.pathname === b.pathname && a.search === b.search;
190
+ }
191
+
192
+ function structuredCopy(value) {
193
+ try {
194
+ return typeof structuredClone === "function" ? structuredClone(value) : value;
195
+ } catch {
196
+ return value;
197
+ }
198
+ }
package/src/storage.js ADDED
@@ -0,0 +1,146 @@
1
+ // `localStorage` and `sessionStorage`, as the Web Storage spec has them. Session storage lasts
2
+ // as long as the realm. Local storage is kept in a JSON file when the runtime has `node:fs`
3
+ // (the full SilkJS runtime), else it lasts as long as the realm too.
4
+ //
5
+ // The file is `$SILKUI_STORAGE_DIR/localStorage.json`, or `globalThis.__silkStorageDir` set
6
+ // before the globals load, else `~/.silkui/storage/<app>/localStorage.json` named by the
7
+ // program.
8
+
9
+ const areas = new WeakMap();
10
+ const items = Symbol("items");
11
+
12
+ export class Storage {
13
+ constructor(key, area) {
14
+ if (key !== items) throw new TypeError("Illegal constructor");
15
+ areas.set(this, area);
16
+ }
17
+
18
+ get [items]() {
19
+ return areas.get(this);
20
+ }
21
+
22
+ get length() {
23
+ return this[items].map.size;
24
+ }
25
+
26
+ key(index) {
27
+ return [...this[items].map.keys()][index >>> 0] ?? null;
28
+ }
29
+
30
+ getItem(key) {
31
+ return this[items].map.get(String(key)) ?? null;
32
+ }
33
+
34
+ setItem(key, value) {
35
+ const area = this[items];
36
+ key = String(key);
37
+ value = String(value);
38
+ if (area.map.get(key) === value) return;
39
+ area.map.set(key, value);
40
+ area.changed();
41
+ }
42
+
43
+ removeItem(key) {
44
+ const area = this[items];
45
+ if (area.map.delete(String(key))) area.changed();
46
+ }
47
+
48
+ clear() {
49
+ const area = this[items];
50
+ if (area.map.size === 0) return;
51
+ area.map.clear();
52
+ area.changed();
53
+ }
54
+ }
55
+
56
+ // `storage.foo` and `storage.foo = "1"` are items, as in a browser.
57
+ const traps = {
58
+ get(target, key, receiver) {
59
+ if (typeof key === "symbol" || key in target) return Reflect.get(target, key, receiver);
60
+ return target[items].map.get(key) ?? undefined;
61
+ },
62
+ set(target, key, value) {
63
+ if (typeof key === "symbol" || key in target) return Reflect.set(target, key, value);
64
+ target.setItem(key, value);
65
+ return true;
66
+ },
67
+ has(target, key) {
68
+ return typeof key === "string" && target[items].map.has(key) ? true : key in target;
69
+ },
70
+ deleteProperty(target, key) {
71
+ if (typeof key === "string" && target[items].map.has(key)) target.removeItem(key);
72
+ return true;
73
+ },
74
+ ownKeys(target) {
75
+ return [...target[items].map.keys()];
76
+ },
77
+ getOwnPropertyDescriptor(target, key) {
78
+ if (typeof key !== "string" || !target[items].map.has(key)) return undefined;
79
+ return { value: target[items].map.get(key), writable: true, enumerable: true, configurable: true };
80
+ },
81
+ };
82
+
83
+ function storage(area) {
84
+ const proxy = new Proxy(new Storage(items, area), traps);
85
+ areas.set(proxy, area);
86
+ return proxy;
87
+ }
88
+
89
+ export function sessionStorageArea() {
90
+ return storage({ map: new Map(), changed() {} });
91
+ }
92
+
93
+ export function localStorageArea() {
94
+ const file = storageFile();
95
+ const fs = file && globalThis.process?.getBuiltinModule?.("node:fs");
96
+ const map = new Map();
97
+ if (fs) {
98
+ try {
99
+ const saved = JSON.parse(fs.readFileSync(file, "utf8"));
100
+ for (const key of Object.keys(saved)) map.set(key, String(saved[key]));
101
+ } catch {}
102
+ }
103
+ let pending = false;
104
+ const write = () => {
105
+ pending = false;
106
+ try {
107
+ fs.mkdirSync(dirname(file), { recursive: true });
108
+ const temporary = file + ".tmp";
109
+ fs.writeFileSync(temporary, JSON.stringify(Object.fromEntries(map)));
110
+ fs.renameSync(temporary, file);
111
+ } catch (error) {
112
+ console.warn("localStorage could not be saved: " + error.message);
113
+ }
114
+ };
115
+ if (fs) globalThis.process?.on?.("exit", () => pending && write());
116
+ return storage({
117
+ map,
118
+ // Writes are joined into one per task.
119
+ changed() {
120
+ if (!fs || pending) return;
121
+ pending = true;
122
+ setTimeout(write, 0);
123
+ },
124
+ });
125
+ }
126
+
127
+ function dirname(path) {
128
+ const at = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
129
+ return at > 0 ? path.slice(0, at) : ".";
130
+ }
131
+
132
+ export function storageDirectory() {
133
+ const process = globalThis.process;
134
+ if (globalThis.__silkStorageDir) return String(globalThis.__silkStorageDir);
135
+ if (process?.env?.SILKUI_STORAGE_DIR) return process.env.SILKUI_STORAGE_DIR;
136
+ const os = process?.getBuiltinModule?.("node:os");
137
+ const home = os?.homedir?.();
138
+ if (!home) return null;
139
+ const program = String(process.argv?.[1] ?? process.execPath ?? "app").split(/[\\/]/).pop().replace(/\.[^.]*$/, "") || "app";
140
+ return home + "/.silkui/storage/" + program;
141
+ }
142
+
143
+ function storageFile() {
144
+ const directory = storageDirectory();
145
+ return directory ? directory + "/localStorage.json" : null;
146
+ }
package/src/worker.js ADDED
@@ -0,0 +1,136 @@
1
+ // The web's `Worker` on the full runtime's `node:worker_threads`: a module (or classic script)
2
+ // on a thread of its own with `self`, `postMessage`, `onmessage` and `close`, messages as
3
+ // `MessageEvent`s, and an uncaught exception as an `error` event. A runtime without worker
4
+ // threads (the embedded engine) has no `Worker`.
5
+
6
+ const threads = globalThis.process?.getBuiltinModule?.("node:worker_threads");
7
+
8
+ // What runs first on the worker's thread: the worker globals, then the script.
9
+ const BOOTSTRAP = `
10
+ const { parentPort, workerData } = require("node:worker_threads");
11
+ const target = new EventTarget();
12
+ globalThis.self = globalThis;
13
+ globalThis.name = workerData.name;
14
+ globalThis.onmessage = null;
15
+ globalThis.onmessageerror = null;
16
+ globalThis.onerror = null;
17
+ globalThis.addEventListener = target.addEventListener.bind(target);
18
+ globalThis.removeEventListener = target.removeEventListener.bind(target);
19
+ globalThis.dispatchEvent = target.dispatchEvent.bind(target);
20
+ globalThis.postMessage = (data, transfer) => parentPort.postMessage(data, Array.isArray(transfer) ? transfer : transfer?.transfer);
21
+ globalThis.close = () => process.exit(0);
22
+ globalThis.importScripts = (...urls) => {
23
+ const { readFileSync } = require("node:fs");
24
+ const { fileURLToPath } = require("node:url");
25
+ for (const url of urls) (0, eval)(readFileSync(fileURLToPath(new URL(url, workerData.url)), "utf8"));
26
+ };
27
+ parentPort.on("message", (data) => {
28
+ const event = new MessageEvent("message", { data });
29
+ if (typeof globalThis.onmessage === "function") globalThis.onmessage(event);
30
+ target.dispatchEvent(event);
31
+ });
32
+ const ErrorEvent = globalThis.ErrorEvent ?? class ErrorEvent extends Event {
33
+ constructor(type, init = {}) { super(type, init); this.message = init.message ?? ""; this.error = init.error; }
34
+ };
35
+ const failed = (error) => {
36
+ const event = new ErrorEvent("error", { error, message: String(error?.message ?? error), cancelable: true });
37
+ if (typeof globalThis.onerror === "function") globalThis.onerror(event);
38
+ target.dispatchEvent(event);
39
+ if (!event.defaultPrevented) parentPort.postMessage({ [workerData.errorKey]: { message: String(error?.message ?? error), stack: error?.stack } });
40
+ };
41
+ process.on("uncaughtException", failed);
42
+ if (workerData.module) import(workerData.url).catch(failed);
43
+ else {
44
+ const { readFileSync } = require("node:fs");
45
+ const { fileURLToPath } = require("node:url");
46
+ const source = workerData.url.startsWith("data:")
47
+ ? decodeURIComponent(workerData.url.slice(workerData.url.indexOf(",") + 1))
48
+ : readFileSync(fileURLToPath(workerData.url), "utf8");
49
+ try { (0, eval)(source); } catch (error) { failed(error); }
50
+ }
51
+ `;
52
+
53
+ const ERROR_KEY = "__silkWorkerError";
54
+
55
+ // Node has no ErrorEvent.
56
+ const ErrorEvent = !threads ? null : globalThis.ErrorEvent ?? class ErrorEvent extends Event {
57
+ constructor(type, init = {}) {
58
+ super(type, init);
59
+ this.message = init.message ?? "";
60
+ this.error = init.error;
61
+ this.filename = init.filename ?? "";
62
+ this.lineno = init.lineno ?? 0;
63
+ this.colno = init.colno ?? 0;
64
+ }
65
+ };
66
+
67
+ function scriptUrl(specifier) {
68
+ const text = String(specifier instanceof URL ? specifier.href : specifier);
69
+ if (/^(file|data):/.test(text)) return text;
70
+ if (text.startsWith("blob:")) {
71
+ const blob = globalThis.process.getBuiltinModule("node:buffer").resolveObjectURL(text);
72
+ if (!blob) throw new (globalThis.DOMException ?? Error)("no object URL " + text, "SecurityError");
73
+ return { blob };
74
+ }
75
+ const { pathToFileURL } = globalThis.process.getBuiltinModule("node:url");
76
+ const base = globalThis.__silkWorkerBase ?? pathToFileURL(globalThis.process.cwd() + "/").href;
77
+ // An address of the window's own origin names a file of the app.
78
+ try {
79
+ const own = new URL(text, globalThis.location?.href);
80
+ if (globalThis.location && own.origin === globalThis.location.origin) return new URL("." + own.pathname, base).href;
81
+ } catch {}
82
+ return new URL(text, base).href;
83
+ }
84
+
85
+ export const WorkerClass = threads
86
+ ? class Worker extends EventTarget {
87
+ #thread = null;
88
+ #queue = [];
89
+ onmessage = null;
90
+ onmessageerror = null;
91
+ onerror = null;
92
+
93
+ constructor(specifier, options = {}) {
94
+ super();
95
+ const url = scriptUrl(specifier);
96
+ const start = (href) => {
97
+ this.#thread = new threads.Worker(BOOTSTRAP, {
98
+ eval: true,
99
+ workerData: { url: href, module: options.type === "module", name: options.name ?? "", errorKey: ERROR_KEY },
100
+ });
101
+ this.#thread.on("message", (data) => {
102
+ if (data && typeof data === "object" && ERROR_KEY in data) {
103
+ const error = Object.assign(new Error(data[ERROR_KEY].message), { stack: data[ERROR_KEY].stack });
104
+ this.#fire(new ErrorEvent("error", { error, message: error.message }));
105
+ return;
106
+ }
107
+ this.#fire(new MessageEvent("message", { data }));
108
+ });
109
+ this.#thread.on("messageerror", (data) => this.#fire(new MessageEvent("messageerror", { data })));
110
+ this.#thread.on("error", (error) => this.#fire(new ErrorEvent("error", { error, message: String(error?.message ?? error) })));
111
+ for (const [data, transfer] of this.#queue.splice(0)) this.#thread.postMessage(data, transfer);
112
+ };
113
+ if (typeof url === "string") start(url);
114
+ else url.blob.text().then((source) => start("data:text/javascript," + encodeURIComponent(source)));
115
+ }
116
+
117
+ #fire(event) {
118
+ const handler = this["on" + event.type];
119
+ if (typeof handler === "function") {
120
+ try { handler.call(this, event); } catch (error) { globalThis.reportError?.(error); }
121
+ }
122
+ this.dispatchEvent(event);
123
+ }
124
+
125
+ postMessage(data, transfer) {
126
+ const list = Array.isArray(transfer) ? transfer : transfer?.transfer;
127
+ if (this.#thread) this.#thread.postMessage(data, list);
128
+ else this.#queue.push([data, list]);
129
+ }
130
+
131
+ terminate() {
132
+ this.#thread?.terminate();
133
+ this.#queue = [];
134
+ }
135
+ }
136
+ : undefined;