@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 CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @use-stall/extensions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The SDK for Stall Flex extensions. It includes the host contract, the `stall-extensions` CLI and a local sandbox. It needs Bun 1.2 or later.
4
+
5
+ ```sh
6
+ bun add -d @use-stall/extensions
7
+ ```
8
+
9
+ ```ts
10
+ import { host } from "@use-stall/extensions/host";
11
+ import { HOST_VERSION, type Host } from "@use-stall/extensions";
12
+ ```
13
+
14
+ `@use-stall/extensions/host` is never bundled: Flex, or the sandbox, provides it at runtime.
15
+
16
+ ## Commands
17
+
18
+ ```sh
19
+ stall-extensions dev [--port 5170] # rebuild on change and serve the sandbox on 127.0.0.1
20
+ stall-extensions build # write dist/index.js
21
+ stall-extensions check [--json] # validate the extension and its bundle
22
+ stall-extensions types [--check] # generate src/endpoints.gen.d.ts
23
+ stall-extensions pack --out <dir> # check, build and write release files (CI)
24
+ ```
25
+
26
+ Every command takes `--root <dir>` and defaults to the current directory.
27
+
28
+ ## Extension layout
29
+
30
+ ```
31
+ package.json
32
+ bun.lock
33
+ src/
34
+ extension.json # manifest, with "host": "2026-12"
35
+ index.ts # exports config, app and ui
36
+ app.ts
37
+ assets/icon.png
38
+ sandbox.seed.json # optional seed rows for the sandbox
39
+ ```
40
+
41
+ `extension.json` can point `$schema` at `node_modules/@use-stall/extensions/schema/extension.schema.json` for editor autocomplete.
42
+
43
+ ## Rules
44
+
45
+ `check` refuses:
46
+
47
+ - `bunfig.toml`, `.env*` and `.npmrc`;
48
+ - import attributes (`with { … }`), which is how Bun macros run;
49
+ - lifecycle scripts;
50
+ - `overrides`, `resolutions`, `trustedDependencies`, `workspaces` and `patchedDependencies`;
51
+ - non-registry dependency specs, and lockfile URLs outside `registry.npmjs.org`;
52
+ - imports outside the shared and bundled modules;
53
+ - network and storage APIs, `eval` and `Function`.
54
+
55
+ `dev` only listens on 127.0.0.1 and rejects other hosts and cross-site requests.
56
+
57
+ To check an extension you don't trust, run the CLI from outside it (`stall-extensions check --root <dir>`). Bun reads `bunfig.toml` from the working directory before the CLI starts.
package/bunfig.toml ADDED
@@ -0,0 +1,5 @@
1
+ [install]
2
+ auto = "disable"
3
+
4
+ [run]
5
+ bun = true
package/cli/bin.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env bun
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ const main = fileURLToPath(new URL("./main.ts", import.meta.url));
5
+ const config = fileURLToPath(new URL("../bunfig.toml", import.meta.url));
6
+
7
+ const env = Object.fromEntries(
8
+ Object.entries(process.env).filter(([key]) => !/^(BUN_|NODE_OPTIONS$|NODE_PATH$)/i.test(key)),
9
+ );
10
+
11
+ const child = Bun.spawn(
12
+ [process.execPath, "--no-macros", "--no-env-file", `--config=${config}`, main, ...process.argv.slice(2)],
13
+ { stdio: ["inherit", "inherit", "inherit"], env },
14
+ );
15
+
16
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
17
+
18
+ process.exit(await child.exited);
package/cli/build.ts ADDED
@@ -0,0 +1,109 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import type { BunPlugin } from "bun";
3
+ import { REGISTRY, SHARED_MODULES } from "../index.js";
4
+ import { Refusal, inside, safe, write_file } from "./paths";
5
+
6
+ export const BUNDLED = ["uuid", "@use-stall/extensions"];
7
+
8
+ export const OUTPUT = "dist/index.js";
9
+
10
+ const NAMESPACE = "stall-shared";
11
+
12
+ const LOADERS = new Set(["js", "jsx", "ts", "tsx", "json"]);
13
+
14
+ const GAP = String.raw`(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*)*`;
15
+
16
+ export const ATTRIBUTES = new RegExp(`["']${GAP}(?:with|assert)${GAP}\\{`);
17
+
18
+ const SIZE = 2 * 1024 * 1024;
19
+
20
+ const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
21
+
22
+ const shared_filter = new RegExp(`^(${SHARED_MODULES.map(escape).join("|")})$`);
23
+
24
+ const bundled = (spec: string) => BUNDLED.some((name) => spec === name || spec.startsWith(`${name}/`));
25
+
26
+ const relative_spec = (spec: string) => spec.startsWith("./") || spec.startsWith("../") || spec.startsWith("@/");
27
+
28
+ export type Bundle = { code: string; sha256: string; bytes: number };
29
+
30
+ const shared = (): BunPlugin => ({
31
+ name: "stall-shared",
32
+ setup(build) {
33
+ build.onResolve({ filter: shared_filter }, (args) => ({ path: args.path, namespace: NAMESPACE }));
34
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, (args) => ({
35
+ contents: `module.exports = globalThis[${JSON.stringify(REGISTRY)}][${JSON.stringify(args.path)}];`,
36
+ loader: "js",
37
+ }));
38
+ },
39
+ });
40
+
41
+ const guard = (root: string): BunPlugin => ({
42
+ name: "stall-guard",
43
+ setup(build) {
44
+ build.onResolve({ filter: /.*/ }, (args) => {
45
+ const spec = args.path;
46
+ if (args.kind === "entry-point-build" || shared_filter.test(spec)) return undefined;
47
+ if (args.kind === "dynamic-import" || args.kind === "require-resolve")
48
+ throw new Error(`'${spec}' can't be imported: dynamic imports aren't allowed`);
49
+ if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) throw new Error(`'${spec}' can't be imported: URL and node: imports aren't allowed`);
50
+ if (spec.startsWith("/")) throw new Error(`'${spec}' can't be imported: absolute paths aren't allowed`);
51
+ const from_source = !args.importer || !args.importer.includes("/node_modules/");
52
+ if (from_source && !relative_spec(spec) && !bundled(spec))
53
+ throw new Error(`'${spec}' can't be imported: only shared modules and ${BUNDLED.join(", ")} are available`);
54
+ return undefined;
55
+ });
56
+ build.onLoad({ filter: /.*/ }, (args) => {
57
+ const real = realpathSync(args.path);
58
+ if (!inside(root, real)) throw new Error(`'${args.path}' is outside the extension and can't be bundled`);
59
+ if (real.split(/[\\/]/).includes(".git")) throw new Error(`'${args.path}' can't be bundled`);
60
+ if (!LOADERS.has(args.loader)) throw new Error(`'${args.path}' uses the '${args.loader}' loader, which isn't allowed`);
61
+ const contents = readFileSync(real);
62
+ if (contents.byteLength > SIZE) throw new Error(`'${args.path}' is larger than 2 MB`);
63
+ const text = contents.toString("utf-8");
64
+ if (args.loader !== "json" && ATTRIBUTES.test(text))
65
+ throw new Error(`'${args.path}' uses import attributes (with { … }), which aren't allowed`);
66
+ return { contents: text, loader: args.loader as "js" | "jsx" | "ts" | "tsx" | "json" };
67
+ });
68
+ },
69
+ });
70
+
71
+ const sha256 = (code: string) => new Bun.CryptoHasher("sha256").update(code).digest("hex");
72
+
73
+ export const bundle = async (root: string, minify = true): Promise<Bundle> => {
74
+ const entry = safe(root, "src/index.ts");
75
+ if (!(await Bun.file(entry).exists())) throw new Refusal("src/index.ts doesn't exist");
76
+ const result = await Bun.build({
77
+ entrypoints: [entry],
78
+ root,
79
+ format: "esm",
80
+ target: "browser",
81
+ minify,
82
+ sourcemap: "none",
83
+ splitting: false,
84
+ env: "disable",
85
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
86
+ jsx: { runtime: "automatic", importSource: "react", development: false },
87
+ packages: "bundle",
88
+ plugins: [shared(), guard(root)],
89
+ throw: false,
90
+ });
91
+ if (!result.success) {
92
+ const details = result.logs.map((log) => String(log.message ?? log)).join("\n");
93
+ throw new Refusal(`Build failed\n${details}`);
94
+ }
95
+ if (result.outputs.length !== 1 || result.outputs[0]!.kind !== "entry-point")
96
+ throw new Refusal("The build must produce a single JavaScript file. Reference images by path (./assets/…) instead of importing them.");
97
+ const body = await result.outputs[0]!.text();
98
+ const imports = new Bun.Transpiler({ loader: "js" }).scanImports(body);
99
+ if (imports.length)
100
+ throw new Refusal(`The bundle still imports ${imports.map((item) => `'${item.path}'`).join(", ")}`);
101
+ const code = `if(!globalThis[${JSON.stringify(REGISTRY)}])throw new Error("Shared modules not available");${body}`;
102
+ return { code, sha256: sha256(code), bytes: Buffer.byteLength(code) };
103
+ };
104
+
105
+ export const build = async (root: string) => {
106
+ const result = await bundle(root);
107
+ write_file(root, OUTPUT, result.code);
108
+ return result;
109
+ };
@@ -0,0 +1,123 @@
1
+ import { REGISTRY } from "../../index.js";
2
+ import { bundle } from "../build";
3
+ import { introspect } from "../introspect";
4
+ import { Refusal, read_json } from "../paths";
5
+ import { verify } from "../types";
6
+ import { check_endpoints, resolved } from "./endpoints";
7
+ import { check_files, check_locks, check_manifest, check_package, is_object, type Json } from "./manifest";
8
+ import { banned, check_source, sources } from "./source";
9
+ import { check_shape, check_widgets } from "./widgets";
10
+
11
+ export type Report = { failures: string[]; warnings: string[]; code: string };
12
+
13
+ export const TARGET = 100 * 1024;
14
+ export const LIMIT = 500 * 1024;
15
+
16
+ const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
17
+
18
+ const json = (root: string, file: string, failures: string[]): Json | null => {
19
+ try {
20
+ const value = read_json<unknown>(root, file);
21
+ if (is_object(value)) return value;
22
+ failures.push(`${file} must be a JSON object`);
23
+ } catch (error) {
24
+ failures.push(message(error));
25
+ }
26
+ return null;
27
+ };
28
+
29
+ const registry = new RegExp(`globalThis(?:\\.${REGISTRY}|\\[${JSON.stringify(REGISTRY).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\])`, "g");
30
+
31
+ const unique = (items: string[]) => [...new Set(items)];
32
+
33
+ export const endpoints = (root: string): Record<string, unknown> => {
34
+ const manifest = read_json<unknown>(root, "src/extension.json");
35
+ if (!is_object(manifest)) throw new Refusal("src/extension.json must be a JSON object");
36
+ return resolved(root, manifest);
37
+ };
38
+
39
+ export const check = async (root: string): Promise<Report> => {
40
+ try {
41
+ return await run(root);
42
+ } catch (error) {
43
+ if (error instanceof Refusal) return { failures: [error.message], warnings: [], code: "" };
44
+ throw error;
45
+ }
46
+ };
47
+
48
+ const run = async (root: string): Promise<Report> => {
49
+ const failures: string[] = [];
50
+ const warnings: string[] = [];
51
+ let code = "";
52
+ const done = (): Report => ({ failures: unique(failures), warnings: unique(warnings), code });
53
+
54
+ failures.push(...check_files(root));
55
+ if (failures.some((item) => item.startsWith("missing required file"))) return done();
56
+
57
+ failures.push(...check_locks(root));
58
+ const pkg = json(root, "package.json", failures);
59
+ const manifest = json(root, "src/extension.json", failures);
60
+ if (!pkg || !manifest) return done();
61
+
62
+ failures.push(...check_package(pkg));
63
+ failures.push(...check_manifest(pkg, manifest));
64
+
65
+ let files: Awaited<ReturnType<typeof sources>> = [];
66
+ try {
67
+ files = sources(root);
68
+ } catch (error) {
69
+ failures.push(message(error));
70
+ }
71
+ const source = check_source(files);
72
+ failures.push(...source);
73
+
74
+ const api = check_endpoints(root, manifest, files);
75
+ failures.push(...api.failures);
76
+ warnings.push(...api.warnings);
77
+ if (!api.failures.length) {
78
+ try {
79
+ verify(root);
80
+ } catch (error) {
81
+ failures.push(message(error));
82
+ }
83
+ }
84
+
85
+ if (source.length) {
86
+ warnings.push("the bundle wasn't checked; fix the source issues first");
87
+ return done();
88
+ }
89
+
90
+ try {
91
+ const built = await bundle(root);
92
+ code = built.code;
93
+ if (built.bytes > LIMIT) failures.push(`dist/index.js is ${built.bytes} bytes (> ${LIMIT} hard limit)`);
94
+ else if (built.bytes > TARGET) warnings.push(`dist/index.js is ${built.bytes} bytes (> ${TARGET} target). Add an explicit justification.`);
95
+ } catch (error) {
96
+ failures.push(message(error));
97
+ return done();
98
+ }
99
+
100
+ failures.push(...banned("dist/index.js", code.replace(registry, "")));
101
+
102
+ try {
103
+ const shape = await introspect(code);
104
+ failures.push(...check_shape(manifest, shape));
105
+ const widgets = check_widgets(root, manifest, shape);
106
+ failures.push(...widgets.failures);
107
+ warnings.push(...widgets.warnings);
108
+ } catch (error) {
109
+ failures.push(message(error));
110
+ }
111
+
112
+ return done();
113
+ };
114
+
115
+ export const print = (report: Report, json: boolean) => {
116
+ if (json) {
117
+ console.log(JSON.stringify({ ok: !report.failures.length, failures: report.failures, warnings: report.warnings }));
118
+ return;
119
+ }
120
+ for (const failure of report.failures) console.log(`[x] ${failure}`);
121
+ for (const warning of report.warnings) console.log(`[!] ${warning}`);
122
+ if (!report.failures.length) console.log("[✓] Extension passed");
123
+ };
@@ -0,0 +1,212 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { Refusal, exists, read_json, safe } from "../paths";
3
+ import { FORBIDDEN, is_object, own, type Json } from "./manifest";
4
+ import { strip, type Source } from "./source";
5
+
6
+ const KEY = /^[a-z0-9-]+$/;
7
+ const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
8
+ const WRITES = new Set(["POST", "PUT", "PATCH"]);
9
+ const PATH = /^(?!.*\/\.{1,2}(\/|$))\/([A-Za-z0-9._~-]+|:[a-z_][a-z0-9_]*)?(\/([A-Za-z0-9._~-]+|:[a-z_][a-z0-9_]*))*$/;
10
+ const PRIVATE = [/^localhost$/i, /\.localhost$/i, /\.local$/i, /\.internal$/i];
11
+ const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
12
+ const PARTS = ["params", "query", "body", "response"];
13
+ const CALL =
14
+ /endpoints\s*(?:\.\s*([A-Za-z0-9_$]+)|\[\s*["']([^"'\n]{1,100})["']\s*\])\s*\.\s*(get|post|put|patch|delete)\s*(?:<[^>\n]{0,200}>)?\s*\(\s*(["'`])((?:(?!\4)[\s\S]){0,400})\4/g;
15
+ const NODES = 20_000;
16
+
17
+ export const public_https = (value: string) => {
18
+ let url: URL;
19
+ try {
20
+ url = new URL(value);
21
+ } catch {
22
+ return false;
23
+ }
24
+ const host = url.hostname;
25
+ return (
26
+ url.protocol === "https:" &&
27
+ !url.search &&
28
+ !url.hash &&
29
+ !url.username &&
30
+ !url.password &&
31
+ !url.port &&
32
+ host.includes(".") &&
33
+ !IPV4.test(host) &&
34
+ !host.startsWith("[") &&
35
+ !PRIVATE.some((pattern) => pattern.test(host))
36
+ );
37
+ };
38
+
39
+ const pointer_at = (doc: unknown, pointer: string, ref: string) => {
40
+ let node: unknown = doc;
41
+ for (const raw of pointer.split("/").filter(Boolean)) {
42
+ const part = raw.replace(/~1/g, "/").replace(/~0/g, "~");
43
+ if (FORBIDDEN.has(part)) throw new Refusal(`$ref '${ref}' uses a reserved key`);
44
+ if (is_object(node) && Object.hasOwn(node, part)) node = node[part];
45
+ else if (Array.isArray(node) && /^\d+$/.test(part) && Number(part) < node.length) node = node[Number(part)];
46
+ else throw new Refusal(`$ref '${ref}' points to nothing`);
47
+ }
48
+ return node;
49
+ };
50
+
51
+ type Doc = { file: string; root: unknown };
52
+
53
+ class Resolver {
54
+ private nodes = 0;
55
+ constructor(private src: string) {}
56
+
57
+ run(value: unknown, base: string, seen: string[], doc: Doc | null): unknown {
58
+ if (++this.nodes > NODES) throw new Refusal("endpoint schemas expand to too many nodes");
59
+ if (seen.length > 32) throw new Refusal("endpoint schemas are nested too deeply");
60
+ if (Array.isArray(value)) return value.map((item) => this.run(item, base, seen, doc));
61
+ if (!is_object(value)) return value;
62
+ const ref = own(value, "$ref");
63
+ if (typeof ref === "string" && ref.startsWith("#") && doc) {
64
+ const key = `${doc.file}${ref}`;
65
+ if (seen.includes(key)) throw new Refusal(`$ref '${ref}' is recursive`);
66
+ return this.run(pointer_at(doc.root, ref.slice(1), ref), base, [...seen, key], doc);
67
+ }
68
+ if (typeof ref === "string" && !ref.startsWith("#")) {
69
+ const index = ref.indexOf("#");
70
+ const path = index < 0 ? ref : ref.slice(0, index);
71
+ const fragment = index < 0 ? "" : ref.slice(index + 1);
72
+ if (!path.endsWith(".json")) throw new Refusal(`$ref '${ref}' must point to a .json file inside src`);
73
+ let target: string;
74
+ try {
75
+ target = safe(this.src, resolve(base, path));
76
+ } catch {
77
+ throw new Refusal(`$ref '${ref}' must point to a .json file inside src`);
78
+ }
79
+ const key = `${target}#${fragment}`;
80
+ if (seen.includes(key)) throw new Refusal(`$ref '${ref}' is circular`);
81
+ if (!exists(this.src, target)) throw new Refusal(`$ref '${ref}' doesn't exist`);
82
+ const loaded = read_json<unknown>(this.src, target);
83
+ return this.run(pointer_at(loaded, fragment, ref), dirname(target), [...seen, key], { file: target, root: loaded });
84
+ }
85
+ const out: Json = {};
86
+ for (const key of Object.keys(value)) {
87
+ if (FORBIDDEN.has(key)) throw new Refusal(`endpoint schemas can't use the '${key}' key`);
88
+ if (doc && (key === "$defs" || key === "definitions")) continue;
89
+ Object.defineProperty(out, key, { value: this.run(value[key], base, seen, doc), enumerable: true, writable: true, configurable: true });
90
+ }
91
+ return out;
92
+ }
93
+ }
94
+
95
+ export const resolved = (root: string, manifest: Json): Json => {
96
+ const src = safe(root, "src");
97
+ const value = own(manifest, "endpoints") ?? {};
98
+ if (!is_object(value)) throw new Refusal("src/extension.json.endpoints must be an object");
99
+ return new Resolver(src).run(value, src, [], null) as Json;
100
+ };
101
+
102
+ const types_of = (schema: Json): string[] => {
103
+ const type = own(schema, "type");
104
+ return Array.isArray(type) ? type.filter((item): item is string => typeof item === "string") : typeof type === "string" ? [type] : [];
105
+ };
106
+
107
+ export const open_paths = (schema: unknown, at = ""): string[] => {
108
+ if (!is_object(schema) || !Object.keys(schema).length) return [];
109
+ const here = at || "/";
110
+ const ref = own(schema, "$ref");
111
+ if (typeof ref === "string" && !ref.startsWith("#")) return [`${here} has an unresolved $ref`];
112
+ const issues: string[] = [];
113
+ const types = types_of(schema);
114
+ const properties = own(schema, "properties");
115
+ if ((types.includes("object") || is_object(properties)) && own(schema, "additionalProperties") !== false)
116
+ issues.push(`${here} needs additionalProperties: false`);
117
+ if (types.includes("string") && typeof own(schema, "maxLength") !== "number" && own(schema, "enum") === undefined && own(schema, "const") === undefined)
118
+ issues.push(`${here} needs maxLength`);
119
+ if (types.includes("array") && typeof own(schema, "maxItems") !== "number") issues.push(`${here} needs maxItems`);
120
+ if (is_object(properties)) for (const key of Object.keys(properties)) issues.push(...open_paths(properties[key], `${at}/${key}`));
121
+ const items = own(schema, "items");
122
+ if (is_object(items)) issues.push(...open_paths(items, `${at}/items`));
123
+ for (const key of ["prefixItems", "anyOf", "oneOf", "allOf"]) {
124
+ const list = own(schema, key);
125
+ if (Array.isArray(list)) list.forEach((value, index) => issues.push(...open_paths(value, `${at}/${key}/${index}`)));
126
+ }
127
+ const defs = own(schema, "$defs");
128
+ if (is_object(defs)) for (const key of Object.keys(defs)) issues.push(...open_paths(defs[key], `${at}/$defs/${key}`));
129
+ return issues;
130
+ };
131
+
132
+ const matches = (pattern: string, path: string) => {
133
+ const want = pattern.split("/").filter(Boolean);
134
+ const got = path.split("?")[0]!.split("/").filter(Boolean);
135
+ return want.length === got.length && want.every((part, index) => part.startsWith(":") || part === got[index] || (got[index]!.startsWith("${") && got[index]!.endsWith("}")));
136
+ };
137
+
138
+ export const check_endpoints = (root: string, manifest: Json, files: Source[]) => {
139
+ const failures: string[] = [];
140
+ const warnings: string[] = [];
141
+ let endpoints: Json;
142
+ try {
143
+ endpoints = resolved(root, manifest);
144
+ } catch (error) {
145
+ return { failures: [`src/extension.json.endpoints: ${error instanceof Error ? error.message : error}`], warnings };
146
+ }
147
+
148
+ for (const key of Object.keys(endpoints)) {
149
+ const label = `src/extension.json.endpoints.${key.slice(0, 60)}`;
150
+ if (!KEY.test(key)) failures.push(`${label}: keys are lowercase slugs`);
151
+ const endpoint = endpoints[key];
152
+ if (!is_object(endpoint)) {
153
+ failures.push(`${label} must be an object`);
154
+ continue;
155
+ }
156
+ if (!public_https(String(own(endpoint, "url") ?? "")))
157
+ failures.push(`${label}.url must be a public https url without a query, port or credentials`);
158
+ const paths = own(endpoint, "paths");
159
+ if (!Array.isArray(paths) || !paths.length) {
160
+ failures.push(`${label}.paths must be a non-empty list`);
161
+ continue;
162
+ }
163
+ if (paths.length > 100) failures.push(`${label}.paths has more than 100 entries`);
164
+ const seen = new Set<string>();
165
+ paths.slice(0, 100).forEach((entry, index) => {
166
+ const at = `${label}.paths[${index}]`;
167
+ if (!is_object(entry)) {
168
+ failures.push(`${at} must be an object`);
169
+ return;
170
+ }
171
+ const method = String(own(entry, "method") ?? "");
172
+ const path = String(own(entry, "path") ?? "");
173
+ const schema = own(entry, "schema") ?? {};
174
+ if (!METHODS.has(method)) failures.push(`${at}.method must be one of ${[...METHODS].join(", ")}`);
175
+ if (path.length > 256 || !PATH.test(path)) failures.push(`${at}.path must start with / and use :name for parameters`);
176
+ if (seen.has(`${method} ${path}`)) failures.push(`${at}: '${method} ${path.slice(0, 80)}' is declared twice`);
177
+ seen.add(`${method} ${path}`);
178
+ if (!is_object(schema) || Object.keys(schema).some((part) => !PARTS.includes(part))) {
179
+ failures.push(`${at}.schema only takes ${PARTS.join(", ")}`);
180
+ return;
181
+ }
182
+ const body = own(schema, "body");
183
+ if (WRITES.has(method) && !(is_object(body) && Object.keys(body).length)) failures.push(`${at}: ${method} paths need a body schema`);
184
+ for (const part of PARTS) for (const issue of open_paths(own(schema, part) ?? {})) failures.push(`${at}.schema.${part}: ${issue}`);
185
+ });
186
+ }
187
+
188
+ for (const file of files) {
189
+ const code = strip(file.code);
190
+ for (const match of code.matchAll(CALL)) {
191
+ const key = match[1] ?? match[2] ?? "";
192
+ const method = match[3]!.toUpperCase();
193
+ const quote = match[4]!;
194
+ const target = match[5]!;
195
+ const where = `${file.path}: endpoints.${key}.${match[3]}('${target.slice(0, 80)}')`;
196
+ const endpoint = Object.hasOwn(endpoints, key) ? endpoints[key] : undefined;
197
+ if (!is_object(endpoint)) {
198
+ failures.push(`${where} uses an undeclared endpoint`);
199
+ continue;
200
+ }
201
+ if (quote === "`" && target.startsWith("${")) {
202
+ warnings.push(`${where} builds its path dynamically and couldn't be checked`);
203
+ continue;
204
+ }
205
+ const list = own(endpoint, "paths");
206
+ const declared = (Array.isArray(list) ? list : []).filter((entry) => own(entry, "method") === method);
207
+ if (!declared.some((entry) => matches(String(own(entry, "path") ?? ""), target))) failures.push(`${where} isn't a declared path`);
208
+ }
209
+ }
210
+
211
+ return { failures, warnings };
212
+ };