@knighted/css 1.0.0-rc.0 → 1.0.0-rc.10

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.
Files changed (51) hide show
  1. package/bin/generate-types.js +31 -0
  2. package/dist/cjs/css.cjs +107 -25
  3. package/dist/cjs/css.d.cts +10 -6
  4. package/dist/cjs/generateTypes.cjs +636 -0
  5. package/dist/cjs/generateTypes.d.cts +104 -0
  6. package/dist/cjs/loader.cjs +128 -56
  7. package/dist/cjs/loader.d.cts +5 -0
  8. package/dist/cjs/loaderInternals.cjs +108 -0
  9. package/dist/cjs/loaderInternals.d.cts +23 -0
  10. package/dist/cjs/moduleGraph.cjs +431 -0
  11. package/dist/cjs/moduleGraph.d.cts +15 -0
  12. package/dist/cjs/moduleInfo.cjs +62 -0
  13. package/dist/cjs/moduleInfo.d.cts +10 -0
  14. package/dist/cjs/sassInternals.cjs +135 -0
  15. package/dist/cjs/sassInternals.d.cts +25 -0
  16. package/dist/cjs/stableNamespace.cjs +12 -0
  17. package/dist/cjs/stableNamespace.d.cts +3 -0
  18. package/dist/cjs/stableSelectors.cjs +44 -0
  19. package/dist/cjs/stableSelectors.d.cts +13 -0
  20. package/dist/cjs/stableSelectorsLiteral.cjs +104 -0
  21. package/dist/cjs/stableSelectorsLiteral.d.cts +19 -0
  22. package/dist/cjs/types.cjs +2 -0
  23. package/dist/cjs/types.d.cts +4 -0
  24. package/dist/css.d.ts +10 -6
  25. package/dist/css.js +107 -26
  26. package/dist/generateTypes.d.ts +104 -0
  27. package/dist/generateTypes.js +628 -0
  28. package/dist/loader.d.ts +5 -0
  29. package/dist/loader.js +127 -55
  30. package/dist/loaderInternals.d.ts +23 -0
  31. package/dist/loaderInternals.js +96 -0
  32. package/dist/moduleGraph.d.ts +15 -0
  33. package/dist/moduleGraph.js +425 -0
  34. package/dist/moduleInfo.d.ts +10 -0
  35. package/dist/moduleInfo.js +55 -0
  36. package/dist/sassInternals.d.ts +25 -0
  37. package/dist/sassInternals.js +124 -0
  38. package/dist/stableNamespace.d.ts +3 -0
  39. package/dist/stableNamespace.js +8 -0
  40. package/dist/stableSelectors.d.ts +13 -0
  41. package/dist/stableSelectors.js +36 -0
  42. package/dist/stableSelectorsLiteral.d.ts +19 -0
  43. package/dist/stableSelectorsLiteral.js +98 -0
  44. package/dist/types.d.ts +4 -0
  45. package/dist/types.js +1 -0
  46. package/loader-queries.d.ts +61 -0
  47. package/package.json +58 -8
  48. package/stable/_index.scss +57 -0
  49. package/stable/stable.css +15 -0
  50. package/types-stub/index.d.ts +5 -0
  51. package/types.d.ts +4 -0
