Initial commit
This commit is contained in:
commit
afed023152
8152 files changed
+2086461
No files matched your search
+526
@@ -0,0 +1,526 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { pathToFileURL, fileURLToPath } from 'node:url';
|
||||
import MagicString from 'magic-string';
|
||||
import { walk } from 'estree-walker';
|
||||
import module$1, { isBuiltin, createRequire } from 'node:module';
|
||||
import { extname } from 'node:path';
|
||||
import { f as filterOutComments } from './chunk-helpers.js';
|
||||
|
||||
const isNodeInPatternWeakSet = new WeakSet();
|
||||
function setIsNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.add(node);
|
||||
}
|
||||
function isNodeInPattern(node) {
|
||||
return isNodeInPatternWeakSet.has(node);
|
||||
}
|
||||
/**
|
||||
* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
|
||||
* Except this is using acorn AST
|
||||
*/
|
||||
function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) {
|
||||
const parentStack = [];
|
||||
const varKindStack = [];
|
||||
const scopeMap = new WeakMap();
|
||||
const identifiers = [];
|
||||
const setScope = (node, name) => {
|
||||
let scopeIds = scopeMap.get(node);
|
||||
if (scopeIds && scopeIds.has(name)) {
|
||||
return;
|
||||
}
|
||||
if (!scopeIds) {
|
||||
scopeIds = new Set();
|
||||
scopeMap.set(node, scopeIds);
|
||||
}
|
||||
scopeIds.add(name);
|
||||
};
|
||||
function isInScope(name, parents) {
|
||||
return parents.some((node) => node && scopeMap.get(node)?.has(name));
|
||||
}
|
||||
function handlePattern(p, parentScope) {
|
||||
if (p.type === "Identifier") {
|
||||
setScope(parentScope, p.name);
|
||||
} else if (p.type === "RestElement") {
|
||||
handlePattern(p.argument, parentScope);
|
||||
} else if (p.type === "ObjectPattern") {
|
||||
p.properties.forEach((property) => {
|
||||
if (property.type === "RestElement") {
|
||||
setScope(parentScope, property.argument.name);
|
||||
} else {
|
||||
handlePattern(property.value, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "ArrayPattern") {
|
||||
p.elements.forEach((element) => {
|
||||
if (element) {
|
||||
handlePattern(element, parentScope);
|
||||
}
|
||||
});
|
||||
} else if (p.type === "AssignmentPattern") {
|
||||
handlePattern(p.left, parentScope);
|
||||
} else {
|
||||
setScope(parentScope, p.name);
|
||||
}
|
||||
}
|
||||
walk(root, {
|
||||
enter(node, parent) {
|
||||
if (node.type === "ImportDeclaration") {
|
||||
return this.skip();
|
||||
}
|
||||
// track parent stack, skip for "else-if"/"else" branches as acorn nests
|
||||
// the ast within "if" nodes instead of flattening them
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.unshift(parent);
|
||||
}
|
||||
// track variable declaration kind stack used by VariableDeclarator
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.unshift(node.kind);
|
||||
}
|
||||
if (node.type === "CallExpression") {
|
||||
onCallExpression?.(node);
|
||||
}
|
||||
if (node.type === "MetaProperty" && node.meta.name === "import") {
|
||||
onImportMeta?.(node);
|
||||
} else if (node.type === "ImportExpression") {
|
||||
onDynamicImport?.(node);
|
||||
}
|
||||
if (node.type === "Identifier") {
|
||||
if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) {
|
||||
// record the identifier, for DFS -> BFS
|
||||
identifiers.push([node, parentStack.slice(0)]);
|
||||
}
|
||||
} else if (node.type === "ClassDeclaration" && node.id) {
|
||||
// A class declaration name could shadow an import, so add its name to the parent scope
|
||||
const parentScope = findParentScope(parentStack);
|
||||
if (parentScope) {
|
||||
setScope(parentScope, node.id.name);
|
||||
}
|
||||
} else if (node.type === "ClassExpression" && node.id) {
|
||||
// A class expression name could shadow an import, so add its name to the scope
|
||||
setScope(node, node.id.name);
|
||||
} else if (isFunctionNode(node)) {
|
||||
// If it is a function declaration, it could be shadowing an import
|
||||
// Add its name to the scope so it won't get replaced
|
||||
if (node.type === "FunctionDeclaration") {
|
||||
const parentScope = findParentScope(parentStack);
|
||||
if (parentScope) {
|
||||
setScope(parentScope, node.id.name);
|
||||
}
|
||||
}
|
||||
// walk function expressions and add its arguments to known identifiers
|
||||
// so that we don't prefix them
|
||||
node.params.forEach((p) => {
|
||||
if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
|
||||
handlePattern(p, node);
|
||||
return;
|
||||
}
|
||||
walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
|
||||
// skip params default value of destructure
|
||||
if (parent?.type === "AssignmentPattern" && parent?.right === child) {
|
||||
return this.skip();
|
||||
}
|
||||
if (child.type !== "Identifier") {
|
||||
return;
|
||||
}
|
||||
// do not record as scope variable if is a destructuring keyword
|
||||
if (isStaticPropertyKey(child, parent)) {
|
||||
return;
|
||||
}
|
||||
// do not record if this is a default value
|
||||
// assignment of a destructuring variable
|
||||
if (parent?.type === "TemplateLiteral" && parent?.expressions.includes(child) || parent?.type === "CallExpression" && parent?.callee === child) {
|
||||
return;
|
||||
}
|
||||
setScope(node, child.name);
|
||||
} });
|
||||
});
|
||||
} else if (node.type === "Property" && parent.type === "ObjectPattern") {
|
||||
// mark property in destructuring pattern
|
||||
setIsNodeInPattern(node);
|
||||
} else if (node.type === "VariableDeclarator") {
|
||||
const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
|
||||
if (parentFunction) {
|
||||
handlePattern(node.id, parentFunction);
|
||||
}
|
||||
} else if (node.type === "CatchClause" && node.param) {
|
||||
handlePattern(node.param, node);
|
||||
}
|
||||
},
|
||||
leave(node, parent) {
|
||||
// untrack parent stack from above
|
||||
if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
|
||||
parentStack.shift();
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
varKindStack.shift();
|
||||
}
|
||||
}
|
||||
});
|
||||
// emit the identifier events in BFS so the hoisted declarations
|
||||
// can be captured correctly
|
||||
identifiers.forEach(([node, stack]) => {
|
||||
if (!isInScope(node.name, stack)) {
|
||||
const parent = stack[0];
|
||||
const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack));
|
||||
const classDeclaration = parent.type === "ClassDeclaration" && node === parent.superClass;
|
||||
const classExpression = parent.type === "ClassExpression" && node === parent.id;
|
||||
onIdentifier?.(node, {
|
||||
hasBindingShortcut,
|
||||
classDeclaration,
|
||||
classExpression
|
||||
}, stack);
|
||||
}
|
||||
});
|
||||
}
|
||||
function isRefIdentifier(id, parent, parentStack) {
|
||||
// declaration id
|
||||
if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
if (isFunctionNode(parent)) {
|
||||
// function declaration/expression id
|
||||
if (parent.id === id) {
|
||||
return false;
|
||||
}
|
||||
// params list
|
||||
if (parent.params.includes(id)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// class method name
|
||||
if (parent.type === "MethodDefinition" && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
// class property
|
||||
if (parent.type === "PropertyDefinition" && !parent.computed) {
|
||||
// Default values can still reference identifiers
|
||||
return id === parent.value;
|
||||
}
|
||||
// property key
|
||||
if (isStaticPropertyKey(id, parent)) {
|
||||
return false;
|
||||
}
|
||||
// object destructuring pattern
|
||||
if (isNodeInPattern(parent) && parent.value === id) {
|
||||
return false;
|
||||
}
|
||||
// non-assignment array destructuring pattern
|
||||
if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) {
|
||||
return false;
|
||||
}
|
||||
// member expression property
|
||||
if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
|
||||
return false;
|
||||
}
|
||||
if (parent.type === "ExportSpecifier") {
|
||||
return false;
|
||||
}
|
||||
// is a special keyword but parsed as identifier
|
||||
if (id.name === "arguments") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isStaticProperty(node) {
|
||||
return node && node.type === "Property" && !node.computed;
|
||||
}
|
||||
function isStaticPropertyKey(node, parent) {
|
||||
return isStaticProperty(parent) && parent.key === node;
|
||||
}
|
||||
const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
|
||||
function isFunctionNode(node) {
|
||||
return functionNodeTypeRE.test(node.type);
|
||||
}
|
||||
const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
|
||||
function isBlock(node) {
|
||||
return blockNodeTypeRE.test(node.type);
|
||||
}
|
||||
function findParentScope(parentStack, isVar = false) {
|
||||
return parentStack.find(isVar ? isFunctionNode : isBlock);
|
||||
}
|
||||
function isInDestructuringAssignment(parent, parentStack) {
|
||||
if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) {
|
||||
return parentStack.some((i) => i.type === "AssignmentExpression");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getArbitraryModuleIdentifier(node) {
|
||||
return node.type === "Identifier" ? node.name : node.raw;
|
||||
}
|
||||
|
||||
/* cjs-module-lexer 2.2.1 */
|
||||
let A$1;const B$1=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$1(E,g="@"){if(!A$1)throw new Error("Not initialized");const w=E.length+1,D=(A$1.__heap_base.value||A$1.__heap_base)+4*w-A$1.memory.buffer.byteLength;D>0&&A$1.memory.grow(Math.ceil(D/65536));const G=A$1.sa(w);(B$1?C$1:I)(E,new Uint16Array(A$1.memory.buffer,G,w));const S=A$1.parseCJS(G,E.length,0,0,0);if(S){const B=new Error(`Parse error ${g}${A$1.e()}:${E.slice(0,A$1.e()).split("\n").length}:${A$1.e()-E.lastIndexOf("\n",A$1.e()-1)}`);throw Object.assign(B,{idx:A$1.e()}),5!==S&&6!==S&&7!==S||Object.assign(B,{code:"ERR_LEXER_ESM_SYNTAX"}),B}let o=new Set,R=new Set,y=new Set;for(;A$1.rre();){const B=Q$1(E.slice(A$1.res(),A$1.ree()));B&&R.add(B);}for(;A$1.ru();)y.add(Q$1(E.slice(A$1.us(),A$1.ue())));for(;A$1.re();){let B=Q$1(E.slice(A$1.es(),A$1.ee()));void 0===B||y.has(B)||o.add(B);}return {exports:[...o],reexports:[...R]}}function Q$1(A){if('"'!==A[0]&&"'"!==A[0])return A;try{const B=function(A){const B=A[0];if('"'===B)try{return JSON.parse(A)}catch{}else if("'"===B&&A.length>1&&"'"===A[A.length-1]&&-1===A.indexOf('"'))try{return JSON.parse('"'+A.slice(1,-1)+'"')}catch{}let Q="",g={v:1};for(;g.v<A.length;){const I=A[g.v];switch(I){case B:return Q;case "\\":++g.v,Q+=E$1(A,g);break;case "\r":case "\n":throw new SyntaxError;default:++g.v,Q+=I;}}throw new SyntaxError}(A);for(let A=0;A<B.length;A++){const Q=64512&B.charCodeAt(A);if(!(Q<55296)){if(55296!==Q)return;if(56320!=(64512&B.charCodeAt(++A)))return}}return B}catch{}}function E$1(A,B){if(B.v===A.length)throw new SyntaxError;const Q=A[B.v];switch(++B.v,Q){case "\r":"\n"===A[B.v]&&++B.v;case "\n":case "\u2028":case "\u2029":return "";case "r":return "\r";case "n":return "\n";case "t":return "\t";case "b":return "\b";case "f":return "\f";case "v":return "\v";case "x":return function(A,B){const Q=g(A[B.v]);++B.v;const E=g(A[B.v]);return ++B.v,String.fromCodePoint(16*Q+E)}(A,B);case "u":return function(A,B){let Q=0;if("{"===A[B.v]){++B.v;do{if(Q=16*Q+g(A[B.v]),Q>1114111)throw new SyntaxError;++B.v;}while("}"!==A[B.v]);++B.v;}else for(let E=0;E<4;++E)Q=16*Q+g(A[B.v]),++B.v;return String.fromCodePoint(Q)}(A,B);case "0":case "1":case "2":case "3":case "4":case "5":case "6":case "7":return function(A,B,Q){let E=A<="3"?2:1,g=+A;do{if((A=B[Q.v])<"0"||A>"7")break;g=8*g+ +A,++Q.v,--E;}while(E>0);return String.fromCodePoint(g)}(Q,A,B);default:return Q}}function g(A){if(A>="0"&&A<="9")return +A;if(A>="a"&&A<="f")return A.charCodeAt(0)-87;if(A>="A"&&A<="F")return A.charCodeAt(0)-55;throw new SyntaxError}function I(A,B){const Q=A.length;let E=0;for(;E<Q;){const Q=A.charCodeAt(E);B[E++]=(255&Q)<<8|Q>>>8;}}function C$1(A,B){const Q=A.length;let E=0;for(;E<Q;)B[E]=A.charCodeAt(E++);}function w(){const A="AGFzbQEAAAABXA1gAX8Bf2ACf38AYAABf2AAAGABfwBgBn9/f39/fwF/YAJ/fwF/YAd/f39/f39/AX9gA39/fwF/YAh/f39/f39/fwF/YAV/f39/fwF/YAR/f39/AX9gBH9/f38AAzMyAQEBAwAABAUJBAAEBAMDAAcCAAAICgAFAAAGBQsHBgAAAAAIAAICAgICAgICAgIFDAYEBQFwAQUFBQMBAAEGCAF/AEHQmAILB1wOBm1lbW9yeQIAC19faGVhcF9iYXNlAwACc2EAJAFlACUCZXMAJgJlZQAnA3JlcwAoA3JlZQApAnVzACoCdWUAKwJyZQAsA3JyZQAtAnJ1AC4IcGFyc2VDSlMALwkKAQBBAQsEAAECAwwBAgrJkwEyDgAgACABQcgfQcAfEDALDgAgACABQdQfQcwfEDALDgAgACABQeAfQdgfEDALEgBBzB9BADYCAEHUH0EANgIAC8wBAQN/AkBBvKABKAIAIgNBAmpB5QBB8QBB9QBB6QBB8gBB5QAQEARAQbygASADQQ5qNgIAAkAQEUEoRw0AQbygAUG8oAEoAgBBAmo2AgAQESEBQbygASgCACECIAFBJ0cgAUEiR3ENACABEAxBvKABQbygASgCAEECaiIBNgIAEBFBKUcNAAJAIABBAWsOAgMDAAtBtKABKAIAIAI2AgBBtKABKAIAIAE2AgRBAQ8LQbygASADNgIAC0EADwsgAiABQaAfKAIAEQEAQQELGwAgAEGYHygCAEYEQEEBDwsgAEECay8BABAPC/8CAQV/QZgfKAIAIQQDQAJAIABBAmshASAALwEAIgJBIEcNACAAIARLIAEhAA0BCwsCQCACQT1HDQADQAJAIAFBAmshACABLwEAQSBHDQAgASAESyAAIQENAQsLIABBAmohASAAQQRqIQNBACECA0ACQCABLwEAIgBBgPgDcUGAuANGBEAgAEH/B3EgAUECay8BAEH/B3FBCnRyQYCABGohAAsgAEUgASAETXINACAAQdwARg0CIAAQEkUNACABQX5BfCAAQYCABEkbaiEBIAAQEyECDAELCyACQQFxRQ0AIAEvAQBBIEcNAEG0oAEoAgAiAkGwHygCAEYNACACIAM2AgwgAiABQQJqNgIIA0ACQCABQQJrIQAgAS8BACIDQSBHDQAgASAESyAAIQENAQsLAkACQAJAIANB8gBrDgMAAwEDCyAAQfYAQeEAEBQNAQwCCyAAQewAQeUAEBQNACAAQeMAQe8AQe4AQfMAEBVFDQELQbSgASACQRBqNgIACws7AQF/AkAgAC8BACABRw0AIAAvAQIgAkcNACAALwEEIANHDQAgAC8BBiAERw0AIAAvAQggBUYhBgsgBgtPAQF/AkAgAC8BACABRw0AIAAvAQIgAkcNACAALwEEIANHDQAgAC8BBiAERw0AIAAvAQggBUcNACAALwEKIAZHDQAgAC8BDCAHRiEICyAIC7MFAQN/QbygAUG8oAEoAgAiAkEOajYCAAJAAkAQESIBQdsARwRAIAFBPUYNASABQS5HDQJBvKABQbygASgCAEECajYCABARQbygASgCACEBEBZFDQJBvKABKAIAIQAQEUE9Rw0CIAEgAEGcHygCABEBAA8LQbygAUG8oAEoAgBBAmo2AgAQESIAQSdHIABBIkdxDQFBvKABKAIAIAAQDEG8oAFBvKABKAIAQQJqIgA2AgAQEUHdAEcNAUG8oAFBvKABKAIAQQJqNgIAEBFBPUcNASAAQZwfKAIAEQEADAELIABFDQBBqB8oAgARAwBBvKABQbygASgCAEECajYCABARIgBB8gBHBEAgAEH7AEcNAUG8oAEoAgBBAmshAQJAAkADQEG8oAFBvKABKAIAIgBBAmo2AgAgAEHAoAEoAgBPDQIQESEAQbygASgCACECAkAgABAWBEBBvKABKAIAIQMQESIAQTpGBEBBvKABQbygASgCAEECajYCABAREBZFDQRBvKABKAIALwEAIQALIAIgA0GcHygCABEBAAwBCwJAIABBIkcEQCAAQS5GDQEgAEEnRw0EC0G8oAEoAgAgABAMQbygAUG8oAEoAgBBAmoiAzYCABARIgBBOkcNAUG8oAFBvKABKAIAQQJqNgIAEBEQFkUNA0G8oAEoAgAvAQAhACADQZwfKAIAEQEADAELQbygASgCACIALwECQS5HDQIgAC8BBEEuRw0CQbygASAAQQLine truncated
|
||||
|
||||
/* es-module-lexer 2.3.2 */
|
||||
(function(A){return A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase",A[A.StaticDeferPhase=6]="StaticDeferPhase",A[A.DynamicDeferPhase=7]="DynamicDeferPhase",A})({});const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse(C,g="@"){if(!E)return init.then(()=>parse(C,g));const I=C.length+1,w=(E.__heap_base.value||E.__heap_base)+4*I-E.memory.buffer.byteLength;w>0&&E.memory.grow(Math.ceil(w/65536));const D=E.sa(I-1);if("undefined"!=typeof Buffer?Buffer.from(E.memory.buffer,D,2*(I-1)).write(C,"utf16le"):(A?Q:B)(C,new Uint16Array(E.memory.buffer,D,I)),!E.parse())throw Object.assign(new Error(`Parse error ${g}:${C.slice(0,E.e()).split("\n").length}:${E.e()-C.lastIndexOf("\n",E.e()-1)}`),{idx:E.e()});const o=[],G=[];for(;E.ri();){const A=E.is(),B=E.ie(),Q=E.it(),g=E.ai(),I=E.id(),w=E.ss(),D=E.se();let G;E.ip()&&(G=i(C.slice(-1===I?A-1:A,-1===I?B+1:B)));let J=null;for(J=[],E.rsa();E.ra();){const A=E.aks(),B=E.ake(),Q=E.avs(),g=E.ave();J.push([s(C.slice(A,B)),s(C.slice(Q,g))]);}0===J.length&&(J=null),o.push({n:G,t:Q,s:A,e:B,ss:w,se:D,d:I,a:g,at:J});}for(;E.re();){const A=E.es(),B=E.ee(),Q=E.els(),g=E.ele(),I=Q<0?void 0:s(C.slice(Q,g)),w=s(C.slice(A,B));G.push({s:A,e:B,ls:Q,le:g,ss:E.ess(),n:w,ln:I});}function i(A){try{return (0,eval)(A)}catch(A){}}function s(A){if(!A)return A;const B=A[0];return ('"'===B||"'"===B)&&i(A)||A}return [o,G,!!E.f(),!!E.ms()]}function B(A,B){const Q=A.length;let E=0;for(;E<Q;){const Q=A.charCodeAt(E);B[E++]=(255&Q)<<8|Q>>>8;}}function Q(A,B){const Q=A.length;let E=0;for(;E<Q;)B[E]=A.charCodeAt(E++);}let E;const C=()=>{return A="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFN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IDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogA
Line truncated
|
||||
|
||||
async function initSyntaxLexers() {
|
||||
await Promise.all([init$1(), init]);
|
||||
}
|
||||
const isTransform = process.execArgv.includes("--experimental-transform-types") || process.env.NODE_OPTIONS?.includes("--experimental-transform-types");
|
||||
function transformCode(code, filename) {
|
||||
const ext = extname(filename.split("?")[0]);
|
||||
const isTs = ext === ".ts" || ext === ".cts" || ext === ".mts";
|
||||
if (!isTs) {
|
||||
return code;
|
||||
}
|
||||
if (!module$1.stripTypeScriptTypes) {
|
||||
throw new Error(`Cannot parse '${filename}' because "module.stripTypeScriptTypes" is not supported. Module mocking requires Node.js 22.15 or higher. This is NOT a bug of Vitest.`);
|
||||
}
|
||||
return module$1.stripTypeScriptTypes(code, { mode: isTransform ? "transform" : "strip" });
|
||||
}
|
||||
const cachedFileExports = new Map();
|
||||
function collectModuleExports(filename, code, format, exports = []) {
|
||||
if (format === "module") {
|
||||
const [imports_, exports_] = parse(code, filename);
|
||||
const fileExports = [...exports_.map((p) => p.n)];
|
||||
imports_.forEach(({ ss: start, se: end, n: name }) => {
|
||||
const substring = code.substring(start, end).replace(/ +/g, " ");
|
||||
if (name && substring.startsWith("export *") && !substring.startsWith("export * as")) {
|
||||
fileExports.push(...tryParseModule(name));
|
||||
}
|
||||
});
|
||||
cachedFileExports.set(filename, fileExports);
|
||||
exports.push(...fileExports);
|
||||
} else {
|
||||
const { exports: exports_, reexports } = parse$1(code, filename);
|
||||
const fileExports = [...exports_];
|
||||
reexports.forEach((name) => {
|
||||
fileExports.push(...tryParseModule(name));
|
||||
});
|
||||
cachedFileExports.set(filename, fileExports);
|
||||
exports.push(...fileExports);
|
||||
}
|
||||
function tryParseModule(name) {
|
||||
try {
|
||||
return parseModule(name);
|
||||
} catch (error) {
|
||||
console.warn(`[module mocking] Failed to parse '${name}' imported from ${filename}:`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
let __require;
|
||||
function getModuleRequire() {
|
||||
return __require ??= createRequire(filename);
|
||||
}
|
||||
function parseModule(name) {
|
||||
if (isBuiltin(name)) {
|
||||
if (cachedFileExports.has(name)) {
|
||||
const cachedExports = cachedFileExports.get(name);
|
||||
return cachedExports;
|
||||
}
|
||||
const builtinModule = getBuiltinModule(name);
|
||||
const builtinExports = Object.keys(builtinModule);
|
||||
cachedFileExports.set(name, builtinExports);
|
||||
return builtinExports;
|
||||
}
|
||||
const resolvedModuleUrl = format === "module" ? import.meta.resolve(name, pathToFileURL(filename).toString()) : getModuleRequire().resolve(name);
|
||||
const resolvedModulePath = format === "commonjs" ? resolvedModuleUrl : fileURLToPath(resolvedModuleUrl);
|
||||
if (cachedFileExports.has(resolvedModulePath)) {
|
||||
return cachedFileExports.get(resolvedModulePath);
|
||||
}
|
||||
const fileContent = readFileSync(resolvedModulePath, "utf-8");
|
||||
const ext = extname(resolvedModulePath);
|
||||
const code = transformCode(fileContent, resolvedModulePath);
|
||||
if (code == null) {
|
||||
cachedFileExports.set(resolvedModulePath, []);
|
||||
return [];
|
||||
}
|
||||
const resolvedModuleFormat = resolveModuleFormat(resolvedModulePath, code);
|
||||
if (ext === ".json") {
|
||||
return ["default"];
|
||||
} else {
|
||||
// can't do wasm, for example
|
||||
console.warn(`Cannot process '${resolvedModuleFormat}' imported from ${filename} because of unknown file extension: ${ext}.`);
|
||||
}
|
||||
if (resolvedModuleFormat) {
|
||||
return collectModuleExports(resolvedModulePath, code, resolvedModuleFormat, exports);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return Array.from(new Set(exports));
|
||||
}
|
||||
function resolveModuleFormat(url, code) {
|
||||
const ext = extname(url);
|
||||
if (ext === ".cjs" || ext === ".cts") {
|
||||
return "commonjs";
|
||||
} else if (ext === ".mjs" || ext === ".mts") {
|
||||
return "module";
|
||||
} else if (ext === ".js" || ext === ".ts" || ext === "") {
|
||||
if (!module$1.findPackageJSON) {
|
||||
throw new Error(`Cannot parse the module format of '${url}' because "module.findPackageJSON" is not available. Upgrade to Node 22.14 to use this feature. This is NOT a bug of Vitest.`);
|
||||
}
|
||||
const pkgJsonPath = module$1.findPackageJSON(url);
|
||||
const pkgJson = pkgJsonPath ? JSON.parse(readFileSync(pkgJsonPath, "utf-8")) : {};
|
||||
if (pkgJson?.type === "module") {
|
||||
return "module";
|
||||
} else if (pkgJson?.type === "commonjs") {
|
||||
return "commonjs";
|
||||
} else {
|
||||
// Ambiguous input! Check if it has ESM syntax. Node.js is much smarter here,
|
||||
// but we don't need to run the code, so we can be more relaxed
|
||||
if (hasESM(filterOutComments(code))) {
|
||||
return "module";
|
||||
} else {
|
||||
return "commonjs";
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
let __globalRequire;
|
||||
function getBuiltinModule(moduleId) {
|
||||
__globalRequire ??= module$1.createRequire(import.meta.url);
|
||||
return __globalRequire(moduleId);
|
||||
}
|
||||
const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
|
||||
function hasESM(code) {
|
||||
return ESM_RE.test(code);
|
||||
}
|
||||
|
||||
// TODO: better source map replacement
|
||||
function automockModule(code, mockType, parse, options = {}) {
|
||||
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (cause) {
|
||||
if (options.id) {
|
||||
throw new Error(`failed to parse ${options.id}`, { cause });
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
const m = new MagicString(code);
|
||||
const allSpecifiers = [];
|
||||
const replacers = [];
|
||||
let importIndex = 0;
|
||||
for (const _node of ast.body) {
|
||||
if (_node.type === "ExportAllDeclaration") {
|
||||
const node = _node;
|
||||
// TODO: pass it down in the browser mode
|
||||
if (!options.id) {
|
||||
throw new Error(`automocking files with \`export *\` is not supported because it cannot be easily statically analysed`);
|
||||
}
|
||||
const source = node.source.value;
|
||||
if (typeof source !== "string") {
|
||||
throw new TypeError(`unknown source type while automocking: ${source}`);
|
||||
}
|
||||
const moduleUrl = import.meta.resolve(source, pathToFileURL(options.id).toString());
|
||||
const modulePath = fileURLToPath(moduleUrl);
|
||||
const moduleContent = readFileSync(modulePath, "utf-8");
|
||||
const transformedCode = transformCode(moduleContent, moduleUrl);
|
||||
const moduleFormat = resolveModuleFormat(moduleUrl, transformedCode);
|
||||
const moduleExports = collectModuleExports(modulePath, transformedCode, moduleFormat || "module");
|
||||
replacers.push(() => {
|
||||
const importNames = [];
|
||||
moduleExports.forEach((exportName) => {
|
||||
const isReexported = allSpecifiers.some(({ name, alias }) => name === exportName || alias === exportName);
|
||||
if (!isReexported) {
|
||||
importNames.push(exportName);
|
||||
allSpecifiers.push({ name: exportName });
|
||||
}
|
||||
});
|
||||
const importString = `import { ${importNames.join(", ")} } from '${source}';`;
|
||||
m.overwrite(node.start, node.end, importString);
|
||||
});
|
||||
}
|
||||
if (_node.type === "ExportNamedDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
function traversePattern(expression) {
|
||||
// export const test = '1'
|
||||
if (expression.type === "Identifier") {
|
||||
allSpecifiers.push({ name: expression.name });
|
||||
} else if (expression.type === "ArrayPattern") {
|
||||
expression.elements.forEach((element) => {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
traversePattern(element);
|
||||
});
|
||||
} else if (expression.type === "ObjectPattern") {
|
||||
expression.properties.forEach((property) => {
|
||||
// export const { ...rest } = {}
|
||||
if (property.type === "RestElement") {
|
||||
traversePattern(property);
|
||||
} else if (property.type === "Property") {
|
||||
traversePattern(property.value);
|
||||
} else ;
|
||||
});
|
||||
} else if (expression.type === "RestElement") {
|
||||
traversePattern(expression.argument);
|
||||
} else if (expression.type === "AssignmentPattern") {
|
||||
throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`);
|
||||
} else if (expression.type === "MemberExpression") {
|
||||
throw new Error(`MemberExpression is not supported. Please open a new bug report.`);
|
||||
} else ;
|
||||
}
|
||||
if (declaration) {
|
||||
if (declaration.type === "FunctionDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else if (declaration.type === "VariableDeclaration") {
|
||||
declaration.declarations.forEach((declaration) => {
|
||||
traversePattern(declaration.id);
|
||||
});
|
||||
} else if (declaration.type === "ClassDeclaration") {
|
||||
allSpecifiers.push({ name: declaration.id.name });
|
||||
} else ;
|
||||
m.remove(node.start, declaration.start);
|
||||
}
|
||||
const specifiers = node.specifiers || [];
|
||||
const source = node.source;
|
||||
if (!source && specifiers.length) {
|
||||
specifiers.forEach((specifier) => {
|
||||
allSpecifiers.push({
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported),
|
||||
name: getArbitraryModuleIdentifier(specifier.local)
|
||||
});
|
||||
});
|
||||
m.remove(node.start, node.end);
|
||||
} else if (source && specifiers.length) {
|
||||
const importNames = [];
|
||||
specifiers.forEach((specifier) => {
|
||||
const importedName = `__vitest_imported_${importIndex++}__`;
|
||||
importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]);
|
||||
allSpecifiers.push({
|
||||
name: importedName,
|
||||
alias: getArbitraryModuleIdentifier(specifier.exported)
|
||||
});
|
||||
});
|
||||
const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`;
|
||||
m.overwrite(node.start, node.end, importString);
|
||||
}
|
||||
}
|
||||
if (_node.type === "ExportDefaultDeclaration") {
|
||||
const node = _node;
|
||||
const declaration = node.declaration;
|
||||
allSpecifiers.push({
|
||||
name: "__vitest_default",
|
||||
alias: "default"
|
||||
});
|
||||
m.overwrite(node.start, declaration.start, `const __vitest_default = `);
|
||||
}
|
||||
}
|
||||
replacers.forEach((cb) => cb());
|
||||
const moduleObject = `
|
||||
const __vitest_current_es_module__ = {
|
||||
__esModule: true,
|
||||
${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")}
|
||||
}
|
||||
const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}")
|
||||
`;
|
||||
const assigning = allSpecifiers.map(({ name }, index) => {
|
||||
return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`;
|
||||
}).join("\n");
|
||||
const redeclarations = allSpecifiers.map(({ name, alias }, index) => {
|
||||
return ` __vitest_mocked_${index}__ as ${alias || name},`;
|
||||
}).join("\n");
|
||||
const specifiersExports = `
|
||||
export {
|
||||
${redeclarations}
|
||||
}
|
||||
`;
|
||||
m.append(moduleObject + assigning + specifiersExports);
|
||||
return m;
|
||||
}
|
||||
|
||||
export { automockModule as a, collectModuleExports as c, esmWalker as e, initSyntaxLexers as i };
|
||||
Reference in new issue
Block a user