@cagov/ca-ds 1.0.0 → 1.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.
Files changed (101) hide show
  1. package/README.md +4 -2
  2. package/THIRD-PARTY-LICENSES.txt +690 -0
  3. package/ca-ds.js +48337 -0
  4. package/package.json +5 -31
  5. package/bin/ca-ds.js +0 -5
  6. package/src/cli/add.js +0 -134
  7. package/src/cli/build.js +0 -15
  8. package/src/cli/diff.js +0 -39
  9. package/src/cli/eject.js +0 -112
  10. package/src/cli/exit.js +0 -22
  11. package/src/cli/format.js +0 -52
  12. package/src/cli/init.js +0 -148
  13. package/src/cli/install.js +0 -178
  14. package/src/cli/items.js +0 -10
  15. package/src/cli/login.js +0 -331
  16. package/src/cli/main.js +0 -108
  17. package/src/cli/new.js +0 -230
  18. package/src/cli/outdated.js +0 -74
  19. package/src/cli/pack.js +0 -75
  20. package/src/cli/preview.js +0 -31
  21. package/src/cli/publish.js +0 -295
  22. package/src/cli/pull.js +0 -208
  23. package/src/cli/remote.js +0 -52
  24. package/src/cli/remove.js +0 -69
  25. package/src/cli/update.js +0 -223
  26. package/src/cli/validate.js +0 -131
  27. package/src/lib/browser.js +0 -12
  28. package/src/lib/build.js +0 -249
  29. package/src/lib/bundle.js +0 -148
  30. package/src/lib/catalog.js +0 -44
  31. package/src/lib/checks.js +0 -31
  32. package/src/lib/collection.js +0 -65
  33. package/src/lib/emblem.js +0 -29
  34. package/src/lib/fixtures.js +0 -59
  35. package/src/lib/floor.js +0 -79
  36. package/src/lib/glyph.js +0 -148
  37. package/src/lib/image.js +0 -138
  38. package/src/lib/json-text.js +0 -213
  39. package/src/lib/keys.js +0 -322
  40. package/src/lib/links.js +0 -321
  41. package/src/lib/markdown.js +0 -408
  42. package/src/lib/merge.js +0 -93
  43. package/src/lib/pack.js +0 -30
  44. package/src/lib/page-schema.js +0 -368
  45. package/src/lib/page.js +0 -372
  46. package/src/lib/patch.js +0 -9
  47. package/src/lib/regions.js +0 -173
  48. package/src/lib/registry.js +0 -371
  49. package/src/lib/release.js +0 -119
  50. package/src/lib/repoints.js +0 -120
  51. package/src/lib/resolve.js +0 -32
  52. package/src/lib/schema.js +0 -28
  53. package/src/lib/serial.js +0 -4
  54. package/src/lib/serialize.js +0 -444
  55. package/src/lib/structured.js +0 -72
  56. package/src/lib/system.js +0 -13
  57. package/src/lib/targets.js +0 -85
  58. package/src/lib/terms.js +0 -11
  59. package/src/lib/token-view.js +0 -289
  60. package/src/lib/tokens.js +0 -247
  61. package/src/lib/version.js +0 -34
  62. package/src/preview/frame.js +0 -75
  63. package/src/preview/pages.js +0 -128
  64. package/src/preview/screenshots.js +0 -72
  65. package/src/preview/server.js +0 -378
  66. package/src/preview/shell.js +0 -153
  67. package/src/schema/a11y.schema.json +0 -56
  68. package/src/schema/collection.lock.schema.json +0 -58
  69. package/src/schema/collection.schema.json +0 -65
  70. package/src/schema/composition.schema.json +0 -98
  71. package/src/schema/contract.schema.json +0 -116
  72. package/src/schema/interface.schema.json +0 -257
  73. package/src/schema/item.schema.json +0 -362
  74. package/src/schema/release.schema.json +0 -39
  75. package/src/schema/system.schema.json +0 -75
  76. package/src/schema/variants.schema.json +0 -60
  77. package/src/validate/collection.js +0 -19
  78. package/src/validate/collisions.js +0 -124
  79. package/src/validate/context.js +0 -357
  80. package/src/validate/facts.js +0 -253
  81. package/src/validate/files.js +0 -103
  82. package/src/validate/findings.js +0 -19
  83. package/src/validate/glyphs.js +0 -126
  84. package/src/validate/html.js +0 -215
  85. package/src/validate/imports.js +0 -29
  86. package/src/validate/index.js +0 -75
  87. package/src/validate/item.js +0 -47
  88. package/src/validate/links.js +0 -113
  89. package/src/validate/manifest.js +0 -147
  90. package/src/validate/media.js +0 -65
  91. package/src/validate/page.js +0 -74
  92. package/src/validate/prefixes.js +0 -58
  93. package/src/validate/relations.js +0 -310
  94. package/src/validate/release.js +0 -109
  95. package/src/validate/skill.js +0 -122
  96. package/src/validate/structured.js +0 -335
  97. package/src/validate/tasc.js +0 -80
  98. package/src/validate/template.js +0 -129
  99. package/src/validate/tokens.js +0 -154
  100. package/src/validate/zip.js +0 -40
  101. /package/{src/preview/preview.css → preview.css} +0 -0