@@ -0,0 +1,628 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { init, parse } from 'es-module-lexer';
7
+ import { moduleType } from 'node-module-type';
8
+ import { getTsconfig } from 'get-tsconfig';
9
+ import { createMatchPath } from 'tsconfig-paths';
10
+ import { cssWithMeta } from './css.js';
11
+ import { determineSelectorVariant, hasQueryFlag, TYPES_QUERY_FLAG, } from './loaderInternals.js';
12
+ import { buildStableSelectorsLiteral } from './stableSelectorsLiteral.js';
13
+ import { resolveStableNamespace } from './stableNamespace.js';
14
+ let activeCssWithMeta = cssWithMeta;
15
+ const DEFAULT_SKIP_DIRS = new Set([
16
+ 'node_modules',
17
+ '.git',
18
+ 'dist',
19
+ 'build',
20
+ 'coverage',
21
+ '.knighted-css',
22
+ '.next',
23
+ '.nuxt',
24
+ '.svelte-kit',
25
+ '.output',
26
+ 'tmp',
27
+ ]);
28
+ const SUPPORTED_EXTENSIONS = new Set([
29
+ '.ts',
30
+ '.tsx',
31
+ '.js',
32
+ '.jsx',
33
+ '.mts',
34
+ '.cts',
35
+ '.mjs',
36
+ '.cjs',
37
+ ]);
38
+ let moduleTypeDetector = moduleType;
39
+ let importMetaUrlProvider = getImportMetaUrl;
40
+ function resolvePackageRoot() {
41
+ const detectedType = moduleTypeDetector();
42
+ if (detectedType === 'commonjs' && typeof __dirname === 'string') {
43
+ return path.resolve(__dirname, '..');
44
+ }
45
+ const moduleUrl = importMetaUrlProvider();
46
+ if (moduleUrl) {
47
+ return path.resolve(path.dirname(fileURLToPath(moduleUrl)), '..');
48
+ }
49
+ return path.resolve(process.cwd(), 'node_modules', '@knighted', 'css');
50
+ }
51
+ function getImportMetaUrl() {
52
+ try {
53
+ return (0, eval)('import.meta.url');
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ const PACKAGE_ROOT = resolvePackageRoot();
60
+ const DEFAULT_TYPES_ROOT = path.join(PACKAGE_ROOT, 'types-stub');
61
+ const DEFAULT_OUT_DIR = path.join(PACKAGE_ROOT, 'node_modules', '.knighted-css');
62
+ export async function generateTypes(options = {}) {
63
+ const rootDir = path.resolve(options.rootDir ?? process.cwd());
64
+ const include = normalizeIncludeOptions(options.include, rootDir);
65
+ const outDir = path.resolve(options.outDir ?? DEFAULT_OUT_DIR);
66
+ const typesRoot = path.resolve(options.typesRoot ?? DEFAULT_TYPES_ROOT);
67
+ const tsconfig = loadTsconfigResolutionContext(rootDir);
68
+ await init;
69
+ await fs.mkdir(outDir, { recursive: true });
70
+ await fs.mkdir(typesRoot, { recursive: true });
71
+ const internalOptions = {
72
+ rootDir,
73
+ include,
74
+ outDir,
75
+ typesRoot,
76
+ stableNamespace: options.stableNamespace,
77
+ tsconfig,
78
+ };
79
+ return generateDeclarations(internalOptions);
80
+ }
81
+ async function generateDeclarations(options) {
82
+ const peerResolver = createProjectPeerResolver(options.rootDir);
83
+ const files = await collectCandidateFiles(options.include);
84
+ const manifestPath = path.join(options.outDir, 'manifest.json');
85
+ const previousManifest = await readManifest(manifestPath);
86
+ const nextManifest = {};
87
+ const selectorCache = new Map();
88
+ const processedSpecifiers = new Set();
89
+ const declarations = [];
90
+ const warnings = [];
91
+ let writes = 0;
92
+ for (const filePath of files) {
93
+ const matches = await findSpecifierImports(filePath);
94
+ for (const match of matches) {
95
+ const cleaned = match.specifier.trim();
96
+ const inlineFree = stripInlineLoader(cleaned);
97
+ if (!inlineFree.includes('?knighted-css'))
98
+ continue;
99
+ const { resource, query } = splitResourceAndQuery(inlineFree);
100
+ if (!query || !hasQueryFlag(query, TYPES_QUERY_FLAG)) {
101
+ continue;
102
+ }
103
+ if (processedSpecifiers.has(cleaned)) {
104
+ continue;
105
+ }
106
+ const resolvedNamespace = resolveStableNamespace(options.stableNamespace);
107
+ const resolvedPath = await resolveImportPath(resource, match.importer, options.rootDir, options.tsconfig);
108
+ if (!resolvedPath) {
109
+ warnings.push(`Unable to resolve ${resource} referenced by ${relativeToRoot(match.importer, options.rootDir)}.`);
110
+ continue;
111
+ }
112
+ const cacheKey = `${resolvedPath}::${resolvedNamespace}`;
113
+ let selectorMap = selectorCache.get(cacheKey);
114
+ if (!selectorMap) {
115
+ try {
116
+ const { css } = await activeCssWithMeta(resolvedPath, {
117
+ cwd: options.rootDir,
118
+ peerResolver,
119
+ });
120
+ selectorMap = buildStableSelectorsLiteral({
121
+ css,
122
+ namespace: resolvedNamespace,
123
+ resourcePath: resolvedPath,
124
+ emitWarning: message => warnings.push(message),
125
+ }).selectorMap;
126
+ }
127
+ catch (error) {
128
+ warnings.push(`Failed to extract CSS for ${relativeToRoot(resolvedPath, options.rootDir)}: ${formatErrorMessage(error)}`);
129
+ continue;
130
+ }
131
+ selectorCache.set(cacheKey, selectorMap);
132
+ }
133
+ const variant = determineSelectorVariant(query);
134
+ const declaration = formatModuleDeclaration(cleaned, variant, selectorMap);
135
+ const declarationHash = hashContent(declaration);
136
+ const fileName = buildDeclarationFileName(cleaned);
137
+ const targetPath = path.join(options.outDir, fileName);
138
+ const previousEntry = previousManifest[cleaned];
139
+ const needsWrite = previousEntry?.hash !== declarationHash || !(await fileExists(targetPath));
140
+ if (needsWrite) {
141
+ await fs.writeFile(targetPath, declaration, 'utf8');
142
+ writes += 1;
143
+ }
144
+ nextManifest[cleaned] = { file: fileName, hash: declarationHash };
145
+ if (needsWrite) {
146
+ declarations.push({ specifier: cleaned, filePath: targetPath });
147
+ }
148
+ processedSpecifiers.add(cleaned);
149
+ }
150
+ }
151
+ const removed = await removeStaleDeclarations(previousManifest, nextManifest, options.outDir);
152
+ await writeManifest(manifestPath, nextManifest);
153
+ const typesIndexPath = path.join(options.typesRoot, 'index.d.ts');
154
+ await writeTypesIndex(typesIndexPath, nextManifest, options.outDir);
155
+ if (Object.keys(nextManifest).length === 0) {
156
+ declarations.length = 0;
157
+ }
158
+ return {
159
+ written: writes,
160
+ removed,
161
+ declarations,
162
+ warnings,
163
+ outDir: options.outDir,
164
+ typesIndexPath,
165
+ };
166
+ }
167
+ function normalizeIncludeOptions(include, rootDir) {
168
+ if (!include || include.length === 0) {
169
+ return [rootDir];
170
+ }
171
+ return include.map(entry => path.isAbsolute(entry) ? entry : path.resolve(rootDir, entry));
172
+ }
173
+ async function collectCandidateFiles(entries) {
174
+ const files = [];
175
+ const visited = new Set();
176
+ async function walk(entryPath) {
177
+ const resolved = path.resolve(entryPath);
178
+ if (visited.has(resolved)) {
179
+ return;
180
+ }
181
+ visited.add(resolved);
182
+ let stat;
183
+ try {
184
+ stat = await fs.stat(resolved);
185
+ }
186
+ catch {
187
+ return;
188
+ }
189
+ if (stat.isDirectory()) {
190
+ const base = path.basename(resolved);
191
+ if (DEFAULT_SKIP_DIRS.has(base)) {
192
+ return;
193
+ }
194
+ const children = await fs.readdir(resolved, { withFileTypes: true });
195
+ for (const child of children) {
196
+ await walk(path.join(resolved, child.name));
197
+ }
198
+ return;
199
+ }
200
+ if (!stat.isFile()) {
201
+ return;
202
+ }
203
+ const ext = path.extname(resolved).toLowerCase();
204
+ if (!SUPPORTED_EXTENSIONS.has(ext)) {
205
+ return;
206
+ }
207
+ files.push(resolved);
208
+ }
209
+ for (const entry of entries) {
210
+ await walk(entry);
211
+ }
212
+ return files;
213
+ }
214
+ async function findSpecifierImports(filePath) {
215
+ let source;
216
+ try {
217
+ source = await fs.readFile(filePath, 'utf8');
218
+ }
219
+ catch {
220
+ return [];
221
+ }
222
+ if (!source.includes('?knighted-css')) {
223
+ return [];
224
+ }
225
+ const matches = [];
226
+ const [imports] = parse(source, filePath);
227
+ for (const record of imports) {
228
+ const specifier = record.n ?? source.slice(record.s, record.e);
229
+ if (specifier && specifier.includes('?knighted-css')) {
230
+ matches.push({ specifier, importer: filePath });
231
+ }
232
+ }
233
+ const requireRegex = /require\((['"])([^'"`]+?\?knighted-css[^'"`]*)\1\)/g;
234
+ let reqMatch;
235
+ while ((reqMatch = requireRegex.exec(source)) !== null) {
236
+ const spec = reqMatch[2];
237
+ if (spec) {
238
+ matches.push({ specifier: spec, importer: filePath });
239
+ }
240
+ }
241
+ return matches;
242
+ }
243
+ function stripInlineLoader(specifier) {
244
+ const idx = specifier.lastIndexOf('!');
245
+ return idx >= 0 ? specifier.slice(idx + 1) : specifier;
246
+ }
247
+ function splitResourceAndQuery(specifier) {
248
+ const hashIndex = specifier.indexOf('#');
249
+ const trimmed = hashIndex >= 0 ? specifier.slice(0, hashIndex) : specifier;
250
+ const queryIndex = trimmed.indexOf('?');
251
+ if (queryIndex < 0) {
252
+ return { resource: trimmed, query: '' };
253
+ }
254
+ return { resource: trimmed.slice(0, queryIndex), query: trimmed.slice(queryIndex) };
255
+ }
256
+ const projectRequireCache = new Map();
257
+ async function resolveImportPath(resourceSpecifier, importerPath, rootDir, tsconfig) {
258
+ if (!resourceSpecifier)
259
+ return undefined;
260
+ if (resourceSpecifier.startsWith('.')) {
261
+ return path.resolve(path.dirname(importerPath), resourceSpecifier);
262
+ }
263
+ if (resourceSpecifier.startsWith('/')) {
264
+ return path.resolve(rootDir, resourceSpecifier.slice(1));
265
+ }
266
+ const tsconfigResolved = await resolveWithTsconfigPaths(resourceSpecifier, tsconfig);
267
+ if (tsconfigResolved) {
268
+ return tsconfigResolved;
269
+ }
270
+ const requireFromRoot = getProjectRequire(rootDir);
271
+ try {
272
+ return requireFromRoot.resolve(resourceSpecifier);
273
+ }
274
+ catch {
275
+ return undefined;
276
+ }
277
+ }
278
+ function buildDeclarationFileName(specifier) {
279
+ const digest = crypto.createHash('sha1').update(specifier).digest('hex').slice(0, 12);
280
+ return `knt-${digest}.d.ts`;
281
+ }
282
+ function formatModuleDeclaration(specifier, variant, selectors) {
283
+ const literalSpecifier = JSON.stringify(specifier);
284
+ const selectorType = formatSelectorType(selectors);
285
+ const header = `declare module ${literalSpecifier} {`;
286
+ const footer = '}';
287
+ if (variant === 'types') {
288
+ return `${header}
289
+ export const knightedCss: string
290
+ export const stableSelectors: ${selectorType}
291
+ ${footer}
292
+ `;
293
+ }
294
+ const stableLine = ` export const stableSelectors: ${selectorType}`;
295
+ const shared = ` const combined: KnightedCssCombinedModule<Record<string, unknown>>
296
+ export const knightedCss: string
297
+ ${stableLine}`;
298
+ if (variant === 'combined') {
299
+ return `${header}
300
+ ${shared}
301
+ export default combined
302
+ ${footer}
303
+ `;
304
+ }
305
+ return `${header}
306
+ ${shared}
307
+ ${footer}
308
+ `;
309
+ }
310
+ function formatSelectorType(selectors) {
311
+ if (selectors.size === 0) {
312
+ return 'Readonly<Record<string, string>>';
313
+ }
314
+ const entries = Array.from(selectors.entries()).sort(([a], [b]) => a.localeCompare(b));
315
+ const lines = entries.map(([token, selector]) => ` readonly ${JSON.stringify(token)}: ${JSON.stringify(selector)}`);
316
+ return `Readonly<{
317
+ ${lines.join('\n')}
318
+ }>`;
319
+ }
320
+ function hashContent(content) {
321
+ return crypto.createHash('sha1').update(content).digest('hex');
322
+ }
323
+ async function readManifest(manifestPath) {
324
+ try {
325
+ const raw = await fs.readFile(manifestPath, 'utf8');
326
+ return JSON.parse(raw);
327
+ }
328
+ catch {
329
+ return {};
330
+ }
331
+ }
332
+ async function writeManifest(manifestPath, manifest) {
333
+ await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
334
+ }
335
+ async function removeStaleDeclarations(previous, next, outDir) {
336
+ const stale = Object.entries(previous).filter(([specifier]) => !next[specifier]);
337
+ let removed = 0;
338
+ for (const [, entry] of stale) {
339
+ const targetPath = path.join(outDir, entry.file);
340
+ try {
341
+ await fs.unlink(targetPath);
342
+ removed += 1;
343
+ }
344
+ catch {
345
+ // ignore
346
+ }
347
+ }
348
+ return removed;
349
+ }
350
+ async function writeTypesIndex(indexPath, manifest, outDir) {
351
+ const header = '// Generated by @knighted/css/generate-types\n// Do not edit.\n';
352
+ const references = Object.values(manifest)
353
+ .sort((a, b) => a.file.localeCompare(b.file))
354
+ .map(entry => {
355
+ const rel = path
356
+ .relative(path.dirname(indexPath), path.join(outDir, entry.file))
357
+ .split(path.sep)
358
+ .join('/');
359
+ return `/// <reference path="${rel}" />`;
360
+ });
361
+ const content = references.length > 0
362
+ ? `${header}
363
+ ${references.join('\n')}
364
+ `
365
+ : `${header}
366
+ `;
367
+ await fs.writeFile(indexPath, content, 'utf8');
368
+ }
369
+ function formatErrorMessage(error) {
370
+ if (error instanceof Error && typeof error.message === 'string') {
371
+ return error.message;
372
+ }
373
+ return String(error);
374
+ }
375
+ function relativeToRoot(filePath, rootDir) {
376
+ return path.relative(rootDir, filePath) || filePath;
377
+ }
378
+ async function fileExists(target) {
379
+ try {
380
+ await fs.access(target);
381
+ return true;
382
+ }
383
+ catch {
384
+ return false;
385
+ }
386
+ }
387
+ async function resolveWithTsconfigPaths(specifier, tsconfig) {
388
+ if (!tsconfig) {
389
+ return undefined;
390
+ }
391
+ if (tsconfig.matchPath) {
392
+ const matched = tsconfig.matchPath(specifier);
393
+ if (matched && (await fileExists(matched))) {
394
+ return matched;
395
+ }
396
+ }
397
+ if (tsconfig.absoluteBaseUrl && isNonRelativeSpecifier(specifier)) {
398
+ const candidate = path.join(tsconfig.absoluteBaseUrl, specifier.split('/').join(path.sep));
399
+ if (await fileExists(candidate)) {
400
+ return candidate;
401
+ }
402
+ }
403
+ return undefined;
404
+ }
405
+ function loadTsconfigResolutionContext(rootDir, loader = getTsconfig) {
406
+ let result;
407
+ try {
408
+ result = loader(rootDir);
409
+ }
410
+ catch {
411
+ return undefined;
412
+ }
413
+ if (!result) {
414
+ return undefined;
415
+ }
416
+ const compilerOptions = result.config.compilerOptions ?? {};
417
+ const configDir = path.dirname(result.path);
418
+ const absoluteBaseUrl = compilerOptions.baseUrl
419
+ ? path.resolve(configDir, compilerOptions.baseUrl)
420
+ : undefined;
421
+ const normalizedPaths = normalizeTsconfigPaths(compilerOptions.paths);
422
+ const matchPath = absoluteBaseUrl && normalizedPaths
423
+ ? createMatchPath(absoluteBaseUrl, normalizedPaths)
424
+ : undefined;
425
+ if (!absoluteBaseUrl && !matchPath) {
426
+ return undefined;
427
+ }
428
+ return { absoluteBaseUrl, matchPath };
429
+ }
430
+ function normalizeTsconfigPaths(paths) {
431
+ if (!paths) {
432
+ return undefined;
433
+ }
434
+ const normalized = {};
435
+ for (const [pattern, replacements] of Object.entries(paths)) {
436
+ if (!replacements) {
437
+ continue;
438
+ }
439
+ const values = Array.isArray(replacements) ? replacements : [replacements];
440
+ if (values.length === 0) {
441
+ continue;
442
+ }
443
+ normalized[pattern] = values;
444
+ }
445
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
446
+ }
447
+ function isNonRelativeSpecifier(specifier) {
448
+ if (!specifier) {
449
+ return false;
450
+ }
451
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
452
+ return false;
453
+ }
454
+ if (/^[a-z][\w+.-]*:/i.test(specifier)) {
455
+ return false;
456
+ }
457
+ return true;
458
+ }
459
+ function createProjectPeerResolver(rootDir) {
460
+ const resolver = getProjectRequire(rootDir);
461
+ return async (name) => {
462
+ const resolved = resolver.resolve(name);
463
+ return import(pathToFileURL(resolved).href);
464
+ };
465
+ }
466
+ function getProjectRequire(rootDir) {
467
+ const cached = projectRequireCache.get(rootDir);
468
+ if (cached) {
469
+ return cached;
470
+ }
471
+ const anchor = path.join(rootDir, 'package.json');
472
+ let loader;
473
+ try {
474
+ loader = createRequire(anchor);
475
+ }
476
+ catch {
477
+ loader = createRequire(path.join(process.cwd(), 'package.json'));
478
+ }
479
+ projectRequireCache.set(rootDir, loader);
480
+ return loader;
481
+ }
482
+ export async function runGenerateTypesCli(argv = process.argv.slice(2)) {
483
+ let parsed;
484
+ try {
485
+ parsed = parseCliArgs(argv);
486
+ }
487
+ catch (error) {
488
+ console.error(`[knighted-css] ${formatErrorMessage(error)}`);
489
+ process.exitCode = 1;
490
+ return;
491
+ }
492
+ if (parsed.help) {
493
+ printHelp();
494
+ return;
495
+ }
496
+ try {
497
+ const result = await generateTypes({
498
+ rootDir: parsed.rootDir,
499
+ include: parsed.include,
500
+ outDir: parsed.outDir,
501
+ typesRoot: parsed.typesRoot,
502
+ stableNamespace: parsed.stableNamespace,
503
+ });
504
+ reportCliResult(result);
505
+ }
506
+ catch (error) {
507
+ console.error('[knighted-css] generate-types failed.');
508
+ console.error(error);
509
+ process.exitCode = 1;
510
+ }
511
+ }
512
+ function parseCliArgs(argv) {
513
+ let rootDir = process.cwd();
514
+ const include = [];
515
+ let outDir;
516
+ let typesRoot;
517
+ let stableNamespace;
518
+ for (let i = 0; i < argv.length; i += 1) {
519
+ const arg = argv[i];
520
+ if (arg === '--help' || arg === '-h') {
521
+ return { rootDir, include, outDir, typesRoot, stableNamespace, help: true };
522
+ }
523
+ if (arg === '--root' || arg === '-r') {
524
+ const value = argv[++i];
525
+ if (!value) {
526
+ throw new Error('Missing value for --root');
527
+ }
528
+ rootDir = path.resolve(value);
529
+ continue;
530
+ }
531
+ if (arg === '--include' || arg === '-i') {
532
+ const value = argv[++i];
533
+ if (!value) {
534
+ throw new Error('Missing value for --include');
535
+ }
536
+ include.push(value);
537
+ continue;
538
+ }
539
+ if (arg === '--out-dir') {
540
+ const value = argv[++i];
541
+ if (!value) {
542
+ throw new Error('Missing value for --out-dir');
543
+ }
544
+ outDir = value;
545
+ continue;
546
+ }
547
+ if (arg === '--types-root') {
548
+ const value = argv[++i];
549
+ if (!value) {
550
+ throw new Error('Missing value for --types-root');
551
+ }
552
+ typesRoot = value;
553
+ continue;
554
+ }
555
+ if (arg === '--stable-namespace') {
556
+ const value = argv[++i];
557
+ if (!value) {
558
+ throw new Error('Missing value for --stable-namespace');
559
+ }
560
+ stableNamespace = value;
561
+ continue;
562
+ }
563
+ if (arg.startsWith('-')) {
564
+ throw new Error(`Unknown flag: ${arg}`);
565
+ }
566
+ include.push(arg);
567
+ }
568
+ return { rootDir, include, outDir, typesRoot, stableNamespace };
569
+ }
570
+ function printHelp() {
571
+ console.log(`Usage: knighted-css-generate-types [options]
572
+
573
+ Options:
574
+ -r, --root <path> Project root directory (default: cwd)
575
+ -i, --include <path> Additional directories/files to scan (repeatable)
576
+ --out-dir <path> Output directory for generated declarations
577
+ --types-root <path> Directory for generated @types entrypoint
578
+ --stable-namespace <name> Stable namespace prefix for generated selector maps
579
+ -h, --help Show this help message
580
+ `);
581
+ }
582
+ function reportCliResult(result) {
583
+ if (result.written === 0 && result.removed === 0) {
584
+ console.log('[knighted-css] No changes to ?knighted-css&types declarations (cache is up to date).');
585
+ }
586
+ else {
587
+ console.log(`[knighted-css] Updated ${result.written} declaration(s), removed ${result.removed}, output in ${result.outDir}.`);
588
+ }
589
+ console.log(`[knighted-css] Type references: ${result.typesIndexPath}`);
590
+ for (const warning of result.warnings) {
591
+ console.warn(`[knighted-css] ${warning}`);
592
+ }
593
+ }
594
+ function setCssWithMetaImplementation(impl) {
595
+ activeCssWithMeta = impl ?? cssWithMeta;
596
+ }
597
+ function setModuleTypeDetector(detector) {
598
+ moduleTypeDetector = detector ?? moduleType;
599
+ }
600
+ function setImportMetaUrlProvider(provider) {
601
+ importMetaUrlProvider = provider ?? getImportMetaUrl;
602
+ }
603
+ export const __generateTypesInternals = {
604
+ writeTypesIndex,
605
+ stripInlineLoader,
606
+ splitResourceAndQuery,
607
+ findSpecifierImports,
608
+ resolveImportPath,
609
+ resolvePackageRoot,
610
+ buildDeclarationFileName,
611
+ formatModuleDeclaration,
612
+ formatSelectorType,
613
+ relativeToRoot,
614
+ collectCandidateFiles,
615
+ normalizeIncludeOptions,
616
+ normalizeTsconfigPaths,
617
+ setCssWithMetaImplementation,
618
+ setModuleTypeDetector,
619
+ setImportMetaUrlProvider,
620
+ isNonRelativeSpecifier,
621
+ createProjectPeerResolver,
622
+ getProjectRequire,
623
+ loadTsconfigResolutionContext,
624
+ resolveWithTsconfigPaths,
625
+ parseCliArgs,
626
+ printHelp,
627
+ reportCliResult,
628
+ };
package/dist/loader.d.ts CHANGED
@@ -3,7 +3,12 @@ import { type CssOptions } from './css.js';
3
3
  export type KnightedCssCombinedModule<TModule> = TModule & {
4
4
  knightedCss: string;
5
5
  };
6
+ export interface KnightedCssVanillaOptions {
7
+ transformToEsm?: boolean;
8
+ }
6
9
  export interface KnightedCssLoaderOptions extends CssOptions {
10
+ vanilla?: KnightedCssVanillaOptions;
11
+ stableNamespace?: string;
7
12
  }
8
13
  declare const loader: LoaderDefinitionFunction<KnightedCssLoaderOptions>;
9
14
  export declare const pitch: PitchLoaderDefinitionFunction<KnightedCssLoaderOptions>;