@knighted/css 1.0.0-rc.6 → 1.0.0-rc.8

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,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from 'node:path'
4
+ import { fileURLToPath, pathToFileURL } from 'node:url'
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
7
+ const distPath = path.resolve(__dirname, '../dist/generateTypes.js')
8
+
9
+ async function main() {
10
+ try {
11
+ const mod = await import(pathToFileURL(distPath).href)
12
+ const runner =
13
+ typeof mod.runGenerateTypesCli === 'function'
14
+ ? mod.runGenerateTypesCli
15
+ : typeof mod.default === 'function'
16
+ ? mod.default
17
+ : undefined
18
+ if (typeof runner !== 'function') {
19
+ console.error('[knighted-css] Unable to load generateTypes CLI entry point.')
20
+ process.exitCode = 1
21
+ return
22
+ }
23
+ await runner(process.argv.slice(2))
24
+ } catch (error) {
25
+ console.error('[knighted-css] Failed to run generateTypes CLI.')
26
+ console.error(error)
27
+ process.exitCode = 1
28
+ }
29
+ }
30
+
31
+ void main()
package/dist/cjs/css.cjs CHANGED
@@ -128,14 +128,41 @@ async function compileStyleModule(file, { cwd, peerResolver, resolver, }) {
128
128
  }
