@stallforge/cli 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 (42) hide show
  1. package/README.md +39 -2
  2. package/bin/cli.mjs +4 -0
  3. package/package.json +58 -4
  4. package/src/commands/create.mjs +117 -0
  5. package/src/commands/dev.mjs +106 -0
  6. package/src/commands/doctor.mjs +48 -0
  7. package/src/commands/publish.mjs +43 -0
  8. package/src/commands/test.mjs +83 -0
  9. package/src/commands/validate.mjs +35 -0
  10. package/src/index.mjs +9 -0
  11. package/src/lib/build.mjs +35 -0
  12. package/src/lib/bundle.mjs +132 -0
  13. package/src/lib/check.mjs +105 -0
  14. package/src/lib/inspect.mjs +38 -0
  15. package/src/lib/names.mjs +6 -0
  16. package/src/lib/package-info.mjs +19 -0
  17. package/src/lib/report.mjs +4 -0
  18. package/src/lib/templates.mjs +5 -0
  19. package/src/lib/usage.mjs +1 -0
  20. package/src/main.mjs +61 -0
  21. package/template/src/index.mjs +69 -0
  22. package/template/templates/_common/README.md.tpl +11 -0
  23. package/template/templates/_common/gitignore.tpl +2 -0
  24. package/template/templates/_common/package.json.tpl +18 -0
  25. package/template/templates/_common/test/manifest.test.ts.tpl +15 -0
  26. package/template/templates/_common/tsconfig.json.tpl +15 -0
  27. package/template/templates/example/plugin.json.tpl +13 -0
  28. package/template/templates/example/src/index.ts.tpl +15 -0
  29. package/template/templates/example/test/plugin.test.ts.tpl +23 -0
  30. package/template/templates/payment/plugin.json.tpl +136 -0
  31. package/template/templates/payment/src/index.ts.tpl +248 -0
  32. package/types/bundle.d.ts +39 -0
  33. package/types/index.d.ts +24 -0
  34. package/types/shims/brand.d.ts +8 -0
  35. package/types/shims/conformance.d.ts +11 -0
  36. package/types/shims/contracts.d.ts +22 -0
  37. package/types/shims/sdk-range.d.ts +2 -0
  38. package/types/shims/sdk-scan.d.ts +8 -0
  39. package/types/shims/sdk.d.ts +1 -0
  40. package/types/shims/slot-shapes.d.ts +4 -0
  41. package/types/shims/slot-suites.d.ts +9 -0
  42. package/types/shims/validate.d.ts +14 -0
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { validateManifestText } from '#contracts/src/manifest/validate.mjs';
5
+ import { BUNDLER, BUNDLER_VERSION } from './build.mjs';
6
+
7
+ export const BUNDLE_FORMAT = 1;
8
+ export const BUNDLE_FILES = Object.freeze({
9
+ bundle: 'index.mjs',
10
+ manifest: 'plugin.json',
11
+ entry: 'registry-entry.json',
12
+ });
13
+
14
+ export const sha256 = (data) => createHash('sha256').update(data).digest('hex');
15
+ export const bundleDirName = (manifest) => `${manifest.name}-${manifest.version}`;
16
+ // The source manifest with only the entry changed; key order is kept so the same source gives the same bytes.
17
+ export const manifestText = (raw) => `${JSON.stringify({ ...raw, entry: BUNDLE_FILES.bundle }, null, 2)}\n`;
18
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
19
+
20
+ /** @param {{ manifest: any, bundle: Uint8Array, manifestBytes: Uint8Array, sourceTag?: string | null }} input */
21
+ export function registryEntry({ manifest, bundle, manifestBytes, sourceTag = null }) {
22
+ return {
23
+ format: BUNDLE_FORMAT,
24
+ name: manifest.name,
25
+ version: manifest.version,
26
+ type: manifest.type,
27
+ license: manifest.license,
28
+ sdk: manifest.sdk,
29
+ capabilities: [...manifest.capabilities].sort(byText),
30
+ network_domains: [...manifest.network.domains].sort(byText),
31
+ slots: manifest.slots.map((item) => ({ slot: item.slot, mode: item.mode })).sort((a, b) => byText(a.slot, b.slot)),
32
+ bundle: { file: BUNDLE_FILES.bundle, sha256: sha256(bundle), bytes: bundle.length },
33
+ manifest: { file: BUNDLE_FILES.manifest, sha256: sha256(manifestBytes), bytes: manifestBytes.length },
34
+ toolchain: { bundler: BUNDLER, version: BUNDLER_VERSION, format: 'esm', minify: true },
35
+ source_tag: sourceTag,
36
+ };
37
+ }
38
+
39
+ /** Copies each publishable route's allow-list file from the plugin source into the bundle folder. */
40
+ function copyPublicFieldFiles(manifest, sourceDir, dir) {
41
+ if (typeof sourceDir !== 'string' || sourceDir === '') return;
42
+ const base = fs.realpathSync(sourceDir);
43
+ for (const route of manifest.routes ?? []) {
44
+ if (route.policy !== 'publishable' || typeof route.public_fields !== 'string') continue;
45
+ const from = path.join(base, route.public_fields);
46
+ const real = fs.realpathSync(from);
47
+ if (real !== base && !real.startsWith(base + path.sep)) {
48
+ throw new Error(`public_fields ${route.public_fields} leaves the plugin folder`);
49
+ }
50
+ const to = path.join(dir, route.public_fields);
51
+ fs.mkdirSync(path.dirname(to), { recursive: true });
52
+ fs.copyFileSync(real, to);
53
+ }
54
+ }
55
+
56
+ // Replaces only outRoot/NAME-VERSION. Nothing is sent anywhere.
57
+ /** @param {{ outRoot: string, raw: any, manifest: any, bundle: Uint8Array, sourceTag?: string | null, sourceDir?: string | null }} input */
58
+ export function writeBundle({ outRoot, raw, manifest, bundle, sourceTag = null, sourceDir = null }) {
59
+ const dir = path.join(outRoot, bundleDirName(manifest));
60
+ fs.rmSync(dir, { recursive: true, force: true });
61
+ fs.mkdirSync(dir, { recursive: true });
62
+ const manifestBytes = Buffer.from(manifestText(raw));
63
+ const entry = registryEntry({ manifest, bundle, manifestBytes, sourceTag });
64
+ fs.writeFileSync(path.join(dir, BUNDLE_FILES.bundle), bundle);
65
+ fs.writeFileSync(path.join(dir, BUNDLE_FILES.manifest), manifestBytes);
66
+ fs.writeFileSync(path.join(dir, BUNDLE_FILES.entry), `${JSON.stringify(entry, null, 2)}\n`);
67
+ copyPublicFieldFiles(manifest, sourceDir, dir);
68
+ return { dir, entry };
69
+ }
70
+
71
+ // Integrity and consistency of a bundle folder. Does not scan the code (validate does that).
72
+ export function verifyBundle(dir) {
73
+ const problems = [];
74
+ const read = (file) => {
75
+ try {
76
+ return fs.readFileSync(path.join(dir, file));
77
+ } catch {
78
+ problems.push(`${file} is missing`);
79
+ return null;
80
+ }
81
+ };
82
+ const entryBytes = read(BUNDLE_FILES.entry);
83
+ const bundle = read(BUNDLE_FILES.bundle);
84
+ const manifestBytes = read(BUNDLE_FILES.manifest);
85
+ /** @type {any} */
86
+ let entry = null;
87
+ if (entryBytes) {
88
+ try {
89
+ entry = JSON.parse(entryBytes.toString('utf8'));
90
+ } catch (error) {
91
+ const err = /** @type {{ message?: string }} */ (error);
92
+ problems.push(`${BUNDLE_FILES.entry} is not valid JSON (${err.message})`);
93
+ }
94
+ }
95
+ const label = typeof entry?.name === 'string' ? entry.name : path.basename(path.resolve(dir));
96
+ if (entry && bundle && manifestBytes) {
97
+ if (entry.format !== BUNDLE_FORMAT)
98
+ problems.push(`${BUNDLE_FILES.entry}: format ${entry.format} is not ${BUNDLE_FORMAT}`);
99
+ if (entry.bundle?.sha256 !== sha256(bundle))
100
+ problems.push(
101
+ `${BUNDLE_FILES.bundle}: sha256 ${sha256(bundle)} does not match the registry entry (${entry.bundle?.sha256})`,
102
+ );
103
+ if (entry.bundle?.bytes !== bundle.length)
104
+ problems.push(`${BUNDLE_FILES.bundle}: ${bundle.length} bytes, the registry entry says ${entry.bundle?.bytes}`);
105
+ if (entry.manifest?.sha256 !== sha256(manifestBytes))
106
+ problems.push(
107
+ `${BUNDLE_FILES.manifest}: sha256 ${sha256(manifestBytes)} does not match the registry entry (${entry.manifest?.sha256})`,
108
+ );
109
+ const check = validateManifestText(manifestBytes.toString('utf8'));
110
+ if (!check.ok) {
111
+ problems.push(...check.errors.map((error) => `${BUNDLE_FILES.manifest}: ${error}`));
112
+ } else {
113
+ const manifest = check.manifest;
114
+ if (manifest.entry !== BUNDLE_FILES.bundle)
115
+ problems.push(`${BUNDLE_FILES.manifest}: entry is ${manifest.entry}, a bundle needs ${BUNDLE_FILES.bundle}`);
116
+ if (entry.name !== manifest.name || entry.version !== manifest.version)
117
+ problems.push(
118
+ `${BUNDLE_FILES.entry} names ${entry.name} ${entry.version} but ${BUNDLE_FILES.manifest} is ${manifest.name} ${manifest.version}`,
119
+ );
120
+ if (JSON.stringify(entry.capabilities) !== JSON.stringify([...manifest.capabilities].sort(byText)))
121
+ problems.push(`${BUNDLE_FILES.entry}: capabilities differ from ${BUNDLE_FILES.manifest}`);
122
+ for (const route of manifest.routes ?? []) {
123
+ if (route.policy !== 'publishable' || typeof route.public_fields !== 'string') continue;
124
+ const fieldsPath = path.join(dir, route.public_fields);
125
+ if (!fs.existsSync(fieldsPath) || !fs.statSync(fieldsPath).isFile()) {
126
+ problems.push(`${route.public_fields}: allow-list file is missing from the bundle`);
127
+ }
128
+ }
129
+ }
130
+ }
131
+ return { ok: problems.length === 0, problems: problems.map((problem) => `${label}: ${problem}`), entry };
132
+ }
@@ -0,0 +1,105 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { scan } from '#sdk/scan';
4
+ import { BUNDLER, BUNDLER_PIN, BUNDLER_VERSION, buildBundle } from './build.mjs';
5
+ import { sha256 } from './bundle.mjs';
6
+ import { readManifest } from './inspect.mjs';
7
+ import { SDK_PACKAGE } from './names.mjs';
8
+
9
+ const CAPABILITY_RULES = new Set(['undeclared-capability', 'unused-capability']);
10
+ const where = (name, finding) =>
11
+ `${name}: index.mjs:${finding.line}:${finding.column} ${finding.rule}: ${finding.message}`;
12
+
13
+ export function rebuildProblem(name, hashes) {
14
+ return new Set(hashes).size > 1
15
+ ? `${name}: rebuild differs: clean builds gave ${hashes.join(' and ')}; a bundle must rebuild byte for byte`
16
+ : null;
17
+ }
18
+
19
+ /** Scan profile for official plugin kinds that need Node built-ins beyond the default set. */
20
+ function scanProfile(manifest) {
21
+ if (manifest?.type === 'database') return 'database-driver';
22
+ if (manifest?.type === 'file-storage') return 'storage';
23
+ return undefined;
24
+ }
25
+
26
+ // Scans the built bundle (what ships) and, when given, the source entry (capability use survives there in full).
27
+ // Capability findings are derived here so every message names the capability.
28
+ /** @param {{ name: string, manifest: any, bundleText: string, sourceText?: string | null }} input */
29
+ export function scanBundle({ name, manifest, bundleText, sourceText = null }) {
30
+ const declared = manifest.capabilities;
31
+ const profile = scanProfile(manifest);
32
+ const bundle = scan(bundleText, { capabilities: declared, profile });
33
+ const used = new Set(bundle.used_capabilities);
34
+ if (sourceText !== null)
35
+ for (const item of scan(sourceText, { capabilities: declared, allowRelative: true, profile }).used_capabilities)
36
+ used.add(item);
37
+ const errors = bundle.errors
38
+ .filter((finding) => !CAPABILITY_RULES.has(finding.rule))
39
+ .map((finding) => where(name, finding));
40
+ for (const capability of [...used].sort()) {
41
+ if (!declared.includes(capability))
42
+ errors.push(`${name}: undeclared-capability: the code uses ${capability} but plugin.json does not declare it`);
43
+ }
44
+ if (bundle.imports.includes(SDK_PACKAGE)) {
45
+ errors.push(
46
+ `${name}: sdk-runtime-import: the bundle imports ${SDK_PACKAGE} at run time; the host passes the SDK in through ctx, so import types only (import type)`,
47
+ );
48
+ }
49
+ const warnings = declared
50
+ .filter((capability) => !used.has(capability))
51
+ .map((capability) => `${name}: unused-capability: plugin.json declares ${capability} but the code never uses it`);
52
+ return { errors, warnings, used: [...used].sort() };
53
+ }
54
+
55
+ // Manifest, SDK range, build, scan and capability use of a plugin source folder. builds is 1 for validate and 2 for publish.
56
+ export async function checkPlugin(dir, { builds = 1 } = {}) {
57
+ const read = readManifest(dir);
58
+ /** @type {{ name: string, raw: any, manifest: any, errors: string[], warnings: string[], bundle: Buffer | null, used: string[] }} */
59
+ const result = {
60
+ name: read.name,
61
+ raw: read.raw,
62
+ manifest: read.manifest,
63
+ errors: [...read.errors],
64
+ warnings: [],
65
+ bundle: null,
66
+ used: [],
67
+ };
68
+ if (!read.manifest || read.manifest.entry === undefined) return result;
69
+ const entryFile = path.resolve(dir, read.manifest.entry);
70
+ if (!fs.existsSync(entryFile)) {
71
+ result.errors.push(`${read.name}: entry: ${read.manifest.entry} does not exist`);
72
+ return result;
73
+ }
74
+ if (BUNDLER_VERSION !== BUNDLER_PIN) {
75
+ result.errors.push(
76
+ `${read.name}: ${BUNDLER} ${BUNDLER_VERSION} is installed but ${BUNDLER_PIN} is pinned; install the pinned version before building`,
77
+ );
78
+ return result;
79
+ }
80
+ const hashes = [];
81
+ try {
82
+ for (let index = 0; index < builds; index += 1) {
83
+ const bytes = await buildBundle(dir, read.manifest.entry, index);
84
+ hashes.push(sha256(bytes));
85
+ if (index === 0) result.bundle = bytes;
86
+ }
87
+ } catch (error) {
88
+ const err = /** @type {{ message?: string }} */ (error);
89
+ result.errors.push(`${read.name}: build failed: ${String(err?.message ?? error).split('\n')[0]}`);
90
+ result.bundle = null;
91
+ return result;
92
+ }
93
+ const different = rebuildProblem(read.name, hashes);
94
+ if (different) result.errors.push(different);
95
+ const scanned = scanBundle({
96
+ name: read.name,
97
+ manifest: read.manifest,
98
+ bundleText: /** @type {Buffer} */ (result.bundle).toString('utf8'),
99
+ sourceText: fs.readFileSync(entryFile, 'utf8'),
100
+ });
101
+ result.errors.push(...scanned.errors);
102
+ result.warnings.push(...scanned.warnings);
103
+ result.used = scanned.used;
104
+ return result;
105
+ }
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { explainRange, sdkSatisfies } from '#contracts/src/manifest/sdk-range.mjs';
4
+ import { validateManifestText } from '#contracts/src/manifest/validate.mjs';
5
+ import { SDK_VERSION } from '#sdk';
6
+
7
+ // Reads and checks plugin.json in a folder. Every error line starts with the plugin name.
8
+ export function readManifest(dir) {
9
+ const label = path.basename(path.resolve(dir));
10
+ let text;
11
+ try {
12
+ text = fs.readFileSync(path.join(dir, 'plugin.json'), 'utf8');
13
+ } catch {
14
+ return {
15
+ name: label,
16
+ raw: null,
17
+ manifest: null,
18
+ errors: [`${label}: plugin.json was not found in ${path.resolve(dir)}`],
19
+ };
20
+ }
21
+ let raw = null;
22
+ try {
23
+ raw = JSON.parse(text);
24
+ } catch {
25
+ // validateManifestText reports the parse error below
26
+ }
27
+ /** @type {any} */
28
+ const parsed = raw;
29
+ const name = typeof parsed?.name === 'string' ? parsed.name : label;
30
+ const check = validateManifestText(text);
31
+ if (!check.ok) return { name, raw, manifest: null, errors: check.errors.map((error) => `${name}: ${error}`) };
32
+ /** @type {any} */
33
+ const manifest = check.manifest;
34
+ const errors = [];
35
+ if (!sdkSatisfies(manifest.sdk, SDK_VERSION)) errors.push(`${name}: sdk: ${explainRange(manifest.sdk, SDK_VERSION)}`);
36
+ if (manifest.entry === undefined) errors.push(`${name}: entry: a plugin needs an entry file to build a bundle`);
37
+ return { name, raw, manifest, errors };
38
+ }
@@ -0,0 +1,6 @@
1
+ // Package names and the command name come from the brand module; no other source file writes them.
2
+ import { brand } from '#contracts/brand';
3
+
4
+ export const SDK_PACKAGE = `${brand.packageScope}/plugin-sdk`;
5
+ export const CLI_PACKAGE = `${brand.packageScope}/cli`;
6
+ export const CLI_NAME = brand.cliName;
@@ -0,0 +1,19 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ // Finds the folder, name and version of an installed package from any specifier that resolves from here.
6
+ export function packageInfo(specifier) {
7
+ let dir = path.dirname(fileURLToPath(import.meta.resolve(specifier)));
8
+ for (;;) {
9
+ const file = path.join(dir, 'package.json');
10
+ if (fs.existsSync(file)) {
11
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
12
+ if (pkg.name && (specifier === pkg.name || specifier.startsWith(`${pkg.name}/`)))
13
+ return { name: pkg.name, version: pkg.version, root: dir };
14
+ }
15
+ const up = path.dirname(dir);
16
+ if (up === dir) throw new Error(`cannot find the package of ${specifier}`);
17
+ dir = up;
18
+ }
19
+ }
@@ -0,0 +1,4 @@
1
+ export function report(ctx, result) {
2
+ for (const warning of result.warnings) ctx.out(`warning: ${warning}`);
3
+ for (const error of result.errors) ctx.err(`error: ${error}`);
4
+ }
@@ -0,0 +1,5 @@
1
+ // The templates ship inside this package (the template folder, kept equal to its source by tools/sync-template.mjs),
2
+ // so an installed copy needs no other package to scaffold a plugin.
3
+ export async function loadTemplates() {
4
+ return import(new URL('../../template/src/index.mjs', import.meta.url).href);
5
+ }
@@ -0,0 +1 @@
1
+ export class UsageError extends Error {}
package/src/main.mjs ADDED
@@ -0,0 +1,61 @@
1
+ import own from '../package.json' with { type: 'json' };
2
+ import { create } from './commands/create.mjs';
3
+ import { dev } from './commands/dev.mjs';
4
+ import { doctor } from './commands/doctor.mjs';
5
+ import { publish } from './commands/publish.mjs';
6
+ import { test } from './commands/test.mjs';
7
+ import { validate } from './commands/validate.mjs';
8
+ import { CLI_NAME } from './lib/names.mjs';
9
+ import { UsageError } from './lib/usage.mjs';
10
+
11
+ const COMMANDS = { create, dev, test, validate, publish, doctor };
12
+ const SUMMARY = {
13
+ create: 'make a plugin from a template',
14
+ dev: 'load the plugin in the test host and reload on change',
15
+ test: 'run the unit tests and the slot suite of every claimed slot',
16
+ validate: 'check the manifest, the SDK range, the bundle scan and capability use',
17
+ publish: 'build the bundle twice and write the bundle folder and registry entry',
18
+ doctor: 'check this machine and the plugin in the folder',
19
+ };
20
+
21
+ export const usage = () =>
22
+ [
23
+ `usage: ${CLI_NAME} COMMAND [options]`,
24
+ '',
25
+ ...Object.keys(COMMANDS).map((name) => ` ${name.padEnd(9)}${SUMMARY[name]}`),
26
+ ].join('\n');
27
+
28
+ // Returns the exit code: 0 ok, 1 a check or an operation failed, 2 usage error.
29
+ export async function run(argv, overrides = {}) {
30
+ const ctx = {
31
+ cwd: process.cwd(),
32
+ out: (line) => process.stdout.write(`${line}\n`),
33
+ err: (line) => process.stderr.write(`${line}\n`),
34
+ ...overrides,
35
+ };
36
+ const [name, ...rest] = argv;
37
+ if (name === undefined) {
38
+ ctx.err(usage());
39
+ return 2;
40
+ }
41
+ if (name === 'help' || name === '--help' || name === '-h') {
42
+ ctx.out(usage());
43
+ return 0;
44
+ }
45
+ if (name === '--version' || name === '-v') {
46
+ ctx.out(own.version);
47
+ return 0;
48
+ }
49
+ if (!Object.hasOwn(COMMANDS, name)) {
50
+ ctx.err(`unknown command "${name}"`);
51
+ ctx.err(usage());
52
+ return 2;
53
+ }
54
+ try {
55
+ return await COMMANDS[name](rest, ctx);
56
+ } catch (error) {
57
+ const err = /** @type {{ message?: string, code?: string }} */ (error);
58
+ ctx.err(`${CLI_NAME} ${name}: ${err.message}`);
59
+ return error instanceof UsageError || String(err?.code).startsWith('ERR_PARSE_ARGS') ? 2 : 1;
60
+ }
61
+ }
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const TEMPLATES_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates');
6
+
7
+ export function templatesRoot() {
8
+ return TEMPLATES_ROOT;
9
+ }
10
+
11
+ export const COMMON = '_common';
12
+ export const PLACEHOLDERS = Object.freeze([
13
+ 'PLUGIN_NAME',
14
+ 'LICENSE',
15
+ 'SDK_PACKAGE',
16
+ 'SDK_RANGE',
17
+ 'CLI_PACKAGE',
18
+ 'CLI_RANGE',
19
+ 'CLI_NAME',
20
+ ]);
21
+
22
+ export function listTemplates() {
23
+ return fs
24
+ .readdirSync(TEMPLATES_ROOT, { withFileTypes: true })
25
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('_'))
26
+ .map((entry) => entry.name)
27
+ .sort();
28
+ }
29
+
30
+ // A template file ends in .tpl so lint and type checks of this repository skip it; gitignore gets its dot back
31
+ // (a package manager drops files named .gitignore from published packages).
32
+ export function outputName(relative) {
33
+ const parts = relative.split(path.sep).join('/').split('/');
34
+ let base = parts.pop() ?? '';
35
+ if (base.endsWith('.tpl')) base = base.slice(0, -4);
36
+ if (base === 'gitignore') base = '.gitignore';
37
+ return [...parts, base].join('/');
38
+ }
39
+
40
+ const filesOf = (dir) =>
41
+ fs.existsSync(dir)
42
+ ? fs
43
+ .readdirSync(dir, { recursive: true })
44
+ .map(String)
45
+ .filter((relative) => fs.statSync(path.join(dir, relative)).isFile())
46
+ .sort()
47
+ : [];
48
+
49
+ export function templateFiles(name) {
50
+ const known = listTemplates();
51
+ if (!known.includes(name)) throw new Error(`unknown template "${name}"; available: ${known.join(', ')}`);
52
+ const merged = new Map();
53
+ for (const folder of [COMMON, name]) {
54
+ for (const relative of filesOf(path.join(TEMPLATES_ROOT, folder))) {
55
+ merged.set(outputName(relative), fs.readFileSync(path.join(TEMPLATES_ROOT, folder, relative), 'utf8'));
56
+ }
57
+ }
58
+ return [...merged]
59
+ .map(([file, text]) => ({ path: file, text }))
60
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
61
+ }
62
+
63
+ export function renderTemplate(text, values) {
64
+ return text.replace(/__([A-Z][A-Z_]*[A-Z])__/g, (whole, key) => {
65
+ if (!PLACEHOLDERS.includes(key)) throw new Error(`unknown placeholder ${whole}`);
66
+ if (typeof values[key] !== 'string') throw new Error(`no value for placeholder ${whole}`);
67
+ return values[key];
68
+ });
69
+ }
@@ -0,0 +1,11 @@
1
+ # __PLUGIN_NAME__
2
+
3
+ A plugin made with `__CLI_NAME__ create`. `plugin.json` is the manifest and `src/index.ts` is the code.
4
+
5
+ - `npm test` runs the unit tests, then the slot suite of every slot this plugin claims.
6
+ - `npm run validate` checks the manifest, the SDK range, the bundle scan and capability use.
7
+ - `npm run dev` loads the plugin in the test host and reloads it when a file changes.
8
+ - `npm run build` writes `dist/NAME-VERSION/` with the bundle, the manifest and the registry entry.
9
+
10
+ Import only types from the SDK in plugin code (`import type`); the host passes the SDK in through `ctx`. Declare every
11
+ capability in `plugin.json`: `validate` fails on a capability the code uses but the manifest does not declare.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ dist/
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "__PLUGIN_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "license": "__LICENSE__",
7
+ "scripts": {
8
+ "dev": "__CLI_NAME__ dev",
9
+ "test": "__CLI_NAME__ test",
10
+ "validate": "__CLI_NAME__ validate",
11
+ "build": "__CLI_NAME__ publish"
12
+ },
13
+ "devDependencies": {
14
+ "@types/node": "26.6.11",
15
+ "__SDK_PACKAGE__": "__SDK_RANGE__",
16
+ "__CLI_PACKAGE__": "__CLI_RANGE__"
17
+ }
18
+ }
@@ -0,0 +1,15 @@
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import test from 'node:test';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+
7
+ const dir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
8
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'plugin.json'), 'utf8'));
9
+
10
+ test('the entry exports activate and every handler the manifest names', async () => {
11
+ const mod = await import(pathToFileURL(path.join(dir, manifest.entry)).href);
12
+ assert.equal(typeof mod.default?.activate, 'function');
13
+ const named = [...(manifest.routes ?? []), ...(manifest.webhooks ?? []), ...(manifest.jobs ?? [])].map((item) => item.handler);
14
+ for (const name of named) assert.equal(typeof mod.handlers?.[name], 'function', `handler ${name} is not exported`);
15
+ });
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2023",
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "allowImportingTsExtensions": true,
10
+ "erasableSyntaxOnly": true,
11
+ "verbatimModuleSyntax": true,
12
+ "types": ["node"]
13
+ },
14
+ "include": ["src", "test"]
15
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "manifest_version": 0,
3
+ "name": "__PLUGIN_NAME__",
4
+ "version": "0.1.0",
5
+ "license": "__LICENSE__",
6
+ "type": "example",
7
+ "sdk": "__SDK_RANGE__",
8
+ "entry": "src/index.ts",
9
+ "capabilities": ["events:emit"],
10
+ "events": { "emits": ["example.greeted"] },
11
+ "policies": [{ "resource": "example", "operations": ["read"] }],
12
+ "routes": [{ "method": "GET", "path": "/hello", "handler": "hello", "policy": "example:read" }]
13
+ }
@@ -0,0 +1,15 @@
1
+ import type { Handlers, PluginContext, PluginModule } from '__SDK_PACKAGE__';
2
+
3
+ export default {
4
+ async activate(_ctx: PluginContext) {},
5
+ async dispose() {},
6
+ } satisfies PluginModule;
7
+
8
+ export const handlers: Handlers = {
9
+ async hello(request, ctx) {
10
+ const asked = request?.query?.name;
11
+ const who = typeof asked === 'string' && asked !== '' ? asked : 'world';
12
+ await ctx.sdk.events.emit('example.greeted', { who });
13
+ return { status: 200, body: { greeting: `Hello, ${who}.` } };
14
+ },
15
+ };
@@ -0,0 +1,23 @@
1
+ import assert from 'node:assert/strict';
2
+ import path from 'node:path';
3
+ import test from 'node:test';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { createTestkitAdapter } from '__SDK_PACKAGE__/conformance';
6
+
7
+ const dir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
8
+
9
+ test('the hello route greets by name and emits one event', async () => {
10
+ const host = await createTestkitAdapter().create();
11
+ try {
12
+ const loaded = await host.load(dir);
13
+ assert.equal(loaded.state, 'active', loaded.errors.join('; '));
14
+ const answer = await host.callRoute('__PLUGIN_NAME__', { method: 'GET', path: '/hello', params: {}, query: { name: 'Ada' }, headers: {}, body: null });
15
+ assert.equal(answer.status, 200);
16
+ assert.deepEqual(answer.body, { greeting: 'Hello, Ada.' });
17
+ const event = (await host.emitted()).find((item) => item.name === 'example.greeted');
18
+ assert.deepEqual(event?.payload, { who: 'Ada' });
19
+ assert.equal((await host.audit()).filter((row) => row.outcome === 'denied').length, 0);
20
+ } finally {
21
+ await host.close();
22
+ }
23
+ });