@whzxc/agent-design-gallery 0.14.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -16
- package/package.json +1 -1
- package/public/access.css +15 -2
- package/public/app.js +708 -483
- package/public/arrangement-worker.js +7 -7
- package/public/arrangement.js +35 -30
- package/public/assets.js +60 -38
- package/public/auth.js +59 -4
- package/public/boards.js +124 -0
- package/public/comment-anchors.js +50 -0
- package/public/comments.css +400 -0
- package/public/comments.js +1106 -0
- package/public/context-menu.js +97 -0
- package/public/frame-identity.js +26 -2
- package/public/hub.css +25 -3
- package/public/hub.html +10 -2
- package/public/hub.js +127 -23
- package/public/icons.js +2 -0
- package/public/index.html +13 -9
- package/public/instance-actions.js +9 -2
- package/public/layout.js +156 -86
- package/public/selection.js +1 -1
- package/public/style.css +74 -152
- package/public/switcher.css +5 -4
- package/public/switcher.js +109 -34
- package/public/token-catalog.js +8 -3
- package/public/tokens.css +14 -1
- package/public/view-route.js +0 -1
- package/src/boards/board.mjs +30 -0
- package/src/boards/token-board.mjs +196 -0
- package/src/cli-output.mjs +8 -5
- package/src/cli.mjs +49 -29
- package/src/comments.mjs +293 -0
- package/src/http.mjs +2 -3
- package/src/hub/project-link.mjs +41 -0
- package/src/hub/registry.mjs +5 -0
- package/src/hub.mjs +14 -10
- package/src/link.mjs +13 -1
- package/src/server.mjs +57 -93
- package/src/service.mjs +46 -12
- package/src/toolkit/arch.mjs +3 -2
- package/src/toolkit/asset-rules.mjs +24 -1
- package/src/toolkit/commands.mjs +12 -7
- package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
- package/src/toolkit/diff-inputs.mjs +66 -30
- package/src/toolkit/diff.mjs +181 -39
- package/src/toolkit/impact-selection.mjs +25 -10
- package/src/toolkit/impact.mjs +32 -12
- package/src/toolkit/move-pairing.mjs +140 -0
- package/src/toolkit/project-index.mjs +2 -2
- package/src/toolkit/results.mjs +1 -1
- package/src/toolkit/review-document.mjs +435 -0
- package/src/toolkit/review-groups.mjs +29 -0
- package/src/toolkit/review-observation.mjs +131 -0
- package/src/toolkit/review-sheet.mjs +117 -0
- package/src/toolkit/review-specimens.mjs +60 -0
- package/src/toolkit/review.mjs +140 -0
- package/src/toolkit/runtime.mjs +1 -1
- package/src/toolkit/theme.mjs +16 -0
- package/public/annotations.js +0 -816
- package/public/labels.js +0 -122
- package/src/annotations.mjs +0 -238
package/src/server.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Adapted from ARC's MIT-licensed tooling/design-server.mjs.
|
|
2
|
-
import {
|
|
2
|
+
import { changeComment, commentFile, commentRevision, listComments, readComment } from './comments.mjs';
|
|
3
3
|
import { randomUUID, createHash } from 'node:crypto';
|
|
4
4
|
import { directLocal, viewerFile, shell, json } from './http.mjs';
|
|
5
5
|
import { createServer } from "node:http";
|
|
@@ -24,9 +24,9 @@ import { createViewerCache } from './viewer-cache.mjs';
|
|
|
24
24
|
import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, isFeatureInternal } from './toolkit/project.mjs';
|
|
25
25
|
import { loadConfig } from './toolkit/config.mjs';
|
|
26
26
|
import { parseTokens } from './toolkit/tokens.mjs';
|
|
27
|
+
import { tokenBoard } from './boards/token-board.mjs';
|
|
27
28
|
import { sourceRelationships } from '../public/relationships.js';
|
|
28
29
|
import { resolveScope } from '../public/assets.js';
|
|
29
|
-
import { diff } from './toolkit/diff.mjs';
|
|
30
30
|
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
31
31
|
const tokenFile = 'tokens.css';
|
|
32
32
|
function tokenSourcePath(directory, project) {
|
|
@@ -39,7 +39,7 @@ export async function startServer({
|
|
|
39
39
|
directory,
|
|
40
40
|
port = 0,
|
|
41
41
|
stateDirectory = defaultState,
|
|
42
|
-
|
|
42
|
+
commentStateDirectory = stateDirectory,
|
|
43
43
|
fixtures = null,
|
|
44
44
|
readOnly = false,
|
|
45
45
|
instanceId = randomUUID(),
|
|
@@ -64,7 +64,7 @@ export async function startServer({
|
|
|
64
64
|
revision = 0,
|
|
65
65
|
closing = false,
|
|
66
66
|
buildStore, viewerCache, codePaths=new Set();
|
|
67
|
-
const overlayStores = new Map(), overlayHashes = new Set()
|
|
67
|
+
const overlayStores = new Map(), overlayHashes = new Set();
|
|
68
68
|
let resettingOverlays = false;
|
|
69
69
|
const knownBuilds = new Map(), legacyDependencies = new Map(), failedSources=new Set(), dirtyBuilds=new Set();
|
|
70
70
|
const describe=built=>({...built,css:undefined,frames:built.frames.map(({html,...frame})=>frame)});
|
|
@@ -84,29 +84,33 @@ export async function startServer({
|
|
|
84
84
|
});
|
|
85
85
|
return writes;
|
|
86
86
|
};
|
|
87
|
-
const emit = (data) => {
|
|
87
|
+
const emit = (data, event) => {
|
|
88
|
+
const type = event ? `event: ${event}\n` : '';
|
|
88
89
|
for (const client of clients)
|
|
89
|
-
client.write(
|
|
90
|
+
client.write(`${type}data: ${JSON.stringify(data)}\n\n`);
|
|
90
91
|
};
|
|
91
|
-
let
|
|
92
|
-
async function
|
|
93
|
-
if (!activeProject) return null;
|
|
92
|
+
let commentsFile, commentStamp, checkingComments = false;
|
|
93
|
+
async function readCommentStamp(file) {
|
|
94
94
|
try {
|
|
95
|
-
const info = await stat(
|
|
96
|
-
return `${info.
|
|
95
|
+
const info = await stat(file, { bigint: true });
|
|
96
|
+
return `${info.ino}-${info.mtimeNs}-${info.ctimeNs}`;
|
|
97
97
|
} catch (e) {
|
|
98
98
|
return e.code === 'ENOENT' ? 'missing' : null;
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
|
-
const
|
|
102
|
-
if (closing || !clients.size || !
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
101
|
+
const commentTimer = setInterval(async () => {
|
|
102
|
+
if (closing || !clients.size || !commentsFile || checkingComments) return;
|
|
103
|
+
checkingComments = true;
|
|
104
|
+
const file = commentsFile;
|
|
105
|
+
try {
|
|
106
|
+
const next = await readCommentStamp(file);
|
|
107
|
+
if (file === commentsFile && next && next !== commentStamp) {
|
|
108
|
+
commentStamp = next;
|
|
109
|
+
emit({ comments: true }, 'comments');
|
|
110
|
+
}
|
|
111
|
+
} finally { checkingComments = false; }
|
|
112
|
+
}, 400);
|
|
113
|
+
commentTimer.unref?.();
|
|
110
114
|
const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
|
|
111
115
|
if (error.name === 'AbortError') return;
|
|
112
116
|
const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
|
|
@@ -251,7 +255,8 @@ export async function startServer({
|
|
|
251
255
|
watcher = nextWatcher;
|
|
252
256
|
activeProject=project;watchArch(project,next);
|
|
253
257
|
root = next;
|
|
254
|
-
|
|
258
|
+
commentsFile = await commentFile(project.root, commentStateDirectory);
|
|
259
|
+
commentStamp = await readCommentStamp(commentsFile);
|
|
255
260
|
tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
|
|
256
261
|
codePaths=nextCode;
|
|
257
262
|
sources = nextSources;
|
|
@@ -369,17 +374,26 @@ export async function startServer({
|
|
|
369
374
|
const data=baseManifest(),context=await contextFor(url), requested=url.searchParams.get('scope');
|
|
370
375
|
const fixtureScope=fixtures?.states[url.searchParams.get('fixture')]?.scope;
|
|
371
376
|
const desired = fixtureScope ?? requested ?? 'all';
|
|
377
|
+
if (data.tokenSource) {
|
|
378
|
+
try {
|
|
379
|
+
const css = await readFile(path.join(data.directory, tokenFile), 'utf8');
|
|
380
|
+
const { light, dark } = parseTokens(css);
|
|
381
|
+
const declarations = values => [...values].map(([name, value]) => `${name}:${value};`).join('\n');
|
|
382
|
+
data.boardCss = `#board-chrome{${declarations(light)}}
|
|
383
|
+
:where([data-theme="dark"]) #board-chrome, #board-chrome[data-theme="dark"]{${declarations(dark)}}`;
|
|
384
|
+
if (desired === 'tokens' || desired === 'all') {
|
|
385
|
+
data.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
|
|
386
|
+
data.tokenBoard = tokenBoard(data.tokenSource, css, { projectName: data.label });
|
|
387
|
+
}
|
|
388
|
+
} catch (error) {
|
|
389
|
+
data.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
|
|
390
|
+
diagnostic(new CliError('TOKENS_INVALID', error.message, { cause: error }));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
372
393
|
if (desired === 'tokens' && data.tokenSource) {
|
|
373
394
|
// Keep the layer choices available without measuring or building any artboards.
|
|
374
395
|
const { layers } = resolveScope(data, sources, 'all');
|
|
375
396
|
const result = { ...data, scope: 'tokens', layers, assets: [] };
|
|
376
|
-
try {
|
|
377
|
-
const { light, dark } = parseTokens(await readFile(path.join(data.directory, tokenFile), 'utf8'));
|
|
378
|
-
result.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
|
|
379
|
-
} catch (error) {
|
|
380
|
-
result.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
|
|
381
|
-
diagnostic(new CliError('TOKENS_INVALID',error.message,{cause:error}));
|
|
382
|
-
}
|
|
383
397
|
return applyFixtureManifest(result, url.searchParams.get('fixture'));
|
|
384
398
|
}
|
|
385
399
|
const scoped=resolveScope(data,sources,desired === 'tokens' ? 'default' : desired);
|
|
@@ -424,42 +438,10 @@ export async function startServer({
|
|
|
424
438
|
}
|
|
425
439
|
return {...asset,metadata,metadataRefs,previewIds};
|
|
426
440
|
}));
|
|
427
|
-
data.packing=(await viewerCache.get(digest('catalog'),'light',context))?.metadata.packing??[];
|
|
428
441
|
}
|
|
429
442
|
data.features={compactSources:1,persistedMetadata:1,incrementalHashes:1};
|
|
430
443
|
return applyFixtureManifest(data,url.searchParams.get('fixture'));
|
|
431
444
|
}
|
|
432
|
-
async function reviewManifest(url) {
|
|
433
|
-
const baseParam = url.searchParams.get('base');
|
|
434
|
-
if (typeof baseParam !== 'string' || !baseParam.trim())
|
|
435
|
-
throw new CliError('USAGE_INVALID', 'Set ?base=<rev> to a Git revision.');
|
|
436
|
-
if (!activeProject || !root)
|
|
437
|
-
throw new CliError('DIRECTORY_NOT_FOUND', 'No project is open.');
|
|
438
|
-
const data = baseManifest();
|
|
439
|
-
const { layers } = resolveScope(data, sources, 'all');
|
|
440
|
-
const reviewDir = path.join(stateDirectory, 'cache', digest(root), 'review', randomUUID());
|
|
441
|
-
let review = null;
|
|
442
|
-
const task = (async () => {
|
|
443
|
-
try {
|
|
444
|
-
await diff(activeProject, [], {
|
|
445
|
-
base: baseParam,
|
|
446
|
-
impacted: true,
|
|
447
|
-
'out-dir': reviewDir,
|
|
448
|
-
'state-dir': stateDirectory,
|
|
449
|
-
json: true,
|
|
450
|
-
}, { log: () => {}, onReview: value => { review = value; } });
|
|
451
|
-
} catch (error) {
|
|
452
|
-
if (error.code !== 'DIFF_FAILED') throw error;
|
|
453
|
-
} finally {
|
|
454
|
-
await rm(reviewDir, { recursive: true, force: true }).catch(() => {});
|
|
455
|
-
}
|
|
456
|
-
if (!review) throw new CliError('INTERNAL_ERROR', 'Review output was not produced.');
|
|
457
|
-
return { ...data, scope: 'review', layers, assets: [], base: review.base, review: { ...review, label: data.label } };
|
|
458
|
-
})();
|
|
459
|
-
activeReviews.add(task);
|
|
460
|
-
try { return await task; }
|
|
461
|
-
finally { activeReviews.delete(task); }
|
|
462
|
-
}
|
|
463
445
|
async function sourceBuild(name) {
|
|
464
446
|
const endBuild = perfSpan('build', name);
|
|
465
447
|
let built;
|
|
@@ -553,29 +535,22 @@ export async function startServer({
|
|
|
553
535
|
const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
|
|
554
536
|
if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
|
|
555
537
|
if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
|
|
556
|
-
if (url.pathname === '/api/
|
|
538
|
+
if (url.pathname === '/api/comments') {
|
|
557
539
|
if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
|
|
558
540
|
if (request.method === 'POST' && request.headers.origin && ![`http://${host}`,`https://${host}`].includes(request.headers.origin)) return json(response,403,{error:'Cross-origin request refused.'});
|
|
559
|
-
|
|
541
|
+
if (!activeProject) return json(response, 404, { error: 'No project is open.' });
|
|
542
|
+
const { root: projectRoot } = activeProject;
|
|
560
543
|
if (request.method === 'GET') {
|
|
561
|
-
if (url.searchParams.has('id'))
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
}
|
|
568
|
-
const status = url.searchParams.get('status') ?? 'all';
|
|
569
|
-
return json(response, 200, await annotations(config.root, annotationStateDirectory, 'list', { status }));
|
|
544
|
+
if (url.searchParams.has('id'))
|
|
545
|
+
return json(response, 200, await readComment(projectRoot, commentStateDirectory, url.searchParams.get('id')));
|
|
546
|
+
const [result, revision] = await Promise.all([
|
|
547
|
+
listComments(projectRoot, commentStateDirectory, { status: url.searchParams.get('status') ?? 'all' }),
|
|
548
|
+
commentRevision(projectRoot),
|
|
549
|
+
]);
|
|
550
|
+
return json(response, 200, { ...result, revision });
|
|
570
551
|
}
|
|
571
|
-
const input = await body(request);
|
|
572
|
-
|
|
573
|
-
...input,
|
|
574
|
-
...(input.action === 'reply' && !input.author ? { author: 'user' } : {}),
|
|
575
|
-
});
|
|
576
|
-
annotationStamp = await readAnnotationStamp();
|
|
577
|
-
emit({ annotations: true });
|
|
578
|
-
return json(response, 200, result);
|
|
552
|
+
const input = await body(request, 256 * 1024);
|
|
553
|
+
return json(response, 200, await changeComment(projectRoot, commentStateDirectory, input, { viewer: true }));
|
|
579
554
|
}
|
|
580
555
|
if(url.pathname==='/api/cache-stats'&&request.method==='GET')return json(response,200,{process:process.memoryUsage(),builds:buildStore?.stats(),viewer:viewerCache?.stats()});
|
|
581
556
|
if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id: instanceId, capabilities: { keyAuth: 1 } });
|
|
@@ -603,12 +578,6 @@ export async function startServer({
|
|
|
603
578
|
}
|
|
604
579
|
return json(response,200,{ok:true});
|
|
605
580
|
}
|
|
606
|
-
if(url.pathname==='/catalog') {
|
|
607
|
-
const data=await body(request,1024*1024),context=await contextFor(url);
|
|
608
|
-
if(!Array.isArray(data.packing)||data.packing.length>32)throw Error('Invalid packing cache.');
|
|
609
|
-
await viewerCache.save(digest('catalog'),'light',context,{packing:data.packing});
|
|
610
|
-
return json(response,200,{ok:true});
|
|
611
|
-
}
|
|
612
581
|
const data = await body(request);
|
|
613
582
|
if (url.pathname === "/preferences") {
|
|
614
583
|
if (typeof data.sidebar === "boolean") state.sidebar = data.sidebar;
|
|
@@ -645,7 +614,6 @@ export async function startServer({
|
|
|
645
614
|
return;
|
|
646
615
|
}
|
|
647
616
|
if (url.pathname === "/events") {
|
|
648
|
-
annotationStamp ??= await readAnnotationStamp();
|
|
649
617
|
response.writeHead(200, {
|
|
650
618
|
"Content-Type": "text/event-stream",
|
|
651
619
|
"Cache-Control": "no-store",
|
|
@@ -668,9 +636,6 @@ export async function startServer({
|
|
|
668
636
|
if (url.pathname === "/manifest") {
|
|
669
637
|
content = JSON.stringify(await manifest(url));
|
|
670
638
|
type = "application/json";
|
|
671
|
-
} else if (url.pathname === "/review") {
|
|
672
|
-
content = JSON.stringify(await reviewManifest(url));
|
|
673
|
-
type = "application/json";
|
|
674
639
|
} else if (url.pathname === "/relationships") {
|
|
675
640
|
const assets = await Promise.all([...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name)).map(async name => ({path:name, imports:(await sourceBuild(name)).imports})));
|
|
676
641
|
content = JSON.stringify(sourceRelationships(assets));
|
|
@@ -708,15 +673,15 @@ export async function startServer({
|
|
|
708
673
|
response.end(request.method === "HEAD" ? undefined : content);
|
|
709
674
|
} catch (error) {
|
|
710
675
|
if (response.destroyed) return;
|
|
711
|
-
|
|
712
|
-
response
|
|
676
|
+
const status = { COMMENT_NOT_FOUND: 404, COMMENT_FORBIDDEN: 403 }[error.code] ?? (error.name === 'AbortError' ? 409 : 400);
|
|
677
|
+
return json(response, status, { error: error.message });
|
|
713
678
|
}
|
|
714
679
|
});
|
|
715
680
|
let closePromise;
|
|
716
681
|
const close = () => closePromise ??= (async () => {
|
|
717
682
|
closing = true;
|
|
718
683
|
clearTimeout(refreshTimer);
|
|
719
|
-
clearInterval(
|
|
684
|
+
clearInterval(commentTimer);
|
|
720
685
|
let primary;
|
|
721
686
|
for (const step of [
|
|
722
687
|
async () => { watcher?.close(); },
|
|
@@ -728,7 +693,6 @@ export async function startServer({
|
|
|
728
693
|
},
|
|
729
694
|
async () => { await writes; },
|
|
730
695
|
async () => { await buildStore?.close(); },
|
|
731
|
-
async () => { await Promise.allSettled([...activeReviews]); },
|
|
732
696
|
closeOverlays,
|
|
733
697
|
async () => { await viewerCache?.close(); },
|
|
734
698
|
]) {
|
package/src/service.mjs
CHANGED
|
@@ -4,7 +4,9 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { promisify } from 'node:util';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
8
|
import { defaultStateDirectory } from './hub/registry.mjs';
|
|
9
|
+
import { hubPublicOrigin } from './hub/project-link.mjs';
|
|
8
10
|
import { CliError } from './cli-output.mjs';
|
|
9
11
|
import { commandFailure } from './toolkit/results.mjs';
|
|
10
12
|
|
|
@@ -17,13 +19,14 @@ const unxml = value => value.replace(/&(amp|lt|gt|quot|apos);/g, (_, entity) =>
|
|
|
17
19
|
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'",
|
|
18
20
|
})[entity]);
|
|
19
21
|
|
|
20
|
-
export function renderLaunchAgent({ nodePath, cliPath, stateDirectory, port = 4310 }) {
|
|
22
|
+
export function renderLaunchAgent({ nodePath, cliPath, stateDirectory, port = 4310, publicOrigin }) {
|
|
21
23
|
const args = [nodePath, cliPath, 'serve', '--port', String(port), '--state-dir', stateDirectory];
|
|
24
|
+
const environment = publicOrigin ? `\n <key>EnvironmentVariables</key><dict>\n <key>ADG_PUBLIC_ORIGIN</key><string>${xml(publicOrigin)}</string>\n </dict>` : '';
|
|
22
25
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
23
26
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
24
27
|
<plist version="1.0"><dict>
|
|
25
28
|
<key>Label</key><string>${SERVICE_LABEL}</string>
|
|
26
|
-
<key>ProgramArguments</key><array>${args.map(arg => `<string>${xml(arg)}</string>`).join('')}</array
|
|
29
|
+
<key>ProgramArguments</key><array>${args.map(arg => `<string>${xml(arg)}</string>`).join('')}</array>${environment}
|
|
27
30
|
<key>RunAtLoad</key><true/>
|
|
28
31
|
<key>KeepAlive</key><true/>
|
|
29
32
|
<key>StandardOutPath</key><string>${xml(path.join(stateDirectory, 'service.stdout.log'))}</string>
|
|
@@ -36,6 +39,11 @@ function launchArguments(plist) {
|
|
|
36
39
|
const array = plist?.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? '';
|
|
37
40
|
return [...array.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(match => unxml(match[1]));
|
|
38
41
|
}
|
|
42
|
+
function launchPublicOrigin(plist) {
|
|
43
|
+
const environment = plist?.match(/<key>EnvironmentVariables<\/key>\s*<dict>([\s\S]*?)<\/dict>/)?.[1];
|
|
44
|
+
const value = environment?.match(/<key>ADG_PUBLIC_ORIGIN<\/key>\s*<string>([\s\S]*?)<\/string>/)?.[1];
|
|
45
|
+
return value === undefined ? undefined : unxml(value);
|
|
46
|
+
}
|
|
39
47
|
const readOptional = async file => {
|
|
40
48
|
try { return await readFile(file, 'utf8'); }
|
|
41
49
|
catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
|
|
@@ -56,7 +64,7 @@ function statusData(status, installedPlist, agentFile, stateDirectory) {
|
|
|
56
64
|
return { label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
|
|
57
65
|
state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
|
|
58
66
|
pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
|
|
59
|
-
plist: agentFile, stateDirectory,
|
|
67
|
+
plist: agentFile, stateDirectory, publicOrigin: launchPublicOrigin(installedPlist) ?? null,
|
|
60
68
|
logs: { stdout: path.join(stateDirectory, 'service.stdout.log'), stderr: path.join(stateDirectory, 'service.stderr.log') } };
|
|
61
69
|
}
|
|
62
70
|
|
|
@@ -142,8 +150,9 @@ export async function service(action, values = {}, {
|
|
|
142
150
|
if (!['install','uninstall','status','logs','migrate'].includes(action)) throw new CliError('USAGE_INVALID','Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
|
|
143
151
|
if (action === 'migrate') return migrateService(values,{home,run,nodePath,cliPath,uid,output});
|
|
144
152
|
const agentFile=path.join(home,'Library','LaunchAgents',`${SERVICE_LABEL}.plist`);
|
|
145
|
-
const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist)
|
|
146
|
-
const
|
|
153
|
+
const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist);
|
|
154
|
+
const argument = flag => installedArgs.includes(flag) ? installedArgs[installedArgs.indexOf(flag) + 1] : undefined;
|
|
155
|
+
const stateDirectory=path.resolve(values['state-dir'] ?? argument('--state-dir') ?? defaultStateDirectory);
|
|
147
156
|
const domain=`gui/${uid}`,target=`${domain}/${SERVICE_LABEL}`;
|
|
148
157
|
const stdout=path.join(stateDirectory,'service.stdout.log'),stderr=path.join(stateDirectory,'service.stderr.log');
|
|
149
158
|
if (action === 'logs') {
|
|
@@ -166,18 +175,43 @@ export async function service(action, values = {}, {
|
|
|
166
175
|
output(`Uninstalled ${SERVICE_LABEL}. State and logs retained in ${stateDirectory}.`);
|
|
167
176
|
return {data:{label:SERVICE_LABEL,plist:agentFile,stateDirectory,retained:true}};
|
|
168
177
|
}
|
|
169
|
-
const port=values.port
|
|
178
|
+
const port=Number(values.port ?? argument('--port') ?? 4310);
|
|
170
179
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 1 to 65535.');
|
|
171
|
-
|
|
180
|
+
const publicOrigin=hubPublicOrigin(values['public-origin'] ?? launchPublicOrigin(installedPlist),'--public-origin');
|
|
172
181
|
const executable=await realpath(nodePath),entry=await realpath(cliPath);
|
|
182
|
+
const plist=renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory,port,publicOrigin});
|
|
183
|
+
const previous=installedPlist === null ? null : await loadedJob(run,target);
|
|
184
|
+
if (previous !== null && installedPlist === plist) {
|
|
185
|
+
output(`${SERVICE_LABEL} is already installed and loaded.`);
|
|
186
|
+
return {data:{service:statusData(previous,plist,agentFile,stateDirectory),port}};
|
|
187
|
+
}
|
|
188
|
+
const bootstrap = async () => {
|
|
189
|
+
for (let attempt = 0;; attempt++) {
|
|
190
|
+
try { return await run('/bin/launchctl',['bootstrap',domain,agentFile]); }
|
|
191
|
+
catch (cause) {
|
|
192
|
+
// launchd can still be releasing the previous job after bootout returns.
|
|
193
|
+
if (previous === null || cause.code !== 5 || attempt === 5) throw cause;
|
|
194
|
+
await delay(100 * 2 ** attempt);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
};
|
|
173
198
|
await mkdir(path.dirname(agentFile),{recursive:true});await mkdir(stateDirectory,{recursive:true});
|
|
174
199
|
await Promise.all([stdout,stderr].map(file=>writeFile(file,'',{flag:'a'})));
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
200
|
+
if (previous !== null) await job(run,['bootout',target]);
|
|
201
|
+
try {
|
|
202
|
+
await writeFile(agentFile,plist);
|
|
203
|
+
await bootstrap();
|
|
204
|
+
}
|
|
178
205
|
catch (cause) {
|
|
179
|
-
|
|
180
|
-
|
|
206
|
+
let message=`Cannot install ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`;
|
|
207
|
+
try {
|
|
208
|
+
if (installedPlist === null) await rm(agentFile,{force:true});
|
|
209
|
+
else {
|
|
210
|
+
await writeFile(agentFile,installedPlist);
|
|
211
|
+
if (previous !== null) await bootstrap();
|
|
212
|
+
}
|
|
213
|
+
} catch (restore) { message += ` Could not restore the previous service: ${restore.message}`; }
|
|
214
|
+
throw new CliError('SERVICE_FAILED',message,{cause});
|
|
181
215
|
}
|
|
182
216
|
output(`Installed ${SERVICE_LABEL}. Logs: ${stdout} and ${stderr}.`);
|
|
183
217
|
return {data:{service:statusData(await loadedJob(run,target),plist,agentFile,stateDirectory),port}};
|
package/src/toolkit/arch.mjs
CHANGED
|
@@ -193,11 +193,12 @@ export async function buildArch(config,file,{snapshot,model:overlayModel,browser
|
|
|
193
193
|
const result=await renderArch(overlayModel??checked.model,tokenSource,{browser});
|
|
194
194
|
const legend=checked.classes.length?`<div class="arch-legend">${checked.classes.map(name=>`<span class="arch-key ${name}" style="--arch-color:var(--arch-${name})"><i class="arch-swatch"></i>${name}</span>`).join('')}</div>`:'';
|
|
195
195
|
const html=`<section data-adg-arch>${legend}${result.svg}</section>`;
|
|
196
|
-
const
|
|
196
|
+
const cssAfterTokens='\nhtml,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;width:max-content}';
|
|
197
|
+
const css=`${archStyles()}\n${tokenSource}${cssAfterTokens}`;
|
|
197
198
|
const note=[metadata.body,metadata.owners.length?`Owners: ${metadata.owners.join(', ')}`:'',metadata.status?`Status: ${metadata.status}`:''].filter(Boolean).join('\n');
|
|
198
199
|
const frame={frame:true,name:'default',html,note};
|
|
199
200
|
frame.document=theme=>`<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="default">${html}</div></body></html>`;
|
|
200
|
-
return {frames:[frame],css,imports:[],dependencies};
|
|
201
|
+
return {frames:[frame],css,cssAfterTokens,imports:[],dependencies};
|
|
201
202
|
}
|
|
202
203
|
|
|
203
204
|
// Executed in the same Chromium page as ordinary frame checks. Bounds are in
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isFeatureEntry, sourceFeature } from './project.mjs';
|
|
1
|
+
import { isFeatureEntry, isFeatureInternal, sourceFeature } from './project.mjs';
|
|
2
2
|
|
|
3
3
|
// Production sources are ordered from lower to higher layers. Studies are explorations.
|
|
4
4
|
export function importDirectionViolations(graph, sources, { strictLayers = false } = {}) {
|
|
@@ -51,3 +51,26 @@ export function singleConsumerComponents(graph, sources, partsBySource) {
|
|
|
51
51
|
}
|
|
52
52
|
return warnings;
|
|
53
53
|
}
|
|
54
|
+
|
|
55
|
+
/** Chapter guidance never changes the check verdict. Paths are design-relative. */
|
|
56
|
+
export function chapterWarnings(files, groups, sources) {
|
|
57
|
+
const production = sources.filter(source => source !== 'studies');
|
|
58
|
+
const requiredLayers = new Set(production.slice(0, Math.min(2, production.length - 1)));
|
|
59
|
+
files = files.filter(file => !isFeatureInternal(file, sources));
|
|
60
|
+
const inventory = new Set(files);
|
|
61
|
+
const assigned = new Set(groups.flatMap(group => group.assets));
|
|
62
|
+
const missing = files.filter(file => requiredLayers.has(file.split('/')[0]) && !assigned.has(file)).sort();
|
|
63
|
+
const warnings = [];
|
|
64
|
+
if (missing.length) warnings.push({
|
|
65
|
+
code: 'CHAPTER_SOURCES_UNASSIGNED', count: missing.length, paths: missing,
|
|
66
|
+
message: `${missing.length} component/module sources have no gallery.json chapter: ${missing.join(', ')}.`, next: [],
|
|
67
|
+
});
|
|
68
|
+
for (const group of groups) {
|
|
69
|
+
const paths = [...new Set(group.assets.filter(source => inventory.has(source)))];
|
|
70
|
+
if (paths.length > 12) warnings.push({
|
|
71
|
+
code: 'CHAPTER_TOO_LARGE', chapter: group.title, count: paths.length, paths,
|
|
72
|
+
message: `Chapter "${group.title}" has ${paths.length} sources; split it into feature chapters of about 3 to 12 sources.`, next: [],
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return warnings;
|
|
76
|
+
}
|
package/src/toolkit/commands.mjs
CHANGED
|
@@ -2,14 +2,15 @@ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { availableParallelism } from 'node:os';
|
|
4
4
|
import { buildSource } from './build.mjs';
|
|
5
|
-
import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems } from './project.mjs';
|
|
6
|
-
import { importDirectionViolations, singleConsumerComponents } from './asset-rules.mjs';
|
|
5
|
+
import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems, readGroups, listSources } from './project.mjs';
|
|
6
|
+
import { importDirectionViolations, singleConsumerComponents, chapterWarnings } from './asset-rules.mjs';
|
|
7
7
|
import { launch, loadFrame, browserTask } from './browser.mjs';
|
|
8
8
|
import { CliError, classifyError } from '../cli-output.mjs';
|
|
9
9
|
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
10
10
|
import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
|
|
11
11
|
import { withImpacted } from './impact-selection.mjs';
|
|
12
12
|
import { mappingFacts, frameOwners } from './source-facts.mjs';
|
|
13
|
+
import { resolveThemes, systemTheme } from './theme.mjs';
|
|
13
14
|
|
|
14
15
|
function frameStructure(frame) {
|
|
15
16
|
return frame.html
|
|
@@ -220,6 +221,11 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
220
221
|
else warnings.push(classifyError(failure).error);
|
|
221
222
|
};
|
|
222
223
|
try {
|
|
224
|
+
const directories = sourceDirectories(config);
|
|
225
|
+
const chapterFiles = listSources(config.design, directories).map(file => path.relative(config.design, file).split(path.sep).join('/'));
|
|
226
|
+
const chapters = chapterWarnings(chapterFiles, readGroups(config.design, directories), directories);
|
|
227
|
+
warnings.push(...chapters);
|
|
228
|
+
if (!options.json) for (const warning of chapters) log(`WARNING ${warning.message}`);
|
|
223
229
|
const mapping = await loadImplementationMap(config);
|
|
224
230
|
const files = session ? session.sources.map(source => path.join(config.root, source)).filter(existsSync) : selectSources(config, args, { write });
|
|
225
231
|
data.sources = files.map(file => relative(config, file));
|
|
@@ -340,21 +346,20 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
340
346
|
} finally { if (browser) await cleanup(() => browser.close(), primary); }
|
|
341
347
|
}
|
|
342
348
|
|
|
343
|
-
export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session } = {}) {
|
|
349
|
+
export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session, readSystemTheme = systemTheme } = {}) {
|
|
350
|
+
const themes = resolveThemes(options.theme, readSystemTheme);
|
|
351
|
+
options = { ...options, theme: themes.length === 2 ? 'both' : themes[0] };
|
|
344
352
|
if (options.impacted && !session) return withImpacted(config, args, options, 'render', selected =>
|
|
345
353
|
render(config, args, options, log, { launchBrowser, session: selected }));
|
|
346
354
|
const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
|
|
347
355
|
/** @type {import('./results.mjs').RenderData} */
|
|
348
|
-
const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, captures: [], deleted: [] };
|
|
356
|
+
const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, themes, captures: [], deleted: [] };
|
|
349
357
|
const warnings = [], completed = [], failures = [];
|
|
350
358
|
let browser, primary;
|
|
351
359
|
try {
|
|
352
360
|
const scale = Number(options.scale ?? 2);
|
|
353
361
|
if (!(Number.isFinite(scale) && scale > 0)) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number');
|
|
354
|
-
const themeOption = options.theme ?? 'both';
|
|
355
|
-
if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
|
|
356
362
|
if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
|
|
357
|
-
const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
|
|
358
363
|
let base, additional = [];
|
|
359
364
|
if (!session && options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
|
|
360
365
|
const git = await import('./arch-git.mjs');
|