@knighted/css 1.0.0-rc.8 → 1.0.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.
@@ -1,54 +1,103 @@
1
- import { type SelectorTypeVariant } from './loaderInternals.cjs';
2
- interface DeclarationRecord {
1
+ import { createRequire } from 'node:module';
2
+ import { moduleType } from 'node-module-type';
3
+ import { getTsconfig } from 'get-tsconfig';
4
+ import { type MatchPath } from 'tsconfig-paths';
5
+ import { cssWithMeta } from './css.cjs';
6
+ interface ImportMatch {
3
7
  specifier: string;
4
- filePath: string;
8
+ importer: string;
5
9
  }
10
+ interface ManifestEntry {
11
+ file: string;
12
+ hash: string;
13
+ }
14
+ type SelectorModuleManifest = Record<string, ManifestEntry>;
15
+ interface TsconfigResolutionContext {
16
+ absoluteBaseUrl?: string;
17
+ matchPath?: MatchPath;
18
+ }
19
+ type CssWithMetaFn = typeof cssWithMeta;
6
20
  export interface GenerateTypesResult {
7
- written: number;
8
- removed: number;
9
- declarations: DeclarationRecord[];
21
+ selectorModulesWritten: number;
22
+ selectorModulesRemoved: number;
10
23
  warnings: string[];
11
- outDir: string;
12
- typesIndexPath: string;
24
+ manifestPath: string;
13
25
  }
14
26
  export interface GenerateTypesOptions {
15
27
  rootDir?: string;
16
28
  include?: string[];
17
29
  outDir?: string;
18
- typesRoot?: string;
19
30
  stableNamespace?: string;
20
31
  }
32
+ type ModuleTypeDetector = () => ReturnType<typeof moduleType>;
33
+ declare function resolvePackageRoot(): string;
21
34
  export declare function generateTypes(options?: GenerateTypesOptions): Promise<GenerateTypesResult>;
22
35
  declare function normalizeIncludeOptions(include: string[] | undefined, rootDir: string): string[];
36
+ declare function collectCandidateFiles(entries: string[]): Promise<string[]>;
37
+ declare function findSpecifierImports(filePath: string): Promise<ImportMatch[]>;
23
38
  declare function stripInlineLoader(specifier: string): string;
24
39
  declare function splitResourceAndQuery(specifier: string): {
25
40
  resource: string;
26
41
  query: string;
27
42
  };
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;
43
+ declare function extractSelectorSourceSpecifier(specifier: string): string | undefined;
44
+ declare function resolveImportPath(resourceSpecifier: string, importerPath: string, rootDir: string, tsconfig?: TsconfigResolutionContext): Promise<string | undefined>;
45
+ declare function buildSelectorModuleManifestKey(resolvedPath: string): string;
46
+ declare function buildSelectorModulePath(resolvedPath: string): string;
47
+ declare function formatSelectorModuleSource(selectors: Map<string, string>): string;
48
+ declare function readManifest(manifestPath: string): Promise<SelectorModuleManifest>;
49
+ declare function writeManifest(manifestPath: string, manifest: SelectorModuleManifest): Promise<void>;
50
+ declare function removeStaleSelectorModules(previous: SelectorModuleManifest, next: SelectorModuleManifest): Promise<number>;
51
+ declare function relativeToRoot(filePath: string, rootDir: string): string;
52
+ declare function ensureSelectorModule(resolvedPath: string, selectors: Map<string, string>, previousManifest: SelectorModuleManifest, nextManifest: SelectorModuleManifest): Promise<boolean>;
53
+ declare function resolveWithTsconfigPaths(specifier: string, tsconfig?: TsconfigResolutionContext): Promise<string | undefined>;
54
+ declare function loadTsconfigResolutionContext(rootDir: string, loader?: typeof getTsconfig): TsconfigResolutionContext | undefined;
55
+ declare function normalizeTsconfigPaths(paths: Record<string, string[] | string> | undefined): Record<string, string[]> | undefined;
56
+ declare function isNonRelativeSpecifier(specifier: string): boolean;
57
+ declare function createProjectPeerResolver(rootDir: string): (name: string) => Promise<any>;
58
+ declare function getProjectRequire(rootDir: string): ReturnType<typeof createRequire>;
31
59
  export declare function runGenerateTypesCli(argv?: string[]): Promise<void>;
32
60
  export interface ParsedCliArgs {
33
61
  rootDir: string;
34
62
  include?: string[];
35
63
  outDir?: string;
36
- typesRoot?: string;
37
64
  stableNamespace?: string;
38
65
  help?: boolean;
39
66
  }
40
67
  declare function parseCliArgs(argv: string[]): ParsedCliArgs;
41
68
  declare function printHelp(): void;
42
69
  declare function reportCliResult(result: GenerateTypesResult): void;
70
+ declare function setCssWithMetaImplementation(impl?: CssWithMetaFn): void;
71
+ declare function setModuleTypeDetector(detector?: ModuleTypeDetector): void;
72
+ declare function setImportMetaUrlProvider(provider?: () => string | undefined): void;
43
73
  export declare const __generateTypesInternals: {
44
74
  stripInlineLoader: typeof stripInlineLoader;
45
75
  splitResourceAndQuery: typeof splitResourceAndQuery;
46
- buildDeclarationFileName: typeof buildDeclarationFileName;
47
- formatModuleDeclaration: typeof formatModuleDeclaration;
48
- formatSelectorType: typeof formatSelectorType;
76
+ extractSelectorSourceSpecifier: typeof extractSelectorSourceSpecifier;
77
+ findSpecifierImports: typeof findSpecifierImports;
78
+ resolveImportPath: typeof resolveImportPath;
79
+ resolvePackageRoot: typeof resolvePackageRoot;
80
+ relativeToRoot: typeof relativeToRoot;
81
+ collectCandidateFiles: typeof collectCandidateFiles;
49
82
  normalizeIncludeOptions: typeof normalizeIncludeOptions;
83
+ normalizeTsconfigPaths: typeof normalizeTsconfigPaths;
84
+ setCssWithMetaImplementation: typeof setCssWithMetaImplementation;
85
+ setModuleTypeDetector: typeof setModuleTypeDetector;
86
+ setImportMetaUrlProvider: typeof setImportMetaUrlProvider;
87
+ isNonRelativeSpecifier: typeof isNonRelativeSpecifier;
88
+ createProjectPeerResolver: typeof createProjectPeerResolver;
89
+ getProjectRequire: typeof getProjectRequire;
90
+ loadTsconfigResolutionContext: typeof loadTsconfigResolutionContext;
91
+ resolveWithTsconfigPaths: typeof resolveWithTsconfigPaths;
50
92
  parseCliArgs: typeof parseCliArgs;
51
93
  printHelp: typeof printHelp;
52
94
  reportCliResult: typeof reportCliResult;
95
+ buildSelectorModuleManifestKey: typeof buildSelectorModuleManifestKey;
96
+ buildSelectorModulePath: typeof buildSelectorModulePath;
97
+ formatSelectorModuleSource: typeof formatSelectorModuleSource;
98
+ ensureSelectorModule: typeof ensureSelectorModule;
99
+ removeStaleSelectorModules: typeof removeStaleSelectorModules;
100
+ readManifest: typeof readManifest;
101
+ writeManifest: typeof writeManifest;
53
102
  };
54
103
  export {};
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.asKnightedCssCombinedModule = asKnightedCssCombinedModule;
4
+ function asKnightedCssCombinedModule(module) {
5
+ return module;
6
+ }
@@ -0,0 +1,4 @@
1
+ import type { KnightedCssCombinedModule } from './loader.cjs';
2
+ type KnightedCssCombinedExtras = Readonly<Record<string, unknown>>;
3
+ export declare function asKnightedCssCombinedModule<TModule, TExtras extends KnightedCssCombinedExtras = Record<never, never>>(module: unknown): KnightedCssCombinedModule<TModule, TExtras>;
4
+ export {};
@@ -18,6 +18,7 @@ const loader = async function loader(source) {
18
18
  namespace: resolvedNamespace,
19
19
  resourcePath: this.resourcePath,
20
20
  emitWarning: message => emitKnightedWarning(this, message),
21
+ target: 'js',
21
22
  })
