@stillwind/analysis 0.3.0 → 0.4.1

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/dist/browser.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as WorkspaceEditorResult, i as AnalysisWorkspaceService, l as WorkspaceResult } from "./workspace-kE7AGW0k.js";
1
+ import { c as WorkspaceEditorResult, i as AnalysisWorkspaceService, l as WorkspaceResult } from "./workspace-DIADkpZF.js";
2
2
  import { AnalysisProjectConfig } from "@stillwind/config";
3
3
  import { BrowserModuleCss, BrowserProject, BrowserStylesheetOutput, EditorRequest, PluginHost } from "@stillwind/host/browser";
4
4
  /**
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as DiscoverWorkspace, c as WorkspaceEditorResult, i as AnalysisWorkspaceService, l as WorkspaceResult, n as AnalysisResult, o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext, s as OpenWorkspaces, t as AnalysisDependency } from "./workspace-kE7AGW0k.js";
2
- import { t as lintReports } from "./reports-C5F8xxeQ.js";
3
- import { EditorRequest, EditorResult } from "@stillwind/host";
4
- export { type AnalysisDependency, type AnalysisResult, type AnalysisWorkspaceContext, type AnalysisWorkspaceService, type DiscoverWorkspace, type EditorRequest, type EditorResult, type OpenAnalysisWorkspaces, type OpenWorkspaces, type WorkspaceEditorResult, type WorkspaceResult, lintReports };
1
+ import { a as DiscoverWorkspace, c as WorkspaceEditorResult, i as AnalysisWorkspaceService, l as WorkspaceResult, n as AnalysisResult, o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext, s as OpenWorkspaces, t as AnalysisDependency } from "./workspace-DIADkpZF.js";
2
+ import { t as lintReports } from "./reports-BI3wqUUD.js";
3
+ import { DesignCandidate, DesignSystemRequest, DesignToken, DesignTokenSource, EditorRequest, EditorResult } from "@stillwind/host";
4
+ export { type AnalysisDependency, type AnalysisResult, type AnalysisWorkspaceContext, type AnalysisWorkspaceService, type DesignCandidate, type DesignSystemRequest, type DesignToken, type DesignTokenSource, type DiscoverWorkspace, type EditorRequest, type EditorResult, type OpenAnalysisWorkspaces, type OpenWorkspaces, type WorkspaceEditorResult, type WorkspaceResult, lintReports };
package/dist/memory.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as AnalysisWorkspaceService, n as AnalysisResult } from "./workspace-kE7AGW0k.js";
1
+ import { i as AnalysisWorkspaceService, n as AnalysisResult } from "./workspace-DIADkpZF.js";
2
2
  /** Compiler input captured from URI documents before asynchronous compilation starts. */
3
3
  export interface MemoryAnalysisInput {
4
4
  /** Requested target URI accepted by the embedding's includes callback. */
package/dist/node.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext } from "./workspace-kE7AGW0k.js";
2
- import { t as lintReports } from "./reports-C5F8xxeQ.js";
3
- import { AnalysisWorkspace, EditorEdit, WorkspaceResult } from "@stillwind/host";
1
+ import { o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext } from "./workspace-DIADkpZF.js";
2
+ import { t as lintReports } from "./reports-BI3wqUUD.js";
3
+ import { AnalysisWorkspace, DesignCandidate, DesignSystemRequest, DesignToken, EditorEdit, WorkspaceResult } from "@stillwind/host";
4
4
  /** Original buffer and ranges excluded by a formatter adapter. Paths are absolute. */
