@sixbell-telco/sdk-tools 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/CHANGELOG.md +32 -0
- package/README.md +277 -2
- package/data/security-floors.json +47 -0
- package/package.json +43 -4
- package/recipes/README.md +53 -0
- package/recipes/crud-list.md +21 -0
- package/recipes/custom-component.md +35 -0
- package/recipes/detail-page.md +19 -0
- package/recipes/form-dialog.md +17 -0
- package/recipes/parts/crud-list/i18n.json +83 -0
- package/recipes/parts/crud-list/src/app/features/__name__/__name__.routes.ts.tpl +30 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.html.tpl +102 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.spec.ts.tpl +101 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.ts.tpl +143 -0
- package/recipes/parts/detail-page/i18n.json +32 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.html.tpl +35 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.spec.ts.tpl +58 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.ts.tpl +68 -0
- package/recipes/parts/entity/i18n.json +5 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.model.ts.tpl +9 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.service.spec.ts.tpl +29 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.service.ts.tpl +33 -0
- package/recipes/parts/form-dialog/i18n.json +35 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.html.tpl +33 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.spec.ts.tpl +69 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.ts.tpl +73 -0
- package/src/add/add.mjs +251 -0
- package/src/check/config.mjs +112 -0
- package/src/check/exceptions.mjs +103 -0
- package/src/check/federation.mjs +224 -0
- package/src/check/finding.mjs +23 -0
- package/src/check/harness.mjs +146 -0
- package/src/check/i18n.mjs +218 -0
- package/src/check/integration.mjs +566 -0
- package/src/check/security.mjs +165 -0
- package/src/check/steps.mjs +37 -0
- package/src/check/styles.mjs +347 -0
- package/src/check/wiring.mjs +198 -0
- package/src/check.mjs +333 -0
- package/src/cli.mjs +551 -0
- package/src/docs/docs.mjs +154 -0
- package/src/doctor/doctor.mjs +492 -0
- package/src/format.mjs +102 -0
- package/src/info/info.mjs +149 -0
- package/src/init/init.mjs +490 -0
- package/src/init/merge.mjs +191 -0
- package/src/init/template.mjs +292 -0
- package/src/mcp/catalog.mjs +248 -0
- package/src/mcp/glossary.mjs +75 -0
- package/src/mcp/manifest.mjs +53 -0
- package/src/mcp/recipes.mjs +198 -0
- package/src/mcp/server.mjs +249 -0
- package/src/mcp/upgrade-guide.mjs +116 -0
- package/src/mcp/usage.mjs +48 -0
- package/src/project/project.mjs +220 -0
- package/src/types.d.ts +448 -0
- package/src/upgrade/lockstep.mjs +153 -0
- package/src/upgrade/upgrade.mjs +623 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds the MFE template repo `sdk-tools init` renders from. A template is named by its GitHub name and
|
|
3
|
+
* resolves, in order, to:
|
|
4
|
+
* 1. `--template <dir>` (a checkout of the template);
|
|
5
|
+
* 2. a local checkout whose origin remote is that repo, below `--template-root`, `SDK_TOOLS_TEMPLATE_ROOT`
|
|
6
|
+
* or, nearest first, the folders above the app (up to six, not above the home folder);
|
|
7
|
+
* 3. a partial clone of its default branch in the cache (`SDK_TOOLS_TEMPLATE_CACHE`, default
|
|
8
|
+
* ~/.cache/sdk-tools/templates), fetched from `SDK_TOOLS_TEMPLATE_REMOTE` or, by default, the host
|
|
9
|
+
* of the app's own origin remote (so an ssh host alias keeps working), else github.com over https.
|
|
10
|
+
* Nothing from the templates ships in this package: content and history come from the repo at run time.
|
|
11
|
+
*/
|
|
12
|
+
import { execFileSync } from 'node:child_process';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { delimiter, dirname, join, resolve, sep } from 'node:path';
|
|
17
|
+
|
|
18
|
+
/** @typedef {import('../types.js').InitRole} InitRole */
|
|
19
|
+
/** @typedef {import('../types.js').TemplateSource} TemplateSource */
|
|
20
|
+
|
|
21
|
+
/** @type {Record<InitRole, string>} */
|
|
22
|
+
const TEMPLATE_REPOS = {
|
|
23
|
+
host: 'EnghouseGlobal/nw-sx-starters-mfe-host-template',
|
|
24
|
+
child: 'EnghouseGlobal/nw-sx-starters-mfe-child-template',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const FALLBACK_REMOTE = 'https://github.com/{repo}.git';
|
|
28
|
+
const SKIP_DISCOVERY = new Set(['node_modules', 'dist', 'coverage', 'build', 'out', 'target', 'vendor']);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {string[]} args
|
|
32
|
+
* @param {string} [cwd]
|
|
33
|
+
* @returns {string}
|
|
34
|
+
*/
|
|
35
|
+
function git(args, cwd) {
|
|
36
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {string} dir A git checkout of its own (not a folder inside some other repo). */
|
|
40
|
+
const isCheckout = (dir) => existsSync(join(dir, '.git'));
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `org/repo`, lowercased, from an ssh, https or file remote URL.
|
|
44
|
+
* @param {string} url
|
|
45
|
+
* @returns {string | null}
|
|
46
|
+
*/
|
|
47
|
+
export function repoSlug(url) {
|
|
48
|
+
const match = /[/:]([^/:]+)\/([^/]+?)(?:\.git)?\/?$/.exec(String(url).trim());
|
|
49
|
+
return match ? `${match[1]}/${match[2]}`.toLowerCase() : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The clone URL template that reaches GitHub the way `originUrl` does: the same ssh host (or alias) or
|
|
54
|
+
* https host, with `{repo}` in place of the repo. Unknown shapes fall back to https.
|
|
55
|
+
* @param {string | undefined} originUrl
|
|
56
|
+
* @returns {string}
|
|
57
|
+
*/
|
|
58
|
+
export function defaultRemote(originUrl) {
|
|
59
|
+
const url = String(originUrl ?? '').trim();
|
|
60
|
+
const scp = /^([^@/\s]+@[^:/\s]+):[^/]+\/[^/]+$/.exec(url);
|
|
61
|
+
if (scp) return `${scp[1]}:{repo}.git`;
|
|
62
|
+
const full = /^((?:ssh|https?):\/\/[^/]+)\/[^/]+\/[^/]+$/.exec(url);
|
|
63
|
+
if (full) return `${full[1]}/{repo}.git`;
|
|
64
|
+
return FALLBACK_REMOTE;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The origin URL of the git checkout that holds `dir` (or its closest existing parent), if any.
|
|
69
|
+
* @param {string} dir
|
|
70
|
+
* @returns {string | undefined}
|
|
71
|
+
*/
|
|
72
|
+
function originOf(dir) {
|
|
73
|
+
let current = resolve(dir);
|
|
74
|
+
while (!existsSync(current) && dirname(current) !== current) current = dirname(current);
|
|
75
|
+
try {
|
|
76
|
+
return git(['config', '--get', 'remote.origin.url'], current).trim() || undefined;
|
|
77
|
+
} catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The origin URL of the checkout at `dir`: read from `.git/config` when `.git` is a folder (no git process
|
|
84
|
+
* per folder the search visits), else (a worktree or submodule) from git.
|
|
85
|
+
* @param {string} dir
|
|
86
|
+
* @returns {string | undefined}
|
|
87
|
+
*/
|
|
88
|
+
function checkoutOrigin(dir) {
|
|
89
|
+
try {
|
|
90
|
+
const config = readFileSync(join(dir, '.git', 'config'), 'utf8');
|
|
91
|
+
const section = /^\s*\[remote "origin"\]\s*$([\s\S]*?)(?=^\s*\[|(?![\s\S]))/m.exec(config)?.[1] ?? '';
|
|
92
|
+
return /^\s*url\s*=\s*(.+?)\s*$/m.exec(section)?.[1];
|
|
93
|
+
} catch {
|
|
94
|
+
try {
|
|
95
|
+
return git(['config', '--get', 'remote.origin.url'], dir).trim() || undefined;
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The first git checkout below `roots` (bounded depth, no hidden or build folders) whose origin is `repo`.
|
|
104
|
+
* Shallower checkouts win.
|
|
105
|
+
* @param {string} repo
|
|
106
|
+
* @param {string[]} roots
|
|
107
|
+
* @param {number} maxDepth
|
|
108
|
+
* @returns {string | undefined}
|
|
109
|
+
*/
|
|
110
|
+
function findLocalCheckout(repo, roots, maxDepth = 3) {
|
|
111
|
+
const want = repo.toLowerCase();
|
|
112
|
+
/** @type {string[]} */
|
|
113
|
+
const found = [];
|
|
114
|
+
/** @type {Set<string>} */
|
|
115
|
+
const seen = new Set();
|
|
116
|
+
/** @param {string} dir @param {number} depth */
|
|
117
|
+
const walk = (dir, depth) => {
|
|
118
|
+
if (seen.has(dir)) return;
|
|
119
|
+
seen.add(dir);
|
|
120
|
+
let entries;
|
|
121
|
+
try {
|
|
122
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
123
|
+
} catch {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (entries.some((e) => e.name === '.git')) {
|
|
127
|
+
const origin = checkoutOrigin(dir);
|
|
128
|
+
if (origin && repoSlug(origin) === want) found.push(dir);
|
|
129
|
+
}
|
|
130
|
+
if (depth >= maxDepth) return;
|
|
131
|
+
for (const e of entries) if (e.isDirectory() && !e.name.startsWith('.') && !SKIP_DISCOVERY.has(e.name)) walk(join(dir, e.name), depth + 1);
|
|
132
|
+
};
|
|
133
|
+
for (const root of roots) walk(resolve(root), 0);
|
|
134
|
+
return found.sort((a, b) => a.split(sep).length - b.split(sep).length || a.localeCompare(b))[0];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** How many folders above the app the default search climbs. */
|
|
138
|
+
const MAX_LEVELS_UP = 6;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Search roots for a local template checkout: the given ones, `SDK_TOOLS_TEMPLATE_ROOT`
|
|
142
|
+
* (path-delimited), else the folders above the app, nearest first: up to MAX_LEVELS_UP, never above
|
|
143
|
+
* the home folder (when the app is below it) and never the filesystem root.
|
|
144
|
+
* @param {string} target
|
|
145
|
+
* @param {string[]} roots
|
|
146
|
+
* @returns {{ roots: string[], climb: boolean }} climb: the roots are the app's ancestors, so the nearest one with a checkout wins
|
|
147
|
+
*/
|
|
148
|
+
function searchRoots(target, roots) {
|
|
149
|
+
if (roots.length) return { roots, climb: false };
|
|
150
|
+
const fromEnv = (process.env.SDK_TOOLS_TEMPLATE_ROOT ?? '').split(delimiter).filter(Boolean);
|
|
151
|
+
if (fromEnv.length) return { roots: fromEnv, climb: false };
|
|
152
|
+
const home = resolve(homedir());
|
|
153
|
+
const start = resolve(target);
|
|
154
|
+
const belowHome = start.startsWith(home + sep);
|
|
155
|
+
const up = [];
|
|
156
|
+
let current = start;
|
|
157
|
+
for (let i = 0; i < MAX_LEVELS_UP; i++) {
|
|
158
|
+
const parent = dirname(current);
|
|
159
|
+
if (parent === current || dirname(parent) === parent) break;
|
|
160
|
+
current = parent;
|
|
161
|
+
up.push(current);
|
|
162
|
+
if (belowHome && current === home) break;
|
|
163
|
+
}
|
|
164
|
+
return { roots: up, climb: true };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Clones (or refreshes) the repo's default branch in the cache. The clone is partial (`blob:none`): it has
|
|
169
|
+
* the full commit history, which init reads to recognize older template copies, but downloads file
|
|
170
|
+
* contents only for the checked-out commit.
|
|
171
|
+
* @param {string} repo
|
|
172
|
+
* @param {{ cacheRoot: string, remote: string }} options
|
|
173
|
+
* @returns {string}
|
|
174
|
+
*/
|
|
175
|
+
function fetchToCache(repo, { cacheRoot, remote }) {
|
|
176
|
+
const dir = join(cacheRoot, repo);
|
|
177
|
+
const url = remote.replaceAll('{repo}', repo);
|
|
178
|
+
if (existsSync(join(dir, '.git'))) {
|
|
179
|
+
git(['-C', dir, 'remote', 'set-url', 'origin', url]);
|
|
180
|
+
git(['-C', dir, 'fetch', '--quiet', '--filter=blob:none', 'origin', 'HEAD']);
|
|
181
|
+
git(['-C', dir, 'reset', '--quiet', '--hard', 'FETCH_HEAD']);
|
|
182
|
+
} else {
|
|
183
|
+
rmSync(dir, { recursive: true, force: true });
|
|
184
|
+
mkdirSync(dirname(dir), { recursive: true });
|
|
185
|
+
git(['clone', '--quiet', '--filter=blob:none', url, dir]);
|
|
186
|
+
}
|
|
187
|
+
return dir;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Resolves the template for `role`, or throws with every place it looked.
|
|
192
|
+
* @param {InitRole} role
|
|
193
|
+
* @param {{ target: string, templateDir?: string, roots?: string[], offline?: boolean }} options
|
|
194
|
+
* @returns {TemplateSource}
|
|
195
|
+
*/
|
|
196
|
+
export function resolveTemplate(role, { target, templateDir, roots = [], offline = false }) {
|
|
197
|
+
const repo = TEMPLATE_REPOS[role];
|
|
198
|
+
const describe = (/** @type {'path' | 'local' | 'cache'} */ source, /** @type {string} */ path) => {
|
|
199
|
+
const commit = isCheckout(path) ? git(['rev-parse', 'HEAD'], path).trim() : null;
|
|
200
|
+
return { repo, source, path, commit };
|
|
201
|
+
};
|
|
202
|
+
if (templateDir) {
|
|
203
|
+
const dir = resolve(templateDir);
|
|
204
|
+
if (!existsSync(join(dir, 'package.json'))) throw new Error(`--template ${templateDir} has no package.json; point it at a checkout of ${repo}`);
|
|
205
|
+
return describe('path', dir);
|
|
206
|
+
}
|
|
207
|
+
const { roots: searched, climb } = searchRoots(target, roots);
|
|
208
|
+
let local;
|
|
209
|
+
if (climb) {
|
|
210
|
+
// One ancestor at a time, nearest first, so a checkout beside the app wins over one further up.
|
|
211
|
+
for (const root of searched) if ((local = findLocalCheckout(repo, [root]))) break;
|
|
212
|
+
} else local = findLocalCheckout(repo, searched);
|
|
213
|
+
if (local) return describe('local', local);
|
|
214
|
+
if (offline)
|
|
215
|
+
throw new Error(
|
|
216
|
+
`no local checkout of ${repo} below ${searched.join(', ')} (--offline). Pass --template <dir>, or --template-root <dir> (or set SDK_TOOLS_TEMPLATE_ROOT) to the folder that holds the checkout.`,
|
|
217
|
+
);
|
|
218
|
+
const cacheRoot = process.env.SDK_TOOLS_TEMPLATE_CACHE ?? join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'sdk-tools', 'templates');
|
|
219
|
+
const remote = process.env.SDK_TOOLS_TEMPLATE_REMOTE ?? defaultRemote(originOf(target));
|
|
220
|
+
try {
|
|
221
|
+
return describe('cache', fetchToCache(repo, { cacheRoot, remote }));
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const detail = /** @type {{ stderr?: string, message?: string }} */ (error);
|
|
224
|
+
throw new Error(
|
|
225
|
+
`could not find ${repo}: no local checkout below ${searched.join(', ')} and the clone from ${remote.replaceAll('{repo}', repo)} failed (${String(
|
|
226
|
+
detail.stderr || detail.message,
|
|
227
|
+
)
|
|
228
|
+
.trim()
|
|
229
|
+
.split('\n')
|
|
230
|
+
.pop()}). Pass --template <dir>, --template-root <dir> (or SDK_TOOLS_TEMPLATE_ROOT) to the folder that holds a checkout, or set SDK_TOOLS_TEMPLATE_REMOTE.`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The files of the template: tracked files of a checkout, or every file below a plain folder.
|
|
237
|
+
* @param {string} dir
|
|
238
|
+
* @returns {string[]} repo-relative posix paths, sorted
|
|
239
|
+
*/
|
|
240
|
+
export function templateFiles(dir) {
|
|
241
|
+
if (isCheckout(dir)) return git(['ls-files', '-z'], dir).split('\0').filter(Boolean).sort();
|
|
242
|
+
{
|
|
243
|
+
/** @type {string[]} */
|
|
244
|
+
const out = [];
|
|
245
|
+
/** @param {string} sub */
|
|
246
|
+
const walk = (sub) => {
|
|
247
|
+
for (const e of readdirSync(join(dir, sub), { withFileTypes: true })) {
|
|
248
|
+
const rel = sub ? `${sub}/${e.name}` : e.name;
|
|
249
|
+
if (e.isDirectory()) {
|
|
250
|
+
if (!['.git', 'node_modules'].includes(e.name)) walk(rel);
|
|
251
|
+
} else if (e.isFile()) out.push(rel);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
walk('');
|
|
255
|
+
return out.sort();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Every blob id each path has had in the template's history, so init can tell an untouched older copy
|
|
261
|
+
* of a template file from a product edit. Empty when the template has no history.
|
|
262
|
+
* @param {string} dir
|
|
263
|
+
* @returns {Map<string, Set<string>>}
|
|
264
|
+
*/
|
|
265
|
+
export function templateHistory(dir) {
|
|
266
|
+
/** @type {Map<string, Set<string>>} */
|
|
267
|
+
const history = new Map();
|
|
268
|
+
if (!isCheckout(dir)) return history;
|
|
269
|
+
let log = '';
|
|
270
|
+
try {
|
|
271
|
+
log = git(['log', '--format=', '--raw', '--no-abbrev', '--no-renames', 'HEAD'], dir);
|
|
272
|
+
} catch {
|
|
273
|
+
return history;
|
|
274
|
+
}
|
|
275
|
+
for (const line of log.split('\n')) {
|
|
276
|
+
const match = /^:\d+ \d+ ([0-9a-f]{40}) ([0-9a-f]{40}) \w+\t(.+)$/.exec(line);
|
|
277
|
+
if (!match) continue;
|
|
278
|
+
const set = history.get(match[3]) ?? new Set();
|
|
279
|
+
for (const blob of [match[1], match[2]]) if (!/^0+$/.test(blob)) set.add(blob);
|
|
280
|
+
history.set(match[3], set);
|
|
281
|
+
}
|
|
282
|
+
return history;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The git blob id of `content`, as `git hash-object` computes it.
|
|
287
|
+
* @param {Buffer} content
|
|
288
|
+
* @returns {string}
|
|
289
|
+
*/
|
|
290
|
+
export function blobId(content) {
|
|
291
|
+
return createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex');
|
|
292
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Answers about the kit from the installed manifest: the component list, search, one component's
|
|
3
|
+
* API and the theme tokens. Pure functions of the manifest, so the MCP tools and tests share them.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {import('../../../eslint-plugin-sdk/src/types.js').Manifest} Manifest
|
|
8
|
+
* @typedef {import('../../../eslint-plugin-sdk/src/types.js').ManifestDeclaration} ManifestDeclaration
|
|
9
|
+
* @typedef {import('../types.js').ComponentSummary} ComponentSummary
|
|
10
|
+
* @typedef {import('../types.js').ComponentDetail} ComponentDetail
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Storybook of the kit (private GitHub Pages); a story id opens at `?path=/story/<id>`. */
|
|
14
|
+
const STORYBOOK_URL = 'https://fantastic-broccoli-8lj2gke.pages.github.io/';
|
|
15
|
+
|
|
16
|
+
/** A lookup that fails with the closest names, so the caller can retry. */
|
|
17
|
+
export class NotFoundError extends Error {}
|
|
18
|
+
|
|
19
|
+
/** @param {string | undefined} text */
|
|
20
|
+
const firstSentence = (text) => (text ? (/^[\s\S]*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text).trim() : undefined);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Edit distance, for typo suggestions.
|
|
24
|
+
* @param {string} a
|
|
25
|
+
* @param {string} b
|
|
26
|
+
*/
|
|
27
|
+
function distance(a, b) {
|
|
28
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
29
|
+
for (let i = 1; i <= a.length; i++) {
|
|
30
|
+
let previous = row[0];
|
|
31
|
+
row[0] = i;
|
|
32
|
+
for (let j = 1; j <= b.length; j++) {
|
|
33
|
+
const current = row[j];
|
|
34
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
35
|
+
previous = current;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return row[b.length];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {ManifestDeclaration} d */
|
|
42
|
+
const tag = (d) => d.selector ?? d.pipe ?? d.name;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {ManifestDeclaration} d
|
|
46
|
+
* @returns {ComponentSummary}
|
|
47
|
+
*/
|
|
48
|
+
function summary(d) {
|
|
49
|
+
return {
|
|
50
|
+
selector: tag(d),
|
|
51
|
+
name: d.name,
|
|
52
|
+
kind: d.kind,
|
|
53
|
+
entryPoint: d.entryPoint,
|
|
54
|
+
...(d.description ? { description: firstSentence(d.description) } : {}),
|
|
55
|
+
...(d.deprecated ? { deprecated: d.deprecated } : {}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Every declaration of the manifest, optionally of one kind.
|
|
61
|
+
* @param {Manifest} manifest
|
|
62
|
+
* @param {{ kind?: 'component' | 'directive' | 'pipe' }} [options]
|
|
63
|
+
*/
|
|
64
|
+
export function listComponents(manifest, { kind } = {}) {
|
|
65
|
+
const items = manifest.declarations.filter((d) => !kind || d.kind === kind).map(summary);
|
|
66
|
+
return { sdkVersion: manifest.version, count: items.length, components: items };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @param {string} text */
|
|
70
|
+
const words = (text) =>
|
|
71
|
+
text
|
|
72
|
+
.toLowerCase()
|
|
73
|
+
.split(/[^a-z0-9]+/)
|
|
74
|
+
.filter(Boolean);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Declarations ranked by how well they match the query words (selector and name first, then entry
|
|
78
|
+
* point, description and input names).
|
|
79
|
+
* @param {Manifest} manifest
|
|
80
|
+
* @param {string} query
|
|
81
|
+
* @param {{ limit?: number }} [options]
|
|
82
|
+
*/
|
|
83
|
+
export function searchComponents(manifest, query, { limit = 10 } = {}) {
|
|
84
|
+
// "st" (the selector prefix) and "component" match every entry, so they do not rank anything.
|
|
85
|
+
const wanted = words(query)
|
|
86
|
+
.filter((w) => !['st', 'component', 'components'].includes(w))
|
|
87
|
+
.map((w) => w.replace(/s$/, ''));
|
|
88
|
+
const scored = manifest.declarations
|
|
89
|
+
.map((d) => {
|
|
90
|
+
const fields = [
|
|
91
|
+
[words(`${tag(d)} ${d.name.replace(/([a-z])([A-Z])/g, '$1 $2')}`), 5],
|
|
92
|
+
[words(d.entryPoint), 3],
|
|
93
|
+
[words(d.description ?? ''), 1],
|
|
94
|
+
[(d.inputs ?? []).flatMap((i) => words(i.name.replace(/([a-z])([A-Z])/g, '$1 $2'))), 1],
|
|
95
|
+
];
|
|
96
|
+
let score = 0;
|
|
97
|
+
for (const w of wanted) {
|
|
98
|
+
for (const [list, weight] of /** @type {[string[], number][]} */ (fields)) {
|
|
99
|
+
if (list.some((x) => x === w || x.replace(/s$/, '') === w)) score += weight;
|
|
100
|
+
else if (w.length > 3 && list.some((x) => x.startsWith(w))) score += weight / 2;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { d, score: d.deprecated ? score / 2 : score };
|
|
104
|
+
})
|
|
105
|
+
.filter((x) => x.score > 0)
|
|
106
|
+
.sort((a, b) => b.score - a.score || tag(a.d).localeCompare(tag(b.d)));
|
|
107
|
+
return { query, sdkVersion: manifest.version, results: scored.slice(0, limit).map((x) => summary(x.d)) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Finds a declaration by selector (`st-dialog`, `<st-dialog>`, `dialog`), attribute selector
|
|
112
|
+
* (`stTextColor`), pipe name or class name (`DialogComponent`).
|
|
113
|
+
* @param {Manifest} manifest
|
|
114
|
+
* @param {string} query
|
|
115
|
+
* @returns {ManifestDeclaration}
|
|
116
|
+
*/
|
|
117
|
+
function findDeclaration(manifest, query) {
|
|
118
|
+
const q = query
|
|
119
|
+
.trim()
|
|
120
|
+
.replace(/^<|\/?>$/g, '')
|
|
121
|
+
.trim();
|
|
122
|
+
const lower = q.toLowerCase();
|
|
123
|
+
/** @param {ManifestDeclaration} d */
|
|
124
|
+
const selectors = (d) => (d.selector ?? '').split(',').map((s) => s.trim().toLowerCase());
|
|
125
|
+
/** @type {((d: ManifestDeclaration) => boolean)[]} */
|
|
126
|
+
const tests = [
|
|
127
|
+
(d) => selectors(d).includes(lower),
|
|
128
|
+
(d) => d.name.toLowerCase() === lower || d.pipe?.toLowerCase() === lower,
|
|
129
|
+
(d) => selectors(d).includes(`st-${lower}`),
|
|
130
|
+
(d) => selectors(d).some((s) => s.replace(/^[a-z-]*\[|\]$/g, '') === lower),
|
|
131
|
+
(d) => d.name.toLowerCase() === `${lower.replace(/^st-/, '').replace(/-/g, '')}component`,
|
|
132
|
+
];
|
|
133
|
+
for (const test of tests) {
|
|
134
|
+
const found = manifest.declarations.find(test);
|
|
135
|
+
if (found) return found;
|
|
136
|
+
}
|
|
137
|
+
const typos = manifest.declarations
|
|
138
|
+
.map((d) => ({ name: tag(d), distance: distance(lower, tag(d).toLowerCase()) }))
|
|
139
|
+
.filter((x) => x.distance <= 3)
|
|
140
|
+
.sort((a, b) => a.distance - b.distance)
|
|
141
|
+
.map((x) => x.name);
|
|
142
|
+
const close = [...new Set([...typos, ...searchComponents(manifest, q, { limit: 5 }).results.map((r) => r.selector)])].slice(0, 5);
|
|
143
|
+
throw new NotFoundError(
|
|
144
|
+
`no component "${query}" in @sixbell-telco/sdk ${manifest.version}.${close.length ? ` Closest: ${close.join(', ')}.` : ''} Call search_components to find one.`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* A starting template for a declaration: the element with its required inputs and its slot
|
|
150
|
+
* elements, so an agent does not invent the structure.
|
|
151
|
+
* @param {ManifestDeclaration} d
|
|
152
|
+
*/
|
|
153
|
+
function exampleTemplate(d) {
|
|
154
|
+
if (d.kind === 'pipe') return `{{ value | ${d.pipe} }}`;
|
|
155
|
+
const selector = (d.selector ?? '').split(',')[0].trim();
|
|
156
|
+
const required = (d.inputs ?? []).filter((i) => i.required);
|
|
157
|
+
const bindings = required.map((i) => (i.values?.length ? ` ${i.name}="${i.values[0]}"` : ` [${i.name}]="${i.name}"`)).join('');
|
|
158
|
+
const element = /^[a-z][\w-]*$/.exec(selector)?.[0];
|
|
159
|
+
if (!element) {
|
|
160
|
+
const attribute = /\[([\w-]+)\]/.exec(selector)?.[1];
|
|
161
|
+
const host = /^([a-z][\w-]*)\[/.exec(selector)?.[1] ?? 'div';
|
|
162
|
+
return attribute ? `<${host} ${attribute}${bindings}></${host}>` : '';
|
|
163
|
+
}
|
|
164
|
+
const children = (d.slots ?? [])
|
|
165
|
+
.map((s) => s.select)
|
|
166
|
+
.filter((s) => /^[a-z][\w-]*$/.test(s))
|
|
167
|
+
.map((s) => ` <${s}>…</${s}>`);
|
|
168
|
+
return children.length ? `<${element}${bindings}>\n${children.join('\n')}\n</${element}>` : `<${element}${bindings}>…</${element}>`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* One declaration's full API from the installed manifest, with an import line, a starting
|
|
173
|
+
* template, the related declarations of its entry point, story links and the usage rules.
|
|
174
|
+
* @param {Manifest} manifest
|
|
175
|
+
* @param {string} query
|
|
176
|
+
* @returns {ComponentDetail}
|
|
177
|
+
*/
|
|
178
|
+
export function getComponent(manifest, query) {
|
|
179
|
+
const d = findDeclaration(manifest, query);
|
|
180
|
+
const related = manifest.declarations.filter((x) => x.entryPoint === d.entryPoint && x !== d).map((x) => tag(x));
|
|
181
|
+
const restricted = (d.inputs ?? []).filter((i) => i.values?.length).map((i) => i.name);
|
|
182
|
+
return {
|
|
183
|
+
sdkVersion: manifest.version,
|
|
184
|
+
selector: tag(d),
|
|
185
|
+
name: d.name,
|
|
186
|
+
kind: d.kind,
|
|
187
|
+
entryPoint: d.entryPoint,
|
|
188
|
+
import: `import { ${d.name} } from '${d.entryPoint}';`,
|
|
189
|
+
...(d.description ? { description: d.description } : {}),
|
|
190
|
+
...(d.deprecated ? { deprecated: d.deprecated } : {}),
|
|
191
|
+
inputs: (d.inputs ?? []).map((i) => ({
|
|
192
|
+
name: i.name,
|
|
193
|
+
type: i.type,
|
|
194
|
+
...(i.values?.length ? { values: i.values } : {}),
|
|
195
|
+
...(i.default !== undefined ? { default: i.default } : {}),
|
|
196
|
+
...(i.required ? { required: true } : {}),
|
|
197
|
+
...(i.twoWay ? { twoWay: true } : {}),
|
|
198
|
+
...(i.bareAttribute ? { bareAttribute: true } : {}),
|
|
199
|
+
...(i.deprecated ? { deprecated: i.deprecated } : {}),
|
|
200
|
+
...(i.description ? { description: i.description } : {}),
|
|
201
|
+
})),
|
|
202
|
+
outputs: (d.outputs ?? []).map((o) => ({
|
|
203
|
+
name: o.name,
|
|
204
|
+
type: o.type,
|
|
205
|
+
...(o.deprecated ? { deprecated: o.deprecated } : {}),
|
|
206
|
+
...(o.description ? { description: o.description } : {}),
|
|
207
|
+
})),
|
|
208
|
+
slots: (d.slots ?? []).map((s) => s.select),
|
|
209
|
+
related,
|
|
210
|
+
example: exampleTemplate(d),
|
|
211
|
+
stories: (d.stories ?? []).map((id) => ({ id, url: `${STORYBOOK_URL}?path=/story/${id}` })),
|
|
212
|
+
do: [
|
|
213
|
+
`Import ${d.name} from '${d.entryPoint}' (never from '@sixbell-telco/sdk') and add it to the component's imports.`,
|
|
214
|
+
...(restricted.length ? [`Give ${restricted.join(', ')} only one of the listed values.`] : []),
|
|
215
|
+
'Put only layout and spacing classes (flex, grid, gap-*, p-*, m-*, w-*) on the element.',
|
|
216
|
+
'Run check_usage on the template before you finish.',
|
|
217
|
+
],
|
|
218
|
+
dont: [
|
|
219
|
+
'Do not invent inputs, outputs or values that are not listed here.',
|
|
220
|
+
'Do not restyle it with color, typography, border or shadow classes, or with style="…".',
|
|
221
|
+
'Do not use raw palette colors (bg-red-500), hex values or arbitrary values (p-[13px]).',
|
|
222
|
+
],
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The theme tokens, by group, with their Tailwind utilities and the deprecated aliases.
|
|
228
|
+
* @param {Manifest} manifest
|
|
229
|
+
* @param {{ group?: string }} [options]
|
|
230
|
+
*/
|
|
231
|
+
export function getTokens(manifest, { group } = {}) {
|
|
232
|
+
const groups = [...new Set(manifest.tokens.map((t) => t.group))];
|
|
233
|
+
if (group && !groups.includes(group)) throw new NotFoundError(`no token group "${group}". Groups: ${groups.join(', ')}.`);
|
|
234
|
+
const selected = manifest.tokens.filter((t) => !group || t.group === group);
|
|
235
|
+
/** @type {Record<string, string[]>} */
|
|
236
|
+
const byGroup = {};
|
|
237
|
+
for (const t of selected.filter((x) => !x.deprecated)) (byGroup[t.group] ??= []).push(t.utility ?? t.suffix);
|
|
238
|
+
return {
|
|
239
|
+
sdkVersion: manifest.version,
|
|
240
|
+
...(byGroup.color
|
|
241
|
+
? {
|
|
242
|
+
colorUsage: `Color tokens go after a color utility prefix: ${(manifest.colorUtilities ?? ['bg', 'text', 'border']).join(', ')}. Example: bg-base-200 text-base-content border-base-300. Status text uses the -strong tokens (text-error-strong).`,
|
|
243
|
+
}
|
|
244
|
+
: {}),
|
|
245
|
+
groups: byGroup,
|
|
246
|
+
deprecated: selected.filter((t) => t.deprecated).map((t) => ({ token: t.name, replacement: t.deprecated?.replacement })),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The kit glossary: `GLOSSARY.md` in the SDK installed in the app (the manifest's `glossary` field
|
|
3
|
+
* names it), so its terms match the kit version the app uses. One line per term:
|
|
4
|
+
* `- **term**: definition. Example: example. Not: synonym, synonym.`
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { NotFoundError } from './catalog.mjs';
|
|
9
|
+
import { loadManifest } from './manifest.mjs';
|
|
10
|
+
|
|
11
|
+
/** @typedef {{ term: string, definition: string, example: string, not: string[] }} GlossaryEntry One term; `not` holds the words not to use for it. */
|
|
12
|
+
|
|
13
|
+
/** The SDK version that first ships GLOSSARY.md. */
|
|
14
|
+
const FIRST_VERSION = '4.6.0';
|
|
15
|
+
const LINE = /^- \*\*([^*]+)\*\*: (.+?) Example: (.+?) Not: (.+?)\.$/;
|
|
16
|
+
|
|
17
|
+
/** The installed SDK has no glossary (older than 4.6.0); reported as a one-line message. */
|
|
18
|
+
export class GlossaryError extends Error {}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The terms of a glossary, in file order. Every `- **` line must follow the one-line format.
|
|
22
|
+
* @param {string} text
|
|
23
|
+
* @returns {GlossaryEntry[]}
|
|
24
|
+
*/
|
|
25
|
+
export function parseGlossary(text) {
|
|
26
|
+
return text
|
|
27
|
+
.replace(/\r\n/g, '\n')
|
|
28
|
+
.split('\n')
|
|
29
|
+
.filter((line) => line.startsWith('- **'))
|
|
30
|
+
.map((line) => {
|
|
31
|
+
const match = LINE.exec(line);
|
|
32
|
+
if (!match) throw new Error(`GLOSSARY.md: "${line.slice(0, 60)}..." is not "- **term**: definition. Example: ... Not: a, b."`);
|
|
33
|
+
return {
|
|
34
|
+
term: match[1],
|
|
35
|
+
definition: match[2],
|
|
36
|
+
example: match[3],
|
|
37
|
+
not: match[4].split(', ').map((s) => s.trim()),
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The glossary of the installed SDK (or of the SDK next to `manifestPath`).
|
|
44
|
+
* @param {{ cwd: string, manifestPath?: string }} options
|
|
45
|
+
* @returns {{ path: string, version: string, text: string, entries: GlossaryEntry[] }}
|
|
46
|
+
*/
|
|
47
|
+
export function loadGlossary({ cwd, manifestPath }) {
|
|
48
|
+
const { path: manifestFile, manifest } = loadManifest({ cwd, manifestPath });
|
|
49
|
+
const named = /** @type {{ glossary?: unknown }} */ (manifest).glossary;
|
|
50
|
+
const path = join(dirname(manifestFile), typeof named === 'string' ? named : 'GLOSSARY.md');
|
|
51
|
+
if (!existsSync(path))
|
|
52
|
+
throw new GlossaryError(
|
|
53
|
+
`@sixbell-telco/sdk ${manifest.version} ships no GLOSSARY.md (SDK ${FIRST_VERSION} or later ships it). Fix: npm install @sixbell-telco/sdk@latest, then restart the MCP server.`,
|
|
54
|
+
);
|
|
55
|
+
const text = readFileSync(path, 'utf8');
|
|
56
|
+
return { path, version: manifest.version, text, entries: parseGlossary(text) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* One term, by its name or by a word its "Not" list rejects (then `use` names the term to say).
|
|
61
|
+
* @param {GlossaryEntry[]} entries
|
|
62
|
+
* @param {string} query
|
|
63
|
+
* @returns {GlossaryEntry & { use?: string }}
|
|
64
|
+
*/
|
|
65
|
+
export function findTerm(entries, query) {
|
|
66
|
+
const wanted = query.trim().toLowerCase();
|
|
67
|
+
const exact = entries.find((e) => e.term.toLowerCase() === wanted);
|
|
68
|
+
if (exact) return exact;
|
|
69
|
+
const rejected = entries.find((e) => e.not.some((word) => word.toLowerCase() === wanted));
|
|
70
|
+
if (rejected) return { ...rejected, use: `"${query.trim()}" is not a kit term: say "${rejected.term}".` };
|
|
71
|
+
const near = entries.filter((e) => e.term.toLowerCase().includes(wanted) || wanted.includes(e.term.toLowerCase())).map((e) => e.term);
|
|
72
|
+
throw new NotFoundError(
|
|
73
|
+
`no glossary term "${query}".${near.length ? ` Close: ${near.join(', ')}.` : ''} Call get_glossary with no term for all ${entries.length} terms.`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manifest the MCP tools answer from: `@sixbell-telco/sdk/manifest.json` of the SDK installed
|
|
3
|
+
* in the app (resolved from the app's folder), so every answer matches the version the app uses.
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { join, resolve } from 'node:path';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {import('../../../eslint-plugin-sdk/src/types.js').Manifest} Manifest
|
|
11
|
+
* @typedef {import('../types.js').LoadedManifest} LoadedManifest
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Resolved from the app at run time (the app's SDK, not a dependency of this package). */
|
|
15
|
+
const SDK = '@sixbell-telco/sdk';
|
|
16
|
+
|
|
17
|
+
/** A problem the user fixes in the app (install or upgrade the SDK), reported without a stack. */
|
|
18
|
+
export class ManifestError extends Error {}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The installed manifest, or the one at `manifestPath`. Throws ManifestError naming the fix when
|
|
22
|
+
* the SDK is missing or too old to ship a manifest.
|
|
23
|
+
* @param {{ cwd: string, manifestPath?: string }} options
|
|
24
|
+
* @returns {LoadedManifest}
|
|
25
|
+
*/
|
|
26
|
+
export function loadManifest({ cwd, manifestPath }) {
|
|
27
|
+
if (manifestPath) {
|
|
28
|
+
const path = resolve(cwd, manifestPath);
|
|
29
|
+
try {
|
|
30
|
+
return { path, manifest: JSON.parse(readFileSync(path, 'utf8')) };
|
|
31
|
+
} catch (thrown) {
|
|
32
|
+
throw new ManifestError(`cannot read the manifest ${path} (${thrown instanceof Error ? thrown.message : thrown}). Fix the --manifest path.`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const require = createRequire(join(cwd, 'noop.js'));
|
|
36
|
+
let path;
|
|
37
|
+
try {
|
|
38
|
+
path = require.resolve(`${SDK}/manifest.json`);
|
|
39
|
+
} catch {
|
|
40
|
+
let version = null;
|
|
41
|
+
try {
|
|
42
|
+
version = JSON.parse(readFileSync(require.resolve(`${SDK}/package.json`), 'utf8')).version;
|
|
43
|
+
} catch {
|
|
44
|
+
// not installed
|
|
45
|
+
}
|
|
46
|
+
throw new ManifestError(
|
|
47
|
+
version
|
|
48
|
+
? `@sixbell-telco/sdk ${version} is installed in ${cwd} but ships no manifest.json (SDK 4.6.0 or later ships it). Fix: npm install @sixbell-telco/sdk@latest, then restart the MCP server.`
|
|
49
|
+
: `@sixbell-telco/sdk is not installed in ${cwd}. Fix: start the MCP server from the app's folder (the one with package.json and node_modules), or run npm install @sixbell-telco/sdk there, then restart the server.`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return { path, manifest: JSON.parse(readFileSync(path, 'utf8')) };
|
|
53
|
+
}
|