@styloviz/schematics 2.0.1 → 2.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.
@@ -0,0 +1,404 @@
1
+ 'use strict';
2
+ /**
3
+ * `ng g @styloviz/core:sources` — Tailwind scans only the kit files the app
4
+ * uses (live-user test M-1, step A1).
5
+ *
6
+ * `ng add` points Tailwind at the whole of node_modules/@styloviz. With an
7
+ * install bundle that is every package, used or not, and a real app then fails
8
+ * Angular's default 1 MB budget on stylesheet size alone. This schematic
9
+ * replaces that broad line with one `@source` per kit file the app's imports
10
+ * reach (see walk.js), plus the app's own code, inside one marked block of the
11
+ * global stylesheet:
12
+ *
13
+ * @import "tailwindcss" source(none);
14
+ * @import "@styloviz/core/styles/styloviz.css";
15
+ * / * styloviz:sources start … * /
16
+ * @source "./";
17
+ * @source "../node_modules/@styloviz/forms/fesm2022/styloviz-forms-checkbox.mjs";
18
+ * / * styloviz:sources end * /
19
+ *
20
+ * `source(none)` is required, not tidy-up: measured on Tailwind 4.3, a file
21
+ * `@source` inside node_modules is widened to its WHOLE package whenever any
22
+ * other source is an ancestor of node_modules — and the default
23
+ * `@import "tailwindcss"` scans from the workspace root. With `source(none)`
24
+ * nothing is scanned implicitly, so the block lists what used to be found
25
+ * automatically: the app's source root, every library project's source root,
26
+ * the build's asset folders, and any app file reached outside them.
27
+ *
28
+ * The kit stylesheet's single import becomes a second block of `@import`s:
29
+ * only the parts of it (styles/parts, see parts.js) that the app's code and
30
+ * the listed kit files mention — the glow, a preset theme or a chart's
31
+ * animations are not paid for by an app that never draws them.
32
+ *
33
+ * --from-build list the kit files the last production build shipped
34
+ * (`ng build --stats-json`) instead of every file the imports
35
+ * reach: exact, where the walk is a superset (build-stats.js).
36
+ * --check write nothing; fail when the block is out of date (for CI).
37
+ * --all write the broad lines back (every installed kit package).
38
+ *
39
+ * Running it twice changes nothing the second time.
40
+ */
41
+ const { SchematicsException } = require('@angular-devkit/schematics');
42
+ const { posix } = require('node:path');
43
+ const { readWorkspace, buildTarget, projectPaths, globalCss } = require('../lib/workspace');
44
+ const { BLOCK_START, BLOCK_END, START_MARK, END_MARK, PARTS_START, PARTS_END, PARTS_START_MARK, PARTS_END_MARK } = require('../lib/sources-block');
45
+ const { loadTypeScript, createWalker, codeFilesUnder, packageName } = require('./walk');
46
+ const { statsFiles, shippedKitFiles, assertFresh } = require('./build-stats');
47
+ const { readPartsManifest, chooseParts, BINARY } = require('./parts');
48
+
49
+ const KIT_STYLESHEET = /@styloviz\/core\/styles\/styloviz\.css/;
50
+ /** The kit stylesheet imported whole, with nothing after the URL (a `layer(…)` or media list is left as it is). */
51
+ const KIT_IMPORT = /^\s*@import\s+(['"])@styloviz\/core\/styles\/styloviz\.css\1\s*;\s*$/;
52
+ const KIT_IMPORT_LINE = '@import "@styloviz/core/styles/styloviz.css";';
53
+ const TAILWIND_IMPORT = /^(\s*@import\s+(['"])tailwindcss(\/utilities(?:\.css)?)?\2)([^;]*)(;.*)$/;
54
+ const BROAD_KIT_SOURCE = /^\s*@source\s+(['"])[^'"]*node_modules\/@styloviz(?:-pro)?\/?\1\s*;\s*$/;
55
+ const SOURCE_LINE = /^\s*@source\s+(['"])([^'"]+)\1/;
56
+ const NODE_MODULES = '/node_modules';
57
+
58
+ /** A workspace path in the tree's form: leading slash, no trailing one. */
59
+ function normalize(path) {
60
+ const p = posix.join('/', path);
61
+ return p.length > 1 ? p.replace(/\/+$/, '') : p;
62
+ }
63
+
64
+ /** Whether `dir` is `path` itself or one of its parent folders. */
65
+ function contains(dir, path) {
66
+ return dir === '/' || path === dir || path.startsWith(`${dir}/`);
67
+ }
68
+
69
+ /** `@source` wants a path relative to the stylesheet. */
70
+ function relativeTo(dir, target) {
71
+ const r = posix.relative(dir, target);
72
+ if (!r) return './';
73
+ return r.startsWith('.') ? r : `./${r}`;
74
+ }
75
+
76
+ function isDir(tree, path) {
77
+ const dir = tree.getDir(path);
78
+ return dir.subfiles.length > 0 || dir.subdirs.length > 0;
79
+ }
80
+
81
+ /** The tsconfig `paths` the app builds with, following `extends` within the workspace. */
82
+ function tsPaths(tree, ts, tsConfig) {
83
+ let entries = null;
84
+ let base = '/';
85
+ let baseUrl = null;
86
+ const visited = new Set();
87
+ for (let file = tsConfig && normalize(tsConfig); file && tree.exists(file) && !visited.has(file); ) {
88
+ visited.add(file);
89
+ const { config } = ts.parseConfigFileTextToJson(file, tree.read(file).toString('utf8'));
90
+ const options = config?.compilerOptions ?? {};
91
+ if (entries === null && options.paths) {
92
+ entries = Object.entries(options.paths);
93
+ base = posix.dirname(file);
94
+ }
95
+ if (baseUrl === null && typeof options.baseUrl === 'string') baseUrl = normalize(posix.join(posix.dirname(file), options.baseUrl));
96
+ const parent = typeof config?.extends === 'string' && config.extends.startsWith('.') ? config.extends : null;
97
+ file = parent && normalize(posix.join(posix.dirname(file), parent.endsWith('.json') ? parent : `${parent}.json`));
98
+ }
99
+ return { base: baseUrl ?? base, entries: entries ?? [] };
100
+ }
101
+
102
+ /** Global stylesheet → the application projects that build with it. */
103
+ function stylesheetsToUpdate(tree, workspace, options) {
104
+ const apps = Object.entries(workspace.projects).filter(([, p]) => p.projectType === 'application');
105
+ if (options.project) {
106
+ const project = workspace.projects[options.project];
107
+ if (!project || project.projectType !== 'application') throw new SchematicsException(`No application project "${options.project}" in angular.json.`);
108
+ }
109
+ const groups = new Map();
110
+ for (const [name, project] of apps) {
111
+ if (options.project && name !== options.project) continue;
112
+ const css = globalCss(project);
113
+ const path = css && normalize(css);
114
+ if (!path || !tree.exists(path)) {
115
+ if (options.project) throw new SchematicsException(`"${name}" has no global .css stylesheet. Run ng add @styloviz/core first.`);
116
+ continue;
117
+ }
118
+ const text = tree.read(path).toString('utf8');
119
+ const usesKit =
120
+ KIT_STYLESHEET.test(text) || text.includes(START_MARK) || text.includes(PARTS_START_MARK) || text.split('\n').some((l) => BROAD_KIT_SOURCE.test(l));
121
+ if (!usesKit) {
122
+ if (options.project) throw new SchematicsException(`${path} does not import @styloviz/core/styles/styloviz.css. Run ng add @styloviz/core first.`);
123
+ continue;
124
+ }
125
+ if (!groups.has(path)) groups.set(path, []);
126
+ groups.get(path).push(name);
127
+ }
128
+ if (!groups.size) throw new SchematicsException('No application stylesheet imports @styloviz/core/styles/styloviz.css. Run ng add @styloviz/core first.');
129
+ return groups;
130
+ }
131
+
132
+ /** The folders Tailwind must scan whole once `source(none)` turns the automatic scan off. */
133
+ function scanRoots(tree, workspace, appNames, context) {
134
+ const roots = [];
135
+ const add = (path, what) => {
136
+ if (contains(path, NODE_MODULES)) {
137
+ throw new SchematicsException(
138
+ `${what} is ${path === '/' ? 'the workspace root' : path}, which contains node_modules. Tailwind would then read each kit ` +
139
+ 'package whole, so an exact list cannot work. Move that code into a folder of its own, or keep the broad scan with --all.',
140
+ );
141
+ }
142
+ if (!roots.some((r) => contains(r, path))) {
143
+ for (let i = roots.length - 1; i >= 0; i--) if (contains(path, roots[i])) roots.splice(i, 1);
144
+ roots.push(path);
145
+ }
146
+ };
147
+ const extraFiles = [];
148
+ for (const name of appNames) {
149
+ const project = workspace.projects[name];
150
+ add(normalize(projectPaths(project).sourceRoot), `The source root of "${name}"`);
151
+ }
152
+ for (const [name, project] of Object.entries(workspace.projects)) {
153
+ if (project.projectType !== 'library') continue;
154
+ const sourceRoot = normalize(projectPaths(project).sourceRoot);
155
+ if (isDir(tree, sourceRoot)) add(sourceRoot, `The source root of library "${name}"`);
156
+ }
157
+ for (const name of appNames) {
158
+ const options = buildTarget(workspace.projects[name])?.options ?? {};
159
+ for (const asset of options.assets ?? []) {
160
+ const input = normalize(typeof asset === 'string' ? asset : asset.input ?? '');
161
+ if (!isDir(tree, input)) continue;
162
+ if (contains(input, NODE_MODULES)) {
163
+ context.logger.warn(`! Asset folder ${input} contains node_modules; it is left out of the scan. List what it needs with an @source line of your own.`);
164
+ continue;
165
+ }
166
+ if (!roots.some((r) => contains(r, input))) roots.push(input);
167
+ }
168
+ const index = typeof options.index === 'string' ? options.index : options.index?.input;
169
+ if (index) {
170
+ const file = normalize(index);
171
+ if (tree.exists(file) && !roots.some((r) => contains(r, file))) extraFiles.push(file);
172
+ }
173
+ }
174
+ return { roots, extraFiles };
175
+ }
176
+
177
+ /** What the block should hold for this stylesheet, exact or broad. */
178
+ function plannedLines(tree, workspace, appNames, stylesPath, options, context) {
179
+ const stylesDir = posix.dirname(stylesPath);
180
+ if (options.all) {
181
+ const scopes = ['@styloviz', ...(isDir(tree, `${NODE_MODULES}/@styloviz-pro`) ? ['@styloviz-pro'] : [])];
182
+ return { lines: scopes.map((s) => `@source "${relativeTo(stylesDir, `${NODE_MODULES}/${s}`)}";`), kitFiles: null, parts: null };
183
+ }
184
+ const ts = loadTypeScript();
185
+ const { roots, extraFiles } = scanRoots(tree, workspace, appNames, context);
186
+ const firstBuild = buildTarget(workspace.projects[appNames[0]])?.options ?? {};
187
+ const unresolved = new Map();
188
+ const walker = createWalker({
189
+ ts,
190
+ read: (path) => tree.read(path)?.toString('utf8') ?? null,
191
+ roots,
192
+ paths: tsPaths(tree, ts, firstBuild.tsConfig),
193
+ onUnresolved: (spec, from, reason) => {
194
+ const key = reason === 'missing' ? packageName(spec) : spec;
195
+ if (!unresolved.has(key)) unresolved.set(key, { reason, from });
196
+ },
197
+ });
198
+ const appFiles = roots.flatMap((root) => codeFilesUnder(tree, root));
199
+ for (const file of appFiles) walker.addAppFile(file);
200
+ for (const [spec, { reason, from }] of unresolved) {
201
+ context.logger.warn(
202
+ reason === 'missing'
203
+ ? `! ${spec} is imported (${from.slice(1)}) but not installed; its styles are left out until it is.`
204
+ : `! ${spec} (imported in ${from.slice(1)}) is not an entry point of its package; left out.`,
205
+ );
206
+ }
207
+ const walked = walker.result();
208
+ const { localFiles } = walked;
209
+ let kitFiles = walked.kitFiles;
210
+ let note = '';
211
+ if (options.fromBuild) {
212
+ const stats = statsFiles(tree, workspace, appNames, options.stats);
213
+ assertFresh(tree, stats, [...appFiles, ...localFiles]);
214
+ // A barrel ships a few bytes of re-export glue and no classes: the walk
215
+ // already knows those files, and neither list needs them.
216
+ const barrels = new Set(walked.barrels);
217
+ const shipped = new Set([...shippedKitFiles(tree, stats)].filter((f) => !barrels.has(f)));
218
+ // The build is the truth; a shipped file the walk missed means the walk has a
219
+ // gap. Keep the file (it ships) and say so, rather than lose its styles.
220
+ const reached = new Set(kitFiles);
221
+ const missed = [...shipped].filter((f) => !reached.has(f));
222
+ if (missed.length) {
223
+ context.logger.warn(
224
+ `! The build ships ${missed.length} kit file(s) the import walk did not reach (${missed.slice(0, 2).map((f) => f.slice(14)).join(', ')}${missed.length > 2 ? ', …' : ''}). ` +
225
+ 'They are listed; please report this at https://github.com/styloviz/community/discussions.',
226
+ );
227
+ }
228
+ note = ` (${reached.size - (shipped.size - missed.length)} imported but not shipped, left out)`;
229
+ kitFiles = [...shipped].sort();
230
+ }
231
+ const paths = [...roots, ...[...new Set([...extraFiles, ...localFiles])].sort(), ...kitFiles];
232
+ return { lines: paths.map((p) => `@source "${relativeTo(stylesDir, p)}";`), kitFiles, note, parts: neededParts(tree, stylesDir, roots, [...extraFiles, ...localFiles, ...kitFiles]) };
233
+ }
234
+
235
+ /**
236
+ * The kit stylesheet parts the app needs, or null when the installed core has
237
+ * none (an older core: the whole stylesheet stays). Everything Tailwind will
238
+ * read is searched: every text file under the roots, the app files reached
239
+ * outside them, and the listed kit files.
240
+ */
241
+ function neededParts(tree, stylesDir, roots, files) {
242
+ const read = (path) => tree.read(path)?.toString('utf8') ?? null;
243
+ const manifest = readPartsManifest(read, stylesDir);
244
+ if (!manifest) return null;
245
+ function* texts() {
246
+ for (const root of roots) {
247
+ const under = [];
248
+ tree.getDir(root).visit((path) => {
249
+ if (!/\/(?:node_modules|\.angular|\.git|dist)\//.test(path) && !BINARY.test(path)) under.push(path);
250
+ });
251
+ for (const path of under) yield read(path) ?? '';
252
+ }
253
+ for (const path of files) yield read(path) ?? '';
254
+ }
255
+ return chooseParts(manifest, texts());
256
+ }
257
+
258
+ /**
259
+ * The stylesheet with the block in place: `source(none)` on the Tailwind import
260
+ * (or taken off, with --all), the broad kit lines gone, the block where the
261
+ * first of them — or the block itself — stood, else after the kit stylesheet.
262
+ */
263
+ function rewrite(css, stylesPath, lines, exact) {
264
+ const rows = css.split('\n');
265
+ let importRow = rows.findIndex((r) => TAILWIND_IMPORT.test(r) && !TAILWIND_IMPORT.exec(r)[3]);
266
+ if (importRow < 0) importRow = rows.findIndex((r) => TAILWIND_IMPORT.test(r));
267
+ if (importRow < 0) throw new SchematicsException(`${stylesPath} has no @import "tailwindcss". Run ng add @styloviz/core first.`);
268
+
269
+ const [, head, , , params, tail] = TAILWIND_IMPORT.exec(rows[importRow]);
270
+ let nextParams = params;
271
+ if (exact && !/\bsource\(\s*none\s*\)/.test(params)) {
272
+ if (/\bsource\(/.test(params)) {
273
+ throw new SchematicsException(
274
+ `${stylesPath}: the Tailwind import sets its own source(…). The exact list needs source(none): replace yours with ` +
275
+ 'source(none), add an @source line for the folder it named, and run this again.',
276
+ );
277
+ }
278
+ nextParams = `${params.replace(/\s+$/, '')} source(none)`;
279
+ } else if (!exact) {
280
+ nextParams = params.replace(/\s*\bsource\(\s*none\s*\)/, '');
281
+ }
282
+ rows[importRow] = `${head}${nextParams}${tail}`;
283
+
284
+ const drop = new Set();
285
+ const start = rows.findIndex((r) => r.includes(START_MARK));
286
+ if (start >= 0) {
287
+ const end = rows.findIndex((r, i) => i > start && r.includes(END_MARK));
288
+ if (end < 0) throw new SchematicsException(`${stylesPath}: the styloviz:sources block has no end marker. Restore "${BLOCK_END}" after its last line.`);
289
+ for (let i = start; i <= end; i++) drop.add(i);
290
+ }
291
+ rows.forEach((r, i) => {
292
+ if (!drop.has(i) && BROAD_KIT_SOURCE.test(r)) drop.add(i);
293
+ });
294
+ // After the kit stylesheet — its single import, or the end of its parts block.
295
+ const partsEnd = rows.findIndex((r) => r.includes(PARTS_END_MARK));
296
+ const kitImport = partsEnd >= 0 ? partsEnd : rows.findIndex((r) => KIT_STYLESHEET.test(r));
297
+ const anchor = drop.size ? Math.min(...drop) : (kitImport >= 0 ? kitImport : importRow) + 1;
298
+
299
+ const out = [];
300
+ for (let i = 0; i <= rows.length; i++) {
301
+ if (i === anchor) out.push(BLOCK_START, ...lines, BLOCK_END);
302
+ if (i < rows.length && !drop.has(i)) out.push(rows[i]);
303
+ }
304
+ return out.join('\n');
305
+ }
306
+
307
+ /**
308
+ * The kit stylesheet import: the parts block for `parts` (in place of the
309
+ * single import, or of the block already there), or the single import back
310
+ * when `parts` is null. Returns the stylesheet unchanged when it imports the
311
+ * kit stylesheet some other way (a relative path, a `layer(…)`).
312
+ */
313
+ function rewriteParts(css, stylesPath, parts) {
314
+ const rows = css.split('\n');
315
+ const start = rows.findIndex((r) => r.includes(PARTS_START_MARK));
316
+ let from;
317
+ let to;
318
+ if (start >= 0) {
319
+ const end = rows.findIndex((r, i) => i > start && r.includes(PARTS_END_MARK));
320
+ if (end < 0) throw new SchematicsException(`${stylesPath}: the styloviz:parts block has no end marker. Restore "${PARTS_END}" after its last line.`);
321
+ [from, to] = [start, end];
322
+ } else {
323
+ const single = rows.findIndex((r) => KIT_IMPORT.test(r));
324
+ if (single < 0) return css;
325
+ [from, to] = [single, single];
326
+ }
327
+ const replacement = parts
328
+ ? [PARTS_START, ...parts.map((p) => `@import "@styloviz/core/styles/${p.file}";`), PARTS_END]
329
+ : [KIT_IMPORT_LINE];
330
+ return [...rows.slice(0, from), ...replacement, ...rows.slice(to + 1)].join('\n');
331
+ }
332
+
333
+ /** Other `@source` lines that would widen every kit file back to its whole package. */
334
+ function wideningLines(css, stylesPath) {
335
+ const stylesDir = posix.dirname(stylesPath);
336
+ const rows = css.split('\n');
337
+ const start = rows.findIndex((r) => r.includes(START_MARK));
338
+ const end = rows.findIndex((r, i) => i > start && r.includes(END_MARK));
339
+ return rows.filter((r, i) => {
340
+ if (start >= 0 && i >= start && i <= end) return false;
341
+ const m = SOURCE_LINE.exec(r);
342
+ return m && contains(normalize(posix.join(stylesDir, m[2])), NODE_MODULES);
343
+ });
344
+ }
345
+
346
+ function blockLines(css) {
347
+ const rows = css.split('\n');
348
+ const start = rows.findIndex((r) => r.includes(START_MARK));
349
+ if (start < 0) return [];
350
+ const end = rows.findIndex((r, i) => i > start && r.includes(END_MARK));
351
+ return rows.slice(start + 1, end < 0 ? rows.length : end);
352
+ }
353
+
354
+ /** @param {{ project?: string, check?: boolean, all?: boolean, fromBuild?: boolean, stats?: string }} options */
355
+ function sources(options = {}) {
356
+ return (tree, context) => {
357
+ if (options.all && options.fromBuild) throw new SchematicsException('--all and --from-build ask for opposite lists; pick one.');
358
+ if (options.stats && !options.fromBuild) throw new SchematicsException('--stats names the build stats for --from-build; add --from-build.');
359
+ const workspace = readWorkspace(tree);
360
+ const stale = [];
361
+ for (const [stylesPath, appNames] of stylesheetsToUpdate(tree, workspace, options)) {
362
+ const css = tree.read(stylesPath).toString('utf8');
363
+ const { lines, kitFiles, note = '', parts } = plannedLines(tree, workspace, appNames, stylesPath, options, context);
364
+ const next = rewrite(rewriteParts(css, stylesPath, parts), stylesPath, lines, !options.all);
365
+ const name = stylesPath.slice(1);
366
+ for (const line of wideningLines(next, stylesPath)) {
367
+ context.logger.warn(`! ${name}: ${line.trim()} covers node_modules, so Tailwind still reads each kit package whole. Point it at a narrower folder.`);
368
+ }
369
+ if (next === css) {
370
+ context.logger.info(`✔ ${name} is up to date`);
371
+ continue;
372
+ }
373
+ if (options.check) {
374
+ const before = new Set(blockLines(css));
375
+ const after = new Set(lines);
376
+ const added = lines.filter((l) => !before.has(l));
377
+ const removed = [...before].filter((l) => !after.has(l));
378
+ const detail = [
379
+ rewriteParts(css, stylesPath, parts) !== css ? 'the kit stylesheet parts change' : '',
380
+ added.length ? `${added.length} to add (${added.slice(0, 3).map((l) => l.replace(/^@source\s+|;$/g, '')).join(', ')}${added.length > 3 ? ', …' : ''})` : '',
381
+ removed.length ? `${removed.length} to drop` : '',
382
+ ].filter(Boolean);
383
+ stale.push(`${name}: ${detail.length ? detail.join(', ') : 'the Tailwind import or the block differs'}`);
384
+ continue;
385
+ }
386
+ tree.overwrite(stylesPath, next);
387
+ if (kitFiles) {
388
+ const packages = new Set(kitFiles.map((f) => f.slice(f.lastIndexOf('/node_modules/') + 14).split('/').slice(0, 2).join('/')));
389
+ context.logger.info(`✔ ${name}: Tailwind now reads ${kitFiles.length} kit file(s) from ${packages.size} package(s), and your own code — not every installed kit package${note}`);
390
+ if (parts) context.logger.info(` and imports ${parts.length} part(s) of the kit stylesheet: ${parts.map((p) => p.name).join(', ')}`);
391
+ } else {
392
+ context.logger.info(`✔ ${name}: Tailwind reads every installed kit package again`);
393
+ }
394
+ }
395
+ if (stale.length) {
396
+ throw new SchematicsException(
397
+ `The kit's @source list is out of date:\n ${stale.join('\n ')}\nRun: ng g @styloviz/core:sources${options.all ? ' --all' : options.fromBuild ? ' --from-build' : ''}`,
398
+ );
399
+ }
400
+ return tree;
401
+ };
402
+ }
403
+
404
+ module.exports = { sources };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+ /**
3
+ * Which parts of the kit stylesheet an app needs (live-user test M-1, step A3).
4
+ *
5
+ * `@styloviz/core/styles/styloviz.css` is also shipped cut into parts
6
+ * (`styles/parts/*.css`), with `styles/parts/parts.json` naming, for each part,
7
+ * the class, attribute and keyframe names it styles. A part is needed when one
8
+ * of those names — or one of its prefixes — appears in a file Tailwind reads for
9
+ * this app: the app's own files and the kit files the block lists. The import
10
+ * order is the manifest's, which is styloviz.css's, so the cascade is unchanged.
11
+ *
12
+ * Matching is by whole name, the way Tailwind finds a class: `modal-panel` does
13
+ * not match `modal-panel--up`, and neither matches `my-modal-panel`. A prefix
14
+ * (`sv-theme-`) counts only where it does not begin one of the names, so
15
+ * `class="sv-theme-paper"` brings the paper preset and `'sv-theme-' + name`
16
+ * brings every preset.
17
+ */
18
+ const { posix } = require('node:path');
19
+
20
+ /** Files Tailwind does not read as text. */
21
+ const BINARY = /\.(?:png|jpe?g|gif|webp|avif|ico|bmp|tiff?|woff2?|ttf|otf|eot|mp[34]|webm|ogg|wav|flac|pdf|zip|gz|tgz|br|wasm)$/i;
22
+
23
+ /** The installed core's parts manifest and the folder it sits in, or null (a core without parts). */
24
+ function readPartsManifest(read, fromDir) {
25
+ for (let dir = fromDir; ; dir = posix.dirname(dir)) {
26
+ if (posix.basename(dir) !== 'node_modules') {
27
+ const coreDir = posix.join(dir, 'node_modules', '@styloviz', 'core');
28
+ if (read(`${coreDir}/package.json`) !== null) {
29
+ const text = read(`${coreDir}/styles/parts/parts.json`);
30
+ if (text === null) return null;
31
+ let manifest;
32
+ try {
33
+ manifest = JSON.parse(text);
34
+ } catch {
35
+ return null;
36
+ }
37
+ return Array.isArray(manifest?.parts) ? manifest : null;
38
+ }
39
+ }
40
+ if (dir === '/') return null;
41
+ }
42
+ }
43
+
44
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
+
46
+ /**
47
+ * The parts to import, in manifest order.
48
+ * @param {{ parts: { name: string, file: string, always: boolean, tokens: string[], prefixes: string[] }[] }} manifest
49
+ * @param {Iterable<string>} texts the contents of every file Tailwind reads for the app
50
+ */
51
+ function chooseParts(manifest, texts) {
52
+ const tokens = [...new Set(manifest.parts.flatMap((p) => p.tokens))];
53
+ const prefixes = [...new Set(manifest.parts.flatMap((p) => p.prefixes ?? []))];
54
+ const found = new Set();
55
+ const byToken = tokens.length ? new RegExp(`(?<![\\w-])(${tokens.map(escape).join('|')})(?![\\w-])`, 'g') : null;
56
+ // A prefix counts when what follows it is not one of the names: `'sv-theme-' + name`
57
+ // or `sv-theme-${name}` — a name built at run time, which could be any of them.
58
+ const byPrefix = prefixes.length ? new RegExp(`(?<![\\w-])(${prefixes.map(escape).join('|')})([\\w-]*)`, 'g') : null;
59
+ const known = new Set(tokens);
60
+ for (const text of texts) {
61
+ if (byToken) for (const m of text.matchAll(byToken)) found.add(m[1]);
62
+ if (byPrefix) for (const m of text.matchAll(byPrefix)) if (!known.has(m[1] + m[2])) found.add(`prefix:${m[1]}`);
63
+ if (found.size === tokens.length + prefixes.length) break;
64
+ }
65
+ return manifest.parts.filter(
66
+ (p) => p.always || p.tokens.some((t) => found.has(t)) || (p.prefixes ?? []).some((x) => found.has(`prefix:${x}`)),
67
+ );
68
+ }
69
+
70
+ module.exports = { readPartsManifest, chooseParts, BINARY };
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "StylovizSources",
4
+ "title": "Styloviz sources",
5
+ "type": "object",
6
+ "properties": {
7
+ "project": { "type": "string", "description": "The application whose stylesheet to update. Defaults to every application whose global stylesheet imports the kit stylesheet." },
8
+ "fromBuild": { "type": "boolean", "default": false, "description": "List the kit files the last production build shipped (ng build --stats-json) instead of every file the app's imports reach." },
9
+ "stats": { "type": "string", "description": "With --from-build: the build stats file to read. Defaults to browser-stats.json (and server-stats.json) in each app's output folder." },
10
+ "check": { "type": "boolean", "default": false, "description": "Write nothing; fail when the @source list is out of date (for CI)." },
11
+ "all": { "type": "boolean", "default": false, "description": "Scan every installed kit package again (the broad lines ng add writes)." }
12
+ }
13
+ }