@use-stall/extensions 0.0.0-stage → 0.1.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 +56 -2
- package/bunfig.toml +5 -0
- package/cli/bin.js +18 -0
- package/cli/build.ts +109 -0
- package/cli/check/check.ts +123 -0
- package/cli/check/endpoints.ts +212 -0
- package/cli/check/manifest.ts +162 -0
- package/cli/check/source.ts +116 -0
- package/cli/check/widgets.ts +133 -0
- package/cli/dev.ts +266 -0
- package/cli/introspect-child.ts +101 -0
- package/cli/introspect.ts +146 -0
- package/cli/main.ts +94 -0
- package/cli/pack.ts +76 -0
- package/cli/paths.ts +58 -0
- package/cli/types.ts +285 -0
- package/host.d.ts +3 -0
- package/host.js +7 -0
- package/index.d.ts +177 -0
- package/index.js +59 -0
- package/package.json +71 -4
- package/sandbox/app.tsx +467 -0
- package/sandbox/bus.ts +26 -0
- package/sandbox/client.tsx +64 -0
- package/sandbox/data.ts +94 -0
- package/sandbox/flex.css +1 -0
- package/sandbox/fonts/Geist-Bold.ttf +0 -0
- package/sandbox/fonts/Geist-Medium.ttf +0 -0
- package/sandbox/fonts/Geist-Regular.ttf +0 -0
- package/sandbox/fonts/Geist-SemiBold.ttf +0 -0
- package/sandbox/host.ts +270 -0
- package/sandbox/seed.ts +111 -0
- package/sandbox/shared.d.ts +3 -0
- package/schema/extension.schema.json +132 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import vm from "node:vm";
|
|
2
|
+
import { HOST_MODULE, REGISTRY, SHARED_MODULES } from "../index.js";
|
|
3
|
+
|
|
4
|
+
const out = Bun.stdout;
|
|
5
|
+
const write = Bun.write;
|
|
6
|
+
const exit = process.exit.bind(process);
|
|
7
|
+
const stringify = JSON.stringify;
|
|
8
|
+
|
|
9
|
+
const input = await Bun.stdin.text();
|
|
10
|
+
const split = input.indexOf("\n");
|
|
11
|
+
const nonce = input.slice(0, split);
|
|
12
|
+
const script = input.slice(split + 1);
|
|
13
|
+
|
|
14
|
+
const finish = async (value: unknown) => {
|
|
15
|
+
await write(out, `\n${nonce}${stringify(value)}\n`);
|
|
16
|
+
exit(0);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const BOOT = `"use strict";
|
|
20
|
+
const J = JSON.stringify;
|
|
21
|
+
const own = Object.hasOwn;
|
|
22
|
+
const names = Object.keys;
|
|
23
|
+
const is_array = Array.isArray;
|
|
24
|
+
const catchall = new Proxy({}, { get: (_, key) => (key === "then" ? undefined : stub()) });
|
|
25
|
+
function stub() {
|
|
26
|
+
return new Proxy(function () {}, {
|
|
27
|
+
get(_, key) {
|
|
28
|
+
if (key === "then") return undefined;
|
|
29
|
+
if (key === Symbol.toPrimitive) return () => "";
|
|
30
|
+
if (key === Symbol.iterator) return function* () {};
|
|
31
|
+
return stub();
|
|
32
|
+
},
|
|
33
|
+
apply: () => stub(),
|
|
34
|
+
construct: () => stub(),
|
|
35
|
+
getPrototypeOf: () => catchall,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
const registry = {};
|
|
39
|
+
for (const name of ${stringify(SHARED_MODULES)}) registry[name] = name === ${stringify(HOST_MODULE)} ? { host: stub() } : stub();
|
|
40
|
+
Object.defineProperty(globalThis, ${stringify(REGISTRY)}, { value: Object.freeze(registry) });
|
|
41
|
+
for (const name of ["setTimeout", "setInterval", "requestAnimationFrame"]) globalThis[name] = () => 0;
|
|
42
|
+
for (const name of ["clearTimeout", "clearInterval", "cancelAnimationFrame"]) globalThis[name] = () => {};
|
|
43
|
+
globalThis.queueMicrotask = (task) => void Promise.resolve().then(task);
|
|
44
|
+
delete globalThis.console;
|
|
45
|
+
const text = (value, limit = 200) => { try { return typeof value === "string" ? value.slice(0, limit) : ""; } catch { return ""; } };
|
|
46
|
+
const list = (value, limit = 500) => { try { return is_array(value) ? value.slice(0, limit) : []; } catch { return []; } };
|
|
47
|
+
const keys = (value, limit = 500) => { try { return value && typeof value === "object" ? names(value).slice(0, limit).map((key) => text(key)) : []; } catch { return []; } };
|
|
48
|
+
const field = (value, key) => { try { return value && typeof value === "object" && own(value, key) ? value[key] : undefined; } catch { return undefined; } };
|
|
49
|
+
const extract = (module) => {
|
|
50
|
+
const config = field(module, "config");
|
|
51
|
+
const app = field(module, "app");
|
|
52
|
+
const ui = field(module, "ui");
|
|
53
|
+
return J({
|
|
54
|
+
id: text(field(config, "id")),
|
|
55
|
+
host: text(field(config, "host")),
|
|
56
|
+
pages: list(field(app, "pages")).map((page) => ({ id: text(field(page, "id")), index: field(page, "index") === true, ui: text(field(page, "ui")) })),
|
|
57
|
+
components: keys(field(ui, "components")),
|
|
58
|
+
handlers: keys(field(app, "handlers")),
|
|
59
|
+
lookups: list(field(app, "lookup")).map((group) => ({
|
|
60
|
+
id: text(field(group, "id")),
|
|
61
|
+
title: text(field(group, "title")),
|
|
62
|
+
data_origin: text(field(group, "data_origin")),
|
|
63
|
+
source: text(field(group, "source")),
|
|
64
|
+
})),
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
const then = Promise.prototype.then;
|
|
68
|
+
const apply = Reflect.apply;
|
|
69
|
+
let result = "";
|
|
70
|
+
const fail = (error) => {
|
|
71
|
+
let detail = "";
|
|
72
|
+
try { detail = error && typeof error === "object" && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "unknown error"; } catch { detail = "unknown error"; }
|
|
73
|
+
result = J({ error: detail.slice(0, 500) });
|
|
74
|
+
};
|
|
75
|
+
const settle = (run) => {
|
|
76
|
+
try {
|
|
77
|
+
apply(then, run(), [(module) => { try { result = extract(module); } catch (error) { fail(error); } }, fail]);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
fail(error);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
[settle, () => result];`;
|
|
83
|
+
|
|
84
|
+
const LIMIT = 10_000;
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
const context = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false } });
|
|
88
|
+
const [settle, read] = vm.runInContext(BOOT, context) as [(run: unknown) => void, () => unknown];
|
|
89
|
+
const run = vm.runInContext(script, context, { timeout: LIMIT });
|
|
90
|
+
settle(run);
|
|
91
|
+
const deadline = Date.now() + LIMIT;
|
|
92
|
+
let value = read();
|
|
93
|
+
while (!(typeof value === "string" && value) && Date.now() < deadline) {
|
|
94
|
+
await Bun.sleep(5);
|
|
95
|
+
value = read();
|
|
96
|
+
}
|
|
97
|
+
if (typeof value !== "string" || !value) await finish({ error: "the module didn't finish loading" });
|
|
98
|
+
else await finish(JSON.parse(value as string));
|
|
99
|
+
} catch (error) {
|
|
100
|
+
await finish({ error: (error instanceof Error ? error.message : "unknown error").slice(0, 500) });
|
|
101
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { Refusal } from "./paths";
|
|
6
|
+
|
|
7
|
+
export type Page = { id: string; index: boolean; ui: string };
|
|
8
|
+
|
|
9
|
+
export type Lookup = { id: string; title: string; data_origin: string; source: string };
|
|
10
|
+
|
|
11
|
+
export type Shape = {
|
|
12
|
+
id: string;
|
|
13
|
+
host: string;
|
|
14
|
+
pages: Page[];
|
|
15
|
+
components: string[];
|
|
16
|
+
handlers: string[];
|
|
17
|
+
lookups: Lookup[];
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const CHILD = fileURLToPath(new URL("./introspect-child.ts", import.meta.url));
|
|
21
|
+
const CONFIG = fileURLToPath(new URL("../bunfig.toml", import.meta.url));
|
|
22
|
+
|
|
23
|
+
export const TIMEOUT = 15_000;
|
|
24
|
+
const CAP = 1024 * 1024;
|
|
25
|
+
const ITEMS = 500;
|
|
26
|
+
const CHARS = 200;
|
|
27
|
+
|
|
28
|
+
const drain = async (stream: ReadableStream<Uint8Array>, cap: number, over: () => void) => {
|
|
29
|
+
const reader = stream.getReader();
|
|
30
|
+
const chunks: Uint8Array[] = [];
|
|
31
|
+
let size = 0;
|
|
32
|
+
for (;;) {
|
|
33
|
+
const { done, value } = await reader.read();
|
|
34
|
+
if (done) break;
|
|
35
|
+
size += value.byteLength;
|
|
36
|
+
if (size > cap) {
|
|
37
|
+
over();
|
|
38
|
+
await reader.cancel().catch(() => undefined);
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
chunks.push(value);
|
|
42
|
+
}
|
|
43
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const str = (value: unknown) => (typeof value === "string" && value.length <= CHARS ? value : "");
|
|
47
|
+
|
|
48
|
+
const strings = (value: unknown) =>
|
|
49
|
+
Array.isArray(value) ? value.slice(0, ITEMS).filter((item): item is string => typeof item === "string" && item.length <= CHARS) : [];
|
|
50
|
+
|
|
51
|
+
const objects = (value: unknown) =>
|
|
52
|
+
Array.isArray(value)
|
|
53
|
+
? value.slice(0, ITEMS).filter((item): item is Record<string, unknown> => !!item && typeof item === "object" && !Array.isArray(item))
|
|
54
|
+
: [];
|
|
55
|
+
|
|
56
|
+
export const shape_of = (raw: unknown): Shape => {
|
|
57
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Refusal("The bundle returned an invalid shape");
|
|
58
|
+
const data = raw as Record<string, unknown>;
|
|
59
|
+
if (typeof data.error === "string") throw new Refusal(`The bundle couldn't be evaluated: ${data.error.slice(0, 500)}`);
|
|
60
|
+
return {
|
|
61
|
+
id: str(data.id),
|
|
62
|
+
host: str(data.host),
|
|
63
|
+
pages: objects(data.pages).map((page) => ({ id: str(page.id), index: page.index === true, ui: str(page.ui) })),
|
|
64
|
+
components: strings(data.components),
|
|
65
|
+
handlers: strings(data.handlers),
|
|
66
|
+
lookups: objects(data.lookups).map((group) => ({
|
|
67
|
+
id: str(group.id),
|
|
68
|
+
title: str(group.title),
|
|
69
|
+
data_origin: str(group.data_origin),
|
|
70
|
+
source: str(group.source),
|
|
71
|
+
})),
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const CLAUSE = /\bexport\s*\{([^{}]*)\}\s*;?\s*$/;
|
|
76
|
+
|
|
77
|
+
const NAME = /^[A-Za-z_$][\w$]*$/;
|
|
78
|
+
|
|
79
|
+
export const script_of = (code: string) => {
|
|
80
|
+
const transpiler = new Bun.Transpiler({ loader: "js" });
|
|
81
|
+
const declared = transpiler.scan(code).exports;
|
|
82
|
+
const match = CLAUSE.exec(code);
|
|
83
|
+
const body = match ? code.slice(0, match.index) : code;
|
|
84
|
+
const pairs = (match?.[1] ?? "")
|
|
85
|
+
.split(",")
|
|
86
|
+
.map((item) => item.trim())
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.map((item) => {
|
|
89
|
+
const [local = "", exported = local] = item.split(/\s+as\s+/);
|
|
90
|
+
if (!NAME.test(local) || !NAME.test(exported)) throw new Refusal("The bundle's exports couldn't be read");
|
|
91
|
+
return [exported, local] as const;
|
|
92
|
+
});
|
|
93
|
+
const names = pairs.map(([exported]) => exported).sort();
|
|
94
|
+
if (JSON.stringify(names) !== JSON.stringify([...declared].sort()) || transpiler.scan(body).exports.length)
|
|
95
|
+
throw new Refusal("The bundle must end with a single export { … } clause");
|
|
96
|
+
const object = pairs.map(([exported, local]) => `${JSON.stringify(exported)}: ${local}`).join(", ");
|
|
97
|
+
return `(async function () {\n"use strict";\n${body}\nreturn { ${object} };\n})`;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
export const introspect = async (code: string, timeout = TIMEOUT): Promise<Shape> => {
|
|
102
|
+
const script = script_of(code);
|
|
103
|
+
const dir = mkdtempSync(join(tmpdir(), "stall-introspect-"));
|
|
104
|
+
const nonce = `@@stall:${crypto.randomUUID()}@@`;
|
|
105
|
+
let reason = "";
|
|
106
|
+
try {
|
|
107
|
+
const child = Bun.spawn([process.execPath, "--no-macros", `--config=${CONFIG}`, CHILD], {
|
|
108
|
+
cwd: dir,
|
|
109
|
+
env: { PATH: process.env.PATH ?? "", NODE_ENV: "production" },
|
|
110
|
+
stdin: "pipe",
|
|
111
|
+
stdout: "pipe",
|
|
112
|
+
stderr: "pipe",
|
|
113
|
+
});
|
|
114
|
+
const kill = (why: string) => {
|
|
115
|
+
reason ||= why;
|
|
116
|
+
child.kill("SIGKILL");
|
|
117
|
+
};
|
|
118
|
+
const timer = setTimeout(() => kill(`timed out after ${timeout / 1000}s`), timeout);
|
|
119
|
+
child.stdin.write(`${nonce}\n${script}`);
|
|
120
|
+
await child.stdin.end();
|
|
121
|
+
const [out, err] = await Promise.all([
|
|
122
|
+
drain(child.stdout, CAP, () => kill("printed too much output")),
|
|
123
|
+
drain(child.stderr, 64 * 1024, () => kill("printed too much output")),
|
|
124
|
+
child.exited,
|
|
125
|
+
]);
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
if (reason) throw new Refusal(`The bundle couldn't be evaluated: it ${reason}`);
|
|
128
|
+
const line = out
|
|
129
|
+
.split("\n")
|
|
130
|
+
.filter((item) => item.startsWith(nonce))
|
|
131
|
+
.pop();
|
|
132
|
+
if (!line) {
|
|
133
|
+
const detail = err.trim().split("\n").slice(-1)[0] ?? "";
|
|
134
|
+
throw new Refusal(`The bundle couldn't be evaluated${detail ? `: ${detail.slice(0, 300)}` : ""}`);
|
|
135
|
+
}
|
|
136
|
+
let raw: unknown;
|
|
137
|
+
try {
|
|
138
|
+
raw = JSON.parse(line.slice(nonce.length));
|
|
139
|
+
} catch {
|
|
140
|
+
throw new Refusal("The bundle returned an invalid shape");
|
|
141
|
+
}
|
|
142
|
+
return shape_of(raw);
|
|
143
|
+
} finally {
|
|
144
|
+
rmSync(dir, { recursive: true, force: true });
|
|
145
|
+
}
|
|
146
|
+
};
|
package/cli/main.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import pkg from "../package.json" with { type: "json" };
|
|
2
|
+
import { HOST_VERSION } from "../index.js";
|
|
3
|
+
import { build } from "./build";
|
|
4
|
+
import { Refusal, root_of } from "./paths";
|
|
5
|
+
|
|
6
|
+
type Flags = Record<string, string | true>;
|
|
7
|
+
|
|
8
|
+
const HELP = `stall-extensions ${pkg.version} (host ${HOST_VERSION})
|
|
9
|
+
|
|
10
|
+
Usage: stall-extensions <command> [--root <dir>] [options]
|
|
11
|
+
|
|
12
|
+
Commands:
|
|
13
|
+
dev Build on change and serve the sandbox [--port 5170]
|
|
14
|
+
build Build dist/index.js
|
|
15
|
+
check Validate the extension and its bundle [--json]
|
|
16
|
+
types Generate src/endpoints.gen.d.ts [--check]
|
|
17
|
+
pack Check, build and write release files --out <dir>
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--root <dir> Extension directory (default: current directory)
|
|
21
|
+
--help Show this help
|
|
22
|
+
--version Show the SDK version`;
|
|
23
|
+
|
|
24
|
+
const parse = (argv: string[]) => {
|
|
25
|
+
const [command = "", ...rest] = argv;
|
|
26
|
+
const flags: Flags = {};
|
|
27
|
+
for (let index = 0; index < rest.length; index++) {
|
|
28
|
+
const arg = rest[index]!;
|
|
29
|
+
if (!arg.startsWith("--")) throw new Refusal(`Unexpected argument '${arg}'`);
|
|
30
|
+
const [key, inline] = arg.slice(2).split("=", 2) as [string, string | undefined];
|
|
31
|
+
if (inline !== undefined) flags[key] = inline;
|
|
32
|
+
else if (rest[index + 1] && !rest[index + 1]!.startsWith("--")) flags[key] = rest[++index]!;
|
|
33
|
+
else flags[key] = true;
|
|
34
|
+
}
|
|
35
|
+
return { command, flags };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const text = (flags: Flags, key: string, fallback = "") => {
|
|
39
|
+
const value = flags[key];
|
|
40
|
+
if (value === true) throw new Refusal(`--${key} needs a value`);
|
|
41
|
+
return value ?? fallback;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const run = async (argv: string[]) => {
|
|
45
|
+
if (argv[0] === "--version" || argv[0] === "-v") return console.log(pkg.version);
|
|
46
|
+
if (!argv[0] || ["help", "--help", "-h"].includes(argv[0])) return console.log(HELP);
|
|
47
|
+
const { command, flags } = parse(argv);
|
|
48
|
+
if (flags.help) return console.log(HELP);
|
|
49
|
+
const root = root_of(text(flags, "root", "."));
|
|
50
|
+
switch (command) {
|
|
51
|
+
case "build": {
|
|
52
|
+
const result = await build(root);
|
|
53
|
+
console.log(`[✓] Built dist/index.js (${(result.bytes / 1024).toFixed(1)} KB, sha256 ${result.sha256})`);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
case "check": {
|
|
57
|
+
const { check, print } = await import("./check/check");
|
|
58
|
+
const report = await check(root);
|
|
59
|
+
print(report, flags.json === true);
|
|
60
|
+
if (report.failures.length) process.exitCode = 1;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
case "types": {
|
|
64
|
+
const { write, verify } = await import("./types");
|
|
65
|
+
if (flags.check) {
|
|
66
|
+
verify(root);
|
|
67
|
+
console.log("[✓] Endpoint types are up to date");
|
|
68
|
+
} else {
|
|
69
|
+
console.log(write(root) ? "[✓] Endpoint types updated" : "[✓] Endpoint types unchanged");
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
case "pack": {
|
|
74
|
+
const { pack } = await import("./pack");
|
|
75
|
+
await pack(root, text(flags, "out"));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
case "dev": {
|
|
79
|
+
const { dev } = await import("./dev");
|
|
80
|
+
await dev(root, Number(text(flags, "port", "5170")));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
default:
|
|
84
|
+
throw new Refusal(`Unknown command '${command}'. Run stall-extensions --help`);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
await run(process.argv.slice(2));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof Refusal) console.error(`[x] ${error.message}`);
|
|
92
|
+
else console.error(error);
|
|
93
|
+
process.exitCode = 1;
|
|
94
|
+
}
|
package/cli/pack.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { HOST_VERSION } from "../index.js";
|
|
4
|
+
import { check, endpoints, print } from "./check/check";
|
|
5
|
+
import { Refusal, inside, read_json, safe } from "./paths";
|
|
6
|
+
|
|
7
|
+
const ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
8
|
+
|
|
9
|
+
const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
|
|
10
|
+
|
|
11
|
+
const HOST = /^\d{4}-(0[1-9]|1[0-2])$/;
|
|
12
|
+
|
|
13
|
+
const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
14
|
+
|
|
15
|
+
const ICON_LIMIT = 512 * 1024;
|
|
16
|
+
|
|
17
|
+
const sha256 = (data: string | Uint8Array) => new Bun.CryptoHasher("sha256").update(data).digest("hex");
|
|
18
|
+
|
|
19
|
+
const text = (value: unknown) => (typeof value === "string" ? value : "");
|
|
20
|
+
|
|
21
|
+
const list = (value: unknown) => (Array.isArray(value) ? value.filter((item) => typeof item === "string") : []);
|
|
22
|
+
|
|
23
|
+
export const pack = async (root: string, out: string) => {
|
|
24
|
+
if (!out) throw new Refusal("pack needs --out <dir>");
|
|
25
|
+
const target = resolve(out);
|
|
26
|
+
if (target === root || inside(root, target)) throw new Refusal("--out must be outside the extension");
|
|
27
|
+
if (existsSync(target) && readdirSync(target).length) throw new Refusal(`${out} must be empty`);
|
|
28
|
+
|
|
29
|
+
const report = await check(root);
|
|
30
|
+
if (report.failures.length) {
|
|
31
|
+
print(report, false);
|
|
32
|
+
throw new Refusal("The extension didn't pass its checks");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const manifest = read_json<Record<string, unknown>>(root, "src/extension.json");
|
|
36
|
+
const id = text(manifest.id);
|
|
37
|
+
const version = text(manifest.version);
|
|
38
|
+
const host = text(manifest.host);
|
|
39
|
+
if (!ID.test(id)) throw new Refusal("id must be a lowercase slug");
|
|
40
|
+
if (!VERSION.test(version)) throw new Refusal("version must look like 1.2.3");
|
|
41
|
+
if (!HOST.test(host) || host > HOST_VERSION) throw new Refusal(`host must be a supported version (latest ${HOST_VERSION})`);
|
|
42
|
+
|
|
43
|
+
const icon_path = safe(root, "src/assets/icon.png");
|
|
44
|
+
const icon = new Uint8Array(await Bun.file(icon_path).arrayBuffer());
|
|
45
|
+
if (icon.byteLength > ICON_LIMIT) throw new Refusal("src/assets/icon.png must be 512 KB or smaller");
|
|
46
|
+
if (!PNG.every((byte, index) => icon[index] === byte)) throw new Refusal("src/assets/icon.png isn't a PNG");
|
|
47
|
+
|
|
48
|
+
const { code } = report;
|
|
49
|
+
if (!code) throw new Refusal("The bundle wasn't built");
|
|
50
|
+
|
|
51
|
+
const payload = {
|
|
52
|
+
id,
|
|
53
|
+
name: text(manifest.name),
|
|
54
|
+
description: text(manifest.description),
|
|
55
|
+
icon: "",
|
|
56
|
+
color: text(manifest.color),
|
|
57
|
+
version,
|
|
58
|
+
host,
|
|
59
|
+
authors: list(manifest.authors),
|
|
60
|
+
keywords: list(manifest.keywords),
|
|
61
|
+
scopes: list(manifest.scopes),
|
|
62
|
+
widgets: Array.isArray(manifest.widgets) ? manifest.widgets : [],
|
|
63
|
+
endpoints: endpoints(root),
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
mkdirSync(target, { recursive: true });
|
|
67
|
+
const real = realpathSync(target);
|
|
68
|
+
writeFileSync(join(real, "index.js"), code);
|
|
69
|
+
writeFileSync(join(real, "icon.png"), icon);
|
|
70
|
+
writeFileSync(join(real, "manifest.json"), `${JSON.stringify(payload, null, 2)}\n`);
|
|
71
|
+
writeFileSync(
|
|
72
|
+
join(real, "release.json"),
|
|
73
|
+
`${JSON.stringify({ id, version, host, sha256: { "index.js": sha256(code), "icon.png": sha256(icon) } }, null, 2)}\n`,
|
|
74
|
+
);
|
|
75
|
+
console.log(`[✓] Packed ${id}@${version} (host ${host}) into ${out}`);
|
|
76
|
+
};
|
package/cli/paths.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
export class Refusal extends Error {}
|
|
5
|
+
|
|
6
|
+
const LIMIT = 2 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
export const inside = (root: string, path: string) => {
|
|
9
|
+
const rel = relative(root, path);
|
|
10
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const root_of = (value = ".") => {
|
|
14
|
+
const dir = resolve(value);
|
|
15
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Refusal(`'${value}' isn't a directory`);
|
|
16
|
+
return realpathSync(dir);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const safe = (root: string, rel: string) => {
|
|
20
|
+
const full = resolve(root, rel);
|
|
21
|
+
if (!inside(root, full)) throw new Refusal(`'${rel}' is outside the extension`);
|
|
22
|
+
if (!existsSync(full)) return full;
|
|
23
|
+
const real = realpathSync(full);
|
|
24
|
+
if (!inside(root, real)) throw new Refusal(`'${rel}' links outside the extension`);
|
|
25
|
+
return real;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const exists = (root: string, rel: string) => existsSync(safe(root, rel));
|
|
29
|
+
|
|
30
|
+
export const read_text = (root: string, rel: string, limit = LIMIT) => {
|
|
31
|
+
const file = safe(root, rel);
|
|
32
|
+
if (!existsSync(file)) throw new Refusal(`${rel} doesn't exist`);
|
|
33
|
+
const stat = statSync(file);
|
|
34
|
+
if (!stat.isFile()) throw new Refusal(`${rel} isn't a file`);
|
|
35
|
+
if (stat.size > limit) throw new Refusal(`${rel} is larger than ${Math.round(limit / 1024)} KB`);
|
|
36
|
+
return readFileSync(file, "utf-8");
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const read_json = <T>(root: string, rel: string): T => {
|
|
40
|
+
const text = read_text(root, rel);
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(text) as T;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new Refusal(`${rel} isn't valid JSON: ${error instanceof Error ? error.message : error}`);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const write_file = (root: string, rel: string, data: string | Uint8Array) => {
|
|
49
|
+
const file = safe(root, rel);
|
|
50
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
51
|
+
const real = realpathSync(dirname(file));
|
|
52
|
+
if (real !== root && !inside(root, real)) throw new Refusal(`'${rel}' links outside the extension`);
|
|
53
|
+
const target = join(real, basename(file));
|
|
54
|
+
const temp = join(real, `.${basename(file)}.${crypto.randomUUID()}.tmp`);
|
|
55
|
+
writeFileSync(temp, data, { mode: 0o644, flag: "wx" });
|
|
56
|
+
renameSync(temp, target);
|
|
57
|
+
return file;
|
|
58
|
+
};
|