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

refactor!: unify runtime again #2914

Merged
merged 7 commits into from
Nov 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
6 changes: 6 additions & 0 deletions package-lock.json

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

6 changes: 3 additions & 3 deletions packages/cli/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ export async function build(
diagnostics,
diagnosticsMode,
inlineRuntime,
runtimeCjsRequest = '@stylable/runtime/dist/pure.js',
runtimeEsmRequest = '@stylable/runtime/esm/pure.js',
runtimeCjsRequest = '@stylable/runtime',
runtimeEsmRequest = '@stylable/runtime',
}: BuildOptions,
{
projectRoot: _projectRoot,
Expand Down Expand Up @@ -456,7 +456,7 @@ function copyRuntime(
}
if (esm) {
fs.ensureDirectorySync(fullOutDir);
runtimeEsmOutPath = fs.join(fullOutDir, 'stylable-esm-runtime.js');
runtimeEsmOutPath = fs.join(fullOutDir, 'stylable-esm-runtime.mjs');
fs.writeFileSync(runtimeEsmOutPath, fs.readFileSync(runtimeEsmPath, 'utf8'));
}
}
Expand Down
14 changes: 7 additions & 7 deletions packages/cli/test/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ describe('build stand alone', () => {
.root {}
`,
'/node_modules/@stylable/runtime/dist/index.js': `// runtime cjs`,
'/node_modules/@stylable/runtime/esm/index.js': `// runtime esm`,
'/node_modules/@stylable/runtime/dist/index.mjs': `// runtime esm`,
});

