@wyw-in-js/transform 0.2.2 → 0.2.3

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/index.js CHANGED
@@ -13,7 +13,7 @@ export { parseFile } from './transform/Entrypoint.helpers';
13
13
  export { baseHandlers } from './transform/generators';
14
14
  export { prepareCode } from './transform/generators/transform';
15
15
  export { Entrypoint } from './transform/Entrypoint';
16
- export { transformUrl } from './transform/generators/extract';
16
+ export { transformUrl } from './transform/generators/createStylisPreprocessor';
17
17
  export { asyncResolveImports, syncResolveImports } from './transform/generators/resolveImports';
18
18
  export { loadWywOptions } from './transform/helpers/loadWywOptions';
19
19
  export { withDefaultServices } from './transform/helpers/withDefaultServices';
package/esm/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["slugify","createFileReporter","default","babelTransformPlugin","preeval","getTransformMetadata","withTransformMetadata","Module","DefaultModuleImplementation","shaker","transform","isUnprocessedEntrypointError","UnprocessedEntrypointError","EvaluatedEntrypoint","parseFile","baseHandlers","prepareCode","Entrypoint","transformUrl","asyncResolveImports","syncResolveImports","loadWywOptions","withDefaultServices","EventEmitter","isNode","getFileIdx","getTagProcessor","getVisitorKeys","peek","processTemplateExpression","TransformCacheCollection"],"sources":["../src/index.ts"],"sourcesContent":["export { slugify } from '@wyw-in-js/shared';\n\nexport { createFileReporter } from './debug/fileReporter';\nexport type { IFileReporterOptions } from './debug/fileReporter';\nexport { default as babelTransformPlugin } from './plugins/babel-transform';\nexport { default as preeval } from './plugins/preeval';\nexport {\n getTransformMetadata,\n withTransformMetadata,\n} from './utils/TransformMetadata';\nexport type { WYWTransformMetadata } from './utils/TransformMetadata';\nexport { Module, DefaultModuleImplementation } from './module';\nexport { default as shaker } from './shaker';\nexport { transform } from './transform';\nexport {\n isUnprocessedEntrypointError,\n UnprocessedEntrypointError,\n} from './transform/actions/UnprocessedEntrypointError';\nexport * from './types';\nexport { EvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport { parseFile } from './transform/Entrypoint.helpers';\nexport type { LoadAndParseFn } from './transform/Entrypoint.types';\nexport { baseHandlers } from './transform/generators';\nexport { prepareCode } from './transform/generators/transform';\nexport { Entrypoint } from './transform/Entrypoint';\nexport { transformUrl } from './transform/generators/extract';\nexport {\n asyncResolveImports,\n syncResolveImports,\n} from './transform/generators/resolveImports';\nexport { loadWywOptions } from './transform/helpers/loadWywOptions';\nexport { withDefaultServices } from './transform/helpers/withDefaultServices';\nexport type { Services } from './transform/types';\nexport { EventEmitter } from './utils/EventEmitter';\nexport type {\n EntrypointEvent,\n OnEvent,\n OnActionStartArgs,\n OnActionFinishArgs,\n} from './utils/EventEmitter';\nexport { isNode } from './utils/isNode';\nexport { getFileIdx } from './utils/getFileIdx';\nexport { getTagProcessor } from './utils/getTagProcessor';\nexport { getVisitorKeys } from './utils/getVisitorKeys';\nexport type { VisitorKeys } from './utils/getVisitorKeys';\nexport { peek } from './utils/peek';\nexport { processTemplateExpression } from './utils/processTemplateExpression';\nexport { TransformCacheCollection } from './cache';\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAE3C,SAASC,kBAAkB,QAAQ,sBAAsB;AAEzD,SAASC,OAAO,IAAIC,oBAAoB,QAAQ,2BAA2B;AAC3E,SAASD,OAAO,IAAIE,OAAO,QAAQ,mBAAmB;AACtD,SACEC,oBAAoB,EACpBC,qBAAqB,QAChB,2BAA2B;AAElC,SAASC,MAAM,EAAEC,2BAA2B,QAAQ,UAAU;AAC9D,SAASN,OAAO,IAAIO,MAAM,QAAQ,UAAU;AAC5C,SAASC,SAAS,QAAQ,aAAa;AACvC,SACEC,4BAA4B,EAC5BC,0BAA0B,QACrB,gDAAgD;AACvD,cAAc,SAAS;AACvB,SAASC,mBAAmB,QAAQ,iCAAiC;AAErE,SAASC,SAAS,QAAQ,gCAAgC;AAE1D,SAASC,YAAY,QAAQ,wBAAwB;AACrD,SAASC,WAAW,QAAQ,kCAAkC;AAC9D,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,YAAY,QAAQ,gCAAgC;AAC7D,SACEC,mBAAmB,EACnBC,kBAAkB,QACb,uCAAuC;AAC9C,SAASC,cAAc,QAAQ,oCAAoC;AACnE,SAASC,mBAAmB,QAAQ,yCAAyC;AAE7E,SAASC,YAAY,QAAQ,sBAAsB;AAOnD,SAASC,MAAM,QAAQ,gBAAgB;AACvC,SAASC,UAAU,QAAQ,oBAAoB;AAC/C,SAASC,eAAe,QAAQ,yBAAyB;AACzD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,SAASC,IAAI,QAAQ,cAAc;AACnC,SAASC,yBAAyB,QAAQ,mCAAmC;AAC7E,SAASC,wBAAwB,QAAQ,SAAS"}
1
+ {"version":3,"file":"index.js","names":["slugify","createFileReporter","default","babelTransformPlugin","preeval","getTransformMetadata","withTransformMetadata","Module","DefaultModuleImplementation","shaker","transform","isUnprocessedEntrypointError","UnprocessedEntrypointError","EvaluatedEntrypoint","parseFile","baseHandlers","prepareCode","Entrypoint","transformUrl","asyncResolveImports","syncResolveImports","loadWywOptions","withDefaultServices","EventEmitter","isNode","getFileIdx","getTagProcessor","getVisitorKeys","peek","processTemplateExpression","TransformCacheCollection"],"sources":["../src/index.ts"],"sourcesContent":["export { slugify } from '@wyw-in-js/shared';\n\nexport { createFileReporter } from './debug/fileReporter';\nexport type { IFileReporterOptions } from './debug/fileReporter';\nexport { default as babelTransformPlugin } from './plugins/babel-transform';\nexport { default as preeval } from './plugins/preeval';\nexport {\n getTransformMetadata,\n withTransformMetadata,\n} from './utils/TransformMetadata';\nexport type { WYWTransformMetadata } from './utils/TransformMetadata';\nexport { Module, DefaultModuleImplementation } from './module';\nexport { default as shaker } from './shaker';\nexport { transform } from './transform';\nexport {\n isUnprocessedEntrypointError,\n UnprocessedEntrypointError,\n} from './transform/actions/UnprocessedEntrypointError';\nexport * from './types';\nexport { EvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport { parseFile } from './transform/Entrypoint.helpers';\nexport type { LoadAndParseFn } from './transform/Entrypoint.types';\nexport { baseHandlers } from './transform/generators';\nexport { prepareCode } from './transform/generators/transform';\nexport { Entrypoint } from './transform/Entrypoint';\nexport { transformUrl } from './transform/generators/createStylisPreprocessor';\nexport {\n asyncResolveImports,\n syncResolveImports,\n} from './transform/generators/resolveImports';\nexport { loadWywOptions } from './transform/helpers/loadWywOptions';\nexport { withDefaultServices } from './transform/helpers/withDefaultServices';\nexport type { Services } from './transform/types';\nexport { EventEmitter } from './utils/EventEmitter';\nexport type {\n EntrypointEvent,\n OnEvent,\n OnActionStartArgs,\n OnActionFinishArgs,\n} from './utils/EventEmitter';\nexport { isNode } from './utils/isNode';\nexport { getFileIdx } from './utils/getFileIdx';\nexport { getTagProcessor } from './utils/getTagProcessor';\nexport { getVisitorKeys } from './utils/getVisitorKeys';\nexport type { VisitorKeys } from './utils/getVisitorKeys';\nexport { peek } from './utils/peek';\nexport { processTemplateExpression } from './utils/processTemplateExpression';\nexport { TransformCacheCollection } from './cache';\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,mBAAmB;AAE3C,SAASC,kBAAkB,QAAQ,sBAAsB;AAEzD,SAASC,OAAO,IAAIC,oBAAoB,QAAQ,2BAA2B;AAC3E,SAASD,OAAO,IAAIE,OAAO,QAAQ,mBAAmB;AACtD,SACEC,oBAAoB,EACpBC,qBAAqB,QAChB,2BAA2B;AAElC,SAASC,MAAM,EAAEC,2BAA2B,QAAQ,UAAU;AAC9D,SAASN,OAAO,IAAIO,MAAM,QAAQ,UAAU;AAC5C,SAASC,SAAS,QAAQ,aAAa;AACvC,SACEC,4BAA4B,EAC5BC,0BAA0B,QACrB,gDAAgD;AACvD,cAAc,SAAS;AACvB,SAASC,mBAAmB,QAAQ,iCAAiC;AAErE,SAASC,SAAS,QAAQ,gCAAgC;AAE1D,SAASC,YAAY,QAAQ,wBAAwB;AACrD,SAASC,WAAW,QAAQ,kCAAkC;AAC9D,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,YAAY,QAAQ,iDAAiD;AAC9E,SACEC,mBAAmB,EACnBC,kBAAkB,QACb,uCAAuC;AAC9C,SAASC,cAAc,QAAQ,oCAAoC;AACnE,SAASC,mBAAmB,QAAQ,yCAAyC;AAE7E,SAASC,YAAY,QAAQ,sBAAsB;AAOnD,SAASC,MAAM,QAAQ,gBAAgB;AACvC,SAASC,UAAU,QAAQ,oBAAoB;AAC/C,SAASC,eAAe,QAAQ,yBAAyB;AACzD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,SAASC,IAAI,QAAQ,cAAc;AACnC,SAASC,yBAAyB,QAAQ,mCAAmC;AAC7E,SAASC,wBAAwB,QAAQ,SAAS"}
@@ -255,6 +255,7 @@ export default function shakerPlugin(babel, {
255
255
  const unreferenced = Object.values(file.scope.getAllBindings()).filter(i => !i.referenced);
256
256
  for (const binding of unreferenced) {
257
257
  if (binding.path.isVariableDeclarator() && !forDeleting.includes(binding.path.get('id'))) {
258
+ forDeleting.push(...binding.constantViolations);
258
259
  forDeleting.push(binding.path.get('id'));
259
260
  changed = true;
260
261
  }
@@ -1 +1 @@
1
- {"version":3,"file":"shaker.js","names":["logger","collectExportsAndImports","sideEffectImport","getFileIdx","isRemoved","applyAction","dereference","findActionForNode","reference","removeWithRelated","invalidateTraversalCache","EXT_REGEX","ALLOWED_EXTENSIONS","shouldKeepSideEffect","importPath","ext","match","includes","getBindingForExport","exportPath","isIdentifier","scope","getBinding","node","name","variableDeclarator","findParent","p","isVariableDeclarator","id","get","isAssignmentExpression","left","isFunctionDeclaration","isClassDeclaration","undefined","withoutRemoved","items","filter","local","rearrangeExports","types","t","root","exportRefs","exports","rearranged","rootScope","forEach","refs","length","declarator","uid","generateUid","declaration","unshiftContainer","variableDeclaration","identifier","registerDeclaration","constantViolations","ref","replaced","replaceWith","isBindingIdentifier","push","registerConstantViolation","assigmentToExport","expressionStatement","assignmentExpression","memberExpression","body","lastViolation","pathInRoot","find","n","isDescendant","pushed","insertAfter","shakerPlugin","babel","keepSideEffects","ifUnknownExport","onlyExports","shakerLogger","extend","pre","file","filename","opts","log","join","onlyExportsSet","Set","collected","path","sideEffectImports","imports","Object","values","reexports","hasWywPreval","__wywPreval","hasDefault","default","has","delete","size","deadExports","keys","remove","importedAsSideEffect","isEsModule","add","aliveExports","importNames","map","imported","entries","exported","some","alive","exp","exportToPath","Map","set","notFoundExports","clear","isAllExportsFound","Error","forDeleting","i","source","deleted","dereferenced","changed","binding","action","parent","outerReferences","referencePaths","isAncestor","unreferenced","getAllBindings","referenced","visitor","post","processedImports","addImport","metadata","wywEvaluator"],"sources":["../../src/plugins/shaker.ts"],"sourcesContent":["import type { BabelFile, PluginObj, NodePath } from '@babel/core';\nimport type { Binding } from '@babel/traverse';\nimport type {\n Identifier,\n MemberExpression,\n Program,\n VariableDeclarator,\n} from '@babel/types';\n\nimport { logger } from '@wyw-in-js/shared';\n\nimport type { Core } from '../babel';\nimport type { IMetadata } from '../utils/ShakerMetadata';\nimport type { Exports, IState } from '../utils/collectExportsAndImports';\nimport {\n collectExportsAndImports,\n sideEffectImport,\n} from '../utils/collectExportsAndImports';\nimport { getFileIdx } from '../utils/getFileIdx';\nimport { isRemoved } from '../utils/isRemoved';\nimport {\n applyAction,\n dereference,\n findActionForNode,\n reference,\n removeWithRelated,\n} from '../utils/scopeHelpers';\nimport { invalidateTraversalCache } from '../utils/traversalCache';\n\nconst EXT_REGEX = /\\.[0-9a-z]+$/;\nconst ALLOWED_EXTENSIONS = ['.js', '.cjs', '.mjs'];\n\nfunction shouldKeepSideEffect(importPath: string) {\n const [ext] = importPath.match(EXT_REGEX) || [''];\n\n return ext === '' || ALLOWED_EXTENSIONS.includes(ext);\n}\n\nexport interface IShakerOptions {\n ifUnknownExport?: 'error' | 'ignore' | 'reexport-all' | 'skip-shaking';\n keepSideEffects?: boolean;\n onlyExports: string[];\n}\n\ninterface NodeWithName {\n name: string;\n}\n\nfunction getBindingForExport(exportPath: NodePath): Binding | undefined {\n if (exportPath.isIdentifier()) {\n return exportPath.scope.getBinding(exportPath.node.name);\n }\n\n const variableDeclarator = exportPath.findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n if (variableDeclarator) {\n const id = variableDeclarator.get('id');\n if (id.isIdentifier()) {\n return variableDeclarator.scope.getBinding(id.node.name);\n }\n }\n\n if (exportPath.isAssignmentExpression()) {\n const left = exportPath.get('left');\n if (left.isIdentifier()) {\n return exportPath.scope.getBinding(left.node.name);\n }\n }\n\n if (exportPath.isFunctionDeclaration() || exportPath.isClassDeclaration()) {\n return exportPath.scope.getBinding(exportPath.node.id!.name);\n }\n\n return undefined;\n}\n\nconst withoutRemoved = <T extends { local: NodePath }>(items: T[]): T[] =>\n items.filter(({ local }) => !isRemoved(local));\n\nfunction rearrangeExports(\n { types: t }: Core,\n root: NodePath<Program>,\n exportRefs: Map<string, NodePath<MemberExpression>[]>,\n exports: Exports\n): Exports {\n const rearranged = {\n ...exports,\n };\n\n const rootScope = root.scope;\n exportRefs.forEach((refs, name) => {\n if (refs.length <= 1) {\n if (refs.length === 1) {\n // Maybe exports is assigned to another variable?\n const declarator = refs[0].findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n\n if (!declarator) {\n return;\n }\n } else {\n return;\n }\n }\n\n const uid = rootScope.generateUid(name);\n // Define variable in the beginning\n const [declaration] = root.unshiftContainer('body', [\n t.variableDeclaration('var', [t.variableDeclarator(t.identifier(uid))]),\n ]);\n\n rootScope.registerDeclaration(declaration);\n\n const constantViolations: NodePath<Identifier>[] = [];\n // Replace every reference with defined variable\n refs.forEach((ref) => {\n const [replaced] = ref.replaceWith(t.identifier(uid));\n if (replaced.isBindingIdentifier()) {\n constantViolations.push(replaced);\n } else {\n reference(replaced);\n }\n });\n\n constantViolations.forEach((id) => {\n rootScope.registerConstantViolation(id);\n });\n\n const assigmentToExport = t.expressionStatement(\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('exports'), t.identifier(name)),\n t.identifier(uid)\n )\n );\n\n // export.foo = _foo will be inserted either after the last _foo assigment or in the end of the file\n const body = root.get('body');\n const lastViolation =\n constantViolations[constantViolations.length - 1] ??\n body[body.length - 1];\n const pathInRoot = root\n .get('body')\n .find((n) => lastViolation.isDescendant(n))!;\n\n const [pushed] = pathInRoot.insertAfter(assigmentToExport);\n\n const local = pushed.get('expression.right') as NodePath<Identifier>;\n reference(local);\n\n rearranged[name] = local;\n });\n\n return rearranged;\n}\n\nexport default function shakerPlugin(\n babel: Core,\n {\n keepSideEffects = false,\n ifUnknownExport = 'skip-shaking',\n onlyExports,\n }: IShakerOptions\n): PluginObj<IState & { filename: string }> {\n const shakerLogger = logger.extend('shaker');\n\n return {\n name: '@wyw-in-js/transform/shaker',\n pre(file: BabelFile) {\n this.filename = file.opts.filename!;\n const log = shakerLogger.extend(getFileIdx(this.filename));\n\n log('start', `${this.filename}, onlyExports: ${onlyExports.join(',')}`);\n const onlyExportsSet = new Set(onlyExports);\n\n const collected = collectExportsAndImports(file.path);\n const sideEffectImports = collected.imports.filter(sideEffectImport);\n log(\n 'import-and-exports',\n [\n `imports: ${collected.imports.length} (side-effects: ${sideEffectImports.length})`,\n `exports: ${Object.values(collected.exports).length}`,\n `reexports: ${collected.reexports.length}`,\n ].join(', ')\n );\n\n // We cannot just throw out exports if they are referred in the code\n // Let's dome some replacements\n const exports = rearrangeExports(\n babel,\n file.path,\n collected.exportRefs,\n collected.exports\n );\n\n Object.values(exports).forEach((local) => {\n if (local.isAssignmentExpression()) {\n const left = local.get('left');\n if (left.isIdentifier()) {\n // For some reason babel does not mark id in AssignmentExpression as a reference\n // So we need to do it manually\n reference(left, left, true);\n }\n }\n });\n\n const hasWywPreval = exports.__wywPreval !== undefined;\n const hasDefault = exports.default !== undefined;\n\n // If __wywPreval is not exported, we can remove it from onlyExports\n if (onlyExportsSet.has('__wywPreval') && !hasWywPreval) {\n onlyExportsSet.delete('__wywPreval');\n }\n\n if (onlyExportsSet.size === 0) {\n // Fast-lane: if there are no exports to keep, we can just shake out the whole file\n this.imports = [];\n this.exports = {};\n this.reexports = [];\n this.deadExports = Object.keys(exports);\n\n file.path.get('body').forEach((p) => {\n p.remove();\n });\n\n return;\n }\n\n const importedAsSideEffect = onlyExportsSet.has('side-effect');\n onlyExportsSet.delete('side-effect');\n\n // Hackaround for packages which include a 'default' export without specifying __esModule; such packages cannot be\n // shaken as they will break interopRequireDefault babel helper\n // See example in shaker-plugin.test.ts\n // Real-world example was found in preact/compat npm package\n if (\n onlyExportsSet.has('default') &&\n hasDefault &&\n !collected.isEsModule\n ) {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n return;\n }\n\n if (!onlyExportsSet.has('*')) {\n // __esModule should be kept alive\n onlyExportsSet.add('__esModule');\n\n const aliveExports = new Set<NodePath>();\n const importNames = collected.imports.map(({ imported }) => imported);\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (onlyExportsSet.has(exported)) {\n aliveExports.add(local);\n } else if (\n importNames.includes((local.node as NodeWithName).name || '')\n ) {\n aliveExports.add(local);\n } else if ([...aliveExports].some((alive) => alive === local)) {\n // It's possible to export multiple values from a single variable initializer, e.g\n // export const { foo, bar } = baz();\n // We need to treat all of them as used if any of them are used, since otherwise\n // we'll attempt to delete the baz() call\n aliveExports.add(local);\n }\n });\n\n collected.reexports.forEach((exp) => {\n if (onlyExportsSet.has(exp.exported)) {\n aliveExports.add(exp.local);\n }\n });\n\n const exportToPath = new Map<string, NodePath>();\n Object.entries(exports).forEach(([exported, local]) => {\n exportToPath.set(exported, local);\n });\n\n collected.reexports.forEach((exp) => {\n exportToPath.set(exp.exported, exp.local);\n });\n\n const notFoundExports = [...onlyExportsSet].filter(\n (exp) =>\n exp !== '__esModule' && !aliveExports.has(exportToPath.get(exp)!)\n );\n exportToPath.clear();\n\n const isAllExportsFound = notFoundExports.length === 0;\n if (!isAllExportsFound && ifUnknownExport !== 'ignore') {\n if (ifUnknownExport === 'error') {\n throw new Error(\n `Unknown export(s) requested: ${onlyExports.join(',')}`\n );\n }\n\n if (ifUnknownExport === 'reexport-all') {\n // If there are unknown exports, we have keep alive all re-exports.\n if (exports['*'] !== undefined) {\n aliveExports.add(exports['*']);\n }\n\n collected.reexports.forEach((exp) => {\n if (exp.exported === '*') {\n aliveExports.add(exp.local);\n }\n });\n }\n\n if (ifUnknownExport === 'skip-shaking') {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n\n return;\n }\n }\n\n const forDeleting = [\n ...Object.values(exports),\n ...collected.reexports.map((i) => i.local),\n ].filter((exp) => !aliveExports.has(exp));\n\n if (!keepSideEffects && !importedAsSideEffect) {\n // Remove all imports that don't import something explicitly and should not be kept\n sideEffectImports.forEach((i) => {\n if (!shouldKeepSideEffect(i.source)) {\n forDeleting.push(i.local);\n }\n });\n }\n\n const deleted = new Set<NodePath>();\n\n let dereferenced: NodePath<Identifier>[] = [];\n let changed = true;\n while (changed && deleted.size < forDeleting.length) {\n changed = false;\n // eslint-disable-next-line no-restricted-syntax\n for (const path of forDeleting) {\n if (deleted.has(path)) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const binding = getBindingForExport(path);\n const action = findActionForNode(path);\n const parent = action?.[1];\n const outerReferences = (binding?.referencePaths || []).filter(\n (ref) => ref !== parent && !parent?.isAncestor(ref)\n );\n if (outerReferences.length > 0 && path.isIdentifier()) {\n // Temporary deref it in order to simplify further checks.\n dereference(path);\n dereferenced.push(path);\n }\n\n if (\n !deleted.has(path) &&\n (!binding || outerReferences.length === 0)\n ) {\n if (action) {\n applyAction(action);\n } else {\n removeWithRelated([path]);\n }\n\n deleted.add(path);\n changed = true;\n }\n }\n\n dereferenced.forEach((path) => {\n // If path is still alive, we need to reference it back\n if (!isRemoved(path)) {\n reference(path);\n }\n });\n\n dereferenced = [];\n\n // Find and mark for deleting all unreferenced variables\n const unreferenced = Object.values(\n file.scope.getAllBindings()\n ).filter((i) => !i.referenced);\n\n for (const binding of unreferenced) {\n if (\n binding.path.isVariableDeclarator() &&\n !forDeleting.includes(binding.path.get('id'))\n ) {\n forDeleting.push(binding.path.get('id'));\n changed = true;\n }\n }\n }\n }\n\n this.imports = withoutRemoved(collected.imports);\n this.exports = {};\n this.deadExports = [];\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (isRemoved(local)) {\n this.deadExports.push(exported);\n } else {\n this.exports[exported] = local;\n }\n });\n\n this.reexports = withoutRemoved(collected.reexports);\n },\n visitor: {},\n post(file: BabelFile) {\n const log = shakerLogger.extend(getFileIdx(file.opts.filename!));\n\n const processedImports = new Set<string>();\n const imports = new Map<string, string[]>();\n const addImport = ({\n imported,\n source,\n }: {\n imported: string;\n source: string;\n }) => {\n if (processedImports.has(`${source}:${imported}`)) {\n return;\n }\n\n if (!imports.has(source)) {\n imports.set(source, []);\n }\n\n if (imported) {\n imports.get(source)!.push(imported);\n }\n\n processedImports.add(`${source}:${imported}`);\n };\n\n this.imports.forEach(addImport);\n this.reexports.forEach(addImport);\n\n log('end', `remaining imports: %O`, imports);\n\n // eslint-disable-next-line no-param-reassign\n (file.metadata as IMetadata).wywEvaluator = {\n imports,\n };\n\n invalidateTraversalCache(file.path);\n },\n };\n}\n"],"mappings":"AASA,SAASA,MAAM,QAAQ,mBAAmB;AAK1C,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,mCAAmC;AAC1C,SAASC,UAAU,QAAQ,qBAAqB;AAChD,SAASC,SAAS,QAAQ,oBAAoB;AAC9C,SACEC,WAAW,EACXC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,EACTC,iBAAiB,QACZ,uBAAuB;AAC9B,SAASC,wBAAwB,QAAQ,yBAAyB;AAElE,MAAMC,SAAS,GAAG,cAAc;AAChC,MAAMC,kBAAkB,GAAG,CAA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,EAAC,CAAC,EAAE;UACjD;QACF;QAEA,IAAI,CAACpB,OAAO,CAACQ,GAAG,CAAC2B,MAAM,CAAC,EAAE;UACxBnC,OAAO,CAAC4B,GAAG,CAACO,MAAM,EAAE,EAAE,CAAC;QACzB;QAEA,IAAIf,QAAQ,EAAE;UACZpB,OAAO,CAAClE,GAAG,CAACqG,MAAM,CAAC,CAAEnE,IAAI,CAACoD,QAAQ,CAAC;QACrC;QAEA8B,gBAAgB,CAAClC,GAAG,CAAE,GAAEmB,MAAO,IAAGf,QAAS,EAAC,CAAC;MAC/C,CAAC;MAED,IAAI,CAACpB,OAAO,CAAChD,OAAO,CAACmG,SAAS,CAAC;MAC/B,IAAI,CAAChD,SAAS,CAACnD,OAAO,CAACmG,SAAS,CAAC;MAEjC1D,GAAG,CAAC,KAAK,EAAG,uBAAsB,EAAEO,OAAO,CAAC;;MAE5C;MACCV,IAAI,CAAC8D,QAAQ,CAAeC,YAAY,GAAG;QAC1CrD;MACF,CAAC;MAEDtF,wBAAwB,CAAC4E,IAAI,CAACQ,IAAI,CAAC;IACrC;EACF,CAAC;AACH"}
1
+ {"version":3,"file":"shaker.js","names":["logger","collectExportsAndImports","sideEffectImport","getFileIdx","isRemoved","applyAction","dereference","findActionForNode","reference","removeWithRelated","invalidateTraversalCache","EXT_REGEX","ALLOWED_EXTENSIONS","shouldKeepSideEffect","importPath","ext","match","includes","getBindingForExport","exportPath","isIdentifier","scope","getBinding","node","name","variableDeclarator","findParent","p","isVariableDeclarator","id","get","isAssignmentExpression","left","isFunctionDeclaration","isClassDeclaration","undefined","withoutRemoved","items","filter","local","rearrangeExports","types","t","root","exportRefs","exports","rearranged","rootScope","forEach","refs","length","declarator","uid","generateUid","declaration","unshiftContainer","variableDeclaration","identifier","registerDeclaration","constantViolations","ref","replaced","replaceWith","isBindingIdentifier","push","registerConstantViolation","assigmentToExport","expressionStatement","assignmentExpression","memberExpression","body","lastViolation","pathInRoot","find","n","isDescendant","pushed","insertAfter","shakerPlugin","babel","keepSideEffects","ifUnknownExport","onlyExports","shakerLogger","extend","pre","file","filename","opts","log","join","onlyExportsSet","Set","collected","path","sideEffectImports","imports","Object","values","reexports","hasWywPreval","__wywPreval","hasDefault","default","has","delete","size","deadExports","keys","remove","importedAsSideEffect","isEsModule","add","aliveExports","importNames","map","imported","entries","exported","some","alive","exp","exportToPath","Map","set","notFoundExports","clear","isAllExportsFound","Error","forDeleting","i","source","deleted","dereferenced","changed","binding","action","parent","outerReferences","referencePaths","isAncestor","unreferenced","getAllBindings","referenced","visitor","post","processedImports","addImport","metadata","wywEvaluator"],"sources":["../../src/plugins/shaker.ts"],"sourcesContent":["import type { BabelFile, PluginObj, NodePath } from '@babel/core';\nimport type { Binding } from '@babel/traverse';\nimport type {\n Identifier,\n MemberExpression,\n Program,\n VariableDeclarator,\n} from '@babel/types';\n\nimport { logger } from '@wyw-in-js/shared';\n\nimport type { Core } from '../babel';\nimport type { IMetadata } from '../utils/ShakerMetadata';\nimport type { Exports, IState } from '../utils/collectExportsAndImports';\nimport {\n collectExportsAndImports,\n sideEffectImport,\n} from '../utils/collectExportsAndImports';\nimport { getFileIdx } from '../utils/getFileIdx';\nimport { isRemoved } from '../utils/isRemoved';\nimport {\n applyAction,\n dereference,\n findActionForNode,\n reference,\n removeWithRelated,\n} from '../utils/scopeHelpers';\nimport { invalidateTraversalCache } from '../utils/traversalCache';\n\nconst EXT_REGEX = /\\.[0-9a-z]+$/;\nconst ALLOWED_EXTENSIONS = ['.js', '.cjs', '.mjs'];\n\nfunction shouldKeepSideEffect(importPath: string) {\n const [ext] = importPath.match(EXT_REGEX) || [''];\n\n return ext === '' || ALLOWED_EXTENSIONS.includes(ext);\n}\n\nexport interface IShakerOptions {\n ifUnknownExport?: 'error' | 'ignore' | 'reexport-all' | 'skip-shaking';\n keepSideEffects?: boolean;\n onlyExports: string[];\n}\n\ninterface NodeWithName {\n name: string;\n}\n\nfunction getBindingForExport(exportPath: NodePath): Binding | undefined {\n if (exportPath.isIdentifier()) {\n return exportPath.scope.getBinding(exportPath.node.name);\n }\n\n const variableDeclarator = exportPath.findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n if (variableDeclarator) {\n const id = variableDeclarator.get('id');\n if (id.isIdentifier()) {\n return variableDeclarator.scope.getBinding(id.node.name);\n }\n }\n\n if (exportPath.isAssignmentExpression()) {\n const left = exportPath.get('left');\n if (left.isIdentifier()) {\n return exportPath.scope.getBinding(left.node.name);\n }\n }\n\n if (exportPath.isFunctionDeclaration() || exportPath.isClassDeclaration()) {\n return exportPath.scope.getBinding(exportPath.node.id!.name);\n }\n\n return undefined;\n}\n\nconst withoutRemoved = <T extends { local: NodePath }>(items: T[]): T[] =>\n items.filter(({ local }) => !isRemoved(local));\n\nfunction rearrangeExports(\n { types: t }: Core,\n root: NodePath<Program>,\n exportRefs: Map<string, NodePath<MemberExpression>[]>,\n exports: Exports\n): Exports {\n const rearranged = {\n ...exports,\n };\n\n const rootScope = root.scope;\n exportRefs.forEach((refs, name) => {\n if (refs.length <= 1) {\n if (refs.length === 1) {\n // Maybe exports is assigned to another variable?\n const declarator = refs[0].findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n\n if (!declarator) {\n return;\n }\n } else {\n return;\n }\n }\n\n const uid = rootScope.generateUid(name);\n // Define variable in the beginning\n const [declaration] = root.unshiftContainer('body', [\n t.variableDeclaration('var', [t.variableDeclarator(t.identifier(uid))]),\n ]);\n\n rootScope.registerDeclaration(declaration);\n\n const constantViolations: NodePath<Identifier>[] = [];\n // Replace every reference with defined variable\n refs.forEach((ref) => {\n const [replaced] = ref.replaceWith(t.identifier(uid));\n if (replaced.isBindingIdentifier()) {\n constantViolations.push(replaced);\n } else {\n reference(replaced);\n }\n });\n\n constantViolations.forEach((id) => {\n rootScope.registerConstantViolation(id);\n });\n\n const assigmentToExport = t.expressionStatement(\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('exports'), t.identifier(name)),\n t.identifier(uid)\n )\n );\n\n // export.foo = _foo will be inserted either after the last _foo assigment or in the end of the file\n const body = root.get('body');\n const lastViolation =\n constantViolations[constantViolations.length - 1] ??\n body[body.length - 1];\n const pathInRoot = root\n .get('body')\n .find((n) => lastViolation.isDescendant(n))!;\n\n const [pushed] = pathInRoot.insertAfter(assigmentToExport);\n\n const local = pushed.get('expression.right') as NodePath<Identifier>;\n reference(local);\n\n rearranged[name] = local;\n });\n\n return rearranged;\n}\n\nexport default function shakerPlugin(\n babel: Core,\n {\n keepSideEffects = false,\n ifUnknownExport = 'skip-shaking',\n onlyExports,\n }: IShakerOptions\n): PluginObj<IState & { filename: string }> {\n const shakerLogger = logger.extend('shaker');\n\n return {\n name: '@wyw-in-js/transform/shaker',\n pre(file: BabelFile) {\n this.filename = file.opts.filename!;\n const log = shakerLogger.extend(getFileIdx(this.filename));\n\n log('start', `${this.filename}, onlyExports: ${onlyExports.join(',')}`);\n const onlyExportsSet = new Set(onlyExports);\n\n const collected = collectExportsAndImports(file.path);\n const sideEffectImports = collected.imports.filter(sideEffectImport);\n log(\n 'import-and-exports',\n [\n `imports: ${collected.imports.length} (side-effects: ${sideEffectImports.length})`,\n `exports: ${Object.values(collected.exports).length}`,\n `reexports: ${collected.reexports.length}`,\n ].join(', ')\n );\n\n // We cannot just throw out exports if they are referred in the code\n // Let's dome some replacements\n const exports = rearrangeExports(\n babel,\n file.path,\n collected.exportRefs,\n collected.exports\n );\n\n Object.values(exports).forEach((local) => {\n if (local.isAssignmentExpression()) {\n const left = local.get('left');\n if (left.isIdentifier()) {\n // For some reason babel does not mark id in AssignmentExpression as a reference\n // So we need to do it manually\n reference(left, left, true);\n }\n }\n });\n\n const hasWywPreval = exports.__wywPreval !== undefined;\n const hasDefault = exports.default !== undefined;\n\n // If __wywPreval is not exported, we can remove it from onlyExports\n if (onlyExportsSet.has('__wywPreval') && !hasWywPreval) {\n onlyExportsSet.delete('__wywPreval');\n }\n\n if (onlyExportsSet.size === 0) {\n // Fast-lane: if there are no exports to keep, we can just shake out the whole file\n this.imports = [];\n this.exports = {};\n this.reexports = [];\n this.deadExports = Object.keys(exports);\n\n file.path.get('body').forEach((p) => {\n p.remove();\n });\n\n return;\n }\n\n const importedAsSideEffect = onlyExportsSet.has('side-effect');\n onlyExportsSet.delete('side-effect');\n\n // Hackaround for packages which include a 'default' export without specifying __esModule; such packages cannot be\n // shaken as they will break interopRequireDefault babel helper\n // See example in shaker-plugin.test.ts\n // Real-world example was found in preact/compat npm package\n if (\n onlyExportsSet.has('default') &&\n hasDefault &&\n !collected.isEsModule\n ) {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n return;\n }\n\n if (!onlyExportsSet.has('*')) {\n // __esModule should be kept alive\n onlyExportsSet.add('__esModule');\n\n const aliveExports = new Set<NodePath>();\n const importNames = collected.imports.map(({ imported }) => imported);\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (onlyExportsSet.has(exported)) {\n aliveExports.add(local);\n } else if (\n importNames.includes((local.node as NodeWithName).name || '')\n ) {\n aliveExports.add(local);\n } else if ([...aliveExports].some((alive) => alive === local)) {\n // It's possible to export multiple values from a single variable initializer, e.g\n // export const { foo, bar } = baz();\n // We need to treat all of them as used if any of them are used, since otherwise\n // we'll attempt to delete the baz() call\n aliveExports.add(local);\n }\n });\n\n collected.reexports.forEach((exp) => {\n if (onlyExportsSet.has(exp.exported)) {\n aliveExports.add(exp.local);\n }\n });\n\n const exportToPath = new Map<string, NodePath>();\n Object.entries(exports).forEach(([exported, local]) => {\n exportToPath.set(exported, local);\n });\n\n collected.reexports.forEach((exp) => {\n exportToPath.set(exp.exported, exp.local);\n });\n\n const notFoundExports = [...onlyExportsSet].filter(\n (exp) =>\n exp !== '__esModule' && !aliveExports.has(exportToPath.get(exp)!)\n );\n exportToPath.clear();\n\n const isAllExportsFound = notFoundExports.length === 0;\n if (!isAllExportsFound && ifUnknownExport !== 'ignore') {\n if (ifUnknownExport === 'error') {\n throw new Error(\n `Unknown export(s) requested: ${onlyExports.join(',')}`\n );\n }\n\n if (ifUnknownExport === 'reexport-all') {\n // If there are unknown exports, we have keep alive all re-exports.\n if (exports['*'] !== undefined) {\n aliveExports.add(exports['*']);\n }\n\n collected.reexports.forEach((exp) => {\n if (exp.exported === '*') {\n aliveExports.add(exp.local);\n }\n });\n }\n\n if (ifUnknownExport === 'skip-shaking') {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n\n return;\n }\n }\n\n const forDeleting = [\n ...Object.values(exports),\n ...collected.reexports.map((i) => i.local),\n ].filter((exp) => !aliveExports.has(exp));\n\n if (!keepSideEffects && !importedAsSideEffect) {\n // Remove all imports that don't import something explicitly and should not be kept\n sideEffectImports.forEach((i) => {\n if (!shouldKeepSideEffect(i.source)) {\n forDeleting.push(i.local);\n }\n });\n }\n\n const deleted = new Set<NodePath>();\n\n let dereferenced: NodePath<Identifier>[] = [];\n let changed = true;\n while (changed && deleted.size < forDeleting.length) {\n changed = false;\n // eslint-disable-next-line no-restricted-syntax\n for (const path of forDeleting) {\n if (deleted.has(path)) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const binding = getBindingForExport(path);\n const action = findActionForNode(path);\n const parent = action?.[1];\n const outerReferences = (binding?.referencePaths || []).filter(\n (ref) => ref !== parent && !parent?.isAncestor(ref)\n );\n if (outerReferences.length > 0 && path.isIdentifier()) {\n // Temporary deref it in order to simplify further checks.\n dereference(path);\n dereferenced.push(path);\n }\n\n if (\n !deleted.has(path) &&\n (!binding || outerReferences.length === 0)\n ) {\n if (action) {\n applyAction(action);\n } else {\n removeWithRelated([path]);\n }\n\n deleted.add(path);\n changed = true;\n }\n }\n\n dereferenced.forEach((path) => {\n // If path is still alive, we need to reference it back\n if (!isRemoved(path)) {\n reference(path);\n }\n });\n\n dereferenced = [];\n\n // Find and mark for deleting all unreferenced variables\n const unreferenced = Object.values(\n file.scope.getAllBindings()\n ).filter((i) => !i.referenced);\n\n for (const binding of unreferenced) {\n if (\n binding.path.isVariableDeclarator() &&\n !forDeleting.includes(binding.path.get('id'))\n ) {\n forDeleting.push(...binding.constantViolations);\n forDeleting.push(binding.path.get('id'));\n changed = true;\n }\n }\n }\n }\n\n this.imports = withoutRemoved(collected.imports);\n this.exports = {};\n this.deadExports = [];\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (isRemoved(local)) {\n this.deadExports.push(exported);\n } else {\n this.exports[exported] = local;\n }\n });\n\n this.reexports = withoutRemoved(collected.reexports);\n },\n visitor: {},\n post(file: BabelFile) {\n const log = shakerLogger.extend(getFileIdx(file.opts.filename!));\n\n const processedImports = new Set<string>();\n const imports = new Map<string, string[]>();\n const addImport = ({\n imported,\n source,\n }: {\n imported: string;\n source: string;\n }) => {\n if (processedImports.has(`${source}:${imported}`)) {\n return;\n }\n\n if (!imports.has(source)) {\n imports.set(source, []);\n }\n\n if (imported) {\n imports.get(source)!.push(imported);\n }\n\n processedImports.add(`${source}:${imported}`);\n };\n\n this.imports.forEach(addImport);\n this.reexports.forEach(addImport);\n\n log('end', `remaining imports: %O`, imports);\n\n // eslint-disable-next-line no-param-reassign\n (file.metadata as IMetadata).wywEvaluator = {\n imports,\n };\n\n invalidateTraversalCache(file.path);\n },\n };\n}\n"],"mappings":"AASA,SAASA,MAAM,QAAQ,mBAAmB;AAK1C,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,mCAAmC;AAC1C,SAASC,UAAU,QAAQ,qBAAqB;AAChD,SAASC,SAAS,QAAQ,oBAAoB;AAC9C,SACEC,WAAW,EACXC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,EACTC,iBAAiB,QACZ,uBAAuB;AAC9B,SAASC,wBAAwB,QAAQ,yBAAyB;AAElE,MAAMC,SAAS,GAAG,cAAc;AAChC,MAAMC,kBAAkB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAElD,SAASC,oBAAoBA,CAACC,UAAkB,EAAE;EAChD,MAA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E;UACjD;QACF;QAEA,IAAI,CAACpB,OAAO,CAACQ,GAAG,CAAC2B,MAAM,CAAC,EAAE;UACxBnC,OAAO,CAAC4B,GAAG,CAACO,MAAM,EAAE,EAAE,CAAC;QACzB;QAEA,IAAIf,QAAQ,EAAE;UACZpB,OAAO,CAAClE,GAAG,CAACqG,MAAM,CAAC,CAAEnE,IAAI,CAACoD,QAAQ,CAAC;QACrC;QAEA8B,gBAAgB,CAAClC,GAAG,CAAE,GAAEmB,MAAO,IAAGf,QAAS,EAAC,CAAC;MAC/C,CAAC;MAED,IAAI,CAACpB,OAAO,CAAChD,OAAO,CAACmG,SAAS,CAAC;MAC/B,IAAI,CAAChD,SAAS,CAACnD,OAAO,CAACmG,SAAS,CAAC;MAEjC1D,GAAG,CAAC,KAAK,EAAG,uBAAsB,EAAEO,OAAO,CAAC;;MAE5C;MACCV,IAAI,CAAC8D,QAAQ,CAAeC,YAAY,GAAG;QAC1CrD;MACF,CAAC;MAEDtF,wBAAwB,CAAC4E,IAAI,CAACQ,IAAI,CAAC;IACrC;EACF,CAAC;AACH"}
@@ -0,0 +1,99 @@
1
+ import * as path from 'path';
2
+ import { compile, middleware, prefixer, serialize, stringify, tokenize, RULESET } from 'stylis';
3
+ const POSIX_SEP = path.posix.sep;
4
+ export function transformUrl(url, outputFilename, sourceFilename, platformPath = path) {
5
+ // Replace asset path with new path relative to the output CSS
6
+ const relative = platformPath.relative(platformPath.dirname(outputFilename),
7
+ // Get the absolute path to the asset from the path relative to the JS file
8
+ platformPath.resolve(platformPath.dirname(sourceFilename), url));
9
+ if (platformPath.sep === POSIX_SEP) {
10
+ return relative;
11
+ }
12
+ return relative.split(platformPath.sep).join(POSIX_SEP);
13
+ }
14
+
15
+ /**
16
+ * Stylis plugin that mimics :global() selector behavior from Stylis v3.
17
+ */
18
+ export const stylisGlobalPlugin = element => {
19
+ function getGlobalSelectorModifiers(value) {
20
+ const match = value.match(/(&\f( )?)?:global\(/);
21
+ if (match === null) {
22
+ throw new Error(`Failed to match :global() selector in "${value}". Please report a bug if it happens.`);
23
+ }
24
+ const [, baseSelector, spaceDelimiter] = match;
25
+ return {
26
+ includeBaseSelector: !!baseSelector,
27
+ includeSpaceDelimiter: !!spaceDelimiter
28
+ };
29
+ }
30
+ switch (element.type) {
31
+ case RULESET:
32
+ if (typeof element.props === 'string') {
33
+ if (process.env.NODE_ENV !== 'production') {
34
+ throw new Error(`"element.props" has type "string" (${JSON.stringify(element.props, null, 2)}), it's not expected. Please report a bug if it happens.`);
35
+ }
36
+ return;
37
+ }
38
+ Object.assign(element, {
39
+ props: element.props.map(cssSelector => {
40
+ // Avoids calling tokenize() on every string
41
+ if (!cssSelector.includes(':global(')) {
42
+ return cssSelector;
43
+ }
44
+ if (element.children.length === 0) {
45
+ Object.assign(element, {
46
+ global: getGlobalSelectorModifiers(element.value)
47
+ });
48
+ return cssSelector;
49
+ }
50
+ const {
51
+ includeBaseSelector,
52
+ includeSpaceDelimiter
53
+ } = element.parent?.global || getGlobalSelectorModifiers(element.value);
54
+ const tokens = tokenize(cssSelector);
55
+ let selector = '';
56
+ for (let i = 0, len = tokens.length; i < len; i++) {
57
+ const token = tokens[i];
58
+
59
+ //
60
+ // Match for ":global("
61
+ if (token === ':' && tokens[i + 1] === 'global') {
62
+ //
63
+ // Match for ":global()"
64
+ if (tokens[i + 2] === '()') {
65
+ selector = [...tokens.slice(i + 4), includeSpaceDelimiter ? ' ' : '', ...(includeBaseSelector ? tokens.slice(0, i - 1) : []), includeSpaceDelimiter ? '' : ' '].join('');
66
+ break;
67
+ }
68
+
69
+ //
70
+ // Match for ":global(selector)"
71
+ selector = [tokens[i + 2].slice(1, -1), includeSpaceDelimiter ? ' ' : '', ...(includeBaseSelector ? tokens.slice(0, i - 1) : []), includeSpaceDelimiter ? '' : ' '].join('');
72
+ break;
73
+ }
74
+ }
75
+ return selector;
76
+ })
77
+ });
78
+ break;
79
+ default:
80
+ }
81
+ };
82
+ export function createStylisUrlReplacePlugin(filename, outputFilename) {
83
+ return element => {
84
+ if (element.type === 'decl' && outputFilename) {
85
+ // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
86
+ // It'll allow css-loader to resolve an imported asset properly.
87
+ // eslint-disable-next-line no-param-reassign
88
+ element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, filename) + p4);
89
+ }
90
+ };
91
+ }
92
+ export function createStylisPreprocessor(options) {
93
+ function stylisPreprocess(selector, text) {
94
+ const compiled = compile(`${selector} {${text}}\n`);
95
+ return serialize(compiled, middleware([createStylisUrlReplacePlugin(options.filename, options.outputFilename), stylisGlobalPlugin, prefixer, stringify]));
96
+ }
97
+ return stylisPreprocess;
98
+ }
99
+ //# sourceMappingURL=createStylisPreprocessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createStylisPreprocessor.js","names":["path","compile","middleware","prefixer","serialize","stringify","tokenize","RULESET","POSIX_SEP","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","stylisGlobalPlugin","element","getGlobalSelectorModifiers","value","match","Error","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","type","props","process","env","NODE_ENV","JSON","Object","assign","map","cssSelector","includes","children","length","global","parent","tokens","selector","i","len","token","slice","createStylisUrlReplacePlugin","filename","return","replace","p1","p2","p3","p4","createStylisPreprocessor","options","stylisPreprocess","text","compiled"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n} from 'stylis';\nimport type { Middleware } 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\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(value: string) {\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 switch (element.type) {\n case RULESET:\n if (typeof element.props === 'string') {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.props\" has type \"string\" (${JSON.stringify(\n element.props,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n Object.assign(element, {\n global: getGlobalSelectorModifiers(element.value),\n });\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n (\n element.parent as unknown as\n | (Element & {\n global: ReturnType<typeof getGlobalSelectorModifiers>;\n })\n | undefined\n )?.global || getGlobalSelectorModifiers(element.value);\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 break;\n\n default:\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 createStylisPreprocessor(options: Options) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware([\n createStylisUrlReplacePlugin(options.filename, options.outputFilename),\n stylisGlobalPlugin,\n prefixer,\n stringify,\n ])\n );\n }\n\n return stylisPreprocess;\n}\n"],"mappings":"AAAA,OAAO,KAAKA,IAAI,MAAM,MAAM;AAC5B,SACEC,OAAO,EACPC,UAAU,EACVC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,OAAO,QACF,QAAQ;AAKf,MAAMC,SAAS,GAAGR,IAAI,CAACS,KAAK,CAACC,GAAG;AAEhC,OAAO,SAASC,YAAYA,CAC1BC,GAAW,EACXC,cAAsB,EACtBC,cAAsB,EACtBC,YAAyB,GAAGf,IAAI,EAChC;EACA;EACA,MAAMgB,QAAQ,GAAGD,YAAY,CAACC,QAAQ,CACpCD,YAAY,CAACE,OAAO,CAACJ,cAAc,CAAC;EACpC;EACAE,YAAY,CAACG,OAAO,CAACH,YAAY,CAACE,OAAO,CAACH,cAAc,CAAC,EAAE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,CAACK,KAAK,CAAC,CAAC,EAAEH,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EACtDlB,qBAAqB,GAAG,EAAE,GAAG,GAAG,CACjC,CAACV,IAAI,CAAC,EAAE,CAAC;cAEV;YACF;UACF;UAEA,OAAO2B,QAAQ;QACjB,CAAC;MACH,CAAC,CAAC;MAEF;IAEF;EACF;AACF,CAAC;AAED,OAAO,SAASK,4BAA4BA,CAC1CC,QAAgB,EAChBxC,cAAkC,EACtB;EACZ,OAAQS,OAAO,IAAK;IAClB,IAAIA,OAAO,CAACS,IAAI,KAAK,MAAM,IAAIlB,cAAc,EAAE;MAC7C;MACA;MACA;MACAS,OAAO,CAACgC,MAAM,GAAGhC,OAAO,CAACE,KAAK,CAAC+B,OAAO,CACpC,mCAAmC,EACnC,CAAC9B,KAAK,EAAE+B,EAAE,EAAEC,EAAE,EAAEC,EAAE,EAAEC,EAAE,KACpBH,EAAE,GAAG7C,YAAY,CAAC+C,EAAE,EAAE7C,cAAc,EAAEwC,QAAQ,CAAC,GAAGM,EACtD,CAAC;IACH;EACF,CAAC;AACH;AAEA,OAAO,SAASC,wBAAwBA,CAACC,OAAgB,EAAE;EACzD,SAASC,gBAAgBA,CAACf,QAAgB,EAAEgB,IAAY,EAAU;IAChE,MAAMC,QAAQ,GAAG/D,OAAO,CAAE,GAAE8C,QAAS,KAAIgB,IAAK,KAAI,CAAC;IAEnD,OAAO3D,SAAS,CACd4D,QAAQ,EACR9D,UAAU,CAAC,CACTkD,4BAA4B,CAACS,OAAO,CAACR,QAAQ,EAAEQ,OAAO,CAAChD,cAAc,CAAC,EACtEQ,kBAAkB,EAClBlB,QAAQ,EACRE,SAAS,CACV,CACH,CAAC;EACH;EAEA,OAAOyD,gBAAgB;AACzB"}
@@ -1,34 +1,5 @@
1
- import path from 'path';
2
1
  import { SourceMapGenerator } from 'source-map';
3
- import { compile, serialize, stringify, middleware, prefixer } from 'stylis';
4
- const posixSep = path.posix.sep;
5
- export function transformUrl(url, outputFilename, sourceFilename, platformPath = path) {
6
- // Replace asset path with new path relative to the output CSS
7
- const relative = platformPath.relative(platformPath.dirname(outputFilename),
8
- // Get the absolute path to the asset from the path relative to the JS file
9
- platformPath.resolve(platformPath.dirname(sourceFilename), url));
10
- if (platformPath.sep === posixSep) {
11
- return relative;
12
- }
13
- return relative.split(platformPath.sep).join(posixSep);
14
- }
15
- function createStylisPreprocessor(options) {
16
- function stylisPreprocess(selector, text) {
17
- const compiled = compile(`${selector} {${text}}\n`);
18
- return serialize(compiled, middleware([element => {
19
- const {
20
- outputFilename
21
- } = options;
22
- if (element.type === 'decl' && outputFilename) {
23
- // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
24
- // It'll allow css-loader to resolve an imported asset properly.
25
- // eslint-disable-next-line no-param-reassign
26
- element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, options.filename) + p4);
27
- }
28
- }, prefixer, stringify]));
29
- }
30
- return stylisPreprocess;
31
- }
2
+ import { createStylisPreprocessor } from './createStylisPreprocessor';
32
3
  function extractCssFromAst(rules, originalCode, options) {
33
4
  const mappings = [];
34
5
  let cssText = '';
@@ -1 +1 @@
1
- {"version":3,"file":"extract.js","names":["path","SourceMapGenerator","compile","serialize","stringify","middleware","prefixer","posixSep","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","createStylisPreprocessor","options","stylisPreprocess","selector","text","compiled","element","type","return","value","replace","match","p1","p2","p3","p4","filename","extractCssFromAst","rules","originalCode","mappings","cssText","preprocessor","Object","keys","forEach","index","push","generated","line","column","original","start","name","source","atom","cssSourceMapText","length","generator","file","mapping","addMapping","setSourceContent","toString","extract","services","entrypoint","processors","data","loadedAndParsed","evaluator","Error","allRules","allReplacements","processor","artifacts","artifact","replacements","code"],"sources":["../../../src/transform/generators/extract.ts"],"sourcesContent":["import path from 'path';\n\nimport type { Mapping } from 'source-map';\nimport { SourceMapGenerator } from 'source-map';\nimport { compile, serialize, stringify, middleware, prefixer } from 'stylis';\n\nimport type { Replacements, Rules } from '@wyw-in-js/shared';\n\nimport type { Options, PreprocessorFn } from '../../types';\nimport type { IExtractAction, SyncScenarioForAction } from '../types';\n\nconst posixSep = 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 === posixSep) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(posixSep);\n}\n\nfunction createStylisPreprocessor(options: Options) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n return serialize(\n compiled,\n middleware([\n (element: { return: string; type: string; value: string }) => {\n const { outputFilename } = options;\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, options.filename) + p4\n );\n }\n },\n prefixer,\n stringify,\n ])\n );\n }\n return stylisPreprocess;\n}\n\nfunction extractCssFromAst(\n rules: Rules,\n originalCode: string,\n options: Pick<Options, 'preprocessor' | 'filename' | 'outputFilename'>\n): { cssSourceMapText: string; cssText: string; rules: Rules } {\n const mappings: Mapping[] = [];\n\n let cssText = '';\n\n let preprocessor: PreprocessorFn;\n if (typeof options.preprocessor === 'function') {\n // eslint-disable-next-line prefer-destructuring\n preprocessor = options.preprocessor;\n } else {\n switch (options.preprocessor) {\n case 'none':\n preprocessor = (selector, text) => `${selector} {${text}}\\n`;\n break;\n case 'stylis':\n default:\n preprocessor = createStylisPreprocessor(options);\n }\n }\n\n Object.keys(rules).forEach((selector, index) => {\n mappings.push({\n generated: {\n line: index + 1,\n column: 0,\n },\n original: rules[selector].start!,\n name: selector,\n source: '',\n });\n\n if (rules[selector].atom) {\n // For atoms, we just directly insert cssText, to give the atomizer full control over the rules\n cssText += `${rules[selector].cssText}\\n`;\n } else {\n // Run each rule through stylis to support nesting\n cssText += `${preprocessor(selector, rules[selector].cssText)}\\n`;\n }\n });\n\n return {\n cssText,\n rules,\n\n get cssSourceMapText() {\n if (mappings?.length) {\n const generator = new SourceMapGenerator({\n file: options.filename.replace(/\\.js$/, '.css'),\n });\n\n mappings.forEach((mapping) =>\n generator.addMapping({ ...mapping, source: options.filename })\n );\n\n generator.setSourceContent(options.filename, originalCode);\n\n return generator.toString();\n }\n\n return '';\n },\n };\n}\n\n/**\n * Extract artifacts (e.g. CSS) from processors\n */\n// eslint-disable-next-line require-yield\nexport function* extract(\n this: IExtractAction\n): SyncScenarioForAction<IExtractAction> {\n const { options } = this.services;\n const { entrypoint } = this;\n const { processors } = this.data;\n const { loadedAndParsed } = entrypoint;\n if (loadedAndParsed.evaluator === 'ignored') {\n throw new Error('entrypoint was ignored');\n }\n\n let allRules: Rules = {};\n const allReplacements: Replacements = [];\n processors.forEach((processor) => {\n processor.artifacts.forEach((artifact) => {\n if (artifact[0] !== 'css') return;\n const [rules, replacements] = artifact[1] as [\n rules: Rules,\n sourceMapReplacements: Replacements,\n ];\n\n allRules = {\n ...allRules,\n ...rules,\n };\n\n allReplacements.push(...replacements);\n });\n });\n\n return {\n ...extractCssFromAst(allRules, loadedAndParsed.code, options),\n replacements: allReplacements,\n };\n}\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM;AAGvB,SAASC,kBAAkB,QAAQ,YAAY;AAC/C,SAASC,OAAO,EAAEC,SAAS,EAAEC,SAAS,EAAEC,UAAU,EAAEC,QAAQ,QAAQ,QAAQ;AAO5E,MAAMC,QAAQ,GAAGP,IAAI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AC1B,IAAI,CAAC,GAAG8B,YAAY,CAAC;IACvC,CAAC,CAAC;EACJ,CAAC,CAAC;EAEF,OAAO;IACL,GAAGxC,iBAAiB,CAACmC,QAAQ,EAAEH,eAAe,CAACS,IAAI,EAAEzD,OAAO,CAAC;IAC7DwD,YAAY,EAAEJ;EAChB,CAAC;AACH"}
1
+ {"version":3,"file":"extract.js","names":["SourceMapGenerator","createStylisPreprocessor","extractCssFromAst","rules","originalCode","options","mappings","cssText","preprocessor","selector","text","Object","keys","forEach","index","push","generated","line","column","original","start","name","source","atom","cssSourceMapText","length","generator","file","filename","replace","mapping","addMapping","setSourceContent","toString","extract","services","entrypoint","processors","data","loadedAndParsed","evaluator","Error","allRules","allReplacements","processor","artifacts","artifact","replacements","code"],"sources":["../../../src/transform/generators/extract.ts"],"sourcesContent":["import type { Mapping } from 'source-map';\nimport { SourceMapGenerator } from 'source-map';\n\nimport type { Replacements, Rules } from '@wyw-in-js/shared';\n\nimport type { Options, PreprocessorFn } from '../../types';\nimport type { IExtractAction, SyncScenarioForAction } from '../types';\nimport { createStylisPreprocessor } from './createStylisPreprocessor';\n\nfunction extractCssFromAst(\n rules: Rules,\n originalCode: string,\n options: Pick<Options, 'preprocessor' | 'filename' | 'outputFilename'>\n): { cssSourceMapText: string; cssText: string; rules: Rules } {\n const mappings: Mapping[] = [];\n\n let cssText = '';\n\n let preprocessor: PreprocessorFn;\n if (typeof options.preprocessor === 'function') {\n // eslint-disable-next-line prefer-destructuring\n preprocessor = options.preprocessor;\n } else {\n switch (options.preprocessor) {\n case 'none':\n preprocessor = (selector, text) => `${selector} {${text}}\\n`;\n break;\n case 'stylis':\n default:\n preprocessor = createStylisPreprocessor(options);\n }\n }\n\n Object.keys(rules).forEach((selector, index) => {\n mappings.push({\n generated: {\n line: index + 1,\n column: 0,\n },\n original: rules[selector].start!,\n name: selector,\n source: '',\n });\n\n if (rules[selector].atom) {\n // For atoms, we just directly insert cssText, to give the atomizer full control over the rules\n cssText += `${rules[selector].cssText}\\n`;\n } else {\n // Run each rule through stylis to support nesting\n cssText += `${preprocessor(selector, rules[selector].cssText)}\\n`;\n }\n });\n\n return {\n cssText,\n rules,\n\n get cssSourceMapText() {\n if (mappings?.length) {\n const generator = new SourceMapGenerator({\n file: options.filename.replace(/\\.js$/, '.css'),\n });\n\n mappings.forEach((mapping) =>\n generator.addMapping({ ...mapping, source: options.filename })\n );\n\n generator.setSourceContent(options.filename, originalCode);\n\n return generator.toString();\n }\n\n return '';\n },\n };\n}\n\n/**\n * Extract artifacts (e.g. CSS) from processors\n */\n// eslint-disable-next-line require-yield\nexport function* extract(\n this: IExtractAction\n): SyncScenarioForAction<IExtractAction> {\n const { options } = this.services;\n const { entrypoint } = this;\n const { processors } = this.data;\n const { loadedAndParsed } = entrypoint;\n if (loadedAndParsed.evaluator === 'ignored') {\n throw new Error('entrypoint was ignored');\n }\n\n let allRules: Rules = {};\n const allReplacements: Replacements = [];\n processors.forEach((processor) => {\n processor.artifacts.forEach((artifact) => {\n if (artifact[0] !== 'css') return;\n const [rules, replacements] = artifact[1] as [\n rules: Rules,\n sourceMapReplacements: Replacements,\n ];\n\n allRules = {\n ...allRules,\n ...rules,\n };\n\n allReplacements.push(...replacements);\n });\n });\n\n return {\n ...extractCssFromAst(allRules, loadedAndParsed.code, options),\n replacements: allReplacements,\n };\n}\n"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,YAAY;AAM/C,SAASC,wBAAwB,QAAQ,4BAA4B;AAErE,SAASC,iBAAiBA,CACxBC,KAAY,EACZC,YAAoB,EACpBC,OAAsE,EACT;EAC7D,MAAMC,QAAmB,GAAG,EAAE;EAE9B,IAAIC,OAAO,GAAG,EAAE;EAEhB,IAAIC,YAA4B;EAChC,IAAI,OAAOH,OAAO,CAACG,YAAY,KAAK,UAAU,EAAE;IAC9C;IACAA,YAAY,GAAGH,OAAO,CAACG,YAAY;EACrC,CAAC,MAAM;IACL,QAAQH,OAAO,CAACG,YAAY;MAC1B,KAAK,MAAM;Q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3B,OAAO,CAACuB,QAAQ,EAAExB,YAAY,CAAC;QAE1D,OAAOsB,SAAS,CAACO,QAAQ,CAAC,CAAC;MAC7B;MAEA,OAAO,EAAE;IACX;EACF,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA,OAAO,UAAUC,OAAOA,CAAA,EAEiB;EACvC,MAAM;IAAE7B;EAAQ,CAAC,GAAG,IAAI,CAAC8B,QAAQ;EACjC,MAAM;IAAEC;EAAW,CAAC,GAAG,IAAI;EAC3B,MAAM;IAAEC;EAAW,CAAC,GAAG,IAAI,CAACC,IAAI;EAChC,MAAM;IAAEC;EAAgB,CAAC,GAAGH,UAAU;EACtC,IAAIG,eAAe,CAACC,SAAS,KAAK,SAAS,EAAE;IAC3C,MAAM,IAAIC,KAAK,CAAC,wBAAwB,CAAC;EAC3C;EAEA,IAAIC,QAAe,GAAG,CAAC,CAAC;EACxB,MAAMC,eAA6B,GAAG,EAAE;EACxCN,UAAU,CAACxB,OAAO,CAAE+B,SAAS,IAAK;IAChCA,SAAS,CAACC,SAAS,CAAChC,OAAO,CAAEiC,QAAQ,IAAK;MACxC,IAAIA,QAAQ,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE;MAC3B,MAAM,CAAC3C,KAAK,EAAE4C,YAAY,CAAC,GAAGD,QAAQ,CAAC,CAAC,CAGvC;MAEDJ,QAAQ,GAAG;QACT,GAAGA,QAAQ;QACX,GAAGvC;MACL,CAAC;MAEDwC,eAAe,CAAC5B,IAAI,CAAC,GAAGgC,YAAY,CAAC;IACvC,CAAC,CAAC;EACJ,CAAC,CAAC;EAEF,OAAO;IACL,GAAG7C,iBAAiB,CAACwC,QAAQ,EAAEH,eAAe,CAACS,IAAI,EAAE3C,OAAO,CAAC;IAC7D0C,YAAY,EAAEJ;EAChB,CAAC;AACH"}
package/lib/index.js CHANGED
@@ -200,7 +200,7 @@ Object.defineProperty(exports, "transform", {
200
200
  Object.defineProperty(exports, "transformUrl", {
201
201
  enumerable: true,
202
202
  get: function () {
203
- return _extract.transformUrl;
203
+ return _createStylisPreprocessor.transformUrl;
204
204
  }
205
205
  });
206
206
  Object.defineProperty(exports, "withDefaultServices", {
@@ -241,7 +241,7 @@ var _Entrypoint = require("./transform/Entrypoint.helpers");
241
241
  var _generators = require("./transform/generators");
242
242
  var _transform2 = require("./transform/generators/transform");
243
243
  var _Entrypoint2 = require("./transform/Entrypoint");
244
- var _extract = require("./transform/generators/extract");
244
+ var _createStylisPreprocessor = require("./transform/generators/createStylisPreprocessor");
245
245
  var _resolveImports = require("./transform/generators/resolveImports");
246
246
  var _loadWywOptions = require("./transform/helpers/loadWywOptions");
247
247
  var _withDefaultServices = require("./transform/helpers/withDefaultServices");
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_shared","require","_fileReporter","_babelTransform","_interopRequireDefault","_preeval","_TransformMetadata","_module","_shaker","_transform","_UnprocessedEntrypointError","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_EvaluatedEntrypoint","_Entrypoint","_generators","_transform2","_Entrypoint2","_extract","_resolveImports","_loadWywOptions","_withDefaultServices","_EventEmitter","_isNode","_getFileIdx","_getTagProcessor","_getVisitorKeys","_peek","_processTemplateExpression","_cache","obj","__esModule","default"],"sources":["../src/index.ts"],"sourcesContent":["export { slugify } from '@wyw-in-js/shared';\n\nexport { createFileReporter } from './debug/fileReporter';\nexport type { IFileReporterOptions } from './debug/fileReporter';\nexport { default as babelTransformPlugin } from './plugins/babel-transform';\nexport { default as preeval } from './plugins/preeval';\nexport {\n getTransformMetadata,\n withTransformMetadata,\n} from './utils/TransformMetadata';\nexport type { WYWTransformMetadata } from './utils/TransformMetadata';\nexport { Module, DefaultModuleImplementation } from './module';\nexport { default as shaker } from './shaker';\nexport { transform } from './transform';\nexport {\n isUnprocessedEntrypointError,\n UnprocessedEntrypointError,\n} from './transform/actions/UnprocessedEntrypointError';\nexport * from './types';\nexport { EvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport { parseFile } from './transform/Entrypoint.helpers';\nexport type { LoadAndParseFn } from './transform/Entrypoint.types';\nexport { baseHandlers } from './transform/generators';\nexport { prepareCode } from './transform/generators/transform';\nexport { Entrypoint } from './transform/Entrypoint';\nexport { transformUrl } from './transform/generators/extract';\nexport {\n asyncResolveImports,\n syncResolveImports,\n} from './transform/generators/resolveImports';\nexport { loadWywOptions } from './transform/helpers/loadWywOptions';\nexport { withDefaultServices } from './transform/helpers/withDefaultServices';\nexport type { Services } from './transform/types';\nexport { EventEmitter } from './utils/EventEmitter';\nexport type {\n EntrypointEvent,\n OnEvent,\n OnActionStartArgs,\n OnActionFinishArgs,\n} from './utils/EventEmitter';\nexport { isNode } from './utils/isNode';\nexport { getFileIdx } from './utils/getFileIdx';\nexport { getTagProcessor } from './utils/getTagProcessor';\nexport { getVisitorKeys } from './utils/getVisitorKeys';\nexport type { VisitorKeys } from './utils/getVisitorKeys';\nexport { peek } from './utils/peek';\nexport { processTemplateExpression } from './utils/processTemplateExpression';\nexport { TransformCacheCollection } from './cache';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,aAAA,GAAAD,OAAA;AAEA,IAAAE,eAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,QAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAKA,IAAAM,OAAA,GAAAN,OAAA;AACA,IAAAO,OAAA,GAA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
1
+ {"version":3,"file":"index.js","names":["_shared","require","_fileReporter","_babelTransform","_interopRequireDefault","_preeval","_TransformMetadata","_module","_shaker","_transform","_UnprocessedEntrypointError","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_EvaluatedEntrypoint","_Entrypoint","_generators","_transform2","_Entrypoint2","_createStylisPreprocessor","_resolveImports","_loadWywOptions","_withDefaultServices","_EventEmitter","_isNode","_getFileIdx","_getTagProcessor","_getVisitorKeys","_peek","_processTemplateExpression","_cache","obj","__esModule","default"],"sources":["../src/index.ts"],"sourcesContent":["export { slugify } from '@wyw-in-js/shared';\n\nexport { createFileReporter } from './debug/fileReporter';\nexport type { IFileReporterOptions } from './debug/fileReporter';\nexport { default as babelTransformPlugin } from './plugins/babel-transform';\nexport { default as preeval } from './plugins/preeval';\nexport {\n getTransformMetadata,\n withTransformMetadata,\n} from './utils/TransformMetadata';\nexport type { WYWTransformMetadata } from './utils/TransformMetadata';\nexport { Module, DefaultModuleImplementation } from './module';\nexport { default as shaker } from './shaker';\nexport { transform } from './transform';\nexport {\n isUnprocessedEntrypointError,\n UnprocessedEntrypointError,\n} from './transform/actions/UnprocessedEntrypointError';\nexport * from './types';\nexport { EvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport { parseFile } from './transform/Entrypoint.helpers';\nexport type { LoadAndParseFn } from './transform/Entrypoint.types';\nexport { baseHandlers } from './transform/generators';\nexport { prepareCode } from './transform/generators/transform';\nexport { Entrypoint } from './transform/Entrypoint';\nexport { transformUrl } from './transform/generators/createStylisPreprocessor';\nexport {\n asyncResolveImports,\n syncResolveImports,\n} from './transform/generators/resolveImports';\nexport { loadWywOptions } from './transform/helpers/loadWywOptions';\nexport { withDefaultServices } from './transform/helpers/withDefaultServices';\nexport type { Services } from './transform/types';\nexport { EventEmitter } from './utils/EventEmitter';\nexport type {\n EntrypointEvent,\n OnEvent,\n OnActionStartArgs,\n OnActionFinishArgs,\n} from './utils/EventEmitter';\nexport { isNode } from './utils/isNode';\nexport { getFileIdx } from './utils/getFileIdx';\nexport { getTagProcessor } from './utils/getTagProcessor';\nexport { getVisitorKeys } from './utils/getVisitorKeys';\nexport type { VisitorKeys } from './utils/getVisitorKeys';\nexport { peek } from './utils/peek';\nexport { processTemplateExpression } from './utils/processTemplateExpression';\nexport { TransformCacheCollection } from './cache';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,aAAA,GAAAD,OAAA;AAEA,IAAAE,eAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,QAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAKA,IAAAM,OAAA,GAAAN,OAAA;AACA,IAAAO,OAAA,GAAAJ,sBAAA,CAAAH,OAAA;AACA,IAAAQ,UAAA,GAAAR,OAAA;AACA,IAAAS,2BAAA,GAAAT,OAAA;AAIA,IAAAU,MAAA,GAAAV,OAAA;AAAAW,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,oBAAA,GAAAvB,OAAA;AAEA,IAAAwB,WAAA,GAAAxB,OAAA;AAEA,IAAAyB,WAAA,GAAAzB,OAAA;AACA,IAAA0B,WAAA,GAAA1B,OAAA;AACA,IAAA2B,YAAA,GAAA3B,OAAA;AACA,IAAA4B,yBAAA,GAAA5B,OAAA;AACA,IAAA6B,eAAA,GAAA7B,OAAA;AAIA,IAAA8B,eAAA,GAAA9B,OAAA;AACA,IAAA+B,oBAAA,GAAA/B,OAAA;AAEA,IAAAgC,aAAA,GAAAhC,OAAA;AAOA,IAAAiC,OAAA,GAAAjC,OAAA;AACA,IAAAkC,WAAA,GAAAlC,OAAA;AACA,IAAAmC,gBAAA,GAAAnC,OAAA;AACA,IAAAoC,eAAA,GAAApC,OAAA;AAEA,IAAAqC,KAAA,GAAArC,OAAA;AACA,IAAAsC,0BAAA,GAAAtC,OAAA;AACA,IAAAuC,MAAA,GAAAvC,OAAA;AAAmD,SAAAG,uBAAAqC,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA"}
@@ -262,6 +262,7 @@ function shakerPlugin(babel, {
262
262
  const unreferenced = Object.values(file.scope.getAllBindings()).filter(i => !i.referenced);
263
263
  for (const binding of unreferenced) {
264
264
  if (binding.path.isVariableDeclarator() && !forDeleting.includes(binding.path.get('id'))) {
265
+ forDeleting.push(...binding.constantViolations);
265
266
  forDeleting.push(binding.path.get('id'));
266
267
  changed = true;
267
268
  }
@@ -1 +1 @@
1
- {"version":3,"file":"shaker.js","names":["_shared","require","_collectExportsAndImports","_getFileIdx","_isRemoved","_scopeHelpers","_traversalCache","EXT_REGEX","ALLOWED_EXTENSIONS","shouldKeepSideEffect","importPath","ext","match","includes","getBindingForExport","exportPath","isIdentifier","scope","getBinding","node","name","variableDeclarator","findParent","p","isVariableDeclarator","id","get","isAssignmentExpression","left","isFunctionDeclaration","isClassDeclaration","undefined","withoutRemoved","items","filter","local","isRemoved","rearrangeExports","types","t","root","exportRefs","exports","rearranged","rootScope","forEach","refs","_constantViolations","length","declarator","uid","generateUid","declaration","unshiftContainer","variableDeclaration","identifier","registerDeclaration","constantViolations","ref","replaced","replaceWith","isBindingIdentifier","push","reference","registerConstantViolation","assigmentToExport","expressionStatement","assignmentExpression","memberExpression","body","lastViolation","pathInRoot","find","n","isDescendant","pushed","insertAfter","shakerPlugin","babel","keepSideEffects","ifUnknownExport","onlyExports","shakerLogger","logger","extend","pre","file","filename","opts","log","getFileIdx","join","onlyExportsSet","Set","collected","collectExportsAndImports","path","sideEffectImports","imports","sideEffectImport","Object","values","reexports","hasWywPreval","__wywPreval","hasDefault","default","has","delete","size","deadExports","keys","remove","importedAsSideEffect","isEsModule","add","aliveExports","importNames","map","imported","entries","exported","some","alive","exp","exportToPath","Map","set","notFoundExports","clear","isAllExportsFound","Error","forDeleting","i","source","deleted","dereferenced","changed","binding","action","findActionForNode","parent","outerReferences","referencePaths","isAncestor","dereference","applyAction","removeWithRelated","unreferenced","getAllBindings","referenced","visitor","post","processedImports","addImport","metadata","wywEvaluator","invalidateTraversalCache"],"sources":["../../src/plugins/shaker.ts"],"sourcesContent":["import type { BabelFile, PluginObj, NodePath } from '@babel/core';\nimport type { Binding } from '@babel/traverse';\nimport type {\n Identifier,\n MemberExpression,\n Program,\n VariableDeclarator,\n} from '@babel/types';\n\nimport { logger } from '@wyw-in-js/shared';\n\nimport type { Core } from '../babel';\nimport type { IMetadata } from '../utils/ShakerMetadata';\nimport type { Exports, IState } from '../utils/collectExportsAndImports';\nimport {\n collectExportsAndImports,\n sideEffectImport,\n} from '../utils/collectExportsAndImports';\nimport { getFileIdx } from '../utils/getFileIdx';\nimport { isRemoved } from '../utils/isRemoved';\nimport {\n applyAction,\n dereference,\n findActionForNode,\n reference,\n removeWithRelated,\n} from '../utils/scopeHelpers';\nimport { invalidateTraversalCache } from '../utils/traversalCache';\n\nconst EXT_REGEX = /\\.[0-9a-z]+$/;\nconst ALLOWED_EXTENSIONS = ['.js', '.cjs', '.mjs'];\n\nfunction shouldKeepSideEffect(importPath: string) {\n const [ext] = importPath.match(EXT_REGEX) || [''];\n\n return ext === '' || ALLOWED_EXTENSIONS.includes(ext);\n}\n\nexport interface IShakerOptions {\n ifUnknownExport?: 'error' | 'ignore' | 'reexport-all' | 'skip-shaking';\n keepSideEffects?: boolean;\n onlyExports: string[];\n}\n\ninterface NodeWithName {\n name: string;\n}\n\nfunction getBindingForExport(exportPath: NodePath): Binding | undefined {\n if (exportPath.isIdentifier()) {\n return exportPath.scope.getBinding(exportPath.node.name);\n }\n\n const variableDeclarator = exportPath.findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n if (variableDeclarator) {\n const id = variableDeclarator.get('id');\n if (id.isIdentifier()) {\n return variableDeclarator.scope.getBinding(id.node.name);\n }\n }\n\n if (exportPath.isAssignmentExpression()) {\n const left = exportPath.get('left');\n if (left.isIdentifier()) {\n return exportPath.scope.getBinding(left.node.name);\n }\n }\n\n if (exportPath.isFunctionDeclaration() || exportPath.isClassDeclaration()) {\n return exportPath.scope.getBinding(exportPath.node.id!.name);\n }\n\n return undefined;\n}\n\nconst withoutRemoved = <T extends { local: NodePath }>(items: T[]): T[] =>\n items.filter(({ local }) => !isRemoved(local));\n\nfunction rearrangeExports(\n { types: t }: Core,\n root: NodePath<Program>,\n exportRefs: Map<string, NodePath<MemberExpression>[]>,\n exports: Exports\n): Exports {\n const rearranged = {\n ...exports,\n };\n\n const rootScope = root.scope;\n exportRefs.forEach((refs, name) => {\n if (refs.length <= 1) {\n if (refs.length === 1) {\n // Maybe exports is assigned to another variable?\n const declarator = refs[0].findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n\n if (!declarator) {\n return;\n }\n } else {\n return;\n }\n }\n\n const uid = rootScope.generateUid(name);\n // Define variable in the beginning\n const [declaration] = root.unshiftContainer('body', [\n t.variableDeclaration('var', [t.variableDeclarator(t.identifier(uid))]),\n ]);\n\n rootScope.registerDeclaration(declaration);\n\n const constantViolations: NodePath<Identifier>[] = [];\n // Replace every reference with defined variable\n refs.forEach((ref) => {\n const [replaced] = ref.replaceWith(t.identifier(uid));\n if (replaced.isBindingIdentifier()) {\n constantViolations.push(replaced);\n } else {\n reference(replaced);\n }\n });\n\n constantViolations.forEach((id) => {\n rootScope.registerConstantViolation(id);\n });\n\n const assigmentToExport = t.expressionStatement(\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('exports'), t.identifier(name)),\n t.identifier(uid)\n )\n );\n\n // export.foo = _foo will be inserted either after the last _foo assigment or in the end of the file\n const body = root.get('body');\n const lastViolation =\n constantViolations[constantViolations.length - 1] ??\n body[body.length - 1];\n const pathInRoot = root\n .get('body')\n .find((n) => lastViolation.isDescendant(n))!;\n\n const [pushed] = pathInRoot.insertAfter(assigmentToExport);\n\n const local = pushed.get('expression.right') as NodePath<Identifier>;\n reference(local);\n\n rearranged[name] = local;\n });\n\n return rearranged;\n}\n\nexport default function shakerPlugin(\n babel: Core,\n {\n keepSideEffects = false,\n ifUnknownExport = 'skip-shaking',\n onlyExports,\n }: IShakerOptions\n): PluginObj<IState & { filename: string }> {\n const shakerLogger = logger.extend('shaker');\n\n return {\n name: '@wyw-in-js/transform/shaker',\n pre(file: BabelFile) {\n this.filename = file.opts.filename!;\n const log = shakerLogger.extend(getFileIdx(this.filename));\n\n log('start', `${this.filename}, onlyExports: ${onlyExports.join(',')}`);\n const onlyExportsSet = new Set(onlyExports);\n\n const collected = collectExportsAndImports(file.path);\n const sideEffectImports = collected.imports.filter(sideEffectImport);\n log(\n 'import-and-exports',\n [\n `imports: ${collected.imports.length} (side-effects: ${sideEffectImports.length})`,\n `exports: ${Object.values(collected.exports).length}`,\n `reexports: ${collected.reexports.length}`,\n ].join(', ')\n );\n\n // We cannot just throw out exports if they are referred in the code\n // Let's dome some replacements\n const exports = rearrangeExports(\n babel,\n file.path,\n collected.exportRefs,\n collected.exports\n );\n\n Object.values(exports).forEach((local) => {\n if (local.isAssignmentExpression()) {\n const left = local.get('left');\n if (left.isIdentifier()) {\n // For some reason babel does not mark id in AssignmentExpression as a reference\n // So we need to do it manually\n reference(left, left, true);\n }\n }\n });\n\n const hasWywPreval = exports.__wywPreval !== undefined;\n const hasDefault = exports.default !== undefined;\n\n // If __wywPreval is not exported, we can remove it from onlyExports\n if (onlyExportsSet.has('__wywPreval') && !hasWywPreval) {\n onlyExportsSet.delete('__wywPreval');\n }\n\n if (onlyExportsSet.size === 0) {\n // Fast-lane: if there are no exports to keep, we can just shake out the whole file\n this.imports = [];\n this.exports = {};\n this.reexports = [];\n this.deadExports = Object.keys(exports);\n\n file.path.get('body').forEach((p) => {\n p.remove();\n });\n\n return;\n }\n\n const importedAsSideEffect = onlyExportsSet.has('side-effect');\n onlyExportsSet.delete('side-effect');\n\n // Hackaround for packages which include a 'default' export without specifying __esModule; such packages cannot be\n // shaken as they will break interopRequireDefault babel helper\n // See example in shaker-plugin.test.ts\n // Real-world example was found in preact/compat npm package\n if (\n onlyExportsSet.has('default') &&\n hasDefault &&\n !collected.isEsModule\n ) {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n return;\n }\n\n if (!onlyExportsSet.has('*')) {\n // __esModule should be kept alive\n onlyExportsSet.add('__esModule');\n\n const aliveExports = new Set<NodePath>();\n const importNames = collected.imports.map(({ imported }) => imported);\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (onlyExportsSet.has(exported)) {\n aliveExports.add(local);\n } else if (\n importNames.includes((local.node as NodeWithName).name || '')\n ) {\n aliveExports.add(local);\n } else if ([...aliveExports].some((alive) => alive === local)) {\n // It's possible to export multiple values from a single variable initializer, e.g\n // export const { foo, bar } = baz();\n // We need to treat all of them as used if any of them are used, since otherwise\n // we'll attempt to delete the baz() call\n aliveExports.add(local);\n }\n });\n\n collected.reexports.forEach((exp) => {\n if (onlyExportsSet.has(exp.exported)) {\n aliveExports.add(exp.local);\n }\n });\n\n const exportToPath = new Map<string, NodePath>();\n Object.entries(exports).forEach(([exported, local]) => {\n exportToPath.set(exported, local);\n });\n\n collected.reexports.forEach((exp) => {\n exportToPath.set(exp.exported, exp.local);\n });\n\n const notFoundExports = [...onlyExportsSet].filter(\n (exp) =>\n exp !== '__esModule' && !aliveExports.has(exportToPath.get(exp)!)\n );\n exportToPath.clear();\n\n const isAllExportsFound = notFoundExports.length === 0;\n if (!isAllExportsFound && ifUnknownExport !== 'ignore') {\n if (ifUnknownExport === 'error') {\n throw new Error(\n `Unknown export(s) requested: ${onlyExports.join(',')}`\n );\n }\n\n if (ifUnknownExport === 'reexport-all') {\n // If there are unknown exports, we have keep alive all re-exports.\n if (exports['*'] !== undefined) {\n aliveExports.add(exports['*']);\n }\n\n collected.reexports.forEach((exp) => {\n if (exp.exported === '*') {\n aliveExports.add(exp.local);\n }\n });\n }\n\n if (ifUnknownExport === 'skip-shaking') {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n\n return;\n }\n }\n\n const forDeleting = [\n ...Object.values(exports),\n ...collected.reexports.map((i) => i.local),\n ].filter((exp) => !aliveExports.has(exp));\n\n if (!keepSideEffects && !importedAsSideEffect) {\n // Remove all imports that don't import something explicitly and should not be kept\n sideEffectImports.forEach((i) => {\n if (!shouldKeepSideEffect(i.source)) {\n forDeleting.push(i.local);\n }\n });\n }\n\n const deleted = new Set<NodePath>();\n\n let dereferenced: NodePath<Identifier>[] = [];\n let changed = true;\n while (changed && deleted.size < forDeleting.length) {\n changed = false;\n // eslint-disable-next-line no-restricted-syntax\n for (const path of forDeleting) {\n if (deleted.has(path)) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const binding = getBindingForExport(path);\n const action = findActionForNode(path);\n const parent = action?.[1];\n const outerReferences = (binding?.referencePaths || []).filter(\n (ref) => ref !== parent && !parent?.isAncestor(ref)\n );\n if (outerReferences.length > 0 && path.isIdentifier()) {\n // Temporary deref it in order to simplify further checks.\n dereference(path);\n dereferenced.push(path);\n }\n\n if (\n !deleted.has(path) &&\n (!binding || outerReferences.length === 0)\n ) {\n if (action) {\n applyAction(action);\n } else {\n removeWithRelated([path]);\n }\n\n deleted.add(path);\n changed = true;\n }\n }\n\n dereferenced.forEach((path) => {\n // If path is still alive, we need to reference it back\n if (!isRemoved(path)) {\n reference(path);\n }\n });\n\n dereferenced = [];\n\n // Find and mark for deleting all unreferenced variables\n const unreferenced = Object.values(\n file.scope.getAllBindings()\n ).filter((i) => !i.referenced);\n\n for (const binding of unreferenced) {\n if (\n binding.path.isVariableDeclarator() &&\n !forDeleting.includes(binding.path.get('id'))\n ) {\n forDeleting.push(binding.path.get('id'));\n changed = true;\n }\n }\n }\n }\n\n this.imports = withoutRemoved(collected.imports);\n this.exports = {};\n this.deadExports = [];\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (isRemoved(local)) {\n this.deadExports.push(exported);\n } else {\n this.exports[exported] = local;\n }\n });\n\n this.reexports = withoutRemoved(collected.reexports);\n },\n visitor: {},\n post(file: BabelFile) {\n const log = shakerLogger.extend(getFileIdx(file.opts.filename!));\n\n const processedImports = new Set<string>();\n const imports = new Map<string, string[]>();\n const addImport = ({\n imported,\n source,\n }: {\n imported: string;\n source: string;\n }) => {\n if (processedImports.has(`${source}:${imported}`)) {\n return;\n }\n\n if (!imports.has(source)) {\n imports.set(source, []);\n }\n\n if (imported) {\n imports.get(source)!.push(imported);\n }\n\n processedImports.add(`${source}:${imported}`);\n };\n\n this.imports.forEach(addImport);\n this.reexports.forEach(addImport);\n\n log('end', `remaining imports: %O`, imports);\n\n // eslint-disable-next-line no-param-reassign\n (file.metadata as IMetadata).wywEvaluator = {\n imports,\n };\n\n invalidateTraversalCache(file.path);\n },\n };\n}\n"],"mappings":";;;;;;AASA,IAAAA,OAAA,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.js","names":["_shared","require","_collectExportsAndImports","_getFileIdx","_isRemoved","_scopeHelpers","_traversalCache","EXT_REGEX","ALLOWED_EXTENSIONS","shouldKeepSideEffect","importPath","ext","match","includes","getBindingForExport","exportPath","isIdentifier","scope","getBinding","node","name","variableDeclarator","findParent","p","isVariableDeclarator","id","get","isAssignmentExpression","left","isFunctionDeclaration","isClassDeclaration","undefined","withoutRemoved","items","filter","local","isRemoved","rearrangeExports","types","t","root","exportRefs","exports","rearranged","rootScope","forEach","refs","_constantViolations","length","declarator","uid","generateUid","declaration","unshiftContainer","variableDeclaration","identifier","registerDeclaration","constantViolations","ref","replaced","replaceWith","isBindingIdentifier","push","reference","registerConstantViolation","assigmentToExport","expressionStatement","assignmentExpression","memberExpression","body","lastViolation","pathInRoot","find","n","isDescendant","pushed","insertAfter","shakerPlugin","babel","keepSideEffects","ifUnknownExport","onlyExports","shakerLogger","logger","extend","pre","file","filename","opts","log","getFileIdx","join","onlyExportsSet","Set","collected","collectExportsAndImports","path","sideEffectImports","imports","sideEffectImport","Object","values","reexports","hasWywPreval","__wywPreval","hasDefault","default","has","delete","size","deadExports","keys","remove","importedAsSideEffect","isEsModule","add","aliveExports","importNames","map","imported","entries","exported","some","alive","exp","exportToPath","Map","set","notFoundExports","clear","isAllExportsFound","Error","forDeleting","i","source","deleted","dereferenced","changed","binding","action","findActionForNode","parent","outerReferences","referencePaths","isAncestor","dereference","applyAction","removeWithRelated","unreferenced","getAllBindings","referenced","visitor","post","processedImports","addImport","metadata","wywEvaluator","invalidateTraversalCache"],"sources":["../../src/plugins/shaker.ts"],"sourcesContent":["import type { BabelFile, PluginObj, NodePath } from '@babel/core';\nimport type { Binding } from '@babel/traverse';\nimport type {\n Identifier,\n MemberExpression,\n Program,\n VariableDeclarator,\n} from '@babel/types';\n\nimport { logger } from '@wyw-in-js/shared';\n\nimport type { Core } from '../babel';\nimport type { IMetadata } from '../utils/ShakerMetadata';\nimport type { Exports, IState } from '../utils/collectExportsAndImports';\nimport {\n collectExportsAndImports,\n sideEffectImport,\n} from '../utils/collectExportsAndImports';\nimport { getFileIdx } from '../utils/getFileIdx';\nimport { isRemoved } from '../utils/isRemoved';\nimport {\n applyAction,\n dereference,\n findActionForNode,\n reference,\n removeWithRelated,\n} from '../utils/scopeHelpers';\nimport { invalidateTraversalCache } from '../utils/traversalCache';\n\nconst EXT_REGEX = /\\.[0-9a-z]+$/;\nconst ALLOWED_EXTENSIONS = ['.js', '.cjs', '.mjs'];\n\nfunction shouldKeepSideEffect(importPath: string) {\n const [ext] = importPath.match(EXT_REGEX) || [''];\n\n return ext === '' || ALLOWED_EXTENSIONS.includes(ext);\n}\n\nexport interface IShakerOptions {\n ifUnknownExport?: 'error' | 'ignore' | 'reexport-all' | 'skip-shaking';\n keepSideEffects?: boolean;\n onlyExports: string[];\n}\n\ninterface NodeWithName {\n name: string;\n}\n\nfunction getBindingForExport(exportPath: NodePath): Binding | undefined {\n if (exportPath.isIdentifier()) {\n return exportPath.scope.getBinding(exportPath.node.name);\n }\n\n const variableDeclarator = exportPath.findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n if (variableDeclarator) {\n const id = variableDeclarator.get('id');\n if (id.isIdentifier()) {\n return variableDeclarator.scope.getBinding(id.node.name);\n }\n }\n\n if (exportPath.isAssignmentExpression()) {\n const left = exportPath.get('left');\n if (left.isIdentifier()) {\n return exportPath.scope.getBinding(left.node.name);\n }\n }\n\n if (exportPath.isFunctionDeclaration() || exportPath.isClassDeclaration()) {\n return exportPath.scope.getBinding(exportPath.node.id!.name);\n }\n\n return undefined;\n}\n\nconst withoutRemoved = <T extends { local: NodePath }>(items: T[]): T[] =>\n items.filter(({ local }) => !isRemoved(local));\n\nfunction rearrangeExports(\n { types: t }: Core,\n root: NodePath<Program>,\n exportRefs: Map<string, NodePath<MemberExpression>[]>,\n exports: Exports\n): Exports {\n const rearranged = {\n ...exports,\n };\n\n const rootScope = root.scope;\n exportRefs.forEach((refs, name) => {\n if (refs.length <= 1) {\n if (refs.length === 1) {\n // Maybe exports is assigned to another variable?\n const declarator = refs[0].findParent((p) =>\n p.isVariableDeclarator()\n ) as NodePath<VariableDeclarator> | undefined;\n\n if (!declarator) {\n return;\n }\n } else {\n return;\n }\n }\n\n const uid = rootScope.generateUid(name);\n // Define variable in the beginning\n const [declaration] = root.unshiftContainer('body', [\n t.variableDeclaration('var', [t.variableDeclarator(t.identifier(uid))]),\n ]);\n\n rootScope.registerDeclaration(declaration);\n\n const constantViolations: NodePath<Identifier>[] = [];\n // Replace every reference with defined variable\n refs.forEach((ref) => {\n const [replaced] = ref.replaceWith(t.identifier(uid));\n if (replaced.isBindingIdentifier()) {\n constantViolations.push(replaced);\n } else {\n reference(replaced);\n }\n });\n\n constantViolations.forEach((id) => {\n rootScope.registerConstantViolation(id);\n });\n\n const assigmentToExport = t.expressionStatement(\n t.assignmentExpression(\n '=',\n t.memberExpression(t.identifier('exports'), t.identifier(name)),\n t.identifier(uid)\n )\n );\n\n // export.foo = _foo will be inserted either after the last _foo assigment or in the end of the file\n const body = root.get('body');\n const lastViolation =\n constantViolations[constantViolations.length - 1] ??\n body[body.length - 1];\n const pathInRoot = root\n .get('body')\n .find((n) => lastViolation.isDescendant(n))!;\n\n const [pushed] = pathInRoot.insertAfter(assigmentToExport);\n\n const local = pushed.get('expression.right') as NodePath<Identifier>;\n reference(local);\n\n rearranged[name] = local;\n });\n\n return rearranged;\n}\n\nexport default function shakerPlugin(\n babel: Core,\n {\n keepSideEffects = false,\n ifUnknownExport = 'skip-shaking',\n onlyExports,\n }: IShakerOptions\n): PluginObj<IState & { filename: string }> {\n const shakerLogger = logger.extend('shaker');\n\n return {\n name: '@wyw-in-js/transform/shaker',\n pre(file: BabelFile) {\n this.filename = file.opts.filename!;\n const log = shakerLogger.extend(getFileIdx(this.filename));\n\n log('start', `${this.filename}, onlyExports: ${onlyExports.join(',')}`);\n const onlyExportsSet = new Set(onlyExports);\n\n const collected = collectExportsAndImports(file.path);\n const sideEffectImports = collected.imports.filter(sideEffectImport);\n log(\n 'import-and-exports',\n [\n `imports: ${collected.imports.length} (side-effects: ${sideEffectImports.length})`,\n `exports: ${Object.values(collected.exports).length}`,\n `reexports: ${collected.reexports.length}`,\n ].join(', ')\n );\n\n // We cannot just throw out exports if they are referred in the code\n // Let's dome some replacements\n const exports = rearrangeExports(\n babel,\n file.path,\n collected.exportRefs,\n collected.exports\n );\n\n Object.values(exports).forEach((local) => {\n if (local.isAssignmentExpression()) {\n const left = local.get('left');\n if (left.isIdentifier()) {\n // For some reason babel does not mark id in AssignmentExpression as a reference\n // So we need to do it manually\n reference(left, left, true);\n }\n }\n });\n\n const hasWywPreval = exports.__wywPreval !== undefined;\n const hasDefault = exports.default !== undefined;\n\n // If __wywPreval is not exported, we can remove it from onlyExports\n if (onlyExportsSet.has('__wywPreval') && !hasWywPreval) {\n onlyExportsSet.delete('__wywPreval');\n }\n\n if (onlyExportsSet.size === 0) {\n // Fast-lane: if there are no exports to keep, we can just shake out the whole file\n this.imports = [];\n this.exports = {};\n this.reexports = [];\n this.deadExports = Object.keys(exports);\n\n file.path.get('body').forEach((p) => {\n p.remove();\n });\n\n return;\n }\n\n const importedAsSideEffect = onlyExportsSet.has('side-effect');\n onlyExportsSet.delete('side-effect');\n\n // Hackaround for packages which include a 'default' export without specifying __esModule; such packages cannot be\n // shaken as they will break interopRequireDefault babel helper\n // See example in shaker-plugin.test.ts\n // Real-world example was found in preact/compat npm package\n if (\n onlyExportsSet.has('default') &&\n hasDefault &&\n !collected.isEsModule\n ) {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n return;\n }\n\n if (!onlyExportsSet.has('*')) {\n // __esModule should be kept alive\n onlyExportsSet.add('__esModule');\n\n const aliveExports = new Set<NodePath>();\n const importNames = collected.imports.map(({ imported }) => imported);\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (onlyExportsSet.has(exported)) {\n aliveExports.add(local);\n } else if (\n importNames.includes((local.node as NodeWithName).name || '')\n ) {\n aliveExports.add(local);\n } else if ([...aliveExports].some((alive) => alive === local)) {\n // It's possible to export multiple values from a single variable initializer, e.g\n // export const { foo, bar } = baz();\n // We need to treat all of them as used if any of them are used, since otherwise\n // we'll attempt to delete the baz() call\n aliveExports.add(local);\n }\n });\n\n collected.reexports.forEach((exp) => {\n if (onlyExportsSet.has(exp.exported)) {\n aliveExports.add(exp.local);\n }\n });\n\n const exportToPath = new Map<string, NodePath>();\n Object.entries(exports).forEach(([exported, local]) => {\n exportToPath.set(exported, local);\n });\n\n collected.reexports.forEach((exp) => {\n exportToPath.set(exp.exported, exp.local);\n });\n\n const notFoundExports = [...onlyExportsSet].filter(\n (exp) =>\n exp !== '__esModule' && !aliveExports.has(exportToPath.get(exp)!)\n );\n exportToPath.clear();\n\n const isAllExportsFound = notFoundExports.length === 0;\n if (!isAllExportsFound && ifUnknownExport !== 'ignore') {\n if (ifUnknownExport === 'error') {\n throw new Error(\n `Unknown export(s) requested: ${onlyExports.join(',')}`\n );\n }\n\n if (ifUnknownExport === 'reexport-all') {\n // If there are unknown exports, we have keep alive all re-exports.\n if (exports['*'] !== undefined) {\n aliveExports.add(exports['*']);\n }\n\n collected.reexports.forEach((exp) => {\n if (exp.exported === '*') {\n aliveExports.add(exp.local);\n }\n });\n }\n\n if (ifUnknownExport === 'skip-shaking') {\n this.imports = collected.imports;\n this.exports = exports;\n this.reexports = collected.reexports;\n this.deadExports = [];\n\n return;\n }\n }\n\n const forDeleting = [\n ...Object.values(exports),\n ...collected.reexports.map((i) => i.local),\n ].filter((exp) => !aliveExports.has(exp));\n\n if (!keepSideEffects && !importedAsSideEffect) {\n // Remove all imports that don't import something explicitly and should not be kept\n sideEffectImports.forEach((i) => {\n if (!shouldKeepSideEffect(i.source)) {\n forDeleting.push(i.local);\n }\n });\n }\n\n const deleted = new Set<NodePath>();\n\n let dereferenced: NodePath<Identifier>[] = [];\n let changed = true;\n while (changed && deleted.size < forDeleting.length) {\n changed = false;\n // eslint-disable-next-line no-restricted-syntax\n for (const path of forDeleting) {\n if (deleted.has(path)) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const binding = getBindingForExport(path);\n const action = findActionForNode(path);\n const parent = action?.[1];\n const outerReferences = (binding?.referencePaths || []).filter(\n (ref) => ref !== parent && !parent?.isAncestor(ref)\n );\n if (outerReferences.length > 0 && path.isIdentifier()) {\n // Temporary deref it in order to simplify further checks.\n dereference(path);\n dereferenced.push(path);\n }\n\n if (\n !deleted.has(path) &&\n (!binding || outerReferences.length === 0)\n ) {\n if (action) {\n applyAction(action);\n } else {\n removeWithRelated([path]);\n }\n\n deleted.add(path);\n changed = true;\n }\n }\n\n dereferenced.forEach((path) => {\n // If path is still alive, we need to reference it back\n if (!isRemoved(path)) {\n reference(path);\n }\n });\n\n dereferenced = [];\n\n // Find and mark for deleting all unreferenced variables\n const unreferenced = Object.values(\n file.scope.getAllBindings()\n ).filter((i) => !i.referenced);\n\n for (const binding of unreferenced) {\n if (\n binding.path.isVariableDeclarator() &&\n !forDeleting.includes(binding.path.get('id'))\n ) {\n forDeleting.push(...binding.constantViolations);\n forDeleting.push(binding.path.get('id'));\n changed = true;\n }\n }\n }\n }\n\n this.imports = withoutRemoved(collected.imports);\n this.exports = {};\n this.deadExports = [];\n\n Object.entries(exports).forEach(([exported, local]) => {\n if (isRemoved(local)) {\n this.deadExports.push(exported);\n } else {\n this.exports[exported] = local;\n }\n });\n\n this.reexports = withoutRemoved(collected.reexports);\n },\n visitor: {},\n post(file: BabelFile) {\n const log = shakerLogger.extend(getFileIdx(file.opts.filename!));\n\n const processedImports = new Set<string>();\n const imports = new Map<string, string[]>();\n const addImport = ({\n imported,\n source,\n }: {\n imported: string;\n source: string;\n }) => {\n if (processedImports.has(`${source}:${imported}`)) {\n return;\n }\n\n if (!imports.has(source)) {\n imports.set(source, []);\n }\n\n if (imported) {\n imports.get(source)!.push(imported);\n }\n\n processedImports.add(`${source}:${imported}`);\n };\n\n this.imports.forEach(addImport);\n this.reexports.forEach(addImport);\n\n log('end', `remaining imports: %O`, imports);\n\n // eslint-disable-next-line no-param-reassign\n (file.metadata as IMetadata).wywEvaluator = {\n imports,\n };\n\n invalidateTraversalCache(file.path);\n },\n };\n}\n"],"mappings":";;;;;;AASA,IAAAA,OAAA,GAAAC,OAAA;AAKA,IAAAC,yBAAA,GAAAD,OAAA;AAIA,IAAAE,WAAA,GAAAF,OAAA;AACA,IAAAG,UAAA,GAAAH,OAAA;AACA,IAAAI,aAAA,GAAAJ,OAAA;AAOA,IAAAK,eAAA,GAAAL,OAAA;AAEA,MAAMM,SAAS,GAAG,cAAc;AAChC,MAAMC,kBAAkB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;AAElD,SAASC,oBAAoBA,CAACC,UAAkB,EAAE;EAChD,MAAM,CAACC,GAAG,CAAC,GAAGD,UAAU,CAACE,KAAK,CAACL,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;EAEjD,OAAOI,GAAG,KAAK,EAAE,IAAIH,kBAAkB,CAACK,QAAQ,CAACF,GAAG,CAAC;AACvD;AAYA,SAASG,mBAAmBA,CAACC,UAAoB,EAAuB;EACtE,IAAIA,UAAU,CAACC,YAAY,CAAC,CAAC,EAAE;IAC7B,OAAOD,UAAU,CAACE,KAAK,CAACC,UAAU,CAACH,UAAU,CAACI,IAAI,CAACC,IAAI,CAAC;EAC1D;EAEA,MAAMC,kBAAkB,GAAGN,UAAU,CAACO,UAAU,CAAEC,CAAC,IACjDA,CAAC,CAACC,oBAAoB,CAAC,CACzB,CAA6C;EAC7C,IAAIH,kBAAkB,EAAE;IACtB,MAAMI,EAAE,GAAGJ,kBAAkB,CAACK,GAAG,CAAC,IAAI,CAAC;IACvC,IAAID,EAAE,CAACT,YAAY,CAAC,CAAC,EAAE;MACrB,OAAOK,kBAAkB,CAACJ,KAAK,CAACC,UAAU,CAACO,EAAE,CAACN,IAAI,CAACC,IAAI,CAAC;IAC1D;EACF;EAEA,IAAI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,CAAC6G,SAAS,CAAC;MAEjCjE,GAAG,CAAC,KAAK,EAAG,uBAAsB,EAAES,OAAO,CAAC;;MAE5C;MACCZ,IAAI,CAACqE,QAAQ,CAAeC,YAAY,GAAG;QAC1C1D;MACF,CAAC;MAED,IAAA2D,wCAAwB,EAACvE,IAAI,CAACU,IAAI,CAAC;IACrC;EACF,CAAC;AACH"}
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createStylisPreprocessor = createStylisPreprocessor;
7
+ exports.createStylisUrlReplacePlugin = createStylisUrlReplacePlugin;
8
+ exports.stylisGlobalPlugin = void 0;
9
+ exports.transformUrl = transformUrl;
10
+ var path = _interopRequireWildcard(require("path"));
11
+ var _stylis = require("stylis");
12
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
13
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
14
+ const POSIX_SEP = path.posix.sep;
15
+ function transformUrl(url, outputFilename, sourceFilename, platformPath = path) {
16
+ // Replace asset path with new path relative to the output CSS
17
+ const relative = platformPath.relative(platformPath.dirname(outputFilename),
18
+ // Get the absolute path to the asset from the path relative to the JS file
19
+ platformPath.resolve(platformPath.dirname(sourceFilename), url));
20
+ if (platformPath.sep === POSIX_SEP) {
21
+ return relative;
22
+ }
23
+ return relative.split(platformPath.sep).join(POSIX_SEP);
24
+ }
25
+
26
+ /**
27
+ * Stylis plugin that mimics :global() selector behavior from Stylis v3.
28
+ */
29
+ const stylisGlobalPlugin = element => {
30
+ function getGlobalSelectorModifiers(value) {
31
+ const match = value.match(/(&\f( )?)?:global\(/);
32
+ if (match === null) {
33
+ throw new Error(`Failed to match :global() selector in "${value}". Please report a bug if it happens.`);
34
+ }
35
+ const [, baseSelector, spaceDelimiter] = match;
36
+ return {
37
+ includeBaseSelector: !!baseSelector,
38
+ includeSpaceDelimiter: !!spaceDelimiter
39
+ };
40
+ }
41
+ switch (element.type) {
42
+ case _stylis.RULESET:
43
+ if (typeof element.props === 'string') {
44
+ if (process.env.NODE_ENV !== 'production') {
45
+ throw new Error(`"element.props" has type "string" (${JSON.stringify(element.props, null, 2)}), it's not expected. Please report a bug if it happens.`);
46
+ }
47
+ return;
48
+ }
49
+ Object.assign(element, {
50
+ props: element.props.map(cssSelector => {
51
+ var _element$parent;
52
+ // Avoids calling tokenize() on every string
53
+ if (!cssSelector.includes(':global(')) {
54
+ return cssSelector;
55
+ }
56
+ if (element.children.length === 0) {
57
+ Object.assign(element, {
58
+ global: getGlobalSelectorModifiers(element.value)
59
+ });
60
+ return cssSelector;
61
+ }
62
+ const {
63
+ includeBaseSelector,
64
+ includeSpaceDelimiter
65
+ } = ((_element$parent = element.parent) === null || _element$parent === void 0 ? void 0 : _element$parent.global) || getGlobalSelectorModifiers(element.value);
66
+ const tokens = (0, _stylis.tokenize)(cssSelector);
67
+ let selector = '';
68
+ for (let i = 0, len = tokens.length; i < len; i++) {
69
+ const token = tokens[i];
70
+
71
+ //
72
+ // Match for ":global("
73
+ if (token === ':' && tokens[i + 1] === 'global') {
74
+ //
75
+ // Match for ":global()"
76
+ if (tokens[i + 2] === '()') {
77
+ selector = [...tokens.slice(i + 4), includeSpaceDelimiter ? ' ' : '', ...(includeBaseSelector ? tokens.slice(0, i - 1) : []), includeSpaceDelimiter ? '' : ' '].join('');
78
+ break;
79
+ }
80
+
81
+ //
82
+ // Match for ":global(selector)"
83
+ selector = [tokens[i + 2].slice(1, -1), includeSpaceDelimiter ? ' ' : '', ...(includeBaseSelector ? tokens.slice(0, i - 1) : []), includeSpaceDelimiter ? '' : ' '].join('');
84
+ break;
85
+ }
86
+ }
87
+ return selector;
88
+ })
89
+ });
90
+ break;
91
+ default:
92
+ }
93
+ };
94
+ exports.stylisGlobalPlugin = stylisGlobalPlugin;
95
+ function createStylisUrlReplacePlugin(filename, outputFilename) {
96
+ return element => {
97
+ if (element.type === 'decl' && outputFilename) {
98
+ // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
99
+ // It'll allow css-loader to resolve an imported asset properly.
100
+ // eslint-disable-next-line no-param-reassign
101
+ element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, filename) + p4);
102
+ }
103
+ };
104
+ }
105
+ function createStylisPreprocessor(options) {
106
+ function stylisPreprocess(selector, text) {
107
+ const compiled = (0, _stylis.compile)(`${selector} {${text}}\n`);
108
+ return (0, _stylis.serialize)(compiled, (0, _stylis.middleware)([createStylisUrlReplacePlugin(options.filename, options.outputFilename), stylisGlobalPlugin, _stylis.prefixer, _stylis.stringify]));
109
+ }
110
+ return stylisPreprocess;
111
+ }
112
+ //# sourceMappingURL=createStylisPreprocessor.js.map
@@ -0,0 +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","stylisGlobalPlugin","element","getGlobalSelectorModifiers","value","match","Error","baseSelector","spaceDelimiter","includeBaseSelector","includeSpaceDelimiter","type","RULESET","props","process","env","NODE_ENV","JSON","stringify","assign","map","cssSelector","_element$parent","includes","children","length","global","parent","tokens","tokenize","selector","len","token","slice","exports","createStylisUrlReplacePlugin","filename","return","replace","p1","p2","p3","p4","createStylisPreprocessor","options","stylisPreprocess","text","compiled","compile","serialize","middleware","prefixer"],"sources":["../../../src/transform/generators/createStylisPreprocessor.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n compile,\n middleware,\n prefixer,\n serialize,\n stringify,\n tokenize,\n RULESET,\n} from 'stylis';\nimport type { Middleware } 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\n/**\n * Stylis plugin that mimics :global() selector behavior from Stylis v3.\n */\nexport const stylisGlobalPlugin: Middleware = (element) => {\n function getGlobalSelectorModifiers(value: string) {\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 switch (element.type) {\n case RULESET:\n if (typeof element.props === 'string') {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `\"element.props\" has type \"string\" (${JSON.stringify(\n element.props,\n null,\n 2\n )}), it's not expected. Please report a bug if it happens.`\n );\n }\n\n return;\n }\n\n Object.assign(element, {\n props: element.props.map((cssSelector) => {\n // Avoids calling tokenize() on every string\n if (!cssSelector.includes(':global(')) {\n return cssSelector;\n }\n\n if (element.children.length === 0) {\n Object.assign(element, {\n global: getGlobalSelectorModifiers(element.value),\n });\n return cssSelector;\n }\n\n const { includeBaseSelector, includeSpaceDelimiter } =\n (\n element.parent as unknown as\n | (Element & {\n global: ReturnType<typeof getGlobalSelectorModifiers>;\n })\n | undefined\n )?.global || getGlobalSelectorModifiers(element.value);\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 break;\n\n default:\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 createStylisPreprocessor(options: Options) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n\n return serialize(\n compiled,\n middleware([\n createStylisUrlReplacePlugin(options.filename, options.outputFilename),\n stylisGlobalPlugin,\n prefixer,\n stringify,\n ])\n );\n }\n\n return stylisPreprocess;\n}\n"],"mappings":";;;;;;;;;AA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AO,EAAE,GAAElB,QAAS,KAAIgB,IAAK,KAAI,CAAC;IAEnD,OAAO,IAAAG,iBAAS,EACdF,QAAQ,EACR,IAAAG,kBAAU,EAAC,CACTf,4BAA4B,CAACS,OAAO,CAACR,QAAQ,EAAEQ,OAAO,CAACnD,cAAc,CAAC,EACtEQ,kBAAkB,EAClBkD,gBAAQ,EACRjC,iBAAS,CACV,CACH,CAAC;EACH;EAEA,OAAO2B,gBAAgB;AACzB"}
@@ -4,39 +4,8 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.extract = extract;
7
- exports.transformUrl = transformUrl;
8
- var _path = _interopRequireDefault(require("path"));
9
7
  var _sourceMap = require("source-map");
10
- var _stylis = require("stylis");
11
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
- const posixSep = _path.default.posix.sep;
13
- function transformUrl(url, outputFilename, sourceFilename, platformPath = _path.default) {
14
- // Replace asset path with new path relative to the output CSS
15
- const relative = platformPath.relative(platformPath.dirname(outputFilename),
16
- // Get the absolute path to the asset from the path relative to the JS file
17
- platformPath.resolve(platformPath.dirname(sourceFilename), url));
18
- if (platformPath.sep === posixSep) {
19
- return relative;
20
- }
21
- return relative.split(platformPath.sep).join(posixSep);
22
- }
23
- function createStylisPreprocessor(options) {
24
- function stylisPreprocess(selector, text) {
25
- const compiled = (0, _stylis.compile)(`${selector} {${text}}\n`);
26
- return (0, _stylis.serialize)(compiled, (0, _stylis.middleware)([element => {
27
- const {
28
- outputFilename
29
- } = options;
30
- if (element.type === 'decl' && outputFilename) {
31
- // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
32
- // It'll allow css-loader to resolve an imported asset properly.
33
- // eslint-disable-next-line no-param-reassign
34
- element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, options.filename) + p4);
35
- }
36
- }, _stylis.prefixer, _stylis.stringify]));
37
- }
38
- return stylisPreprocess;
39
- }
8
+ var _createStylisPreprocessor = require("./createStylisPreprocessor");
40
9
  function extractCssFromAst(rules, originalCode, options) {
41
10
  const mappings = [];
42
11
  let cssText = '';
@@ -51,7 +20,7 @@ function extractCssFromAst(rules, originalCode, options) {
51
20
  break;
52
21
  case 'stylis':
53
22
  default:
54
- preprocessor = createStylisPreprocessor(options);
23
+ preprocessor = (0, _createStylisPreprocessor.createStylisPreprocessor)(options);
55
24
  }
56
25
  }
57
26
  Object.keys(rules).forEach((selector, index) => {
@@ -1 +1 @@
1
- {"version":3,"file":"extract.js","names":["_path","_interopRequireDefault","require","_sourceMap","_stylis","obj","__esModule","default","posixSep","path","posix","sep","transformUrl","url","outputFilename","sourceFilename","platformPath","relative","dirname","resolve","split","join","createStylisPreprocessor","options","stylisPreprocess","selector","text","compiled","compile","serialize","middleware","element","type","return","value","replace","match","p1","p2","p3","p4","filename","prefixer","stringify","extractCssFromAst","rules","originalCode","mappings","cssText","preprocessor","Object","keys","forEach","index","push","generated","line","column","original","start","name","source","atom","cssSourceMapText","length","generator","SourceMapGenerator","file","mapping","addMapping","setSourceContent","toString","extract","services","entrypoint","processors","data","loadedAndParsed","evaluator","Error","allRules","allReplacements","processor","artifacts","artifact","replacements","code"],"sources":["../../../src/transform/generators/extract.ts"],"sourcesContent":["import path from 'path';\n\nimport type { Mapping } from 'source-map';\nimport { SourceMapGenerator } from 'source-map';\nimport { compile, serialize, stringify, middleware, prefixer } from 'stylis';\n\nimport type { Replacements, Rules } from '@wyw-in-js/shared';\n\nimport type { Options, PreprocessorFn } from '../../types';\nimport type { IExtractAction, SyncScenarioForAction } from '../types';\n\nconst posixSep = 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 === posixSep) {\n return relative;\n }\n\n return relative.split(platformPath.sep).join(posixSep);\n}\n\nfunction createStylisPreprocessor(options: Options) {\n function stylisPreprocess(selector: string, text: string): string {\n const compiled = compile(`${selector} {${text}}\\n`);\n return serialize(\n compiled,\n middleware([\n (element: { return: string; type: string; value: string }) => {\n const { outputFilename } = options;\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, options.filename) + p4\n );\n }\n },\n prefixer,\n stringify,\n ])\n );\n }\n return stylisPreprocess;\n}\n\nfunction extractCssFromAst(\n rules: Rules,\n originalCode: string,\n options: Pick<Options, 'preprocessor' | 'filename' | 'outputFilename'>\n): { cssSourceMapText: string; cssText: string; rules: Rules } {\n const mappings: Mapping[] = [];\n\n let cssText = '';\n\n let preprocessor: PreprocessorFn;\n if (typeof options.preprocessor === 'function') {\n // eslint-disable-next-line prefer-destructuring\n preprocessor = options.preprocessor;\n } else {\n switch (options.preprocessor) {\n case 'none':\n preprocessor = (selector, text) => `${selector} {${text}}\\n`;\n break;\n case 'stylis':\n default:\n preprocessor = createStylisPreprocessor(options);\n }\n }\n\n Object.keys(rules).forEach((selector, index) => {\n mappings.push({\n generated: {\n line: index + 1,\n column: 0,\n },\n original: rules[selector].start!,\n name: selector,\n source: '',\n });\n\n if (rules[selector].atom) {\n // For atoms, we just directly insert cssText, to give the atomizer full control over the rules\n cssText += `${rules[selector].cssText}\\n`;\n } else {\n // Run each rule through stylis to support nesting\n cssText += `${preprocessor(selector, rules[selector].cssText)}\\n`;\n }\n });\n\n return {\n cssText,\n rules,\n\n get cssSourceMapText() {\n if (mappings?.length) {\n const generator = new SourceMapGenerator({\n file: options.filename.replace(/\\.js$/, '.css'),\n });\n\n mappings.forEach((mapping) =>\n generator.addMapping({ ...mapping, source: options.filename })\n );\n\n generator.setSourceContent(options.filename, originalCode);\n\n return generator.toString();\n }\n\n return '';\n },\n };\n}\n\n/**\n * Extract artifacts (e.g. CSS) from processors\n */\n// eslint-disable-next-line require-yield\nexport function* extract(\n this: IExtractAction\n): SyncScenarioForAction<IExtractAction> {\n const { options } = this.services;\n const { entrypoint } = this;\n const { processors } = this.data;\n const { loadedAndParsed } = entrypoint;\n if (loadedAndParsed.evaluator === 'ignored') {\n throw new Error('entrypoint was ignored');\n }\n\n let allRules: Rules = {};\n const allReplacements: Replacements = [];\n processors.forEach((processor) => {\n processor.artifacts.forEach((artifact) => {\n if (artifact[0] !== 'css') return;\n const [rules, replacements] = artifact[1] as [\n rules: Rules,\n sourceMapReplacements: Replacements,\n ];\n\n allRules = {\n ...allRules,\n ...rules,\n };\n\n allReplacements.push(...replacements);\n });\n });\n\n return {\n ...extractCssFromAst(allRules, loadedAndParsed.code, options),\n replacements: allReplacements,\n };\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAA6E,SAAAD,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAO7E,MAAMG,QAAQ,GAAGC,aAAI,CAACC,KAAK,CAACC,GAAG;AAExB,SAASC,YAAYA,CAC1BC,GAAW,EACXC,cAAsB,EACtBC,cAAsB,EACtBC,YAAyB,GAAGP,aAAI,EAChC;EACA;EACA,MAAMQ,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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CssFromAst","rules","originalCode","options","mappings","cssText","preprocessor","selector","text","createStylisPreprocessor","Object","keys","forEach","index","push","generated","line","column","original","start","name","source","atom","cssSourceMapText","length","generator","SourceMapGenerator","file","filename","replace","mapping","addMapping","setSourceContent","toString","extract","services","entrypoint","processors","data","loadedAndParsed","evaluator","Error","allRules","allReplacements","processor","artifacts","artifact","replacements","code"],"sources":["../../../src/transform/generators/extract.ts"],"sourcesContent":["import type { Mapping } from 'source-map';\nimport { SourceMapGenerator } from 'source-map';\n\nimport type { Replacements, Rules } from '@wyw-in-js/shared';\n\nimport type { Options, PreprocessorFn } from '../../types';\nimport type { IExtractAction, SyncScenarioForAction } from '../types';\nimport { createStylisPreprocessor } from './createStylisPreprocessor';\n\nfunction extractCssFromAst(\n rules: Rules,\n originalCode: string,\n options: Pick<Options, 'preprocessor' | 'filename' | 'outputFilename'>\n): { cssSourceMapText: string; cssText: string; rules: Rules } {\n const mappings: Mapping[] = [];\n\n let cssText = '';\n\n let preprocessor: PreprocessorFn;\n if (typeof options.preprocessor === 'function') {\n // eslint-disable-next-line prefer-destructuring\n preprocessor = options.preprocessor;\n } else {\n switch (options.preprocessor) {\n case 'none':\n preprocessor = (selector, text) => `${selector} {${text}}\\n`;\n break;\n case 'stylis':\n default:\n preprocessor = createStylisPreprocessor(options);\n }\n }\n\n Object.keys(rules).forEach((selector, index) => {\n mappings.push({\n generated: {\n line: index + 1,\n column: 0,\n },\n original: rules[selector].start!,\n name: selector,\n source: '',\n });\n\n if (rules[selector].atom) {\n // For atoms, we just directly insert cssText, to give the atomizer full control over the rules\n cssText += `${rules[selector].cssText}\\n`;\n } else {\n // Run each rule through stylis to support nesting\n cssText += `${preprocessor(selector, rules[selector].cssText)}\\n`;\n }\n });\n\n return {\n cssText,\n rules,\n\n get cssSourceMapText() {\n if (mappings?.length) {\n const generator = new SourceMapGenerator({\n file: options.filename.replace(/\\.js$/, '.css'),\n });\n\n mappings.forEach((mapping) =>\n generator.addMapping({ ...mapping, source: options.filename })\n );\n\n generator.setSourceContent(options.filename, originalCode);\n\n return generator.toString();\n }\n\n return '';\n },\n };\n}\n\n/**\n * Extract artifacts (e.g. CSS) from processors\n */\n// eslint-disable-next-line require-yield\nexport function* extract(\n this: IExtractAction\n): SyncScenarioForAction<IExtractAction> {\n const { options } = this.services;\n const { entrypoint } = this;\n const { processors } = this.data;\n const { loadedAndParsed } = entrypoint;\n if (loadedAndParsed.evaluator === 'ignored') {\n throw new Error('entrypoint was ignored');\n }\n\n let allRules: Rules = {};\n const allReplacements: Replacements = [];\n processors.forEach((processor) => {\n processor.artifacts.forEach((artifact) => {\n if (artifact[0] !== 'css') return;\n const [rules, replacements] = artifact[1] as [\n rules: Rules,\n sourceMapReplacements: Replacements,\n ];\n\n allRules = {\n ...allRules,\n ...rules,\n };\n\n allReplacements.push(...replacements);\n });\n });\n\n return {\n ...extractCssFromAst(allRules, loadedAndParsed.code, options),\n replacements: allReplacements,\n };\n}\n"],"mappings":";;;;;;AACA,IAAAA,UAAA,GAAAC,OAAA;AAMA,IAAAC,yBAAA,GAAAD,OAAA;AAEA,SAASE,iBAAiBA,CACxBC,KAAY,EACZC,YAAoB,EACpBC,OAAsE,EACT;EAC7D,MAAMC,QAAmB,GAAG,EAAE;EAE9B,IAAIC,OAAO,GAAG,EAAE;EAEhB,IAAIC,YAA4B;EAChC,IAAI,OAAOH,OAAO,CAACG,YAAY,KAAK,UAAU,EAAE;IAC9C;IACAA,YAAY,GAAGH,OAAO,CAACG,YAAY;EACrC,CAAC,MAAM;IACL,QAAQH,OAAO,CAACG,YAAY;MAC1B,KAAK,MAAM;QACTA,YAAY,GAAGA,CAACC,QAAQ,EAAEC,IAAI,KAAM,GAAED,QAAS,KAAIC,IAAK,KAAI;QAC5D;MACF,KAAK,QAAQ;MACb;QACEF,YAAY,GAAG,IAAAG,kDAAwB,EAACN,OAAO,CAAC;IACpD;EACF;EAEAO,MAAM,CAACC,IAAI,CAACV,KAAK,CAAC,CAACW,OAAO,CAAC,CAAC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EAAQ,CAAC,GAAG,IAAI,CAACgC,QAAQ;EACjC,MAAM;IAAEC;EAAW,CAAC,GAAG,IAAI;EAC3B,MAAM;IAAEC;EAAW,CAAC,GAAG,IAAI,CAACC,IAAI;EAChC,MAAM;IAAEC;EAAgB,CAAC,GAAGH,UAAU;EACtC,IAAIG,eAAe,CAACC,SAAS,KAAK,SAAS,EAAE;IAC3C,MAAM,IAAIC,KAAK,CAAC,wBAAwB,CAAC;EAC3C;EAEA,IAAIC,QAAe,GAAG,CAAC,CAAC;EACxB,MAAMC,eAA6B,GAAG,EAAE;EACxCN,UAAU,CAACzB,OAAO,CAAEgC,SAAS,IAAK;IAChCA,SAAS,CAACC,SAAS,CAACjC,OAAO,CAAEkC,QAAQ,IAAK;MACxC,IAAIA,QAAQ,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE;MAC3B,MAAM,CAAC7C,KAAK,EAAE8C,YAAY,CAAC,GAAGD,QAAQ,CAAC,CAAC,CAGvC;MAEDJ,QAAQ,GAAG;QACT,GAAGA,QAAQ;QACX,GAAGzC;MACL,CAAC;MAED0C,eAAe,CAAC7B,IAAI,CAAC,GAAGiC,YAAY,CAAC;IACvC,CAAC,CAAC;EACJ,CAAC,CAAC;EAEF,OAAO;IACL,GAAG/C,iBAAiB,CAAC0C,QAAQ,EAAEH,eAAe,CAACS,IAAI,EAAE7C,OAAO,CAAC;IAC7D4C,YAAY,EAAEJ;EAChB,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wyw-in-js/transform",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
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.2.2",
19
- "@wyw-in-js/shared": "0.2.2"
18
+ "@wyw-in-js/processor-utils": "0.2.3",
19
+ "@wyw-in-js/shared": "0.2.3"
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.2.2",
41
- "@wyw-in-js/eslint-config": "0.2.2",
42
- "@wyw-in-js/jest-preset": "0.2.2",
43
- "@wyw-in-js/ts-config": "0.2.2"
40
+ "@wyw-in-js/babel-config": "0.2.3",
41
+ "@wyw-in-js/eslint-config": "0.2.3",
42
+ "@wyw-in-js/jest-preset": "0.2.3",
43
+ "@wyw-in-js/ts-config": "0.2.3"
44
44
  },
45
45
  "engines": {
46
46
  "node": ">=16.0.0"
package/types/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export type { LoadAndParseFn } from './transform/Entrypoint.types';
17
17
  export { baseHandlers } from './transform/generators';
18
18
  export { prepareCode } from './transform/generators/transform';
19
19
  export { Entrypoint } from './transform/Entrypoint';
20
- export { transformUrl } from './transform/generators/extract';
20
+ export { transformUrl } from './transform/generators/createStylisPreprocessor';
21
21
  export { asyncResolveImports, syncResolveImports, } from './transform/generators/resolveImports';
22
22
  export { loadWywOptions } from './transform/helpers/loadWywOptions';
23
23
  export { withDefaultServices } from './transform/helpers/withDefaultServices';
package/types/index.js CHANGED
@@ -50,8 +50,8 @@ var transform_2 = require("./transform/generators/transform");
50
50
  Object.defineProperty(exports, "prepareCode", { enumerable: true, get: function () { return transform_2.prepareCode; } });
51
51
  var Entrypoint_1 = require("./transform/Entrypoint");
52
52
  Object.defineProperty(exports, "Entrypoint", { enumerable: true, get: function () { return Entrypoint_1.Entrypoint; } });
53
- var extract_1 = require("./transform/generators/extract");
54
- Object.defineProperty(exports, "transformUrl", { enumerable: true, get: function () { return extract_1.transformUrl; } });
53
+ var createStylisPreprocessor_1 = require("./transform/generators/createStylisPreprocessor");
54
+ Object.defineProperty(exports, "transformUrl", { enumerable: true, get: function () { return createStylisPreprocessor_1.transformUrl; } });
55
55
  var resolveImports_1 = require("./transform/generators/resolveImports");
56
56
  Object.defineProperty(exports, "asyncResolveImports", { enumerable: true, get: function () { return resolveImports_1.asyncResolveImports; } });
57
57
  Object.defineProperty(exports, "syncResolveImports", { enumerable: true, get: function () { return resolveImports_1.syncResolveImports; } });
@@ -263,6 +263,7 @@ function shakerPlugin(babel, { keepSideEffects = false, ifUnknownExport = 'skip-
263
263
  for (const binding of unreferenced) {
264
264
  if (binding.path.isVariableDeclarator() &&
265
265
  !forDeleting.includes(binding.path.get('id'))) {
266
+ forDeleting.push(...binding.constantViolations);
266
267
  forDeleting.push(binding.path.get('id'));
267
268
  changed = true;
268
269
  }
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ import * as path from 'path';
3
+ import type { Middleware } from 'stylis';
4
+ import type { Options } from '../../types';
5
+ export declare function transformUrl(url: string, outputFilename: string, sourceFilename: string, platformPath?: typeof path): string;
6
+ /**
7
+ * Stylis plugin that mimics :global() selector behavior from Stylis v3.
8
+ */
9
+ export declare const stylisGlobalPlugin: Middleware;
10
+ export declare function createStylisUrlReplacePlugin(filename: string, outputFilename: string | undefined): Middleware;
11
+ export declare function createStylisPreprocessor(options: Options): (selector: string, text: string) => string;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.createStylisPreprocessor = exports.createStylisUrlReplacePlugin = exports.stylisGlobalPlugin = exports.transformUrl = void 0;
27
+ const path = __importStar(require("path"));
28
+ const stylis_1 = require("stylis");
29
+ const POSIX_SEP = path.posix.sep;
30
+ function transformUrl(url, outputFilename, sourceFilename, platformPath = path) {
31
+ // Replace asset path with new path relative to the output CSS
32
+ const relative = platformPath.relative(platformPath.dirname(outputFilename),
33
+ // Get the absolute path to the asset from the path relative to the JS file
34
+ platformPath.resolve(platformPath.dirname(sourceFilename), url));
35
+ if (platformPath.sep === POSIX_SEP) {
36
+ return relative;
37
+ }
38
+ return relative.split(platformPath.sep).join(POSIX_SEP);
39
+ }
40
+ exports.transformUrl = transformUrl;
41
+ /**
42
+ * Stylis plugin that mimics :global() selector behavior from Stylis v3.
43
+ */
44
+ const stylisGlobalPlugin = (element) => {
45
+ function getGlobalSelectorModifiers(value) {
46
+ const match = value.match(/(&\f( )?)?:global\(/);
47
+ if (match === null) {
48
+ throw new Error(`Failed to match :global() selector in "${value}". Please report a bug if it happens.`);
49
+ }
50
+ const [, baseSelector, spaceDelimiter] = match;
51
+ return {
52
+ includeBaseSelector: !!baseSelector,
53
+ includeSpaceDelimiter: !!spaceDelimiter,
54
+ };
55
+ }
56
+ switch (element.type) {
57
+ case stylis_1.RULESET:
58
+ if (typeof element.props === 'string') {
59
+ if (process.env.NODE_ENV !== 'production') {
60
+ throw new Error(`"element.props" has type "string" (${JSON.stringify(element.props, null, 2)}), it's not expected. Please report a bug if it happens.`);
61
+ }
62
+ return;
63
+ }
64
+ Object.assign(element, {
65
+ props: element.props.map((cssSelector) => {
66
+ // Avoids calling tokenize() on every string
67
+ if (!cssSelector.includes(':global(')) {
68
+ return cssSelector;
69
+ }
70
+ if (element.children.length === 0) {
71
+ Object.assign(element, {
72
+ global: getGlobalSelectorModifiers(element.value),
73
+ });
74
+ return cssSelector;
75
+ }
76
+ const { includeBaseSelector, includeSpaceDelimiter } = element.parent?.global || getGlobalSelectorModifiers(element.value);
77
+ const tokens = (0, stylis_1.tokenize)(cssSelector);
78
+ let selector = '';
79
+ for (let i = 0, len = tokens.length; i < len; i++) {
80
+ const token = tokens[i];
81
+ //
82
+ // Match for ":global("
83
+ if (token === ':' && tokens[i + 1] === 'global') {
84
+ //
85
+ // Match for ":global()"
86
+ if (tokens[i + 2] === '()') {
87
+ selector = [
88
+ ...tokens.slice(i + 4),
89
+ includeSpaceDelimiter ? ' ' : '',
90
+ ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),
91
+ includeSpaceDelimiter ? '' : ' ',
92
+ ].join('');
93
+ break;
94
+ }
95
+ //
96
+ // Match for ":global(selector)"
97
+ selector = [
98
+ tokens[i + 2].slice(1, -1),
99
+ includeSpaceDelimiter ? ' ' : '',
100
+ ...(includeBaseSelector ? tokens.slice(0, i - 1) : []),
101
+ includeSpaceDelimiter ? '' : ' ',
102
+ ].join('');
103
+ break;
104
+ }
105
+ }
106
+ return selector;
107
+ }),
108
+ });
109
+ break;
110
+ default:
111
+ }
112
+ };
113
+ exports.stylisGlobalPlugin = stylisGlobalPlugin;
114
+ function createStylisUrlReplacePlugin(filename, outputFilename) {
115
+ return (element) => {
116
+ if (element.type === 'decl' && outputFilename) {
117
+ // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
118
+ // It'll allow css-loader to resolve an imported asset properly.
119
+ // eslint-disable-next-line no-param-reassign
120
+ element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, filename) + p4);
121
+ }
122
+ };
123
+ }
124
+ exports.createStylisUrlReplacePlugin = createStylisUrlReplacePlugin;
125
+ function createStylisPreprocessor(options) {
126
+ function stylisPreprocess(selector, text) {
127
+ const compiled = (0, stylis_1.compile)(`${selector} {${text}}\n`);
128
+ return (0, stylis_1.serialize)(compiled, (0, stylis_1.middleware)([
129
+ createStylisUrlReplacePlugin(options.filename, options.outputFilename),
130
+ exports.stylisGlobalPlugin,
131
+ stylis_1.prefixer,
132
+ stylis_1.stringify,
133
+ ]));
134
+ }
135
+ return stylisPreprocess;
136
+ }
137
+ exports.createStylisPreprocessor = createStylisPreprocessor;
@@ -1,7 +1,4 @@
1
- /// <reference types="node" />
2
- import path from 'path';
3
1
  import type { IExtractAction, SyncScenarioForAction } from '../types';
4
- export declare function transformUrl(url: string, outputFilename: string, sourceFilename: string, platformPath?: typeof path): string;
5
2
  /**
6
3
  * Extract artifacts (e.g. CSS) from processors
7
4
  */
@@ -1,43 +1,8 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.extract = exports.transformUrl = void 0;
7
- const path_1 = __importDefault(require("path"));
3
+ exports.extract = void 0;
8
4
  const source_map_1 = require("source-map");
9
- const stylis_1 = require("stylis");
10
- const posixSep = path_1.default.posix.sep;
11
- function transformUrl(url, outputFilename, sourceFilename, platformPath = path_1.default) {
12
- // Replace asset path with new path relative to the output CSS
13
- const relative = platformPath.relative(platformPath.dirname(outputFilename),
14
- // Get the absolute path to the asset from the path relative to the JS file
15
- platformPath.resolve(platformPath.dirname(sourceFilename), url));
16
- if (platformPath.sep === posixSep) {
17
- return relative;
18
- }
19
- return relative.split(platformPath.sep).join(posixSep);
20
- }
21
- exports.transformUrl = transformUrl;
22
- function createStylisPreprocessor(options) {
23
- function stylisPreprocess(selector, text) {
24
- const compiled = (0, stylis_1.compile)(`${selector} {${text}}\n`);
25
- return (0, stylis_1.serialize)(compiled, (0, stylis_1.middleware)([
26
- (element) => {
27
- const { outputFilename } = options;
28
- if (element.type === 'decl' && outputFilename) {
29
- // When writing to a file, we need to adjust the relative paths inside url(..) expressions.
30
- // It'll allow css-loader to resolve an imported asset properly.
31
- // eslint-disable-next-line no-param-reassign
32
- element.return = element.value.replace(/\b(url\((["']?))(\.[^)]+?)(\2\))/g, (match, p1, p2, p3, p4) => p1 + transformUrl(p3, outputFilename, options.filename) + p4);
33
- }
34
- },
35
- stylis_1.prefixer,
36
- stylis_1.stringify,
37
- ]));
38
- }
39
- return stylisPreprocess;
40
- }
5
+ const createStylisPreprocessor_1 = require("./createStylisPreprocessor");
41
6
  function extractCssFromAst(rules, originalCode, options) {
42
7
  const mappings = [];
43
8
  let cssText = '';
@@ -53,7 +18,7 @@ function extractCssFromAst(rules, originalCode, options) {
53
18
  break;
54
19
  case 'stylis':
55
20
  default:
56
- preprocessor = createStylisPreprocessor(options);
21
+ preprocessor = (0, createStylisPreprocessor_1.createStylisPreprocessor)(options);
57
22
  }
58
23
  }
59
24
  Object.keys(rules).forEach((selector, index) => {