5
5
  interface RewriteInput {
6
6
  /** Absolute target path used for workspace membership and dependency resolution. */
@@ -67,6 +67,114 @@ export declare function format(options?: RewriteOptions & {
67
67
  /** Whether to report changes without saving them. Defaults to false. */
68
68
  check?: boolean;
69
69
  }): Promise<FormatResult>;
70
+ /**
71
+ * Design-system answers from every project of one configuration.
72
+ */
73
+ interface DesignSystemAnswer {
74
+ /** Absolute path of the evaluated configuration. */
75
+ config: string;
76
+ /** Tokens in project and name order. */
77
+ tokens: (DesignToken & {
78
+ /** Zero-based project index in the evaluated configuration. */
79
+ project: number;
80
+ })[];
81
+ /** Candidates in project order. */
82
+ candidates: (DesignCandidate & {
83
+ /** Zero-based project index in the evaluated configuration. */
84
+ project: number;
85
+ })[];
86
+ /** Targets without a match in any project. */
87
+ unmatched: string[];
88
+ }
89
+ /**
90
+ * Answers a question about each project's design system in a child process.
91
+ *
92
+ * @param options - Configuration discovery. Target globs do not apply.
93
+ * @param request - Theme, utility, or variant request.
94
+ * @returns Answers from every project. Unknown names and unmatched targets are data.
95
+ * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.
96
+ */
97
+ export declare function designSystem(options: Omit<RewriteOptions, "patterns">, request: DesignSystemRequest): Promise<DesignSystemAnswer>;
98
+ /**
99
+ * Selects generated CSS by file, line, or position.
100
+ */
101
+ interface InspectTarget {
102
+ /** Path or glob accepted by target selection. */
103
+ pattern: string;
104
+ /** One-based line. Omission selects the whole file. */
105
+ line?: number;
106
+ /** One-based UTF-16 column. It requires line. */
107
+ column?: number;
108
+ }
109
+ /**
110
+ * Generated CSS for one source range in one project.
111
+ */
112
+ interface InspectPreview {
113
+ /** Zero-based project index in the evaluated configuration. */
114
+ project: number;
115
+ /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */
116
+ location: {
117
+ uri: string;
118
+ startLine: number;
119
+ startColumn: number;
120
+ endLine: number;
121
+ endColumn: number;
122
+ };
123
+ /** Original source text in the range. */
124
+ source: string;
125
+ /** Formatted CSS. It is empty for a failed occurrence or a marker class. */
126
+ css: string;
127
+ /** False when diagnostics contains an error, or when a required style failed. */
128
+ valid: boolean;
129
+ /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */
130
+ diagnostics: {
131
+ /** Report severity, as in the reports of lint. */
132
+ severity: string;
133
+ /** Stable compiler code or lint rule. */
134
+ code: string;
135
+ /** Description of the finding. */
136
+ message: string;
137
+ }[];
138
+ /** Markdown for a marker class. */
139
+ documentation?: string;
140
+ /** Authored runtime key expressions that the CSS depends on. */
141
+ runtimeNames?: string[];
142
+ }
143
+ /**
144
+ * A target that could not be read.
145
+ */
146
+ interface InspectFailure {
147
+ /** Absolute path of the target. */
148
+ file: string;
149
+ /** Reason for the failure. */
150
+ message: string;
151
+ }
152
+ /**
153
+ * Inspection results with analysis outcomes retained for each project.
154
+ */
155
+ interface InspectResult {
156
+ /** Absolute path of the evaluated configuration. */
157
+ config: string;
158
+ /** Analysis of each selected file, in file and project order. */
159
+ results: WorkspaceResult[];
160
+ /** Selected previews in file, project, and source order, without repeated ranges. */
161
+ previews: InspectPreview[];
162
+ /** Targets that could not be read. */
163
+ failures: InspectFailure[];
164
+ }
165
+ /**
166
+ * Reports the generated CSS of configured source files in a child process.
167
+ *
168
+ * @param options - Configuration discovery and targets. Paths and globs follow the target rules
169
+ * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.
170
+ * @returns Previews and analysis results. A file with incomplete analysis has no previews.
171
+ * @throws If a target is invalid or matches no file, or if configuration discovery, worker
172
+ * initialization, target enumeration, or cleanup fails.
173
+ */
174
+ export declare function inspect(options?: Omit<RewriteOptions, "patterns"> & {
175
+ /** Targets as written on the command line. */
176
+ targets?: readonly string[];
177
+ }): Promise<InspectResult>;
70
178
  /** Lint results preserve project membership and identify incomplete analysis. */
71
179
  interface LintResult {
72
180
  /** Absolute path of the evaluated configuration. */
@@ -160,5 +268,5 @@ export declare class SourceFormatter {
160
268
  * @returns The absolute configuration path, or undefined when discovery finds none.
161
269
  */
162
270
  export declare function findFormatterConfig(file: string, config?: string): string | undefined;
163
- export { type FormatResult, type LintResult, type RewriteFileFailure, type RewriteInput, type RewriteOptions, type RewriteResult, lintReports };
271
+ export { type DesignSystemAnswer, type FormatResult, type InspectFailure, type InspectPreview, type InspectResult, type InspectTarget, type LintResult, type RewriteFileFailure, type RewriteInput, type RewriteOptions, type RewriteResult, lintReports };
164
272
  //# sourceMappingURL=node.d.ts.map
package/dist/node.js CHANGED
@@ -5,7 +5,8 @@ import path from "node:path";
5
5
  import { findConfiguration, findDocumentConfiguration } from "@stillwind/config/node";
6
6
  import { fork } from "node:child_process";
7
7
  import process$1 from "node:process";
8
- import { fileURLToPath } from "node:url";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { isStylesheet } from "@stillwind/host";
9
10
  // src/worker-client.ts
10
11
  /** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */
11
12
  var AnalysisWorker = class {
@@ -300,6 +301,240 @@ async function format(options = {}) {
300
301
  exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0
301
302
  };
302
303
  }
304
+ // src/design-system.ts
305
+ /**
306
+ * Answers a question about each project's design system in a child process.
307
+ *
308
+ * @param options - Configuration discovery. Target globs do not apply.
309
+ * @param request - Theme, utility, or variant request.
310
+ * @returns Answers from every project. Unknown names and unmatched targets are data.
311
+ * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.
312
+ */
313
+ async function designSystem(options, request) {
314
+ const config = resolveRewriteConfig(options);
315
+ const worker = new AnalysisWorker();
316
+ try {
317
+ await worker.open(config);
318
+ const answers = await worker.request({
319
+ method: "designSystem",
320
+ request
321
+ });
322
+ return {
323
+ config,
324
+ tokens: answers.flatMap(({ project, result }) => result.tokens.map((token) => ({
325
+ ...token,
326
+ project
327
+ }))),
328
+ candidates: answers.flatMap(({ project, result }) => result.candidates.map((candidate) => ({
329
+ ...candidate,
330
+ project
331
+ }))),
332
+ unmatched: request.targets.filter((target) => answers.every(({ result }) => result.unmatched.includes(target)))
333
+ };
334
+ } finally {
335
+ await worker.close();
336
+ }
337
+ }
338
+ // src/inspect.ts
339
+ /**
340
+ * Parses a command-line target with an optional `:line` or `:line:column` suffix.
341
+ *
342
+ * @param target - Path or glob, including absolute Windows paths.
343
+ * @returns The pattern and any one-based position.
344
+ * @throws If the position is not positive or the target names a stylesheet.
345
+ */
346
+ function parseInspectTarget(target) {
347
+ const [, pattern, line, column] = /^(.+?)(?::(\d+)(?::(\d+))?)?$/s.exec(target) ?? [];
348
+ if (!pattern || /^0+$/.test(line ?? "") || /^0+$/.test(column ?? "")) throw new Error(`Invalid inspect target: ${target}`);
349
+ if (isStylesheet(pattern)) throw new Error(`inspect does not accept stylesheets: ${target}`);
350
+ return {
351
+ pattern,
352
+ ...line ? { line: Number(line) } : {},
353
+ ...column ? { column: Number(column) } : {}
354
+ };
355
+ }
356
+ /**
357
+ * Finds the UTF-16 offset of the start of each line.
358
+ *
359
+ * @param source - Document text. Lines end at `\n`, so `\r\n` remains one line break.
360
+ * @returns Ascending offsets, beginning with zero.
361
+ */
362
+ function lineOffsets(source) {
363
+ const offsets = [0];
364
+ for (let index = source.indexOf("\n"); index >= 0; index = source.indexOf("\n", index + 1)) offsets.push(index + 1);
365
+ return offsets;
366
+ }
367
+ /**
368
+ * Converts an offset to a position.
369
+ *
370
+ * @param lines - Result of {@link lineOffsets}.
371
+ * @param offset - UTF-16 offset in the same document.
372
+ * @returns The zero-based line and column.
373
+ */
374
+ function position(lines, offset) {
375
+ let line = lines.length - 1;
376
+ while (lines[line] > offset) line--;
377
+ return {
378
+ line,
379
+ column: offset - lines[line]
380
+ };
381
+ }
382
+ /**
383
+ * Checks whether a report location belongs to a file.
384
+ *
385
+ * @param uri - File URI or path.
386
+ * @param file - Absolute path.
387
+ * @returns Whether both name the same path.
388
+ */
389
+ function isDocument(uri, file) {
390
+ return path.resolve(uri.startsWith("file:") ? fileURLToPath(uri) : uri) === path.resolve(file);
391
+ }
392
+ /**
393
+ * Answers one target for one file.
394
+ *
395
+ * @param worker - Opened worker that owns the file's analysis.
396
+ * @param file - Absolute target path.
397
+ * @param source - Text of the file.
398
+ * @param target - Position to select. Positions outside the file select nothing.
399
+ * @param reports - Reports with a range in this file, for each project.
400
+ * @returns Previews with their project, in project and source order.
401
+ * @throws If the editor query fails.
402
+ */
403
+ async function selectPreviews(worker, file, source, target, reports) {
404
+ const lines = lineOffsets(source);
405
+ const line = target.line === void 0 ? void 0 : target.line - 1;
406
+ const lineStart = line === void 0 ? void 0 : lines[line];
407
+ const lineEnd = line === void 0 ? void 0 : (lines[line + 1] ?? source.length + 1) - 1;
408
+ if (line !== void 0 && lineStart === void 0) return [];
409
+ const offset = target.column === void 0 ? void 0 : lineStart + target.column - 1;
410
+ if (offset !== void 0 && offset > lineEnd) return [];
411
+ const query = (request) => worker.request({
412
+ method: "query",
413
+ file,
414
+ request
415
+ });
416
+ const uri = pathToFileURL(file).href;
417
+ let selected;
418
+ if (offset === void 0) selected = (await query({ kind: "previews" })).flatMap(({ project, result }) => (result.previews ?? []).filter(({ start, end }) => line === void 0 || end > lineStart && start <= lineEnd).map((range) => ({
419
+ project,
420
+ range
421
+ })));
422
+ else {
423
+ const hovers = await query({
424
+ kind: "hover",
425
+ offset
426
+ });
427
+ selected = hovers.flatMap(({ project, result }) => result.hover ? [{
428
+ project,
429
+ range: result.hover
430
+ }] : []);
431
+ if (selected.length < hovers.length) {
432
+ const answered = new Set(selected.map(({ project }) => project));
433
+ selected.push(...(await query({ kind: "previews" })).flatMap(({ project, result }) => answered.has(project) ? [] : (result.previews ?? []).filter(({ start, end }) => start <= offset && offset <= end).map((range) => ({
434
+ project,
435
+ range
436
+ }))));
437
+ }
438
+ }
439
+ return selected.flatMap(({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {
440
+ const diagnostics = reports.filter(({ project: owner, report: { primary } }) => owner === project && primary.location.startUtf16 < end && start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1)).map(({ report: { severity, code, message } }) => ({
441
+ severity,
442
+ code,
443
+ message
444
+ }));
445
+ if (!css && valid && !diagnostics.length && !documentation) return [];
446
+ const first = position(lines, start);
447
+ const last = position(lines, end);
448
+ return [{
449
+ project,
450
+ location: {
451
+ uri,
452
+ startLine: first.line,
453
+ startColumn: first.column,
454
+ endLine: last.line,
455
+ endColumn: last.column
456
+ },
457
+ source: source.slice(start, end),
458
+ css,
459
+ valid: valid && !diagnostics.some(({ severity }) => severity === "error"),
460
+ diagnostics,
461
+ ...documentation ? { documentation } : {},
462
+ ...runtimeNames ? { runtimeNames } : {}
463
+ }];
464
+ });
465
+ }
466
+ /**
467
+ * Reports the generated CSS of configured source files in a child process.
468
+ *
469
+ * @param options - Configuration discovery and targets. Paths and globs follow the target rules
470
+ * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.
471
+ * @returns Previews and analysis results. A file with incomplete analysis has no previews.
472
+ * @throws If a target is invalid or matches no file, or if configuration discovery, worker
473
+ * initialization, target enumeration, or cleanup fails.
474
+ */
475
+ async function inspect(options = {}) {
476
+ const targets = (options.targets ?? []).map(parseInspectTarget);
477
+ const config = resolveRewriteConfig(options);
478
+ const worker = new AnalysisWorker();
479
+ try {
480
+ await worker.open(config);
481
+ const selections = /* @__PURE__ */ new Map();
482
+ for (const target of targets.length ? targets : [void 0]) {
483
+ const files = (await worker.targets(target ? [target.pattern] : void 0)).filter((file) => !isStylesheet(file));
484
+ if (!files.length) throw new Error(target ? `No analysis targets matched ${target.pattern}` : "No analysis targets matched the configured scopes");
485
+ for (const file of files) selections.set(file, [...selections.get(file) ?? [], target ?? { pattern: file }]);
486
+ }
487
+ const files = [...selections.keys()].sort();
488
+ await worker.request({
489
+ method: "prepare",
490
+ files
491
+ });
492
+ const result = {
493
+ config,
494
+ results: [],
495
+ previews: [],
496
+ failures: []
497
+ };
498
+ for (const file of files) {
499
+ const analyses = await worker.analyze(file);
500
+ result.results.push(...analyses);
501
+ const complete = new Set(analyses.filter(({ result }) => result.status === "complete").map(({ project }) => project));
502
+ let source;
503
+ try {
504
+ const bytes = await readFile(file);
505
+ source = bytes.toString("utf8");
506
+ if (!Buffer.from(source).equals(bytes)) throw new Error(`Source is not valid UTF-8: ${file}`);
507
+ } catch (error) {
508
+ result.failures.push({
509
+ file,
510
+ message: error instanceof Error ? error.message : String(error)
511
+ });
512
+ continue;
513
+ }
514
+ const reports = lintReports(analyses).filter(({ report }) => report.primary.scope === "range" && isDocument(report.primary.location.uri, file));
515
+ const seen = /* @__PURE__ */ new Set();
516
+ const previews = [];
517
+ for (const target of selections.get(file)) for (const preview of await selectPreviews(worker, file, source, target, reports)) {
518
+ const { startLine, startColumn, endLine, endColumn } = preview.location;
519
+ const key = [
520
+ preview.project,
521
+ startLine,
522
+ startColumn,
523
+ endLine,
524
+ endColumn
525
+ ].join();
526
+ if (complete.has(preview.project) && !seen.has(key)) {
527
+ seen.add(key);
528
+ previews.push(preview);
529
+ }
530
+ }
531
+ result.previews.push(...previews.sort((a, b) => a.project - b.project || a.location.startLine - b.location.startLine || a.location.startColumn - b.location.startColumn));
532
+ }
533
+ return result;
534
+ } finally {
535
+ await worker.close();
536
+ }
537
+ }
303
538
  // src/lint.ts
304
539
  /**
305
540
  * Analyzes configured target scopes in a child process and closes it before returning.
@@ -436,6 +671,10 @@ async function openConfiguration(file, workspaces, errors) {
436
671
  method: "refresh",
437
672
  files: uris.filter(accepts).map((uri) => fileURLToPath(uri))
438
673
  }),
674
+ affects: (uris) => worker.request({
675
+ method: "affects",
676
+ files: uris.filter(accepts).map((uri) => fileURLToPath(uri))
677
+ }),
439
678
  prepare: async (uris, signal) => {
440
679
  if (!signal?.aborted) await worker.request({
441
680
  method: "prepare",
@@ -547,6 +786,6 @@ function findFormatterConfig(file, config) {
547
786
  if (config) return path.resolve(config);
548
787
  return findConfiguration(path.dirname(path.resolve(file)));
549
788
  }
550
- export { SourceFormatter, discoverNodeWorkspace, findFormatterConfig, format, formatLint, lint, lintReports, openNodeWorkspaces };
789
+ export { SourceFormatter, designSystem, discoverNodeWorkspace, findFormatterConfig, format, formatLint, inspect, lint, lintReports, openNodeWorkspaces };
551
790
 
552
791
  //# sourceMappingURL=node.js.map
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/format.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteBatchResult } from \"./rewrite.ts\";\n\n/** Requests sent to the process that owns trusted config evaluation and plugin lifetimes. */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass or lint fixes that must converge. */\n operation: \"sort\" | \"fixes\";\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/** IPC response correlated with one request. Successful void operations can omit value. */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** A replacement with the original bytes retained for verification before saving. */\nexport interface FileChange {\n /** Target path. The caller must provide at most one change per file. */\n file: string;\n /** Bytes captured before planning, compared against disk before saving. */\n before: Buffer;\n /** Planned replacement bytes. Equal bytes skip verification and writing. */\n after: Buffer;\n}\n\n/**\n * Saves changed bytes once per file. Identical buffers perform no filesystem operations.\n * Checks each original immediately before saving and continues after a target fails.\n * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { RewriteFileFailure, RewriteInput } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/** Selects configured source files for CLI analysis and rewriting. */\nexport interface RewriteOptions {\n /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */\n config?: string;\n /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */\n cwd?: string;\n /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */\n patterns?: string[];\n}\n\n/** A completed rewrite batch with findings kept separately for each owning project. */\ninterface RewriteFilesResult {\n /** Absolute configuration path used by the isolated worker. */\n config: string;\n /** Absolute paths whose original and final bytes differ, in sorted order. */\n changed: string[];\n /** Original findings for sorting and final findings for lint fixes, in project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Computes all replacements before optionally saving changed files. Fixes return final findings.\n * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting or converged lint fixes.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: \"sort\" | \"fixes\",\n write: boolean,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check);\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Reuses an isolated process while refreshing trusted configuration for each formatting request. */\nexport class SourceFormatter {\n /** Child process reused across formatting requests and owned until close completes. */\n readonly #worker = new AnalysisWorker();\n /** Serializes requests while allowing a new request after a preceding failure. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Starts the isolated worker that evaluates configuration on each formatting request.\n * @param config - Configuration path resolved in the worker's inherited working directory.\n */\n constructor(private readonly config: string) {}\n\n /**\n * Sorts the supplied buffer with current project settings.\n * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.\n * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.\n * @returns The sorted buffer and original findings after configuration is reopened.\n * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.\n */\n format(input: RewriteInput): Promise<RewriteResult> {\n const task = this.#queue.then(async () => {\n await this.#worker.open(this.config);\n const { outputs, failures } = await this.#worker.rewrite(\n [\n {\n ...input,\n file: path.resolve(input.file),\n },\n ],\n \"sort\",\n );\n if (failures.length) {\n throw new RewriteFailure(failures[0].message, failures[0].results);\n }\n return outputs[0];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Waits for queued formatting and releases the child process. Stop submitting requests before closure.\n * @returns Completion of worker cleanup.\n * @throws If the worker's cleanup request fails.\n */\n async close(): Promise<void> {\n await this.#queue;\n await this.#worker.close();\n }\n}\n\n/**\n * Finds a configuration above a source file or resolves an explicit path from cwd.\n * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.dirname(path.resolve(file)));\n}\n"],"mappings":";;;;;;;;;;AAuGA,IAAa,iBAAb,MAA4B;;CAE1B;;CAEA,2BAAoB,IAAI,IAQtB;;CAEF;;CAGA,UAAU;;CAEV,UAAU;;CAEV,WAAW;;;;CAKX,cAAc;EACZ,KAAK,SAAS,KAAK,cAAc,IAAI,IAAI,eAAe,YAAY,GAAG,CAAC,GAAG,CAAC,GAAG;GAC7E,OAAO;IAAC;IAAU;IAA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G;IACH,MAAM,KAAK,QAAQ,MAAM,IAAI;GAC/B,CACF,GACA,MACF;GACA,IAAI,SAAS,QACX,MAAM,IAAI,eAAe,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,CAAC,OAAO;GAEnE,OAAO,QAAQ;EACjB,CAAC;EACD,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC;EACjC,OAAO;CACT;;;;;;CAOA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF;;;;;;;AAQA,SAAgB,oBAAoB,MAAc,QAAqC;CACrF,IAAI,QACF,OAAO,KAAK,QAAQ,MAAM;CAE5B,OAAO,kBAAkB,KAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC;AAC3D"}
1
+ {"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/format.ts","../src/design-system.ts","../src/inspect.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { DesignSystemRequest, EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteBatchResult } from \"./rewrite.ts\";\n\n/** Requests sent to the process that owns trusted config evaluation and plugin lifetimes. */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass or lint fixes that must converge. */\n operation: \"sort\" | \"fixes\";\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for a question about each project's design system. */\n method: \"designSystem\";\n /** Theme, utility, or variant request. */\n request: DesignSystemRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for checking whether file changes can change results. */\n method: \"affects\";\n /** Absolute file paths reported by watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/** IPC response correlated with one request. Successful void operations can omit value. */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** A replacement with the original bytes retained for verification before saving. */\nexport interface FileChange {\n /** Target path. The caller must provide at most one change per file. */\n file: string;\n /** Bytes captured before planning, compared against disk before saving. */\n before: Buffer;\n /** Planned replacement bytes. Equal bytes skip verification and writing. */\n after: Buffer;\n}\n\n/**\n * Saves changed bytes once per file. Identical buffers perform no filesystem operations.\n * Checks each original immediately before saving and continues after a target fails.\n * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { RewriteFileFailure, RewriteInput } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/** Selects configured source files for CLI analysis and rewriting. */\nexport interface RewriteOptions {\n /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */\n config?: string;\n /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */\n cwd?: string;\n /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */\n patterns?: string[];\n}\n\n/** A completed rewrite batch with findings kept separately for each owning project. */\ninterface RewriteFilesResult {\n /** Absolute configuration path used by the isolated worker. */\n config: string;\n /** Absolute paths whose original and final bytes differ, in sorted order. */\n changed: string[];\n /** Original findings for sorting and final findings for lint fixes, in project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Computes all replacements before optionally saving changed files. Fixes return final findings.\n * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting or converged lint fixes.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: \"sort\" | \"fixes\",\n write: boolean,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check);\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { DesignCandidate, DesignSystemRequest, DesignToken } from \"@stillwind/host\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Design-system answers from every project of one configuration.\n */\nexport interface DesignSystemAnswer {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Tokens in project and name order. */\n tokens: (DesignToken & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Candidates in project order. */\n candidates: (DesignCandidate & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Targets without a match in any project. */\n unmatched: string[];\n}\n\n/**\n * Answers a question about each project's design system in a child process.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @param request - Theme, utility, or variant request.\n * @returns Answers from every project. Unknown names and unmatched targets are data.\n * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.\n */\nexport async function designSystem(\n options: Omit<RewriteOptions, \"patterns\">,\n request: DesignSystemRequest,\n): Promise<DesignSystemAnswer> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const answers = await worker.request<\n {\n project: number;\n result: {\n tokens: DesignToken[];\n candidates: DesignCandidate[];\n unmatched: string[];\n };\n }[]\n >({\n method: \"designSystem\",\n request,\n });\n return {\n config,\n tokens: answers.flatMap(({ project, result }) =>\n result.tokens.map((token) => ({\n ...token,\n project,\n })),\n ),\n candidates: answers.flatMap(({ project, result }) =>\n result.candidates.map((candidate) => ({\n ...candidate,\n project,\n })),\n ),\n unmatched: request.targets.filter((target) =>\n answers.every(({ result }) => result.unmatched.includes(target)),\n ),\n };\n } finally {\n await worker.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n isStylesheet,\n type EditorRequest,\n type EditorResult,\n type WorkspaceResult,\n} from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type { WorkspaceEditorResult } from \"./workspace.ts\";\n\n/**\n * Selects generated CSS by file, line, or position.\n */\nexport interface InspectTarget {\n /** Path or glob accepted by target selection. */\n pattern: string;\n /** One-based line. Omission selects the whole file. */\n line?: number;\n /** One-based UTF-16 column. It requires line. */\n column?: number;\n}\n\n/**\n * Generated CSS for one source range in one project.\n */\nexport interface InspectPreview {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */\n location: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n };\n /** Original source text in the range. */\n source: string;\n /** Formatted CSS. It is empty for a failed occurrence or a marker class. */\n css: string;\n /** False when diagnostics contains an error, or when a required style failed. */\n valid: boolean;\n /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */\n diagnostics: {\n /** Report severity, as in the reports of lint. */\n severity: string;\n /** Stable compiler code or lint rule. */\n code: string;\n /** Description of the finding. */\n message: string;\n }[];\n /** Markdown for a marker class. */\n documentation?: string;\n /** Authored runtime key expressions that the CSS depends on. */\n runtimeNames?: string[];\n}\n\n/**\n * An editor answer with a source range. Hovers omit valid because they describe generated CSS.\n */\ntype PreviewRange = NonNullable<EditorResult[\"hover\"]> & {\n valid?: boolean;\n};\n\n/**\n * A target that could not be read.\n */\nexport interface InspectFailure {\n /** Absolute path of the target. */\n file: string;\n /** Reason for the failure. */\n message: string;\n}\n\n/**\n * Inspection results with analysis outcomes retained for each project.\n */\nexport interface InspectResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Analysis of each selected file, in file and project order. */\n results: WorkspaceResult[];\n /** Selected previews in file, project, and source order, without repeated ranges. */\n previews: InspectPreview[];\n /** Targets that could not be read. */\n failures: InspectFailure[];\n}\n\n/**\n * Parses a command-line target with an optional `:line` or `:line:column` suffix.\n *\n * @param target - Path or glob, including absolute Windows paths.\n * @returns The pattern and any one-based position.\n * @throws If the position is not positive or the target names a stylesheet.\n */\nexport function parseInspectTarget(target: string): InspectTarget {\n const [, pattern, line, column] = /^(.+?)(?::(\\d+)(?::(\\d+))?)?$/s.exec(target) ?? [];\n if (!pattern || /^0+$/.test(line ?? \"\") || /^0+$/.test(column ?? \"\")) {\n throw new Error(`Invalid inspect target: ${target}`);\n }\n if (isStylesheet(pattern)) {\n throw new Error(`inspect does not accept stylesheets: ${target}`);\n }\n return {\n pattern,\n ...(line ? { line: Number(line) } : {}),\n ...(column ? { column: Number(column) } : {}),\n };\n}\n\n/**\n * Finds the UTF-16 offset of the start of each line.\n *\n * @param source - Document text. Lines end at `\\n`, so `\\r\\n` remains one line break.\n * @returns Ascending offsets, beginning with zero.\n */\nfunction lineOffsets(source: string): number[] {\n const offsets = [0];\n for (let index = source.indexOf(\"\\n\"); index >= 0; index = source.indexOf(\"\\n\", index + 1)) {\n offsets.push(index + 1);\n }\n return offsets;\n}\n\n/**\n * Converts an offset to a position.\n *\n * @param lines - Result of {@link lineOffsets}.\n * @param offset - UTF-16 offset in the same document.\n * @returns The zero-based line and column.\n */\nfunction position(lines: readonly number[], offset: number) {\n let line = lines.length - 1;\n while (lines[line] > offset) {\n line--;\n }\n return {\n line,\n column: offset - lines[line],\n };\n}\n\n/**\n * Checks whether a report location belongs to a file.\n *\n * @param uri - File URI or path.\n * @param file - Absolute path.\n * @returns Whether both name the same path.\n */\nfunction isDocument(uri: string, file: string): boolean {\n return path.resolve(uri.startsWith(\"file:\") ? fileURLToPath(uri) : uri) === path.resolve(file);\n}\n\n/**\n * Answers one target for one file.\n *\n * @param worker - Opened worker that owns the file's analysis.\n * @param file - Absolute target path.\n * @param source - Text of the file.\n * @param target - Position to select. Positions outside the file select nothing.\n * @param reports - Reports with a range in this file, for each project.\n * @returns Previews with their project, in project and source order.\n * @throws If the editor query fails.\n */\nasync function selectPreviews(\n worker: AnalysisWorker,\n file: string,\n source: string,\n target: InspectTarget,\n reports: ReturnType<typeof lintReports>,\n): Promise<InspectPreview[]> {\n const lines = lineOffsets(source);\n const line = target.line === undefined ? undefined : target.line - 1;\n const lineStart = line === undefined ? undefined : lines[line];\n const lineEnd = line === undefined ? undefined : (lines[line + 1] ?? source.length + 1) - 1;\n if (line !== undefined && lineStart === undefined) {\n return [];\n }\n const offset = target.column === undefined ? undefined : lineStart! + target.column - 1;\n if (offset !== undefined && offset > lineEnd!) {\n return [];\n }\n const query = (request: EditorRequest) =>\n worker.request<WorkspaceEditorResult[]>({ method: \"query\", file, request });\n const uri = pathToFileURL(file).href;\n let selected: { project: number; range: PreviewRange }[];\n if (offset === undefined) {\n selected = (\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n (result.previews ?? [])\n .filter(({ start, end }) => line === undefined || (end > lineStart! && start <= lineEnd!))\n .map((range) => ({\n project,\n range,\n })),\n );\n } else {\n const hovers = await query({\n kind: \"hover\",\n offset,\n });\n selected = hovers.flatMap(({ project, result }) =>\n result.hover ? [{ project, range: result.hover }] : [],\n );\n if (selected.length < hovers.length) {\n // Failed occurrences and Vue template expressions have no hover, so the listing supplies them.\n const answered = new Set(selected.map(({ project }) => project));\n selected.push(\n ...(\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n answered.has(project)\n ? []\n : (result.previews ?? [])\n .filter(({ start, end }) => start <= offset && offset <= end)\n .map((range) => ({\n project,\n range,\n })),\n ),\n );\n }\n }\n return selected.flatMap(\n ({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {\n const diagnostics = reports\n .filter(\n ({ project: owner, report: { primary } }) =>\n owner === project &&\n primary.location.startUtf16 < end &&\n start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1),\n )\n .map(({ report: { severity, code, message } }) => ({ severity, code, message }));\n if (!css && valid && !diagnostics.length && !documentation) {\n return [];\n }\n const first = position(lines, start);\n const last = position(lines, end);\n return [\n {\n project,\n location: {\n uri,\n startLine: first.line,\n startColumn: first.column,\n endLine: last.line,\n endColumn: last.column,\n },\n source: source.slice(start, end),\n css,\n valid: valid && !diagnostics.some(({ severity }) => severity === \"error\"),\n diagnostics,\n ...(documentation ? { documentation } : {}),\n ...(runtimeNames ? { runtimeNames } : {}),\n },\n ];\n },\n );\n}\n\n/**\n * Reports the generated CSS of configured source files in a child process.\n *\n * @param options - Configuration discovery and targets. Paths and globs follow the target rules\n * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.\n * @returns Previews and analysis results. A file with incomplete analysis has no previews.\n * @throws If a target is invalid or matches no file, or if configuration discovery, worker\n * initialization, target enumeration, or cleanup fails.\n */\nexport async function inspect(\n options: Omit<RewriteOptions, \"patterns\"> & {\n /** Targets as written on the command line. */\n targets?: readonly string[];\n } = {},\n): Promise<InspectResult> {\n const targets = (options.targets ?? []).map(parseInspectTarget);\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const selections = new Map<string, InspectTarget[]>();\n for (const target of targets.length ? targets : [undefined]) {\n const files = (await worker.targets(target ? [target.pattern] : undefined)).filter(\n (file) => !isStylesheet(file),\n );\n if (!files.length) {\n throw new Error(\n target\n ? `No analysis targets matched ${target.pattern}`\n : \"No analysis targets matched the configured scopes\",\n );\n }\n for (const file of files) {\n selections.set(file, [\n ...(selections.get(file) ?? []),\n target ?? {\n pattern: file,\n },\n ]);\n }\n }\n const files = [...selections.keys()].sort();\n await worker.request({\n method: \"prepare\",\n files,\n });\n\n const result: InspectResult = {\n config,\n results: [],\n previews: [],\n failures: [],\n };\n for (const file of files) {\n const analyses = await worker.analyze(file);\n result.results.push(...analyses);\n const complete = new Set(\n analyses.filter(({ result }) => result.status === \"complete\").map(({ project }) => project),\n );\n let source: string;\n try {\n const bytes = await readFile(file);\n source = bytes.toString(\"utf8\");\n if (!Buffer.from(source).equals(bytes)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n } catch (error) {\n result.failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const reports = lintReports(analyses).filter(\n ({ report }) =>\n report.primary.scope === \"range\" && isDocument(report.primary.location.uri, file),\n );\n const seen = new Set<string>();\n const previews: InspectPreview[] = [];\n for (const target of selections.get(file)!) {\n for (const preview of await selectPreviews(worker, file, source, target, reports)) {\n const { startLine, startColumn, endLine, endColumn } = preview.location;\n const key = [preview.project, startLine, startColumn, endLine, endColumn].join();\n if (complete.has(preview.project) && !seen.has(key)) {\n seen.add(key);\n previews.push(preview);\n }\n }\n }\n result.previews.push(\n ...previews.sort(\n (a, b) =>\n a.project - b.project ||\n a.location.startLine - b.location.startLine ||\n a.location.startColumn - b.location.startColumn,\n ),\n );\n }\n return result;\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n affects: (uris) =>\n worker.request<boolean>({\n method: \"affects\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Reuses an isolated process while refreshing trusted configuration for each formatting request. */\nexport class SourceFormatter {\n /** Child process reused across formatting requests and owned until close completes. */\n readonly #worker = new AnalysisWorker();\n /** Serializes requests while allowing a new request after a preceding failure. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Starts the isolated worker that evaluates configuration on each formatting request.\n * @param config - Configuration path resolved in the worker's inherited working directory.\n */\n constructor(private readonly config: string) {}\n\n /**\n * Sorts the supplied buffer with current project settings.\n * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.\n * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.\n * @returns The sorted buffer and original findings after configuration is reopened.\n * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.\n */\n format(input: RewriteInput): Promise<RewriteResult> {\n const task = this.#queue.then(async () => {\n await this.#worker.open(this.config);\n const { outputs, failures } = await this.#worker.rewrite(\n [\n {\n ...input,\n file: path.resolve(input.file),\n },\n ],\n \"sort\",\n );\n if (failures.length) {\n throw new RewriteFailure(failures[0].message, failures[0].results);\n }\n return outputs[0];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Waits for queued formatting and releases the child process. Stop submitting requests before closure.\n * @returns Completion of worker cleanup.\n * @throws If the worker's cleanup request fails.\n */\n async close(): Promise<void> {\n await this.#queue;\n await this.#worker.close();\n }\n}\n\n/**\n * Finds a configuration above a source file or resolves an explicit path from cwd.\n * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.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EAAhB,KAAA,SAAA;CAAiB;;;;;;;;CAS9C,OAAO,OAA6C;EAClD,MAAM,OAAO,KAAK,OAAO,KAAK,YAAY;GACxC,MAAM,KAAK,QAAQ,KAAK,KAAK,MAAM;GACnC,MAAM,EAAE,SAAS,aAAa,MAAM,KAAK,QAAQ,QAC/C,CACE;IACE,GAAG;IACH,MAAM,KAAK,QAAQ,MAAM,IAAI;GAC/B,CACF,GACA,MACF;GACA,IAAI,SAAS,QACX,MAAM,IAAI,eAAe,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,CAAC,OAAO;GAEnE,OAAO,QAAQ;EACjB,CAAC;EACD,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC;EACjC,OAAO;CACT;;;;;;CAOA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF;;;;;;;AAQA,SAAgB,oBAAoB,MAAc,QAAqC;CACrF,IAAI,QACF,OAAO,KAAK,QAAQ,MAAM;CAE5B,OAAO,kBAAkB,KAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC;AAC3D"}
@@ -1,4 +1,4 @@
1
- import { l as WorkspaceResult } from "./workspace-kE7AGW0k.js";
1
+ import { l as WorkspaceResult } from "./workspace-DIADkpZF.js";
2
2
  /**
3
3
  * Collects distinct reports per project while preserving their analysis order.
4
4
  * @param results - Analysis results with their project membership.
@@ -9,4 +9,4 @@ declare function lintReports(results: readonly WorkspaceResult[]): {
9
9
  report: import("@stillwind/native").BindingReport;
10
10
  }[];
11
11
  export { lintReports as t };
12
- //# sourceMappingURL=reports-C5F8xxeQ.d.ts.map
12
+ //# sourceMappingURL=reports-BI3wqUUD.d.ts.map
package/dist/worker.js CHANGED
@@ -57,6 +57,7 @@ async function handle(request) {
57
57
  case "analyze": return workspace.analyze(request.file);
58
58
  case "prepare": return workspace.prepare(request.files);
59
59
  case "query": return workspace.query(request.file, request.request);
60
+ case "designSystem": return workspace.designSystem(request.request);
60
61
  case "update":
61
62
  workspace.update(request.file, request.source, request.version);
62
63
  return;
@@ -67,6 +68,7 @@ async function handle(request) {
67
68
  workspace.invalidate();
68
69
  return;
69
70
  case "refresh": return workspace.refresh(request.files);
71
+ case "affects": return workspace.affects(request.files);
70
72
  case "close":
71
73
  await workspace.close();
72
74
  workspace = void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","names":[],"sources":["../src/worker.ts"],"sourcesContent":["import process from \"node:process\";\n\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport { RewriteFailure, SourceRewriter } from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The targets operation returns sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return undefined;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"rewrite\":\n return rewriter!.rewrite(request.inputs, request.operation);\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n"],"mappings":";;;;AAOA,IAAI;AACJ,IAAI;AAEJ,QAAQ,GACN,YACC,YAKK;CACJ,OAAY,QAAQ,OAAO,CAAC,CAAC,MAC1B,UAAU;EACT,QAAQ,OAAO;GAAE,IAAI,QAAQ;GAAI;EAAM,SAAS;GAC9C,IAAI,QAAQ,QAAQ,WAAW,SAC7B,QAAQ,aAAa;EAEzB,CAAC;CACH,IACC,UAAmB;EAClB,QAAQ,OAAO;GACb,IAAI,QAAQ;GACZ,OAAO;IACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,SAAS,iBAAiB,iBAAiB,MAAM,UAAU,KAAA;GAC7D;EACF,CAAC;CACH,CACF;AACF,CACF;AAEA,QAAQ,GAAG,oBAAoB;CAC7B,QAAa,QAAQ,WAAW,MAAM,CAAC,CAAC,CAAC,cAAc;EACrD,QAAQ,KAAK;CACf,CAAC;AACH,CAAC;;;;;;;;;AAUD,eAAe,OAAO,SAA0C;CAC9D,IAAI,QAAQ,WAAW,QAAQ;EAC7B,MAAM,WAAW,MAAM;EACvB,YAAY,KAAA;EACZ,YAAY,MAAM,kBAAkB,KAAK,QAAQ,MAAM;EACvD,WAAW,IAAI,eAAe,SAAS;EACvC;CACF;CAEA,IAAI,CAAC,WAAW;EACd,IAAI,QAAQ,WAAW,SACrB;EAEF,MAAM,IAAI,MAAM,yCAAyC;CAC3D;CAEA,QAAQ,QAAQ,QAAhB;EACE,KAAK,WAAW;GACd,MAAM,QAAQ,MAAM,QAAQ,IAC1B,UAAU,SAAS,KAAK,YACtB,UAAW,QAAQ,SAAS,QAAQ,WAAW,CAAC,GAAG,QAAQ,QAAQ,IAAI,KAAA,GAAW,EAChF,aAAa,QAAQ,YACvB,CAAC,CACH,CACF;GACA,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK;EACzC;EAEA,KAAK,WACH,OAAO,SAAU,QAAQ,QAAQ,QAAQ,QAAQ,SAAS;EAE5D,KAAK,QACH,OAAO,UAAU,KAAK,QAAQ,WAAW,CAAC,GAAG,QAAQ,QAAQ,IAAI,KAAA,CAAS;EAE5E,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,IAAI;EAEvC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK,SACH,OAAO,UAAU,MAAM,QAAQ,MAAM,QAAQ,OAAO;EAEtD,KAAK;GACH,UAAU,OAAO,QAAQ,MAAM,QAAQ,QAAQ,QAAQ,OAAO;GAC9D;EAEF,KAAK;GACH,UAAU,cAAc,QAAQ,IAAI;GACpC;EAEF,KAAK;GACH,UAAU,WAAW;GACrB;EAEF,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK;GACH,MAAM,UAAU,MAAM;GACtB,YAAY,KAAA;GACZ;CACJ;AACF"}
1
+ {"version":3,"file":"worker.js","names":[],"sources":["../src/worker.ts"],"sourcesContent":["import process from \"node:process\";\n\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport { RewriteFailure, SourceRewriter } from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The targets operation returns sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return undefined;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"rewrite\":\n return rewriter!.rewrite(request.inputs, request.operation);\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"designSystem\":\n return workspace.designSystem(request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"affects\":\n return workspace.affects(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n"],"mappings":";;;;AAOA,IAAI;AACJ,IAAI;AAEJ,QAAQ,GACN,YACC,YAKK;CACJ,OAAY,QAAQ,OAAO,CAAC,CAAC,MAC1B,UAAU;EACT,QAAQ,OAAO;GAAE,IAAI,QAAQ;GAAI;EAAM,SAAS;GAC9C,IAAI,QAAQ,QAAQ,WAAW,SAC7B,QAAQ,aAAa;EAEzB,CAAC;CACH,IACC,UAAmB;EAClB,QAAQ,OAAO;GACb,IAAI,QAAQ;GACZ,OAAO;IACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,SAAS,iBAAiB,iBAAiB,MAAM,UAAU,KAAA;GAC7D;EACF,CAAC;CACH,CACF;AACF,CACF;AAEA,QAAQ,GAAG,oBAAoB;CAC7B,QAAa,QAAQ,WAAW,MAAM,CAAC,CAAC,CAAC,cAAc;EACrD,QAAQ,KAAK;CACf,CAAC;AACH,CAAC;;;;;;;;;AAUD,eAAe,OAAO,SAA0C;CAC9D,IAAI,QAAQ,WAAW,QAAQ;EAC7B,MAAM,WAAW,MAAM;EACvB,YAAY,KAAA;EACZ,YAAY,MAAM,kBAAkB,KAAK,QAAQ,MAAM;EACvD,WAAW,IAAI,eAAe,SAAS;EACvC;CACF;CAEA,IAAI,CAAC,WAAW;EACd,IAAI,QAAQ,WAAW,SACrB;EAEF,MAAM,IAAI,MAAM,yCAAyC;CAC3D;CAEA,QAAQ,QAAQ,QAAhB;EACE,KAAK,WAAW;GACd,MAAM,QAAQ,MAAM,QAAQ,IAC1B,UAAU,SAAS,KAAK,YACtB,UAAW,QAAQ,SAAS,QAAQ,WAAW,CAAC,GAAG,QAAQ,QAAQ,IAAI,KAAA,GAAW,EAChF,aAAa,QAAQ,YACvB,CAAC,CACH,CACF;GACA,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK;EACzC;EAEA,KAAK,WACH,OAAO,SAAU,QAAQ,QAAQ,QAAQ,QAAQ,SAAS;EAE5D,KAAK,QACH,OAAO,UAAU,KAAK,QAAQ,WAAW,CAAC,GAAG,QAAQ,QAAQ,IAAI,KAAA,CAAS;EAE5E,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,IAAI;EAEvC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK,SACH,OAAO,UAAU,MAAM,QAAQ,MAAM,QAAQ,OAAO;EAEtD,KAAK,gBACH,OAAO,UAAU,aAAa,QAAQ,OAAO;EAE/C,KAAK;GACH,UAAU,OAAO,QAAQ,MAAM,QAAQ,QAAQ,QAAQ,OAAO;GAC9D;EAEF,KAAK;GACH,UAAU,cAAc,QAAQ,IAAI;GACpC;EAEF,KAAK;GACH,UAAU,WAAW;GACrB;EAEF,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK;GACH,MAAM,UAAU,MAAM;GACtB,YAAY,KAAA;GACZ;CACJ;AACF"}
@@ -67,6 +67,14 @@ interface AnalysisWorkspaceService {
67
67
  * @throws If the service or its transport cannot check the files.
68
68
  */
69
69
  refresh?(uris: readonly string[]): Promise<boolean>;
70
+ /**
71
+ * Checks whether watched file changes can change this service's results, without changing state.
72
+ * Omission makes the server treat every change as relevant.
73
+ *
74
+ * @param uris - Document URIs or absolute virtual paths reported by the notification.
75
+ * @returns False when the server can ignore the changes and keep running analysis.
76
+ */
77
+ affects?(uris: readonly string[]): Promise<boolean>;
70
78
  /**
71
79
  * Queries optional editor features against captured original documents.
72
80
  *
@@ -156,4 +164,4 @@ type OpenWorkspaces = (context: AnalysisWorkspaceContext) => Promise<OpenAnalysi
156
164
  */
157
165
  type DiscoverWorkspace = (uri: string, context: AnalysisWorkspaceContext, known: ReadonlySet<string>) => Promise<OpenAnalysisWorkspaces | undefined>;
158
166
  export { DiscoverWorkspace as a, WorkspaceEditorResult as c, AnalysisWorkspaceService as i, WorkspaceResult$1 as l, AnalysisResult as n, OpenAnalysisWorkspaces as o, AnalysisWorkspaceContext as r, OpenWorkspaces as s, AnalysisDependency as t };
159
- //# sourceMappingURL=workspace-kE7AGW0k.d.ts.map
167
+ //# sourceMappingURL=workspace-DIADkpZF.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stillwind/analysis",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Analysis services for Stillwind tools",
5
5
  "homepage": "https://stillwind.dev",
6
6
  "bugs": {
@@ -39,9 +39,9 @@
39
39
  "access": "public"
40
40
  },
41
41
  "dependencies": {
42
- "@stillwind/config": "0.3.0",
43
- "@stillwind/host": "0.3.0",
44
- "@stillwind/native": "0.3.0",
42
+ "@stillwind/config": "0.4.1",
43
+ "@stillwind/host": "0.4.1",
44
+ "@stillwind/native": "0.4.1",
45
45
  "minimatch": "^11.0.3",
46
46
  "pathe": "^2.0.3"
47
47
  },