@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,162 @@
|
|
|
1
|
+
import { readdirSync } from "node:fs";
|
|
2
|
+
import { HOST_VERSION, valid_scope } from "../../index.js";
|
|
3
|
+
import { exists, read_text } from "../paths";
|
|
4
|
+
|
|
5
|
+
export type Json = Record<string, unknown>;
|
|
6
|
+
|
|
7
|
+
export const REQUIRED = ["package.json", "src/index.ts", "src/app.ts", "src/extension.json", "src/assets/icon.png"];
|
|
8
|
+
|
|
9
|
+
export const STALE = ["stall.config.ts", "stall.build.ts", "stall.types.ts"];
|
|
10
|
+
|
|
11
|
+
export const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
|
|
12
|
+
|
|
13
|
+
export const ALLOWED = new Set([
|
|
14
|
+
"@types/bun",
|
|
15
|
+
"@types/react",
|
|
16
|
+
"@types/react-dom",
|
|
17
|
+
"@use-stall/extensions",
|
|
18
|
+
"@use-stall/icons",
|
|
19
|
+
"@use-stall/types",
|
|
20
|
+
"@use-stall/ui",
|
|
21
|
+
"framer-motion",
|
|
22
|
+
"react",
|
|
23
|
+
"react-dom",
|
|
24
|
+
"react-router-dom",
|
|
25
|
+
"sonner",
|
|
26
|
+
"typescript",
|
|
27
|
+
"uuid",
|
|
28
|
+
"zustand",
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const SECTIONS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
|
|
32
|
+
const LIFECYCLE = ["preinstall", "install", "postinstall", "prepare", "preprepare", "postprepare", "prepublish", "prepack", "postpack"];
|
|
33
|
+
const REDIRECTS = ["overrides", "resolutions", "trustedDependencies", "workspaces", "patchedDependencies"];
|
|
34
|
+
const SPEC = /^[0-9A-Za-z.^~<>=*|+ -]{1,64}$/;
|
|
35
|
+
const HOST = /^\d{4}-(0[1-9]|1[0-2])$/;
|
|
36
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
37
|
+
const COLOR = /^(#[0-9a-fA-F]{6})?$/;
|
|
38
|
+
const LOCKS = ["bun.lock", "package-lock.json"];
|
|
39
|
+
const REGISTRY = "https://registry.npmjs.org/";
|
|
40
|
+
const URL_PATTERN = /https?:\/\/[^\s"'<>]{1,500}/g;
|
|
41
|
+
|
|
42
|
+
export const RESERVED = new Set(["system"]);
|
|
43
|
+
|
|
44
|
+
export const is_object = (value: unknown): value is Json =>
|
|
45
|
+
!!value && typeof value === "object" && !Array.isArray(value);
|
|
46
|
+
|
|
47
|
+
export const own = (value: unknown, key: string): unknown =>
|
|
48
|
+
is_object(value) && Object.hasOwn(value, key) ? value[key] : undefined;
|
|
49
|
+
|
|
50
|
+
export const text = (value: unknown) => (typeof value === "string" ? value.trim() : "");
|
|
51
|
+
|
|
52
|
+
export const hostile = (value: unknown, path = "", depth = 0, found: string[] = []): string[] => {
|
|
53
|
+
if (found.length > 20) return found;
|
|
54
|
+
if (depth > 64) {
|
|
55
|
+
found.push(`${path || "/"} is nested too deeply`);
|
|
56
|
+
return found;
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(value)) value.forEach((item, index) => hostile(item, `${path}/${index}`, depth + 1, found));
|
|
59
|
+
else if (is_object(value))
|
|
60
|
+
for (const key of Object.keys(value)) {
|
|
61
|
+
if (FORBIDDEN.has(key)) found.push(`${path}/${key} uses a reserved key`);
|
|
62
|
+
else hostile(value[key], `${path}/${key}`, depth + 1, found);
|
|
63
|
+
}
|
|
64
|
+
return found;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export const check_files = (root: string) => {
|
|
68
|
+
const failures: string[] = [];
|
|
69
|
+
for (const file of REQUIRED) if (!exists(root, file)) failures.push(`missing required file: ${file}`);
|
|
70
|
+
for (const file of STALE)
|
|
71
|
+
if (exists(root, file)) failures.push(`${file} is from the old template; remove it, stall-extensions builds the extension now`);
|
|
72
|
+
for (const name of readdirSync(root)) {
|
|
73
|
+
if (/^\.?bunfig\.toml$/i.test(name)) failures.push(`${name} isn't allowed in an extension; it can run code during installs and builds`);
|
|
74
|
+
else if (/^\.env/i.test(name)) failures.push(`${name} isn't allowed in an extension; Bun loads it into every command`);
|
|
75
|
+
else if (/^\.(npmrc|yarnrc)/i.test(name)) failures.push(`${name} isn't allowed in an extension; packages come from the public npm registry`);
|
|
76
|
+
}
|
|
77
|
+
return failures;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export const check_package = (pkg: Json) => {
|
|
81
|
+
const failures: string[] = [];
|
|
82
|
+
for (const section of SECTIONS) {
|
|
83
|
+
const deps = own(pkg, section);
|
|
84
|
+
if (deps === undefined) continue;
|
|
85
|
+
if (!is_object(deps)) {
|
|
86
|
+
failures.push(`package.json.${section} must be an object`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
for (const name of Object.keys(deps)) {
|
|
90
|
+
if (!ALLOWED.has(name)) failures.push(`package.json.${section} contains disallowed package '${name.slice(0, 80)}'`);
|
|
91
|
+
const spec = deps[name];
|
|
92
|
+
if (typeof spec !== "string" || !SPEC.test(spec) || /\b(file|link|git|github|workspace|npm|http|https)\b/.test(spec))
|
|
93
|
+
failures.push(`package.json.${section}.${name.slice(0, 80)} must be a registry version range`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const scripts = own(pkg, "scripts");
|
|
97
|
+
if (scripts !== undefined && !is_object(scripts)) failures.push("package.json.scripts must be an object");
|
|
98
|
+
for (const name of LIFECYCLE)
|
|
99
|
+
if (own(scripts, name) !== undefined) failures.push(`package.json.scripts.${name} isn't allowed; install scripts can run code in CI`);
|
|
100
|
+
for (const field of REDIRECTS)
|
|
101
|
+
if (own(pkg, field) !== undefined) failures.push(`package.json.${field} isn't allowed`);
|
|
102
|
+
return failures;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export const check_locks = (root: string) => {
|
|
106
|
+
const failures: string[] = [];
|
|
107
|
+
for (const lock of LOCKS) {
|
|
108
|
+
if (!exists(root, lock)) continue;
|
|
109
|
+
const code = read_text(root, lock, 8 * 1024 * 1024);
|
|
110
|
+
const foreign = new Set<string>();
|
|
111
|
+
for (const match of code.matchAll(URL_PATTERN)) if (!match[0].startsWith(REGISTRY)) foreign.add(match[0].slice(0, 120));
|
|
112
|
+
for (const url of [...foreign].slice(0, 5)) failures.push(`${lock} resolves a package from '${url}'; only ${REGISTRY} is allowed`);
|
|
113
|
+
}
|
|
114
|
+
return failures;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export const check_manifest = (pkg: Json, manifest: Json) => {
|
|
118
|
+
const failures: string[] = [];
|
|
119
|
+
failures.push(...hostile(manifest).map((issue) => `src/extension.json${issue}`));
|
|
120
|
+
|
|
121
|
+
const version = text(own(pkg, "version"));
|
|
122
|
+
const declared = text(own(manifest, "version"));
|
|
123
|
+
if (!version || !declared) failures.push("missing version in package.json or src/extension.json");
|
|
124
|
+
else if (version !== declared) failures.push(`version mismatch: package.json=${version.slice(0, 40)}, src/extension.json=${declared.slice(0, 40)}`);
|
|
125
|
+
|
|
126
|
+
const id = text(own(manifest, "id"));
|
|
127
|
+
if (!id) failures.push("src/extension.json.id is required");
|
|
128
|
+
else if (!SLUG.test(id) || id.length > 64) failures.push("src/extension.json.id must be a lowercase slug like 'speed-pos'");
|
|
129
|
+
else if (RESERVED.has(id)) failures.push(`src/extension.json.id '${id}' is reserved`);
|
|
130
|
+
|
|
131
|
+
const host = own(manifest, "host");
|
|
132
|
+
if (typeof host !== "string" || !host) failures.push(`src/extension.json.host is required; use "${HOST_VERSION}"`);
|
|
133
|
+
else if (!HOST.test(host)) failures.push("src/extension.json.host must look like YYYY-MM");
|
|
134
|
+
else if (host > HOST_VERSION)
|
|
135
|
+
failures.push(`src/extension.json.host '${host}' is newer than this SDK (${HOST_VERSION}); update @use-stall/extensions`);
|
|
136
|
+
|
|
137
|
+
const color = own(manifest, "color");
|
|
138
|
+
if (typeof color !== "string" || !COLOR.test(color))
|
|
139
|
+
failures.push("src/extension.json.color must be a 6-digit hex like #E5484D, or empty");
|
|
140
|
+
|
|
141
|
+
for (const field of ["name", "description"])
|
|
142
|
+
if (!text(own(manifest, field))) failures.push(`src/extension.json.${field} is required`);
|
|
143
|
+
|
|
144
|
+
const schema = own(manifest, "$schema");
|
|
145
|
+
if (schema !== undefined && typeof schema !== "string") failures.push("src/extension.json.$schema must be a string");
|
|
146
|
+
|
|
147
|
+
const scopes = own(manifest, "scopes");
|
|
148
|
+
if (!Array.isArray(scopes)) failures.push("src/extension.json.scopes must be a list (it may be empty)");
|
|
149
|
+
else {
|
|
150
|
+
for (const scope of scopes)
|
|
151
|
+
if (typeof scope !== "string" || !valid_scope(scope))
|
|
152
|
+
failures.push(`src/extension.json.scopes has unknown scope '${String(scope).slice(0, 40)}'`);
|
|
153
|
+
if (new Set(scopes).size !== scopes.length) failures.push("src/extension.json.scopes has duplicates");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const entry = own(manifest, "entrypoint");
|
|
157
|
+
const kind = text(own(entry, "type"));
|
|
158
|
+
if (kind !== "lookup" && kind !== "page") failures.push("src/extension.json.entrypoint.type must be 'lookup' or 'page'");
|
|
159
|
+
if (!text(own(entry, "id"))) failures.push("src/extension.json.entrypoint.id is required");
|
|
160
|
+
|
|
161
|
+
return failures;
|
|
162
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { lstatSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { SHARED_MODULES } from "../../index.js";
|
|
4
|
+
import { BUNDLED } from "../build";
|
|
5
|
+
import { Refusal, read_text, safe } from "../paths";
|
|
6
|
+
|
|
7
|
+
export type Source = { path: string; code: string };
|
|
8
|
+
|
|
9
|
+
const SUFFIXES = [".ts", ".tsx", ".js", ".jsx", ".mjs"];
|
|
10
|
+
const FILES = 2000;
|
|
11
|
+
const SIZE = 1024 * 1024;
|
|
12
|
+
const SKIP = new Set(["node_modules", ".git", "dist"]);
|
|
13
|
+
|
|
14
|
+
export const BANNED: Record<string, RegExp> = {
|
|
15
|
+
window: /\bwindow\s*[.\[)]/,
|
|
16
|
+
globalThis: /\bglobalThis\b/,
|
|
17
|
+
self: /(?<![\w.$])self\s*\./,
|
|
18
|
+
"document.cookie": /\bdocument\s*\.\s*cookie\b/,
|
|
19
|
+
localStorage: /\blocalStorage\b/,
|
|
20
|
+
sessionStorage: /\bsessionStorage\b/,
|
|
21
|
+
indexedDB: /\bindexedDB\b/,
|
|
22
|
+
fetch: /(?<![\w.$])fetch\s*\(/,
|
|
23
|
+
XMLHttpRequest: /\bXMLHttpRequest\b/,
|
|
24
|
+
WebSocket: /\bWebSocket\b/,
|
|
25
|
+
EventSource: /\bEventSource\b/,
|
|
26
|
+
sendBeacon: /\bsendBeacon\b/,
|
|
27
|
+
importScripts: /\bimportScripts\b/,
|
|
28
|
+
Worker: /\bnew\s+(Shared)?Worker\b/,
|
|
29
|
+
eval: /(?<![\w.$])eval\b/,
|
|
30
|
+
"Function constructor": /\bnew\s+Function\b|(?<![\w.$])Function\s*\(/,
|
|
31
|
+
"dynamic import": /(?<![\w.$])import\s*\(/,
|
|
32
|
+
require: /(?<![\w.$])require\s*\(/,
|
|
33
|
+
"window references": /\b(defaultView|contentWindow|contentDocument|parentWindow)\b/,
|
|
34
|
+
"constructor access": /\.\s*constructor\b|\[\s*["'`]constructor["'`]\s*\]/,
|
|
35
|
+
"script elements": /\bcreateElement\s*\(\s*["'`](script|iframe|object|embed|frame)\b/i,
|
|
36
|
+
"HTML strings": /\b(innerHTML|outerHTML|insertAdjacentHTML|srcdoc|dangerouslySetInnerHTML|createContextualFragment)\b|\bdocument\s*\.\s*write/,
|
|
37
|
+
"setTimeout string": /\bset(Timeout|Interval)\s*\(\s*['"`]/,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const MACRO = /\b(?:with|assert)\s*\{\s*type\s*:\s*["']macro["']/;
|
|
41
|
+
const STAR = /\bexport\s*\*\s*from\s*["']([^"'\n]{1,200})["']/g;
|
|
42
|
+
const OLD_HOST = /["']@use-stall\/host["']/;
|
|
43
|
+
|
|
44
|
+
export const strip = (code: string) =>
|
|
45
|
+
code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:'"`])\/\/.*$/gm, "$1");
|
|
46
|
+
|
|
47
|
+
export const sources = (root: string) => {
|
|
48
|
+
const src = safe(root, "src");
|
|
49
|
+
const found: Source[] = [];
|
|
50
|
+
const walk = (dir: string) => {
|
|
51
|
+
for (const entry of readdirSync(dir)) {
|
|
52
|
+
if (SKIP.has(entry)) continue;
|
|
53
|
+
const full = join(dir, entry);
|
|
54
|
+
const stat = lstatSync(full);
|
|
55
|
+
if (stat.isSymbolicLink()) continue;
|
|
56
|
+
if (stat.isDirectory()) {
|
|
57
|
+
walk(full);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (!stat.isFile() || !SUFFIXES.some((suffix) => entry.endsWith(suffix)) || entry.endsWith(".test.ts")) continue;
|
|
61
|
+
if (found.length >= FILES) throw new Refusal(`src has more than ${FILES} source files`);
|
|
62
|
+
const path = relative(root, full);
|
|
63
|
+
found.push({ path, code: read_text(root, path, SIZE) });
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
walk(src);
|
|
67
|
+
return found;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export const banned = (label: string, code: string) => {
|
|
71
|
+
const clean = strip(code);
|
|
72
|
+
return Object.entries(BANNED)
|
|
73
|
+
.filter(([, pattern]) => pattern.test(clean))
|
|
74
|
+
.map(([name]) => `${label}: uses ${name}`);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const allowed = (spec: string) =>
|
|
78
|
+
spec.startsWith(".") ||
|
|
79
|
+
spec.startsWith("@/") ||
|
|
80
|
+
SHARED_MODULES.includes(spec) ||
|
|
81
|
+
BUNDLED.some((name) => spec === name || spec.startsWith(`${name}/`));
|
|
82
|
+
|
|
83
|
+
const imports = (file: Source) => {
|
|
84
|
+
const issues: string[] = [];
|
|
85
|
+
const loader = file.path.endsWith(".tsx") || file.path.endsWith(".jsx") ? "tsx" : "ts";
|
|
86
|
+
let found: { path: string; kind: string }[] = [];
|
|
87
|
+
try {
|
|
88
|
+
found = new Bun.Transpiler({ loader }).scanImports(file.code);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
return [`${file.path}: couldn't be parsed (${error instanceof Error ? error.message.slice(0, 120) : "syntax error"})`];
|
|
91
|
+
}
|
|
92
|
+
for (const item of found) {
|
|
93
|
+
if (item.kind === "dynamic-import" || item.kind === "require-resolve")
|
|
94
|
+
issues.push(`${file.path}: uses ${item.kind} '${item.path}'`);
|
|
95
|
+
else if (!allowed(item.path)) issues.push(`${file.path}: imports '${item.path}', which isn't an allowed module`);
|
|
96
|
+
}
|
|
97
|
+
return issues;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export const check_source = (files: Source[]) => {
|
|
101
|
+
const failures: string[] = [];
|
|
102
|
+
for (const file of files) {
|
|
103
|
+
if (file.path.endsWith(".d.ts")) {
|
|
104
|
+
if (OLD_HOST.test(file.code)) failures.push(`${file.path}: declares '@use-stall/host'; remove it, the types come from @use-stall/extensions`);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
failures.push(...banned(file.path, file.code));
|
|
108
|
+
failures.push(...imports(file));
|
|
109
|
+
const clean = strip(file.code);
|
|
110
|
+
if (OLD_HOST.test(clean)) failures.push(`${file.path}: uses '@use-stall/host'; import { host } from "@use-stall/extensions/host"`);
|
|
111
|
+
if (MACRO.test(clean)) failures.push(`${file.path}: uses a macro import, which isn't allowed`);
|
|
112
|
+
for (const match of clean.matchAll(STAR))
|
|
113
|
+
if (SHARED_MODULES.includes(match[1]!)) failures.push(`${file.path}: re-exports everything from '${match[1]}'`);
|
|
114
|
+
}
|
|
115
|
+
return failures;
|
|
116
|
+
};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { Shape } from "../introspect";
|
|
2
|
+
import { exists, read_text } from "../paths";
|
|
3
|
+
import { is_object, own, text, type Json } from "./manifest";
|
|
4
|
+
|
|
5
|
+
const ID = /^[a-z0-9-]+$/;
|
|
6
|
+
const TYPES = new Set(["action", "value"]);
|
|
7
|
+
const CLICKS = new Set(["none", "navigate", "function"]);
|
|
8
|
+
const ICONS = "node_modules/@use-stall/icons/dist/index.d.ts";
|
|
9
|
+
const USERS = "node_modules/@use-stall/types/src/users.d.ts";
|
|
10
|
+
|
|
11
|
+
const safely = (root: string, file: string) => {
|
|
12
|
+
try {
|
|
13
|
+
return exists(root, file) ? read_text(root, file, 8 * 1024 * 1024) : "";
|
|
14
|
+
} catch {
|
|
15
|
+
return "";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const icon_names = (root: string) => {
|
|
20
|
+
const code = safely(root, ICONS);
|
|
21
|
+
const names = new Set<string>();
|
|
22
|
+
for (const block of code.matchAll(/export\s*\{([^}]*)\}/g))
|
|
23
|
+
for (const item of block[1]!.split(",")) {
|
|
24
|
+
const name = item.trim();
|
|
25
|
+
if (name.startsWith("St") && !name.startsWith("type ")) names.add(name);
|
|
26
|
+
}
|
|
27
|
+
return names;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const members = (code: string, name: string) => {
|
|
31
|
+
const match = new RegExp(`export\\s+type\\s+${name}\\s*=([^;]+);`).exec(code);
|
|
32
|
+
return new Set(match ? [...match[1]!.matchAll(/"([^"]+)"/g)].map((item) => item[1]!) : []);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export const permissions = (root: string) => {
|
|
36
|
+
const code = safely(root, USERS);
|
|
37
|
+
return { modules: members(code, "PermissionModule"), actions: members(code, "PermissionAction") };
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const check_widgets = (root: string, manifest: Json, shape: Shape) => {
|
|
41
|
+
const failures: string[] = [];
|
|
42
|
+
const warnings: string[] = [];
|
|
43
|
+
const widgets = own(manifest, "widgets");
|
|
44
|
+
if (!Array.isArray(widgets)) return { failures: ["src/extension.json.widgets must be a list (it may be empty)"], warnings };
|
|
45
|
+
|
|
46
|
+
const icons = icon_names(root);
|
|
47
|
+
const { modules, actions } = permissions(root);
|
|
48
|
+
const handlers = new Set(shape.handlers);
|
|
49
|
+
const paths = new Set(shape.pages.map((page) => `/${page.id}`));
|
|
50
|
+
const seen = new Set<string>();
|
|
51
|
+
let missing_icons = false;
|
|
52
|
+
let missing_permissions = false;
|
|
53
|
+
|
|
54
|
+
widgets.slice(0, 100).forEach((widget, index) => {
|
|
55
|
+
if (!is_object(widget)) {
|
|
56
|
+
failures.push(`src/extension.json.widgets[${index}] must be an object`);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const id = text(own(widget, "id"));
|
|
60
|
+
const label = `widget '${(id || String(index)).slice(0, 40)}'`;
|
|
61
|
+
if (!ID.test(id)) failures.push(`${label}: id must be a lowercase slug`);
|
|
62
|
+
if (seen.has(id)) failures.push(`${label}: id is used more than once`);
|
|
63
|
+
seen.add(id);
|
|
64
|
+
if (!text(own(widget, "title"))) failures.push(`${label}: title is required`);
|
|
65
|
+
|
|
66
|
+
const icon = text(own(widget, "icon"));
|
|
67
|
+
if (icon && !icons.size) missing_icons = true;
|
|
68
|
+
else if (icon && !icons.has(icon)) failures.push(`${label}: icon '${icon.slice(0, 40)}' isn't a @use-stall/icons export`);
|
|
69
|
+
|
|
70
|
+
const type = own(widget, "type");
|
|
71
|
+
if (typeof type !== "string" || !TYPES.has(type)) failures.push(`${label}: type must be 'action' or 'value'`);
|
|
72
|
+
|
|
73
|
+
const configs = is_object(own(widget, "configs")) ? (own(widget, "configs") as Json) : {};
|
|
74
|
+
const click = is_object(own(configs, "on_click")) ? (own(configs, "on_click") as Json) : {};
|
|
75
|
+
const kind = own(click, "type");
|
|
76
|
+
const value = text(own(click, "value"));
|
|
77
|
+
if (typeof kind !== "string" || !CLICKS.has(kind)) failures.push(`${label}: on_click.type must be one of ${[...CLICKS].join(", ")}`);
|
|
78
|
+
|
|
79
|
+
const value_handler = text(own(configs, "value_handler"));
|
|
80
|
+
const badge_handler = text(own(configs, "badge_handler"));
|
|
81
|
+
if (type === "value" && !value_handler) failures.push(`${label}: value widgets need a value_handler`);
|
|
82
|
+
if (type === "action" && kind === "none") failures.push(`${label}: action widgets need an on_click other than 'none'`);
|
|
83
|
+
|
|
84
|
+
const permission = text(own(configs, "required_permission"));
|
|
85
|
+
if (permission) {
|
|
86
|
+
const [module = "", action = ""] = permission.split(":");
|
|
87
|
+
if (!modules.size || !actions.size) missing_permissions = true;
|
|
88
|
+
else if (!modules.has(module) || !actions.has(action))
|
|
89
|
+
failures.push(`${label}: '${permission.slice(0, 60)}' isn't a valid '<module>:<action>' permission`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const names: [string, string][] = [
|
|
93
|
+
["value_handler", value_handler],
|
|
94
|
+
["badge_handler", badge_handler],
|
|
95
|
+
];
|
|
96
|
+
if (kind === "function") names.push(["on_click.value", value]);
|
|
97
|
+
for (const [field, name] of names) {
|
|
98
|
+
if (field === "on_click.value" && !name) failures.push(`${label}: on_click.value must name a handler`);
|
|
99
|
+
else if (name && !handlers.has(name)) failures.push(`${label}: ${field} '${name.slice(0, 60)}' isn't in app.handlers`);
|
|
100
|
+
}
|
|
101
|
+
if (kind === "navigate" && !paths.has(value))
|
|
102
|
+
failures.push(`${label}: on_click.value '${value.slice(0, 60)}' must be '/<page id>' of a page in src/app.ts`);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
if (widgets.length > 100) failures.push("src/extension.json.widgets has more than 100 widgets");
|
|
106
|
+
if (missing_icons) warnings.push("widget icons weren't checked; install @use-stall/icons");
|
|
107
|
+
if (missing_permissions) warnings.push("widget permissions weren't checked; install @use-stall/types");
|
|
108
|
+
return { failures, warnings };
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export const check_shape = (manifest: Json, shape: Shape) => {
|
|
112
|
+
const failures: string[] = [];
|
|
113
|
+
const id = text(own(manifest, "id"));
|
|
114
|
+
const host = own(manifest, "host");
|
|
115
|
+
if (!shape.id) failures.push("src/index.ts must export config from ./extension.json");
|
|
116
|
+
else if (shape.id !== id) failures.push(`the bundle declares id '${shape.id}', but src/extension.json says '${id}'`);
|
|
117
|
+
if (typeof host === "string" && shape.host !== host) failures.push("the bundle's host version doesn't match src/extension.json");
|
|
118
|
+
const components = new Set(shape.components);
|
|
119
|
+
const pages = new Set<string>();
|
|
120
|
+
for (const page of shape.pages) {
|
|
121
|
+
if (!page.id) failures.push("a page in src/app.ts has no id");
|
|
122
|
+
if (pages.has(page.id)) failures.push(`page '${page.id}' is declared twice`);
|
|
123
|
+
pages.add(page.id);
|
|
124
|
+
if (!components.has(page.ui)) failures.push(`page '${page.id}' uses ui '${page.ui}', which src/ui.tsx doesn't export in components`);
|
|
125
|
+
}
|
|
126
|
+
const entry = own(manifest, "entrypoint");
|
|
127
|
+
const entry_id = text(own(entry, "id"));
|
|
128
|
+
const kind = text(own(entry, "type"));
|
|
129
|
+
if (entry_id && kind === "page" && !pages.has(entry_id)) failures.push(`entrypoint page '${entry_id}' isn't in app.pages`);
|
|
130
|
+
if (entry_id && kind === "lookup" && !shape.lookups.some((group) => group.id === entry_id))
|
|
131
|
+
failures.push(`entrypoint lookup '${entry_id}' isn't in app.lookup`);
|
|
132
|
+
return failures;
|
|
133
|
+
};
|
package/cli/dev.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { existsSync, watch } from "node:fs";
|
|
2
|
+
import { extname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import type { BunPlugin } from "bun";
|
|
5
|
+
import { HOST_MODULE, SHARED_MODULES } from "../index.js";
|
|
6
|
+
import { bundle } from "./build";
|
|
7
|
+
import { Refusal, exists, read_json, safe } from "./paths";
|
|
8
|
+
|
|
9
|
+
const SANDBOX = fileURLToPath(new URL("../sandbox/", import.meta.url));
|
|
10
|
+
|
|
11
|
+
const REQUIRED = ["react", "react-dom", "react-dom/client", "react/jsx-runtime", "react-router-dom", "sonner", "@use-stall/ui"];
|
|
12
|
+
|
|
13
|
+
const ALIASES: Record<string, string> = { "react-dom": "react-dom/client", "react/jsx-dev-runtime": "react/jsx-runtime" };
|
|
14
|
+
|
|
15
|
+
const IMAGES: Record<string, string> = {
|
|
16
|
+
".png": "image/png",
|
|
17
|
+
".jpg": "image/jpeg",
|
|
18
|
+
".jpeg": "image/jpeg",
|
|
19
|
+
".gif": "image/gif",
|
|
20
|
+
".webp": "image/webp",
|
|
21
|
+
".svg": "image/svg+xml",
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const CSP = [
|
|
25
|
+
"default-src 'none'",
|
|
26
|
+
"script-src 'self'",
|
|
27
|
+
"style-src 'self' 'unsafe-inline'",
|
|
28
|
+
"img-src 'self' data: blob: https:",
|
|
29
|
+
"font-src 'self' data:",
|
|
30
|
+
"connect-src 'self'",
|
|
31
|
+
"base-uri 'none'",
|
|
32
|
+
"form-action 'none'",
|
|
33
|
+
"frame-ancestors 'none'",
|
|
34
|
+
].join("; ");
|
|
35
|
+
|
|
36
|
+
const HTML = `<!doctype html>
|
|
37
|
+
<html lang="en">
|
|
38
|
+
<head>
|
|
39
|
+
<meta charset="utf-8" />
|
|
40
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
41
|
+
<title>Stall extension sandbox</title>
|
|
42
|
+
<link rel="preload" href="/__sandbox/fonts/Geist-Regular.ttf" as="font" type="font/ttf" crossorigin />
|
|
43
|
+
<link rel="preload" href="/__sandbox/fonts/Geist-Medium.ttf" as="font" type="font/ttf" crossorigin />
|
|
44
|
+
<link rel="preload" href="/__sandbox/fonts/Geist-SemiBold.ttf" as="font" type="font/ttf" crossorigin />
|
|
45
|
+
<link rel="stylesheet" href="/__sandbox/flex.css" />
|
|
46
|
+
</head>
|
|
47
|
+
<body>
|
|
48
|
+
<div id="root"></div>
|
|
49
|
+
<script type="module" src="/__sandbox/client.js"></script>
|
|
50
|
+
</body>
|
|
51
|
+
</html>`;
|
|
52
|
+
|
|
53
|
+
const resolver = (root: string) => {
|
|
54
|
+
const cache = new Map<string, string | null>();
|
|
55
|
+
return (spec: string) => {
|
|
56
|
+
if (!cache.has(spec)) {
|
|
57
|
+
try {
|
|
58
|
+
cache.set(spec, Bun.resolveSync(spec, root));
|
|
59
|
+
} catch {
|
|
60
|
+
cache.set(spec, null);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return cache.get(spec) ?? null;
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const shared_source = (resolve: (spec: string) => string | null) => {
|
|
68
|
+
const lines: string[] = [
|
|
69
|
+
`const missing = (name) => new Proxy({}, { get(_, key) { if (key === "__esModule" || typeof key === "symbol") return undefined; throw new Error(name + " isn't installed in this extension"); } });`,
|
|
70
|
+
];
|
|
71
|
+
const entries: string[] = [];
|
|
72
|
+
SHARED_MODULES.filter((spec) => spec !== HOST_MODULE).forEach((spec, index) => {
|
|
73
|
+
const path = resolve(ALIASES[spec] ?? spec);
|
|
74
|
+
if (!path) return entries.push(`${JSON.stringify(spec)}: missing(${JSON.stringify(spec)})`);
|
|
75
|
+
lines.push(`import * as m${index} from ${JSON.stringify(path)};`);
|
|
76
|
+
entries.push(`${JSON.stringify(spec)}: ${spec === "sonner" ? `{ toast: m${index}.toast }` : `m${index}`}`);
|
|
77
|
+
});
|
|
78
|
+
lines.push(`export const modules = { ${entries.join(", ")} };`);
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const client = async (root: string) => {
|
|
83
|
+
const resolve = resolver(root);
|
|
84
|
+
const absent = REQUIRED.filter((spec) => !resolve(spec));
|
|
85
|
+
if (absent.length) throw new Refusal(`The sandbox needs these packages installed in the extension: ${absent.join(", ")}`);
|
|
86
|
+
const pin: BunPlugin = {
|
|
87
|
+
name: "stall-sandbox",
|
|
88
|
+
setup(build) {
|
|
89
|
+
build.onResolve({ filter: /^stall-sandbox:shared$/ }, () => ({ path: "shared", namespace: "stall-sandbox" }));
|
|
90
|
+
build.onLoad({ filter: /.*/, namespace: "stall-sandbox" }, () => ({ contents: shared_source(resolve), loader: "js" }));
|
|
91
|
+
build.onResolve({ filter: /^(react|react-dom|react-router-dom|sonner|framer-motion|zustand|@use-stall\/[\w-]+)(\/.*)?$/ }, (args) => {
|
|
92
|
+
const path = resolve(args.path);
|
|
93
|
+
return path ? { path } : undefined;
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
const result = await Bun.build({
|
|
98
|
+
entrypoints: [join(SANDBOX, "client.tsx")],
|
|
99
|
+
format: "esm",
|
|
100
|
+
target: "browser",
|
|
101
|
+
minify: false,
|
|
102
|
+
env: "disable",
|
|
103
|
+
define: { "process.env.NODE_ENV": JSON.stringify("development") },
|
|
104
|
+
plugins: [pin],
|
|
105
|
+
throw: false,
|
|
106
|
+
});
|
|
107
|
+
if (!result.success || !result.outputs[0])
|
|
108
|
+
throw new Refusal(`Couldn't build the sandbox\n${result.logs.map((log) => String(log.message ?? log)).join("\n")}`);
|
|
109
|
+
return result.outputs[0].text();
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const headers = (type: string) => ({
|
|
113
|
+
"Content-Type": type,
|
|
114
|
+
"Content-Security-Policy": CSP,
|
|
115
|
+
"X-Content-Type-Options": "nosniff",
|
|
116
|
+
"Referrer-Policy": "no-referrer",
|
|
117
|
+
"X-Frame-Options": "DENY",
|
|
118
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
119
|
+
"Cross-Origin-Resource-Policy": "same-origin",
|
|
120
|
+
"Cache-Control": "no-store",
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const reply = (body: BodyInit | null, type: string, status = 200) => new Response(body, { status, headers: headers(type) });
|
|
124
|
+
|
|
125
|
+
const asset = (root: string, name: string) => {
|
|
126
|
+
let decoded: string;
|
|
127
|
+
try {
|
|
128
|
+
decoded = decodeURIComponent(name);
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (!/^[\w.-]+(\/[\w.-]+)*$/.test(decoded) || decoded.split("/").some((part) => part.startsWith("."))) return null;
|
|
133
|
+
const type = IMAGES[extname(decoded).toLowerCase()];
|
|
134
|
+
if (!type) return null;
|
|
135
|
+
try {
|
|
136
|
+
const file = safe(root, `src/assets/${decoded}`);
|
|
137
|
+
return existsSync(file) ? { file, type } : null;
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export const dev = async (root: string, port: number) => {
|
|
144
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Refusal("--port must be between 1024 and 65535");
|
|
145
|
+
const script = await client(root);
|
|
146
|
+
const css_path = join(SANDBOX, "flex.css");
|
|
147
|
+
const css = existsSync(css_path) ? await Bun.file(css_path).text() : "";
|
|
148
|
+
const allowed = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
149
|
+
const streams = new Set<ReadableStreamDefaultController<string>>();
|
|
150
|
+
const state = { version: 0, code: "", error: "" };
|
|
151
|
+
|
|
152
|
+
const event = () => `event: build\ndata: ${JSON.stringify({ ok: !state.error, version: state.version, error: state.error })}\n\n`;
|
|
153
|
+
|
|
154
|
+
const broadcast = () => {
|
|
155
|
+
const text = event();
|
|
156
|
+
for (const stream of streams) {
|
|
157
|
+
try {
|
|
158
|
+
stream.enqueue(text);
|
|
159
|
+
} catch {
|
|
160
|
+
streams.delete(stream);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const rebuild = async () => {
|
|
166
|
+
try {
|
|
167
|
+
const { write } = await import("./types");
|
|
168
|
+
write(root);
|
|
169
|
+
const result = await bundle(root, false);
|
|
170
|
+
state.code = result.code;
|
|
171
|
+
state.version += 1;
|
|
172
|
+
state.error = "";
|
|
173
|
+
console.log(`[✓] Built at ${new Date().toLocaleTimeString()} (${(result.bytes / 1024).toFixed(1)} KB)`);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
state.error = error instanceof Error ? error.message : String(error);
|
|
176
|
+
console.error(`[x] ${state.error}`);
|
|
177
|
+
}
|
|
178
|
+
broadcast();
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
let server: ReturnType<typeof Bun.serve>;
|
|
182
|
+
try {
|
|
183
|
+
server = Bun.serve({
|
|
184
|
+
hostname: "127.0.0.1",
|
|
185
|
+
port,
|
|
186
|
+
idleTimeout: 0,
|
|
187
|
+
fetch(request) {
|
|
188
|
+
if (!allowed.has(request.headers.get("host") ?? "")) return reply("Forbidden host", "text/plain", 403);
|
|
189
|
+
const site = request.headers.get("sec-fetch-site");
|
|
190
|
+
if (site && site !== "same-origin" && site !== "none") return reply("Forbidden", "text/plain", 403);
|
|
191
|
+
if (request.method !== "GET" && request.method !== "HEAD") return reply("Method not allowed", "text/plain", 405);
|
|
192
|
+
const { pathname } = new URL(request.url);
|
|
193
|
+
if (pathname === "/__sandbox/client.js") return reply(script, "text/javascript; charset=utf-8");
|
|
194
|
+
if (pathname === "/__sandbox/flex.css") return reply(css, "text/css; charset=utf-8");
|
|
195
|
+
if (pathname.startsWith("/__sandbox/fonts/")) {
|
|
196
|
+
const name = pathname.slice("/__sandbox/fonts/".length);
|
|
197
|
+
const file = join(SANDBOX, "fonts", name);
|
|
198
|
+
return /^Geist-[A-Za-z]+\.ttf$/.test(name) && existsSync(file)
|
|
199
|
+
? new Response(Bun.file(file), { headers: headers("font/ttf") })
|
|
200
|
+
: reply("Not found", "text/plain", 404);
|
|
201
|
+
}
|
|
202
|
+
if (pathname === "/__sandbox/extension.js")
|
|
203
|
+
return state.code
|
|
204
|
+
? reply(state.code, "text/javascript; charset=utf-8")
|
|
205
|
+
: reply(`throw new Error("The extension hasn't built yet");`, "text/javascript; charset=utf-8", 503);
|
|
206
|
+
if (pathname === "/__sandbox/manifest.json") {
|
|
207
|
+
try {
|
|
208
|
+
return reply(JSON.stringify(read_json(root, "src/extension.json")), "application/json");
|
|
209
|
+
} catch (error) {
|
|
210
|
+
return reply(JSON.stringify({ error: String(error) }), "application/json", 500);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (pathname === "/__sandbox/seed.json") {
|
|
214
|
+
try {
|
|
215
|
+
const seed = exists(root, "sandbox.seed.json") ? read_json<unknown>(root, "sandbox.seed.json") : {};
|
|
216
|
+
return reply(JSON.stringify(seed && typeof seed === "object" && !Array.isArray(seed) ? seed : {}), "application/json");
|
|
217
|
+
} catch (error) {
|
|
218
|
+
return reply(JSON.stringify({}), "application/json");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (pathname === "/__sandbox/events") {
|
|
222
|
+
let controller: ReadableStreamDefaultController<string>;
|
|
223
|
+
let timer: ReturnType<typeof setInterval>;
|
|
224
|
+
const body = new ReadableStream<string>({
|
|
225
|
+
start(stream) {
|
|
226
|
+
controller = stream;
|
|
227
|
+
streams.add(stream);
|
|
228
|
+
stream.enqueue(event());
|
|
229
|
+
timer = setInterval(() => {
|
|
230
|
+
try {
|
|
231
|
+
stream.enqueue(": ping\n\n");
|
|
232
|
+
} catch {
|
|
233
|
+
clearInterval(timer);
|
|
234
|
+
}
|
|
235
|
+
}, 15_000);
|
|
236
|
+
},
|
|
237
|
+
cancel() {
|
|
238
|
+
clearInterval(timer);
|
|
239
|
+
streams.delete(controller);
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
return new Response(body, { headers: { ...headers("text/event-stream"), Connection: "keep-alive" } });
|
|
243
|
+
}
|
|
244
|
+
if (pathname.startsWith("/assets/")) {
|
|
245
|
+
const found = asset(root, pathname.slice("/assets/".length));
|
|
246
|
+
return found ? new Response(Bun.file(found.file), { headers: headers(found.type) }) : reply("Not found", "text/plain", 404);
|
|
247
|
+
}
|
|
248
|
+
if (pathname.startsWith("/__sandbox/")) return reply("Not found", "text/plain", 404);
|
|
249
|
+
return reply(HTML, "text/html; charset=utf-8");
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
} catch (error) {
|
|
253
|
+
throw new Refusal(`Couldn't listen on 127.0.0.1:${port}: ${error instanceof Error ? error.message : error}`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
await rebuild();
|
|
257
|
+
|
|
258
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
259
|
+
watch(safe(root, "src"), { recursive: true }, (_event, file) => {
|
|
260
|
+
if (file && String(file).endsWith(".d.ts")) return;
|
|
261
|
+
clearTimeout(timer);
|
|
262
|
+
timer = setTimeout(rebuild, 120);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
console.log(`\n Sandbox: http://localhost:${server.port}\n Only reachable from this machine. Press Ctrl+C to stop.\n`);
|
|
266
|
+
};
|