@whzxc/agent-design-gallery 0.6.0 → 0.7.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 +2 -0
- package/package.json +1 -1
- package/public/app.js +38 -10
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +16 -4
- package/public/layout.js +29 -13
- package/src/cli-output.mjs +236 -0
- package/src/cli.mjs +113 -42
- package/src/http.mjs +1 -0
- package/src/hub/auth.mjs +2 -1
- package/src/hub/proxy.mjs +5 -3
- package/src/hub/registry.mjs +57 -23
- package/src/hub.mjs +36 -21
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +10 -9
- package/src/open.mjs +58 -54
- package/src/perf.mjs +12 -0
- package/src/server.mjs +78 -41
- package/src/service.mjs +115 -94
- package/src/toolkit/arch-git.mjs +8 -7
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +24 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +16 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +18 -17
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/tokens.mjs +5 -4
package/src/link.mjs
CHANGED
|
@@ -1,28 +1,29 @@
|
|
|
1
|
+
import { CliError } from './cli-output.mjs';
|
|
1
2
|
import { readViewRoute, viewURL, viewerBase } from '../public/view-route.js';
|
|
2
3
|
|
|
3
4
|
export function previewTarget(options) {
|
|
4
5
|
const { asset, frame, group, layer, tokens, base, mode = 'query' } = options;
|
|
5
|
-
if (!['path', 'query'].includes(mode)) throw
|
|
6
|
+
if (!['path', 'query'].includes(mode)) throw new CliError('USAGE_INVALID', 'Choose --mode=path or --mode=query.');
|
|
6
7
|
const targets = [asset, group, layer, tokens].filter(value => value !== undefined && value !== false);
|
|
7
8
|
if (targets.length > 1 || (frame !== undefined && !asset) || targets.some(value => value === '') || frame === '')
|
|
8
|
-
throw
|
|
9
|
+
throw new CliError('USAGE_INVALID', 'Choose one of --asset, --group, --layer, or --tokens. --frame needs --asset.');
|
|
9
10
|
if (asset && (!/\.(tsx|svg|mmd)$/i.test(asset) || asset.includes('\\') || asset.split('/').some(part => !part || part === '.' || part === '..')))
|
|
10
|
-
throw
|
|
11
|
-
if (tokens && mode === 'path') throw
|
|
12
|
-
if(base!==undefined && !base.trim())throw
|
|
11
|
+
throw new CliError('USAGE_INVALID', 'Use a design-relative .tsx/.svg or project-root-relative .mmd file path for --asset.');
|
|
12
|
+
if (tokens && mode === 'path') throw new CliError('USAGE_INVALID', 'Use --mode=query for --tokens.');
|
|
13
|
+
if(base!==undefined && !base.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
|
|
13
14
|
return { asset, frame, group, layer, tokens, mode, ...(base!==undefined?{base}:{}) };
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
export function previewURL(input, target) {
|
|
17
18
|
let base;
|
|
18
19
|
try { base = new URL(input); }
|
|
19
|
-
catch { throw
|
|
20
|
+
catch { throw new CliError('USAGE_INVALID', 'Enter an absolute ADG viewer URL.'); }
|
|
20
21
|
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password)
|
|
21
|
-
throw
|
|
22
|
+
throw new CliError('USAGE_INVALID', 'Enter an HTTP or HTTPS viewer URL without credentials.');
|
|
22
23
|
const pathname = base.pathname.replace(/^(\/(?:p|i)\/[A-Za-z0-9_-]+)$/, '$1/');
|
|
23
24
|
const root = viewerBase(pathname);
|
|
24
25
|
if (pathname !== root && !pathname.startsWith(`${root}view/`) && pathname !== `${root}index.html`)
|
|
25
|
-
throw
|
|
26
|
+
throw new CliError('USAGE_INVALID', 'Use a direct viewer, hub project, or live instance URL.');
|
|
26
27
|
const previous = target.asset || target.group || target.layer || target.tokens ? null : readViewRoute(base);
|
|
27
28
|
const [kind, ...name] = (previous?.scope ?? '').split(':');
|
|
28
29
|
const key = name.join(':');
|
|
@@ -37,7 +38,7 @@ export function previewURL(input, target) {
|
|
|
37
38
|
const revision=target.base ?? base.searchParams.get('base');
|
|
38
39
|
base.search = base.hash = '';
|
|
39
40
|
if(revision!==null && revision!==undefined)base.searchParams.set('base',revision);
|
|
40
|
-
if (tokens && mode === 'path') throw
|
|
41
|
+
if (tokens && mode === 'path') throw new CliError('USAGE_INVALID', 'Use --mode=query for --tokens.');
|
|
41
42
|
if (tokens) return viewURL(base, 'tokens');
|
|
42
43
|
if (mode === 'query') {
|
|
43
44
|
if (asset) base.searchParams.set('asset', asset);
|
package/src/open.mjs
CHANGED
|
@@ -1,57 +1,61 @@
|
|
|
1
|
-
import { spawn } from
|
|
2
|
-
import { loadConfig } from
|
|
3
|
-
import { registerInstance } from
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { loadConfig } from './toolkit/config.mjs';
|
|
3
|
+
import { registerInstance } from './hub/instances.mjs';
|
|
4
|
+
import { defaultStateDirectory } from './hub/registry.mjs';
|
|
5
|
+
import { existsSync, unlinkSync } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { startServer } from './server.mjs';
|
|
7
8
|
import { previewTarget, previewURL } from './link.mjs';
|
|
9
|
+
import { CliError, asCliError, sanitize } from './cli-output.mjs';
|
|
10
|
+
import { cleanup } from './toolkit/results.mjs';
|
|
8
11
|
|
|
9
|
-
export async function open(positionals, values
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
);
|
|
56
|
-
|
|
12
|
+
export async function open(positionals, values, {
|
|
13
|
+
cwd = process.cwd(), startViewer = startServer, register = registerInstance, spawnBrowser = spawn,
|
|
14
|
+
onDiagnostic, onFatal,
|
|
15
|
+
} = {}) {
|
|
16
|
+
if (positionals.length > 1) throw new CliError('USAGE_INVALID','Expected one directory. Run adg --help.');
|
|
17
|
+
const target = previewTarget(values), port = values.port === undefined ? 0 : Number(values.port);
|
|
18
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 0 to 65535.');
|
|
19
|
+
const input = path.resolve(cwd,positionals[0] ?? '.');
|
|
20
|
+
const config = await loadConfig(input);
|
|
21
|
+
if (values.base !== undefined && (!target.asset || target.asset.endsWith('.mmd'))) await (await import('./toolkit/arch-git.mjs')).resolveBase(config,values.base);
|
|
22
|
+
const directory = config.root === input && existsSync(config.design) ? config.design : input;
|
|
23
|
+
const stateDirectory = path.resolve(cwd,values['state-dir'] ?? defaultStateDirectory);
|
|
24
|
+
const server = await startViewer({directory,port,stateDirectory,onDiagnostic,onFatal});
|
|
25
|
+
let instance;
|
|
26
|
+
try { instance = await register({directory:server.directory,port:server.port,id:server.id,stateDirectory}); }
|
|
27
|
+
catch (cause) {
|
|
28
|
+
const primary = asCliError(cause);
|
|
29
|
+
await cleanup(() => server.close(),primary);
|
|
30
|
+
throw primary;
|
|
31
|
+
}
|
|
32
|
+
const exitCleanup = () => { try { unlinkSync(instance.file); } catch {} };
|
|
33
|
+
process.once('exit',exitCleanup);
|
|
34
|
+
const url = previewURL(server.url,target).href;
|
|
35
|
+
let closing;
|
|
36
|
+
return {
|
|
37
|
+
id:server.id,url,port:server.port,directory:server.directory,stateDirectory,
|
|
38
|
+
close() {
|
|
39
|
+
return closing ??= (async () => {
|
|
40
|
+
let primary;
|
|
41
|
+
try { await server.close(); }
|
|
42
|
+
catch (cause) { primary = new CliError('SHUTDOWN_FAILED',cause.message,{cause}); }
|
|
43
|
+
try { await cleanup(() => instance.remove(),primary); }
|
|
44
|
+
catch (cause) { primary = cause; }
|
|
45
|
+
finally { process.off('exit',exitCleanup); }
|
|
46
|
+
if (primary) throw primary;
|
|
47
|
+
})();
|
|
48
|
+
},
|
|
49
|
+
openBrowser() {
|
|
50
|
+
if (values['no-open']) return;
|
|
51
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32.exe' : 'xdg-open';
|
|
52
|
+
const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler',url] : [url];
|
|
53
|
+
const warn=()=>{
|
|
54
|
+
const diagnostic={code:'BROWSER_OPEN_FAILED',message:`Open ${url} in your browser.`,next:[]};
|
|
55
|
+
if(onDiagnostic)onDiagnostic(diagnostic);else console.error(sanitize(diagnostic.message));
|
|
56
|
+
};
|
|
57
|
+
try {const child=spawnBrowser(command,args,{stdio:'ignore',detached:true});child.on('error',warn);child.unref();}
|
|
58
|
+
catch {warn();}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
57
61
|
}
|
package/src/perf.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { appendFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
// Opt-in local diagnostics. Epoch timestamps align Node and browser spans.
|
|
4
|
+
const destination = process.env.ADG_PERF_LOG;
|
|
5
|
+
export function perfSpan(phase, source, detail = {}) {
|
|
6
|
+
if (!destination) return;
|
|
7
|
+
const start = performance.timeOrigin + performance.now();
|
|
8
|
+
return (extra = {}) => appendFileSync(destination, JSON.stringify({
|
|
9
|
+
phase, source, start, end: performance.timeOrigin + performance.now(),
|
|
10
|
+
pid: process.pid, ...detail, ...extra,
|
|
11
|
+
}) + '\n');
|
|
12
|
+
}
|
package/src/server.mjs
CHANGED
|
@@ -13,8 +13,11 @@ import {
|
|
|
13
13
|
import { watch, existsSync } from "node:fs";
|
|
14
14
|
import path from "node:path";
|
|
15
15
|
import os from "node:os";
|
|
16
|
+
import { perfSpan } from './perf.mjs';
|
|
16
17
|
|
|
17
18
|
import { createBuildStore } from './toolkit/build-store.mjs';
|
|
19
|
+
import { CliError, asCliError } from './cli-output.mjs';
|
|
20
|
+
import { cleanup } from './toolkit/results.mjs';
|
|
18
21
|
import { createViewerCache } from './viewer-cache.mjs';
|
|
19
22
|
import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories } from './toolkit/project.mjs';
|
|
20
23
|
import { loadConfig } from './toolkit/config.mjs';
|
|
@@ -27,7 +30,7 @@ function tokenSourcePath(directory, project) {
|
|
|
27
30
|
const base = project.design === directory ? project.root : path.dirname(directory);
|
|
28
31
|
return path.relative(base, path.join(directory, tokenFile)).split(path.sep).join('/');
|
|
29
32
|
}
|
|
30
|
-
const viewerVersion = Promise.all(['assets.js','layout.js','selection.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
|
|
33
|
+
const viewerVersion = Promise.all(['assets.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
|
|
31
34
|
const defaultState = path.join(
|
|
32
35
|
process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local/state"),
|
|
33
36
|
"agent-design-gallery",
|
|
@@ -39,14 +42,16 @@ export async function startServer({
|
|
|
39
42
|
fixtures = null,
|
|
40
43
|
readOnly = false,
|
|
41
44
|
instanceId = randomUUID(),
|
|
45
|
+
onDiagnostic, onFatal, watchDirectory = watch,
|
|
42
46
|
} = {}) {
|
|
47
|
+
const endStartup = perfSpan('viewer-startup');
|
|
43
48
|
let state = { recent: [], views: {}, selections: {}, theme: "system" };
|
|
44
49
|
const statePath = path.join(stateDirectory, "state.json");
|
|
45
50
|
try {
|
|
46
51
|
state = { ...state, ...JSON.parse(await readFile(statePath, "utf8")) };
|
|
47
52
|
} catch (e) {
|
|
48
53
|
if (e.code !== "ENOENT")
|
|
49
|
-
throw new
|
|
54
|
+
throw new CliError(e instanceof SyntaxError ? 'STATE_INVALID' : 'IO_FAILED', `Cannot read preferences: ${e.message}`, { cause: e });
|
|
50
55
|
}
|
|
51
56
|
let root,
|
|
52
57
|
tokenSource = null,
|
|
@@ -82,6 +87,20 @@ export async function startServer({
|
|
|
82
87
|
for (const client of clients)
|
|
83
88
|
client.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
84
89
|
};
|
|
90
|
+
const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
|
|
91
|
+
if (error.name === 'AbortError') return;
|
|
92
|
+
const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
|
|
93
|
+
const source = name && activeProject ? (name.endsWith('.mmd') ? name : path.relative(activeProject.root,path.join(root,name)).split(path.sep).join('/')) : null;
|
|
94
|
+
onDiagnostic?.(asCliError(error,fallback),source ? {source,frame:null,theme:null,line:Number.isInteger(at?.line)&&at.line>0?at.line:null,column:Number.isInteger(at?.column)?at.column+1:null} : null);
|
|
95
|
+
};
|
|
96
|
+
const refreshError = error => {
|
|
97
|
+
if (error.name === 'AbortError') return;
|
|
98
|
+
emit({error:error.message}); diagnostic(error,null,'WATCH_FAILED');
|
|
99
|
+
};
|
|
100
|
+
const watcherError = (error,kind) => {
|
|
101
|
+
const failure = new CliError('WATCH_FAILED',`${kind} watcher: ${error.message}`,{cause:error});
|
|
102
|
+
emit({error:failure.message}); onFatal?.(failure);
|
|
103
|
+
};
|
|
85
104
|
async function closeOverlays() {
|
|
86
105
|
resettingOverlays = true;
|
|
87
106
|
try { await Promise.all([...overlayStores.values()].map(async pending=>(await pending).close())); }
|
|
@@ -107,7 +126,9 @@ export async function startServer({
|
|
|
107
126
|
return [...affected];
|
|
108
127
|
}
|
|
109
128
|
async function overlayBuild(name,base) {
|
|
110
|
-
|
|
129
|
+
let built;
|
|
130
|
+
try { built=await (await overlayStore(base)).get(name); }
|
|
131
|
+
catch(error) { diagnostic(error,name); throw error; }
|
|
111
132
|
overlayHashes.add(built.hash);frameCounts.set(name,built.frames.length);
|
|
112
133
|
return built;
|
|
113
134
|
}
|
|
@@ -155,25 +176,25 @@ export async function startServer({
|
|
|
155
176
|
archWatcher?.close();archWatcher=null;
|
|
156
177
|
const directory=project.archDirectory;
|
|
157
178
|
if(project.design!==base || !directory || !existsSync(directory)) return;
|
|
158
|
-
archWatcher=
|
|
179
|
+
archWatcher=watchDirectory(directory,{recursive:true},(_event,filename)=>{
|
|
159
180
|
if(!filename || !/\.(mmd|md)$/.test(String(filename)))return;
|
|
160
181
|
const file=path.join(directory,String(filename));
|
|
161
182
|
const dependency=path.relative(base,file).split(path.sep).join('/');
|
|
162
183
|
const name=path.relative(project.root,file).split(path.sep).join('/');
|
|
163
|
-
touched.add(dependency);touched.add(name);invalidateBuilds([dependency,name]).catch(
|
|
164
|
-
clearTimeout(refreshTimer);refreshTimer=setTimeout(()=>refresh().catch(
|
|
184
|
+
touched.add(dependency);touched.add(name);invalidateBuilds([dependency,name]).catch(refreshError);
|
|
185
|
+
clearTimeout(refreshTimer);refreshTimer=setTimeout(()=>refresh().catch(refreshError),80);
|
|
165
186
|
});
|
|
166
|
-
archWatcher.on('error',e=>
|
|
187
|
+
archWatcher.on('error',e=>watcherError(e,'Architecture'));
|
|
167
188
|
}
|
|
168
189
|
async function openDirectory(input) {
|
|
169
190
|
let next;
|
|
170
191
|
try { next = await realpath(path.resolve(input.replace(/^~(?=$|[\\/])/, os.homedir()))); }
|
|
171
192
|
catch (error) {
|
|
172
|
-
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new
|
|
193
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new CliError('DIRECTORY_NOT_FOUND', `Directory not found: ${input}; choose an existing directory.`, { cause: error });
|
|
173
194
|
throw error;
|
|
174
195
|
}
|
|
175
196
|
if (!(await stat(next)).isDirectory())
|
|
176
|
-
throw new
|
|
197
|
+
throw new CliError('DIRECTORY_NOT_FOUND', "Choose a directory containing SVG files.");
|
|
177
198
|
const hasTokens = (await readdir(next)).includes(tokenFile);
|
|
178
199
|
if (hasTokens && !readOnly) refreshTypes({design:next});
|
|
179
200
|
const project = await loadConfig(next);
|
|
@@ -190,21 +211,21 @@ export async function startServer({
|
|
|
190
211
|
if(nextFiles.has(built.path)) {knownBuilds.set(built.path,built);Object.assign(nextFiles.get(built.path),{hash:built.hash,version:built.hash});frameCounts.set(built.path,built.frames.length);}
|
|
191
212
|
}
|
|
192
213
|
// Complete discovery before starting the watcher.
|
|
193
|
-
const nextWatcher =
|
|
214
|
+
const nextWatcher = watchDirectory(next, { recursive: true }, (_event, filename) => {
|
|
194
215
|
if (filename && String(filename).split(path.sep).some(part => part.startsWith("."))) return;
|
|
195
216
|
if (filename) {
|
|
196
217
|
const name=String(filename).split(path.sep).join('/');
|
|
197
218
|
touched.add(name);
|
|
198
|
-
invalidateBuilds([name]).catch(
|
|
219
|
+
invalidateBuilds([name]).catch(refreshError);
|
|
199
220
|
}
|
|
200
221
|
clearTimeout(refreshTimer);
|
|
201
222
|
refreshTimer = setTimeout(
|
|
202
|
-
() => refresh().catch(
|
|
223
|
+
() => refresh().catch(refreshError),
|
|
203
224
|
80,
|
|
204
225
|
);
|
|
205
226
|
});
|
|
206
227
|
nextWatcher.on("error", (e) =>
|
|
207
|
-
|
|
228
|
+
watcherError(e,'File'),
|
|
208
229
|
);
|
|
209
230
|
watcher?.close();
|
|
210
231
|
watcher = nextWatcher;
|
|
@@ -334,6 +355,7 @@ export async function startServer({
|
|
|
334
355
|
result.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
|
|
335
356
|
} catch (error) {
|
|
336
357
|
result.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
|
|
358
|
+
diagnostic(new CliError('TOKENS_INVALID',error.message,{cause:error}));
|
|
337
359
|
}
|
|
338
360
|
return applyFixtureManifest(result, url.searchParams.get('fixture'));
|
|
339
361
|
}
|
|
@@ -385,8 +407,10 @@ export async function startServer({
|
|
|
385
407
|
return applyFixtureManifest(data,url.searchParams.get('fixture'));
|
|
386
408
|
}
|
|
387
409
|
async function sourceBuild(name) {
|
|
410
|
+
const endBuild = perfSpan('build', name);
|
|
388
411
|
let built;
|
|
389
|
-
try{built=await buildStore.get(name);}catch(error){if(error.name!=='AbortError')failedSources.add(name);throw error;}
|
|
412
|
+
try{built=await buildStore.get(name);}catch(error){if(error.name!=='AbortError'){failedSources.add(name);diagnostic(error,name);}throw error;}
|
|
413
|
+
finally {endBuild?.();}
|
|
390
414
|
knownBuilds.set(name,describe(built));dirtyBuilds.delete(name);failedSources.delete(name);frameCounts.set(name,built.frames.length);
|
|
391
415
|
if(files.has(name))Object.assign(files.get(name),{hash:built.hash,version:built.hash});
|
|
392
416
|
return built;
|
|
@@ -402,7 +426,7 @@ export async function startServer({
|
|
|
402
426
|
if (/\.(tsx|mmd)$/.test(name)) {
|
|
403
427
|
const built=base&&name.endsWith('.mmd')?await overlayBuild(name,base):await sourceBuild(name);
|
|
404
428
|
const frames = onlyFrame ? built.frames.filter(frame => frame.name === onlyFrame) : built.frames;
|
|
405
|
-
if (!frames.length && onlyFrame) throw
|
|
429
|
+
if (!frames.length && onlyFrame) throw new CliError('FRAME_NOT_FOUND', `Frame ${onlyFrame} does not exist in ${name}.`);
|
|
406
430
|
return {version:built.hash,imports:built.imports,dependencies:built.dependencies,
|
|
407
431
|
body:JSON.stringify({format:'tsx',hash:built.hash,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
|
|
408
432
|
}
|
|
@@ -600,40 +624,53 @@ export async function startServer({
|
|
|
600
624
|
});
|
|
601
625
|
response.end(request.method === "HEAD" ? undefined : content);
|
|
602
626
|
} catch (error) {
|
|
627
|
+
if (response.destroyed) return;
|
|
603
628
|
response.writeHead(error.name==='AbortError'?409:400, { "Content-Type": "application/json" });
|
|
604
629
|
response.end(JSON.stringify({ error: error.message }));
|
|
605
630
|
}
|
|
606
631
|
});
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
632
|
+
let closePromise;
|
|
633
|
+
const close = () => closePromise ??= (async () => {
|
|
634
|
+
closing = true;
|
|
635
|
+
clearTimeout(refreshTimer);
|
|
636
|
+
let primary;
|
|
637
|
+
for (const step of [
|
|
638
|
+
async () => { watcher?.close(); },
|
|
639
|
+
async () => { archWatcher?.close(); },
|
|
640
|
+
async () => {
|
|
641
|
+
for (const client of clients) client.end();
|
|
642
|
+
const disconnected = server.listening ? new Promise(resolve => server.close(resolve)) : Promise.resolve();
|
|
643
|
+
server.closeAllConnections(); await disconnected;
|
|
644
|
+
},
|
|
645
|
+
async () => { await writes; },
|
|
646
|
+
async () => { await buildStore?.close(); },
|
|
647
|
+
closeOverlays,
|
|
648
|
+
async () => { await viewerCache?.close(); },
|
|
649
|
+
]) {
|
|
650
|
+
try { await cleanup(step,primary); }
|
|
651
|
+
catch (error) { primary=error; }
|
|
613
652
|
}
|
|
614
|
-
|
|
653
|
+
if (primary) throw primary;
|
|
654
|
+
})();
|
|
615
655
|
try {
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
server.
|
|
656
|
+
if (directory) await openDirectory(directory);
|
|
657
|
+
await new Promise((resolve,reject) => {
|
|
658
|
+
const startupError = error => { server.off('listening',listening); reject(error); };
|
|
659
|
+
const listening = () => {
|
|
660
|
+
server.off('error',startupError);
|
|
661
|
+
server.on('error',error => { if (!closing) onFatal?.(asCliError(error)); });
|
|
662
|
+
resolve();
|
|
663
|
+
};
|
|
664
|
+
server.once('error',startupError);
|
|
665
|
+
server.listen(port,'127.0.0.1',listening);
|
|
619
666
|
});
|
|
620
|
-
} catch (
|
|
621
|
-
|
|
622
|
-
|
|
667
|
+
} catch (cause) {
|
|
668
|
+
const primary=asCliError(cause);
|
|
669
|
+
await cleanup(close,primary);
|
|
670
|
+
throw primary;
|
|
623
671
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
closing = true;
|
|
627
|
-
clearTimeout(refreshTimer);
|
|
628
|
-
watcher?.close();archWatcher?.close();
|
|
629
|
-
for (const c of clients) c.end();
|
|
630
|
-
const disconnected = new Promise(resolve => server.close(resolve));
|
|
631
|
-
server.closeAllConnections();
|
|
632
|
-
await disconnected;
|
|
633
|
-
await writes;
|
|
634
|
-
await buildStore?.close();await closeOverlays();await viewerCache?.close();
|
|
635
|
-
};
|
|
636
|
-
return { id: instanceId, directory: root, url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
|
|
672
|
+
endStartup?.();
|
|
673
|
+
return { id: instanceId, directory: root, stateDirectory:path.resolve(stateDirectory), url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
|
|
637
674
|
cacheStats:()=>({builds:buildStore?.stats(),viewer:viewerCache?.stats()}),
|
|
638
675
|
stats: () => {
|
|
639
676
|
const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name));
|