@@ -1,178 +0,0 @@
1
- import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, rmdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
2
- import { basename, dirname, join, relative, resolve } from 'node:path';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import semver from 'semver';
5
- import { COLLECTION, LOCK, skillFolders } from '../lib/collection.js';
6
- import { itemFiles, sha256 } from '../lib/pack.js';
7
- import { validateCollection, validateLock } from '../lib/schema.js';
8
- import { loadItem } from '../validate/item.js';
9
- import { skillNameOf as frontmatterName } from '../validate/skill.js';
10
- import { usageError } from './exit.js';
11
-
12
- const NAME = /^[a-z0-9]+(-[a-z0-9]+)*\/[a-z0-9]+(-[a-z0-9]+)*$/;
13
-
14
- export const scopeOf = (name) => name.slice(0, name.indexOf('/'));
15
-
16
- export function parseSpec(arg) {
17
- const at = arg.indexOf('@');
18
- const name = at === -1 ? arg : arg.slice(0, at);
19
- const range = at === -1 ? null : arg.slice(at + 1);
20
- if (!NAME.test(name)) throw usageError(`${arg} names no item. Name one as <scope>/<name>, with an optional @<range>.`);
21
- if (range !== null && !semver.validRange(range)) throw usageError(`${arg}'s range, ${range}, is not a semver range.`);
22
- return { name, range };
23
- }
24
-
25
- export function installPath(config, name) {
26
- return `${(config?.install ?? 'items').replace(/\/+$/, '')}/${name}`;
27
- }
28
-
29
- // A registry-supplied path must not escape its item's folder.
30
- export const safePath = (path) =>
31
- typeof path === 'string' && path.length > 0 && !path.startsWith('/') && path.split('/').every((s) => s && s !== '.' && s !== '..' && !/[\\\0:]/.test(s));
32
-
33
- export function localFiles(dir) {
34
- if (!existsSync(join(dir, 'item.json'))) return new Map();
35
- return itemFiles(loadItem(dir));
36
- }
37
-
38
- export function hashesOf(files) {
39
- return Object.fromEntries([...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, bytes]) => [path, sha256(bytes)]));
40
- }
41
-
42
- export function baselineOf(record) {
43
- return Object.fromEntries(record.files.map((f) => [f.path, f.sha256]).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
44
- }
45
-
46
- export function writeFiles(abs, files, remove = []) {
47
- for (const [path, bytes] of files) {
48
- if (!safePath(path)) throw new Error(`The registry listed a file outside its item's folder: ${path}.`);
49
- mkdirSync(dirname(join(abs, path)), { recursive: true });
50
- writeFileSync(join(abs, path), bytes);
51
- }
52
- for (const path of remove) {
53
- if (!safePath(path)) continue;
54
- rmSync(join(abs, path), { force: true });
55
- pruneEmpty(dirname(join(abs, path)), abs);
56
- }
57
- }
58
-
59
- export function pruneEmpty(dir, stop) {
60
- while (dir !== stop && dir.startsWith(stop) && existsSync(dir) && readdirSync(dir).length === 0) {
61
- rmdirSync(dir);
62
- dir = dirname(dir);
63
- }
64
- }
65
-
66
- export function deleteItem(root, path) {
67
- const abs = join(root, path);
68
- rmSync(abs, { recursive: true, force: true });
69
- pruneEmpty(dirname(abs), root);
70
- }
71
-
72
- // A skill's folder takes its frontmatter name, which agents load it by. Null when it names none.
73
- export const skillNameOf = (doc) => frontmatterName(new TextDecoder().decode(doc ?? new Uint8Array()));
74
-
75
- export const skillPath = (config, skillName) => `${skillFolders(config)[0]}/${skillName}`;
76
-
77
- export const installedManifest = (collection, name) => collection.items.find((i) => i.installed && i.manifest?.name === name)?.manifest ?? null;
78
-
79
- export const isInstalledSkill = (collection, name) => installedManifest(collection, name)?.kind === 'skill';
80
-
81
- // Each installed skill's folder name, the frontmatter name it installed under, to its item. A skill's lock entry
82
- // carries `links`, so a skill whose folder was deleted by hand still holds its name.
83
- export function installedSkills(collection) {
84
- return new Map(Object.entries(collection.lock.items).filter(([name, entry]) => Array.isArray(entry.links) || isInstalledSkill(collection, name)).map(([name, entry]) => [basename(entry.path), name]));
85
- }
86
-
87
- export const skillLinks = (config, path) =>
88
- skillFolders(config)
89
- .filter((f) => f !== dirname(path))
90
- .map((f) => `${f}/${basename(path)}`);
91
-
92
- // The fallback copy, where a link is refused, carries this file, so a person's own folder is never taken for one.
93
- export const COPY_MARKER = '.ca-ds-copy';
94
-
95
- export function linkState(root, link, path) {
96
- const abs = join(root, link);
97
- let stat;
98
- try {
99
- stat = lstatSync(abs);
100
- } catch {
101
- return 'absent';
102
- }
103
- if (stat.isSymbolicLink()) return resolve(dirname(abs), readlinkSync(abs)) === join(root, path) ? 'ours' : 'other';
104
- if (stat.isDirectory() && existsSync(join(abs, COPY_MARKER))) return 'copy';
105
- return 'other';
106
- }
107
-
108
- // A marked copy the item's lock entry never recorded may be another install's, or hold a person's files, so it clashes.
109
- const replaceable = (root, link, path, recorded) => {
110
- const state = linkState(root, link, path);
111
- return state === 'copy' && !recorded.includes(link) ? 'other' : state;
112
- };
113
-
114
- export const linkClash = (root, config, path, recorded = []) => skillLinks(config, path).find((link) => !['absent', 'ours'].includes(replaceable(root, link, path, recorded))) ?? null;
115
-
116
- export function linkSkill(root, config, path, { recorded = [], symlink = symlinkSync } = {}) {
117
- const target = join(root, path);
118
- const linked = [];
119
- for (const link of skillLinks(config, path)) {
120
- const state = replaceable(root, link, path, recorded);
121
- if (state === 'other') continue;
122
- linked.push(link);
123
- if (state === 'ours') continue;
124
- const abs = join(root, link);
125
- if (state === 'copy') rmSync(abs, { recursive: true, force: true });
126
- mkdirSync(dirname(abs), { recursive: true });
127
- try {
128
- symlink(relative(dirname(abs), target), abs, 'dir');
129
- } catch (err) {
130
- if (err.code !== 'EPERM') throw err;
131
- cpSync(target, abs, { recursive: true, filter: (src) => src !== join(target, 'item.json') });
132
- writeFileSync(join(abs, COPY_MARKER), `A copy of ${path}, which ca-ds made where a link was refused.\n`);
133
- }
134
- }
135
- return linked;
136
- }
137
-
138
- // Removes the links and copies the lock records, each only while it is still ours, and answers a warning for each it leaves.
139
- export function unlinkSkill(root, links, path, name) {
140
- const warnings = [];
141
- for (const link of links ?? []) {
142
- const abs = join(root, link);
143
- const state = linkState(root, link, path);
144
- if (state === 'ours') unlinkSync(abs);
145
- else if (state === 'copy') rmSync(abs, { recursive: true, force: true });
146
- else {
147
- if (state === 'other') warnings.push({ rule: 'skill-link', name, message: `${link} is no longer ${name}'s link or copy, so it stays. Delete it by hand if you don't need it.` });
148
- continue;
149
- }
150
- pruneEmpty(dirname(abs), root);
151
- }
152
- return warnings;
153
- }
154
-
155
- export function dependentsOf(collection, name, skip = new Set()) {
156
- return collection.items
157
- .filter((i) => i.manifest && !skip.has(i.manifest.name) && Object.hasOwn(i.manifest.dependencies ?? {}, name))
158
- .map((i) => i.manifest.name)
159
- .sort();
160
- }
161
-
162
- const write = (path, data) => writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`);
163
-
164
- const failing = (check) => check.errors.map((e) => `${e.instancePath || '(root)'} ${e.message}`).join('; ');
165
-
166
- export function saveRoots(collection, { config, lock }) {
167
- const items = Object.fromEntries(Object.entries(lock.items).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
168
- const sorted = { release: lock.release, ...(lock.foundation ? { foundation: lock.foundation } : {}), items };
169
- if (config.items && Object.keys(config.items).length === 0) delete config.items;
170
- if (!validateCollection(config)) throw new Error(`The new ${COLLECTION} fails its schema: ${failing(validateCollection)}.`);
171
- if (!validateLock(sorted)) throw new Error(`The new ${LOCK} fails its schema: ${failing(validateLock)}.`);
172
- if (!isDeepStrictEqual(config, collection.config)) write(join(collection.root, COLLECTION), config);
173
- write(join(collection.root, LOCK), sorted);
174
- }
175
-
176
- export function rootsOf(collection) {
177
- return { config: structuredClone(collection.config), lock: structuredClone(collection.lock) };
178
- }
package/src/cli/items.js DELETED
@@ -1,10 +0,0 @@
1
- import { join, resolve as resolvePath } from 'node:path';
2
-
3
- const NAME = /^[a-z0-9]+(-[a-z0-9]+)*\/[a-z0-9]+(-[a-z0-9]+)*$/;
4
-
5
- export const itemNamed = (collection, name) => collection.items.find((i) => i.manifest?.name === name) ?? null;
6
-
7
- export function argPath(collection, arg) {
8
- const item = NAME.test(arg) ? itemNamed(collection, arg) : null;
9
- return item ? join(collection.root, item.dir) : resolvePath(arg);
10
- }
package/src/cli/login.js DELETED
@@ -1,331 +0,0 @@
1
- import { createHash, randomBytes } from 'node:crypto';
2
- import { createServer } from 'node:http';
3
- import { findCollection, openCollection } from '../lib/collection.js';
4
- import {
5
- OAUTH_CLIENT,
6
- RegistryFailure,
7
- credentialsFile,
8
- forgetToken,
9
- isOAuth,
10
- oauthEntry,
11
- postForm,
12
- registryClient,
13
- registryUrl,
14
- saveCredential,
15
- saveToken,
16
- storedCredential,
17
- } from '../lib/registry.js';
18
- import { openUrl } from '../lib/browser.js';
19
- import { CliError, EXIT, usageError } from './exit.js';
20
-
21
- export const LOGIN_TIMEOUT = 5 * 60 * 1000;
22
-
23
- export const CALLBACK_PATH = '/callback';
24
-
25
- export const SCOPE = 'registry';
26
-
27
- function registryOf(cwd, env) {
28
- const root = findCollection(cwd);
29
- return registryUrl(root ? openCollection(root).config : null, env);
30
- }
31
-
32
- function readHidden(stdin) {
33
- return new Promise((resolve, reject) => {
34
- let line = '';
35
- const done = (err) => {
36
- stdin.off('data', onData);
37
- stdin.setRawMode?.(false);
38
- stdin.pause();
39
- if (err) reject(err);
40
- else resolve(line);
41
- };
42
- const onData = (chunk) => {
43
- for (const ch of String(chunk)) {
44
- if (ch === '\r' || ch === '\n') return done();
45
- if (ch === '\u0003' || ch === '\u0004') return done(usageError('Cancelled. No token was stored.'));
46
- if (ch === '\u007f' || ch === '\b') line = line.slice(0, -1);
47
- else line += ch;
48
- }
49
- };
50
- stdin.setRawMode?.(true);
51
- stdin.setEncoding?.('utf8');
52
- stdin.on('data', onData);
53
- stdin.resume();
54
- });
55
- }
56
-
57
- async function readPiped(stdin) {
58
- let text = '';
59
- for await (const chunk of stdin) text += chunk;
60
- return text.split(/\r?\n/).find((l) => l.trim()) ?? '';
61
- }
62
-
63
- export async function discover(url, fetch = globalThis.fetch) {
64
- let res;
65
- try {
66
- res = await fetch(`${url}/.well-known/oauth-authorization-server`, { headers: { accept: 'application/json' } });
67
- } catch (err) {
68
- throw new RegistryFailure(`The registry at ${url} is unreachable: ${err.cause?.message ?? err.message}.`);
69
- }
70
- const fallback = (why) => ({ fallback: `The registry at ${url} offers no browser sign-in, since its authorization server metadata ${why}, so ca-ds asks for a token instead.` });
71
- if (res.status !== 200) return fallback(`answered ${res.status}`);
72
- let metadata;
73
- try {
74
- metadata = JSON.parse(await res.text());
75
- } catch {
76
- return fallback("isn't JSON");
77
- }
78
- if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return fallback("isn't a JSON object");
79
- for (const key of ['authorization_endpoint', 'token_endpoint']) {
80
- if (typeof metadata[key] !== 'string' || !URL.canParse(metadata[key])) return fallback(`names no ${key}`);
81
- }
82
- return { metadata };
83
- }
84
-
85
- const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
86
-
87
- const callbackPage = (title, text) =>
88
- `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>${escapeHtml(title)}</title>\n</head>\n<body>\n<h1>${escapeHtml(title)}</h1>\n<p>${escapeHtml(text)}</p>\n</body>\n</html>\n`;
89
-
90
- const PAGE_HEADERS = {
91
- 'content-type': 'text/html; charset=utf-8',
92
- 'cache-control': 'no-store',
93
- 'content-security-policy': "default-src 'none'; frame-ancestors 'none'",
94
- 'referrer-policy': 'no-referrer',
95
- connection: 'close',
96
- };
97
-
98
- function answerPage(res, status, title, text) {
99
- return new Promise((resolve) => {
100
- res.on('close', resolve);
101
- res.writeHead(status, PAGE_HEADERS).end(callbackPage(title, text));
102
- });
103
- }
104
-
105
- const signInError = (message) => new CliError(message, EXIT.auth);
106
-
107
- export async function browserLogin({ url, metadata, io, stdin, fetch = globalThis.fetch, open = null, timeout = LOGIN_TIMEOUT, now = Date.now }) {
108
- const verifier = randomBytes(32).toString('base64url');
109
- const challenge = createHash('sha256').update(verifier).digest('base64url');
110
- const state = randomBytes(16).toString('base64url');
111
-
112
- let deliver;
113
- const answered = new Promise((resolve) => {
114
- deliver = resolve;
115
- });
116
- let taken = false;
117
- const take = (answer) => {
118
- if (taken) return false;
119
- taken = true;
120
- deliver(answer);
121
- return true;
122
- };
123
-
124
- // Only this sign-in's state, at this host and port, answers, so another local program or a DNS-rebinding page can't end it.
125
- const server = createServer((req, res) => {
126
- const at = new URL(req.url ?? '/', 'http://127.0.0.1');
127
- const host = `127.0.0.1:${server.address().port}`;
128
- if (req.method !== 'GET' || at.pathname !== CALLBACK_PATH || req.headers.host !== host) {
129
- res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' }).end('Not found\n');
130
- return;
131
- }
132
- const respond = (status, title, text) => answerPage(res, status, title, text);
133
- if (at.searchParams.get('state') !== state) {
134
- respond(400, 'Not this sign-in', "This address doesn't answer the sign-in ca-ds is waiting for. Finish the sign-in from the address ca-ds printed.");
135
- return;
136
- }
137
- if (!take({ params: at.searchParams, respond })) respond(409, 'Sign-in already answered', 'ca-ds took an answer for this sign-in already. Close this tab.');
138
- });
139
- await new Promise((resolve, reject) => {
140
- server.once('error', reject);
141
- server.listen(0, '127.0.0.1', resolve);
142
- });
143
- const redirectUri = `http://127.0.0.1:${server.address().port}${CALLBACK_PATH}`;
144
-
145
- // Or the pasted address the browser landed on, for a browser on another machine.
146
- let pending = '';
147
- const onData = (chunk) => {
148
- pending += chunk;
149
- const lines = pending.split(/\r?\n/);
150
- pending = lines.pop();
151
- for (const line of lines.map((l) => l.trim()).filter(Boolean)) {
152
- const pasted = URL.canParse(line) ? new URL(line) : null;
153
- const params = pasted?.searchParams;
154
- if (!params || !['code', 'error', 'state'].some((name) => params.has(name))) {
155
- io.tell(`That isn't the address the browser landed on. Paste the whole address, starting with ${redirectUri}.`);
156
- continue;
157
- }
158
- if (params.get('state') !== state) {
159
- io.tell("That address answers another sign-in. Paste the address this one's browser tab landed on.");
160
- continue;
161
- }
162
- take({ params, respond: null });
163
- }
164
- };
165
- stdin.setEncoding?.('utf8');
166
- stdin.on('data', onData);
167
- stdin.resume();
168
-
169
- let timer;
170
- const expired = new Promise((resolve) => {
171
- timer = setTimeout(() => resolve(null), timeout);
172
- timer.unref?.();
173
- });
174
-
175
- const authorize = new URL(metadata.authorization_endpoint);
176
- for (const [name, value] of Object.entries({
177
- response_type: 'code',
178
- client_id: OAUTH_CLIENT,
179
- redirect_uri: redirectUri,
180
- code_challenge: challenge,
181
- code_challenge_method: 'S256',
182
- state,
183
- scope: SCOPE,
184
- resource: `${url}/mcp`,
185
- })) {
186
- authorize.searchParams.set(name, value);
187
- }
188
- io.tell(open ? `Sign in to ${url} in the browser that opened, or at this address:` : `Sign in to ${url} at this address:`);
189
- io.tell(authorize.href);
190
- io.tell("If the browser can't reach this machine, paste the address it lands on:");
191
- if (open) open(authorize.href);
192
-
193
- let answer = null;
194
- try {
195
- answer = await Promise.race([answered, expired]);
196
- if (!answer) {
197
- taken = true;
198
- const minutes = Math.max(1, Math.round(timeout / 60000));
199
- throw signInError(`No sign-in came within ${minutes} minute${minutes === 1 ? '' : 's'}, so nothing was stored. Run ca-ds login again.`);
200
- }
201
- const entry = await finish(answer.params);
202
- await answer.respond?.(200, 'Sign-in finished', `ca-ds is signed in to ${url}. You can close this tab.`);
203
- return entry;
204
- } catch (err) {
205
- await answer?.respond?.(400, 'Sign-in failed', `${err.message} You can close this tab.`);
206
- throw err;
207
- } finally {
208
- clearTimeout(timer);
209
- stdin.off('data', onData);
210
- stdin.pause?.();
211
- server.close();
212
- server.closeAllConnections();
213
- }
214
-
215
- async function finish(params) {
216
- if (params.get('state') !== state) throw signInError("The sign-in's answer carries a state ca-ds never sent, so ca-ds stored nothing. Run ca-ds login again.");
217
- const iss = params.get('iss');
218
- // RFC 9207: iss is required when the metadata says the registry sends one.
219
- if (iss === null ? metadata.authorization_response_iss_parameter_supported === true : iss !== metadata.issuer) {
220
- throw signInError(`The sign-in's answer names the issuer ${iss ?? 'nowhere'}, and the registry's metadata names ${metadata.issuer}, so ca-ds stored nothing. Run ca-ds login again.`);
221
- }
222
- const error = params.get('error');
223
- if (error === 'access_denied') throw signInError(`The sign-in to ${url} was denied, so nothing was stored.`);
224
- if (error !== null) {
225
- const said = params.get('error_description');
226
- throw signInError(`The registry at ${url} refused the sign-in, ${error}.${said ? ` ${said}` : ''}`);
227
- }
228
- const code = params.get('code');
229
- if (!code) throw signInError("The sign-in's answer holds no code, so ca-ds stored nothing. Run ca-ds login again.");
230
- const { status, body } = await postForm(
231
- metadata.token_endpoint,
232
- { grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: OAUTH_CLIENT, code_verifier: verifier, resource: `${url}/mcp` },
233
- fetch,
234
- );
235
- const said = body?.error_description ? ` ${body.error_description}` : '';
236
- if (status === 400 || status === 401) throw new RegistryFailure(`The registry at ${url} refused the sign-in's code, ${body?.error ?? status}.${said}`, { auth: true, status, code: body?.error ?? null });
237
- const entry = status === 200 ? oauthEntry(body, { tokenEndpoint: metadata.token_endpoint, revocationEndpoint: metadata.revocation_endpoint ?? null, clientId: OAUTH_CLIENT }, now()) : null;
238
- if (!entry) throw new RegistryFailure(`The registry at ${url} answered the sign-in's code with ${status} and no access token.${said}`, { status });
239
- await registryClient({ url, token: entry.token, fetch }).checkToken();
240
- return entry;
241
- }
242
- }
243
-
244
- export const login = {
245
- synopsis: 'login',
246
- summary: 'sign in to a registry, or store a token for it',
247
- usage: ['ca-ds login [--no-open]', 'ca-ds login --paste [--no-open]', 'ca-ds login --token <token>', "printf '%s' \"$TOKEN\" | ca-ds login"],
248
- options: { token: { type: 'string' }, paste: { type: 'boolean' }, 'no-open': { type: 'boolean' } },
249
- async run({ values, positionals, io, env, fetch, cwd, stdin }) {
250
- if (positionals.length) throw usageError('ca-ds login takes no arguments.');
251
- const url = registryOf(cwd, env);
252
- const file = credentialsFile(env);
253
- const opens = !values['no-open'] && !io.json;
254
- const warnEnv = () => env.CA_DS_TOKEN && io.warn('CA_DS_TOKEN is set, and it overrides the stored credential while it is.');
255
- let token = values.token;
256
-
257
- if (token === undefined && stdin.isTTY && !values.paste) {
258
- const found = await discover(url, fetch);
259
- if (found.metadata) {
260
- const entry = await browserLogin({ url, metadata: found.metadata, io, stdin, fetch, open: opens ? openUrl : null });
261
- saveCredential(url, entry, file);
262
- io.log(`Signed in to ${url}, and stored the sign-in in ${file}.`);
263
- warnEnv();
264
- return { result: { registry: url, file, kind: 'oauth', expiresAt: entry.expiresAt } };
265
- }
266
- io.tell(found.fallback);
267
- }
268
-
269
- const page = `${url}/settings/api-keys`;
270
- if (token === undefined) {
271
- if (stdin.isTTY) {
272
- io.tell(`Create a token at ${page}, then paste it here. It won't echo.`);
273
- if (opens) openUrl(page);
274
- token = await readHidden(stdin);
275
- } else {
276
- token = await readPiped(stdin);
277
- }
278
- }
279
- token = token.trim();
280
- if (!token) throw usageError(`No token came. Create one at ${page}, then pass it with --token or on stdin.`);
281
- if (/\s/.test(token)) throw usageError('A token holds no spaces. Paste the token alone.');
282
- await registryClient({ url, token, fetch }).checkToken();
283
- saveToken(url, token, file);
284
- io.log(`Stored the token for ${url} in ${file}.`);
285
- warnEnv();
286
- return { result: { registry: url, file } };
287
- },
288
- };
289
-
290
- async function revoke(url, entry, { io, fetch }) {
291
- const after = `Revoke it under Connected apps at ${url}/settings/api-keys.`;
292
- if (typeof entry.revocationEndpoint !== 'string' || !URL.canParse(entry.revocationEndpoint)) {
293
- io.warn(`The stored sign-in for ${url} names no revocation endpoint, so it stays live until it lapses. ${after}`);
294
- return false;
295
- }
296
- try {
297
- const { status } = await postForm(entry.revocationEndpoint, { token: entry.refresh, token_type_hint: 'refresh_token', client_id: entry.clientId ?? OAUTH_CLIENT }, fetch);
298
- if (status === 200) return true;
299
- io.warn(`The registry at ${url} answered the revocation with ${status}, so the sign-in may stay live. ${after}`);
300
- } catch (err) {
301
- if (!(err instanceof RegistryFailure)) throw err;
302
- io.warn(`${err.message} The sign-in may stay live. ${after}`);
303
- }
304
- return false;
305
- }
306
-
307
- export const logout = {
308
- synopsis: 'logout',
309
- summary: 'sign out of a registry, or remove a stored token',
310
- usage: ['ca-ds logout'],
311
- options: {},
312
- async run({ positionals, io, env, cwd, fetch }) {
313
- if (positionals.length) throw usageError('ca-ds logout takes no arguments.');
314
- const url = registryOf(cwd, env);
315
- const file = credentialsFile(env);
316
- const entry = storedCredential(url, file);
317
- if (isOAuth(entry)) {
318
- const revoked = await revoke(url, entry, { io, fetch });
319
- const removed = forgetToken(url, file);
320
- io.log(revoked ? `Signed out of ${url}. The registry revoked the sign-in, and ${file} no longer holds it.` : `Removed the sign-in for ${url} from ${file}.`);
321
- return { result: { registry: url, file, removed, kind: 'oauth', revoked } };
322
- }
323
- const removed = forgetToken(url, file);
324
- io.log(
325
- removed
326
- ? `Removed the token for ${url} from ${file}. It stays live until it's revoked at ${url}/settings/api-keys.`
327
- : `${file} holds no token for ${url}.`,
328
- );
329
- return { result: { registry: url, file, removed } };
330
- },
331
- };
package/src/cli/main.js DELETED
@@ -1,108 +0,0 @@
1
- import { parseArgs } from 'node:util';
2
- import { findCollection, openCollection, COLLECTION } from '../lib/collection.js';
3
- import { EXIT, exitName, exitOf, usageError } from './exit.js';
4
- import { command as build } from './build.js';
5
- import { command as validate } from './validate.js';
6
- import { command as pack } from './pack.js';
7
- import { command as scaffold } from './new.js';
8
- import { command as preview } from './preview.js';
9
- import { command as add } from './add.js';
10
- import { command as remove } from './remove.js';
11
- import { command as update } from './update.js';
12
- import { command as diff } from './diff.js';
13
- import { command as outdated } from './outdated.js';
14
- import { command as eject } from './eject.js';
15
- import { command as publish } from './publish.js';
16
- import { command as pull } from './pull.js';
17
- import { command as format } from './format.js';
18
- import { command as init } from './init.js';
19
- import { login, logout } from './login.js';
20
- import { VERSION as version } from '../lib/version.js';
21
-
22
- export const COMMANDS = { init, new: scaffold, add, remove, update, diff, outdated, eject, build, preview, validate, format, pack, publish, pull, login, logout };
23
-
24
- const GLOBAL = {
25
- json: { type: 'boolean' },
26
- help: { type: 'boolean', short: 'h' },
27
- };
28
-
29
- const pad = (s, n) => s + ' '.repeat(Math.max(1, n - s.length));
30
-
31
- export function help() {
32
- const rows = Object.entries(COMMANDS).map(([name, c]) => ` ${pad(c.synopsis ?? name, 34)}${c.summary}`);
33
- const codes = Object.entries(EXIT).map(([name, code]) => `${code} ${name}`).join(', ');
34
- return [
35
- `ca-ds ${version}, the California Design System's toolbelt for a collection of items`,
36
- '',
37
- 'Usage: ca-ds <command> [options]',
38
- '',
39
- 'Commands:',
40
- ...rows,
41
- '',
42
- 'Every command takes --json, which prints one JSON document on stdout, and --help.',
43
- `Exit codes: ${codes}.`,
44
- 'ca-ds --version prints the version.',
45
- ].join('\n');
46
- }
47
-
48
- export async function main(
49
- args,
50
- {
51
- out = (s) => process.stdout.write(`${s}\n`),
52
- err = (s) => process.stderr.write(`${s}\n`),
53
- cwd = process.cwd(),
54
- env = process.env,
55
- fetch = globalThis.fetch,
56
- stdin = process.stdin,
57
- } = {},
58
- ) {
59
- const [name, ...rest] = args;
60
- const json = rest.includes('--json') || name === '--json';
61
- const fail = (e, usage = null) => {
62
- const exit = exitOf(e);
63
- if (json) out(JSON.stringify({ error: { code: exitName(exit), message: e.message } }, null, 2));
64
- else err(exit === EXIT.usage && usage ? `${e.message}\nUsage: ${usage}` : e.message);
65
- return exit;
66
- };
67
-
68
- if (name === '--version' || name === '-v') {
69
- out(json ? JSON.stringify({ version }) : version);
70
- return EXIT.ok;
71
- }
72
- if (name === '--help' || name === '-h' || name === 'help') {
73
- out(help());
74
- return EXIT.ok;
75
- }
76
- if (name === undefined || name.startsWith('-')) {
77
- if (json) return fail(usageError('Name a command. ca-ds --help lists them.'));
78
- err(help());
79
- return EXIT.usage;
80
- }
81
- if (!Object.hasOwn(COMMANDS, name)) return fail(usageError(`ca-ds has no command ${name}. ca-ds --help lists them.`));
82
-
83
- const command = COMMANDS[name];
84
- const usage = command.usage.join('\n ');
85
- try {
86
- const { values, positionals } = parseArgs({ args: rest, options: { ...GLOBAL, ...command.options }, allowPositionals: true, strict: true });
87
- if (values.help) {
88
- out(`Usage: ${usage}\n\n${command.summary}`);
89
- return EXIT.ok;
90
- }
91
- const io = {
92
- json,
93
- log: (s) => json || out(s),
94
- warn: (s) => json || err(s),
95
- tell: (s) => err(s),
96
- };
97
- const collection = () => {
98
- const root = findCollection(cwd);
99
- if (!root) throw usageError(`No ${COLLECTION} sits in ${cwd} or any folder above it.`);
100
- return openCollection(root);
101
- };
102
- const { exit = EXIT.ok, result = {} } = (await command.run({ values, positionals, io, collection, cwd, env, fetch, stdin })) ?? {};
103
- if (json) out(JSON.stringify(result, null, 2));
104
- return exit;
105
- } catch (e) {
106
- return fail(e, usage);
107
- }
108
- }