22
23
  : undefined;
23
24
  const injection = buildInjection(css, {
@@ -80,6 +81,7 @@ const pitch = function pitch() {
80
81
  namespace: resolvedNamespace,
81
82
  resourcePath: this.resourcePath,
82
83
  emitWarning: message => emitKnightedWarning(this, message),
84
+ target: 'js',
83
85
  })
84
86
  : undefined;
85
87
  return createCombinedModule(request, css, {
@@ -1,6 +1,7 @@
1
1
  import type { LoaderDefinitionFunction, PitchLoaderDefinitionFunction } from 'webpack';
2
2
  import { type CssOptions } from './css.cjs';
3
- export type KnightedCssCombinedModule<TModule> = TModule & {
3
+ type KnightedCssCombinedExtras = Readonly<Record<string, unknown>>;
4
+ export type KnightedCssCombinedModule<TModule, TExtras extends KnightedCssCombinedExtras = Record<never, never>> = TModule & TExtras & {
4
5
  knightedCss: string;
5
6
  };
6
7
  export interface KnightedCssVanillaOptions {
@@ -0,0 +1,432 @@
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.collectStyleImports = collectStyleImports;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_module_1 = require("node:module");
9
+ const node_fs_1 = require("node:fs");
10
+ const node_url_1 = require("node:url");
11
+ const oxc_parser_1 = require("oxc-parser");
12
+ const oxc_resolver_1 = require("oxc-resolver");
13
+ const tsconfig_paths_1 = require("tsconfig-paths");
14
+ const get_tsconfig_1 = require("get-tsconfig");
15
+ const SCRIPT_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
16
+ const BUILTIN_SPECIFIERS = new Set([
17
+ ...node_module_1.builtinModules,
18
+ ...node_module_1.builtinModules.map(mod => `node:${mod}`),
19
+ ]);
20
+ const tsconfigResultCache = new Map();
21
+ const tsconfigFsCache = new Map();
22
+ async function collectStyleImports(entryPath, options) {
23
+ const { cwd, styleExtensions, filter, resolver, graphOptions } = options;
24
+ const normalizedStyles = normalizeExtensions(styleExtensions);
25
+ const scriptExtensions = normalizeExtensions([
26
+ ...SCRIPT_EXTENSIONS,
27
+ ...(graphOptions?.extensions ?? []),
28
+ ]);
29
+ const resolutionExtensions = dedupeExtensions([
30
+ ...scriptExtensions,
31
+ ...normalizedStyles,
32
+ ]);
33
+ const tsconfigMatcher = createTsconfigMatcher(graphOptions?.tsConfig, cwd, resolutionExtensions);
34
+ const seenScripts = new Set();
35
+ const seenStyles = new Set();
36
+ const styleOrder = [];
37
+ const resolutionCache = new Map();
38
+ const resolverFactory = createResolverFactory(cwd, resolutionExtensions, scriptExtensions, graphOptions);
39
+ async function walk(filePath) {
40
+ const absolutePath = node_path_1.default.resolve(filePath);
41
+ if (seenScripts.has(absolutePath)) {
42
+ return;
43
+ }
44
+ seenScripts.add(absolutePath);
45
+ const source = await readSourceFile(absolutePath);
46
+ if (!source) {
47
+ return;
48
+ }
49
+ const specifiers = extractModuleSpecifiers(source, absolutePath);
50
+ for (const specifier of specifiers) {
51
+ if (!specifier || isBuiltinSpecifier(specifier)) {
52
+ continue;
53
+ }
54
+ const resolved = await resolveImport(specifier, absolutePath);
55
+ if (!resolved) {
56
+ continue;
57
+ }
58
+ const normalized = node_path_1.default.resolve(resolved);
59
+ if (!filter(normalized)) {
60
+ continue;
61
+ }
62
+ if (isStyleExtension(normalized, normalizedStyles)) {
63
+ if (!seenStyles.has(normalized)) {
64
+ seenStyles.add(normalized);
65
+ styleOrder.push(normalized);
66
+ }
67
+ continue;
68
+ }
69
+ if (isScriptExtension(normalized, scriptExtensions)) {
70
+ await walk(normalized);
71
+ }
72
+ }
73
+ }
74
+ async function resolveImport(specifier, importer) {
75
+ const cacheKey = `${importer}::${specifier}`;
76
+ if (resolutionCache.has(cacheKey)) {
77
+ return resolutionCache.get(cacheKey);
78
+ }
79
+ let resolved;
80
+ if (resolver) {
81
+ resolved = normalizeResolverResult(await resolver(specifier, { cwd, from: importer }), cwd);
82
+ }
83
+ if (!resolved && tsconfigMatcher) {
84
+ resolved = tsconfigMatcher(specifier);
85
+ }
86
+ if (!resolved) {
87
+ resolved = resolveWithFactory(resolverFactory, specifier, importer, resolutionExtensions);
88
+ }
89
+ resolutionCache.set(cacheKey, resolved);
90
+ return resolved;
91
+ }
92
+ await walk(entryPath);
93
+ return styleOrder;
94
+ }
95
+ function normalizeExtensions(extensions) {
96
+ const result = new Set();
97
+ for (const ext of extensions) {
98
+ if (!ext)
99
+ continue;
100
+ const normalized = ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`;
101
+ result.add(normalized);
102
+ }
103
+ return Array.from(result);
104
+ }
105
+ function dedupeExtensions(extensions) {
106
+ const result = new Set();
107
+ for (const ext of extensions) {
108
+ result.add(ext);
109
+ }
110
+ return Array.from(result);
111
+ }
112
+ function isBuiltinSpecifier(specifier) {
113
+ if (BUILTIN_SPECIFIERS.has(specifier)) {
114
+ return true;
115
+ }
116
+ if (specifier.startsWith('node:')) {
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+ function isStyleExtension(filePath, extensions) {
122
+ const lower = filePath.toLowerCase();
123
+ return extensions.some(ext => lower.endsWith(ext));
124
+ }
125
+ function isScriptExtension(filePath, extensions) {
126
+ const ext = node_path_1.default.extname(filePath).toLowerCase();
127
+ return extensions.includes(ext);
128
+ }
129
+ async function readSourceFile(filePath) {
130
+ try {
131
+ return await node_fs_1.promises.readFile(filePath, 'utf8');
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ function extractModuleSpecifiers(sourceText, filePath) {
138
+ let program;
139
+ try {
140
+ ;
141
+ ({ program } = (0, oxc_parser_1.parseSync)(filePath, sourceText, { sourceType: 'unambiguous' }));
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ const specifiers = [];
147
+ const addSpecifier = (raw) => {
148
+ if (!raw) {
149
+ return;
150
+ }
151
+ const normalized = normalizeSpecifier(raw);
152
+ if (normalized) {
153
+ specifiers.push(normalized);
154
+ }
155
+ };
156
+ const visitor = new oxc_parser_1.Visitor({
157
+ ImportDeclaration(node) {
158
+ addSpecifier(node.source?.value);
159
+ },
160
+ ExportNamedDeclaration(node) {
161
+ if (node.source) {
162
+ addSpecifier(node.source.value);
163
+ }
164
+ },
165
+ ExportAllDeclaration(node) {
166
+ addSpecifier(node.source?.value);
167
+ },
168
+ TSImportEqualsDeclaration(node) {
169
+ const specifier = extractImportEqualsSpecifier(node);
170
+ if (specifier) {
171
+ addSpecifier(specifier);
172
+ }
173
+ },
174
+ ImportExpression(node) {
175
+ const specifier = getStringFromExpression(node.source);
176
+ if (specifier) {
177
+ addSpecifier(specifier);
178
+ }
179
+ },
180
+ CallExpression(node) {
181
+ if (!isRequireLikeCallee(node.callee)) {
182
+ return;
183
+ }
184
+ const specifier = getStringFromArgument(node.arguments[0]);
185
+ if (specifier) {
186
+ addSpecifier(specifier);
187
+ }
188
+ },
189
+ });
190
+ visitor.visit(program);
191
+ return specifiers;
192
+ }
193
+ function normalizeSpecifier(raw) {
194
+ if (!raw)
195
+ return '';
196
+ const trimmed = raw.trim();
197
+ if (!trimmed || trimmed.startsWith('\0')) {
198
+ return '';
199
+ }
200
+ const querySearchOffset = trimmed.startsWith('#') ? 1 : 0;
201
+ const remainder = trimmed.slice(querySearchOffset);
202
+ const queryMatchIndex = remainder.search(/[?#]/);
203
+ const queryIndex = queryMatchIndex === -1 ? -1 : querySearchOffset + queryMatchIndex;
204
+ const withoutQuery = queryIndex === -1 ? trimmed : trimmed.slice(0, queryIndex);
205
+ if (!withoutQuery) {
206
+ return '';
207
+ }
208
+ if (/^[a-z][\w+.-]*:/i.test(withoutQuery) && !withoutQuery.startsWith('file:')) {
209
+ return '';
210
+ }
211
+ return withoutQuery;
212
+ }
213
+ function extractImportEqualsSpecifier(node) {
214
+ if (node.moduleReference.type === 'TSExternalModuleReference') {
215
+ return node.moduleReference.expression.value;
216
+ }
217
+ return undefined;
218
+ }
219
+ function getStringFromArgument(argument) {
220
+ if (!argument || argument.type === 'SpreadElement') {
221
+ return undefined;
222
+ }
223
+ return getStringFromExpression(argument);
224
+ }
225
+ function getStringFromExpression(expression) {
226
+ if (!expression) {
227
+ return undefined;
228
+ }
229
+ if (expression.type === 'Literal') {
230
+ const literalValue = expression.value;
231
+ return typeof literalValue === 'string' ? literalValue : undefined;
232
+ }
233
+ if (expression.type === 'TemplateLiteral' && expression.expressions.length === 0) {
234
+ const [first] = expression.quasis;
235
+ return first?.value.cooked ?? first?.value.raw ?? undefined;
236
+ }
237
+ return undefined;
238
+ }
239
+ function isRequireLikeCallee(expression) {
240
+ const target = unwrapExpression(expression);
241
+ if (target.type === 'Identifier') {
242
+ return target.name === 'require';
243
+ }
244
+ if (target.type === 'MemberExpression') {
245
+ const object = target.object;
246
+ if (object.type === 'Identifier') {
247
+ return object.name === 'require';
248
+ }
249
+ }
250
+ return false;
251
+ }
252
+ function unwrapExpression(expression) {
253
+ if (expression.type === 'ChainExpression') {
254
+ const inner = expression.expression;
255
+ if (inner.type === 'CallExpression') {
256
+ return unwrapExpression(inner.callee);
257
+ }
258
+ return unwrapExpression(inner);
259
+ }
260
+ if (expression.type === 'TSNonNullExpression') {
261
+ return unwrapExpression(expression.expression);
262
+ }
263
+ return expression;
264
+ }
265
+ function normalizeResolverResult(result, cwd) {
266
+ if (!result) {
267
+ return undefined;
268
+ }
269
+ if (result.startsWith('file://')) {
270
+ try {
271
+ return (0, node_url_1.fileURLToPath)(new URL(result));
272
+ }
273
+ catch {
274
+ return undefined;
275
+ }
276
+ }
277
+ return node_path_1.default.isAbsolute(result) ? result : node_path_1.default.resolve(cwd, result);
278
+ }
279
+ function resolveWithFactory(factory, specifier, importer, extensions) {
280
+ if (specifier.startsWith('file://')) {
281
+ try {
282
+ return findExistingFile((0, node_url_1.fileURLToPath)(new URL(specifier)), extensions);
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ }
288
+ if (/^[a-z][\w+.-]*:/i.test(specifier)) {
289
+ return undefined;
290
+ }
291
+ try {
292
+ const result = factory.resolveFileSync(importer, specifier);
293
+ return result?.path;
294
+ }
295
+ catch {
296
+ return undefined;
297
+ }
298
+ }
299
+ function createResolverFactory(cwd, extensions, scriptExtensions, graphOptions) {
300
+ const options = {
301
+ extensions,
302
+ conditionNames: graphOptions?.conditions,
303
+ };
304
+ const extensionAlias = buildExtensionAlias(scriptExtensions);
305
+ if (extensionAlias) {
306
+ options.extensionAlias = extensionAlias;
307
+ }
308
+ const tsconfigOption = resolveResolverTsconfig(graphOptions?.tsConfig, cwd);
309
+ options.tsconfig = tsconfigOption ?? 'auto';
310
+ return new oxc_resolver_1.ResolverFactory(options);
311
+ }
312
+ function buildExtensionAlias(scriptExtensions) {
313
+ const alias = {};
314
+ const jsTargets = dedupeExtensions(scriptExtensions.filter(ext => ['.js', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts'].includes(ext)));
315
+ if (jsTargets.length > 0) {
316
+ for (const key of ['.js', '.mjs', '.cjs']) {
317
+ alias[key] = jsTargets;
318
+ }
319
+ }
320
+ const jsxTargets = dedupeExtensions(scriptExtensions.filter(ext => ext === '.jsx' || ext === '.tsx'));
321
+ if (jsxTargets.length > 0) {
322
+ alias['.jsx'] = jsxTargets;
323
+ }
324
+ return Object.keys(alias).length > 0 ? alias : undefined;
325
+ }
326
+ function resolveResolverTsconfig(input, cwd) {
327
+ if (!input || typeof input !== 'string') {
328
+ return undefined;
329
+ }
330
+ const resolved = resolveTsconfigPath(input, cwd);
331
+ if (!resolved) {
332
+ return undefined;
333
+ }
334
+ return { configFile: resolved };
335
+ }
336
+ function createTsconfigMatcher(input, cwd, extensions) {
337
+ const config = loadTsconfigPaths(input, cwd);
338
+ if (!config) {
339
+ return undefined;
340
+ }
341
+ const matchPath = (0, tsconfig_paths_1.createMatchPath)(config.absoluteBaseUrl, config.paths);
342
+ return (specifier) => {
343
+ const matched = matchPath(specifier, undefined, undefined, extensions);
344
+ if (!matched) {
345
+ return undefined;
346
+ }
347
+ return findExistingFile(matched, extensions) ?? matched;
348
+ };
349
+ }
350
+ function loadTsconfigPaths(input, cwd) {
351
+ if (!input) {
352
+ return undefined;
353
+ }
354
+ if (typeof input === 'string') {
355
+ const target = node_path_1.default.isAbsolute(input) ? input : node_path_1.default.resolve(cwd, input);
356
+ const cached = tsconfigResultCache.get(target);
357
+ if (cached !== undefined) {
358
+ return cached ?? undefined;
359
+ }
360
+ const result = (0, get_tsconfig_1.getTsconfig)(target, undefined, tsconfigFsCache);
361
+ if (!result) {
362
+ tsconfigResultCache.set(target, null);
363
+ return undefined;
364
+ }
365
+ const normalized = normalizeTsconfigCompilerOptions(result.config.compilerOptions, node_path_1.default.dirname(result.path));
366
+ tsconfigResultCache.set(target, normalized ?? null);
367
+ return normalized;
368
+ }
369
+ const compilerOptions = input.compilerOptions;
370
+ return normalizeTsconfigCompilerOptions(compilerOptions, cwd);
371
+ }
372
+ function normalizeTsconfigCompilerOptions(compilerOptions, configDir) {
373
+ if (!compilerOptions?.baseUrl || !compilerOptions.paths) {
374
+ return undefined;
375
+ }
376
+ const normalizedPaths = {};
377
+ for (const [pattern, replacements] of Object.entries(compilerOptions.paths)) {
378
+ if (!replacements || replacements.length === 0) {
379
+ continue;
380
+ }
381
+ normalizedPaths[pattern] = Array.isArray(replacements)
382
+ ? [...replacements]
383
+ : [replacements];
384
+ }
385
+ if (Object.keys(normalizedPaths).length === 0) {
386
+ return undefined;
387
+ }
388
+ const absoluteBaseUrl = node_path_1.default.isAbsolute(compilerOptions.baseUrl)
389
+ ? compilerOptions.baseUrl
390
+ : node_path_1.default.resolve(configDir, compilerOptions.baseUrl);
391
+ return { absoluteBaseUrl, paths: normalizedPaths };
392
+ }
393
+ function resolveTsconfigPath(tsconfigPath, cwd) {
394
+ const absolute = node_path_1.default.isAbsolute(tsconfigPath)
395
+ ? tsconfigPath
396
+ : node_path_1.default.resolve(cwd, tsconfigPath);
397
+ if (!(0, node_fs_1.existsSync)(absolute)) {
398
+ return undefined;
399
+ }
400
+ const stats = (0, node_fs_1.statSync)(absolute);
401
+ if (stats.isDirectory()) {
402
+ const candidate = node_path_1.default.join(absolute, 'tsconfig.json');
403
+ return (0, node_fs_1.existsSync)(candidate) ? candidate : undefined;
404
+ }
405
+ return absolute;
406
+ }
407
+ function findExistingFile(candidate, extensions) {
408
+ const candidateHasExt = hasExtension(candidate);
409
+ if (candidateHasExt && (0, node_fs_1.existsSync)(candidate)) {
410
+ return candidate;
411
+ }
412
+ if (!candidateHasExt) {
413
+ for (const ext of extensions) {
414
+ const withExt = `${candidate}${ext}`;
415
+ if ((0, node_fs_1.existsSync)(withExt)) {
416
+ return withExt;
417
+ }
418
+ }
419
+ }
420
+ if ((0, node_fs_1.existsSync)(candidate) && (0, node_fs_1.statSync)(candidate).isDirectory()) {
421
+ for (const ext of extensions) {
422
+ const indexPath = node_path_1.default.join(candidate, `index${ext}`);
423
+ if ((0, node_fs_1.existsSync)(indexPath)) {
424
+ return indexPath;
425
+ }
426
+ }
427
+ }
428
+ return undefined;
429
+ }
430
+ function hasExtension(filePath) {
431
+ return Boolean(node_path_1.default.extname(filePath));
432
+ }
@@ -0,0 +1,15 @@
1
+ import type { CssResolver } from './types.cjs';
2
+ export interface ModuleGraphOptions {
3
+ tsConfig?: string | Record<string, unknown>;
4
+ extensions?: string[];
5
+ conditions?: string[];
6
+ }
7
+ interface CollectOptions {
8
+ cwd: string;
9
+ styleExtensions: string[];
10
+ filter: (filePath: string) => boolean;
11
+ resolver?: CssResolver;
12
+ graphOptions?: ModuleGraphOptions;
13
+ }
14
+ export declare function collectStyleImports(entryPath: string, options: CollectOptions): Promise<string[]>;
15
+ export {};
@@ -24,8 +24,11 @@ function createSassImporter({ cwd, resolver, }) {
24
24
  console.error('[knighted-css:sass] containing url:', context.containingUrl.href);
25
25
  }
26
26
  }
27
+ const containingPath = context?.containingUrl
28
+ ? (0, node_url_1.fileURLToPath)(context.containingUrl)
29
+ : undefined;
27
30
  if (shouldNormalizeSpecifier(url)) {
28
- const resolvedPath = await resolveAliasSpecifier(url, resolver, cwd);
31
+ const resolvedPath = await resolveAliasSpecifier(url, resolver, cwd, containingPath);
29
32
  if (!resolvedPath) {
30
33
  if (debug) {
31
34
  console.error('[knighted-css:sass] resolver returned no result for', url);
@@ -61,8 +64,8 @@ function createSassImporter({ cwd, resolver, }) {
61
64
  },
62
65
  };
63
66
  }
64
- async function resolveAliasSpecifier(specifier, resolver, cwd) {
65
- const resolved = await resolver(specifier, { cwd });
67
+ async function resolveAliasSpecifier(specifier, resolver, cwd, from) {
68
+ const resolved = await resolver(specifier, { cwd, from });
66
69
  if (!resolved) {
67
70
  return undefined;
68
71
  }
@@ -1,6 +1,5 @@
1
- export type CssResolver = (specifier: string, ctx: {
2
- cwd: string;
3
- }) => string | Promise<string | undefined>;
1
+ import type { CssResolver } from './types.cjs';
2
+ export type { CssResolver } from './types.cjs';
4
3
  export declare function createSassImporter({ cwd, resolver, }: {
5
4
  cwd: string;
6
5
  resolver?: CssResolver;
@@ -13,7 +12,7 @@ export declare function createSassImporter({ cwd, resolver, }: {
13
12
  syntax: "scss" | "indented";
14
13
  }>;
15
14
  } | undefined;
16
- export declare function resolveAliasSpecifier(specifier: string, resolver: CssResolver, cwd: string): Promise<string | undefined>;
15
+ export declare function resolveAliasSpecifier(specifier: string, resolver: CssResolver, cwd: string, from?: string): Promise<string | undefined>;
17
16
  export declare function shouldNormalizeSpecifier(specifier: string): boolean;
18
17
  export declare function ensureSassPath(filePath: string): string | undefined;
19
18
  export declare function resolveRelativeSpecifier(specifier: string, containingUrl?: URL | null): string | undefined;