129
129
  async function compileSass(filePath, indented, { cwd, peerResolver, resolver, }) {
130
130
  const sassModule = await optionalPeer('sass', 'Sass', peerResolver);
131
- const sass = sassModule;
131
+ const sass = resolveSassNamespace(sassModule);
132
132
  const importer = (0, sassInternals_js_1.createSassImporter)({ cwd, resolver });
133
- const result = await sass.compileAsync(filePath, {
134
- style: 'expanded',
135
- loadPaths: buildSassLoadPaths(filePath),
136
- importers: importer ? [importer] : undefined,
133
+ const loadPaths = buildSassLoadPaths(filePath);
134
+ if (typeof sass.compileAsync === 'function') {
135
+ const result = await sass.compileAsync(filePath, {
136
+ style: 'expanded',
137
+ loadPaths,
138
+ importers: importer ? [importer] : undefined,
139
+ });
140
+ return result.css;
141
+ }
142
+ if (typeof sass.render === 'function') {
143
+ return renderLegacySass(sass, filePath, indented, loadPaths);
144
+ }
145
+ throw new Error('@knighted/css: Installed "sass" package does not expose compileAsync or render APIs. Please update "sass" to a supported version.');
146
+ }
147
+ function renderLegacySass(sass, filePath, indented, loadPaths) {
148
+ return new Promise((resolve, reject) => {
149
+ sass.render({
150
+ file: filePath,
151
+ indentedSyntax: indented,
152
+ outputStyle: 'expanded',
153
+ includePaths: loadPaths,
154
+ }, (error, result) => {
155
+ if (error) {
156
+ reject(error);
157
+ return;
158
+ }
159
+ if (!result || typeof result.css === 'undefined') {
160
+ resolve('');
161
+ return;
162
+ }
163
+ resolve(result.css.toString());
164
+ });
137
165
  });
138
- return result.css;
139
166
  }
140
167
  // Ensure Sass can resolve bare module specifiers by walking node_modules folders.
141
168
  function buildSassLoadPaths(filePath) {
@@ -223,6 +250,27 @@ async function optionalPeer(name, label, loader) {
223
250
  throw error;
224
251
  }
225
252
  }
253
+ function resolveSassNamespace(mod) {
254
+ if (isSassNamespace(mod)) {
255
+ return mod;
256
+ }
257
+ if (typeof mod === 'object' &&
258
+ mod !== null &&
259
+ 'default' in mod) {
260
+ const candidate = mod.default;
261
+ if (isSassNamespace(candidate)) {
262
+ return candidate;
263
+ }
264
+ }
265
+ return mod;
266
+ }
267
+ function isSassNamespace(candidate) {
268
+ if (typeof candidate !== 'object' || !candidate) {
269
+ return false;
270
+ }
271
+ const namespace = candidate;
272
+ return typeof namespace.compile === 'function' || typeof namespace.render === 'function';
273
+ }
226
274
  function unwrapModuleNamespace(mod) {
227
275
  if (typeof mod === 'object' &&
228
276
  mod !== null &&
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.__generateTypesInternals = void 0;
7
+ exports.generateTypes = generateTypes;
8
+ exports.runGenerateTypesCli = runGenerateTypesCli;
9
+ const node_crypto_1 = __importDefault(require("node:crypto"));
10
+ const promises_1 = __importDefault(require("node:fs/promises"));
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ const node_module_1 = require("node:module");
13
+ const node_url_1 = require("node:url");
14
+ const es_module_lexer_1 = require("es-module-lexer");
15
+ const node_module_type_1 = require("node-module-type");
16
+ const css_js_1 = require("./css.cjs");
17
+ const loaderInternals_js_1 = require("./loaderInternals.cjs");
18
+ const stableSelectorsLiteral_js_1 = require("./stableSelectorsLiteral.cjs");
19
+ const stableNamespace_js_1 = require("./stableNamespace.cjs");
20
+ const DEFAULT_SKIP_DIRS = new Set([
21
+ 'node_modules',
22
+ '.git',
23
+ 'dist',
24
+ 'build',
25
+ 'coverage',
26
+ '.knighted-css',
27
+ '.next',
28
+ '.nuxt',
29
+ '.svelte-kit',
30
+ '.output',
31
+ 'tmp',
32
+ ]);
33
+ const SUPPORTED_EXTENSIONS = new Set([
34
+ '.ts',
35
+ '.tsx',
36
+ '.js',
37
+ '.jsx',
38
+ '.mts',
39
+ '.cts',
40
+ '.mjs',
41
+ '.cjs',
42
+ ]);
43
+ function resolvePackageRoot() {
44
+ const detectedType = (0, node_module_type_1.moduleType)();
45
+ if (detectedType === 'commonjs' && typeof __dirname === 'string') {
46
+ return node_path_1.default.resolve(__dirname, '..');
47
+ }
48
+ const moduleUrl = getImportMetaUrl();
49
+ if (moduleUrl) {
50
+ return node_path_1.default.resolve(node_path_1.default.dirname((0, node_url_1.fileURLToPath)(moduleUrl)), '..');
51
+ }
52
+ return node_path_1.default.resolve(process.cwd(), 'node_modules', '@knighted', 'css');
53
+ }
54
+ function getImportMetaUrl() {
55
+ try {
56
+ return (0, eval)('import.meta.url');
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
62
+ const PACKAGE_ROOT = resolvePackageRoot();
63
+ const DEFAULT_TYPES_ROOT = node_path_1.default.join(PACKAGE_ROOT, 'types-stub');
64
+ const DEFAULT_OUT_DIR = node_path_1.default.join(PACKAGE_ROOT, 'node_modules', '.knighted-css');
65
+ async function generateTypes(options = {}) {
66
+ const rootDir = node_path_1.default.resolve(options.rootDir ?? process.cwd());
67
+ const include = normalizeIncludeOptions(options.include, rootDir);
68
+ const outDir = node_path_1.default.resolve(options.outDir ?? DEFAULT_OUT_DIR);
69
+ const typesRoot = node_path_1.default.resolve(options.typesRoot ?? DEFAULT_TYPES_ROOT);
70
+ await es_module_lexer_1.init;
71
+ await promises_1.default.mkdir(outDir, { recursive: true });
72
+ await promises_1.default.mkdir(typesRoot, { recursive: true });
73
+ const internalOptions = {
74
+ rootDir,
75
+ include,
76
+ outDir,
77
+ typesRoot,
78
+ stableNamespace: options.stableNamespace,
79
+ };
80
+ return generateDeclarations(internalOptions);
81
+ }
82
+ async function generateDeclarations(options) {
83
+ const peerResolver = createProjectPeerResolver(options.rootDir);
84
+ const files = await collectCandidateFiles(options.include);
85
+ const manifestPath = node_path_1.default.join(options.outDir, 'manifest.json');
86
+ const previousManifest = await readManifest(manifestPath);
87
+ const nextManifest = {};
88
+ const selectorCache = new Map();
89
+ const processedSpecifiers = new Set();
90
+ const declarations = [];
91
+ const warnings = [];
92
+ let writes = 0;
93
+ for (const filePath of files) {
94
+ const matches = await findSpecifierImports(filePath);
95
+ for (const match of matches) {
96
+ const cleaned = match.specifier.trim();
97
+ const inlineFree = stripInlineLoader(cleaned);
98
+ if (!inlineFree.includes('?knighted-css'))
99
+ continue;
100
+ const { resource, query } = splitResourceAndQuery(inlineFree);
101
+ if (!query || !(0, loaderInternals_js_1.hasQueryFlag)(query, loaderInternals_js_1.TYPES_QUERY_FLAG)) {
102
+ continue;
103
+ }
104
+ if (processedSpecifiers.has(cleaned)) {
105
+ continue;
106
+ }
107
+ const resolvedNamespace = (0, stableNamespace_js_1.resolveStableNamespace)(options.stableNamespace);
108
+ const resolvedPath = await resolveImportPath(resource, match.importer, options.rootDir);
109
+ if (!resolvedPath) {
110
+ warnings.push(`Unable to resolve ${resource} referenced by ${relativeToRoot(match.importer, options.rootDir)}.`);
111
+ continue;
112
+ }
113
+ const cacheKey = `${resolvedPath}::${resolvedNamespace}`;
114
+ let selectorMap = selectorCache.get(cacheKey);
115
+ if (!selectorMap) {
116
+ try {
117
+ const { css } = await (0, css_js_1.cssWithMeta)(resolvedPath, {
118
+ cwd: options.rootDir,
119
+ peerResolver,
120
+ });
121
+ selectorMap = (0, stableSelectorsLiteral_js_1.buildStableSelectorsLiteral)({
122
+ css,
123
+ namespace: resolvedNamespace,
124
+ resourcePath: resolvedPath,
125
+ emitWarning: message => warnings.push(message),
126
+ }).selectorMap;
127
+ }
128
+ catch (error) {
129
+ warnings.push(`Failed to extract CSS for ${relativeToRoot(resolvedPath, options.rootDir)}: ${formatErrorMessage(error)}`);
130
+ continue;
131
+ }
132
+ selectorCache.set(cacheKey, selectorMap);
133
+ }
134
+ const variant = (0, loaderInternals_js_1.determineSelectorVariant)(query);
135
+ const declaration = formatModuleDeclaration(cleaned, variant, selectorMap);
136
+ const declarationHash = hashContent(declaration);
137
+ const fileName = buildDeclarationFileName(cleaned);
138
+ const targetPath = node_path_1.default.join(options.outDir, fileName);
139
+ const previousEntry = previousManifest[cleaned];
140
+ const needsWrite = previousEntry?.hash !== declarationHash || !(await fileExists(targetPath));
141
+ if (needsWrite) {
142
+ await promises_1.default.writeFile(targetPath, declaration, 'utf8');
143
+ writes += 1;
144
+ }
145
+ nextManifest[cleaned] = { file: fileName, hash: declarationHash };
146
+ if (needsWrite) {
147
+ declarations.push({ specifier: cleaned, filePath: targetPath });
148
+ }
149
+ processedSpecifiers.add(cleaned);
150
+ }
151
+ }
152
+ const removed = await removeStaleDeclarations(previousManifest, nextManifest, options.outDir);
153
+ await writeManifest(manifestPath, nextManifest);
154
+ const typesIndexPath = node_path_1.default.join(options.typesRoot, 'index.d.ts');
155
+ await writeTypesIndex(typesIndexPath, nextManifest, options.outDir);
156
+ if (Object.keys(nextManifest).length === 0) {
157
+ declarations.length = 0;
158
+ }
159
+ return {
160
+ written: writes,
161
+ removed,
162
+ declarations,
163
+ warnings,
164
+ outDir: options.outDir,
165
+ typesIndexPath,
166
+ };
167
+ }
168
+ function normalizeIncludeOptions(include, rootDir) {
169
+ if (!include || include.length === 0) {
170
+ return [rootDir];
171
+ }
172
+ return include.map(entry => node_path_1.default.isAbsolute(entry) ? entry : node_path_1.default.resolve(rootDir, entry));
173
+ }
174
+ async function collectCandidateFiles(entries) {
175
+ const files = [];
176
+ const visited = new Set();
177
+ async function walk(entryPath) {
178
+ const resolved = node_path_1.default.resolve(entryPath);
179
+ if (visited.has(resolved)) {
180
+ return;
181
+ }
182
+ visited.add(resolved);
183
+ let stat;
184
+ try {
185
+ stat = await promises_1.default.stat(resolved);
186
+ }
187
+ catch {
188
+ return;
189
+ }
190
+ if (stat.isDirectory()) {
191
+ const base = node_path_1.default.basename(resolved);
192
+ if (DEFAULT_SKIP_DIRS.has(base)) {
193
+ return;
194
+ }
195
+ const children = await promises_1.default.readdir(resolved, { withFileTypes: true });
196
+ for (const child of children) {
197
+ await walk(node_path_1.default.join(resolved, child.name));
198
+ }
199
+ return;
200
+ }
201
+ if (!stat.isFile()) {
202
+ return;
203
+ }
204
+ const ext = node_path_1.default.extname(resolved).toLowerCase();
205
+ if (!SUPPORTED_EXTENSIONS.has(ext)) {
206
+ return;
207
+ }
208
+ files.push(resolved);
209
+ }
210
+ for (const entry of entries) {
211
+ await walk(entry);
212
+ }
213
+ return files;
214
+ }
215
+ async function findSpecifierImports(filePath) {
216
+ let source;
217
+ try {
218
+ source = await promises_1.default.readFile(filePath, 'utf8');
219
+ }
220
+ catch {
221
+ return [];
222
+ }
223
+ if (!source.includes('?knighted-css')) {
224
+ return [];
225
+ }
226
+ const matches = [];
227
+ const [imports] = (0, es_module_lexer_1.parse)(source, filePath);
228
+ for (const record of imports) {
229
+ const specifier = record.n ?? source.slice(record.s, record.e);
230
+ if (specifier && specifier.includes('?knighted-css')) {
231
+ matches.push({ specifier, importer: filePath });
232
+ }
233
+ }
234
+ const requireRegex = /require\((['"])([^'"`]+?\?knighted-css[^'"`]*)\1\)/g;
235
+ let reqMatch;
236
+ while ((reqMatch = requireRegex.exec(source)) !== null) {
237
+ const spec = reqMatch[2];
238
+ if (spec) {
239
+ matches.push({ specifier: spec, importer: filePath });
240
+ }
241
+ }
242
+ return matches;
243
+ }
244
+ function stripInlineLoader(specifier) {
245
+ const idx = specifier.lastIndexOf('!');
246
+ return idx >= 0 ? specifier.slice(idx + 1) : specifier;
247
+ }
248
+ function splitResourceAndQuery(specifier) {
249
+ const hashIndex = specifier.indexOf('#');
250
+ const trimmed = hashIndex >= 0 ? specifier.slice(0, hashIndex) : specifier;
251
+ const queryIndex = trimmed.indexOf('?');
252
+ if (queryIndex < 0) {
253
+ return { resource: trimmed, query: '' };
254
+ }
255
+ return { resource: trimmed.slice(0, queryIndex), query: trimmed.slice(queryIndex) };
256
+ }
257
+ const projectRequireCache = new Map();
258
+ async function resolveImportPath(resourceSpecifier, importerPath, rootDir) {
259
+ if (!resourceSpecifier)
260
+ return undefined;
261
+ if (resourceSpecifier.startsWith('.')) {
262
+ return node_path_1.default.resolve(node_path_1.default.dirname(importerPath), resourceSpecifier);
263
+ }
264
+ if (resourceSpecifier.startsWith('/')) {
265
+ return node_path_1.default.resolve(rootDir, resourceSpecifier.slice(1));
266
+ }
267
+ const requireFromRoot = getProjectRequire(rootDir);
268
+ try {
269
+ return requireFromRoot.resolve(resourceSpecifier);
270
+ }
271
+ catch {
272
+ return undefined;
273
+ }
274
+ }
275
+ function buildDeclarationFileName(specifier) {
276
+ const digest = node_crypto_1.default.createHash('sha1').update(specifier).digest('hex').slice(0, 12);
277
+ return `knt-${digest}.d.ts`;
278
+ }
279
+ function formatModuleDeclaration(specifier, variant, selectors) {
280
+ const literalSpecifier = JSON.stringify(specifier);
281
+ const selectorType = formatSelectorType(selectors);
282
+ const header = `declare module ${literalSpecifier} {`;
283
+ const footer = '}';
284
+ if (variant === 'types') {
285
+ return `${header}
286
+ export const knightedCss: string
287
+ export const stableSelectors: ${selectorType}
288
+ ${footer}
289
+ `;
290
+ }
291
+ const stableLine = ` export const stableSelectors: ${selectorType}`;
292
+ const shared = ` const combined: KnightedCssCombinedModule<Record<string, unknown>>
293
+ export const knightedCss: string
294
+ ${stableLine}`;
295
+ if (variant === 'combined') {
296
+ return `${header}
297
+ ${shared}
298
+ export default combined
299
+ ${footer}
300
+ `;
301
+ }
302
+ return `${header}
303
+ ${shared}
304
+ ${footer}
305
+ `;
306
+ }
307
+ function formatSelectorType(selectors) {
308
+ if (selectors.size === 0) {
309
+ return 'Readonly<Record<string, string>>';
310
+ }
311
+ const entries = Array.from(selectors.entries()).sort(([a], [b]) => a.localeCompare(b));
312
+ const lines = entries.map(([token, selector]) => ` readonly ${JSON.stringify(token)}: ${JSON.stringify(selector)}`);
313
+ return `Readonly<{
314
+ ${lines.join('\n')}
315
+ }>`;
316
+ }
317
+ function hashContent(content) {
318
+ return node_crypto_1.default.createHash('sha1').update(content).digest('hex');
319
+ }
320
+ async function readManifest(manifestPath) {
321
+ try {
322
+ const raw = await promises_1.default.readFile(manifestPath, 'utf8');
323
+ return JSON.parse(raw);
324
+ }
325
+ catch {
326
+ return {};
327
+ }
328
+ }
329
+ async function writeManifest(manifestPath, manifest) {
330
+ await promises_1.default.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
331
+ }
332
+ async function removeStaleDeclarations(previous, next, outDir) {
333
+ const stale = Object.entries(previous).filter(([specifier]) => !next[specifier]);
334
+ let removed = 0;
335
+ for (const [, entry] of stale) {
336
+ const targetPath = node_path_1.default.join(outDir, entry.file);
337
+ try {
338
+ await promises_1.default.unlink(targetPath);
339
+ removed += 1;
340
+ }
341
+ catch {
342
+ // ignore
343
+ }
344
+ }
345
+ return removed;
346
+ }
347
+ async function writeTypesIndex(indexPath, manifest, outDir) {
348
+ const header = '// Generated by @knighted/css/generate-types\n// Do not edit.\n';
349
+ const references = Object.values(manifest)
350
+ .sort((a, b) => a.file.localeCompare(b.file))
351
+ .map(entry => {
352
+ const rel = node_path_1.default
353
+ .relative(node_path_1.default.dirname(indexPath), node_path_1.default.join(outDir, entry.file))
354
+ .split(node_path_1.default.sep)
355
+ .join('/');
356
+ return `/// <reference path="${rel}" />`;
357
+ });
358
+ const content = references.length > 0
359
+ ? `${header}
360
+ ${references.join('\n')}
361
+ `
362
+ : `${header}
363
+ `;
364
+ await promises_1.default.writeFile(indexPath, content, 'utf8');
365
+ }
366
+ function formatErrorMessage(error) {
367
+ if (error instanceof Error && typeof error.message === 'string') {
368
+ return error.message;
369
+ }
370
+ return String(error);
371
+ }
372
+ function relativeToRoot(filePath, rootDir) {
373
+ return node_path_1.default.relative(rootDir, filePath) || filePath;
374
+ }
375
+ async function fileExists(target) {
376
+ try {
377
+ await promises_1.default.access(target);
378
+ return true;
379
+ }
380
+ catch {
381
+ return false;
382
+ }
383
+ }
384
+ function createProjectPeerResolver(rootDir) {
385
+ const resolver = getProjectRequire(rootDir);
386
+ return async (name) => {
387
+ const resolved = resolver.resolve(name);
388
+ return import((0, node_url_1.pathToFileURL)(resolved).href);
389
+ };
390
+ }
391
+ function getProjectRequire(rootDir) {
392
+ const cached = projectRequireCache.get(rootDir);
393
+ if (cached) {
394
+ return cached;
395
+ }
396
+ const anchor = node_path_1.default.join(rootDir, 'package.json');
397
+ let loader;
398
+ try {
399
+ loader = (0, node_module_1.createRequire)(anchor);
400
+ }
401
+ catch {
402
+ loader = (0, node_module_1.createRequire)(node_path_1.default.join(process.cwd(), 'package.json'));
403
+ }
404
+ projectRequireCache.set(rootDir, loader);
405
+ return loader;
406
+ }
407
+ async function runGenerateTypesCli(argv = process.argv.slice(2)) {
408
+ let parsed;
409
+ try {
410
+ parsed = parseCliArgs(argv);
411
+ }
412
+ catch (error) {
413
+ console.error(`[knighted-css] ${formatErrorMessage(error)}`);
414
+ process.exitCode = 1;
415
+ return;
416
+ }
417
+ if (parsed.help) {
418
+ printHelp();
419
+ return;
420
+ }
421
+ try {
422
+ const result = await generateTypes({
423
+ rootDir: parsed.rootDir,
424
+ include: parsed.include,
425
+ outDir: parsed.outDir,
426
+ typesRoot: parsed.typesRoot,
427
+ stableNamespace: parsed.stableNamespace,
428
+ });
429
+ reportCliResult(result);
430
+ }
431
+ catch (error) {
432
+ console.error('[knighted-css] generate-types failed.');
433
+ console.error(error);
434
+ process.exitCode = 1;
435
+ }
436
+ }
437
+ function parseCliArgs(argv) {
438
+ let rootDir = process.cwd();
439
+ const include = [];
440
+ let outDir;
441
+ let typesRoot;
442
+ let stableNamespace;
443
+ for (let i = 0; i < argv.length; i += 1) {
444
+ const arg = argv[i];
445
+ if (arg === '--help' || arg === '-h') {
446
+ return { rootDir, include, outDir, typesRoot, stableNamespace, help: true };
447
+ }
448
+ if (arg === '--root' || arg === '-r') {
449
+ const value = argv[++i];
450
+ if (!value) {
451
+ throw new Error('Missing value for --root');
452
+ }
453
+ rootDir = node_path_1.default.resolve(value);
454
+ continue;
455
+ }
456
+ if (arg === '--include' || arg === '-i') {
457
+ const value = argv[++i];
458
+ if (!value) {
459
+ throw new Error('Missing value for --include');
460
+ }
461
+ include.push(value);
462
+ continue;
463
+ }
464
+ if (arg === '--out-dir') {
465
+ const value = argv[++i];
466
+ if (!value) {
467
+ throw new Error('Missing value for --out-dir');
468
+ }
469
+ outDir = value;
470
+ continue;
471
+ }
472
+ if (arg === '--types-root') {
473
+ const value = argv[++i];
474
+ if (!value) {
475
+ throw new Error('Missing value for --types-root');
476
+ }
477
+ typesRoot = value;
478
+ continue;
479
+ }
480
+ if (arg === '--stable-namespace') {
481
+ const value = argv[++i];
482
+ if (!value) {
483
+ throw new Error('Missing value for --stable-namespace');
484
+ }
485
+ stableNamespace = value;
486
+ continue;
487
+ }
488
+ if (arg.startsWith('-')) {
489
+ throw new Error(`Unknown flag: ${arg}`);
490
+ }
491
+ include.push(arg);
492
+ }
493
+ return { rootDir, include, outDir, typesRoot, stableNamespace };
494
+ }
495
+ function printHelp() {
496
+ console.log(`Usage: knighted-css-generate-types [options]
497
+
498
+ Options:
499
+ -r, --root <path> Project root directory (default: cwd)
500
+ -i, --include <path> Additional directories/files to scan (repeatable)
501
+ --out-dir <path> Output directory for generated declarations
502
+ --types-root <path> Directory for generated @types entrypoint
503
+ --stable-namespace <name> Stable namespace prefix for generated selector maps
504
+ -h, --help Show this help message
505
+ `);
506
+ }
507
+ function reportCliResult(result) {
508
+ if (result.written === 0 && result.removed === 0) {
509
+ console.log('[knighted-css] No changes to ?knighted-css&types declarations (cache is up to date).');
510
+ }
511
+ else {
512
+ console.log(`[knighted-css] Updated ${result.written} declaration(s), removed ${result.removed}, output in ${result.outDir}.`);
513
+ }
514
+ console.log(`[knighted-css] Type references: ${result.typesIndexPath}`);
515
+ for (const warning of result.warnings) {
516
+ console.warn(`[knighted-css] ${warning}`);
517
+ }
518
+ }
519
+ exports.__generateTypesInternals = {
520
+ stripInlineLoader,
521
+ splitResourceAndQuery,
522
+ buildDeclarationFileName,
523
+ formatModuleDeclaration,
524
+ formatSelectorType,
525
+ normalizeIncludeOptions,
526
+ parseCliArgs,
527
+ printHelp,
528
+ reportCliResult,
529
+ };
@@ -0,0 +1,54 @@
1
+ import { type SelectorTypeVariant } from './loaderInternals.cjs';
2
+ interface DeclarationRecord {
3
+ specifier: string;
4
+ filePath: string;
5
+ }
6
+ export interface GenerateTypesResult {
7
+ written: number;
8
+ removed: number;
9
+ declarations: DeclarationRecord[];
10
+ warnings: string[];
11
+ outDir: string;
12
+ typesIndexPath: string;
13
+ }
14
+ export interface GenerateTypesOptions {
15
+ rootDir?: string;
16
+ include?: string[];
17
+ outDir?: string;
18
+ typesRoot?: string;
19
+ stableNamespace?: string;
20
+ }
21
+ export declare function generateTypes(options?: GenerateTypesOptions): Promise<GenerateTypesResult>;
22
+ declare function normalizeIncludeOptions(include: string[] | undefined, rootDir: string): string[];
23
+ declare function stripInlineLoader(specifier: string): string;
24
+ declare function splitResourceAndQuery(specifier: string): {
25
+ resource: string;
26
+ query: string;
27
+ };
28
+ declare function buildDeclarationFileName(specifier: string): string;
29
+ declare function formatModuleDeclaration(specifier: string, variant: SelectorTypeVariant, selectors: Map<string, string>): string;
30
+ declare function formatSelectorType(selectors: Map<string, string>): string;
31
+ export declare function runGenerateTypesCli(argv?: string[]): Promise<void>;
32
+ export interface ParsedCliArgs {
33
+ rootDir: string;
34
+ include?: string[];
35
+ outDir?: string;
36
+ typesRoot?: string;
37
+ stableNamespace?: string;
38
+ help?: boolean;
39
+ }
40
+ declare function parseCliArgs(argv: string[]): ParsedCliArgs;
41
+ declare function printHelp(): void;
42
+ declare function reportCliResult(result: GenerateTypesResult): void;
43
+ export declare const __generateTypesInternals: {
44
+ stripInlineLoader: typeof stripInlineLoader;
45
+ splitResourceAndQuery: typeof splitResourceAndQuery;
46
+ buildDeclarationFileName: typeof buildDeclarationFileName;
47
+ formatModuleDeclaration: typeof formatModuleDeclaration;
48
+ formatSelectorType: typeof formatSelectorType;
49
+ normalizeIncludeOptions: typeof normalizeIncludeOptions;
50
+ parseCliArgs: typeof parseCliArgs;
51
+ printHelp: typeof printHelp;
52
+ reportCliResult: typeof reportCliResult;
53
+ };
54
+ export {};