Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: move to file-services/resolve as default resolver #2907

Merged
merged 8 commits into from
Oct 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/cli/src/cli-codemod.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env node

import fs from 'fs';
import fs from '@file-services/node';
import { resolve } from 'path';
import yargs from 'yargs';
import { codeMods } from './code-mods/code-mods';
Expand Down
11 changes: 5 additions & 6 deletions packages/cli/src/code-format.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env node
import yargs from 'yargs';
import { nodeFs } from '@file-services/node';
import fs from '@file-services/node';
import { getDocumentFormatting, formatCSS } from '@stylable/code-formatter';
import { createLogger } from './logger';
import { writeFileSync } from 'fs';

const { join } = nodeFs;
const { join, writeFileSync } = fs;

const argv = yargs
.usage('$0 [options]')
Expand Down Expand Up @@ -134,7 +133,7 @@ for (const request of requires) {
}

function readDirectoryDeep(dirPath: string, fileSuffixFilter = '.st.css', res = new Set<string>()) {
const items = nodeFs.readdirSync(dirPath, { withFileTypes: true });
const items = fs.readdirSync(dirPath, { withFileTypes: true });

for (const item of items) {
const path = join(dirPath, item.name);
Expand All @@ -150,7 +149,7 @@ function readDirectoryDeep(dirPath: string, fileSuffixFilter = '.st.css', res =
}

function formatStylesheet(filePath: string) {
const fileContent = nodeFs.readFileSync(filePath, 'utf-8');
const fileContent = fs.readFileSync(filePath, 'utf-8');

const newText = experimental
? formatCSS(fileContent, {
Expand Down Expand Up @@ -188,7 +187,7 @@ if (debug) {
log('Starting code formatting');
}

const formatPathStats = nodeFs.statSync(target);
const formatPathStats = fs.statSync(target);

if (formatPathStats.isFile()) {
if (target.endsWith('.st.css')) {
Expand Down
11 changes: 6 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,8 @@ 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 {
stcConfig?: Configuration<string> | undefined;
Expand Down Expand Up @@ -64,21 +65,21 @@ export async function projectsConfig(
}

// todo: make fs not optional next major version
export function resolveConfig(context: string, request?: string, fs?: 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?: 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?: MinimalFS) {
function resolveConfigFile(context: string, fs?: IFileSystem) {
return loadStylableConfig(context, (config) => resolveConfigValue(config, fs));
}

function resolveConfigValue(config: any, fs?: MinimalFS) {
function resolveConfigValue(config: any, fs?: IFileSystem) {
return tryRun(
(): StylableRuntimeConfigs => ({
stcConfig: isSTCConfig(config)
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/test/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('assets', function () {
'/src/other.st.css': '.other {}',
'/node_modules/styles/3rd-party.css': '.third-party {}',
});
const resolve = createDefaultResolver(fs, {});
const resolve = createDefaultResolver({ fs });
const stylable = new Stylable({
projectRoot: '/',
fileSystem: fs,
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', () => {
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
10 changes: 5 additions & 5 deletions packages/cli/test/cli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,18 +558,18 @@ describe('Stylable Cli', function () {
});
});

describe('resolver', () => {
describe('resolver (cli)', () => {
it('should be able to build with enhanced-resolver alias configured', () => {
populateDirectorySync(tempDir.path, {
'package.json': `{"name": "test", "version": "0.0.0"}`,
'stylable.config.js': `
const { resolve } = require('node:path');
const { createDefaultResolver } = require('@stylable/core');
barak007 marked this conversation as resolved.
Show resolved Hide resolved
const { createWebpackResolver } = require('@stylable/webpack-plugin');

module.exports = {
defaultConfig(fs) {
return {
resolveModule: createDefaultResolver(fs, {
resolveModule: createWebpackResolver(fs, {
alias: {
'@colors': resolve(__dirname, './colors')
}
Expand Down Expand Up @@ -618,12 +618,12 @@ describe('Stylable Cli', function () {
'stylable.config.js': `
const { join } = require('path');
const { TsconfigPathsPlugin } = require('tsconfig-paths-webpack-plugin');
const { createDefaultResolver } = require('@stylable/core');
const { createWebpackResolver } = require('@stylable/webpack-plugin');

module.exports = {
defaultConfig(fs) {
return {
resolveModule: createDefaultResolver(fs, {
resolveModule: createWebpackResolver(fs, {
plugins: [new TsconfigPathsPlugin({ configFile: join(${JSON.stringify(
tempDir.path
)},'tsconfig.json') })],
Expand Down
23 changes: 21 additions & 2 deletions 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 @@ -62,7 +63,7 @@ export function generateInfra(config: InfraConfig, diagnostics: Diagnostics = ne
createDiagnostics: () => diagnostics,
});

const resolveModule = createDefaultResolver(fs, {});
const resolveModule = createDefaultResolver({ fs });
const resolvePath = (context: string | undefined = '/', moduleId: string) =>
resolveModule(context, moduleId);

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 = `resolve './unknown.st.css' in '/'\n No description file found in / or above\n No description file found in / or above\n no extension\n /unknown.st.css doesn't exist\n .js\n /unknown.st.css.js doesn't exist\n .json\n /unknown.st.css.json doesn't exist\n .node\n /unknown.st.css.node doesn't exist\n as directory\n /unknown.st.css doesn't exist`;
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
5 changes: 1 addition & 4 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,14 @@
"scripts": {
"test": "mocha \"./dist/test/**/*.spec.js\""
},
"browser": {
"module": false
},
"dependencies": {
"@file-services/resolve": "^8.2.0",
"@tokey/css-selector-parser": "^0.6.2",
"@tokey/css-value-parser": "^0.1.4",
"@tokey/imports-parser": "^1.0.0",
"balanced-match": "^2.0.0",
"css-selector-tokenizer": "^0.8.0",
"cssesc": "^3.0.0",
"enhanced-resolve": "^5.15.0",
"is-vendor-prefixed": "^4.0.0",
"lodash.clonedeep": "^4.5.0",
"lodash.clonedeepwith": "^4.5.0",
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.

Loading