@wyw-in-js/transform 0.4.1 → 0.5.1
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.
- package/esm/module.js +3 -2
- package/esm/module.js.map +1 -1
- package/esm/transform/generators/createStylisPreprocessor.js +11 -2
- package/esm/transform/generators/createStylisPreprocessor.js.map +1 -1
- package/esm/transform/helpers/loadWywOptions.js +2 -1
- package/esm/transform/helpers/loadWywOptions.js.map +1 -1
- package/lib/module.js +3 -2
- package/lib/module.js.map +1 -1
- package/lib/transform/generators/createStylisPreprocessor.js +12 -3
- package/lib/transform/generators/createStylisPreprocessor.js.map +1 -1
- package/lib/transform/helpers/loadWywOptions.js +2 -1
- package/lib/transform/helpers/loadWywOptions.js.map +1 -1
- package/package.json +7 -7
- package/types/module.d.ts +1 -1
- package/types/module.js +7 -2
- package/types/transform/generators/createStylisPreprocessor.js +13 -2
- package/types/transform/helpers/loadWywOptions.js +1 -0
package/esm/module.js
CHANGED
|
@@ -16,6 +16,7 @@ import NativeModule from 'module';
|
|
|
16
16
|
import path from 'path';
|
|
17
17
|
import vm from 'vm';
|
|
18
18
|
import { invariant } from 'ts-invariant';
|
|
19
|
+
import { isFeatureEnabled } from '@wyw-in-js/shared';
|
|
19
20
|
import './utils/dispose-polyfill';
|
|
20
21
|
import { Entrypoint } from './transform/Entrypoint';
|
|
21
22
|
import { getStack, isSuperSet } from './transform/Entrypoint.helpers';
|
|
@@ -119,7 +120,7 @@ export class Module {
|
|
|
119
120
|
this.services = services;
|
|
120
121
|
this.moduleImpl = moduleImpl;
|
|
121
122
|
this.cache = services.cache;
|
|
122
|
-
this.#entrypointRef = new WeakRef(entrypoint);
|
|
123
|
+
this.#entrypointRef = isFeatureEnabled(services.options.pluginOptions.features, 'useWeakRefInEval', entrypoint.name) ? new WeakRef(entrypoint) : entrypoint;
|
|
123
124
|
this.idx = entrypoint.idx;
|
|
124
125
|
this.id = entrypoint.name;
|
|
125
126
|
this.filename = entrypoint.name;
|
|
@@ -143,7 +144,7 @@ export class Module {
|
|
|
143
144
|
this.debug('the whole exports was overridden with %O', value);
|
|
144
145
|
}
|
|
145
146
|
get entrypoint() {
|
|
146
|
-
const entrypoint = this.#entrypointRef.deref();
|
|
147
|
+
const entrypoint = this.#entrypointRef instanceof WeakRef ? this.#entrypointRef.deref() : this.#entrypointRef;
|
|
147
148
|
invariant(entrypoint, `Module ${this.idx} is disposed`);
|
|
148
149
|
return entrypoint;
|
|
149
150
|
}
|
package/esm/module.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.js","names":["fs","NativeModule","path","vm","invariant","Entrypoint","getStack","isSuperSet","isUnprocessedEntrypointError","createVmContext","DefaultModuleImplementation","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","http","https","module","net","os","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","zlib","NOOP","getUncached","cached","test","cachedSet","Set","split","has","filter","t","resolve","id","resolved","resolveDependency","Module","callstack","isEvaluated","require","Object","assign","debug","dependency","isAbsolute","Error","source","dependencies","push","entrypoint","getEntrypoint","only","evaluated","evaluatedOnly","exports","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","services","parentModule","moduleImpl","cache","WeakRef","idx","name","filename","log","extend","parentIsIgnored","ignored","extensions","options","pluginOptions","value","deref","assertTransformed","get","evaluatedCreated","supersededWith","add","createEvaluated","transformedCode","JSON","parse","context","teardown","features","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","EvalError","message","join","extension","extname","includes","newEntrypoint","readFileSync","stack","uncachedExports","length","code","createRoot","getDependency","Promise","_extensions","added","forEach","ext","_resolveFilename","paths","_nodeModulePaths"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport type { Debugger } from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport { getStack, isSuperSet } from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst NOOP = () => {};\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint>;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = new WeakRef(entrypoint);\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint = this.#entrypointRef.deref();\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const { filename } = this;\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: string) => this.require(id),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n throw new EvalError(\n `${(e as Error).message} in${this.callstack.join('\\n| ')}\\n`\n );\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const extension = path.extname(filename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n const entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(filename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const uncachedExports = getUncached(entrypoint.only ?? [], only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n entrypoint.only\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(filename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n only,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n\n const resolved = this.moduleImpl._resolveFilename(id, {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n });\n\n return {\n source: id,\n only: ['*'],\n resolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,YAAY,MAAM,QAAQ;AACjC,OAAOC,IAAI,MAAM,MAAM;AACvB,OAAOC,EAAE,MAAM,IAAI;AAEnB,SAASC,SAAS,QAAQ,cAAc;AAIxC,OAAO,0BAA0B;AAEjC,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SA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BAAgB,CAAC1I,IAAI,CAAC+G,OAAO,CAACxB,QAAQ,CAAC;MAChE,CAAC,CAAC;MAEF,OAAO;QACLvB,MAAM,EAAEb,EAAE;QACVkB,IAAI,EAAE,CAAC,GAAG,CAAC;QACXjB;MACF,CAAC;IACH,CAAC,SAAS;MACR;MACAiF,KAAK,CAACC,OAAO,CAAEC,GAAG,IAAK,OAAO3C,UAAU,CAAC2C,GAAG,CAAC,CAAC;IAChD;EACF,CAAC;EAES7D,WAAWA,CAACP,UAAsB,EAAU;IACpD,OAAO,IAAIb,MAAM,CAAC,IAAI,CAAC0B,QAAQ,EAAEb,UAAU,EAAE,IAAI,EAAE,IAAI,CAACe,UAAU,CAAC;EACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"module.js","names":["fs","NativeModule","path","vm","invariant","isFeatureEnabled","Entrypoint","getStack","isSuperSet","isUnprocessedEntrypointError","createVmContext","DefaultModuleImplementation","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","http","https","module","net","os","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","zlib","NOOP","getUncached","cached","test","cachedSet","Set","split","has","filter","t","resolve","id","resolved","resolveDependency","Module","callstack","isEvaluated","require","Object","assign","debug","dependency","isAbsolute","Error","source","dependencies","push","entrypoint","getEntrypoint","only","evaluated","evaluatedOnly","exports","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","services","parentModule","moduleImpl","cache","options","pluginOptions","features","name","WeakRef","idx","filename","log","extend","parentIsIgnored","ignored","extensions","value","deref","assertTransformed","get","evaluatedCreated","supersededWith","add","createEvaluated","transformedCode","JSON","parse","context","teardown","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","EvalError","message","join","extension","extname","includes","newEntrypoint","readFileSync","stack","uncachedExports","length","code","createRoot","getDependency","Promise","_extensions","added","forEach","ext","_resolveFilename","paths","_nodeModulePaths"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport { isFeatureEnabled, type Debugger } from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport { getStack, isSuperSet } from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst NOOP = () => {};\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint> | Entrypoint;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = isFeatureEnabled(\n services.options.pluginOptions.features,\n 'useWeakRefInEval',\n entrypoint.name\n )\n ? new WeakRef(entrypoint)\n : entrypoint;\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint =\n this.#entrypointRef instanceof WeakRef\n ? this.#entrypointRef.deref()\n : this.#entrypointRef;\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const { filename } = this;\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: string) => this.require(id),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n throw new EvalError(\n `${(e as Error).message} in${this.callstack.join('\\n| ')}\\n`\n );\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const extension = path.extname(filename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n const entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(filename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const uncachedExports = getUncached(entrypoint.only ?? [], only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n entrypoint.only\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(filename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n only,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n\n const resolved = this.moduleImpl._resolveFilename(id, {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n });\n\n return {\n source: id,\n only: ['*'],\n resolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;A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AAMC,KAAe,GAAG,EAAE;IAE1B,IAAI;MACF;MACA,IAAI,CAACtC,UAAU,CAACuC,OAAO,CAAEC,GAAG,IAAK;QAC/B,IAAIA,GAAG,IAAIxC,UAAU,EAAE;UACrB;QACF;;QAEA;QACA;QACA;QACAA,UAAU,CAACwC,GAAG,CAAC,GAAG/F,IAAI;QACtB6F,KAAK,CAACnE,IAAI,CAACqE,GAAG,CAAC;MACjB,CAAC,CAAC;MAEF,MAAM;QAAE7C;MAAS,CAAC,GAAG,IAAI;MAEzB,MAAMtC,QAAQ,GAAG,IAAI,CAAC8B,UAAU,CAACsD,gBAAgB,CAACrF,EAAE,EAAE;QACpDA,EAAE,EAAEuC,QAAQ;QACZA,QAAQ;QACR+C,KAAK,EAAE,IAAI,CAACvD,UAAU,CAACwD,gBAAgB,CAAC3I,IAAI,CAACgH,OAAO,CAACrB,QAAQ,CAAC;MAChE,CAAC,CAAC;MAEF,OAAO;QACL1B,MAAM,EAAEb,EAAE;QACVkB,IAAI,EAAE,CAAC,GAAG,CAAC;QACXjB;MACF,CAAC;IACH,CAAC,SAAS;MACR;MACAiF,KAAK,CAACC,OAAO,CAAEC,GAAG,IAAK,OAAOxC,UAAU,CAACwC,GAAG,CAAC,CAAC;IAChD;EACF,CAAC;EAES7D,WAAWA,CAACP,UAAsB,EAAU;IACpD,OAAO,IAAIb,MAAM,CAAC,IAAI,CAAC0B,QAAQ,EAAEb,UAAU,EAAE,IAAI,EAAE,IAAI,CAACe,UAAU,CAAC;EACrE;AACF"}
|
|
@@ -13,6 +13,7 @@ export function transformUrl(url, outputFilename, sourceFilename, platformPath =
|
|
|
13
13
|
return relative.split(platformPath.sep).join(POSIX_SEP);
|
|
14
14
|
}
|
|
15
15
|
const DEFINED_KEYFRAMES = Symbol('definedKeyframes');
|
|
16
|
+
const ORIGINAL_KEYFRAME_NAME = Symbol('originalKeyframeName');
|
|
16
17
|
const ORIGINAL_VALUE_KEY = Symbol('originalValue');
|
|
17
18
|
const IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');
|
|
18
19
|
const getOriginalElementValue = element => {
|
|
@@ -156,7 +157,12 @@ export function createKeyframeSuffixerPlugin() {
|
|
|
156
157
|
}
|
|
157
158
|
const keyframes = new Set();
|
|
158
159
|
for (const sibling of element.siblings ?? []) {
|
|
159
|
-
if (
|
|
160
|
+
if (sibling[ORIGINAL_KEYFRAME_NAME]) {
|
|
161
|
+
keyframes.add(sibling[ORIGINAL_KEYFRAME_NAME]);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const name = sibling.props[0];
|
|
165
|
+
if (!isKeyframes(sibling) || sibling[IS_GLOBAL_KEYFRAMES] === true || name?.startsWith(':global(')) {
|
|
160
166
|
continue;
|
|
161
167
|
}
|
|
162
168
|
keyframes.add(sibling.props[0]);
|
|
@@ -170,8 +176,11 @@ export function createKeyframeSuffixerPlugin() {
|
|
|
170
176
|
if (isKeyframes(element) && element.parent) {
|
|
171
177
|
const suffix = elementToKeyframeSuffix(element);
|
|
172
178
|
const replaceFn = (_match, globalMatch, scopedMatch) => globalMatch || `${scopedMatch}-${suffix}`;
|
|
179
|
+
const originalName = element.props[0];
|
|
180
|
+
const isGlobal = originalName?.startsWith(':global(') ?? false;
|
|
173
181
|
Object.assign(element, {
|
|
174
|
-
[
|
|
182
|
+
[ORIGINAL_KEYFRAME_NAME]: isGlobal ? undefined : originalName,
|
|
183
|
+
[IS_GLOBAL_KEYFRAMES]: isGlobal,
|
|
175
184
|
props: element.props.map(getReplacer(/^\s*/, animationNameRegexp, replaceFn)),
|
|
176
185
|
value: getReplacer(buildPropsRegexp('keyframes', true), animationNameRegexp, replaceFn)(element.value)
|
|
177
186
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createStylisPreprocessor.js","names":["path","compile","middleware","prefixer","serialize","stringify","tokenize","RULESET","KEYFRAMES","DECLARATION","POSIX_SEP","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","DEFINED_KEYFRAMES","Symbol","ORIGINAL_VALUE_KEY","IS_GLOBAL_KEYFRAMES","getOriginalElementValue","element","value","throwIfNotProd","key","type","process","env","NODE_ENV","Error","JSON","childrenIsString","children","propsAreStrings","props","Array","isArray","propsIsString","isDeclaration","isKeyframes","isRuleset","stylisGlobalPlugin","getGlobalSelectorModifiers","el","parent","parentValue","length","includes","match","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","Object","assign","map","cssSelector","tokens","selector","i","len","token","slice","createStylisUrlReplacePlugin","filename","return","replace","_match","p1","_p2","p3","p4","createKeyframeSuffixerPlugin","prefixes","getPrefixedProp","prop","prefix","buildPropsRegexp","isAtRule","at","colon","RegExp","animationNameRegexp","getReplacer","startsWith","searchValue","replacer","input","fullMatch","undefined","rest","elementToKeyframeSuffix","replaceAll","animationPropsSet","Set","getDefinedKeyframes","keyframes","sibling","siblings","add","suffix","replaceFn","globalMatch","scopedMatch","keys","has","scopedKeyframes","patch","fromEntries","result","globalName","substring","isMiddleware","obj","createStylisPreprocessor","options","stylisPreprocess","text","compiled","filter"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n KEYFRAMES,\n DECLARATION,\n} from 'stylis';\nimport type { Middleware, Element } from 'stylis';\n\nimport type { Options } from '../../types';\n\nconst POSIX_SEP = path.posix.sep;\n\nexport function transformUrl(\n url: string,\n outputFilename: string,\n sourceFilename: string,\n platformPath: typeof path = path\n) {\n // Replace asset path with new path relative to the output CSS\n const relative = platformPath.relative(\n platformPath.dirname(outputFilename),\n // Get the absolute path to the asset from the path relative to the JS file\n platformPath.resolve(platformPath.dirname(sourceFilename), url)\n );\n\n if (platformPath.sep === POSIX_SEP) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(POSIX_SEP);\n}\n\ninterface IGlobalSelectorModifiers {\n includeBaseSelector: boolean;\n includeSpaceDelimiter: boolean;\n}\n\nconst DEFINED_KEYFRAMES = Symbol('definedKeyframes');\nconst ORIGINAL_VALUE_KEY = Symbol('originalValue');\nconst IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');\n\nconst getOriginalElementValue = (\n element: (Element & { [ORIGINAL_VALUE_KEY]?: string }) | null\n) => {\n return element ? element[ORIGINAL_VALUE_KEY] ?? element.value : '';\n};\n\nfunction throwIfNotProd(key: string, value: unknown, type: string): false {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.${key}\" has type \"${type}\" (${JSON.stringify(\n value,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return false;\n}\n\ntype SpecificElement<TFields> = Omit<Element, keyof TFields> & TFields;\ntype Declaration = SpecificElement<{\n children: string;\n props: string;\n type: typeof DECLARATION;\n}>;\ntype Keyframes = SpecificElement<{\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n props: string[];\n type: typeof KEYFRAMES;\n}>;\ntype Ruleset = SpecificElement<{\n props: string[];\n type: typeof RULESET;\n}>;\n\nfunction childrenIsString(children: string | Element[]): children is string {\n return (\n typeof children === 'string' ||\n throwIfNotProd('children', children, 'Element[]')\n );\n}\n\nfunction propsAreStrings(props: string | string[]): props is string[] {\n return Array.isArray(props) || throwIfNotProd('props', props, 'string');\n}\n\nfunction propsIsString(props: string | string[]): props is string {\n return (\n typeof props === 'string' || throwIfNotProd('props', props, 'string[]')\n );\n}\n\nconst isDeclaration = (element: Element): element is Declaration => {\n return (\n element.type === DECLARATION &&\n propsIsString(element.props) &&\n childrenIsString(element.children)\n );\n};\n\nconst isKeyframes = (element: Element): element is Keyframes => {\n return element.type === KEYFRAMES && propsAreStrings(element.props);\n};\n\nconst isRuleset = (element: Element): element is Ruleset => {\n return element.type === RULESET && propsAreStrings(element.props);\n};\n\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(el: Element): IGlobalSelectorModifiers {\n const { parent } = el;\n\n const value = getOriginalElementValue(el);\n const parentValue = getOriginalElementValue(parent);\n\n if (\n (parent?.children.length === 0 && parentValue.includes(':global(')) ||\n (parent && !value.includes(':global('))\n ) {\n return getGlobalSelectorModifiers(parent);\n }\n\n const match = value.match(/(&\\f( )?)?:global\\(/);\n\n if (match === null) {\n throw new Error(\n `Failed to match :global() selector in \"${value}\". Please report a bug if it happens.`\n );\n }\n\n const [, baseSelector, spaceDelimiter] = match;\n\n return {\n includeBaseSelector: !!baseSelector,\n includeSpaceDelimiter: !!spaceDelimiter,\n };\n }\n\n if (!isRuleset(element)) {\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // The value can be changed by other middlewares, but we need an original one with `&`\n Object.assign(element, { [ORIGINAL_VALUE_KEY]: element.value });\n\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n getGlobalSelectorModifiers(element);\n\n const tokens = tokenize(cssSelector);\n let selector = '';\n\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n\n //\n // Match for \":global(\"\n if (token === ':' && tokens[i + 1] === 'global') {\n //\n // Match for \":global()\"\n if (tokens[i + 2] === '()') {\n selector = [\n ...tokens.slice(i + 4),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n\n //\n // Match for \":global(selector)\"\n selector = [\n tokens[i + 2].slice(1, -1),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n }\n\n return selector;\n }),\n });\n};\n\nexport function createStylisUrlReplacePlugin(\n filename: string,\n outputFilename: string | undefined\n): Middleware {\n return (element) => {\n if (element.type === 'decl' && outputFilename) {\n // When writing to a file, we need to adjust the relative paths inside url(..) expressions.\n // It'll allow css-loader to resolve an imported asset properly.\n // eslint-disable-next-line no-param-reassign\n element.return = element.value.replace(\n /\\b(url\\(([\"']?))(\\.[^)]+?)(\\2\\))/g,\n (_match, p1, _p2, p3, p4) =>\n p1 + transformUrl(p3, outputFilename, filename) + p4\n );\n }\n };\n}\n\nexport function createKeyframeSuffixerPlugin(): Middleware {\n const prefixes = ['webkit', 'moz', 'ms', 'o', ''].map((i) =>\n i ? `-${i}-` : ''\n );\n\n const getPrefixedProp = (prop: string): string[] =>\n prefixes.map((prefix) => `${prefix}${prop}`);\n\n const buildPropsRegexp = (prop: string, isAtRule: boolean) => {\n const [at, colon] = isAtRule ? ['@', ''] : ['', ':'];\n return new RegExp(\n `^(${at}(?:${getPrefixedProp(prop).join('|')})${colon})\\\\s*`\n );\n };\n\n const animationNameRegexp = /:global\\(([\\w_-]+)\\)|([\\w_-]+)/;\n\n const getReplacer = (\n startsWith: RegExp,\n searchValue: RegExp,\n replacer: (substring: string, ...matches: string[]) => string\n ): ((input: string) => string) => {\n return (input) => {\n const [fullMatch] = input.match(startsWith) ?? [];\n if (fullMatch === undefined) {\n return input;\n }\n\n const rest = input.slice(fullMatch.length);\n return fullMatch + rest.replace(searchValue, replacer);\n };\n };\n\n const elementToKeyframeSuffix = (el: Element): string => {\n if (el.parent) {\n return elementToKeyframeSuffix(el.parent);\n }\n\n return el.value.replaceAll(/[^a-zA-Z0-9_-]/g, '');\n };\n\n const animationPropsSet = new Set([\n ...getPrefixedProp('animation'),\n ...getPrefixedProp('animation-name'),\n ]);\n\n const getDefinedKeyframes = (\n element: Element & {\n [DEFINED_KEYFRAMES]?: Set<string>;\n siblings?: (Element & { [IS_GLOBAL_KEYFRAMES]?: boolean })[];\n }\n ): Set<string> => {\n if (element[DEFINED_KEYFRAMES]) {\n return element[DEFINED_KEYFRAMES];\n }\n\n if (element.parent) {\n return getDefinedKeyframes(element.parent);\n }\n\n const keyframes = new Set<string>();\n for (const sibling of element.siblings ?? []) {\n if (!isKeyframes(sibling) || sibling[IS_GLOBAL_KEYFRAMES] === true) {\n continue;\n }\n\n keyframes.add(sibling.props[0]);\n }\n\n Object.assign(element, { [DEFINED_KEYFRAMES]: keyframes });\n\n return keyframes;\n };\n\n return (element) => {\n if (isKeyframes(element) && element.parent) {\n const suffix = elementToKeyframeSuffix(element);\n\n const replaceFn = (\n _match: string,\n globalMatch: string,\n scopedMatch: string\n ): string => globalMatch || `${scopedMatch}-${suffix}`;\n\n Object.assign(element, {\n [IS_GLOBAL_KEYFRAMES]:\n element.props[0]?.startsWith(':global(') ?? false,\n props: element.props.map(\n getReplacer(/^\\s*/, animationNameRegexp, replaceFn)\n ),\n value: getReplacer(\n buildPropsRegexp('keyframes', true),\n animationNameRegexp,\n replaceFn\n )(element.value),\n });\n\n return;\n }\n\n if (isDeclaration(element)) {\n const suffix = elementToKeyframeSuffix(element);\n const keys = [\n 'children',\n 'return',\n 'value',\n ] satisfies (keyof Declaration)[];\n\n if (animationPropsSet.has(element.props)) {\n const scopedKeyframes = getDefinedKeyframes(element);\n const patch = Object.fromEntries(\n keys.map((key) => {\n const tokens = tokenize(element[key]);\n let result = '';\n for (let i = 0; i < tokens.length; i += 1) {\n if (\n tokens[i] === ':' &&\n tokens[i + 1] === 'global' &&\n tokens[i + 2].startsWith('(')\n ) {\n const globalName = tokens[i + 2].substring(\n 1,\n tokens[i + 2].length - 1\n );\n i += 2;\n\n result += globalName;\n if (tokens[i + 1] !== ';') {\n result += ' ';\n }\n continue;\n }\n\n if (scopedKeyframes.has(tokens[i])) {\n result += `${tokens[i]}-${suffix}`;\n continue;\n }\n\n result += tokens[i];\n }\n\n return [key, result];\n })\n );\n\n Object.assign(element, patch);\n }\n }\n };\n}\n\nconst isMiddleware = (obj: Middleware | null): obj is Middleware =>\n obj !== null;\n\nexport function createStylisPreprocessor(\n options: Options & { prefixer?: boolean }\n) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware(\n [\n createStylisUrlReplacePlugin(\n options.filename,\n options.outputFilename\n ),\n stylisGlobalPlugin,\n options.prefixer === false ? null : prefixer,\n createKeyframeSuffixerPlugin(),\n stringify,\n ].filter(isMiddleware)\n )\n );\n }\n\n return stylisPreprocess;\n}\n"],"mappings":"AAAA;AACA,OAAO,KAAKA,IAAI,MAAM,MAAM;AAC5B,SACEC,OAAO,EACPC,UAAU,EACVC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,OAAO,EACPC,SAAS,EACTC,WAAW,QACN,QAAQ;AAKf,MAAMC,SAAS,GAAGV,IAAI,CAACW,KAAK,CAACC,GAAG;AAEhC,OAAO,SAASC,YAAYA,CAC1BC,GAAW,EACXC,cAAsB,EACtBC,cAAsB,EACtBC,YAAyB,GAAGjB,IAAI,EAChC;EACA;EACA,MAAMkB,QAAQ,GAAGD,YAAY,CAACC,QAAQ,CACpCD,YAAY,CAACE,OAAO,CAACJ,cAAc,CAAC;EACpC;EACAE,YAAY,CAACG,OAAO,CAACH,YAAY,CAACE,OAAO,CAACH,cAAc,CAAC,EAAEF,GAAG,CAChE,CAAC;EAED,IAAIG,YAAY,CAACL,GAAG,KAAKF,SAAS,EAAE;IAClC,OAAOQ,QAAQ;EACjB;EAEA,OAAOA,QAAQ,CAACG,KAAK,CAACJ,YAAY,CAACL,GAAG,CAAC,CAACU,IAAI,CAACZ,SAAS,CAAC;AACzD;AAOA,MAAMa,iBAAiB,GAAGC,MAAM,CAAC,kBAAkB,CAAC;AACpD,MAAMC,kBAAkB,GAAGD,MAAM,CAAC,eAAe,CAAC;AAClD,MAAME,mBAAmB,GAAGF,MAAM,CAAC,mBAAmB,CAAC;AAEvD,MAAMG,uBAAuB,GAC3BC,OAA6D,IAC1D;EACH,OAAOA,OAAO,GAAGA,OAAO,CA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O,EAAEsF,KAAK,CAAC;MAC/B;IACF;EACF,CAAC;AACH;AAEA,MAAMK,YAAY,GAAIC,GAAsB,IAC1CA,GAAG,KAAK,IAAI;AAEd,OAAO,SAASC,wBAAwBA,CACtCC,OAAyC,EACzC;EACA,SAASC,gBAAgBA,CAAC1D,QAAgB,EAAE2D,IAAY,EAAU;IAChE,MAAMC,QAAQ,GAAG5H,OAAO,CAAE,GAAEgE,QAAS,KAAI2D,IAAK,KAAI,CAAC;IAEnD,OAAOxH,SAAS,CACdyH,QAAQ,EACR3H,UAAU,CACR,CACEoE,4BAA4B,CAC1BoD,OAAO,CAACnD,QAAQ,EAChBmD,OAAO,CAAC3G,cACV,CAAC,EACDiC,kBAAkB,EAClB0E,OAAO,CAACvH,QAAQ,KAAK,KAAK,GAAG,IAAI,GAAGA,QAAQ,EAC5C4E,4BAA4B,CAAC,CAAC,EAC9B1E,SAAS,CACV,CAACyH,MAAM,CAACP,YAAY,CACvB,CACF,CAAC;EACH;EAEA,OAAOI,gBAAgB;AACzB"}
|
|
1
|
+
{"version":3,"file":"createStylisPreprocessor.js","names":["path","compile","middleware","prefixer","serialize","stringify","tokenize","RULESET","KEYFRAMES","DECLARATION","POSIX_SEP","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","DEFINED_KEYFRAMES","Symbol","ORIGINAL_KEYFRAME_NAME","ORIGINAL_VALUE_KEY","IS_GLOBAL_KEYFRAMES","getOriginalElementValue","element","value","throwIfNotProd","key","type","process","env","NODE_ENV","Error","JSON","childrenIsString","children","propsAreStrings","props","Array","isArray","propsIsString","isDeclaration","isKeyframes","isRuleset","stylisGlobalPlugin","getGlobalSelectorModifiers","el","parent","parentValue","length","includes","match","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","Object","assign","map","cssSelector","tokens","selector","i","len","token","slice","createStylisUrlReplacePlugin","filename","return","replace","_match","p1","_p2","p3","p4","createKeyframeSuffixerPlugin","prefixes","getPrefixedProp","prop","prefix","buildPropsRegexp","isAtRule","at","colon","RegExp","animationNameRegexp","getReplacer","startsWith","searchValue","replacer","input","fullMatch","undefined","rest","elementToKeyframeSuffix","replaceAll","animationPropsSet","Set","getDefinedKeyframes","keyframes","sibling","siblings","add","name","suffix","replaceFn","globalMatch","scopedMatch","originalName","isGlobal","keys","has","scopedKeyframes","patch","fromEntries","result","globalName","substring","isMiddleware","obj","createStylisPreprocessor","options","stylisPreprocess","text","compiled","filter"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n KEYFRAMES,\n DECLARATION,\n} from 'stylis';\nimport type { Middleware, Element } from 'stylis';\n\nimport type { Options } from '../../types';\n\nconst POSIX_SEP = path.posix.sep;\n\nexport function transformUrl(\n url: string,\n outputFilename: string,\n sourceFilename: string,\n platformPath: typeof path = path\n) {\n // Replace asset path with new path relative to the output CSS\n const relative = platformPath.relative(\n platformPath.dirname(outputFilename),\n // Get the absolute path to the asset from the path relative to the JS file\n platformPath.resolve(platformPath.dirname(sourceFilename), url)\n );\n\n if (platformPath.sep === POSIX_SEP) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(POSIX_SEP);\n}\n\ninterface IGlobalSelectorModifiers {\n includeBaseSelector: boolean;\n includeSpaceDelimiter: boolean;\n}\n\nconst DEFINED_KEYFRAMES = Symbol('definedKeyframes');\nconst ORIGINAL_KEYFRAME_NAME = Symbol('originalKeyframeName');\nconst ORIGINAL_VALUE_KEY = Symbol('originalValue');\nconst IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');\n\nconst getOriginalElementValue = (\n element: (Element & { [ORIGINAL_VALUE_KEY]?: string }) | null\n) => {\n return element ? element[ORIGINAL_VALUE_KEY] ?? element.value : '';\n};\n\nfunction throwIfNotProd(key: string, value: unknown, type: string): false {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.${key}\" has type \"${type}\" (${JSON.stringify(\n value,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return false;\n}\n\ntype SpecificElement<TFields> = Omit<Element, keyof TFields> & TFields;\ntype Declaration = SpecificElement<{\n children: string;\n props: string;\n type: typeof DECLARATION;\n}>;\ntype Keyframes = SpecificElement<{\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n props: string[];\n type: typeof KEYFRAMES;\n}>;\ntype Ruleset = SpecificElement<{\n props: string[];\n type: typeof RULESET;\n}>;\n\nfunction childrenIsString(children: string | Element[]): children is string {\n return (\n typeof children === 'string' ||\n throwIfNotProd('children', children, 'Element[]')\n );\n}\n\nfunction propsAreStrings(props: string | string[]): props is string[] {\n return Array.isArray(props) || throwIfNotProd('props', props, 'string');\n}\n\nfunction propsIsString(props: string | string[]): props is string {\n return (\n typeof props === 'string' || throwIfNotProd('props', props, 'string[]')\n );\n}\n\nconst isDeclaration = (element: Element): element is Declaration => {\n return (\n element.type === DECLARATION &&\n propsIsString(element.props) &&\n childrenIsString(element.children)\n );\n};\n\nconst isKeyframes = (element: Element): element is Keyframes => {\n return element.type === KEYFRAMES && propsAreStrings(element.props);\n};\n\nconst isRuleset = (element: Element): element is Ruleset => {\n return element.type === RULESET && propsAreStrings(element.props);\n};\n\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(el: Element): IGlobalSelectorModifiers {\n const { parent } = el;\n\n const value = getOriginalElementValue(el);\n const parentValue = getOriginalElementValue(parent);\n\n if (\n (parent?.children.length === 0 && parentValue.includes(':global(')) ||\n (parent && !value.includes(':global('))\n ) {\n return getGlobalSelectorModifiers(parent);\n }\n\n const match = value.match(/(&\\f( )?)?:global\\(/);\n\n if (match === null) {\n throw new Error(\n `Failed to match :global() selector in \"${value}\". Please report a bug if it happens.`\n );\n }\n\n const [, baseSelector, spaceDelimiter] = match;\n\n return {\n includeBaseSelector: !!baseSelector,\n includeSpaceDelimiter: !!spaceDelimiter,\n };\n }\n\n if (!isRuleset(element)) {\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // The value can be changed by other middlewares, but we need an original one with `&`\n Object.assign(element, { [ORIGINAL_VALUE_KEY]: element.value });\n\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n getGlobalSelectorModifiers(element);\n\n const tokens = tokenize(cssSelector);\n let selector = '';\n\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n\n //\n // Match for \":global(\"\n if (token === ':' && tokens[i + 1] === 'global') {\n //\n // Match for \":global()\"\n if (tokens[i + 2] === '()') {\n selector = [\n ...tokens.slice(i + 4),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n\n //\n // Match for \":global(selector)\"\n selector = [\n tokens[i + 2].slice(1, -1),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n }\n\n return selector;\n }),\n });\n};\n\nexport function createStylisUrlReplacePlugin(\n filename: string,\n outputFilename: string | undefined\n): Middleware {\n return (element) => {\n if (element.type === 'decl' && outputFilename) {\n // When writing to a file, we need to adjust the relative paths inside url(..) expressions.\n // It'll allow css-loader to resolve an imported asset properly.\n // eslint-disable-next-line no-param-reassign\n element.return = element.value.replace(\n /\\b(url\\(([\"']?))(\\.[^)]+?)(\\2\\))/g,\n (_match, p1, _p2, p3, p4) =>\n p1 + transformUrl(p3, outputFilename, filename) + p4\n );\n }\n };\n}\n\nexport function createKeyframeSuffixerPlugin(): Middleware {\n const prefixes = ['webkit', 'moz', 'ms', 'o', ''].map((i) =>\n i ? `-${i}-` : ''\n );\n\n const getPrefixedProp = (prop: string): string[] =>\n prefixes.map((prefix) => `${prefix}${prop}`);\n\n const buildPropsRegexp = (prop: string, isAtRule: boolean) => {\n const [at, colon] = isAtRule ? ['@', ''] : ['', ':'];\n return new RegExp(\n `^(${at}(?:${getPrefixedProp(prop).join('|')})${colon})\\\\s*`\n );\n };\n\n const animationNameRegexp = /:global\\(([\\w_-]+)\\)|([\\w_-]+)/;\n\n const getReplacer = (\n startsWith: RegExp,\n searchValue: RegExp,\n replacer: (substring: string, ...matches: string[]) => string\n ): ((input: string) => string) => {\n return (input) => {\n const [fullMatch] = input.match(startsWith) ?? [];\n if (fullMatch === undefined) {\n return input;\n }\n\n const rest = input.slice(fullMatch.length);\n return fullMatch + rest.replace(searchValue, replacer);\n };\n };\n\n const elementToKeyframeSuffix = (el: Element): string => {\n if (el.parent) {\n return elementToKeyframeSuffix(el.parent);\n }\n\n return el.value.replaceAll(/[^a-zA-Z0-9_-]/g, '');\n };\n\n const animationPropsSet = new Set([\n ...getPrefixedProp('animation'),\n ...getPrefixedProp('animation-name'),\n ]);\n\n const getDefinedKeyframes = (\n element: Element & {\n [DEFINED_KEYFRAMES]?: Set<string>;\n siblings?: (Element & {\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n [ORIGINAL_KEYFRAME_NAME]?: string;\n })[];\n }\n ): Set<string> => {\n if (element[DEFINED_KEYFRAMES]) {\n return element[DEFINED_KEYFRAMES];\n }\n\n if (element.parent) {\n return getDefinedKeyframes(element.parent);\n }\n\n const keyframes = new Set<string>();\n for (const sibling of element.siblings ?? []) {\n if (sibling[ORIGINAL_KEYFRAME_NAME]) {\n keyframes.add(sibling[ORIGINAL_KEYFRAME_NAME]);\n continue;\n }\n\n const name = sibling.props[0];\n if (\n !isKeyframes(sibling) ||\n sibling[IS_GLOBAL_KEYFRAMES] === true ||\n name?.startsWith(':global(')\n ) {\n continue;\n }\n\n keyframes.add(sibling.props[0]);\n }\n\n Object.assign(element, { [DEFINED_KEYFRAMES]: keyframes });\n\n return keyframes;\n };\n\n return (element) => {\n if (isKeyframes(element) && element.parent) {\n const suffix = elementToKeyframeSuffix(element);\n\n const replaceFn = (\n _match: string,\n globalMatch: string,\n scopedMatch: string\n ): string => globalMatch || `${scopedMatch}-${suffix}`;\n\n const originalName = element.props[0];\n const isGlobal = originalName?.startsWith(':global(') ?? false;\n\n Object.assign(element, {\n [ORIGINAL_KEYFRAME_NAME]: isGlobal ? undefined : originalName,\n [IS_GLOBAL_KEYFRAMES]: isGlobal,\n props: element.props.map(\n getReplacer(/^\\s*/, animationNameRegexp, replaceFn)\n ),\n value: getReplacer(\n buildPropsRegexp('keyframes', true),\n animationNameRegexp,\n replaceFn\n )(element.value),\n });\n\n return;\n }\n\n if (isDeclaration(element)) {\n const suffix = elementToKeyframeSuffix(element);\n const keys = [\n 'children',\n 'return',\n 'value',\n ] satisfies (keyof Declaration)[];\n\n if (animationPropsSet.has(element.props)) {\n const scopedKeyframes = getDefinedKeyframes(element);\n const patch = Object.fromEntries(\n keys.map((key) => {\n const tokens = tokenize(element[key]);\n let result = '';\n for (let i = 0; i < tokens.length; i += 1) {\n if (\n tokens[i] === ':' &&\n tokens[i + 1] === 'global' &&\n tokens[i + 2].startsWith('(')\n ) {\n const globalName = tokens[i + 2].substring(\n 1,\n tokens[i + 2].length - 1\n );\n i += 2;\n\n result += globalName;\n if (tokens[i + 1] !== ';') {\n result += ' ';\n }\n continue;\n }\n\n if (scopedKeyframes.has(tokens[i])) {\n result += `${tokens[i]}-${suffix}`;\n continue;\n }\n\n result += tokens[i];\n }\n\n return [key, result];\n })\n );\n\n Object.assign(element, patch);\n }\n }\n };\n}\n\nconst isMiddleware = (obj: Middleware | null): obj is Middleware =>\n obj !== null;\n\nexport function createStylisPreprocessor(\n options: Options & { prefixer?: boolean }\n) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware(\n [\n createStylisUrlReplacePlugin(\n options.filename,\n options.outputFilename\n ),\n stylisGlobalPlugin,\n options.prefixer === false ? null : prefixer,\n createKeyframeSuffixerPlugin(),\n stringify,\n ].filter(isMiddleware)\n )\n );\n }\n\n return stylisPreprocess;\n}\n"],"mappings":"AAAA;AACA,OAAO,KAAKA,IAAI,MAAM,MAAM;AAC5B,SACEC,OAAO,EACPC,UAAU,EACVC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,OAAO,EACPC,SAAS,EACTC,WAAW,QACN,QAAQ;AAKf,MAAMC,SAAS,GAAGV,IAAI,CAACW,KAAK,CAACC,GAAG;AAEhC,OAAO,SAASC,YAAYA,CAC1BC,GAAW,EACXC,cAAsB,EACtBC,cAAsB,EACtBC,YAAyB,GAAGjB,IAAI,EAChC;EACA;EACA,MAAMkB,QAAQ,GAAGD,YAAY,CAACC,QAAQ,CACpCD,YAAY,CAACE,OAAO,CAACJ,cAAc,CAAC;EACpC;EACAE,YAAY,CAACG,OAAO,CAACH,YAAY,CAACE,OAAO,CAACH,cAAc,CAAC,EAAEF,GAAG,CAChE,CAAC;EAED,IAAIG,YAAY,CAACL,GAAG,KAAKF,SAAS,EAAE;IAClC,OAAOQ,QAAQ;EACjB;EAEA,OAAOA,QAAQ,CAACG,KAAK,CAACJ,YAAY,CAACL,GAAG,CAAC,CAACU,IAAI,CAACZ,SAAS,CAAC;AACzD;AAOA,MAAMa,iBAAiB,GAAGC,MAAM,CAAC,kBAAkB,CAAC;AACpD,MAAMC,sBAAsB,GAAGD,MAAM,CAAC,sBAAsB,CAAC;AAC7D,MAAME,kBAAkB,GAAGF,MAAM,CAAC,eAAe,CAAC;AAClD,MAAMG,mBAAmB,GAAGH,MAAM,CAAC,mBAAmB,CAAC;AAEvD,MAAMI,uBAAuB,GAC3BC,OAA6D,IAC1D;EACH,OAAOA,OAAO,GAAGA,OAAO,CAACH,kBAAkB,CAAC,IAAIG,OAAO,CAACC,KAAK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G;cACf;cACA;YACF;YAEA,IAAIH,eAAe,CAACD,GAAG,CAACnD,MAAM,CAACE,CAAC,CAAC,CAAC,EAAE;cAClCqD,MAAM,IAAK,GAAEvD,MAAM,CAACE,CAAC,CAAE,IAAG0C,MAAO,EAAC;cAClC;YACF;YAEAW,MAAM,IAAIvD,MAAM,CAACE,CAAC,CAAC;UACrB;UAEA,OAAO,CAACnC,GAAG,EAAEwF,MAAM,CAAC;QACtB,CAAC,CACH,CAAC;QAED3D,MAAM,CAACC,MAAM,CAACjC,OAAO,EAAEyF,KAAK,CAAC;MAC/B;IACF;EACF,CAAC;AACH;AAEA,MAAMK,YAAY,GAAIC,GAAsB,IAC1CA,GAAG,KAAK,IAAI;AAEd,OAAO,SAASC,wBAAwBA,CACtCC,OAAyC,EACzC;EACA,SAASC,gBAAgBA,CAAC7D,QAAgB,EAAE8D,IAAY,EAAU;IAChE,MAAMC,QAAQ,GAAGhI,OAAO,CAAE,GAAEiE,QAAS,KAAI8D,IAAK,KAAI,CAAC;IAEnD,OAAO5H,SAAS,CACd6H,QAAQ,EACR/H,UAAU,CACR,CACEqE,4BAA4B,CAC1BuD,OAAO,CAACtD,QAAQ,EAChBsD,OAAO,CAAC/G,cACV,CAAC,EACDkC,kBAAkB,EAClB6E,OAAO,CAAC3H,QAAQ,KAAK,KAAK,GAAG,IAAI,GAAGA,QAAQ,EAC5C6E,4BAA4B,CAAC,CAAC,EAC9B3E,SAAS,CACV,CAAC6H,MAAM,CAACP,YAAY,CACvB,CACF,CAAC;EACH;EAEA,OAAOI,gBAAgB;AACzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadWywOptions.js","names":["cosmiconfigSync","shaker","searchPlaces","explorerSync","cache","WeakMap","defaultOverrides","nodeModulesRegExp","loadWywOptions","overrides","has","get","configFile","ignore","rules","babelOptions","rest","result","undefined","load","search","defaultFeatures","dangerousCodeRemover","globalCache","happyDOM","softErrors","useBabelConfigs","options","displayName","evaluate","extensions","action","test","filename","code","highPriorityPlugins","config","features","set"],"sources":["../../../src/transform/helpers/loadWywOptions.ts"],"sourcesContent":["import { cosmiconfigSync } from 'cosmiconfig';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\n\nimport { shaker } from '../../shaker';\nimport type { PluginOptions } from '../../types';\n\nconst searchPlaces = [\n `.wyw-in-jsrc`,\n `.wyw-in-jsrc.json`,\n `.wyw-in-jsrc.yaml`,\n `.wyw-in-jsrc.yml`,\n `.wyw-in-jsrc.js`,\n `.wyw-in-jsrc.cjs`,\n `.config/wyw-in-jsrc`,\n `.config/wyw-in-jsrc.json`,\n `.config/wyw-in-jsrc.yaml`,\n `.config/wyw-in-jsrc.yml`,\n `.config/wyw-in-jsrc.js`,\n `.config/wyw-in-jsrc.cjs`,\n `wyw-in-js.config.js`,\n `wyw-in-js.config.cjs`,\n];\n\nconst explorerSync = cosmiconfigSync('wyw-in-js', { searchPlaces });\n\nexport type PartialOptions = Partial<Omit<PluginOptions, 'features'>> & {\n features?: Partial<FeatureFlags>;\n};\n\nconst cache = new WeakMap<Partial<PartialOptions>, StrictOptions>();\nconst defaultOverrides = {};\nconst nodeModulesRegExp = /[\\\\/]node_modules[\\\\/]/;\n\nexport function loadWywOptions(\n overrides: PartialOptions = defaultOverrides\n): StrictOptions {\n if (cache.has(overrides)) {\n return cache.get(overrides)!;\n }\n\n const { configFile, ignore, rules, babelOptions = {}, ...rest } = overrides;\n\n const result =\n // eslint-disable-next-line no-nested-ternary\n configFile === false\n ? undefined\n : configFile !== undefined\n ? explorerSync.load(configFile)\n : explorerSync.search();\n\n const defaultFeatures: FeatureFlags = {\n dangerousCodeRemover: true,\n globalCache: true,\n happyDOM: true,\n softErrors: false,\n useBabelConfigs: true,\n };\n\n const options: StrictOptions = {\n displayName: false,\n evaluate: true,\n extensions: ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'],\n rules: rules ?? [\n {\n action: shaker,\n },\n {\n // The old `ignore` option is used as a default value for `ignore` rule.\n test: ignore ?? nodeModulesRegExp,\n action: 'ignore',\n },\n {\n // Do not ignore ES-modules\n test: (filename, code) => {\n if (!nodeModulesRegExp.test(filename)) {\n return false;\n }\n\n // If a file contains `export` or `import` keywords, we assume it's an ES-module\n return /(?:^|\\*\\/|;|})\\s*(?:export|import)[\\s{]/m.test(code);\n },\n action: shaker,\n },\n ],\n babelOptions,\n highPriorityPlugins: ['module-resolver'],\n ...(result ? result.config : {}),\n ...rest,\n features: {\n ...defaultFeatures,\n ...(result ? result.config.features : {}),\n ...rest.features,\n },\n };\n\n cache.set(overrides, options);\n\n return options;\n}\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,aAAa;AAI7C,SAASC,MAAM,QAAQ,cAAc;AAGrC,MAAMC,YAAY,GAAG,CAClB,cAAa,EACb,mBAAkB,EAClB,mBAAkB,EAClB,kBAAiB,EACjB,iBAAgB,EAChB,kBAAiB,EACjB,qBAAoB,EACpB,0BAAyB,EACzB,0BAAyB,EACzB,yBAAwB,EACxB,wBAAuB,EACvB,yBAAwB,EACxB,qBAAoB,EACpB,sBAAqB,CACvB;AAED,MAAMC,YAAY,GAAGH,eAAe,CAAC,WAAW,EAAE;EAAEE;AAAa,CAAC,CAAC;AAMnE,MAAME,KAAK,GAAG,IAAIC,OAAO,CAAyC,CAAC;AACnE,MAAMC,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAMC,iBAAiB,GAAG,wBAAwB;AAElD,OAAO,SAASC,cAAcA,CAC5BC,SAAyB,GAAGH,gBAAgB,EAC7B;EACf,IAAIF,KAAK,CAACM,GAAG,CAACD,SAAS,CAAC,EAAE;IACxB,OAAOL,KAAK,CAACO,GAAG,CAACF,SAAS,CAAC;EAC7B;EAEA,MAAM;IAAEG,UAAU;IAAEC,MAAM;IAAEC,KAAK;IAAEC,YAAY,GAAG,CAAC,CAAC;IAAE,GAAGC;EAAK,CAAC,GAAGP,SAAS;EAE3E,MAAMQ,MAAM;EACV;EACAL,UAAU,KAAK,KAAK,GAChBM,SAAS,GACTN,UAAU,KAAKM,SAAS,GACxBf,YAAY,CAACgB,IAAI,CAACP,UAAU,CAAC,GAC7BT,YAAY,CAACiB,MAAM,CAAC,CAAC;EAE3B,MAAMC,eAA6B,GAAG;IACpCC,oBAAoB,EAAE,IAAI;IAC1BC,WAAW,EAAE,IAAI;IACjBC,QAAQ,EAAE,IAAI;IACdC,UAAU,EAAE,KAAK;IACjBC,eAAe,EAAE;
|
|
1
|
+
{"version":3,"file":"loadWywOptions.js","names":["cosmiconfigSync","shaker","searchPlaces","explorerSync","cache","WeakMap","defaultOverrides","nodeModulesRegExp","loadWywOptions","overrides","has","get","configFile","ignore","rules","babelOptions","rest","result","undefined","load","search","defaultFeatures","dangerousCodeRemover","globalCache","happyDOM","softErrors","useBabelConfigs","useWeakRefInEval","options","displayName","evaluate","extensions","action","test","filename","code","highPriorityPlugins","config","features","set"],"sources":["../../../src/transform/helpers/loadWywOptions.ts"],"sourcesContent":["import { cosmiconfigSync } from 'cosmiconfig';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\n\nimport { shaker } from '../../shaker';\nimport type { PluginOptions } from '../../types';\n\nconst searchPlaces = [\n `.wyw-in-jsrc`,\n `.wyw-in-jsrc.json`,\n `.wyw-in-jsrc.yaml`,\n `.wyw-in-jsrc.yml`,\n `.wyw-in-jsrc.js`,\n `.wyw-in-jsrc.cjs`,\n `.config/wyw-in-jsrc`,\n `.config/wyw-in-jsrc.json`,\n `.config/wyw-in-jsrc.yaml`,\n `.config/wyw-in-jsrc.yml`,\n `.config/wyw-in-jsrc.js`,\n `.config/wyw-in-jsrc.cjs`,\n `wyw-in-js.config.js`,\n `wyw-in-js.config.cjs`,\n];\n\nconst explorerSync = cosmiconfigSync('wyw-in-js', { searchPlaces });\n\nexport type PartialOptions = Partial<Omit<PluginOptions, 'features'>> & {\n features?: Partial<FeatureFlags>;\n};\n\nconst cache = new WeakMap<Partial<PartialOptions>, StrictOptions>();\nconst defaultOverrides = {};\nconst nodeModulesRegExp = /[\\\\/]node_modules[\\\\/]/;\n\nexport function loadWywOptions(\n overrides: PartialOptions = defaultOverrides\n): StrictOptions {\n if (cache.has(overrides)) {\n return cache.get(overrides)!;\n }\n\n const { configFile, ignore, rules, babelOptions = {}, ...rest } = overrides;\n\n const result =\n // eslint-disable-next-line no-nested-ternary\n configFile === false\n ? undefined\n : configFile !== undefined\n ? explorerSync.load(configFile)\n : explorerSync.search();\n\n const defaultFeatures: FeatureFlags = {\n dangerousCodeRemover: true,\n globalCache: true,\n happyDOM: true,\n softErrors: false,\n useBabelConfigs: true,\n useWeakRefInEval: true,\n };\n\n const options: StrictOptions = {\n displayName: false,\n evaluate: true,\n extensions: ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'],\n rules: rules ?? [\n {\n action: shaker,\n },\n {\n // The old `ignore` option is used as a default value for `ignore` rule.\n test: ignore ?? nodeModulesRegExp,\n action: 'ignore',\n },\n {\n // Do not ignore ES-modules\n test: (filename, code) => {\n if (!nodeModulesRegExp.test(filename)) {\n return false;\n }\n\n // If a file contains `export` or `import` keywords, we assume it's an ES-module\n return /(?:^|\\*\\/|;|})\\s*(?:export|import)[\\s{]/m.test(code);\n },\n action: shaker,\n },\n ],\n babelOptions,\n highPriorityPlugins: ['module-resolver'],\n ...(result ? result.config : {}),\n ...rest,\n features: {\n ...defaultFeatures,\n ...(result ? result.config.features : {}),\n ...rest.features,\n },\n };\n\n cache.set(overrides, options);\n\n return options;\n}\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,aAAa;AAI7C,SAASC,MAAM,QAAQ,cAAc;AAGrC,MAAMC,YAAY,GAAG,CAClB,cAAa,EACb,mBAAkB,EAClB,mBAAkB,EAClB,kBAAiB,EACjB,iBAAgB,EAChB,kBAAiB,EACjB,qBAAoB,EACpB,0BAAyB,EACzB,0BAAyB,EACzB,yBAAwB,EACxB,wBAAuB,EACvB,yBAAwB,EACxB,qBAAoB,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,CAAC,EACD;MACE;MACAC,IAAI,EAAEA,CAACC,QAAQ,EAAEC,IAAI,KAAK;QACxB,IAAI,CAAC5B,iBAAiB,CAAC0B,IAAI,CAACC,QAAQ,CAAC,EAAE;UACrC,OAAO,KAAK;QACd;;QAEA;QACA,OAAO,0CAA0C,CAACD,IAAI,CAACE,IAAI,CAAC;MAC9D,CAAC;MACDH,MAAM,EAAE/B;IACV,CAAC,CACF;IACDc,YAAY;IACZqB,mBAAmB,EAAE,CAAC,iBAAiB,CAAC;IACxC,IAAInB,MAAM,GAAGA,MAAM,CAACoB,MAAM,GAAG,CAAC,CAAC,CAAC;IAChC,GAAGrB,IAAI;IACPsB,QAAQ,EAAE;MACR,GAAGjB,eAAe;MAClB,IAAIJ,MAAM,GAAGA,MAAM,CAACoB,MAAM,CAACC,QAAQ,GAAG,CAAC,CAAC,CAAC;MACzC,GAAGtB,IAAI,CAACsB;IACV;EACF,CAAC;EAEDlC,KAAK,CAACmC,GAAG,CAAC9B,SAAS,EAAEmB,OAAO,CAAC;EAE7B,OAAOA,OAAO;AAChB"}
|
package/lib/module.js
CHANGED
|
@@ -9,6 +9,7 @@ var _module = _interopRequireDefault(require("module"));
|
|
|
9
9
|
var _path = _interopRequireDefault(require("path"));
|
|
10
10
|
var _vm = _interopRequireDefault(require("vm"));
|
|
11
11
|
var _tsInvariant = require("ts-invariant");
|
|
12
|
+
var _shared = require("@wyw-in-js/shared");
|
|
12
13
|
require("./utils/dispose-polyfill");
|
|
13
14
|
var _Entrypoint = require("./transform/Entrypoint");
|
|
14
15
|
var _Entrypoint2 = require("./transform/Entrypoint.helpers");
|
|
@@ -127,7 +128,7 @@ class Module {
|
|
|
127
128
|
this.services = services;
|
|
128
129
|
this.moduleImpl = moduleImpl;
|
|
129
130
|
this.cache = services.cache;
|
|
130
|
-
this.#entrypointRef = new WeakRef(entrypoint);
|
|
131
|
+
this.#entrypointRef = (0, _shared.isFeatureEnabled)(services.options.pluginOptions.features, 'useWeakRefInEval', entrypoint.name) ? new WeakRef(entrypoint) : entrypoint;
|
|
131
132
|
this.idx = entrypoint.idx;
|
|
132
133
|
this.id = entrypoint.name;
|
|
133
134
|
this.filename = entrypoint.name;
|
|
@@ -151,7 +152,7 @@ class Module {
|
|
|
151
152
|
this.debug('the whole exports was overridden with %O', value);
|
|
152
153
|
}
|
|
153
154
|
get entrypoint() {
|
|
154
|
-
const entrypoint = this.#entrypointRef.deref();
|
|
155
|
+
const entrypoint = this.#entrypointRef instanceof WeakRef ? this.#entrypointRef.deref() : this.#entrypointRef;
|
|
155
156
|
(0, _tsInvariant.invariant)(entrypoint, `Module ${this.idx} is disposed`);
|
|
156
157
|
return entrypoint;
|
|
157
158
|
}
|
package/lib/module.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.js","names":["_fs","_interopRequireDefault","require","_module","_path","_vm","_tsInvariant","_Entrypoint","_Entrypoint2","_UnprocessedEntrypointError","_createVmContext","obj","__esModule","default","DefaultModuleImplementation","exports","NativeModule","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","fs","http","https","module","net","os","path","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","vm","zlib","NOOP","getUncached","cached","test","cachedSet","Set","split","has","filter","t","resolve","id","resolved","resolveDependency","invariant","Module","callstack","isEvaluated","Object","assign","debug","dependency","isAbsolute","Error","source","dependencies","push","entrypoint","getEntrypoint","only","evaluated","isSuperSet","evaluatedOnly","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","services","parentModule","moduleImpl","_parentModule$ignored","_entrypoint$ignored","cache","WeakRef","idx","name","filename","log","extend","parentIsIgnored","ignored","extensions","options","pluginOptions","value","deref","assertTransformed","get","evaluatedCreated","supersededWith","add","createEvaluated","transformedCode","JSON","parse","context","teardown","createVmContext","features","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","isUnprocessedEntrypointError","EvalError","message","join","_entrypoint$evaluated","extension","extname","includes","newEntrypoint","readFileSync","stack","getStack","_entrypoint$only","uncachedExports","length","code","Entrypoint","createRoot","getDependency","Promise","_extensions","added","forEach","ext","_resolveFilename","paths","_nodeModulePaths"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport type { Debugger } from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport { getStack, isSuperSet } from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst NOOP = () => {};\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint>;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = new WeakRef(entrypoint);\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint = this.#entrypointRef.deref();\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const { filename } = this;\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: string) => this.require(id),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n throw new EvalError(\n `${(e as Error).message} in${this.callstack.join('\\n| ')}\\n`\n );\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const extension = path.extname(filename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n const entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(filename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const uncachedExports = getUncached(entrypoint.only ?? [], only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n entrypoint.only\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(filename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n only,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n\n const resolved = this.moduleImpl._resolveFilename(id, {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n });\n\n return {\n source: id,\n only: ['*'],\n resolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n}\n"],"mappings":";;;;;;AAa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E,IAAI,CAACe,UAAU,CAAC;EACrE;AACF;AAAC9E,OAAA,CAAAmD,MAAA,GAAAA,MAAA"}
|
|
1
|
+
{"version":3,"file":"module.js","names":["_fs","_interopRequireDefault","require","_module","_path","_vm","_tsInvariant","_shared","_Entrypoint","_Entrypoint2","_UnprocessedEntrypointError","_createVmContext","obj","__esModule","default","DefaultModuleImplementation","exports","NativeModule","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","fs","http","https","module","net","os","path","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","vm","zlib","NOOP","getUncached","cached","test","cachedSet","Set","split","has","filter","t","resolve","id","resolved","resolveDependency","invariant","Module","callstack","isEvaluated","Object","assign","debug","dependency","isAbsolute","Error","source","dependencies","push","entrypoint","getEntrypoint","only","evaluated","isSuperSet","evaluatedOnly","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","services","parentModule","moduleImpl","_parentModule$ignored","_entrypoint$ignored","cache","isFeatureEnabled","options","pluginOptions","features","name","WeakRef","idx","filename","log","extend","parentIsIgnored","ignored","extensions","value","deref","assertTransformed","get","evaluatedCreated","supersededWith","add","createEvaluated","transformedCode","JSON","parse","context","teardown","createVmContext","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","isUnprocessedEntrypointError","EvalError","message","join","_entrypoint$evaluated","extension","extname","includes","newEntrypoint","readFileSync","stack","getStack","_entrypoint$only","uncachedExports","length","code","Entrypoint","createRoot","getDependency","Promise","_extensions","added","forEach","ext","_resolveFilename","paths","_nodeModulePaths"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport { isFeatureEnabled, type Debugger } from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport { getStack, isSuperSet } from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst NOOP = () => {};\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint> | Entrypoint;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = isFeatureEnabled(\n services.options.pluginOptions.features,\n 'useWeakRefInEval',\n entrypoint.name\n )\n ? new WeakRef(entrypoint)\n : entrypoint;\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint =\n this.#entrypointRef instanceof WeakRef\n ? this.#entrypointRef.deref()\n : this.#entrypointRef;\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const { filename } = this;\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: string) => this.require(id),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n throw new EvalError(\n `${(e as Error).message} in${this.callstack.join('\\n| ')}\\n`\n );\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const extension = path.extname(filename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n const entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(filename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const uncachedExports = getUncached(entrypoint.only ?? [], only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n entrypoint.only\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(filename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n only,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n\n const resolved = this.moduleImpl._resolveFilename(id, {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n });\n\n return {\n source: id,\n only: ['*'],\n resolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n}\n"],"mappings":";;;;;;AAaA,IAAAA,GAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,KAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,GAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,YAAA,GAAAJ,OAAA;AAEA,IAAAK,OAAA,G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AE,IAAI,CAACe,UAAU,CAAC;EACrE;AACF;AAAC9E,OAAA,CAAAmD,MAAA,GAAAA,MAAA"}
|
|
@@ -26,6 +26,7 @@ function transformUrl(url, outputFilename, sourceFilename, platformPath = path)
|
|
|
26
26
|
return relative.split(platformPath.sep).join(POSIX_SEP);
|
|
27
27
|
}
|
|
28
28
|
const DEFINED_KEYFRAMES = Symbol('definedKeyframes');
|
|
29
|
+
const ORIGINAL_KEYFRAME_NAME = Symbol('originalKeyframeName');
|
|
29
30
|
const ORIGINAL_VALUE_KEY = Symbol('originalValue');
|
|
30
31
|
const IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');
|
|
31
32
|
const getOriginalElementValue = element => {
|
|
@@ -173,7 +174,12 @@ function createKeyframeSuffixerPlugin() {
|
|
|
173
174
|
const keyframes = new Set();
|
|
174
175
|
for (const sibling of (_element$siblings = element.siblings) !== null && _element$siblings !== void 0 ? _element$siblings : []) {
|
|
175
176
|
var _element$siblings;
|
|
176
|
-
if (
|
|
177
|
+
if (sibling[ORIGINAL_KEYFRAME_NAME]) {
|
|
178
|
+
keyframes.add(sibling[ORIGINAL_KEYFRAME_NAME]);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const name = sibling.props[0];
|
|
182
|
+
if (!isKeyframes(sibling) || sibling[IS_GLOBAL_KEYFRAMES] === true || name !== null && name !== void 0 && name.startsWith(':global(')) {
|
|
177
183
|
continue;
|
|
178
184
|
}
|
|
179
185
|
keyframes.add(sibling.props[0]);
|
|
@@ -185,11 +191,14 @@ function createKeyframeSuffixerPlugin() {
|
|
|
185
191
|
};
|
|
186
192
|
return element => {
|
|
187
193
|
if (isKeyframes(element) && element.parent) {
|
|
188
|
-
var
|
|
194
|
+
var _originalName$startsW;
|
|
189
195
|
const suffix = elementToKeyframeSuffix(element);
|
|
190
196
|
const replaceFn = (_match, globalMatch, scopedMatch) => globalMatch || `${scopedMatch}-${suffix}`;
|
|
197
|
+
const originalName = element.props[0];
|
|
198
|
+
const isGlobal = (_originalName$startsW = originalName === null || originalName === void 0 ? void 0 : originalName.startsWith(':global(')) !== null && _originalName$startsW !== void 0 ? _originalName$startsW : false;
|
|
191
199
|
Object.assign(element, {
|
|
192
|
-
[
|
|
200
|
+
[ORIGINAL_KEYFRAME_NAME]: isGlobal ? undefined : originalName,
|
|
201
|
+
[IS_GLOBAL_KEYFRAMES]: isGlobal,
|
|
193
202
|
props: element.props.map(getReplacer(/^\s*/, animationNameRegexp, replaceFn)),
|
|
194
203
|
value: getReplacer(buildPropsRegexp('keyframes', true), animationNameRegexp, replaceFn)(element.value)
|
|
195
204
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createStylisPreprocessor.js","names":["path","_interopRequireWildcard","require","_stylis","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","POSIX_SEP","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","DEFINED_KEYFRAMES","Symbol","ORIGINAL_VALUE_KEY","IS_GLOBAL_KEYFRAMES","getOriginalElementValue","element","_element$ORIGINAL_VAL","value","throwIfNotProd","key","type","process","env","NODE_ENV","Error","JSON","stringify","childrenIsString","children","propsAreStrings","props","Array","isArray","propsIsString","isDeclaration","DECLARATION","isKeyframes","KEYFRAMES","isRuleset","RULESET","stylisGlobalPlugin","getGlobalSelectorModifiers","el","parent","parentValue","length","includes","match","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","assign","map","cssSelector","tokens","tokenize","selector","len","token","slice","exports","createStylisUrlReplacePlugin","filename","return","replace","_match","p1","_p2","p3","p4","createKeyframeSuffixerPlugin","prefixes","getPrefixedProp","prop","prefix","buildPropsRegexp","isAtRule","at","colon","RegExp","animationNameRegexp","getReplacer","startsWith","searchValue","replacer","input","_input$match","fullMatch","undefined","rest","elementToKeyframeSuffix","replaceAll","animationPropsSet","Set","getDefinedKeyframes","keyframes","sibling","_element$siblings","siblings","add","_element$props$0$star","_element$props$","suffix","replaceFn","globalMatch","scopedMatch","keys","scopedKeyframes","patch","fromEntries","result","globalName","substring","isMiddleware","obj","createStylisPreprocessor","options","stylisPreprocess","text","compiled","compile","serialize","middleware","prefixer","filter"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n KEYFRAMES,\n DECLARATION,\n} from 'stylis';\nimport type { Middleware, Element } from 'stylis';\n\nimport type { Options } from '../../types';\n\nconst POSIX_SEP = path.posix.sep;\n\nexport function transformUrl(\n url: string,\n outputFilename: string,\n sourceFilename: string,\n platformPath: typeof path = path\n) {\n // Replace asset path with new path relative to the output CSS\n const relative = platformPath.relative(\n platformPath.dirname(outputFilename),\n // Get the absolute path to the asset from the path relative to the JS file\n platformPath.resolve(platformPath.dirname(sourceFilename), url)\n );\n\n if (platformPath.sep === POSIX_SEP) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(POSIX_SEP);\n}\n\ninterface IGlobalSelectorModifiers {\n includeBaseSelector: boolean;\n includeSpaceDelimiter: boolean;\n}\n\nconst DEFINED_KEYFRAMES = Symbol('definedKeyframes');\nconst ORIGINAL_VALUE_KEY = Symbol('originalValue');\nconst IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');\n\nconst getOriginalElementValue = (\n element: (Element & { [ORIGINAL_VALUE_KEY]?: string }) | null\n) => {\n return element ? element[ORIGINAL_VALUE_KEY] ?? element.value : '';\n};\n\nfunction throwIfNotProd(key: string, value: unknown, type: string): false {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.${key}\" has type \"${type}\" (${JSON.stringify(\n value,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return false;\n}\n\ntype SpecificElement<TFields> = Omit<Element, keyof TFields> & TFields;\ntype Declaration = SpecificElement<{\n children: string;\n props: string;\n type: typeof DECLARATION;\n}>;\ntype Keyframes = SpecificElement<{\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n props: string[];\n type: typeof KEYFRAMES;\n}>;\ntype Ruleset = SpecificElement<{\n props: string[];\n type: typeof RULESET;\n}>;\n\nfunction childrenIsString(children: string | Element[]): children is string {\n return (\n typeof children === 'string' ||\n throwIfNotProd('children', children, 'Element[]')\n );\n}\n\nfunction propsAreStrings(props: string | string[]): props is string[] {\n return Array.isArray(props) || throwIfNotProd('props', props, 'string');\n}\n\nfunction propsIsString(props: string | string[]): props is string {\n return (\n typeof props === 'string' || throwIfNotProd('props', props, 'string[]')\n );\n}\n\nconst isDeclaration = (element: Element): element is Declaration => {\n return (\n element.type === DECLARATION &&\n propsIsString(element.props) &&\n childrenIsString(element.children)\n );\n};\n\nconst isKeyframes = (element: Element): element is Keyframes => {\n return element.type === KEYFRAMES && propsAreStrings(element.props);\n};\n\nconst isRuleset = (element: Element): element is Ruleset => {\n return element.type === RULESET && propsAreStrings(element.props);\n};\n\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(el: Element): IGlobalSelectorModifiers {\n const { parent } = el;\n\n const value = getOriginalElementValue(el);\n const parentValue = getOriginalElementValue(parent);\n\n if (\n (parent?.children.length === 0 && parentValue.includes(':global(')) ||\n (parent && !value.includes(':global('))\n ) {\n return getGlobalSelectorModifiers(parent);\n }\n\n const match = value.match(/(&\\f( )?)?:global\\(/);\n\n if (match === null) {\n throw new Error(\n `Failed to match :global() selector in \"${value}\". Please report a bug if it happens.`\n );\n }\n\n const [, baseSelector, spaceDelimiter] = match;\n\n return {\n includeBaseSelector: !!baseSelector,\n includeSpaceDelimiter: !!spaceDelimiter,\n };\n }\n\n if (!isRuleset(element)) {\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // The value can be changed by other middlewares, but we need an original one with `&`\n Object.assign(element, { [ORIGINAL_VALUE_KEY]: element.value });\n\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n getGlobalSelectorModifiers(element);\n\n const tokens = tokenize(cssSelector);\n let selector = '';\n\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n\n //\n // Match for \":global(\"\n if (token === ':' && tokens[i + 1] === 'global') {\n //\n // Match for \":global()\"\n if (tokens[i + 2] === '()') {\n selector = [\n ...tokens.slice(i + 4),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n\n //\n // Match for \":global(selector)\"\n selector = [\n tokens[i + 2].slice(1, -1),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n }\n\n return selector;\n }),\n });\n};\n\nexport function createStylisUrlReplacePlugin(\n filename: string,\n outputFilename: string | undefined\n): Middleware {\n return (element) => {\n if (element.type === 'decl' && outputFilename) {\n // When writing to a file, we need to adjust the relative paths inside url(..) expressions.\n // It'll allow css-loader to resolve an imported asset properly.\n // eslint-disable-next-line no-param-reassign\n element.return = element.value.replace(\n /\\b(url\\(([\"']?))(\\.[^)]+?)(\\2\\))/g,\n (_match, p1, _p2, p3, p4) =>\n p1 + transformUrl(p3, outputFilename, filename) + p4\n );\n }\n };\n}\n\nexport function createKeyframeSuffixerPlugin(): Middleware {\n const prefixes = ['webkit', 'moz', 'ms', 'o', ''].map((i) =>\n i ? `-${i}-` : ''\n );\n\n const getPrefixedProp = (prop: string): string[] =>\n prefixes.map((prefix) => `${prefix}${prop}`);\n\n const buildPropsRegexp = (prop: string, isAtRule: boolean) => {\n const [at, colon] = isAtRule ? ['@', ''] : ['', ':'];\n return new RegExp(\n `^(${at}(?:${getPrefixedProp(prop).join('|')})${colon})\\\\s*`\n );\n };\n\n const animationNameRegexp = /:global\\(([\\w_-]+)\\)|([\\w_-]+)/;\n\n const getReplacer = (\n startsWith: RegExp,\n searchValue: RegExp,\n replacer: (substring: string, ...matches: string[]) => string\n ): ((input: string) => string) => {\n return (input) => {\n const [fullMatch] = input.match(startsWith) ?? [];\n if (fullMatch === undefined) {\n return input;\n }\n\n const rest = input.slice(fullMatch.length);\n return fullMatch + rest.replace(searchValue, replacer);\n };\n };\n\n const elementToKeyframeSuffix = (el: Element): string => {\n if (el.parent) {\n return elementToKeyframeSuffix(el.parent);\n }\n\n return el.value.replaceAll(/[^a-zA-Z0-9_-]/g, '');\n };\n\n const animationPropsSet = new Set([\n ...getPrefixedProp('animation'),\n ...getPrefixedProp('animation-name'),\n ]);\n\n const getDefinedKeyframes = (\n element: Element & {\n [DEFINED_KEYFRAMES]?: Set<string>;\n siblings?: (Element & { [IS_GLOBAL_KEYFRAMES]?: boolean })[];\n }\n ): Set<string> => {\n if (element[DEFINED_KEYFRAMES]) {\n return element[DEFINED_KEYFRAMES];\n }\n\n if (element.parent) {\n return getDefinedKeyframes(element.parent);\n }\n\n const keyframes = new Set<string>();\n for (const sibling of element.siblings ?? []) {\n if (!isKeyframes(sibling) || sibling[IS_GLOBAL_KEYFRAMES] === true) {\n continue;\n }\n\n keyframes.add(sibling.props[0]);\n }\n\n Object.assign(element, { [DEFINED_KEYFRAMES]: keyframes });\n\n return keyframes;\n };\n\n return (element) => {\n if (isKeyframes(element) && element.parent) {\n const suffix = elementToKeyframeSuffix(element);\n\n const replaceFn = (\n _match: string,\n globalMatch: string,\n scopedMatch: string\n ): string => globalMatch || `${scopedMatch}-${suffix}`;\n\n Object.assign(element, {\n [IS_GLOBAL_KEYFRAMES]:\n element.props[0]?.startsWith(':global(') ?? false,\n props: element.props.map(\n getReplacer(/^\\s*/, animationNameRegexp, replaceFn)\n ),\n value: getReplacer(\n buildPropsRegexp('keyframes', true),\n animationNameRegexp,\n replaceFn\n )(element.value),\n });\n\n return;\n }\n\n if (isDeclaration(element)) {\n const suffix = elementToKeyframeSuffix(element);\n const keys = [\n 'children',\n 'return',\n 'value',\n ] satisfies (keyof Declaration)[];\n\n if (animationPropsSet.has(element.props)) {\n const scopedKeyframes = getDefinedKeyframes(element);\n const patch = Object.fromEntries(\n keys.map((key) => {\n const tokens = tokenize(element[key]);\n let result = '';\n for (let i = 0; i < tokens.length; i += 1) {\n if (\n tokens[i] === ':' &&\n tokens[i + 1] === 'global' &&\n tokens[i + 2].startsWith('(')\n ) {\n const globalName = tokens[i + 2].substring(\n 1,\n tokens[i + 2].length - 1\n );\n i += 2;\n\n result += globalName;\n if (tokens[i + 1] !== ';') {\n result += ' ';\n }\n continue;\n }\n\n if (scopedKeyframes.has(tokens[i])) {\n result += `${tokens[i]}-${suffix}`;\n continue;\n }\n\n result += tokens[i];\n }\n\n return [key, result];\n })\n );\n\n Object.assign(element, patch);\n }\n }\n };\n}\n\nconst isMiddleware = (obj: Middleware | null): obj is Middleware =>\n obj !== null;\n\nexport function createStylisPreprocessor(\n options: Options & { prefixer?: boolean }\n) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware(\n [\n createStylisUrlReplacePlugin(\n options.filename,\n options.outputFilename\n ),\n stylisGlobalPlugin,\n options.prefixer === false ? null : prefixer,\n createKeyframeSuffixerPlugin(),\n stringify,\n ].filter(isMiddleware)\n )\n );\n }\n\n return stylisPreprocess;\n}\n"],"mappings":";;;;;;;;;;AACA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AAUgB,SAAAE,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA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Q,GAAG,IAAAC,eAAO,EAAE,GAAEhE,QAAS,KAAI8D,IAAK,KAAI,CAAC;IAEnD,OAAO,IAAAG,iBAAS,EACdF,QAAQ,EACR,IAAAG,kBAAU,EACR,CACE7D,4BAA4B,CAC1BuD,OAAO,CAACtD,QAAQ,EAChBsD,OAAO,CAACnH,cACV,CAAC,EACDsC,kBAAkB,EAClB6E,OAAO,CAACO,QAAQ,KAAK,KAAK,GAAG,IAAI,GAAGA,gBAAQ,EAC5CrD,4BAA4B,CAAC,CAAC,EAC9B7C,iBAAS,CACV,CAACmG,MAAM,CAACX,YAAY,CACvB,CACF,CAAC;EACH;EAEA,OAAOI,gBAAgB;AACzB"}
|
|
1
|
+
{"version":3,"file":"createStylisPreprocessor.js","names":["path","_interopRequireWildcard","require","_stylis","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","POSIX_SEP","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","DEFINED_KEYFRAMES","Symbol","ORIGINAL_KEYFRAME_NAME","ORIGINAL_VALUE_KEY","IS_GLOBAL_KEYFRAMES","getOriginalElementValue","element","_element$ORIGINAL_VAL","value","throwIfNotProd","key","type","process","env","NODE_ENV","Error","JSON","stringify","childrenIsString","children","propsAreStrings","props","Array","isArray","propsIsString","isDeclaration","DECLARATION","isKeyframes","KEYFRAMES","isRuleset","RULESET","stylisGlobalPlugin","getGlobalSelectorModifiers","el","parent","parentValue","length","includes","match","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","assign","map","cssSelector","tokens","tokenize","selector","len","token","slice","exports","createStylisUrlReplacePlugin","filename","return","replace","_match","p1","_p2","p3","p4","createKeyframeSuffixerPlugin","prefixes","getPrefixedProp","prop","prefix","buildPropsRegexp","isAtRule","at","colon","RegExp","animationNameRegexp","getReplacer","startsWith","searchValue","replacer","input","_input$match","fullMatch","undefined","rest","elementToKeyframeSuffix","replaceAll","animationPropsSet","Set","getDefinedKeyframes","keyframes","sibling","_element$siblings","siblings","add","name","_originalName$startsW","suffix","replaceFn","globalMatch","scopedMatch","originalName","isGlobal","keys","scopedKeyframes","patch","fromEntries","result","globalName","substring","isMiddleware","obj","createStylisPreprocessor","options","stylisPreprocess","text","compiled","compile","serialize","middleware","prefixer","filter"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n KEYFRAMES,\n DECLARATION,\n} from 'stylis';\nimport type { Middleware, Element } from 'stylis';\n\nimport type { Options } from '../../types';\n\nconst POSIX_SEP = path.posix.sep;\n\nexport function transformUrl(\n url: string,\n outputFilename: string,\n sourceFilename: string,\n platformPath: typeof path = path\n) {\n // Replace asset path with new path relative to the output CSS\n const relative = platformPath.relative(\n platformPath.dirname(outputFilename),\n // Get the absolute path to the asset from the path relative to the JS file\n platformPath.resolve(platformPath.dirname(sourceFilename), url)\n );\n\n if (platformPath.sep === POSIX_SEP) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(POSIX_SEP);\n}\n\ninterface IGlobalSelectorModifiers {\n includeBaseSelector: boolean;\n includeSpaceDelimiter: boolean;\n}\n\nconst DEFINED_KEYFRAMES = Symbol('definedKeyframes');\nconst ORIGINAL_KEYFRAME_NAME = Symbol('originalKeyframeName');\nconst ORIGINAL_VALUE_KEY = Symbol('originalValue');\nconst IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');\n\nconst getOriginalElementValue = (\n element: (Element & { [ORIGINAL_VALUE_KEY]?: string }) | null\n) => {\n return element ? element[ORIGINAL_VALUE_KEY] ?? element.value : '';\n};\n\nfunction throwIfNotProd(key: string, value: unknown, type: string): false {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.${key}\" has type \"${type}\" (${JSON.stringify(\n value,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return false;\n}\n\ntype SpecificElement<TFields> = Omit<Element, keyof TFields> & TFields;\ntype Declaration = SpecificElement<{\n children: string;\n props: string;\n type: typeof DECLARATION;\n}>;\ntype Keyframes = SpecificElement<{\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n props: string[];\n type: typeof KEYFRAMES;\n}>;\ntype Ruleset = SpecificElement<{\n props: string[];\n type: typeof RULESET;\n}>;\n\nfunction childrenIsString(children: string | Element[]): children is string {\n return (\n typeof children === 'string' ||\n throwIfNotProd('children', children, 'Element[]')\n );\n}\n\nfunction propsAreStrings(props: string | string[]): props is string[] {\n return Array.isArray(props) || throwIfNotProd('props', props, 'string');\n}\n\nfunction propsIsString(props: string | string[]): props is string {\n return (\n typeof props === 'string' || throwIfNotProd('props', props, 'string[]')\n );\n}\n\nconst isDeclaration = (element: Element): element is Declaration => {\n return (\n element.type === DECLARATION &&\n propsIsString(element.props) &&\n childrenIsString(element.children)\n );\n};\n\nconst isKeyframes = (element: Element): element is Keyframes => {\n return element.type === KEYFRAMES && propsAreStrings(element.props);\n};\n\nconst isRuleset = (element: Element): element is Ruleset => {\n return element.type === RULESET && propsAreStrings(element.props);\n};\n\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(el: Element): IGlobalSelectorModifiers {\n const { parent } = el;\n\n const value = getOriginalElementValue(el);\n const parentValue = getOriginalElementValue(parent);\n\n if (\n (parent?.children.length === 0 && parentValue.includes(':global(')) ||\n (parent && !value.includes(':global('))\n ) {\n return getGlobalSelectorModifiers(parent);\n }\n\n const match = value.match(/(&\\f( )?)?:global\\(/);\n\n if (match === null) {\n throw new Error(\n `Failed to match :global() selector in \"${value}\". Please report a bug if it happens.`\n );\n }\n\n const [, baseSelector, spaceDelimiter] = match;\n\n return {\n includeBaseSelector: !!baseSelector,\n includeSpaceDelimiter: !!spaceDelimiter,\n };\n }\n\n if (!isRuleset(element)) {\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // The value can be changed by other middlewares, but we need an original one with `&`\n Object.assign(element, { [ORIGINAL_VALUE_KEY]: element.value });\n\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n getGlobalSelectorModifiers(element);\n\n const tokens = tokenize(cssSelector);\n let selector = '';\n\n for (let i = 0, len = tokens.length; i < len; i++) {\n const token = tokens[i];\n\n //\n // Match for \":global(\"\n if (token === ':' && tokens[i + 1] === 'global') {\n //\n // Match for \":global()\"\n if (tokens[i + 2] === '()') {\n selector = [\n ...tokens.slice(i + 4),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n\n //\n // Match for \":global(selector)\"\n selector = [\n tokens[i + 2].slice(1, -1),\n includeSpaceDelimiter ? ' ' : '',\n ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),\n includeSpaceDelimiter ? '' : ' ',\n ].join('');\n\n break;\n }\n }\n\n return selector;\n }),\n });\n};\n\nexport function createStylisUrlReplacePlugin(\n filename: string,\n outputFilename: string | undefined\n): Middleware {\n return (element) => {\n if (element.type === 'decl' && outputFilename) {\n // When writing to a file, we need to adjust the relative paths inside url(..) expressions.\n // It'll allow css-loader to resolve an imported asset properly.\n // eslint-disable-next-line no-param-reassign\n element.return = element.value.replace(\n /\\b(url\\(([\"']?))(\\.[^)]+?)(\\2\\))/g,\n (_match, p1, _p2, p3, p4) =>\n p1 + transformUrl(p3, outputFilename, filename) + p4\n );\n }\n };\n}\n\nexport function createKeyframeSuffixerPlugin(): Middleware {\n const prefixes = ['webkit', 'moz', 'ms', 'o', ''].map((i) =>\n i ? `-${i}-` : ''\n );\n\n const getPrefixedProp = (prop: string): string[] =>\n prefixes.map((prefix) => `${prefix}${prop}`);\n\n const buildPropsRegexp = (prop: string, isAtRule: boolean) => {\n const [at, colon] = isAtRule ? ['@', ''] : ['', ':'];\n return new RegExp(\n `^(${at}(?:${getPrefixedProp(prop).join('|')})${colon})\\\\s*`\n );\n };\n\n const animationNameRegexp = /:global\\(([\\w_-]+)\\)|([\\w_-]+)/;\n\n const getReplacer = (\n startsWith: RegExp,\n searchValue: RegExp,\n replacer: (substring: string, ...matches: string[]) => string\n ): ((input: string) => string) => {\n return (input) => {\n const [fullMatch] = input.match(startsWith) ?? [];\n if (fullMatch === undefined) {\n return input;\n }\n\n const rest = input.slice(fullMatch.length);\n return fullMatch + rest.replace(searchValue, replacer);\n };\n };\n\n const elementToKeyframeSuffix = (el: Element): string => {\n if (el.parent) {\n return elementToKeyframeSuffix(el.parent);\n }\n\n return el.value.replaceAll(/[^a-zA-Z0-9_-]/g, '');\n };\n\n const animationPropsSet = new Set([\n ...getPrefixedProp('animation'),\n ...getPrefixedProp('animation-name'),\n ]);\n\n const getDefinedKeyframes = (\n element: Element & {\n [DEFINED_KEYFRAMES]?: Set<string>;\n siblings?: (Element & {\n [IS_GLOBAL_KEYFRAMES]?: boolean;\n [ORIGINAL_KEYFRAME_NAME]?: string;\n })[];\n }\n ): Set<string> => {\n if (element[DEFINED_KEYFRAMES]) {\n return element[DEFINED_KEYFRAMES];\n }\n\n if (element.parent) {\n return getDefinedKeyframes(element.parent);\n }\n\n const keyframes = new Set<string>();\n for (const sibling of element.siblings ?? []) {\n if (sibling[ORIGINAL_KEYFRAME_NAME]) {\n keyframes.add(sibling[ORIGINAL_KEYFRAME_NAME]);\n continue;\n }\n\n const name = sibling.props[0];\n if (\n !isKeyframes(sibling) ||\n sibling[IS_GLOBAL_KEYFRAMES] === true ||\n name?.startsWith(':global(')\n ) {\n continue;\n }\n\n keyframes.add(sibling.props[0]);\n }\n\n Object.assign(element, { [DEFINED_KEYFRAMES]: keyframes });\n\n return keyframes;\n };\n\n return (element) => {\n if (isKeyframes(element) && element.parent) {\n const suffix = elementToKeyframeSuffix(element);\n\n const replaceFn = (\n _match: string,\n globalMatch: string,\n scopedMatch: string\n ): string => globalMatch || `${scopedMatch}-${suffix}`;\n\n const originalName = element.props[0];\n const isGlobal = originalName?.startsWith(':global(') ?? false;\n\n Object.assign(element, {\n [ORIGINAL_KEYFRAME_NAME]: isGlobal ? undefined : originalName,\n [IS_GLOBAL_KEYFRAMES]: isGlobal,\n props: element.props.map(\n getReplacer(/^\\s*/, animationNameRegexp, replaceFn)\n ),\n value: getReplacer(\n buildPropsRegexp('keyframes', true),\n animationNameRegexp,\n replaceFn\n )(element.value),\n });\n\n return;\n }\n\n if (isDeclaration(element)) {\n const suffix = elementToKeyframeSuffix(element);\n const keys = [\n 'children',\n 'return',\n 'value',\n ] satisfies (keyof Declaration)[];\n\n if (animationPropsSet.has(element.props)) {\n const scopedKeyframes = getDefinedKeyframes(element);\n const patch = Object.fromEntries(\n keys.map((key) => {\n const tokens = tokenize(element[key]);\n let result = '';\n for (let i = 0; i < tokens.length; i += 1) {\n if (\n tokens[i] === ':' &&\n tokens[i + 1] === 'global' &&\n tokens[i + 2].startsWith('(')\n ) {\n const globalName = tokens[i + 2].substring(\n 1,\n tokens[i + 2].length - 1\n );\n i += 2;\n\n result += globalName;\n if (tokens[i + 1] !== ';') {\n result += ' ';\n }\n continue;\n }\n\n if (scopedKeyframes.has(tokens[i])) {\n result += `${tokens[i]}-${suffix}`;\n continue;\n }\n\n result += tokens[i];\n }\n\n return [key, result];\n })\n );\n\n Object.assign(element, patch);\n }\n }\n };\n}\n\nconst isMiddleware = (obj: Middleware | null): obj is Middleware =>\n obj !== null;\n\nexport function createStylisPreprocessor(\n options: Options & { prefixer?: boolean }\n) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware(\n [\n createStylisUrlReplacePlugin(\n options.filename,\n options.outputF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ywOptions.js","names":["_cosmiconfig","require","_shaker","searchPlaces","explorerSync","cosmiconfigSync","cache","WeakMap","defaultOverrides","nodeModulesRegExp","loadWywOptions","overrides","has","get","configFile","ignore","rules","babelOptions","rest","result","undefined","load","search","defaultFeatures","dangerousCodeRemover","globalCache","happyDOM","softErrors","useBabelConfigs","options","displayName","evaluate","extensions","action","shaker","test","filename","code","highPriorityPlugins","config","features","set"],"sources":["../../../src/transform/helpers/loadWywOptions.ts"],"sourcesContent":["import { cosmiconfigSync } from 'cosmiconfig';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\n\nimport { shaker } from '../../shaker';\nimport type { PluginOptions } from '../../types';\n\nconst searchPlaces = [\n `.wyw-in-jsrc`,\n `.wyw-in-jsrc.json`,\n `.wyw-in-jsrc.yaml`,\n `.wyw-in-jsrc.yml`,\n `.wyw-in-jsrc.js`,\n `.wyw-in-jsrc.cjs`,\n `.config/wyw-in-jsrc`,\n `.config/wyw-in-jsrc.json`,\n `.config/wyw-in-jsrc.yaml`,\n `.config/wyw-in-jsrc.yml`,\n `.config/wyw-in-jsrc.js`,\n `.config/wyw-in-jsrc.cjs`,\n `wyw-in-js.config.js`,\n `wyw-in-js.config.cjs`,\n];\n\nconst explorerSync = cosmiconfigSync('wyw-in-js', { searchPlaces });\n\nexport type PartialOptions = Partial<Omit<PluginOptions, 'features'>> & {\n features?: Partial<FeatureFlags>;\n};\n\nconst cache = new WeakMap<Partial<PartialOptions>, StrictOptions>();\nconst defaultOverrides = {};\nconst nodeModulesRegExp = /[\\\\/]node_modules[\\\\/]/;\n\nexport function loadWywOptions(\n overrides: PartialOptions = defaultOverrides\n): StrictOptions {\n if (cache.has(overrides)) {\n return cache.get(overrides)!;\n }\n\n const { configFile, ignore, rules, babelOptions = {}, ...rest } = overrides;\n\n const result =\n // eslint-disable-next-line no-nested-ternary\n configFile === false\n ? undefined\n : configFile !== undefined\n ? explorerSync.load(configFile)\n : explorerSync.search();\n\n const defaultFeatures: FeatureFlags = {\n dangerousCodeRemover: true,\n globalCache: true,\n happyDOM: true,\n softErrors: false,\n useBabelConfigs: true,\n };\n\n const options: StrictOptions = {\n displayName: false,\n evaluate: true,\n extensions: ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'],\n rules: rules ?? [\n {\n action: shaker,\n },\n {\n // The old `ignore` option is used as a default value for `ignore` rule.\n test: ignore ?? nodeModulesRegExp,\n action: 'ignore',\n },\n {\n // Do not ignore ES-modules\n test: (filename, code) => {\n if (!nodeModulesRegExp.test(filename)) {\n return false;\n }\n\n // If a file contains `export` or `import` keywords, we assume it's an ES-module\n return /(?:^|\\*\\/|;|})\\s*(?:export|import)[\\s{]/m.test(code);\n },\n action: shaker,\n },\n ],\n babelOptions,\n highPriorityPlugins: ['module-resolver'],\n ...(result ? result.config : {}),\n ...rest,\n features: {\n ...defaultFeatures,\n ...(result ? result.config.features : {}),\n ...rest.features,\n },\n };\n\n cache.set(overrides, options);\n\n return options;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAIA,IAAAC,OAAA,GAAAD,OAAA;AAGA,MAAME,YAAY,GAAG,CAClB,cAAa,EACb,mBAAkB,EAClB,mBAAkB,EAClB,kBAAiB,EACjB,iBAAgB,EAChB,kBAAiB,EACjB,qBAAoB,EACpB,0BAAyB,EACzB,0BAAyB,EACzB,yBAAwB,EACxB,wBAAuB,EACvB,yBAAwB,EACxB,qBAAoB,EACpB,sBAAqB,CACvB;AAED,MAAMC,YAAY,GAAG,IAAAC,4BAAe,EAAC,WAAW,EAAE;EAAEF;AAAa,CAAC,CAAC;AAMnE,MAAMG,KAAK,GAAG,IAAIC,OAAO,CAAyC,CAAC;AACnE,MAAMC,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAMC,iBAAiB,GAAG,wBAAwB;AAE3C,SAASC,cAAcA,CAC5BC,SAAyB,GAAGH,gBAAgB,EAC7B;EACf,IAAIF,KAAK,CAACM,GAAG,CAACD,SAAS,CAAC,EAAE;IACxB,OAAOL,KAAK,CAACO,GAAG,CAACF,SAAS,CAAC;EAC7B;EAEA,MAAM;IAAEG,UAAU;IAAEC,MAAM;IAAEC,KAAK;IAAEC,YAAY,GAAG,CAAC,CAAC;IAAE,GAAGC;EAAK,CAAC,GAAGP,SAAS;EAE3E,MAAMQ,MAAM;EACV;EACAL,UAAU,KAAK,KAAK,GAChBM,SAAS,GACTN,UAAU,KAAKM,SAAS,GACxBhB,YAAY,CAACiB,IAAI,CAACP,UAAU,CAAC,GAC7BV,YAAY,CAACkB,MAAM,CAAC,CAAC;EAE3B,MAAMC,eAA6B,GAAG;IACpCC,oBAAoB,EAAE,IAAI;IAC1BC,WAAW,EAAE,IAAI;IACjBC,QAAQ,EAAE,IAAI;IACdC,UAAU,EAAE,KAAK;IACjBC,eAAe,EAAE;
|
|
1
|
+
{"version":3,"file":"loadWywOptions.js","names":["_cosmiconfig","require","_shaker","searchPlaces","explorerSync","cosmiconfigSync","cache","WeakMap","defaultOverrides","nodeModulesRegExp","loadWywOptions","overrides","has","get","configFile","ignore","rules","babelOptions","rest","result","undefined","load","search","defaultFeatures","dangerousCodeRemover","globalCache","happyDOM","softErrors","useBabelConfigs","useWeakRefInEval","options","displayName","evaluate","extensions","action","shaker","test","filename","code","highPriorityPlugins","config","features","set"],"sources":["../../../src/transform/helpers/loadWywOptions.ts"],"sourcesContent":["import { cosmiconfigSync } from 'cosmiconfig';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\n\nimport { shaker } from '../../shaker';\nimport type { PluginOptions } from '../../types';\n\nconst searchPlaces = [\n `.wyw-in-jsrc`,\n `.wyw-in-jsrc.json`,\n `.wyw-in-jsrc.yaml`,\n `.wyw-in-jsrc.yml`,\n `.wyw-in-jsrc.js`,\n `.wyw-in-jsrc.cjs`,\n `.config/wyw-in-jsrc`,\n `.config/wyw-in-jsrc.json`,\n `.config/wyw-in-jsrc.yaml`,\n `.config/wyw-in-jsrc.yml`,\n `.config/wyw-in-jsrc.js`,\n `.config/wyw-in-jsrc.cjs`,\n `wyw-in-js.config.js`,\n `wyw-in-js.config.cjs`,\n];\n\nconst explorerSync = cosmiconfigSync('wyw-in-js', { searchPlaces });\n\nexport type PartialOptions = Partial<Omit<PluginOptions, 'features'>> & {\n features?: Partial<FeatureFlags>;\n};\n\nconst cache = new WeakMap<Partial<PartialOptions>, StrictOptions>();\nconst defaultOverrides = {};\nconst nodeModulesRegExp = /[\\\\/]node_modules[\\\\/]/;\n\nexport function loadWywOptions(\n overrides: PartialOptions = defaultOverrides\n): StrictOptions {\n if (cache.has(overrides)) {\n return cache.get(overrides)!;\n }\n\n const { configFile, ignore, rules, babelOptions = {}, ...rest } = overrides;\n\n const result =\n // eslint-disable-next-line no-nested-ternary\n configFile === false\n ? undefined\n : configFile !== undefined\n ? explorerSync.load(configFile)\n : explorerSync.search();\n\n const defaultFeatures: FeatureFlags = {\n dangerousCodeRemover: true,\n globalCache: true,\n happyDOM: true,\n softErrors: false,\n useBabelConfigs: true,\n useWeakRefInEval: true,\n };\n\n const options: StrictOptions = {\n displayName: false,\n evaluate: true,\n extensions: ['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'],\n rules: rules ?? [\n {\n action: shaker,\n },\n {\n // The old `ignore` option is used as a default value for `ignore` rule.\n test: ignore ?? nodeModulesRegExp,\n action: 'ignore',\n },\n {\n // Do not ignore ES-modules\n test: (filename, code) => {\n if (!nodeModulesRegExp.test(filename)) {\n return false;\n }\n\n // If a file contains `export` or `import` keywords, we assume it's an ES-module\n return /(?:^|\\*\\/|;|})\\s*(?:export|import)[\\s{]/m.test(code);\n },\n action: shaker,\n },\n ],\n babelOptions,\n highPriorityPlugins: ['module-resolver'],\n ...(result ? result.config : {}),\n ...rest,\n features: {\n ...defaultFeatures,\n ...(result ? result.config.features : {}),\n ...rest.features,\n },\n };\n\n cache.set(overrides, options);\n\n return options;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,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,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC;IAC1EjB,KAAK,EAAEA,KAAK,aAALA,KAAK,cAALA,KAAK,GAAI,CACd;MACEkB,MAAM,EAAEC;IACV,CAAC,EACD;MACE;MACAC,IAAI,EAAErB,MAAM,aAANA,MAAM,cAANA,MAAM,GAAIN,iBAAiB;MACjCyB,MAAM,EAAE;IACV,CAAC,EACD;MACE;MACAE,IAAI,EAAEA,CAACC,QAAQ,EAAEC,IAAI,KAAK;QACxB,IAAI,CAAC7B,iBAAiB,CAAC2B,IAAI,CAACC,QAAQ,CAAC,EAAE;UACrC,OAAO,KAAK;QACd;;QAEA;QACA,OAAO,0CAA0C,CAACD,IAAI,CAACE,IAAI,CAAC;MAC9D,CAAC;MACDJ,MAAM,EAAEC;IACV,CAAC,CACF;IACDlB,YAAY;IACZsB,mBAAmB,EAAE,CAAC,iBAAiB,CAAC;IACxC,IAAIpB,MAAM,GAAGA,MAAM,CAACqB,MAAM,GAAG,CAAC,CAAC,CAAC;IAChC,GAAGtB,IAAI;IACPuB,QAAQ,EAAE;MACR,GAAGlB,eAAe;MAClB,IAAIJ,MAAM,GAAGA,MAAM,CAACqB,MAAM,CAACC,QAAQ,GAAG,CAAC,CAAC,CAAC;MACzC,GAAGvB,IAAI,CAACuB;IACV;EACF,CAAC;EAEDnC,KAAK,CAACoC,GAAG,CAAC/B,SAAS,EAAEmB,OAAO,CAAC;EAE7B,OAAOA,OAAO;AAChB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wyw-in-js/transform",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"dependencies": {
|
|
5
5
|
"@babel/core": "^7.23.5",
|
|
6
6
|
"@babel/generator": "^7.23.5",
|
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
"source-map": "^0.7.4",
|
|
16
16
|
"stylis": "^4.3.0",
|
|
17
17
|
"ts-invariant": "^0.10.3",
|
|
18
|
-
"@wyw-in-js/processor-utils": "0.
|
|
19
|
-
"@wyw-in-js/shared": "0.
|
|
18
|
+
"@wyw-in-js/processor-utils": "0.5.1",
|
|
19
|
+
"@wyw-in-js/shared": "0.5.1"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@babel/plugin-syntax-typescript": "^7.23.3",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"glob": "^10.3.10",
|
|
38
38
|
"strip-ansi": "^5.2.0",
|
|
39
39
|
"typescript": "^5.2.2",
|
|
40
|
-
"@wyw-in-js/babel-config": "0.
|
|
41
|
-
"@wyw-in-js/eslint-config": "0.
|
|
42
|
-
"@wyw-in-js/jest-preset": "0.
|
|
43
|
-
"@wyw-in-js/ts-config": "0.
|
|
40
|
+
"@wyw-in-js/babel-config": "0.5.1",
|
|
41
|
+
"@wyw-in-js/eslint-config": "0.5.1",
|
|
42
|
+
"@wyw-in-js/jest-preset": "0.5.1",
|
|
43
|
+
"@wyw-in-js/ts-config": "0.5.1"
|
|
44
44
|
},
|
|
45
45
|
"engines": {
|
|
46
46
|
"node": ">=16.0.0"
|
package/types/module.d.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
/// <reference types="node" />
|
|
14
14
|
/// <reference types="debug" />
|
|
15
15
|
import NativeModule from 'module';
|
|
16
|
-
import type
|
|
16
|
+
import { type Debugger } from '@wyw-in-js/shared';
|
|
17
17
|
import './utils/dispose-polyfill';
|
|
18
18
|
import { Entrypoint } from './transform/Entrypoint';
|
|
19
19
|
import type { IEntrypointDependency } from './transform/Entrypoint.types';
|
package/types/module.js
CHANGED
|
@@ -21,6 +21,7 @@ const module_1 = __importDefault(require("module"));
|
|
|
21
21
|
const path_1 = __importDefault(require("path"));
|
|
22
22
|
const vm_1 = __importDefault(require("vm"));
|
|
23
23
|
const ts_invariant_1 = require("ts-invariant");
|
|
24
|
+
const shared_1 = require("@wyw-in-js/shared");
|
|
24
25
|
require("./utils/dispose-polyfill");
|
|
25
26
|
const Entrypoint_1 = require("./transform/Entrypoint");
|
|
26
27
|
const Entrypoint_helpers_1 = require("./transform/Entrypoint.helpers");
|
|
@@ -132,7 +133,9 @@ class Module {
|
|
|
132
133
|
this.services = services;
|
|
133
134
|
this.moduleImpl = moduleImpl;
|
|
134
135
|
this.cache = services.cache;
|
|
135
|
-
this.#entrypointRef =
|
|
136
|
+
this.#entrypointRef = (0, shared_1.isFeatureEnabled)(services.options.pluginOptions.features, 'useWeakRefInEval', entrypoint.name)
|
|
137
|
+
? new WeakRef(entrypoint)
|
|
138
|
+
: entrypoint;
|
|
136
139
|
this.idx = entrypoint.idx;
|
|
137
140
|
this.id = entrypoint.name;
|
|
138
141
|
this.filename = entrypoint.name;
|
|
@@ -157,7 +160,9 @@ class Module {
|
|
|
157
160
|
this.debug('the whole exports was overridden with %O', value);
|
|
158
161
|
}
|
|
159
162
|
get entrypoint() {
|
|
160
|
-
const entrypoint = this.#entrypointRef
|
|
163
|
+
const entrypoint = this.#entrypointRef instanceof WeakRef
|
|
164
|
+
? this.#entrypointRef.deref()
|
|
165
|
+
: this.#entrypointRef;
|
|
161
166
|
(0, ts_invariant_1.invariant)(entrypoint, `Module ${this.idx} is disposed`);
|
|
162
167
|
return entrypoint;
|
|
163
168
|
}
|
|
@@ -40,6 +40,7 @@ function transformUrl(url, outputFilename, sourceFilename, platformPath = path)
|
|
|
40
40
|
}
|
|
41
41
|
exports.transformUrl = transformUrl;
|
|
42
42
|
const DEFINED_KEYFRAMES = Symbol('definedKeyframes');
|
|
43
|
+
const ORIGINAL_KEYFRAME_NAME = Symbol('originalKeyframeName');
|
|
43
44
|
const ORIGINAL_VALUE_KEY = Symbol('originalValue');
|
|
44
45
|
const IS_GLOBAL_KEYFRAMES = Symbol('isGlobalKeyframes');
|
|
45
46
|
const getOriginalElementValue = (element) => {
|
|
@@ -191,7 +192,14 @@ function createKeyframeSuffixerPlugin() {
|
|
|
191
192
|
}
|
|
192
193
|
const keyframes = new Set();
|
|
193
194
|
for (const sibling of element.siblings ?? []) {
|
|
194
|
-
if (
|
|
195
|
+
if (sibling[ORIGINAL_KEYFRAME_NAME]) {
|
|
196
|
+
keyframes.add(sibling[ORIGINAL_KEYFRAME_NAME]);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const name = sibling.props[0];
|
|
200
|
+
if (!isKeyframes(sibling) ||
|
|
201
|
+
sibling[IS_GLOBAL_KEYFRAMES] === true ||
|
|
202
|
+
name?.startsWith(':global(')) {
|
|
195
203
|
continue;
|
|
196
204
|
}
|
|
197
205
|
keyframes.add(sibling.props[0]);
|
|
@@ -203,8 +211,11 @@ function createKeyframeSuffixerPlugin() {
|
|
|
203
211
|
if (isKeyframes(element) && element.parent) {
|
|
204
212
|
const suffix = elementToKeyframeSuffix(element);
|
|
205
213
|
const replaceFn = (_match, globalMatch, scopedMatch) => globalMatch || `${scopedMatch}-${suffix}`;
|
|
214
|
+
const originalName = element.props[0];
|
|
215
|
+
const isGlobal = originalName?.startsWith(':global(') ?? false;
|
|
206
216
|
Object.assign(element, {
|
|
207
|
-
[
|
|
217
|
+
[ORIGINAL_KEYFRAME_NAME]: isGlobal ? undefined : originalName,
|
|
218
|
+
[IS_GLOBAL_KEYFRAMES]: isGlobal,
|
|
208
219
|
props: element.props.map(getReplacer(/^\s*/, animationNameRegexp, replaceFn)),
|
|
209
220
|
value: getReplacer(buildPropsRegexp('keyframes', true), animationNameRegexp, replaceFn)(element.value),
|
|
210
221
|
});
|