const stylable = new Stylable({
Expand All @@ -423,7 +423,7 @@ describe('build stand alone', () => {
esm: true,
inlineRuntime: true,
runtimeCjsRequest: '/node_modules/@stylable/runtime/dist/index.js',
runtimeEsmRequest: '/node_modules/@stylable/runtime/esm/index.js',
runtimeEsmRequest: '/node_modules/@stylable/runtime/dist/index.mjs',
},
{
fs,
Expand All @@ -440,18 +440,18 @@ describe('build stand alone', () => {

// this makes sure that we actually copied the runtime
const runtimeCjs = fs.readFileSync('/dist/stylable-cjs-runtime.js', 'utf8');
const runtimeMjs = fs.readFileSync('/dist/stylable-esm-runtime.js', 'utf8');
const runtimeMjs = fs.readFileSync('/dist/stylable-esm-runtime.mjs', 'utf8');

expect(builtFileCjs, 'imports the cjs runtime with full extension').to.contain(
`./stylable-cjs-runtime.js`
);
expect(builtFileEsm, 'imports the esm runtime with full extension').to.contain(
`./stylable-esm-runtime.js`
`./stylable-esm-runtime.mjs`
);
expect(
innerPathBuiltFileEsm,
'imports the esm runtime with full extension with relative path'
).to.contain(`./../stylable-esm-runtime.js`);
).to.contain(`./../stylable-esm-runtime.mjs`);
expect(runtimeCjs).to.eql(`// runtime cjs`);
expect(runtimeMjs).to.eql(`// runtime esm`);
});
Expand Down Expand Up @@ -495,10 +495,10 @@ describe('build stand alone', () => {
const builtFileEsm = fs.readFileSync('/dist/comp.st.css.js', 'utf8');

expect(builtFileCjs, 'imports the cjs runtime with full extension').to.contain(
`"@stylable/runtime/dist/pure.js"`
`"@stylable/runtime"`
);
expect(builtFileEsm, 'imports the esm runtime with full extension').to.contain(
`"@stylable/runtime/esm/pure.js"`
`"@stylable/runtime"`
);
});

Expand Down
8 changes: 1 addition & 7 deletions packages/core/src/stylable-js-module-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,7 @@ function runtimeImport(
injectOptions: InjectCSSOptions | undefined
) {
const importInjectCSS = injectOptions?.css ? `, injectCSS` : '';
const request = JSON.stringify(
runtimeRequest ??
// TODO: we use direct requests here since we don't know how this will be resolved
(moduleType === 'esm'
? '@stylable/runtime/esm/runtime.js'
: '@stylable/runtime/dist/runtime.js')
);
const request = JSON.stringify(runtimeRequest ?? '@stylable/runtime');
return moduleType === 'esm'
? `import { classesRuntime, statesRuntime${importInjectCSS} } from ${request};`
: `const { classesRuntime, statesRuntime${importInjectCSS} } = require(${request});`;
Expand Down
39 changes: 16 additions & 23 deletions packages/dom-test-kit/test/contract-test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,23 @@
import { create } from '@stylable/runtime';
import type { PartialElement } from '@stylable/dom-test-kit';
import { statesRuntime, type StateValue } from '@stylable/runtime';
import type { PartialElement, StylesheetHost } from '@stylable/dom-test-kit';

import { expect } from 'chai';

export const contractTest =
<T extends PartialElement>(
StylableUtilClass: any,
StylableUtilClass: new (
host: StylesheetHost & { cssStates(states: Record<string, StateValue>): string }
) => any,
options: { scopeSelectorTest?: boolean; createElement: () => T }
) =>
() => {
const s = create(
'ns',
{
classes: { root: 'ns-root', x: 'ns__x', y: 'ns__y', z: 'ns__z ns__y' },
keyframes: {},
layers: {},
containers: {},
vars: {},
stVars: {},
},
'',
0,
'0',
null
);

const util = new StylableUtilClass(s);
const namespace = 'ns';
const classes = { root: 'ns-root', x: 'ns__x', y: 'ns__y', z: 'ns__z ns__y' };
const util = new StylableUtilClass({
classes,
namespace,
cssStates: statesRuntime.bind(null, namespace),
});

if (options.scopeSelectorTest) {
it('scopeSelector defaults to root', () => {
Expand Down Expand Up @@ -67,17 +60,17 @@ export const contractTest =
describe('Style state', () => {
it('hasStyleState returns true if the requested style state exists', async () => {
const elem = options.createElement();
elem.classList.add(s.cssStates({ loading: true }));
elem.classList.add(statesRuntime(namespace, { loading: true }));
expect(await util.hasStyleState(elem, 'loading')).to.equal(true);
});
it('getStyleState returns the requested boolean style state value', async () => {
const elem = options.createElement();
elem.classList.add(s.cssStates({ loading: true }));
elem.classList.add(statesRuntime(namespace, { loading: true }));
expect(await util.getStyleState(elem, 'loading')).to.equal(true);
});
it('getStyleState returns the requested string style state value', async () => {
const elem = options.createElement();
elem.classList.add(s.cssStates({ loading: 'value' }));
elem.classList.add(statesRuntime(namespace, { loading: 'value' }));
expect(await util.getStyleState(elem, 'loading')).to.equal('value');
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/e2e-test-kit/src/stylable-webpack-test-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RuntimeRenderer } from '@stylable/runtime';
import * as runtime from '@stylable/runtime';
import * as stylesheet from '@stylable/runtime';

export interface MinimalModule {
Expand Down Expand Up @@ -48,7 +48,7 @@ export function evalStylableModule(
const moduleFactory = new Function('module', 'exports', '__webpack_require__', code);
const customRequire = (id: string) => {
if (id.match(/@stylable\/runtime$/)) {
return new RuntimeRenderer();
return runtime;
}
if (id.match(/css-runtime-stylesheet.js$/)) {
return stylesheet;
Expand Down
2 changes: 1 addition & 1 deletion packages/esbuild/src/stylable-esbuild-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ export const stylablePlugin = (initialPluginOptions: ESBuildOptions = {}): Plugi
namespace: res.meta.namespace,
jsExports: res.exports,
moduleType: 'esm',
runtimeRequest: '@stylable/runtime/esm/pure',
runtimeRequest: '@stylable/runtime',
},
cssInjection === 'js'
? {
Expand Down
21 changes: 9 additions & 12 deletions packages/experimental-loader/src/create-runtime-target-code.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import type { StylableExports } from '@stylable/core/dist/index-internal';
import { generateStylableJSModuleSource } from '@stylable/core';

export function createRuntimeTargetCode(namespace: string, mapping: StylableExports) {
return `
var rt = require("@stylable/runtime/dist/css-runtime-stylesheet.js");

module.exports = rt.create(
${JSON.stringify(namespace)},
${JSON.stringify(mapping)},
"",
-1,
module.id
);
`;
export function createRuntimeTargetCode(namespace: string, jsExports: StylableExports) {
const code = generateStylableJSModuleSource({
jsExports,
moduleType: 'cjs',
namespace,
varType: 'var',
});
return code;
}
5 changes: 2 additions & 3 deletions packages/module-utils/test/test-kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ export function evalStylableModule<T = unknown>(source: string, fullPath: string
return evalModule(fullPath, source, (id) => {
if (
id === '@stylable/runtime' ||
id === '@stylable/runtime/dist/runtime' ||
id === '@stylable/runtime/dist/runtime.js' ||
id === '@stylable/runtime/dist/pure.js'
id === '@stylable/runtime/dist/index.js' ||
id === '@stylable/runtime/dist/index.mjs'
) {
return runtime;
}
Expand Down
4 changes: 0 additions & 4 deletions packages/node/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ async function initiateModuleFactory() {
},
{
moduleType: 'esm',
// point to cjs - the esm runtime isn't published with mjs
// and causes issues. currently it's problematic for direct esm
// usage and only works for bundlers.
runtimePath: '@stylable/runtime/dist/pure.js',
}
);
}
Expand Down
5 changes: 0 additions & 5 deletions packages/rollup-plugin/runtime.js

This file was deleted.

41 changes: 24 additions & 17 deletions packages/rollup-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Plugin } from 'rollup';
import fs from '@file-services/node';
import { join, parse } from 'path';
import { Stylable, StylableConfig } from '@stylable/core';
import { Stylable, StylableConfig, generateStylableJSModuleSource } from '@stylable/core';
import {
emitDiagnostics,
DiagnosticsMode,
Expand All @@ -17,12 +17,7 @@ import {
import { packageJsonLookupCache, resolveNamespace as resolveNamespaceNode } from '@stylable/node';
import { StylableOptimizer } from '@stylable/optimizer';
import decache from 'decache';
import {
emitAssets,
generateCssString,
generateStylableModuleCode,
getDefaultMode,
} from './plugin-utils';
import { emitAssets, generateCssString, getDefaultMode } from './plugin-utils';
import { resolveConfig as resolveStcConfig, STCBuilder } from '@stylable/cli';

export interface StylableRollupPluginOptions {
Expand Down Expand Up @@ -190,18 +185,20 @@ export function stylableRollupPlugin({
const { meta, exports } = stylable.transform(stylable.analyze(path, source));
const assetsIds = emitAssets(this, stylable, meta, emittedAssets, inlineAssets);
const css = generateCssString(meta, minify, stylable, assetsIds);
const moduleImports: string[] = [];
const moduleImports: { from: string }[] = [];

if (includeGlobalSideEffects) {
// new mode that collect deep side effects
collectImportsWithSideEffects(stylable, meta, (_contextMeta, absPath, isUsed) => {
if (isUsed) {
if (!absPath.endsWith(ST_CSS)) {
moduleImports.push(
`import ${JSON.stringify(absPath + LOADABLE_CSS_QUERY)};`
);
moduleImports.push({
from: absPath + LOADABLE_CSS_QUERY,
});
} else {
moduleImports.push(`import ${JSON.stringify(absPath)};`);
moduleImports.push({
from: absPath,
});
}
}
});
Expand All @@ -220,11 +217,13 @@ export function stylableRollupPlugin({
}
// include Stylable and native css files that have effects on other files as regular imports
if (resolved.endsWith('.css') && !resolved.endsWith(ST_CSS)) {
moduleImports.push(
`import ${JSON.stringify(resolved + LOADABLE_CSS_QUERY)};`
);
moduleImports.push({
from: resolved + LOADABLE_CSS_QUERY,
});
} else if (hasImportedSideEffects(stylable, meta, imported)) {
moduleImports.push(`import ${JSON.stringify(imported.request)};`);
moduleImports.push({
from: imported.request,
});
}
}
}
Expand All @@ -249,8 +248,16 @@ export function stylableRollupPlugin({
);
}

const code = generateStylableJSModuleSource({
jsExports: exports,
moduleType: 'esm',
namespace: meta.namespace,
varType: 'var',
imports: moduleImports,
});

return {
code: generateStylableModuleCode(meta, exports, moduleImports),
code,
map: { mappings: '' },
};
},
Expand Down
25 changes: 0 additions & 25 deletions packages/rollup-plugin/src/plugin-utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Stylable, StylableMeta } from '@stylable/core';
import type { StylableExports } from '@stylable/core/dist/index-internal';
import type { PluginContext } from 'rollup';
import type { StylableRollupPluginOptions } from './index';
import { processUrlDependencies } from '@stylable/build-tools';
Expand All @@ -8,30 +7,6 @@ import { basename, extname, isAbsolute, join } from 'path';
import { createHash } from 'crypto';
import { getType } from 'mime';

const runtimePath = JSON.stringify(require.resolve('@stylable/rollup-plugin/runtime'));
const runtimeImport = `import { stc, sts } from ${runtimePath};`;

export function generateStylableModuleCode(
meta: StylableMeta,
exports: StylableExports,
moduleImports: string[]
) {
return `
${runtimeImport}
${moduleImports.join('\n')}
export var namespace = ${JSON.stringify(meta.namespace)};
export var st = sts.bind(null, namespace);
export var style = st;
export var cssStates = stc.bind(null, namespace);
export var classes = ${JSON.stringify(exports.classes)};
export var keyframes = ${JSON.stringify(exports.keyframes)};
export var layers = ${JSON.stringify(exports.layers)};
export var containers = ${JSON.stringify(exports.containers)};
export var stVars = ${JSON.stringify(exports.stVars)};
export var vars = ${JSON.stringify(exports.vars)};
`;
}

export function generateCssString(
meta: StylableMeta,
minify: boolean,
Expand Down
9 changes: 9 additions & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
"test:unit": "mocha \"dist/test/unit/**/*.spec.js\"",
"test:e2e": "mocha \"dist/test/e2e/**/*.spec.js\" --timeout 20000"
},
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./package.json": "./package.json",
"./dist/index.js": "./dist/index.js",
"./dist/index.mjs": "./dist/index.mjs"
},
"files": [
"dist",
"esm",
Expand Down
Loading