Skip to content

Commit

Permalink
refactor!: remove resolve options
Browse files Browse the repository at this point in the history
refactor!: reduce minimalFS api
  • Loading branch information
barak007 committed Sep 28, 2023
1 parent 87d1754 commit 48445e7
Show file tree
Hide file tree
Showing 20 changed files with 128 additions and 158 deletions.
10 changes: 5 additions & 5 deletions packages/cli/src/config/projects-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { processProjects } from './process-projects';
import { createDefaultOptions, mergeBuildOptions, validateOptions } from './resolve-options';
import { resolveNpmRequests } from './resolve-requests';
import type { ModuleResolver } from '@stylable/core/dist/index-internal';
import type { MinimalFS, processNamespace } from '@stylable/core';
import type { processNamespace } from '@stylable/core';
import type { IFileSystem } from '@file-services/types';

interface StylableRuntimeConfigs {
Expand Down Expand Up @@ -65,21 +65,21 @@ export async function projectsConfig(
}

// todo: make fs not optional next major version
export function resolveConfig(context: string, request?: string, fs?: IFileSystem | MinimalFS) {
export function resolveConfig(context: string, request?: string, fs?: IFileSystem) {
return request ? requireConfigFile(request, context, fs) : resolveConfigFile(context, fs);
}

function requireConfigFile(request: string, context: string, fs?: IFileSystem | MinimalFS) {
function requireConfigFile(request: string, context: string, fs?: IFileSystem) {
const path = require.resolve(request, { paths: [context] });
const config = resolveConfigValue(require(path), fs);
return config ? { config, path } : undefined;
}

function resolveConfigFile(context: string, fs?: IFileSystem | MinimalFS) {
function resolveConfigFile(context: string, fs?: IFileSystem) {
return loadStylableConfig(context, (config) => resolveConfigValue(config, fs));
}

function resolveConfigValue(config: any, fs?: IFileSystem | MinimalFS) {
function resolveConfigValue(config: any, fs?: IFileSystem) {
return tryRun(
(): StylableRuntimeConfigs => ({
stcConfig: isSTCConfig(config)
Expand Down
54 changes: 0 additions & 54 deletions packages/cli/test/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,60 +681,6 @@ describe('build stand alone', () => {
expect(dtsSourceMapContent).to.contain(`"sources": [`);
expect(dtsSourceMapContent).to.contain(`"main.st.css"`);
});

describe('resolver (build)', () => {
it('should be able to build with enhanced-resolver alias configured', async () => {
const identifier = 'build-identifier';
const fs = createMemoryFs({
'/entry.st.css': `
@st-import [green] from '@colors/green.st.css';
.root { -st-mixin: green;}`,
'/colors/green.st.css': `
.green { color: green; }`,
});

const diagnosticsManager = new DiagnosticsManager();
const stylable = new Stylable({
projectRoot: '/',
fileSystem: fs,
requireModule: () => ({}),
resolveOptions: {
alias: {
'@colors/*': '/colors/*',
},
},
});

await build(
{
outDir: '.',
srcDir: '.',
outputCSS: true,
diagnostics: true,
},
{
fs,
stylable,
rootDir: '/',
projectRoot: '/',
log,
diagnosticsManager,
identifier,
}
);

['/entry.st.css', '/entry.css'].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});

const messages = diagnosticsManager.get(identifier, '/entry.st.css')?.diagnostics;
expect(messages).to.eql(undefined);

const entryCSSContent = fs.readFileSync('/entry.css', 'utf8');
expect(entryCSSContent).to.contain(`color: green;`);
});
});
});

describe('build - bundle', () => {
Expand Down
21 changes: 20 additions & 1 deletion packages/core-test-kit/src/generate-test-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { isAbsolute } from 'path';
import * as postcss from 'postcss';
import { createMemoryFs } from '@file-services/memory';
import type { IFileSystem } from '@file-services/types';
import type { IDirectoryContents } from '@file-services/types';

export interface File {
Expand Down Expand Up @@ -118,6 +119,24 @@ export function createProcess(
return (path: string) => fileProcessor.process(path);
}

export function createResolveExtendsResults(
fileSystem: IFileSystem,
fileToProcess: string,
classNameToLookup: string,
isElement = false
) {
const stylable = new Stylable({
fileSystem,
projectRoot: '/',
});

return stylable.resolver.resolveExtends(
stylable.analyze(fileToProcess),
classNameToLookup,
isElement
);
}

export function generateStylableResult(
config: Config,
diagnostics: Diagnostics = new Diagnostics()
Expand All @@ -140,7 +159,7 @@ export function generateStylableExports(config: Config) {

export function generateStylableEnvironment(
content: IDirectoryContents,
stylableConfig: Partial<StylableConfig> = {}
stylableConfig: Partial<Omit<StylableConfig, 'fileSystem'>> = {}
) {
const fs = createMemoryFs(content);

Expand Down
1 change: 1 addition & 0 deletions packages/core-test-kit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
generateStylableRoot,
processSource,
generateStylableEnvironment,
createResolveExtendsResults,
} from './generate-test-util';
export { flatMatch } from './matchers/flat-match';
export { matchCSSMatchers } from './matchers/match-css';
Expand Down
2 changes: 1 addition & 1 deletion packages/core-test-kit/test/inline-expectations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1021,7 +1021,7 @@ describe('inline-expectations', () => {
);
});
it(`should throw on possible location mismatch`, () => {
const resolveErrorMessage = 'Stylable could not resolve "./unknown.st.css" from "/"';
const resolveErrorMessage = "Stylable could not resolve \"./unknown.st.css\" from \"/\"\nVisited paths:\n/unknown.st.css\n/unknown.st.css.js\n/unknown.st.css.mjs\n/unknown.st.css.cjs\n/unknown.st.css.ts\n/unknown.st.css.mts\n/unknown.st.css.cts\n/unknown.st.css.json"
const result = generateStylableResult({
entry: `/style.st.css`,
files: {
Expand Down
3 changes: 0 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
"scripts": {
"test": "mocha \"./dist/test/**/*.spec.js\""
},
"browser": {
"module": false
},
"dependencies": {
"@file-services/resolve": "^8.2.0",
"@tokey/css-selector-parser": "^0.6.2",
Expand Down
2 changes: 0 additions & 2 deletions packages/core/src/cached-process-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ export interface CacheItem<T> {
}

export interface MinimalFS {
statSync: (filePath: string) => { mtime: Date };
readFileSync: (filePath: string, encoding: 'utf8') => string;
readlinkSync: (filePath: string) => string;
}

export interface FileProcessor<T> {
Expand Down
9 changes: 0 additions & 9 deletions packages/core/src/enhanced-resolve-alias.ts

This file was deleted.

27 changes: 18 additions & 9 deletions packages/core/src/module-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
// in browser build this gets remapped to an empty object via our package.json->"browser"

import { IRequestResolverOptions, createRequestResolver } from '@file-services/resolve';
import {
IRequestResolverOptions,
IResolutionFileSystem,
createRequestResolver,
} from '@file-services/resolve';
import type { ModuleResolver } from './types';

export type { IRequestResolverOptions, IResolutionFileSystem };

export function createDefaultResolver(options: IRequestResolverOptions): ModuleResolver {
const resolver = createRequestResolver({
extensions: ['.js', '.json', '.mjs', '.cjs', '.ts', '.mts', '.cts'],
extensions: ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.json'],
...options,
});

return (directoryPath, request): string => {
const res = resolver(directoryPath, request);
if (res.resolvedFile === false) {
const { resolvedFile, visitedPaths } = resolver(directoryPath, request);

if (resolvedFile === false) {
throw new Error(
`Stylable does not support browser field 'false' values. ${request} resolved to 'false' from ${directoryPath}`
);
}
if (typeof res.resolvedFile !== 'string') {
throw new Error(`Stylable could not resolve ${JSON.stringify(request)} from ${JSON.stringify(directoryPath)}`);
if (typeof resolvedFile !== 'string') {
throw new Error(
`Stylable could not resolve ${JSON.stringify(request)} from ${JSON.stringify(
directoryPath
)}` + (visitedPaths.size ? `\nVisited paths:\n${[...visitedPaths].join('\n')}` : '')
);
}
return res.resolvedFile;
return resolvedFile;
};
}
50 changes: 33 additions & 17 deletions packages/core/src/stylable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,41 @@ import {
TransformHooks,
} from './stylable-transformer';
import type { IStylableOptimizer, ModuleResolver } from './types';
import { createDefaultResolver } from './module-resolver';
import {
createDefaultResolver,
IRequestResolverOptions,
IResolutionFileSystem,
} from './module-resolver';
import { STImport, STScope, STVar, STMixin, CSSClass, CSSCustomProperty } from './features';
import { Dependency, visitMetaCSSDependencies } from './visit-meta-css-dependencies';
import * as postcss from 'postcss';

export interface StylableConfig {
export interface StylableConfigBase {
projectRoot: string;
fileSystem: MinimalFS;
requireModule?: (path: string) => any;
onProcess?: (meta: StylableMeta, path: string) => StylableMeta;
hooks?: TransformHooks;
/** @deprecated provide a `resolveModule` instead */
resolveOptions?: {
alias?: any;
symlinks?: boolean;
[key: string]: any;
};
optimizer?: IStylableOptimizer;
mode?: 'production' | 'development';
resolveNamespace?: typeof processNamespace;
resolveModule?: ModuleResolver;
cssParser?: CssParser;
resolverCache?: StylableResolverCache;
fileProcessorCache?: Record<string, CacheItem<StylableMeta>>;
experimentalSelectorInference?: boolean;
}

export type StylableConfig = StylableConfigBase &
(
| {
fileSystem: MinimalFS;
resolveModule: ModuleResolver;
}
| {
fileSystem: IResolutionFileSystem;
resolveModule?: ModuleResolver | Omit<IRequestResolverOptions, 'fs'>;
}
);

// This defines and validates known configs for the defaultConfig in 'stylable.config.js
const globalDefaultSupportedConfigs = new Set([
'resolveModule',
Expand Down Expand Up @@ -75,12 +83,11 @@ export class Stylable {
public cssClass = new CSSClass.StylablePublicApi(this);
//
public projectRoot: string;
protected fileSystem: MinimalFS;
protected fileSystem: IResolutionFileSystem | MinimalFS;
protected requireModule: (path: string) => any;
protected onProcess?: (meta: StylableMeta, path: string) => StylableMeta;
protected diagnostics = new Diagnostics();
protected hooks: TransformHooks;
protected resolveOptions: any;
public optimizer?: IStylableOptimizer;
protected mode: 'production' | 'development';
public resolveNamespace?: typeof processNamespace;
Expand All @@ -97,17 +104,16 @@ export class Stylable {
this.requireModule =
config.requireModule ||
(() => {
throw new Error('Javascript files are not supported without requireModule options');
throw new Error(
'Javascript files are not supported without Stylable `requireModule` option'
);
});
this.onProcess = config.onProcess;
this.hooks = config.hooks || {};
this.resolveOptions = config.resolveOptions || {};
this.optimizer = config.optimizer;
this.mode = config.mode || `production`;
this.resolveNamespace = config.resolveNamespace;
this.moduleResolver =
config.resolveModule ||
createDefaultResolver({ fs: this.fileSystem, ...this.resolveOptions });
this.moduleResolver = this.initModuleResolver(config);
this.cssParser = config.cssParser || cssParse;
this.resolverCache = config.resolverCache; // ToDo: v5 default to `new Map()`
this.fileProcessorCache = config.fileProcessorCache;
Expand All @@ -121,6 +127,16 @@ export class Stylable {

this.resolver = this.createResolver();
}
private initModuleResolver(config: StylableConfig): ModuleResolver {
return typeof config.resolveModule === 'function'
? config.resolveModule
: createDefaultResolver({
fs: this
.fileSystem as IResolutionFileSystem /* we force to provide resolveModule when using MinimalFS */,
...config.resolveModule,
});
}

public getDependencies(meta: StylableMeta) {
const dependencies: Dependency[] = [];

Expand Down
16 changes: 9 additions & 7 deletions packages/core/test/features/st-import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,10 @@ describe(`features/st-import`, () => {
`);
});
it(`should error on unresolved file`, () => {
const resolveErrorMessage = `Stylable could not resolve "./missing.st.css" from "/"`;
const resolveErrorMessagePackage = `Stylable could not resolve "missing-package/index.st.css" from "/"`;

const resolveErrorMessage =
'Stylable could not resolve "./missing.st.css" from "/"\nVisited paths:\n/missing.st.css\n/missing.st.css.js\n/missing.st.css.mjs\n/missing.st.css.cjs\n/missing.st.css.ts\n/missing.st.css.mts\n/missing.st.css.cts\n/missing.st.css.json';
const resolveErrorMessagePackage =
'Stylable could not resolve "missing-package/index.st.css" from "/"';
testStylableCore(`
/* @transform-error(relative) word(./missing.st.css) ${stImportDiagnostics.UNKNOWN_IMPORTED_FILE(
`./missing.st.css`,
Expand Down Expand Up @@ -532,10 +533,11 @@ describe(`features/st-import`, () => {
}
`);
});
it(`should error on unresolved file`, () => {
const resolveErrorMessage = `Stylable could not resolve "./missing.st.css" from "/"`;
const resolveErrorMessagePackage = `Stylable could not resolve "missing-package/index.st.css" from "/"`;

it(`should error on unresolved file (:import)`, () => {
const resolveErrorMessage =
'Stylable could not resolve "./missing.st.css" from "/"\nVisited paths:\n/missing.st.css\n/missing.st.css.js\n/missing.st.css.mjs\n/missing.st.css.cjs\n/missing.st.css.ts\n/missing.st.css.mts\n/missing.st.css.cts\n/missing.st.css.json';
const resolveErrorMessagePackage =
'Stylable could not resolve "missing-package/index.st.css" from "/"';
testStylableCore(`
:import{
/* @transform-error(relative) word(./missing.st.css) ${stImportDiagnostics.UNKNOWN_IMPORTED_FILE(
Expand Down
25 changes: 5 additions & 20 deletions packages/core/test/stylable-resolver.spec.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,10 @@
import { expect } from 'chai';
import type * as postcss from 'postcss';
import { testStylableCore, generateStylableResult } from '@stylable/core-test-kit';
import { Stylable, MinimalFS } from '@stylable/core';

function createResolveExtendsResults(
fileSystem: MinimalFS,
fileToProcess: string,
classNameToLookup: string,
isElement = false
) {
const stylable = new Stylable({
fileSystem,
projectRoot: '/',
});

return stylable.resolver.resolveExtends(
stylable.analyze(fileToProcess),
classNameToLookup,
isElement
);
}
import {
testStylableCore,
generateStylableResult,
createResolveExtendsResults,
} from '@stylable/core-test-kit';

describe('stylable-resolver', () => {
it('should resolve extend classes', () => {
Expand Down
Loading

0 comments on commit 48445e7

Please sign in to comment.