@stillwind/host 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -2
- package/dist/browser.d.ts +220 -0
- package/dist/browser.js +1066 -0
- package/dist/browser.js.map +1 -0
- package/dist/configuration-CnrzO-F3.js +405 -0
- package/dist/configuration-CnrzO-F3.js.map +1 -0
- package/dist/index-CprPvXxv.d.ts +844 -0
- package/dist/index.d.ts +1243 -0
- package/dist/index.js +2672 -0
- package/dist/index.js.map +1 -0
- package/dist/options-BrXyddsL.js +4770 -0
- package/dist/options-BrXyddsL.js.map +1 -0
- package/dist/plugin-DvCyhK1k.js +1410 -0
- package/dist/plugin-DvCyhK1k.js.map +1 -0
- package/dist/projection.d.ts +2 -0
- package/dist/projection.js +1 -0
- package/dist/resolution-BI5eZllL.d.ts +12 -0
- package/dist/resolution-C3cvLPzx.js +100 -0
- package/dist/resolution-C3cvLPzx.js.map +1 -0
- package/dist/resolution.d.ts +2 -0
- package/dist/resolution.js +1 -0
- package/package.json +77 -3
package/dist/browser.js
ADDED
|
@@ -0,0 +1,1066 @@
|
|
|
1
|
+
import { A as prepareSourcePlugins, D as attachPlugins, E as TypeFactsError, T as fileSourceKind, _ as defaultPluginExport, a as pluginDirectory, b as analyzeModule, c as EditorSnapshot, d as withRequestedProbes, f as isStylesheet, h as loadEditorCssGraph, i as completePluginPaths, l as CheckerSource, m as loadCssGraph, n as cssEntrypoint, o as queryPluginPaths, r as StylesheetEditor, s as CompilationProject, t as compilerOptions, u as checkerId, y as finalizeCss } from "./options-BrXyddsL.js";
|
|
2
|
+
import { t as resolveVirtualModule } from "./resolution-C3cvLPzx.js";
|
|
3
|
+
import { NativeProjectSession, fingerprint } from "@stillwind/native";
|
|
4
|
+
import ts from "typescript-6";
|
|
5
|
+
import * as path from "pathe";
|
|
6
|
+
import { dirname, relative, resolve } from "pathe";
|
|
7
|
+
import { captureProjectConfig } from "@stillwind/config";
|
|
8
|
+
import { minimatch } from "minimatch";
|
|
9
|
+
// src/semantics/browser/facts.ts
|
|
10
|
+
/**
|
|
11
|
+
* Visits an AST in parent-first order.
|
|
12
|
+
*
|
|
13
|
+
* @param node - Root of the subtree to traverse.
|
|
14
|
+
* @param callback - Operation invoked for the root and every child node. Exceptions propagate.
|
|
15
|
+
*/
|
|
16
|
+
function visit(node, callback) {
|
|
17
|
+
callback(node);
|
|
18
|
+
node.forEachChild((child) => visit(child, callback));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Tests whether a type alias is declared in one of `files`.
|
|
22
|
+
*
|
|
23
|
+
* @param type - Checker type to inspect.
|
|
24
|
+
* @param files - Declaration file names of the macro module.
|
|
25
|
+
* @returns Whether the first declaration of the alias symbol belongs to `files`.
|
|
26
|
+
*/
|
|
27
|
+
function declaredBy(type, files) {
|
|
28
|
+
const file = type.aliasSymbol?.declarations?.[0]?.getSourceFile().fileName;
|
|
29
|
+
return file !== void 0 && files.has(file);
|
|
30
|
+
}
|
|
31
|
+
/** Types whose values cannot be Stillwind assets. */
|
|
32
|
+
const primitiveTypeFlags = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.EnumLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.Never;
|
|
33
|
+
/**
|
|
34
|
+
* Decodes a checker type into finite declarations from one registered asset family.
|
|
35
|
+
*
|
|
36
|
+
* @param checker - Checker that owns type and location.
|
|
37
|
+
* @param type - Probed type, including unions of declaration candidates.
|
|
38
|
+
* @param location - AST node used to obtain property types.
|
|
39
|
+
* @param identities - Serialized keys mapped to declarations inserted into this snapshot.
|
|
40
|
+
* @param brands - Checker symbol names registered from asset producers and mapped to their families.
|
|
41
|
+
* @param producers - Producer call types of this snapshot, used to detect object types that may hold
|
|
42
|
+
* a widened asset.
|
|
43
|
+
* @param recognitionOnly - True skips checks for widened asset types when only macro recognition is needed.
|
|
44
|
+
* @returns Finite candidates, a confirmed non-asset, an object type that may hold a widened
|
|
45
|
+
* asset, or an unverified value whose declarations cannot be determined.
|
|
46
|
+
*/
|
|
47
|
+
function decode(checker, type, location, identities, brands, producers, recognitionOnly) {
|
|
48
|
+
if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return { kind: "unverified" };
|
|
49
|
+
let family;
|
|
50
|
+
let recognized = false;
|
|
51
|
+
let valid = true;
|
|
52
|
+
let finite = true;
|
|
53
|
+
const values = [];
|
|
54
|
+
for (const member of type.isUnion() ? type.types : [type]) {
|
|
55
|
+
let kind;
|
|
56
|
+
let identityType;
|
|
57
|
+
for (const property of checker.getPropertiesOfType(member)) {
|
|
58
|
+
if (property.name === "data-__stillwindStyleIdentity") kind = "style";
|
|
59
|
+
else if (brands.get(property.name) === "ref" && checker.getSignaturesOfType(member, ts.SignatureKind.Call).length) kind = "ref";
|
|
60
|
+
else if (brands.get(property.name) === "keyframes" && checker.getSignaturesOfType(member, ts.SignatureKind.Call).length) kind = "keyframes";
|
|
61
|
+
else if (brands.get(property.name) === "viewTransition") {
|
|
62
|
+
const method = checker.getPropertyOfType(member, "for");
|
|
63
|
+
if (method && checker.getSignaturesOfType(checker.getTypeOfSymbolAtLocation(method, location), ts.SignatureKind.Call).length) kind = "viewTransition";
|
|
64
|
+
}
|
|
65
|
+
if (kind) {
|
|
66
|
+
identityType = checker.getTypeOfSymbolAtLocation(property, location);
|
|
67
|
+
if (kind === "ref") {
|
|
68
|
+
const ref = checker.getPropertyOfType(identityType, "ref");
|
|
69
|
+
identityType = ref && checker.getTypeOfSymbolAtLocation(ref, location);
|
|
70
|
+
}
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const name = (member.aliasSymbol ?? member.getSymbol())?.name;
|
|
75
|
+
recognized ||= !!kind || !!name && /^Style(?:Result|Ref|Keyframes|ViewTransition)$/.test(name);
|
|
76
|
+
if (!kind || family && kind !== family) {
|
|
77
|
+
valid = false;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
family = kind;
|
|
81
|
+
if (!identityType) {
|
|
82
|
+
finite = false;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
for (const candidate of identityType.isUnion() ? identityType.types : [identityType]) {
|
|
86
|
+
const identity = candidate.isStringLiteral() ? identities.get(candidate.value) : void 0;
|
|
87
|
+
if (!identity) {
|
|
88
|
+
finite = false;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (identity.kind !== kind) {
|
|
92
|
+
valid = false;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
values.push(identity);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (valid && family === "style" && !finite) return {
|
|
99
|
+
kind: "asset",
|
|
100
|
+
value: {
|
|
101
|
+
kind: "styles",
|
|
102
|
+
value: {
|
|
103
|
+
kind: "style",
|
|
104
|
+
candidates: { kind: "universe" }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
if (!valid || !family || !values.length) {
|
|
109
|
+
if (recognized) return { kind: "unverified" };
|
|
110
|
+
const members = type.isUnion() ? type.types : [type];
|
|
111
|
+
const macroFiles = new Set(producers.flatMap((producer) => {
|
|
112
|
+
const file = producer.aliasSymbol?.declarations?.[0]?.getSourceFile().fileName;
|
|
113
|
+
return file === void 0 ? [] : [file];
|
|
114
|
+
}));
|
|
115
|
+
return { kind: !recognitionOnly && members.some((member) => !(member.flags & primitiveTypeFlags) && !declaredBy(member, macroFiles) && (producers.length === 0 || producers.some((producer) => checker.isTypeAssignableTo(producer, member)))) ? "unbranded" : "nonAsset" };
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
kind: "asset",
|
|
119
|
+
value: {
|
|
120
|
+
kind: {
|
|
121
|
+
style: "styles",
|
|
122
|
+
ref: "refs",
|
|
123
|
+
keyframes: "keyframes",
|
|
124
|
+
viewTransition: "viewTransitions"
|
|
125
|
+
}[family],
|
|
126
|
+
value: {
|
|
127
|
+
kind: family,
|
|
128
|
+
candidates: {
|
|
129
|
+
kind: "finite",
|
|
130
|
+
values
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Tests whether a TypeScript argument error belongs to a style producer call.
|
|
138
|
+
* Lowering reports unsupported macro arguments as lints, so these errors do not invalidate the
|
|
139
|
+
* facts of the call. The operands still require valid facts.
|
|
140
|
+
*
|
|
141
|
+
* @param diagnostic - Checker diagnostic for `sourceFile`.
|
|
142
|
+
* @param sourceFile - Checker source file that contains the diagnostic.
|
|
143
|
+
* @param mapping - Producer call ranges of the same source.
|
|
144
|
+
* @returns Whether the diagnostic is an argument error (TS2345 or TS2769) whose innermost
|
|
145
|
+
* enclosing call is a recorded producer call.
|
|
146
|
+
*/
|
|
147
|
+
function producerArgumentDiagnostic(diagnostic, sourceFile, mapping) {
|
|
148
|
+
if (diagnostic.code !== 2345 && diagnostic.code !== 2769 || diagnostic.start === void 0) return false;
|
|
149
|
+
const start = diagnostic.start;
|
|
150
|
+
const end = start + (diagnostic.length ?? 0);
|
|
151
|
+
let owner;
|
|
152
|
+
visit(sourceFile, (node) => {
|
|
153
|
+
if (ts.isCallExpression(node) && node.getStart(sourceFile) <= start && node.end >= end && (!owner || node.end - node.getStart(sourceFile) < owner.end - owner.getStart(sourceFile))) owner = node;
|
|
154
|
+
});
|
|
155
|
+
return !!owner && mapping.producers.has(`${owner.getStart(sourceFile)}:${owner.end}`);
|
|
156
|
+
}
|
|
157
|
+
// src/semantics/browser/program.ts
|
|
158
|
+
/**
|
|
159
|
+
* Maintains the TypeScript program over a browser workspace's virtual files.
|
|
160
|
+
*/
|
|
161
|
+
var BrowserProgram = class {
|
|
162
|
+
/** Root, settings, and dependency files used when preparing checker inputs. */
|
|
163
|
+
#options;
|
|
164
|
+
/** Language service reused while snapshots and project versions change. */
|
|
165
|
+
#service;
|
|
166
|
+
/** Current captured inventory with overlays, checker buffers, and helper declarations applied. */
|
|
167
|
+
#files = /* @__PURE__ */ new Map();
|
|
168
|
+
/** Per-file change counters exposed as language-service script versions. */
|
|
169
|
+
#versions = /* @__PURE__ */ new Map();
|
|
170
|
+
/** Effective TypeScript options from the virtual tsconfig and enforced checker settings. */
|
|
171
|
+
#compilerOptions = {};
|
|
172
|
+
/** Checker buffers and ambient declaration filenames selected as current project roots. */
|
|
173
|
+
#roots = [];
|
|
174
|
+
/** Advances when file text, roots, or compiler options change. */
|
|
175
|
+
#revision = 0;
|
|
176
|
+
/** Serialized compiler options and root filenames, used to detect settings changes. */
|
|
177
|
+
#settings = "";
|
|
178
|
+
/**
|
|
179
|
+
* Creates a checker without loading its sources.
|
|
180
|
+
*
|
|
181
|
+
* After changing dependency files, call invalidate before preparing another program.
|
|
182
|
+
* Do not change files while a query is running.
|
|
183
|
+
*
|
|
184
|
+
* @param options - Virtual root, complete dependency files, and optional tsconfig selection.
|
|
185
|
+
*/
|
|
186
|
+
constructor(options) {
|
|
187
|
+
this.#options = options;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Builds checker buffers and updates the language service from the supplied files.
|
|
191
|
+
*
|
|
192
|
+
* @param sources - Sources with original UTF-8 probes and any framework checker buffers.
|
|
193
|
+
* @param assets - Declarations grouped by module ID, used to mark producer calls.
|
|
194
|
+
* @param inputs - Overlays and ambient declarations applied over the configured files.
|
|
195
|
+
* @returns The updated program and mappings between original sources and checker buffers.
|
|
196
|
+
* @throws If a probe cannot be mapped, tsconfig is invalid, or the language service has no program.
|
|
197
|
+
*/
|
|
198
|
+
prepare(sources, assets, inputs) {
|
|
199
|
+
const files = new Map([
|
|
200
|
+
...this.#options.files,
|
|
201
|
+
...inputs.overlayFiles ?? [],
|
|
202
|
+
...inputs.ambientDeclarations ?? []
|
|
203
|
+
]);
|
|
204
|
+
const mappings = [];
|
|
205
|
+
const ids = new Map(sources.map((source) => [source.resolverId, checkerId(source)]));
|
|
206
|
+
const extraRoots = new Set(inputs.ambientDeclarations?.keys());
|
|
207
|
+
for (const source of sources) {
|
|
208
|
+
if (source.kind === "projected" && source.projection.checkerGlobals) {
|
|
209
|
+
const id = path.join(this.#options.root, `.stillwind-globals-${fingerprint(source.projection.checkerGlobals)}.d.ts`);
|
|
210
|
+
files.set(id, source.projection.checkerGlobals);
|
|
211
|
+
extraRoots.add(id);
|
|
212
|
+
}
|
|
213
|
+
const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
|
|
214
|
+
const buffers = source.checkerBuffers ?? [{
|
|
215
|
+
source: source.kind === "direct" ? source.document.code : source.projection.code,
|
|
216
|
+
language: syntax.language === "tsx" || syntax.language === "jsx" ? "tsx" : "ts"
|
|
217
|
+
}];
|
|
218
|
+
for (const [index, buffer] of buffers.entries()) {
|
|
219
|
+
const mapping = new CheckerSource(source, buffer, index, assets.get(source.moduleId) ?? [], ids);
|
|
220
|
+
files.set(mapping.id, mapping.text);
|
|
221
|
+
mappings.push(mapping);
|
|
222
|
+
if (mapping.helperModule) files.set(mapping.helperModule.id, mapping.helperModule.text);
|
|
223
|
+
}
|
|
224
|
+
for (const probe of source.probes) if (!mappings.some((mapping) => mapping.source === source && [...mapping.probes.values()].some((candidate) => candidate.start === probe.start && candidate.end === probe.end))) throw new TypeFactsError(source.moduleId, probe.start, probe.end, "checker", "Cannot map this expression to a checker source");
|
|
225
|
+
for (const id of source.checkerTypes ?? []) extraRoots.add(id);
|
|
226
|
+
}
|
|
227
|
+
const structureChanged = files.size !== this.#files.size || [...files.keys()].some((id) => !this.#files.has(id));
|
|
228
|
+
const resolutionChanged = structureChanged || [...files].some(([id, text]) => /\.json$/i.test(id) && this.#files.get(id) !== text);
|
|
229
|
+
let changed = structureChanged;
|
|
230
|
+
for (const [id, text] of files) if (this.#files.get(id) !== text) {
|
|
231
|
+
changed = true;
|
|
232
|
+
this.#versions.set(id, (this.#versions.get(id) ?? 0) + 1);
|
|
233
|
+
}
|
|
234
|
+
this.#files = files;
|
|
235
|
+
const configPath = path.resolve(this.#options.root, this.#options.tsconfig || "tsconfig.json");
|
|
236
|
+
let configured;
|
|
237
|
+
if (this.#options.tsconfig !== false && files.has(configPath)) {
|
|
238
|
+
const config = ts.readConfigFile(configPath, (id) => files.get(id));
|
|
239
|
+
if (config.error) throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, "\n"));
|
|
240
|
+
configured = ts.parseJsonConfigFileContent(config.config, {
|
|
241
|
+
useCaseSensitiveFileNames: true,
|
|
242
|
+
fileExists: (id) => files.has(id),
|
|
243
|
+
readFile: (id) => files.get(id),
|
|
244
|
+
readDirectory: (directory, extensions, excludes, includes, depth) => [...files.keys()].filter((id) => id.startsWith(directory + "/") && (!extensions || extensions.some((ext) => id.endsWith(ext))) && (depth === void 0 || path.relative(directory, id).split("/").length - 1 <= depth) && (includes ?? ["**/*"]).some((pattern) => matchesFile(directory, id, pattern)) && !(excludes ?? []).some((pattern) => matchesFile(directory, id, pattern)))
|
|
245
|
+
}, path.dirname(configPath));
|
|
246
|
+
const error = configured.errors.find((item) => item.code !== 18003);
|
|
247
|
+
if (error) throw new Error(ts.flattenDiagnosticMessageText(error.messageText, "\n"));
|
|
248
|
+
} else if (typeof this.#options.tsconfig === "string") throw new Error(`TypeScript configuration does not exist: ${configPath}`);
|
|
249
|
+
this.#compilerOptions = {
|
|
250
|
+
target: ts.ScriptTarget.ESNext,
|
|
251
|
+
module: ts.ModuleKind.ESNext,
|
|
252
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
253
|
+
jsx: ts.JsxEmit.Preserve,
|
|
254
|
+
strict: true,
|
|
255
|
+
types: [],
|
|
256
|
+
...configured?.options,
|
|
257
|
+
allowJs: true,
|
|
258
|
+
checkJs: true,
|
|
259
|
+
allowImportingTsExtensions: true,
|
|
260
|
+
noEmit: true,
|
|
261
|
+
skipLibCheck: true
|
|
262
|
+
};
|
|
263
|
+
this.#roots = [.../* @__PURE__ */ new Set([
|
|
264
|
+
...mappings.map((mapping) => mapping.id),
|
|
265
|
+
...extraRoots,
|
|
266
|
+
...configured?.fileNames.filter((id) => /\.d\.[cm]?ts$/.test(id)) ?? []
|
|
267
|
+
])];
|
|
268
|
+
const settings = JSON.stringify([this.#compilerOptions, this.#roots]);
|
|
269
|
+
if (changed || settings !== this.#settings) this.#revision++;
|
|
270
|
+
this.#settings = settings;
|
|
271
|
+
if (resolutionChanged) this.invalidate();
|
|
272
|
+
if (!this.#service) {
|
|
273
|
+
/**
|
|
274
|
+
* Infers a virtual directory from the captured files beneath it.
|
|
275
|
+
* @param directory - Absolute virtual directory with an optional trailing slash.
|
|
276
|
+
* @returns Whether at least one file key starts with the directory prefix.
|
|
277
|
+
*/
|
|
278
|
+
const directoryExists = (directory) => [...this.#files.keys()].some((id) => id.startsWith(directory.replace(/\/$/, "") + "/"));
|
|
279
|
+
this.#service = ts.createLanguageService({
|
|
280
|
+
getCompilationSettings: () => this.#compilerOptions,
|
|
281
|
+
getScriptFileNames: () => this.#roots,
|
|
282
|
+
getScriptVersion: (id) => String(this.#versions.get(id) ?? 0),
|
|
283
|
+
getProjectVersion: () => String(this.#revision),
|
|
284
|
+
getScriptSnapshot: (id) => {
|
|
285
|
+
const text = this.#files.get(id);
|
|
286
|
+
return text === void 0 ? void 0 : ts.ScriptSnapshot.fromString(text);
|
|
287
|
+
},
|
|
288
|
+
getCurrentDirectory: () => this.#options.root,
|
|
289
|
+
getDefaultLibFileName: () => "/node_modules/typescript/lib/lib.esnext.full.d.ts",
|
|
290
|
+
fileExists: (id) => this.#files.has(id),
|
|
291
|
+
readFile: (id) => this.#files.get(id),
|
|
292
|
+
directoryExists,
|
|
293
|
+
getDirectories: (directory) => [...new Set([...this.#files.keys()].filter((id) => id.startsWith(directory + "/")).map((id) => id.slice(directory.length + 1).split("/", 1)[0]))],
|
|
294
|
+
useCaseSensitiveFileNames: () => true
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
const program = this.#service.getProgram();
|
|
298
|
+
if (!program) throw new Error("Browser checker could not open the Stillwind project");
|
|
299
|
+
return {
|
|
300
|
+
program,
|
|
301
|
+
mappings
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Discards the language service after file or configuration changes.
|
|
306
|
+
*/
|
|
307
|
+
invalidate() {
|
|
308
|
+
this.#service?.dispose();
|
|
309
|
+
this.#service = void 0;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
/**
|
|
313
|
+
* Applies tsconfig file and directory patterns to paths in the virtual filesystem.
|
|
314
|
+
*
|
|
315
|
+
* @param directory - Absolute virtual base directory.
|
|
316
|
+
* @param id - Absolute virtual file path.
|
|
317
|
+
* @param pattern - Absolute or directory-relative glob. A plain directory name expands to its descendants.
|
|
318
|
+
* @returns Whether the relative path matches, including dot-prefixed segments.
|
|
319
|
+
*/
|
|
320
|
+
function matchesFile(directory, id, pattern) {
|
|
321
|
+
const name = path.relative(directory, id);
|
|
322
|
+
const glob = path.isAbsolute(pattern) ? path.relative(directory, pattern) : pattern;
|
|
323
|
+
const expanded = !/[?*]/.test(glob) && !/\.[^/]+$/.test(glob) ? `${glob}/**/*` : glob;
|
|
324
|
+
return minimatch(name, expanded, { dot: true });
|
|
325
|
+
}
|
|
326
|
+
// src/semantics/browser/service.ts
|
|
327
|
+
/**
|
|
328
|
+
* Answers declaration probes with the browser TypeScript checker.
|
|
329
|
+
*/
|
|
330
|
+
var BrowserTypeFactsService = class {
|
|
331
|
+
/** Program and language service owned by this backend. */
|
|
332
|
+
#program;
|
|
333
|
+
/** Prevents preparing further requests after cleanup. */
|
|
334
|
+
#closed = false;
|
|
335
|
+
/** Project inputs retained until {@link setProjectSources} replaces them. Queries select a subset. */
|
|
336
|
+
#installed;
|
|
337
|
+
/** Program and source mappings prepared from the installed project inputs. */
|
|
338
|
+
#prepared;
|
|
339
|
+
/**
|
|
340
|
+
* Creates a service without loading its sources.
|
|
341
|
+
*
|
|
342
|
+
* @param options - Virtual files and fixed TypeScript settings. Call invalidate after changing dependency files.
|
|
343
|
+
*/
|
|
344
|
+
constructor(options) {
|
|
345
|
+
this.#program = new BrowserProgram(options);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Keeps project inputs for later queries and clears prepared checker buffers.
|
|
349
|
+
*
|
|
350
|
+
* @param sources - Prepared project sources, retained by reference until replaced.
|
|
351
|
+
* @param assets - Declarations grouped by compiler module ID, retained with the sources.
|
|
352
|
+
* @param inputs - File overlays and ambient declarations. Omission supplies no extra files.
|
|
353
|
+
* Do not mutate these inputs while they are installed. Queries select their own probes and sources.
|
|
354
|
+
*/
|
|
355
|
+
setProjectSources(sources, assets, inputs = {}) {
|
|
356
|
+
this.#installed = {
|
|
357
|
+
sources,
|
|
358
|
+
assets,
|
|
359
|
+
inputs
|
|
360
|
+
};
|
|
361
|
+
this.#prepared = void 0;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Collects finite declaration candidates and rejects unavailable required queries.
|
|
365
|
+
*
|
|
366
|
+
* @param sources - Prepared sources with probes in original UTF-8 coordinates.
|
|
367
|
+
* @param assets - Declaration records grouped by compiler module identity.
|
|
368
|
+
* @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.
|
|
369
|
+
* An installed project uses the inputs supplied by {@link setProjectSources}.
|
|
370
|
+
* @returns Facts keyed by compiler identity, deduplicated by original range across checker buffers.
|
|
371
|
+
* Known non-asset types produce null facts. Unresolved recognition-only probes produce no fact.
|
|
372
|
+
* @throws If the service is closed, preparation fails, or checker contracts cannot be verified.
|
|
373
|
+
*/
|
|
374
|
+
collect(sources, assets, inputs) {
|
|
375
|
+
return this.#collect(sources, assets, inputs, false).facts;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Collects usable facts while retaining unavailable original ranges for analysis.
|
|
379
|
+
*
|
|
380
|
+
* @param sources - Prepared sources with original UTF-8 probes and checker correspondences.
|
|
381
|
+
* @param assets - Declaration records grouped by compiler module identity.
|
|
382
|
+
* @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.
|
|
383
|
+
* An installed project uses the inputs supplied by {@link setProjectSources}.
|
|
384
|
+
* @returns Verified facts and unverified ranges without discarding other expressions' answers.
|
|
385
|
+
* @throws If the service is closed, preparation fails, or checker results conflict for one original range.
|
|
386
|
+
*/
|
|
387
|
+
collectAvailable(sources, assets, inputs) {
|
|
388
|
+
return this.#collect(sources, assets, inputs, true);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Resolves authored imports and exports from module symbols in the virtual checker.
|
|
392
|
+
* When project sources are installed, resolves imports for the whole installed project.
|
|
393
|
+
*
|
|
394
|
+
* @param sources - Prepared sources whose checker buffers contain module requests.
|
|
395
|
+
* @param assets - Declaration records used to prepare checker identities and helpers.
|
|
396
|
+
* @param inputs - Overlays and ambient declarations for independent resolution. Omission supplies none.
|
|
397
|
+
* An installed project uses the inputs supplied by {@link setProjectSources}.
|
|
398
|
+
* @returns Maps from importing resolver identity to specifier and resolved identity. Unmatched requests are omitted.
|
|
399
|
+
* @throws If the service is closed or checker preparation fails.
|
|
400
|
+
*/
|
|
401
|
+
resolveModules(sources, assets, inputs) {
|
|
402
|
+
const { program, mappings } = this.#prepare(sources, assets, inputs);
|
|
403
|
+
const result = /* @__PURE__ */ new Map();
|
|
404
|
+
const checker = program.getTypeChecker();
|
|
405
|
+
for (const mapping of mappings) {
|
|
406
|
+
const file = program.getSourceFile(mapping.id);
|
|
407
|
+
if (!file) continue;
|
|
408
|
+
const resolutions = /* @__PURE__ */ new Map();
|
|
409
|
+
result.set(mapping.source.resolverId, resolutions);
|
|
410
|
+
visit(file, (node) => {
|
|
411
|
+
if (!(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) || !node.moduleSpecifier || !ts.isStringLiteral(node.moduleSpecifier)) return;
|
|
412
|
+
const declaration = checker.getSymbolAtLocation(node.moduleSpecifier)?.declarations?.find((item) => ts.isSourceFile(item) || item.getSourceFile().isDeclarationFile);
|
|
413
|
+
if (declaration) {
|
|
414
|
+
const filename = declaration.getSourceFile().fileName;
|
|
415
|
+
resolutions.set(mapping.moduleSpecifiers.get(`${node.moduleSpecifier.getStart(file)}:${node.moduleSpecifier.end}`) ?? node.moduleSpecifier.text, (this.#installed?.sources ?? sources).find((source) => checkerId(source) === filename)?.resolverId ?? filename);
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
return result;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Discards the language service after file or configuration changes.
|
|
423
|
+
*/
|
|
424
|
+
invalidate() {
|
|
425
|
+
this.#program.invalidate();
|
|
426
|
+
this.#prepared = void 0;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Releases the checker. Subsequent queries reject.
|
|
430
|
+
*/
|
|
431
|
+
close() {
|
|
432
|
+
this.#closed = true;
|
|
433
|
+
this.invalidate();
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Reuses prepared project inputs or prepares only the requested sources if project preparation fails.
|
|
437
|
+
*
|
|
438
|
+
* @param sources - Requested sources to use when no project is installed or preparation fails.
|
|
439
|
+
* @param assets - Declarations grouped by module ID for those sources.
|
|
440
|
+
* @param inputs - Overlays and ambient declarations for the requested sources.
|
|
441
|
+
* @returns The current checker program and source mappings. Successful project preparation is cached.
|
|
442
|
+
* @throws If the service is closed or the requested sources cannot be prepared.
|
|
443
|
+
*/
|
|
444
|
+
#prepare(sources, assets, inputs = {}) {
|
|
445
|
+
if (this.#closed) throw new Error("Browser checker is closed");
|
|
446
|
+
if (this.#prepared) return this.#prepared;
|
|
447
|
+
if (this.#installed) try {
|
|
448
|
+
this.#prepared = this.#program.prepare(this.#installed.sources, this.#installed.assets, this.#installed.inputs);
|
|
449
|
+
return this.#prepared;
|
|
450
|
+
} catch {}
|
|
451
|
+
return this.#program.prepare(sources, assets, inputs);
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Decodes current checker expressions and enforces finite declaration identities for probes.
|
|
455
|
+
*
|
|
456
|
+
* @param sources - Prepared sources with validated checker correspondences.
|
|
457
|
+
* @param assets - Native declarations keyed by compiler identity.
|
|
458
|
+
* @param inputs - Overlays and ambient declarations for this snapshot.
|
|
459
|
+
* @param available - Whether unavailable queries are recorded instead of thrown.
|
|
460
|
+
* @returns Facts grouped by compiler identity and original UTF-8 ranges that could not be verified.
|
|
461
|
+
* @throws If preparation fails, checker results conflict, or strict mode encounters unavailable facts.
|
|
462
|
+
*/
|
|
463
|
+
#collect(sources, assets, inputs, available) {
|
|
464
|
+
if (this.#installed) {
|
|
465
|
+
const updated = withRequestedProbes(this.#installed.sources, sources);
|
|
466
|
+
if (updated !== this.#installed.sources) {
|
|
467
|
+
this.#installed = {
|
|
468
|
+
...this.#installed,
|
|
469
|
+
sources: updated
|
|
470
|
+
};
|
|
471
|
+
this.#prepared = void 0;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const prepared = this.#prepare(sources, assets, inputs);
|
|
475
|
+
const { program } = prepared;
|
|
476
|
+
const selected = new Set(sources.map((source) => source.resolverId));
|
|
477
|
+
const mappings = prepared.mappings.filter((mapping) => selected.has(mapping.source.resolverId));
|
|
478
|
+
const identities = new Map(mappings.flatMap((mapping) => [...mapping.identities]));
|
|
479
|
+
const checker = program.getTypeChecker();
|
|
480
|
+
const facts = /* @__PURE__ */ new Map();
|
|
481
|
+
const unverified = [];
|
|
482
|
+
const brands = /* @__PURE__ */ new Map();
|
|
483
|
+
const producers = [];
|
|
484
|
+
for (const mapping of mappings) {
|
|
485
|
+
const file = program.getSourceFile(mapping.id);
|
|
486
|
+
if (!file) continue;
|
|
487
|
+
visit(file, (node) => {
|
|
488
|
+
const kind = mapping.producers.get(`${node.getStart(file)}:${node.end}`);
|
|
489
|
+
if (!kind) return;
|
|
490
|
+
producers.push(checker.getTypeAtLocation(node));
|
|
491
|
+
if (kind === "style") return;
|
|
492
|
+
const prefix = {
|
|
493
|
+
ref: "refIdentity",
|
|
494
|
+
keyframes: "keyframesIdentity",
|
|
495
|
+
viewTransition: "viewTransitionIdentity"
|
|
496
|
+
}[kind];
|
|
497
|
+
const property = checker.getPropertiesOfType(checker.getTypeAtLocation(node)).find((item) => item.name.startsWith(`__@${prefix}@`));
|
|
498
|
+
if (property) brands.set(property.name, kind);
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Records an unverifiable use when partial facts are allowed.
|
|
503
|
+
*
|
|
504
|
+
* @param error - Failure with the original module identity and UTF-8 range, when available.
|
|
505
|
+
* @throws The supplied error when this collection requires complete facts.
|
|
506
|
+
*/
|
|
507
|
+
const unavailable = (error) => {
|
|
508
|
+
if (!available) throw error;
|
|
509
|
+
unverified.push({
|
|
510
|
+
moduleId: error.moduleId,
|
|
511
|
+
start: error.start,
|
|
512
|
+
end: error.end,
|
|
513
|
+
reason: error.message
|
|
514
|
+
});
|
|
515
|
+
};
|
|
516
|
+
for (const mapping of mappings) {
|
|
517
|
+
const file = program.getSourceFile(mapping.id);
|
|
518
|
+
if (!file) throw new Error(`Browser checker omitted ${mapping.id}`);
|
|
519
|
+
const diagnostic = [...program.getSyntacticDiagnostics(file), ...program.getSemanticDiagnostics(file)].find((item) => !producerArgumentDiagnostic(item, file, mapping) && /stillwind\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(ts.flattenDiagnosticMessageText(item.messageText, "\n")));
|
|
520
|
+
if (diagnostic) {
|
|
521
|
+
const start = mapping.originalOffset(diagnostic.start ?? 0) ?? void 0;
|
|
522
|
+
const end = mapping.originalOffset((diagnostic.start ?? 0) + (diagnostic.length ?? 0), true) ?? void 0;
|
|
523
|
+
unavailable(new TypeFactsError(mapping.source.moduleId, start, end, "assignment", `TS${diagnostic.code}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")} Preserve declaration candidates with an explicit union or a generic parameter.`));
|
|
524
|
+
}
|
|
525
|
+
const matched = /* @__PURE__ */ new Set();
|
|
526
|
+
const values = facts.get(mapping.source.moduleId) ?? [];
|
|
527
|
+
visit(file, (node) => {
|
|
528
|
+
if (!ts.isExpression(node)) return;
|
|
529
|
+
const key = `${node.getStart(file)}:${node.end}`;
|
|
530
|
+
const probe = mapping.probes.get(key);
|
|
531
|
+
if (!probe) return;
|
|
532
|
+
matched.add(key);
|
|
533
|
+
const type = checker.getTypeAtLocation(node);
|
|
534
|
+
const decoded = decode(checker, type, node, identities, brands, producers, probe.recognitionOnly ?? false);
|
|
535
|
+
if (decoded.kind === "asset" || decoded.kind === "nonAsset" || decoded.kind === "unbranded" && probe.recognitionOnly) {
|
|
536
|
+
const value = decoded.kind === "asset" ? decoded.value : null;
|
|
537
|
+
const existing = values.find((item) => item.start === probe.start && item.end === probe.end);
|
|
538
|
+
if (existing && JSON.stringify(existing.value) !== JSON.stringify(value)) throw new TypeFactsError(mapping.source.moduleId, probe.start, probe.end, "checker", "Ambiguous checker results for this original expression");
|
|
539
|
+
if (!existing) values.push({
|
|
540
|
+
...probe,
|
|
541
|
+
value
|
|
542
|
+
});
|
|
543
|
+
} else if (!probe.recognitionOnly) unavailable(new TypeFactsError(mapping.source.moduleId, probe.start, probe.end, "identity", "Cannot determine a finite set of declaration identities. Preserve the value's inferred type, use an explicit union, or use a generic parameter."));
|
|
544
|
+
});
|
|
545
|
+
for (const [key, probe] of mapping.probes) if (!matched.has(key)) unavailable(new TypeFactsError(mapping.source.moduleId, probe.start, probe.end, "checker", "Projected expression has no matching checker AST node"));
|
|
546
|
+
facts.set(mapping.source.moduleId, values);
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
facts,
|
|
550
|
+
unverified
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
// src/browser/project.ts
|
|
555
|
+
/** Owns the design system, semantic checker, and compiler artifacts for one captured inventory. */
|
|
556
|
+
var BrowserProject = class {
|
|
557
|
+
/** Editor views retained for each analyzed entry in the captured inventory. */
|
|
558
|
+
#editors = /* @__PURE__ */ new Map();
|
|
559
|
+
/** Owned configuration records and callbacks fixed for this project's lifetime. */
|
|
560
|
+
#options;
|
|
561
|
+
/** Copy of the original inventory used by source, CSS, and checker reads. */
|
|
562
|
+
#files;
|
|
563
|
+
/** Owned checker for the captured virtual inventory. */
|
|
564
|
+
#facts;
|
|
565
|
+
/** Prepared sources shared by analyses of different entries. */
|
|
566
|
+
#compilation = new CompilationProject();
|
|
567
|
+
/** Virtual paths read by CSS or plugins. Changes to these files reload CSS. */
|
|
568
|
+
#cssDependencies = /* @__PURE__ */ new Set();
|
|
569
|
+
/** Lazily loaded CSS graph shared by all entry analyses. */
|
|
570
|
+
#loader;
|
|
571
|
+
/** Original or recovered CSS graph retained for queries. Sorting and fixes require original CSS. */
|
|
572
|
+
#editorCss;
|
|
573
|
+
/** Native session retaining successful compiler artifacts across entry analyses. */
|
|
574
|
+
#session;
|
|
575
|
+
/** Serializes analyses and permits subsequent work after a failure. */
|
|
576
|
+
#queue = Promise.resolve();
|
|
577
|
+
/** Prevents new analyses and suppresses editor answers after closure starts. */
|
|
578
|
+
#closed = false;
|
|
579
|
+
/** Resource placeholders supplied by the loaded CSS graph. */
|
|
580
|
+
#resources = [];
|
|
581
|
+
/** Paths that the loaded CSS graph marks for stylesheet lint, in load order. */
|
|
582
|
+
#lintSources = [];
|
|
583
|
+
/** Plugin runtime of the retained loader. */
|
|
584
|
+
#plugins;
|
|
585
|
+
/** Analysis graphs keyed by full entry identity, invalidated when native artifacts are removed. */
|
|
586
|
+
#cache = /* @__PURE__ */ new Map();
|
|
587
|
+
/**
|
|
588
|
+
* Copies the files and configuration without loading CSS or compiling sources.
|
|
589
|
+
*
|
|
590
|
+
* @param options - Captured files and configuration. Use replaceFiles between transactions to change sources.
|
|
591
|
+
*/
|
|
592
|
+
constructor(options) {
|
|
593
|
+
this.#options = {
|
|
594
|
+
...options,
|
|
595
|
+
config: captureProjectConfig(options.config)
|
|
596
|
+
};
|
|
597
|
+
this.#files = new Map(options.files);
|
|
598
|
+
this.#facts = new BrowserTypeFactsService({
|
|
599
|
+
root: options.root,
|
|
600
|
+
files: this.#files,
|
|
601
|
+
tsconfig: options.config.tsconfig
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Selects the document identity shared by compiler reports and CSS maps.
|
|
606
|
+
*
|
|
607
|
+
* @param file - Absolute path in the virtual filesystem.
|
|
608
|
+
* @returns The configured URI, or the path prefixed with `file://`.
|
|
609
|
+
*/
|
|
610
|
+
#documentUri(file) {
|
|
611
|
+
return this.#options.documentUri?.(file) ?? `file://${file}`;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Reads captured text without accessing the physical filesystem.
|
|
615
|
+
*
|
|
616
|
+
* @param file - Exact path key in the virtual filesystem.
|
|
617
|
+
* @returns The text currently stored under that key.
|
|
618
|
+
* @throws If the virtual file is absent.
|
|
619
|
+
*/
|
|
620
|
+
async #read(file) {
|
|
621
|
+
const text = this.#files.get(file);
|
|
622
|
+
if (text === void 0) throw new Error(`Virtual file does not exist: ${file}`);
|
|
623
|
+
return text;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Loads the configured CSS graph once and creates the native session that uses it.
|
|
627
|
+
*
|
|
628
|
+
* @returns The retained loader.
|
|
629
|
+
* @throws If resolving, reading, or loading the CSS graph fails.
|
|
630
|
+
*/
|
|
631
|
+
async #designSystem() {
|
|
632
|
+
if (!this.#loader) {
|
|
633
|
+
const { config, root } = this.#options;
|
|
634
|
+
const loaded = await loadCssGraph(resolve(root, cssEntrypoint(config)), compilerOptions(config), this.#cssHost(), void 0, void 0, {
|
|
635
|
+
plugins: config.plugins,
|
|
636
|
+
tailwind: config.tailwind,
|
|
637
|
+
important: config.important,
|
|
638
|
+
root
|
|
639
|
+
});
|
|
640
|
+
this.#loader = loaded.loader;
|
|
641
|
+
this.#resources = loaded.resources;
|
|
642
|
+
this.#lintSources = loaded.lintSources;
|
|
643
|
+
this.#plugins = loaded.plugins;
|
|
644
|
+
this.#session = new NativeProjectSession(this.#loader, false, "development", config.naming);
|
|
645
|
+
attachPlugins(this.#session, this.#plugins);
|
|
646
|
+
}
|
|
647
|
+
return this.#loader;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Creates CSS loader operations backed by this project's captured virtual inventory.
|
|
651
|
+
*
|
|
652
|
+
* @returns A host that resolves style imports and uses document URIs for diagnostics and maps.
|
|
653
|
+
* Its reads reject missing files, and its resolver rejects unresolved imports. Observed paths
|
|
654
|
+
* determine when replacement files reload CSS.
|
|
655
|
+
*/
|
|
656
|
+
#cssHost() {
|
|
657
|
+
/**
|
|
658
|
+
* Selects the document identity of a virtual stylesheet.
|
|
659
|
+
*
|
|
660
|
+
* @param file - Absolute virtual path.
|
|
661
|
+
* @returns The configured document URI.
|
|
662
|
+
*/
|
|
663
|
+
const uri = (file) => this.#documentUri(file);
|
|
664
|
+
return {
|
|
665
|
+
resolve: async (specifier, importer) => {
|
|
666
|
+
const resolved = resolveVirtualModule(this.#files, specifier, importer, "style");
|
|
667
|
+
if (!resolved) throw new Error(`Cannot resolve CSS ${specifier} from ${importer}`);
|
|
668
|
+
return resolved;
|
|
669
|
+
},
|
|
670
|
+
read: (file) => this.#read(file),
|
|
671
|
+
documentUri: uri,
|
|
672
|
+
sourceMapSource: uri,
|
|
673
|
+
watch: (id) => {
|
|
674
|
+
this.#cssDependencies.add(id);
|
|
675
|
+
},
|
|
676
|
+
plugins: {
|
|
677
|
+
load: async (specifier, importer, watch) => {
|
|
678
|
+
if (!this.#options.plugins) throw new Error(`This host cannot load plugin ${specifier}`);
|
|
679
|
+
return this.#options.plugins.load(specifier, importer, watch);
|
|
680
|
+
},
|
|
681
|
+
resolve: async (specifier, importer) => resolveVirtualModule(this.#files, specifier, importer) ?? await this.#options.plugins?.resolve(specifier, importer),
|
|
682
|
+
read: async (id) => this.#files.get(id) ?? (this.#options.plugins ? this.#options.plugins.read(id) : this.#read(id)),
|
|
683
|
+
list: async (id) => {
|
|
684
|
+
const entries = pluginDirectory(this.#files, id);
|
|
685
|
+
if (!entries.length) {
|
|
686
|
+
if (this.#options.plugins?.list) return this.#options.plugins.list(id);
|
|
687
|
+
throw new Error(`Directory ${id} does not exist`);
|
|
688
|
+
}
|
|
689
|
+
return entries;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Reports stylesheet lint for the CSS files that this project lints.
|
|
696
|
+
*
|
|
697
|
+
* @returns Linted virtual paths in load order, and the reports whose primary location is one of
|
|
698
|
+
* them.
|
|
699
|
+
* @throws If the project is closed or the CSS graph cannot be loaded.
|
|
700
|
+
*/
|
|
701
|
+
stylesheetLint() {
|
|
702
|
+
if (this.#closed) return Promise.reject(/* @__PURE__ */ new Error("Browser project is closed"));
|
|
703
|
+
const task = this.#queue.then(async () => {
|
|
704
|
+
const loader = await this.#designSystem();
|
|
705
|
+
return {
|
|
706
|
+
sources: [...this.#lintSources],
|
|
707
|
+
reports: loader.stylesheetReports()
|
|
708
|
+
};
|
|
709
|
+
});
|
|
710
|
+
this.#queue = task.catch(() => {});
|
|
711
|
+
return task;
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Creates compiler operations that read the current virtual files.
|
|
715
|
+
*
|
|
716
|
+
* @param onModule - Optional callback for each module the compiler attempts to analyze.
|
|
717
|
+
* @returns A host using this project's configuration, files, and custom source provider.
|
|
718
|
+
* Its reads reject missing files. Its resolver returns null for unresolved requests.
|
|
719
|
+
*/
|
|
720
|
+
#host(onModule) {
|
|
721
|
+
const { config, root } = this.#options;
|
|
722
|
+
const uri = (file) => this.#documentUri(file);
|
|
723
|
+
const read = (file) => this.#read(file);
|
|
724
|
+
/**
|
|
725
|
+
* Describes a virtual file for compilation and checker preparation.
|
|
726
|
+
*
|
|
727
|
+
* @param file - Absolute virtual path whose extension selects its source format.
|
|
728
|
+
* @returns Metadata with project-relative module and projection names and an absolute checker path.
|
|
729
|
+
*/
|
|
730
|
+
const descriptor = (file) => ({
|
|
731
|
+
moduleId: relative(root, file),
|
|
732
|
+
checkerFileName: file,
|
|
733
|
+
projectionFileName: relative(root, file),
|
|
734
|
+
document: {
|
|
735
|
+
uri: uri(file),
|
|
736
|
+
format: fileSourceKind(file).format
|
|
737
|
+
},
|
|
738
|
+
syntax: fileSourceKind(file).syntax
|
|
739
|
+
});
|
|
740
|
+
return {
|
|
741
|
+
onModule,
|
|
742
|
+
describe: descriptor,
|
|
743
|
+
read,
|
|
744
|
+
typeFactsResolution: config.typeFacts !== false,
|
|
745
|
+
supports: (file) => config.sources?.kind === "custom" ? config.sources.supports(file) : /\.[cm]?[jt]sx?$/.test(file) && !/\.d\.[cm]?ts$/.test(file),
|
|
746
|
+
load: async (file) => {
|
|
747
|
+
const input = config.sources?.kind === "custom" ? await config.sources.load(file, {
|
|
748
|
+
root,
|
|
749
|
+
documents: this.#files
|
|
750
|
+
}) : {
|
|
751
|
+
resolverId: file,
|
|
752
|
+
...descriptor(file),
|
|
753
|
+
document: {
|
|
754
|
+
...descriptor(file).document,
|
|
755
|
+
code: await read(file)
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
return !("kind" in input) && config.projection?.kind === "custom" ? config.projection.prepare(input) : input;
|
|
759
|
+
},
|
|
760
|
+
resolve: async (specifier, importer) => {
|
|
761
|
+
const custom = config.sources?.kind === "custom" && config.sources.resolve ? await config.sources.resolve(specifier, importer, {
|
|
762
|
+
root,
|
|
763
|
+
documents: this.#files
|
|
764
|
+
}) : null;
|
|
765
|
+
if (custom) return { id: custom };
|
|
766
|
+
const resolved = specifier.startsWith(".") || specifier.startsWith("/") ? resolveVirtualModule(this.#files, specifier, importer, "source") : null;
|
|
767
|
+
return resolved ? { id: resolved } : null;
|
|
768
|
+
},
|
|
769
|
+
watch: () => {},
|
|
770
|
+
warn: () => {}
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Replaces virtual files after earlier operations finish and clears cached analysis and editor results.
|
|
775
|
+
* Source edits keep CSS loaded. CSS dependencies, package metadata, and file additions or deletions
|
|
776
|
+
* cause the next operation to reload CSS.
|
|
777
|
+
*
|
|
778
|
+
* @param files - All replacement files, copied before the update is queued.
|
|
779
|
+
* @returns Completion of the update. Unchanged files have no effect.
|
|
780
|
+
* @throws If the project is closed when the update runs.
|
|
781
|
+
*/
|
|
782
|
+
replaceFiles(files) {
|
|
783
|
+
const captured = new Map(files);
|
|
784
|
+
const task = this.#queue.then(() => {
|
|
785
|
+
if (this.#closed) throw new Error("Browser project is closed");
|
|
786
|
+
const changed = new Set([...this.#files.keys(), ...captured.keys()].filter((id) => this.#files.get(id) !== captured.get(id)));
|
|
787
|
+
if (!changed.size) return;
|
|
788
|
+
const resolutionChanged = [...changed].some((id) => /\.json$/i.test(id) || this.#files.has(id) !== captured.has(id));
|
|
789
|
+
this.#compilation.invalidate(changed);
|
|
790
|
+
this.#files.clear();
|
|
791
|
+
for (const [id, text] of captured) this.#files.set(id, text);
|
|
792
|
+
this.#cache.clear();
|
|
793
|
+
this.#editors.clear();
|
|
794
|
+
if (resolutionChanged || [...changed].some((id) => isStylesheet(id) || this.#cssDependencies.has(id))) {
|
|
795
|
+
this.#loader = void 0;
|
|
796
|
+
this.#editorCss = void 0;
|
|
797
|
+
this.#session = void 0;
|
|
798
|
+
this.#plugins = void 0;
|
|
799
|
+
this.#resources = [];
|
|
800
|
+
this.#lintSources = [];
|
|
801
|
+
this.#cssDependencies.clear();
|
|
802
|
+
}
|
|
803
|
+
});
|
|
804
|
+
this.#queue = task.catch(() => {});
|
|
805
|
+
return task;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Loads target sources together and prepares their plugin candidates for later analysis.
|
|
809
|
+
*
|
|
810
|
+
* @param ids - Full virtual resolver IDs of the targets.
|
|
811
|
+
* @returns Completion of preparation, or no work after closure. Loading and plugin failures are
|
|
812
|
+
* left for each target's analysis to report. A failed plugin runtime is discarded before retrying.
|
|
813
|
+
*/
|
|
814
|
+
prepare(ids) {
|
|
815
|
+
const task = this.#queue.then(async () => {
|
|
816
|
+
if (this.#closed) return;
|
|
817
|
+
try {
|
|
818
|
+
const loader = await this.#designSystem();
|
|
819
|
+
await this.#compilation.prepare(ids, this.#host(), this.#session);
|
|
820
|
+
await prepareSourcePlugins(this.#session, loader, this.#compilation.texts());
|
|
821
|
+
} catch {
|
|
822
|
+
this.#loader = void 0;
|
|
823
|
+
this.#session = void 0;
|
|
824
|
+
this.#plugins = void 0;
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
this.#queue = task.catch(() => {});
|
|
828
|
+
return task;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Analyzes and transforms an entry with its demanded semantic dependencies.
|
|
832
|
+
*
|
|
833
|
+
* @param id - Absolute virtual source path, including any query selecting distinct source.
|
|
834
|
+
* @returns Readonly reports, code, and dependency coverage, shared by cache reads.
|
|
835
|
+
* @throws If the project is closed, CSS loading fails, or compilation fails.
|
|
836
|
+
*/
|
|
837
|
+
analyze(id) {
|
|
838
|
+
if (this.#closed) return Promise.reject(/* @__PURE__ */ new Error("Browser project is closed"));
|
|
839
|
+
const task = this.#queue.then(async () => {
|
|
840
|
+
const cached = this.#cache.get(id);
|
|
841
|
+
if (cached) return cached;
|
|
842
|
+
const { config } = this.#options;
|
|
843
|
+
await this.#designSystem();
|
|
844
|
+
const attempted = /* @__PURE__ */ new Set();
|
|
845
|
+
const host = this.#host((id) => attempted.add(id));
|
|
846
|
+
let result;
|
|
847
|
+
try {
|
|
848
|
+
result = await analyzeModule(this.#session, () => config.typeFacts === false ? void 0 : this.#facts, id, host, { overlayFiles: this.#files }, this.#compilation);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
this.#invalidate(attempted);
|
|
851
|
+
throw error;
|
|
852
|
+
}
|
|
853
|
+
if (result.generation === "blocked") this.#invalidate(attempted);
|
|
854
|
+
result.sources = structuredClone(result.sources);
|
|
855
|
+
const editor = new EditorSnapshot(result, this.#session, this.#loader, config, await this.#plugins?.catalog() ?? [], this.#plugins);
|
|
856
|
+
for (const report of editor.reports()) {
|
|
857
|
+
const batch = result.batches.find((batch) => batch.reports.some((item) => item.primary.location.uri === report.primary.location.uri)) ?? result.batches[0];
|
|
858
|
+
if (batch) batch.reports.push(report);
|
|
859
|
+
}
|
|
860
|
+
this.#editors.set(id, editor);
|
|
861
|
+
const published = result;
|
|
862
|
+
this.#cache.set(id, published);
|
|
863
|
+
return published;
|
|
864
|
+
});
|
|
865
|
+
this.#queue = task.catch(() => {});
|
|
866
|
+
return task;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Returns document CSS for successfully compiled graphs. automatic:false includes
|
|
870
|
+
* only shared base CSS. Local text resources become data URLs; remote URLs retain
|
|
871
|
+
* their authored values.
|
|
872
|
+
*
|
|
873
|
+
* @returns Document CSS and naming fallbacks, or empty CSS and reports before session creation.
|
|
874
|
+
* @throws If an emitted local resource is absent from the captured files.
|
|
875
|
+
*/
|
|
876
|
+
css() {
|
|
877
|
+
if (!this.#session) return {
|
|
878
|
+
css: "",
|
|
879
|
+
rejectedNames: []
|
|
880
|
+
};
|
|
881
|
+
if (this.#options.config.automatic === false) {
|
|
882
|
+
const output = this.#session.baseCss();
|
|
883
|
+
return {
|
|
884
|
+
css: this.#replaceResources(output.css, this.#resources),
|
|
885
|
+
rejectedNames: output.rejectedNames
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
const plan = this.#session.planStylesheet({
|
|
889
|
+
modules: this.#modules(),
|
|
890
|
+
coverage: { kind: "observed" },
|
|
891
|
+
placement: "document"
|
|
892
|
+
});
|
|
893
|
+
return {
|
|
894
|
+
css: this.#replaceResources(finalizeCss(plan), [...this.#resources, ...plan.resources.map((resource) => ({
|
|
895
|
+
...resource,
|
|
896
|
+
sourceName: resource.moduleId
|
|
897
|
+
}))]),
|
|
898
|
+
rejectedNames: plan.rejectedNames
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Queries a captured source graph or a stylesheet in the project's CSS graph.
|
|
903
|
+
* CSS completion, hover, resolution, and colors retry failed graph loads with recovered
|
|
904
|
+
* definitions. CSS sorting and lint fixes require the original graph to load successfully.
|
|
905
|
+
* Plugin path completion and links read captured files inside the project root without
|
|
906
|
+
* loading the CSS graph or executing plugins.
|
|
907
|
+
* Script queries first analyze their entry.
|
|
908
|
+
*
|
|
909
|
+
* @param id - Absolute virtual entry path, including a query that selects distinct source.
|
|
910
|
+
* @param request - Operation with original UTF-16 offsets for that source.
|
|
911
|
+
* @returns The editor answer, or undefined when no snapshot is available, the CSS graph
|
|
912
|
+
* does not mark the stylesheet for a semantic query, or closure suppresses a pending answer.
|
|
913
|
+
* @throws If a script query starts after closure, or if entry analysis, CSS graph loading,
|
|
914
|
+
* source reading, or the editor query fails.
|
|
915
|
+
*/
|
|
916
|
+
async query(id, request) {
|
|
917
|
+
if (isStylesheet(id)) {
|
|
918
|
+
const task = this.#queue.then(async () => {
|
|
919
|
+
if (this.#closed) return;
|
|
920
|
+
if (!this.#files.has(id)) return;
|
|
921
|
+
const navigation = await queryPluginPaths(id, await this.#read(id), request, {
|
|
922
|
+
root: this.#options.root,
|
|
923
|
+
names: this.#options.config.plugins?.map((plugin) => plugin.name) ?? [],
|
|
924
|
+
documentUri: (file) => this.#documentUri(file),
|
|
925
|
+
host: {
|
|
926
|
+
resolve: async (specifier, importer) => await this.#options.plugins?.resolve(specifier, importer) ?? resolveVirtualModule(this.#files, specifier, importer),
|
|
927
|
+
complete: async (prefix, importer, root) => [...await completePluginPaths(prefix, importer, root, {
|
|
928
|
+
read: (file) => this.#read(file),
|
|
929
|
+
directory: async (directory) => pluginDirectory(this.#files, directory)
|
|
930
|
+
}), ...await this.#options.plugins?.complete?.(prefix, importer, root) ?? []]
|
|
931
|
+
}
|
|
932
|
+
});
|
|
933
|
+
if (navigation) return this.#closed ? void 0 : navigation;
|
|
934
|
+
if (request.kind === "sort" || request.kind === "fixes") {
|
|
935
|
+
await this.#designSystem();
|
|
936
|
+
if (this.#editorCss?.recovered) {
|
|
937
|
+
this.#editorCss = void 0;
|
|
938
|
+
for (const [source, editor] of this.#editors) if (editor instanceof StylesheetEditor) this.#editors.delete(source);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
if (!this.#editorCss) this.#editorCss = this.#loader ? {
|
|
942
|
+
loader: this.#loader,
|
|
943
|
+
resources: this.#resources,
|
|
944
|
+
lintSources: this.#lintSources,
|
|
945
|
+
recovered: false,
|
|
946
|
+
plugins: this.#plugins
|
|
947
|
+
} : await loadEditorCssGraph(resolve(this.#options.root, cssEntrypoint(this.#options.config)), compilerOptions(this.#options.config), this.#cssHost());
|
|
948
|
+
if (!this.#editorCss.lintSources.includes(id) || this.#closed) return;
|
|
949
|
+
if (!this.#editors.has(id)) {
|
|
950
|
+
const reports = this.#editorCss.recovered ? [] : this.#editorCss.loader.stylesheetReports().filter((report) => report.primary.location.uri === this.#documentUri(id));
|
|
951
|
+
this.#editors.set(id, new StylesheetEditor(id, await this.#read(id), reports, this.#editorCss.loader.editorQuery(), this.#options.config, await this.#editorCss.plugins?.catalog() ?? [], this.#editorCss.plugins));
|
|
952
|
+
}
|
|
953
|
+
const editor = this.#editors.get(id);
|
|
954
|
+
await editor?.prepare(id, request);
|
|
955
|
+
return this.#closed ? void 0 : editor?.query(id, request);
|
|
956
|
+
});
|
|
957
|
+
this.#queue = task.catch(() => {});
|
|
958
|
+
return task;
|
|
959
|
+
}
|
|
960
|
+
await this.analyze(id);
|
|
961
|
+
if (this.#closed) return;
|
|
962
|
+
const editor = this.#editors.get(id);
|
|
963
|
+
if (editor instanceof EditorSnapshot) await editor.prepare(id, request);
|
|
964
|
+
return editor?.query(id, request);
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Returns CSS values keyed by absolute source path for explicit stillwind/module-css imports.
|
|
968
|
+
* Parts preserve stylesheet occurrence order and include their content fingerprints.
|
|
969
|
+
*
|
|
970
|
+
* @returns A new map of module CSS records. No session produces an empty map.
|
|
971
|
+
* @throws If an emitted local resource is absent from the captured files.
|
|
972
|
+
*/
|
|
973
|
+
cssValues() {
|
|
974
|
+
const values = /* @__PURE__ */ new Map();
|
|
975
|
+
if (!this.#session) return values;
|
|
976
|
+
for (const id of this.#modules()) {
|
|
977
|
+
const plan = this.#session.planStylesheet({
|
|
978
|
+
modules: [id],
|
|
979
|
+
coverage: { kind: "observed" },
|
|
980
|
+
placement: "carrier"
|
|
981
|
+
});
|
|
982
|
+
const resources = [...this.#resources, ...plan.resources.map((resource) => ({
|
|
983
|
+
...resource,
|
|
984
|
+
sourceName: resource.moduleId
|
|
985
|
+
}))];
|
|
986
|
+
values.set(resolve(this.#options.root, id), {
|
|
987
|
+
css: this.#replaceResources(finalizeCss(plan), resources),
|
|
988
|
+
rejectedNames: plan.rejectedNames,
|
|
989
|
+
parts: plan.parts.map((part) => ({
|
|
990
|
+
banners: part.banners,
|
|
991
|
+
key: part.key,
|
|
992
|
+
css: this.#replaceResources(part.css, resources)
|
|
993
|
+
}))
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
return values;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Collects modules with generated code from retained successful graphs.
|
|
1000
|
+
*
|
|
1001
|
+
* @returns Distinct compiler identities in first graph occurrence order.
|
|
1002
|
+
*/
|
|
1003
|
+
#modules() {
|
|
1004
|
+
return [...new Set([...this.#cache.values()].filter((graph) => graph.generation === "complete").flatMap((graph) => graph.modules.filter((module) => module.code !== null).map((module) => module.moduleId)))];
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Removes cached graphs and editor snapshots affected by a rejected native transaction.
|
|
1008
|
+
*
|
|
1009
|
+
* @param modules - Compiler identities attempted by that transaction, including dependencies.
|
|
1010
|
+
*/
|
|
1011
|
+
#invalidate(modules) {
|
|
1012
|
+
for (const [id, graph] of this.#cache) if (modules.has(graph.entry) || graph.sources.some((source) => modules.has(source.moduleId))) {
|
|
1013
|
+
this.#cache.delete(id);
|
|
1014
|
+
this.#editors.delete(id);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Replaces emitted CSS placeholders with authored remote URLs or embedded local text.
|
|
1019
|
+
*
|
|
1020
|
+
* @param css - Generated CSS containing zero or more resource placeholders.
|
|
1021
|
+
* @param resources - Placeholder records with source names relative to the project root or absolute.
|
|
1022
|
+
* @returns CSS with JSON-escaped URL contents. SVG uses image/svg+xml and other local text uses text/plain.
|
|
1023
|
+
* @throws If a referenced local file is absent from the captured inventory.
|
|
1024
|
+
*/
|
|
1025
|
+
#replaceResources(css, resources) {
|
|
1026
|
+
for (const resource of resources) {
|
|
1027
|
+
if (!css.includes(resource.placeholder)) continue;
|
|
1028
|
+
let url = resource.specifier;
|
|
1029
|
+
if (!/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(url)) {
|
|
1030
|
+
const file = resolve(dirname(resolve(this.#options.root, resource.sourceName)), url);
|
|
1031
|
+
const source = this.#files.get(file);
|
|
1032
|
+
if (source === void 0) throw new Error(`Browser CSS resource is missing: ${file}`);
|
|
1033
|
+
url = `data:${file.endsWith(".svg") ? "image/svg+xml" : "text/plain"};charset=utf-8,${encodeURIComponent(source)}`;
|
|
1034
|
+
}
|
|
1035
|
+
css = css.replaceAll(resource.placeholder, JSON.stringify(url).slice(1, -1));
|
|
1036
|
+
}
|
|
1037
|
+
return css;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Prevents new analyses, waits for queued work, and releases the checker, snapshots, and native session.
|
|
1041
|
+
*
|
|
1042
|
+
* @returns Completion of project cleanup.
|
|
1043
|
+
*/
|
|
1044
|
+
async close() {
|
|
1045
|
+
this.#closed = true;
|
|
1046
|
+
await this.#queue;
|
|
1047
|
+
this.#facts.close();
|
|
1048
|
+
this.#editors.clear();
|
|
1049
|
+
this.#session = void 0;
|
|
1050
|
+
this.#loader = void 0;
|
|
1051
|
+
this.#editorCss = void 0;
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
/**
|
|
1055
|
+
* Converts a workspace URI to its decoded absolute path without filesystem access.
|
|
1056
|
+
*
|
|
1057
|
+
* @param uri - Absolute URI whose pathname identifies a file in the virtual inventory.
|
|
1058
|
+
* @returns The decoded pathname; the scheme and authority are omitted.
|
|
1059
|
+
* @throws If the URI or its percent encoding is invalid.
|
|
1060
|
+
*/
|
|
1061
|
+
function virtualPath(uri) {
|
|
1062
|
+
return decodeURIComponent(new URL(uri).pathname);
|
|
1063
|
+
}
|
|
1064
|
+
export { BrowserProject, BrowserTypeFactsService, EditorSnapshot, TypeFactsError, defaultPluginExport, resolveVirtualModule, virtualPath };
|
|
1065
|
+
|
|
1066
|
+
//# sourceMappingURL=browser.js.map
|