@edhspace/devkit 0.0.0-stage → 0.2.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.
Files changed (4) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +47 -2
  3. package/dist/cli.js +664 -0
  4. package/package.json +47 -5
package/LICENSE ADDED
@@ -0,0 +1,14 @@
1
+ ISC License
2
+
3
+ Copyright (c) EDHspace contributors
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
11
+ FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
12
+ OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
13
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
14
+ ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @edhspace/devkit
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
+ Local CLI for reviewed EDHspace extensions. Requires Node 22.12+.
4
+
5
+ ```sh
6
+ edhspace check extensions/my-extension
7
+ edhspace build extensions/my-extension
8
+ edhspace dev extensions/my-extension
9
+ edhspace sideload extensions/my-extension
10
+ edhspace check-all extensions
11
+ edhspace build-all extensions
12
+ edhspace inspect-dependency node_modules/<package>
13
+ ```
14
+
15
+ Check validates package manifests, strict TypeScript and dependency/import policy.
16
+ Build additionally rejects escaped/symlinked imports, emits externalized ESM and
17
+ declarations, enforces 256 KiB per artifact, and records hashes in `dist/build.json`.
18
+ All commands fail explicitly on policy violations. They do not publish or install.
19
+ Third-party libraries require reviewed exact versions, matching registry lock
20
+ integrity and installed file hashes, transitive approval, and retained licenses.
21
+ The inspection command reads files without executing or approving the package.
22
+ See [dependency review](../../DEPENDENCIES.md).
23
+
24
+ Dev bundles a native React workbench at `127.0.0.1:5186` with synthetic deck data,
25
+ mock inspection and a light/dark switch. It has no account connection or production
26
+ storage. API requests use the host's consent dialog before any outgoing data is
27
+ sent. Unsupported capabilities reject. Stop with Ctrl+C; generated workbench
28
+ assets stay in `.local/dev`, separate from distributable `dist`.
29
+
30
+ Sideload builds `dist/sideload.edhspace-extension.json` for the site's development
31
+ upload. From the public repository root, use
32
+ `npm run build:sideload -- extensions/my-extension`.
33
+ Each declared panel includes its own React/API/UI runtime, styles, and inlined
34
+ assets; no private site packages or local server are needed. Source, manifest,
35
+ dependency, and import checks still apply. Native `build` outputs remain unchanged.
36
+ The bootstrap renders mana/rules symbols as text tokens so shared UI does not
37
+ request external images from the sandbox.
38
+ Choose or drop the file through Workspace > Extensions > Test an extension using an
39
+ ordinary EDHspace account and a disposable owned test deck. Rebuild and reopen
40
+ Manage test extension to upload your changes or remove the build.
41
+
42
+ Sideload bundles are unreviewed code. The host must render them only in an opaque
43
+ sandboxed iframe and keep grants, host actions, and network approvals outside it.
44
+ Do not import or execute an uploaded bundle in the application context.
45
+
46
+ The policy catches common violations, not malicious JavaScript in general.
47
+ Contributions require source/artifact review before native application inclusion.
48
+ See the [API reference](../../API.md) and [contribution guide](../../CONTRIBUTING.md).
package/dist/cli.js ADDED
@@ -0,0 +1,664 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/build.ts
4
+ import { readFile as readFile2, mkdir, writeFile, realpath as realpath2, stat, lstat as lstat2, rm } from "fs/promises";
5
+ import path2 from "path";
6
+ import { createHash as createHash2 } from "crypto";
7
+ import ts from "typescript";
8
+ import { build } from "esbuild";
9
+ import { extensionPackageSchema, toExtensionManifest } from "@edhspace/api";
10
+
11
+ // src/dependencies.ts
12
+ import { createHash } from "crypto";
13
+ import { readFile, readdir, lstat, realpath } from "fs/promises";
14
+ import path from "path";
15
+
16
+ // src/approved-dependencies.ts
17
+ var approvedDependencies = [];
18
+
19
+ // src/dependencies.ts
20
+ var lifecycle = ["preinstall", "install", "postinstall", "prepare"];
21
+ var official = ["react", "react-dom", "@edhspace/api", "@edhspace/ui"];
22
+ var semver = /^\^?\d+\.\d+\.\d+$/;
23
+ async function inspectDependency(directory2) {
24
+ const root = await realpath(directory2);
25
+ const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
26
+ if (typeof pkg.name !== "string" || !/^\d+\.\d+\.\d+$/.test(pkg.version) || typeof pkg.license !== "string")
27
+ throw new Error("Dependency metadata must include its name, exact version and license.");
28
+ const hash = createHash("sha256");
29
+ async function visit(directory3) {
30
+ const entries = await readdir(directory3, { withFileTypes: true });
31
+ for (const entry of entries.sort(
32
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
33
+ )) {
34
+ if (entry.name === "node_modules" && entry.isDirectory()) continue;
35
+ if (entry.isSymbolicLink())
36
+ throw new Error(`Dependency contains a symlink: ${entry.name}.`);
37
+ const file = path.join(directory3, entry.name);
38
+ if (entry.isDirectory()) await visit(file);
39
+ else if (entry.isFile()) {
40
+ hash.update(path.relative(root, file).split(path.sep).join("/") + "\0");
41
+ const bytes = await readFile(file);
42
+ hash.update(String(bytes.byteLength) + "\0");
43
+ hash.update(bytes);
44
+ } else throw new Error(`Dependency contains a non-regular file: ${file}.`);
45
+ }
46
+ }
47
+ await visit(root);
48
+ return { ...pkg, filesSha256: hash.digest("hex") };
49
+ }
50
+ async function installedPackage(name, from) {
51
+ for (let directory2 = from; ; directory2 = path.dirname(directory2)) {
52
+ const target = path.join(directory2, "node_modules", name);
53
+ try {
54
+ const info = await lstat(target);
55
+ if (info.isSymbolicLink() || !info.isDirectory())
56
+ throw new Error(
57
+ `Reviewed dependencies must be installed registry packages: ${name}.`
58
+ );
59
+ return await realpath(target);
60
+ } catch (error) {
61
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
62
+ throw error;
63
+ }
64
+ if (path.dirname(directory2) === directory2) break;
65
+ }
66
+ throw new Error(
67
+ `Reviewed dependency is not installed: ${name}. Use a locked, script-free install.`
68
+ );
69
+ }
70
+ async function verifyLock(root, review) {
71
+ for (let directory2 = path.dirname(root); ; directory2 = path.dirname(directory2)) {
72
+ const file = path.join(directory2, "package-lock.json");
73
+ let contents;
74
+ try {
75
+ contents = await readFile(file, "utf8");
76
+ } catch (error) {
77
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
78
+ throw error;
79
+ if (path.dirname(directory2) === directory2) break;
80
+ continue;
81
+ }
82
+ const lock = JSON.parse(contents);
83
+ const entry = lock.packages?.[path.relative(directory2, root).split(path.sep).join("/")];
84
+ if (entry?.version !== review.version || entry.integrity !== review.integrity || entry.link || entry.hasInstallScript || !entry.resolved?.startsWith("https://registry.npmjs.org/"))
85
+ throw new Error(
86
+ `Dependency lock does not match its reviewed registry archive: ${review.name}.`
87
+ );
88
+ return;
89
+ }
90
+ throw new Error(`A package-lock.json is required for reviewed dependency ${review.name}.`);
91
+ }
92
+ async function verifyDependencies(root, pkg, policy = approvedDependencies) {
93
+ if (lifecycle.some((script) => script in pkg.scripts))
94
+ throw new Error("Extension lifecycle installation scripts are not allowed.");
95
+ for (const [name, version] of Object.entries(pkg.devDependencies))
96
+ if (name !== "@edhspace/devkit" || !semver.test(version))
97
+ throw new Error(`Unreviewed extension development dependency: ${name}.`);
98
+ const verified = /* @__PURE__ */ new Map();
99
+ async function verify(name, version, from) {
100
+ const review = policy.find((entry) => entry.name === name && entry.version === version);
101
+ if (!review || !/^(?:@[a-z0-9.-]+\/)?[a-z0-9][a-z0-9.-]*$/.test(name) || !/^\d+\.\d+\.\d+$/.test(version) || !/^[a-f0-9]{64}$/.test(review.filesSha256) || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(review.integrity) || !review.review.startsWith("https://github.com/EDHspace/extensions/") || !review.licenseFiles.length || review.imports.some((entry) => entry !== name && !entry.startsWith(name + "/")))
102
+ throw new Error(
103
+ `Unreviewed extension dependency: ${name}@${version}. Request maintainer review.`
104
+ );
105
+ const directory2 = await installedPackage(name, from);
106
+ if (verified.has(directory2)) return;
107
+ const installed = await inspectDependency(directory2);
108
+ if (installed.name !== name || installed.version !== version || installed.license !== review.license || installed.filesSha256 !== review.filesSha256)
109
+ throw new Error(
110
+ `Installed dependency differs from its reviewed files: ${name}@${version}.`
111
+ );
112
+ if (lifecycle.some((script) => script in (installed.scripts ?? {})))
113
+ throw new Error(`Dependency lifecycle installation scripts are not allowed: ${name}.`);
114
+ if (installed.bin) throw new Error(`Dependency executable bins are not allowed: ${name}.`);
115
+ await verifyLock(directory2, review);
116
+ for (const file of review.licenseFiles) {
117
+ const resolved = await realpath(path.join(directory2, file));
118
+ if (!resolved.startsWith(directory2 + path.sep) || !(await lstat(resolved)).isFile())
119
+ throw new Error(`Dependency license file escapes its package: ${name}/${file}.`);
120
+ }
121
+ verified.set(directory2, { root: directory2, review });
122
+ const dependencies = {
123
+ ...installed.dependencies,
124
+ ...installed.optionalDependencies,
125
+ ...installed.peerDependencies
126
+ };
127
+ const names = Object.keys(dependencies).filter((name2) => !official.includes(name2)).sort();
128
+ if (names.join("\0") !== Object.keys(review.dependencies).sort().join("\0"))
129
+ throw new Error(`Dependency graph differs from its review: ${name}.`);
130
+ for (const dependency of names)
131
+ await verify(dependency, review.dependencies[dependency], directory2);
132
+ }
133
+ for (const [name, version] of Object.entries({
134
+ ...pkg.dependencies,
135
+ ...pkg.peerDependencies
136
+ })) {
137
+ if (official.includes(name)) {
138
+ if (!semver.test(version))
139
+ throw new Error(
140
+ "Extension dependencies must use reviewed semver, not URLs, files or Git."
141
+ );
142
+ } else await verify(name, version, root);
143
+ }
144
+ return [...verified.values()];
145
+ }
146
+
147
+ // src/build.ts
148
+ var shared = ["@edhspace/api", "@edhspace/ui", "react", "react-dom"];
149
+ var packageName = (specifier) => specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
150
+ function allowedImport(specifier, dependencies = []) {
151
+ return specifier.startsWith(".") || shared.includes(packageName(specifier)) && !specifier.startsWith("@edhspace/api/host") || dependencies.some((entry) => entry.review.imports.includes(specifier));
152
+ }
153
+ var printDiagnostics = (diagnostics) => ts.formatDiagnosticsWithColorAndContext(diagnostics, {
154
+ getCurrentDirectory: () => process.cwd(),
155
+ getCanonicalFileName: (file) => file,
156
+ getNewLine: () => "\n"
157
+ });
158
+ async function validateExtension(directory2, policy = approvedDependencies) {
159
+ const root = await realpath2(directory2);
160
+ const raw = JSON.parse(await readFile2(path2.join(root, "package.json"), "utf8"));
161
+ const pkg = extensionPackageSchema.parse(raw);
162
+ const manifest = toExtensionManifest(raw);
163
+ const dependencies = await verifyDependencies(root, pkg, policy);
164
+ const directDependencies = dependencies.filter(
165
+ (entry) => entry.review.name in pkg.dependencies || entry.review.name in pkg.peerDependencies
166
+ );
167
+ for (const entry of [
168
+ pkg.icon,
169
+ ...pkg.panels.map((panel) => panel.entry),
170
+ ...pkg.commands.map((command2) => command2.entry)
171
+ ]) {
172
+ const resolved = await realpath2(path2.join(root, entry));
173
+ if (!resolved.startsWith(`${root}${path2.sep}`))
174
+ throw new Error(`Extension file escapes its directory: ${entry}.`);
175
+ if (!(await stat(resolved)).isFile())
176
+ throw new Error(`Extension entry is not a file: ${entry}.`);
177
+ }
178
+ const configPath = path2.join(root, "tsconfig.json");
179
+ const config = ts.readConfigFile(configPath, ts.sys.readFile);
180
+ if (config.error) throw new Error(printDiagnostics([config.error]));
181
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root);
182
+ if (parsed.errors.length) throw new Error(printDiagnostics(parsed.errors));
183
+ if (parsed.options.strict !== true || [
184
+ parsed.options.noImplicitAny,
185
+ parsed.options.strictNullChecks,
186
+ parsed.options.strictFunctionTypes,
187
+ parsed.options.strictBindCallApply,
188
+ parsed.options.strictPropertyInitialization,
189
+ parsed.options.alwaysStrict,
190
+ parsed.options.strictBuiltinIteratorReturn,
191
+ parsed.options.useUnknownInCatchVariables
192
+ ].includes(false))
193
+ throw new Error("Extensions must enable strict TypeScript without disabling its checks.");
194
+ if (parsed.fileNames.some((file) => !file.startsWith(`${root}${path2.sep}`)))
195
+ throw new Error("Extension TypeScript sources must stay inside the extension directory.");
196
+ const options = { ...parsed.options, noEmit: true, strict: true };
197
+ const program = ts.createProgram(parsed.fileNames, options);
198
+ const diagnostics = ts.getPreEmitDiagnostics(program);
199
+ if (diagnostics.length) throw new Error(printDiagnostics(diagnostics));
200
+ const forbidden = /* @__PURE__ */ new Set([
201
+ "window",
202
+ "document",
203
+ "globalThis",
204
+ "localStorage",
205
+ "sessionStorage",
206
+ "fetch",
207
+ "eval",
208
+ "Function",
209
+ "parent",
210
+ "top",
211
+ "self",
212
+ "alert",
213
+ "confirm",
214
+ "prompt",
215
+ "navigator",
216
+ "XMLHttpRequest",
217
+ "WebSocket",
218
+ "EventSource",
219
+ "Worker",
220
+ "SharedWorker",
221
+ "importScripts",
222
+ "Image",
223
+ "process"
224
+ ]);
225
+ const checker = program.getTypeChecker();
226
+ for (const source of program.getSourceFiles()) {
227
+ if (!source.fileName.startsWith(`${root}${path2.sep}`) || source.isDeclarationFile) continue;
228
+ const visit = (node) => {
229
+ const imported = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword ? node.arguments[0] : void 0;
230
+ if (imported && ts.isStringLiteral(imported)) {
231
+ if (!allowedImport(imported.text, directDependencies) || imported.text.startsWith(".") && !path2.resolve(path2.dirname(source.fileName), imported.text).startsWith(`${root}${path2.sep}`))
232
+ throw new Error(`Forbidden extension import: ${imported.text}.`);
233
+ }
234
+ if (ts.isIdentifier(node) && forbidden.has(node.text)) {
235
+ const symbol = checker.getSymbolAtLocation(node);
236
+ if (symbol?.declarations?.some(
237
+ (declaration) => /[/\\]lib\.[^/\\]+\.d\.ts$/.test(declaration.getSourceFile().fileName)
238
+ ))
239
+ throw new Error(
240
+ `Use the SDK instead of browser global ${node.text} in ${path2.relative(root, source.fileName)}.`
241
+ );
242
+ }
243
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && !ts.isStringLiteral(node.arguments[0]))
244
+ throw new Error(
245
+ "Extension dynamic imports must use literal, reviewed module paths."
246
+ );
247
+ ts.forEachChild(node, visit);
248
+ };
249
+ visit(source);
250
+ }
251
+ return { root, pkg, manifest, program, options, dependencies, directDependencies };
252
+ }
253
+ function importBoundary(root, dependencies = [], directDependencies = dependencies) {
254
+ return {
255
+ name: "edhspace-extension-boundary",
256
+ setup(builder) {
257
+ builder.onResolve({ filter: /.*/ }, async (args) => {
258
+ if (args.pluginData?.boundaryChecked) return;
259
+ const owner = [root, ...dependencies.map((entry) => entry.root)].sort((a, b) => b.length - a.length).find((directory2) => args.importer.startsWith(`${directory2}${path2.sep}`));
260
+ if (!owner) return;
261
+ if (args.path.startsWith(".")) {
262
+ const target = path2.resolve(path2.dirname(args.importer), args.path);
263
+ if (!target.startsWith(`${owner}${path2.sep}`))
264
+ return {
265
+ errors: [
266
+ { text: `Extension import escapes its directory: ${args.path}.` }
267
+ ]
268
+ };
269
+ const resolved = await builder.resolve(args.path, {
270
+ importer: args.importer,
271
+ resolveDir: args.resolveDir,
272
+ kind: args.kind,
273
+ pluginData: { boundaryChecked: true }
274
+ });
275
+ if (resolved.errors.length) return resolved;
276
+ if (!(await realpath2(resolved.path)).startsWith(`${owner}${path2.sep}`))
277
+ return {
278
+ errors: [
279
+ {
280
+ text: `Extension import follows a symlink outside its directory: ${args.path}.`
281
+ }
282
+ ]
283
+ };
284
+ return resolved;
285
+ } else {
286
+ const packageOwner = dependencies.find((entry) => entry.root === owner);
287
+ const permitted = packageOwner ? dependencies.filter(
288
+ (entry) => entry.review.name === packageOwner.review.name || entry.review.name in packageOwner.review.dependencies
289
+ ) : directDependencies;
290
+ if (!allowedImport(args.path, permitted))
291
+ return { errors: [{ text: `Forbidden extension import: ${args.path}.` }] };
292
+ }
293
+ return void 0;
294
+ });
295
+ builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => {
296
+ if (!dependencies.some((entry) => args.path.startsWith(entry.root + path2.sep)))
297
+ return;
298
+ const source = ts.createSourceFile(
299
+ args.path,
300
+ await readFile2(args.path, "utf8"),
301
+ ts.ScriptTarget.Latest,
302
+ true
303
+ );
304
+ const blocked = /* @__PURE__ */ new Set([
305
+ "fetch",
306
+ "XMLHttpRequest",
307
+ "WebSocket",
308
+ "EventSource",
309
+ "window",
310
+ "document",
311
+ "globalThis",
312
+ "navigator",
313
+ "eval",
314
+ "Function",
315
+ "localStorage",
316
+ "sessionStorage",
317
+ "Worker",
318
+ "SharedWorker",
319
+ "importScripts"
320
+ ]);
321
+ function visit(node) {
322
+ if (ts.isIdentifier(node) && blocked.has(node.text))
323
+ throw new Error(
324
+ `Reviewed dependency uses forbidden browser API ${node.text}: ${args.path}.`
325
+ );
326
+ ts.forEachChild(node, visit);
327
+ }
328
+ visit(source);
329
+ return void 0;
330
+ });
331
+ }
332
+ };
333
+ }
334
+ async function buildExtension(directory2, policy = approvedDependencies) {
335
+ const context2 = await validateExtension(directory2, policy);
336
+ const entries = Object.fromEntries([
337
+ ...context2.pkg.panels.map((panel) => [panel.id, path2.join(context2.root, panel.entry)]),
338
+ ...context2.pkg.commands.map((command2) => [
339
+ `command-${command2.id}`,
340
+ path2.join(context2.root, command2.entry)
341
+ ])
342
+ ]);
343
+ const output = path2.join(context2.root, "dist");
344
+ const result = await build({
345
+ entryPoints: entries,
346
+ outdir: output,
347
+ write: false,
348
+ bundle: true,
349
+ format: "esm",
350
+ platform: "browser",
351
+ target: "es2022",
352
+ minify: true,
353
+ metafile: true,
354
+ loader: { ".svg": "file", ".png": "file" },
355
+ external: shared.flatMap((name) => [name, `${name}/*`]),
356
+ plugins: [importBoundary(context2.root, context2.dependencies, context2.directDependencies)]
357
+ });
358
+ for (const file of result.outputFiles)
359
+ if (file.contents.byteLength > 262144)
360
+ throw new Error(`Bundle exceeds 256 KiB: ${path2.basename(file.path)}.`);
361
+ try {
362
+ const existing = await lstat2(output);
363
+ if (existing.isSymbolicLink() || !existing.isDirectory())
364
+ throw new Error("Extension dist output must be a regular directory.");
365
+ await rm(output, { recursive: true });
366
+ } catch (error) {
367
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
368
+ }
369
+ await mkdir(output, { recursive: true });
370
+ for (const file of result.outputFiles) await writeFile(file.path, file.contents);
371
+ const licenses = [];
372
+ for (const dependency of context2.dependencies)
373
+ for (const file of dependency.review.licenseFiles) {
374
+ const name = `${dependency.review.name.replace(/[@/]/g, "-")}-${dependency.review.version}-${path2.basename(file)}`;
375
+ const bytes = await readFile2(path2.join(dependency.root, file));
376
+ await mkdir(path2.join(output, "licenses"), { recursive: true });
377
+ await writeFile(path2.join(output, "licenses", name), bytes);
378
+ licenses.push({
379
+ file: `licenses/${name}`,
380
+ sha256: createHash2("sha256").update(bytes).digest("hex")
381
+ });
382
+ }
383
+ const declarations = ts.createProgram(context2.program.getRootFileNames(), {
384
+ ...context2.options,
385
+ noEmit: false,
386
+ declaration: true,
387
+ emitDeclarationOnly: true,
388
+ rootDir: path2.join(context2.root, "src"),
389
+ outDir: output
390
+ });
391
+ const emitted = declarations.emit();
392
+ if (emitted.emitSkipped || emitted.diagnostics.length)
393
+ throw new Error(printDiagnostics(emitted.diagnostics));
394
+ await writeFile(
395
+ path2.join(output, "build.json"),
396
+ JSON.stringify(
397
+ {
398
+ manifest: context2.manifest,
399
+ apiVersion: context2.pkg.apiVersion,
400
+ dependencies: context2.dependencies.map((dependency) => dependency.review),
401
+ licenses,
402
+ artifacts: result.outputFiles.map((file) => ({
403
+ file: path2.basename(file.path),
404
+ bytes: file.contents.byteLength,
405
+ sha256: createHash2("sha256").update(file.contents).digest("hex")
406
+ }))
407
+ },
408
+ null,
409
+ 2
410
+ )
411
+ );
412
+ return context2;
413
+ }
414
+
415
+ // src/dev.ts
416
+ import { createServer } from "http";
417
+ import { readFile as readFile3, mkdir as mkdir2 } from "fs/promises";
418
+ import path3 from "path";
419
+ import { context } from "esbuild";
420
+ async function devExtension(directory2) {
421
+ const { root, pkg, manifest, dependencies, directDependencies } = await validateExtension(directory2);
422
+ const output = path3.join(root, ".local", "dev");
423
+ await mkdir2(output, { recursive: true });
424
+ const source = `
425
+ import React from "react";
426
+ import { createRoot } from "react-dom/client";
427
+ import { createExtensionClient, ExtensionError } from "@edhspace/api";
428
+ import { ExtensionSession, createNetworkHandler, NetworkApprovalQueue } from "@edhspace/api/host";
429
+ import { ExtensionProvider } from "@edhspace/api/react";
430
+ import { ApiRequestDialog } from "@edhspace/ui";
431
+ import "@edhspace/ui/styles.css";
432
+ import Panel from ${JSON.stringify(path3.join(root, pkg.panels[0].entry))};
433
+ const deck = { id: "22222222-2222-4222-8222-222222222222", name: "SDK mock deck", revision: "1", format: "commander",
434
+ cards: [{id:"forest",name:"Forest",quantity:38,manaValue:0,manaCost:"",typeLine:"Basic Land"},
435
+ {id:"ring",name:"Sol Ring",quantity:1,manaValue:1,manaCost:"{1}",typeLine:"Artifact"},
436
+ {id:"sample",name:"Sample spells (mock)",quantity:60,manaValue:3,typeLine:"Sorcery"}] };
437
+ const sessionId = crypto.randomUUID();
438
+ const manifest = ${JSON.stringify(manifest)};
439
+ const approvals = new NetworkApprovalQueue();
440
+ const session = new ExtensionSession(manifest, sessionId, manifest.permissions, () => true, {
441
+ "network.request": createNetworkHandler(manifest, {approve: approvals.approve}),
442
+ "deck.read": async()=>deck,
443
+ "selection.read": async()=>[],
444
+ "cards.inspect": async({cardId})=>{
445
+ const card=deck.cards.find(c=>c.id===cardId);
446
+ if(!card)throw new ExtensionError("Only mock deck cards can be inspected.","denied");
447
+ alert("Mock preview: "+card.name);return {opened:true}},
448
+ "preferences.get": async()=>Object.fromEntries(manifest.preferences.map(p=>[p.id,p.default])),
449
+ });
450
+ const api = createExtensionClient(request=>session.execute(request), sessionId, manifest.permissions);
451
+ function Workbench(){
452
+ const pending=React.useSyncExternalStore(approvals.subscribe,approvals.getSnapshot)[0];
453
+ return <div className="edhspace-ui"><header><p>Synthetic data only. External API requests require your approval.</p>
454
+ <button type="button" onClick={()=>{document.documentElement.dataset.theme=document.documentElement.dataset.theme==="dark"?"light":"dark"}}>Toggle theme</button></header>
455
+ <ExtensionProvider api={api} revision="1"><Panel/></ExtensionProvider>
456
+ {pending&&<ApiRequestDialog key={pending.id} extension={manifest.title} url={pending.request.url} method={pending.request.method}
457
+ data={JSON.stringify({query:pending.request.query,body:pending.request.body},null,2)}
458
+ onAccept={remember=>approvals.answer(pending.id,true,remember)} onCancel={()=>approvals.answer(pending.id,false)}/>}
459
+ </div>}
460
+ createRoot(document.getElementById("root")).render(<Workbench/>);
461
+ `;
462
+ const bundler = await context({
463
+ stdin: { contents: source, loader: "tsx", resolveDir: root },
464
+ bundle: true,
465
+ format: "esm",
466
+ platform: "browser",
467
+ target: "es2022",
468
+ outfile: path3.join(output, "app.js"),
469
+ plugins: [importBoundary(root, dependencies, directDependencies)]
470
+ });
471
+ try {
472
+ await bundler.rebuild();
473
+ await bundler.watch();
474
+ } catch (error) {
475
+ await bundler.dispose();
476
+ throw error;
477
+ }
478
+ const assets = /* @__PURE__ */ new Map([
479
+ ["/app.js", ["app.js", "text/javascript"]],
480
+ ["/app.css", ["app.css", "text/css"]]
481
+ ]);
482
+ const server = createServer(async (request, response) => {
483
+ const url = new URL(request.url ?? "/", "http://127.0.0.1:5186");
484
+ if (url.pathname === "/" || url.pathname === "/health") {
485
+ response.writeHead(200, { "Content-Type": "text/html", "Cache-Control": "no-store" });
486
+ response.end(
487
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>EDHspace extension workbench</title><link rel="stylesheet" href="/app.css"><style>body{margin:0;font:16px system-ui}html[data-theme=dark]{--set-panel:#202620;--set-text:#f3f6f3;--set-muted:#bfcbbf;--set-accent:#8fca9b;--set-border:#81968b}header{padding:1rem}button{min-height:44px}</style></head><body><div id="root"></div><script type="module" src="/app.js"></script></body></html>`
488
+ );
489
+ return;
490
+ }
491
+ const asset = assets.get(url.pathname);
492
+ if (!asset) {
493
+ response.writeHead(404);
494
+ response.end("Not found.");
495
+ return;
496
+ }
497
+ try {
498
+ response.writeHead(200, { "Content-Type": asset[1], "Cache-Control": "no-store" });
499
+ response.end(await readFile3(path3.join(output, asset[0])));
500
+ } catch (error) {
501
+ console.error("Workbench asset failed.", error);
502
+ response.destroy();
503
+ }
504
+ });
505
+ server.on("error", (error) => {
506
+ console.error("Workbench server failed.", error);
507
+ void bundler.dispose();
508
+ process.exitCode = 1;
509
+ });
510
+ server.listen(
511
+ 5186,
512
+ "127.0.0.1",
513
+ () => console.log("Extension workbench: http://127.0.0.1:5186")
514
+ );
515
+ for (const signal of ["SIGINT", "SIGTERM"])
516
+ process.once(signal, () => {
517
+ server.close();
518
+ void bundler.dispose();
519
+ });
520
+ }
521
+
522
+ // src/cli.ts
523
+ import { readdir as readdir2, realpath as realpath3 } from "fs/promises";
524
+ import path5 from "path";
525
+
526
+ // src/sideload.ts
527
+ import { build as build2 } from "esbuild";
528
+ import { mkdir as mkdir3, readFile as readFile4, writeFile as writeFile2, lstat as lstat3 } from "fs/promises";
529
+ import path4 from "path";
530
+ import { sideloadBundleSchema, sideloadProtocol, sideloadVersion } from "@edhspace/api/sideload";
531
+ async function buildSideloadExtension(directory2) {
532
+ const context2 = await validateExtension(directory2);
533
+ const panels = [];
534
+ const notices = [];
535
+ for (const dependency of context2.dependencies)
536
+ for (const file of dependency.review.licenseFiles)
537
+ notices.push(
538
+ `${dependency.review.name}@${dependency.review.version}
539
+ ` + await readFile4(path4.join(dependency.root, file), "utf8")
540
+ );
541
+ for (const panel of context2.pkg.panels) {
542
+ const source = `
543
+ import React from "react";
544
+ import { createRoot } from "react-dom/client";
545
+ import { connectSideload, sideloadProtocol, sideloadVersion } from "@edhspace/api/sideload";
546
+ import { ExtensionProvider } from "@edhspace/api/react";
547
+ import { Notice, SymbolRenderingProvider } from "@edhspace/ui";
548
+ import "@edhspace/ui/styles.css";
549
+ import Panel from ${JSON.stringify(path4.join(context2.root, panel.entry))};
550
+ const root = createRoot(document.getElementById("root"));
551
+ function fail(error) {
552
+ const message = error instanceof Error ? error.message : "The extension failed to start.";
553
+ root.render(<div className="edhspace-ui"><Notice error>{message}</Notice></div>);
554
+ window.parent.postMessage({protocol:sideloadProtocol,version:sideloadVersion,type:"error",message:message.slice(0,300)}, "*");
555
+ }
556
+ class Boundary extends React.Component {
557
+ state = {error:undefined};
558
+ static getDerivedStateFromError(error) { return {error}; }
559
+ componentDidCatch(error) {
560
+ console.error("Sideloaded panel failed.", error);
561
+ window.parent.postMessage({protocol:sideloadProtocol,version:sideloadVersion,type:"error",message:"The extension panel failed to render."}, "*");
562
+ }
563
+ render() {
564
+ return this.state.error ? <Notice error>The extension panel failed to render.</Notice> : this.props.children;
565
+ }
566
+ }
567
+ connectSideload(${JSON.stringify(panel.id)}).then(connection => {
568
+ function SideloadPanel() {
569
+ const state = React.useSyncExternalStore(connection.subscribe, connection.getSnapshot);
570
+ React.useEffect(() => { document.documentElement.dataset.theme = state.theme; }, [state.theme]);
571
+ return <div className="edhspace-ui">{state.error ? <Notice error>{state.error.message}</Notice> :
572
+ <Boundary><SymbolRenderingProvider mode="text"><ExtensionProvider api={connection.api} revision={state.revision}><Panel/></ExtensionProvider></SymbolRenderingProvider></Boundary>}</div>;
573
+ }
574
+ window.addEventListener("pagehide", () => connection.dispose(), {once:true});
575
+ root.render(<SideloadPanel/>);
576
+ }).catch(fail);
577
+ `;
578
+ const result = await build2({
579
+ stdin: { contents: source, loader: "tsx", resolveDir: context2.root },
580
+ outfile: "panel.js",
581
+ write: false,
582
+ bundle: true,
583
+ format: "iife",
584
+ platform: "browser",
585
+ target: "es2022",
586
+ minify: true,
587
+ legalComments: "inline",
588
+ define: { "process.env.NODE_ENV": '"production"' },
589
+ loader: { ".svg": "dataurl", ".png": "dataurl", ".jpg": "dataurl", ".woff2": "dataurl" },
590
+ plugins: [importBoundary(context2.root, context2.dependencies, context2.directDependencies)],
591
+ banner: notices.length ? { js: notices.join("\n\n").split("\n").map((line) => `// ${line}`).join("\n") } : void 0
592
+ });
593
+ const javascript = result.outputFiles.find((file) => file.path.endsWith(".js"));
594
+ if (!javascript) throw new Error(`No JavaScript was emitted for panel ${panel.id}.`);
595
+ const unsupported = result.outputFiles.filter(
596
+ (file) => !file.path.endsWith(".js") && !file.path.endsWith(".css")
597
+ );
598
+ if (unsupported.length)
599
+ throw new Error(`Sideload panels must inline all assets: ${unsupported[0].path}.`);
600
+ panels.push({
601
+ id: panel.id,
602
+ javascript: javascript.text,
603
+ css: result.outputFiles.find((file) => file.path.endsWith(".css"))?.text ?? ""
604
+ });
605
+ }
606
+ const bundle = sideloadBundleSchema.parse({
607
+ protocol: sideloadProtocol,
608
+ version: sideloadVersion,
609
+ manifest: context2.manifest,
610
+ panels
611
+ });
612
+ const outputDirectory = path4.join(context2.root, "dist");
613
+ try {
614
+ const output2 = await lstat3(outputDirectory);
615
+ if (!output2.isDirectory() || output2.isSymbolicLink())
616
+ throw new Error("Extension dist output must be a regular directory.");
617
+ } catch (error) {
618
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
619
+ }
620
+ await mkdir3(outputDirectory, { recursive: true });
621
+ const output = path4.join(outputDirectory, "sideload.edhspace-extension.json");
622
+ try {
623
+ const existing = await lstat3(output);
624
+ if (existing.isSymbolicLink() || !existing.isFile())
625
+ throw new Error("Sideload output must be a regular file.");
626
+ } catch (error) {
627
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
628
+ }
629
+ await writeFile2(output, JSON.stringify(bundle));
630
+ return { ...context2, bundle, output };
631
+ }
632
+
633
+ // src/cli.ts
634
+ var [command, directory] = process.argv.slice(2);
635
+ try {
636
+ if (!directory || !["build", "check", "dev", "sideload", "build-all", "check-all", "inspect-dependency"].includes(command))
637
+ throw new Error(
638
+ "Usage: edhspace <check|build|dev|sideload> <extension-directory>, <check-all|build-all> <extensions-directory>, or inspect-dependency <installed-package-directory>"
639
+ );
640
+ if (command === "inspect-dependency")
641
+ console.log(JSON.stringify(await inspectDependency(directory), null, 2));
642
+ else if (command === "dev") await devExtension(directory);
643
+ else if (command === "sideload") {
644
+ const result = await buildSideloadExtension(directory);
645
+ console.log(`Sideload bundle: ${result.output}`);
646
+ } else {
647
+ let directories = [directory];
648
+ if (command.endsWith("-all")) {
649
+ const root = await realpath3(directory);
650
+ const entries = await readdir2(root, { withFileTypes: true });
651
+ if (entries.some((entry) => entry.isSymbolicLink()))
652
+ throw new Error("Extension directories cannot be symlinks.");
653
+ directories = entries.filter((entry) => entry.isDirectory()).map((entry) => path5.join(root, entry.name)).sort();
654
+ if (!directories.length) throw new Error("No extension directories found.");
655
+ }
656
+ for (const extension of directories) {
657
+ const result = command.startsWith("build") ? await buildExtension(extension) : await validateExtension(extension);
658
+ console.log(`${command}: ${result.pkg.name} v${result.pkg.version}`);
659
+ }
660
+ }
661
+ } catch (error) {
662
+ console.error("EDHspace extension command failed.", error);
663
+ process.exitCode = 1;
664
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
- "name": "@edhspace/devkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@edhspace/devkit",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "license": "ISC",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/EDHspace/extensions.git",
9
+ "directory": "packages/devkit"
10
+ },
11
+ "homepage": "https://github.com/EDHspace/extensions/tree/main/packages/devkit#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/EDHspace/extensions/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "description": "Build and validate curated EDHspace community extensions",
20
+ "bin": {
21
+ "edhspace": "dist/cli.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsup",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "vitest run --maxWorkers=1"
31
+ },
32
+ "dependencies": {
33
+ "@edhspace/api": "^0.2.0",
34
+ "@edhspace/ui": "^0.2.0",
35
+ "esbuild": "0.27.1",
36
+ "typescript": "5.9.3",
37
+ "react": "^19.2.8",
38
+ "react-dom": "^19.2.8"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^20.10.0",
42
+ "tsup": "^8.0.0",
43
+ "vitest": "3.2.7"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.12.0"
47
+ }
48
+ }