@tscircuit/eval 0.0.1029 → 0.0.1030
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/dist/blob-url.js +1 -1
- package/dist/eval/index.js +64 -8
- package/dist/lib/index.js +64 -8
- package/dist/webworker/entrypoint.js +5 -2
- package/package.json +1 -1
|
@@ -939,7 +939,10 @@ ${namesToRegister.map(({variableName,uniqueLocalName})=>` reactHotLoader.regist
|
|
|
939
939
|
leaveModule(module);
|
|
940
940
|
})();`}process(){return!1}};var RESERVED_WORDS=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","enum","implements","interface","let","package","private","protected","public","static","await","false","null","true"]);function isIdentifier(name){if(name.length===0||!IS_IDENTIFIER_START[name.charCodeAt(0)])return!1;for(let i5=1;i5<name.length;i5++)if(!IS_IDENTIFIER_CHAR[name.charCodeAt(i5)])return!1;return!RESERVED_WORDS.has(name)}var TypeScriptTransformer=class extends Transformer{constructor(rootTransformer,tokens,isImportsTransformEnabled){super(),this.rootTransformer=rootTransformer,this.tokens=tokens,this.isImportsTransformEnabled=isImportsTransformEnabled}process(){return this.rootTransformer.processPossibleArrowParamEnd()||this.rootTransformer.processPossibleAsyncArrowWithTypeParams()||this.rootTransformer.processPossibleTypeRange()?!0:this.tokens.matches1(TokenType._public)||this.tokens.matches1(TokenType._protected)||this.tokens.matches1(TokenType._private)||this.tokens.matches1(TokenType._abstract)||this.tokens.matches1(TokenType._readonly)||this.tokens.matches1(TokenType._override)||this.tokens.matches1(TokenType.nonNullAssertion)?(this.tokens.removeInitialToken(),!0):this.tokens.matches1(TokenType._enum)||this.tokens.matches2(TokenType._const,TokenType._enum)?(this.processEnum(),!0):this.tokens.matches2(TokenType._export,TokenType._enum)||this.tokens.matches3(TokenType._export,TokenType._const,TokenType._enum)?(this.processEnum(!0),!0):!1}processEnum(isExport=!1){for(this.tokens.removeInitialToken();this.tokens.matches1(TokenType._const)||this.tokens.matches1(TokenType._enum);)this.tokens.removeToken();let enumName=this.tokens.identifierName();this.tokens.removeToken(),isExport&&!this.isImportsTransformEnabled&&this.tokens.appendCode("export "),this.tokens.appendCode(`var ${enumName}; (function (${enumName})`),this.tokens.copyExpectedToken(TokenType.braceL),this.processEnumBody(enumName),this.tokens.copyExpectedToken(TokenType.braceR),isExport&&this.isImportsTransformEnabled?this.tokens.appendCode(`)(${enumName} || (exports.${enumName} = ${enumName} = {}));`):this.tokens.appendCode(`)(${enumName} || (${enumName} = {}));`)}processEnumBody(enumName){let previousValueCode=null;for(;!this.tokens.matches1(TokenType.braceR);){let{nameStringCode,variableName}=this.extractEnumKeyInfo(this.tokens.currentToken());this.tokens.removeInitialToken(),this.tokens.matches3(TokenType.eq,TokenType.string,TokenType.comma)||this.tokens.matches3(TokenType.eq,TokenType.string,TokenType.braceR)?this.processStringLiteralEnumMember(enumName,nameStringCode,variableName):this.tokens.matches1(TokenType.eq)?this.processExplicitValueEnumMember(enumName,nameStringCode,variableName):this.processImplicitValueEnumMember(enumName,nameStringCode,variableName,previousValueCode),this.tokens.matches1(TokenType.comma)&&this.tokens.removeToken(),variableName!=null?previousValueCode=variableName:previousValueCode=`${enumName}[${nameStringCode}]`}}extractEnumKeyInfo(nameToken){if(nameToken.type===TokenType.name){let name=this.tokens.identifierNameForToken(nameToken);return{nameStringCode:`"${name}"`,variableName:isIdentifier(name)?name:null}}else if(nameToken.type===TokenType.string){let name=this.tokens.stringValueForToken(nameToken);return{nameStringCode:this.tokens.code.slice(nameToken.start,nameToken.end),variableName:isIdentifier(name)?name:null}}else throw new Error("Expected name or string at beginning of enum element.")}processStringLiteralEnumMember(enumName,nameStringCode,variableName){variableName!=null?(this.tokens.appendCode(`const ${variableName}`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(`; ${enumName}[${nameStringCode}] = ${variableName};`)):(this.tokens.appendCode(`${enumName}[${nameStringCode}]`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(";"))}processExplicitValueEnumMember(enumName,nameStringCode,variableName){let rhsEndIndex=this.tokens.currentToken().rhsEndIndex;if(rhsEndIndex==null)throw new Error("Expected rhsEndIndex on enum assign.");if(variableName!=null){for(this.tokens.appendCode(`const ${variableName}`),this.tokens.copyToken();this.tokens.currentIndex()<rhsEndIndex;)this.rootTransformer.processToken();this.tokens.appendCode(`; ${enumName}[${enumName}[${nameStringCode}] = ${variableName}] = ${nameStringCode};`)}else{for(this.tokens.appendCode(`${enumName}[${enumName}[${nameStringCode}]`),this.tokens.copyToken();this.tokens.currentIndex()<rhsEndIndex;)this.rootTransformer.processToken();this.tokens.appendCode(`] = ${nameStringCode};`)}}processImplicitValueEnumMember(enumName,nameStringCode,variableName,previousValueCode){let valueCode=previousValueCode!=null?`${previousValueCode} + 1`:"0";variableName!=null&&(this.tokens.appendCode(`const ${variableName} = ${valueCode}; `),valueCode=variableName),this.tokens.appendCode(`${enumName}[${enumName}[${nameStringCode}] = ${valueCode}] = ${nameStringCode};`)}};var RootTransformer=class _RootTransformer{__init(){this.transformers=[]}__init2(){this.generatedVariables=[]}constructor(sucraseContext,transforms,enableLegacyBabel5ModuleInterop,options){_RootTransformer.prototype.__init.call(this),_RootTransformer.prototype.__init2.call(this),this.nameManager=sucraseContext.nameManager,this.helperManager=sucraseContext.helperManager;let{tokenProcessor,importProcessor}=sucraseContext;this.tokens=tokenProcessor,this.isImportsTransformEnabled=transforms.includes("imports"),this.isReactHotLoaderTransformEnabled=transforms.includes("react-hot-loader"),this.disableESTransforms=!!options.disableESTransforms,options.disableESTransforms||(this.transformers.push(new OptionalChainingNullishTransformer(tokenProcessor,this.nameManager)),this.transformers.push(new NumericSeparatorTransformer(tokenProcessor)),this.transformers.push(new OptionalCatchBindingTransformer(tokenProcessor,this.nameManager))),transforms.includes("jsx")&&(options.jsxRuntime!=="preserve"&&this.transformers.push(new JSXTransformer(this,tokenProcessor,importProcessor,this.nameManager,options)),this.transformers.push(new ReactDisplayNameTransformer(this,tokenProcessor,importProcessor,options)));let reactHotLoaderTransformer=null;if(transforms.includes("react-hot-loader")){if(!options.filePath)throw new Error("filePath is required when using the react-hot-loader transform.");reactHotLoaderTransformer=new ReactHotLoaderTransformer(tokenProcessor,options.filePath),this.transformers.push(reactHotLoaderTransformer)}if(transforms.includes("imports")){if(importProcessor===null)throw new Error("Expected non-null importProcessor with imports transform enabled.");this.transformers.push(new CJSImportTransformer(this,tokenProcessor,importProcessor,this.nameManager,this.helperManager,reactHotLoaderTransformer,enableLegacyBabel5ModuleInterop,!!options.enableLegacyTypeScriptModuleInterop,transforms.includes("typescript"),transforms.includes("flow"),!!options.preserveDynamicImport,!!options.keepUnusedImports))}else this.transformers.push(new ESMImportTransformer(tokenProcessor,this.nameManager,this.helperManager,reactHotLoaderTransformer,transforms.includes("typescript"),transforms.includes("flow"),!!options.keepUnusedImports,options));transforms.includes("flow")&&this.transformers.push(new FlowTransformer(this,tokenProcessor,transforms.includes("imports"))),transforms.includes("typescript")&&this.transformers.push(new TypeScriptTransformer(this,tokenProcessor,transforms.includes("imports"))),transforms.includes("jest")&&this.transformers.push(new JestHoistTransformer(this,tokenProcessor,this.nameManager,importProcessor))}transform(){this.tokens.reset(),this.processBalancedCode();let prefix=this.isImportsTransformEnabled?'"use strict";':"";for(let transformer of this.transformers)prefix+=transformer.getPrefixCode();prefix+=this.helperManager.emitHelpers(),prefix+=this.generatedVariables.map(v5=>` var ${v5};`).join("");for(let transformer of this.transformers)prefix+=transformer.getHoistedCode();let suffix="";for(let transformer of this.transformers)suffix+=transformer.getSuffixCode();let result=this.tokens.finish(),{code}=result;if(code.startsWith("#!")){let newlineIndex=code.indexOf(`
|
|
941
941
|
`);return newlineIndex===-1&&(newlineIndex=code.length,code+=`
|
|
942
|
-
`),{code:code.slice(0,newlineIndex+1)+prefix+code.slice(newlineIndex+1)+suffix,mappings:this.shiftMappings(result.mappings,prefix.length)}}else return{code:prefix+code+suffix,mappings:this.shiftMappings(result.mappings,prefix.length)}}processBalancedCode(){let braceDepth=0,parenDepth=0;for(;!this.tokens.isAtEnd();){if(this.tokens.matches1(TokenType.braceL)||this.tokens.matches1(TokenType.dollarBraceL))braceDepth++;else if(this.tokens.matches1(TokenType.braceR)){if(braceDepth===0)return;braceDepth--}if(this.tokens.matches1(TokenType.parenL))parenDepth++;else if(this.tokens.matches1(TokenType.parenR)){if(parenDepth===0)return;parenDepth--}this.processToken()}}processToken(){if(this.tokens.matches1(TokenType._class)){this.processClass();return}for(let transformer of this.transformers)if(transformer.process())return;this.tokens.copyToken()}processNamedClass(){if(!this.tokens.matches2(TokenType._class,TokenType.name))throw new Error("Expected identifier for exported class name.");let name=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.processClass(),name}processClass(){let classInfo=getClassInfo(this,this.tokens,this.nameManager,this.disableESTransforms),needsCommaExpression=(classInfo.headerInfo.isExpression||!classInfo.headerInfo.className)&&classInfo.staticInitializerNames.length+classInfo.instanceInitializerNames.length>0,className=classInfo.headerInfo.className;needsCommaExpression&&(className=this.nameManager.claimFreeName("_class"),this.generatedVariables.push(className),this.tokens.appendCode(` (${className} =`));let contextId=this.tokens.currentToken().contextId;if(contextId==null)throw new Error("Expected class to have a context ID.");for(this.tokens.copyExpectedToken(TokenType._class);!this.tokens.matchesContextIdAndLabel(TokenType.braceL,contextId);)this.processToken();this.processClassBody(classInfo,className);let staticInitializerStatements=classInfo.staticInitializerNames.map(name=>`${className}.${name}()`);needsCommaExpression?this.tokens.appendCode(`, ${staticInitializerStatements.map(s4=>`${s4}, `).join("")}${className})`):classInfo.staticInitializerNames.length>0&&this.tokens.appendCode(` ${staticInitializerStatements.map(s4=>`${s4};`).join(" ")}`)}processClassBody(classInfo,className){let{headerInfo,constructorInsertPos,constructorInitializerStatements,fields,instanceInitializerNames,rangesToRemove}=classInfo,fieldIndex=0,rangeToRemoveIndex=0,classContextId=this.tokens.currentToken().contextId;if(classContextId==null)throw new Error("Expected non-null context ID on class.");this.tokens.copyExpectedToken(TokenType.braceL),this.isReactHotLoaderTransformEnabled&&this.tokens.appendCode("__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}");let needsConstructorInit=constructorInitializerStatements.length+instanceInitializerNames.length>0;if(constructorInsertPos===null&&needsConstructorInit){let constructorInitializersCode=this.makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className);if(headerInfo.hasSuperclass){let argsName=this.nameManager.claimFreeName("args");this.tokens.appendCode(`constructor(...${argsName}) { super(...${argsName}); ${constructorInitializersCode}; }`)}else this.tokens.appendCode(`constructor() { ${constructorInitializersCode}; }`)}for(;!this.tokens.matchesContextIdAndLabel(TokenType.braceR,classContextId);)if(fieldIndex<fields.length&&this.tokens.currentIndex()===fields[fieldIndex].start){let needsCloseBrace=!1;for(this.tokens.matches1(TokenType.bracketL)?this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this`):this.tokens.matches1(TokenType.string)||this.tokens.matches1(TokenType.num)?(this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this[`),needsCloseBrace=!0):this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this.`);this.tokens.currentIndex()<fields[fieldIndex].end;)needsCloseBrace&&this.tokens.currentIndex()===fields[fieldIndex].equalsIndex&&this.tokens.appendCode("]"),this.processToken();this.tokens.appendCode("}"),fieldIndex++}else if(rangeToRemoveIndex<rangesToRemove.length&&this.tokens.currentIndex()>=rangesToRemove[rangeToRemoveIndex].start){for(this.tokens.currentIndex()<rangesToRemove[rangeToRemoveIndex].end&&this.tokens.removeInitialToken();this.tokens.currentIndex()<rangesToRemove[rangeToRemoveIndex].end;)this.tokens.removeToken();rangeToRemoveIndex++}else this.tokens.currentIndex()===constructorInsertPos?(this.tokens.copyToken(),needsConstructorInit&&this.tokens.appendCode(`;${this.makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className)};`),this.processToken()):this.processToken();this.tokens.copyExpectedToken(TokenType.braceR)}makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className){return[...constructorInitializerStatements,...instanceInitializerNames.map(name=>`${className}.prototype.${name}.call(this)`)].join(";")}processPossibleArrowParamEnd(){if(this.tokens.matches2(TokenType.parenR,TokenType.colon)&&this.tokens.tokenAtRelativeIndex(1).isType){let nextNonTypeIndex=this.tokens.currentIndex()+1;for(;this.tokens.tokens[nextNonTypeIndex].isType;)nextNonTypeIndex++;if(this.tokens.matches1AtIndex(nextNonTypeIndex,TokenType.arrow)){for(this.tokens.removeInitialToken();this.tokens.currentIndex()<nextNonTypeIndex;)this.tokens.removeToken();return this.tokens.replaceTokenTrimmingLeftWhitespace(") =>"),!0}}return!1}processPossibleAsyncArrowWithTypeParams(){if(!this.tokens.matchesContextual(ContextualKeyword._async)&&!this.tokens.matches1(TokenType._async))return!1;let nextToken2=this.tokens.tokenAtRelativeIndex(1);if(nextToken2.type!==TokenType.lessThan||!nextToken2.isType)return!1;let nextNonTypeIndex=this.tokens.currentIndex()+1;for(;this.tokens.tokens[nextNonTypeIndex].isType;)nextNonTypeIndex++;if(this.tokens.matches1AtIndex(nextNonTypeIndex,TokenType.parenL)){for(this.tokens.replaceToken("async ("),this.tokens.removeInitialToken();this.tokens.currentIndex()<nextNonTypeIndex;)this.tokens.removeToken();return this.tokens.removeToken(),this.processBalancedCode(),this.processToken(),!0}return!1}processPossibleTypeRange(){if(this.tokens.currentToken().isType){for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return!0}return!1}shiftMappings(mappings,prefixLength){for(let i5=0;i5<mappings.length;i5++){let mapping=mappings[i5];mapping!==void 0&&(mappings[i5]=mapping+prefixLength)}return mappings}};var import_lines_and_columns=__toESM(require_build());function getTSImportedNames(tokens){let importedNames=new Set;for(let i5=0;i5<tokens.tokens.length;i5++)tokens.matches1AtIndex(i5,TokenType._import)&&!tokens.matches3AtIndex(i5,TokenType._import,TokenType.name,TokenType.eq)&&collectNamesForImport(tokens,i5,importedNames);return importedNames}function collectNamesForImport(tokens,index,importedNames){index++,!tokens.matches1AtIndex(index,TokenType.parenL)&&(tokens.matches1AtIndex(index,TokenType.name)&&(importedNames.add(tokens.identifierNameAtIndex(index)),index++,tokens.matches1AtIndex(index,TokenType.comma)&&index++),tokens.matches1AtIndex(index,TokenType.star)&&(index+=2,importedNames.add(tokens.identifierNameAtIndex(index)),index++),tokens.matches1AtIndex(index,TokenType.braceL)&&(index++,collectNamesForNamedImport(tokens,index,importedNames)))}function collectNamesForNamedImport(tokens,index,importedNames){for(;;){if(tokens.matches1AtIndex(index,TokenType.braceR))return;let specifierInfo=getImportExportSpecifierInfo(tokens,index);if(index=specifierInfo.endIndex,specifierInfo.isType||importedNames.add(specifierInfo.rightName),tokens.matches2AtIndex(index,TokenType.comma,TokenType.braceR))return;if(tokens.matches1AtIndex(index,TokenType.braceR))return;if(tokens.matches1AtIndex(index,TokenType.comma))index++;else throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`)}}function transform6(code,options){validateOptions(options);try{let sucraseContext=getSucraseContext(code,options),transformerResult=new RootTransformer(sucraseContext,options.transforms,!!options.enableLegacyBabel5ModuleInterop,options).transform(),result={code:transformerResult.code};if(options.sourceMapOptions){if(!options.filePath)throw new Error("filePath must be specified when generating a source map.");result={...result,sourceMap:computeSourceMap(transformerResult,options.filePath,options.sourceMapOptions,code,sucraseContext.tokenProcessor.tokens)}}return result}catch(e6){throw options.filePath&&(e6.message=`Error transforming ${options.filePath}: ${e6.message}`),e6}}function getSucraseContext(code,options){let isJSXEnabled2=options.transforms.includes("jsx"),isTypeScriptEnabled2=options.transforms.includes("typescript"),isFlowEnabled2=options.transforms.includes("flow"),disableESTransforms=options.disableESTransforms===!0,file=parse4(code,isJSXEnabled2,isTypeScriptEnabled2,isFlowEnabled2),tokens=file.tokens,scopes=file.scopes,nameManager=new NameManager(code,tokens),helperManager=new HelperManager(nameManager),tokenProcessor=new TokenProcessor(code,tokens,isFlowEnabled2,disableESTransforms,helperManager),enableLegacyTypeScriptModuleInterop=!!options.enableLegacyTypeScriptModuleInterop,importProcessor=null;return options.transforms.includes("imports")?(importProcessor=new CJSImportProcessor(nameManager,tokenProcessor,enableLegacyTypeScriptModuleInterop,options,options.transforms.includes("typescript"),!!options.keepUnusedImports,helperManager),importProcessor.preprocessTokens(),identifyShadowedGlobals(tokenProcessor,scopes,importProcessor.getGlobalNames()),options.transforms.includes("typescript")&&!options.keepUnusedImports&&importProcessor.pruneTypeOnlyImports()):options.transforms.includes("typescript")&&!options.keepUnusedImports&&identifyShadowedGlobals(tokenProcessor,scopes,getTSImportedNames(tokenProcessor)),{tokenProcessor,scopes,nameManager,importProcessor,helperManager}}var TS_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts"]),JSX_EXTENSIONS=new Set([".tsx",".jsx",".ts"]),TYPE_STAR_EXPORT_REGEX=/^\s*export\s+type\s+\*\s+(?:as\s+[\w$]+\s+)?from\s+['"][^'"]+['"]\s*;?\s*$/gim,stripTypeStarExports=code=>code.replace(TYPE_STAR_EXPORT_REGEX,""),stripQueryAndHash=filePath=>{let queryIndex=filePath.indexOf("?"),hashIndex=filePath.indexOf("#"),endIndex=filePath.length;return queryIndex!==-1&&hashIndex!==-1?endIndex=Math.min(queryIndex,hashIndex):queryIndex!==-1?endIndex=queryIndex:hashIndex!==-1&&(endIndex=hashIndex),filePath.slice(0,endIndex)},getExtension=filePath=>{let normalizedPath=stripQueryAndHash(filePath),lastDotIndex=normalizedPath.lastIndexOf(".");return lastDotIndex===-1||Math.max(normalizedPath.lastIndexOf("/"),normalizedPath.lastIndexOf("\\"))>lastDotIndex?"":normalizedPath.slice(lastDotIndex).toLowerCase()},getTransformsForFilePath=filePath=>{let extension=getExtension(filePath),transforms=["imports"];return TS_EXTENSIONS.has(extension)&&transforms.unshift("typescript"),JSX_EXTENSIONS.has(extension)&&transforms.push("jsx"),transforms},transformWithSucrase=(code,filePath)=>{let transforms=getTransformsForFilePath(filePath),sanitizedCode=stripTypeStarExports(code),{code:transformedCode}=transform6(sanitizedCode,{filePath,disableESTransforms:!0,production:!0,transforms});return transformedCode};var getImportsFromCode=code=>{let strippedCode=stripComments(code),importRegex=/(?:^|[;\n\r}])\s*import\s*(?:(?:[\w$]+\s*,\s*)?(?:\*\s*as\s+[\w$]+|\{[^}]+\}|[\w$]+)\s*from\s*)?['"]([^'"]+)['"]/gm,imports=[],match2;for(;(match2=importRegex.exec(strippedCode))!==null;){let fullMatch=match2[0];/\bimport\s+type\b/.test(fullMatch)||imports.push(match2[1])}let reExportRegex=/^\s*export\s+(?:type\s+)?(?:\*\s+as\s+[\w$]+|\*|\{[^}]+\})\s+from\s*['"](.+?)['"]/gm,reExportMatch;for(;(reExportMatch=reExportRegex.exec(strippedCode))!==null;){let fullMatch=reExportMatch[0];/^\s*export\s+type\b/.test(fullMatch)||imports.push(reExportMatch[1])}let requireRegex=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,requireMatch=requireRegex.exec(strippedCode);for(;requireMatch!==null;)imports.push(requireMatch[1]),requireMatch=requireRegex.exec(strippedCode);return imports};var getTypeExportsFromCode=code=>{let strippedCode=stripComments(code),typeExports=[],exportTypeRegex=/export\s+type\s+(\w+)\s*(?:=|<)/g,match2;for(;(match2=exportTypeRegex.exec(strippedCode))!==null;)typeExports.push(match2[1]);let exportInterfaceRegex=/export\s+interface\s+(\w+)/g;for(;(match2=exportInterfaceRegex.exec(strippedCode))!==null;)typeExports.push(match2[1]);return typeExports};var normalizePackageEntrypoint=entrypoint=>entrypoint.replace(/^\.\//,"");function getBrowserMappedEntrypoint(packageJson){if(!packageJson.browser||typeof packageJson.browser=="string")return null;let entryPoint=packageJson.module||packageJson.main||"index.js",browserEntrypoint=packageJson.browser[entryPoint];if(typeof browserEntrypoint=="string")return browserEntrypoint;let normalizedEntryPoint=normalizePackageEntrypoint(entryPoint),normalizedBrowserEntrypoint=packageJson.browser[`./${normalizedEntryPoint}`]??packageJson.browser[normalizedEntryPoint];return typeof normalizedBrowserEntrypoint=="string"?normalizedBrowserEntrypoint:null}function createContext(modulePath,fsMap,basePath){return{fsMap,extensions:[".js",".jsx",".ts",".tsx",".json"],basePath,modulePath}}function findPackageJson(nodeModulesPath,ctx){let packageJsonPath=`${nodeModulesPath}/package.json`;if(!ctx.fsMap[packageJsonPath])return null;try{return JSON.parse(ctx.fsMap[packageJsonPath])}catch{return null}}function tryResolveWithExtensions(path,ctx){if(ctx.fsMap[path])return path;for(let ext of ctx.extensions){let pathWithExt=path.replace(/\.js$|\.jsx$/,"")+ext;if(ctx.fsMap[pathWithExt])return pathWithExt}return null}function resolveExportPath(nodeModulesPath,exportPath,ctx){let fullExportPath=`${nodeModulesPath}/${exportPath.replace(/^\.\//,"")}`;return tryResolveWithExtensions(fullExportPath,ctx)}function resolveConditionalExport(exportValue){if(typeof exportValue=="string")return exportValue;let conditions=["import","default","require","node","browser"];for(let condition of conditions)if(exportValue[condition]){let conditionValue=exportValue[condition];if(typeof conditionValue=="string")return conditionValue;let resolved=resolveConditionalExport(conditionValue);if(resolved)return resolved}return null}function resolvePackageExports(nodeModulesPath,packageJson,remainingPath,ctx){if(!packageJson.exports)return null;let defaultExport=packageJson.exports["."];if(remainingPath===""&&defaultExport){let exportPath=resolveConditionalExport(defaultExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}let subpathExport=remainingPath?packageJson.exports[`./${remainingPath}`]:null;if(subpathExport){let exportPath=resolveConditionalExport(subpathExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}let importExport=packageJson.exports.import;if(remainingPath===""&&importExport!==void 0){let exportPath=resolveConditionalExport(importExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}return null}function resolvePackageEntryPoint(nodeModulesPath,packageJson,ctx){let entryPoint=normalizePackageEntrypoint(typeof packageJson.browser=="string"&&packageJson.browser||getBrowserMappedEntrypoint(packageJson)||packageJson.module||packageJson.main||"index.js"),fullPath=`${nodeModulesPath}/${entryPoint}`;return tryResolveWithExtensions(fullPath,ctx)}function resolveRemainingPath(nodeModulesPath,remainingPath,ctx){if(!remainingPath){for(let ext of ctx.extensions){let indexPath=`${nodeModulesPath}/index${ext}`;if(ctx.fsMap[indexPath])return indexPath}return null}let fullPath=`${nodeModulesPath}/${remainingPath}`,directMatch=tryResolveWithExtensions(fullPath,ctx);if(directMatch)return directMatch;for(let ext of ctx.extensions){let indexPath=`${fullPath}/index${ext}`;if(ctx.fsMap[indexPath])return indexPath}return null}function resolveNodeModuleInPath(searchPath,ctx){let moduleParts=ctx.modulePath.split("/"),scope=moduleParts[0].startsWith("@")?moduleParts.slice(0,2).join("/"):moduleParts[0],remainingPath=moduleParts.slice(scope.includes("/")?2:1).join("/"),nodeModulesPath=`${searchPath==="."?"":`${searchPath}/`}node_modules/${scope}`,packageJson=findPackageJson(nodeModulesPath,ctx);if(packageJson){let exportsResolution=resolvePackageExports(nodeModulesPath,packageJson,remainingPath,ctx);if(exportsResolution)return exportsResolution;let entryPointResolution=resolvePackageEntryPoint(nodeModulesPath,packageJson,ctx);if(entryPointResolution)return entryPointResolution}let remainingPathResolution=resolveRemainingPath(nodeModulesPath,remainingPath,ctx);if(remainingPathResolution)return remainingPathResolution;let parentPath=dirname(searchPath);return parentPath&&parentPath!==searchPath?resolveNodeModuleInPath(parentPath,ctx):null}function resolveNodeModule(modulePath,fsMap,basePath){let ctx=createContext(modulePath,fsMap,basePath);return resolveNodeModuleInPath(ctx.basePath,ctx)}var hasPreSuppliedImport=(preSuppliedImports,importName)=>Object.prototype.hasOwnProperty.call(preSuppliedImports,importName);function evalCompiledJs(compiledCode,preSuppliedImports,cwd){globalThis.__tscircuit_require=name=>{let resolvedFilePath=resolveFilePath(name,preSuppliedImports,cwd);!resolvedFilePath&&!name.startsWith(".")&&!name.startsWith("/")&&(resolvedFilePath=resolveNodeModule(name,preSuppliedImports,cwd||""));let hasResolvedFilePath=resolvedFilePath&&hasPreSuppliedImport(preSuppliedImports,resolvedFilePath);if(!hasPreSuppliedImport(preSuppliedImports,name)&&!hasResolvedFilePath)throw new Error(`Import "${name}" not found ${cwd?`in "${cwd}"`:""}`);let mod=hasPreSuppliedImport(preSuppliedImports,name)?preSuppliedImports[name]:preSuppliedImports[resolvedFilePath];if(mod.__esModule&&mod.default!==void 0){let modKeys=Object.keys(mod);if(modKeys.length===2&&modKeys.includes("__esModule")&&modKeys.includes("default"))return mod.default}if(mod.default&&typeof mod.default=="function"){let callableWrapper=(...args)=>mod.default(...args);return Object.assign(callableWrapper,mod),callableWrapper.__esModule=!0,callableWrapper}return new Proxy(mod,{get(target,prop){if(!(prop in target)){if(prop==="default")return target.default!==void 0?target.default:target.__esModule?void 0:typeof target=="function"||typeof target=="object"?target:void 0;if(prop==="__esModule")return!0;if(prop==="__typeOnlyExports__")return target.__typeOnlyExports__||[];let typeExports=target.__typeOnlyExports__||[],propName=String(prop);throw typeExports.includes(propName)?new Error(`"${propName}" is a type exported by "${name}" and cannot be imported as a value.
|
|
942
|
+
`),{code:code.slice(0,newlineIndex+1)+prefix+code.slice(newlineIndex+1)+suffix,mappings:this.shiftMappings(result.mappings,prefix.length)}}else return{code:prefix+code+suffix,mappings:this.shiftMappings(result.mappings,prefix.length)}}processBalancedCode(){let braceDepth=0,parenDepth=0;for(;!this.tokens.isAtEnd();){if(this.tokens.matches1(TokenType.braceL)||this.tokens.matches1(TokenType.dollarBraceL))braceDepth++;else if(this.tokens.matches1(TokenType.braceR)){if(braceDepth===0)return;braceDepth--}if(this.tokens.matches1(TokenType.parenL))parenDepth++;else if(this.tokens.matches1(TokenType.parenR)){if(parenDepth===0)return;parenDepth--}this.processToken()}}processToken(){if(this.tokens.matches1(TokenType._class)){this.processClass();return}for(let transformer of this.transformers)if(transformer.process())return;this.tokens.copyToken()}processNamedClass(){if(!this.tokens.matches2(TokenType._class,TokenType.name))throw new Error("Expected identifier for exported class name.");let name=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.processClass(),name}processClass(){let classInfo=getClassInfo(this,this.tokens,this.nameManager,this.disableESTransforms),needsCommaExpression=(classInfo.headerInfo.isExpression||!classInfo.headerInfo.className)&&classInfo.staticInitializerNames.length+classInfo.instanceInitializerNames.length>0,className=classInfo.headerInfo.className;needsCommaExpression&&(className=this.nameManager.claimFreeName("_class"),this.generatedVariables.push(className),this.tokens.appendCode(` (${className} =`));let contextId=this.tokens.currentToken().contextId;if(contextId==null)throw new Error("Expected class to have a context ID.");for(this.tokens.copyExpectedToken(TokenType._class);!this.tokens.matchesContextIdAndLabel(TokenType.braceL,contextId);)this.processToken();this.processClassBody(classInfo,className);let staticInitializerStatements=classInfo.staticInitializerNames.map(name=>`${className}.${name}()`);needsCommaExpression?this.tokens.appendCode(`, ${staticInitializerStatements.map(s4=>`${s4}, `).join("")}${className})`):classInfo.staticInitializerNames.length>0&&this.tokens.appendCode(` ${staticInitializerStatements.map(s4=>`${s4};`).join(" ")}`)}processClassBody(classInfo,className){let{headerInfo,constructorInsertPos,constructorInitializerStatements,fields,instanceInitializerNames,rangesToRemove}=classInfo,fieldIndex=0,rangeToRemoveIndex=0,classContextId=this.tokens.currentToken().contextId;if(classContextId==null)throw new Error("Expected non-null context ID on class.");this.tokens.copyExpectedToken(TokenType.braceL),this.isReactHotLoaderTransformEnabled&&this.tokens.appendCode("__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}");let needsConstructorInit=constructorInitializerStatements.length+instanceInitializerNames.length>0;if(constructorInsertPos===null&&needsConstructorInit){let constructorInitializersCode=this.makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className);if(headerInfo.hasSuperclass){let argsName=this.nameManager.claimFreeName("args");this.tokens.appendCode(`constructor(...${argsName}) { super(...${argsName}); ${constructorInitializersCode}; }`)}else this.tokens.appendCode(`constructor() { ${constructorInitializersCode}; }`)}for(;!this.tokens.matchesContextIdAndLabel(TokenType.braceR,classContextId);)if(fieldIndex<fields.length&&this.tokens.currentIndex()===fields[fieldIndex].start){let needsCloseBrace=!1;for(this.tokens.matches1(TokenType.bracketL)?this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this`):this.tokens.matches1(TokenType.string)||this.tokens.matches1(TokenType.num)?(this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this[`),needsCloseBrace=!0):this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this.`);this.tokens.currentIndex()<fields[fieldIndex].end;)needsCloseBrace&&this.tokens.currentIndex()===fields[fieldIndex].equalsIndex&&this.tokens.appendCode("]"),this.processToken();this.tokens.appendCode("}"),fieldIndex++}else if(rangeToRemoveIndex<rangesToRemove.length&&this.tokens.currentIndex()>=rangesToRemove[rangeToRemoveIndex].start){for(this.tokens.currentIndex()<rangesToRemove[rangeToRemoveIndex].end&&this.tokens.removeInitialToken();this.tokens.currentIndex()<rangesToRemove[rangeToRemoveIndex].end;)this.tokens.removeToken();rangeToRemoveIndex++}else this.tokens.currentIndex()===constructorInsertPos?(this.tokens.copyToken(),needsConstructorInit&&this.tokens.appendCode(`;${this.makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className)};`),this.processToken()):this.processToken();this.tokens.copyExpectedToken(TokenType.braceR)}makeConstructorInitCode(constructorInitializerStatements,instanceInitializerNames,className){return[...constructorInitializerStatements,...instanceInitializerNames.map(name=>`${className}.prototype.${name}.call(this)`)].join(";")}processPossibleArrowParamEnd(){if(this.tokens.matches2(TokenType.parenR,TokenType.colon)&&this.tokens.tokenAtRelativeIndex(1).isType){let nextNonTypeIndex=this.tokens.currentIndex()+1;for(;this.tokens.tokens[nextNonTypeIndex].isType;)nextNonTypeIndex++;if(this.tokens.matches1AtIndex(nextNonTypeIndex,TokenType.arrow)){for(this.tokens.removeInitialToken();this.tokens.currentIndex()<nextNonTypeIndex;)this.tokens.removeToken();return this.tokens.replaceTokenTrimmingLeftWhitespace(") =>"),!0}}return!1}processPossibleAsyncArrowWithTypeParams(){if(!this.tokens.matchesContextual(ContextualKeyword._async)&&!this.tokens.matches1(TokenType._async))return!1;let nextToken2=this.tokens.tokenAtRelativeIndex(1);if(nextToken2.type!==TokenType.lessThan||!nextToken2.isType)return!1;let nextNonTypeIndex=this.tokens.currentIndex()+1;for(;this.tokens.tokens[nextNonTypeIndex].isType;)nextNonTypeIndex++;if(this.tokens.matches1AtIndex(nextNonTypeIndex,TokenType.parenL)){for(this.tokens.replaceToken("async ("),this.tokens.removeInitialToken();this.tokens.currentIndex()<nextNonTypeIndex;)this.tokens.removeToken();return this.tokens.removeToken(),this.processBalancedCode(),this.processToken(),!0}return!1}processPossibleTypeRange(){if(this.tokens.currentToken().isType){for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return!0}return!1}shiftMappings(mappings,prefixLength){for(let i5=0;i5<mappings.length;i5++){let mapping=mappings[i5];mapping!==void 0&&(mappings[i5]=mapping+prefixLength)}return mappings}};var import_lines_and_columns=__toESM(require_build());function getTSImportedNames(tokens){let importedNames=new Set;for(let i5=0;i5<tokens.tokens.length;i5++)tokens.matches1AtIndex(i5,TokenType._import)&&!tokens.matches3AtIndex(i5,TokenType._import,TokenType.name,TokenType.eq)&&collectNamesForImport(tokens,i5,importedNames);return importedNames}function collectNamesForImport(tokens,index,importedNames){index++,!tokens.matches1AtIndex(index,TokenType.parenL)&&(tokens.matches1AtIndex(index,TokenType.name)&&(importedNames.add(tokens.identifierNameAtIndex(index)),index++,tokens.matches1AtIndex(index,TokenType.comma)&&index++),tokens.matches1AtIndex(index,TokenType.star)&&(index+=2,importedNames.add(tokens.identifierNameAtIndex(index)),index++),tokens.matches1AtIndex(index,TokenType.braceL)&&(index++,collectNamesForNamedImport(tokens,index,importedNames)))}function collectNamesForNamedImport(tokens,index,importedNames){for(;;){if(tokens.matches1AtIndex(index,TokenType.braceR))return;let specifierInfo=getImportExportSpecifierInfo(tokens,index);if(index=specifierInfo.endIndex,specifierInfo.isType||importedNames.add(specifierInfo.rightName),tokens.matches2AtIndex(index,TokenType.comma,TokenType.braceR))return;if(tokens.matches1AtIndex(index,TokenType.braceR))return;if(tokens.matches1AtIndex(index,TokenType.comma))index++;else throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`)}}function transform6(code,options){validateOptions(options);try{let sucraseContext=getSucraseContext(code,options),transformerResult=new RootTransformer(sucraseContext,options.transforms,!!options.enableLegacyBabel5ModuleInterop,options).transform(),result={code:transformerResult.code};if(options.sourceMapOptions){if(!options.filePath)throw new Error("filePath must be specified when generating a source map.");result={...result,sourceMap:computeSourceMap(transformerResult,options.filePath,options.sourceMapOptions,code,sucraseContext.tokenProcessor.tokens)}}return result}catch(e6){throw options.filePath&&(e6.message=`Error transforming ${options.filePath}: ${e6.message}`),e6}}function getSucraseContext(code,options){let isJSXEnabled2=options.transforms.includes("jsx"),isTypeScriptEnabled2=options.transforms.includes("typescript"),isFlowEnabled2=options.transforms.includes("flow"),disableESTransforms=options.disableESTransforms===!0,file=parse4(code,isJSXEnabled2,isTypeScriptEnabled2,isFlowEnabled2),tokens=file.tokens,scopes=file.scopes,nameManager=new NameManager(code,tokens),helperManager=new HelperManager(nameManager),tokenProcessor=new TokenProcessor(code,tokens,isFlowEnabled2,disableESTransforms,helperManager),enableLegacyTypeScriptModuleInterop=!!options.enableLegacyTypeScriptModuleInterop,importProcessor=null;return options.transforms.includes("imports")?(importProcessor=new CJSImportProcessor(nameManager,tokenProcessor,enableLegacyTypeScriptModuleInterop,options,options.transforms.includes("typescript"),!!options.keepUnusedImports,helperManager),importProcessor.preprocessTokens(),identifyShadowedGlobals(tokenProcessor,scopes,importProcessor.getGlobalNames()),options.transforms.includes("typescript")&&!options.keepUnusedImports&&importProcessor.pruneTypeOnlyImports()):options.transforms.includes("typescript")&&!options.keepUnusedImports&&identifyShadowedGlobals(tokenProcessor,scopes,getTSImportedNames(tokenProcessor)),{tokenProcessor,scopes,nameManager,importProcessor,helperManager}}var TS_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts"]),JSX_EXTENSIONS=new Set([".tsx",".jsx",".ts"]),TYPE_STAR_EXPORT_REGEX=/^\s*export\s+type\s+\*\s+(?:as\s+[\w$]+\s+)?from\s+['"][^'"]+['"]\s*;?\s*$/gim,stripTypeStarExports=code=>code.replace(TYPE_STAR_EXPORT_REGEX,""),getJsxCommentRepairCandidates=code=>{let candidates=[],jsxCommentRegex=/\{\/\*[\s\S]*?\*\/\}/g;for(let match2 of code.matchAll(jsxCommentRegex)){let commentStart=match2.index,commentEnd=commentStart+match2[0].length,commentBody=match2[0].slice(3,-3);candidates.push(`${code.slice(0,commentStart)}/* ${commentBody} */${code.slice(commentEnd)}`)}return candidates},getSyntaxErrorMessage=error2=>error2.message.replace(/^Error transforming [^:]+:\s*/,"").replace(/\s*\(\d+:\d+\)$/,""),createCodeFrame=(code,line2,column)=>{let lines=code.split(/\r?\n/),firstLine=Math.max(1,line2-2),lastLine=Math.min(lines.length,line2+2),lineNumberWidth=String(lastLine).length,frame=[];for(let lineNumber=firstLine;lineNumber<=lastLine;lineNumber++){let marker=lineNumber===line2?">":" ";frame.push(`${marker} ${String(lineNumber).padStart(lineNumberWidth)} | ${lines[lineNumber-1]}`),lineNumber===line2&&frame.push(` ${" ".repeat(lineNumberWidth)} | ${" ".repeat(Math.max(0,column-1))}^`)}return frame.join(`
|
|
943
|
+
`)},createHelpfulSyntaxError=(error2,code,filePath)=>{let line2=error2.loc?.line,column=error2.loc?.column;return typeof line2!="number"||typeof column!="number"?error2:new SyntaxError(`Syntax error in "${filePath}" at ${line2}:${column}: ${getSyntaxErrorMessage(error2)}
|
|
944
|
+
|
|
945
|
+
${createCodeFrame(code,line2,column)}`)},stripQueryAndHash=filePath=>{let queryIndex=filePath.indexOf("?"),hashIndex=filePath.indexOf("#"),endIndex=filePath.length;return queryIndex!==-1&&hashIndex!==-1?endIndex=Math.min(queryIndex,hashIndex):queryIndex!==-1?endIndex=queryIndex:hashIndex!==-1&&(endIndex=hashIndex),filePath.slice(0,endIndex)},getExtension=filePath=>{let normalizedPath=stripQueryAndHash(filePath),lastDotIndex=normalizedPath.lastIndexOf(".");return lastDotIndex===-1||Math.max(normalizedPath.lastIndexOf("/"),normalizedPath.lastIndexOf("\\"))>lastDotIndex?"":normalizedPath.slice(lastDotIndex).toLowerCase()},getTransformsForFilePath=filePath=>{let extension=getExtension(filePath),transforms=["imports"];return TS_EXTENSIONS.has(extension)&&transforms.unshift("typescript"),JSX_EXTENSIONS.has(extension)&&transforms.push("jsx"),transforms},transformWithSucrase=(code,filePath)=>{let transforms=getTransformsForFilePath(filePath),sanitizedCode=stripTypeStarExports(code),transformCode=codeToTransform=>transform6(codeToTransform,{filePath,disableESTransforms:!0,production:!0,transforms}).code;try{return transformCode(sanitizedCode)}catch(error2){if(!(error2 instanceof Error))throw error2;for(let repairCandidate of getJsxCommentRepairCandidates(sanitizedCode))try{return transformCode(repairCandidate)}catch{}throw createHelpfulSyntaxError(error2,code,filePath)}};var getImportsFromCode=code=>{let strippedCode=stripComments(code),importRegex=/(?:^|[;\n\r}])\s*import\s*(?:(?:[\w$]+\s*,\s*)?(?:\*\s*as\s+[\w$]+|\{[^}]+\}|[\w$]+)\s*from\s*)?['"]([^'"]+)['"]/gm,imports=[],match2;for(;(match2=importRegex.exec(strippedCode))!==null;){let fullMatch=match2[0];/\bimport\s+type\b/.test(fullMatch)||imports.push(match2[1])}let reExportRegex=/^\s*export\s+(?:type\s+)?(?:\*\s+as\s+[\w$]+|\*|\{[^}]+\})\s+from\s*['"](.+?)['"]/gm,reExportMatch;for(;(reExportMatch=reExportRegex.exec(strippedCode))!==null;){let fullMatch=reExportMatch[0];/^\s*export\s+type\b/.test(fullMatch)||imports.push(reExportMatch[1])}let requireRegex=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,requireMatch=requireRegex.exec(strippedCode);for(;requireMatch!==null;)imports.push(requireMatch[1]),requireMatch=requireRegex.exec(strippedCode);return imports};var getTypeExportsFromCode=code=>{let strippedCode=stripComments(code),typeExports=[],exportTypeRegex=/export\s+type\s+(\w+)\s*(?:=|<)/g,match2;for(;(match2=exportTypeRegex.exec(strippedCode))!==null;)typeExports.push(match2[1]);let exportInterfaceRegex=/export\s+interface\s+(\w+)/g;for(;(match2=exportInterfaceRegex.exec(strippedCode))!==null;)typeExports.push(match2[1]);return typeExports};var normalizePackageEntrypoint=entrypoint=>entrypoint.replace(/^\.\//,"");function getBrowserMappedEntrypoint(packageJson){if(!packageJson.browser||typeof packageJson.browser=="string")return null;let entryPoint=packageJson.module||packageJson.main||"index.js",browserEntrypoint=packageJson.browser[entryPoint];if(typeof browserEntrypoint=="string")return browserEntrypoint;let normalizedEntryPoint=normalizePackageEntrypoint(entryPoint),normalizedBrowserEntrypoint=packageJson.browser[`./${normalizedEntryPoint}`]??packageJson.browser[normalizedEntryPoint];return typeof normalizedBrowserEntrypoint=="string"?normalizedBrowserEntrypoint:null}function createContext(modulePath,fsMap,basePath){return{fsMap,extensions:[".js",".jsx",".ts",".tsx",".json"],basePath,modulePath}}function findPackageJson(nodeModulesPath,ctx){let packageJsonPath=`${nodeModulesPath}/package.json`;if(!ctx.fsMap[packageJsonPath])return null;try{return JSON.parse(ctx.fsMap[packageJsonPath])}catch{return null}}function tryResolveWithExtensions(path,ctx){if(ctx.fsMap[path])return path;for(let ext of ctx.extensions){let pathWithExt=path.replace(/\.js$|\.jsx$/,"")+ext;if(ctx.fsMap[pathWithExt])return pathWithExt}return null}function resolveExportPath(nodeModulesPath,exportPath,ctx){let fullExportPath=`${nodeModulesPath}/${exportPath.replace(/^\.\//,"")}`;return tryResolveWithExtensions(fullExportPath,ctx)}function resolveConditionalExport(exportValue){if(typeof exportValue=="string")return exportValue;let conditions=["import","default","require","node","browser"];for(let condition of conditions)if(exportValue[condition]){let conditionValue=exportValue[condition];if(typeof conditionValue=="string")return conditionValue;let resolved=resolveConditionalExport(conditionValue);if(resolved)return resolved}return null}function resolvePackageExports(nodeModulesPath,packageJson,remainingPath,ctx){if(!packageJson.exports)return null;let defaultExport=packageJson.exports["."];if(remainingPath===""&&defaultExport){let exportPath=resolveConditionalExport(defaultExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}let subpathExport=remainingPath?packageJson.exports[`./${remainingPath}`]:null;if(subpathExport){let exportPath=resolveConditionalExport(subpathExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}let importExport=packageJson.exports.import;if(remainingPath===""&&importExport!==void 0){let exportPath=resolveConditionalExport(importExport);if(exportPath){let resolved=resolveExportPath(nodeModulesPath,exportPath,ctx);if(resolved)return resolved}}return null}function resolvePackageEntryPoint(nodeModulesPath,packageJson,ctx){let entryPoint=normalizePackageEntrypoint(typeof packageJson.browser=="string"&&packageJson.browser||getBrowserMappedEntrypoint(packageJson)||packageJson.module||packageJson.main||"index.js"),fullPath=`${nodeModulesPath}/${entryPoint}`;return tryResolveWithExtensions(fullPath,ctx)}function resolveRemainingPath(nodeModulesPath,remainingPath,ctx){if(!remainingPath){for(let ext of ctx.extensions){let indexPath=`${nodeModulesPath}/index${ext}`;if(ctx.fsMap[indexPath])return indexPath}return null}let fullPath=`${nodeModulesPath}/${remainingPath}`,directMatch=tryResolveWithExtensions(fullPath,ctx);if(directMatch)return directMatch;for(let ext of ctx.extensions){let indexPath=`${fullPath}/index${ext}`;if(ctx.fsMap[indexPath])return indexPath}return null}function resolveNodeModuleInPath(searchPath,ctx){let moduleParts=ctx.modulePath.split("/"),scope=moduleParts[0].startsWith("@")?moduleParts.slice(0,2).join("/"):moduleParts[0],remainingPath=moduleParts.slice(scope.includes("/")?2:1).join("/"),nodeModulesPath=`${searchPath==="."?"":`${searchPath}/`}node_modules/${scope}`,packageJson=findPackageJson(nodeModulesPath,ctx);if(packageJson){let exportsResolution=resolvePackageExports(nodeModulesPath,packageJson,remainingPath,ctx);if(exportsResolution)return exportsResolution;let entryPointResolution=resolvePackageEntryPoint(nodeModulesPath,packageJson,ctx);if(entryPointResolution)return entryPointResolution}let remainingPathResolution=resolveRemainingPath(nodeModulesPath,remainingPath,ctx);if(remainingPathResolution)return remainingPathResolution;let parentPath=dirname(searchPath);return parentPath&&parentPath!==searchPath?resolveNodeModuleInPath(parentPath,ctx):null}function resolveNodeModule(modulePath,fsMap,basePath){let ctx=createContext(modulePath,fsMap,basePath);return resolveNodeModuleInPath(ctx.basePath,ctx)}var hasPreSuppliedImport=(preSuppliedImports,importName)=>Object.prototype.hasOwnProperty.call(preSuppliedImports,importName);function evalCompiledJs(compiledCode,preSuppliedImports,cwd){globalThis.__tscircuit_require=name=>{let resolvedFilePath=resolveFilePath(name,preSuppliedImports,cwd);!resolvedFilePath&&!name.startsWith(".")&&!name.startsWith("/")&&(resolvedFilePath=resolveNodeModule(name,preSuppliedImports,cwd||""));let hasResolvedFilePath=resolvedFilePath&&hasPreSuppliedImport(preSuppliedImports,resolvedFilePath);if(!hasPreSuppliedImport(preSuppliedImports,name)&&!hasResolvedFilePath)throw new Error(`Import "${name}" not found ${cwd?`in "${cwd}"`:""}`);let mod=hasPreSuppliedImport(preSuppliedImports,name)?preSuppliedImports[name]:preSuppliedImports[resolvedFilePath];if(mod.__esModule&&mod.default!==void 0){let modKeys=Object.keys(mod);if(modKeys.length===2&&modKeys.includes("__esModule")&&modKeys.includes("default"))return mod.default}if(mod.default&&typeof mod.default=="function"){let callableWrapper=(...args)=>mod.default(...args);return Object.assign(callableWrapper,mod),callableWrapper.__esModule=!0,callableWrapper}return new Proxy(mod,{get(target,prop){if(!(prop in target)){if(prop==="default")return target.default!==void 0?target.default:target.__esModule?void 0:typeof target=="function"||typeof target=="object"?target:void 0;if(prop==="__esModule")return!0;if(prop==="__typeOnlyExports__")return target.__typeOnlyExports__||[];let typeExports=target.__typeOnlyExports__||[],propName=String(prop);throw typeExports.includes(propName)?new Error(`"${propName}" is a type exported by "${name}" and cannot be imported as a value.
|
|
943
946
|
Use "export type { ${propName} }" instead of "export { ${propName} }"`):new Error(`"${propName}" is not exported by "${name}".
|
|
944
947
|
If "${propName}" is a type, use "export type { ${propName} }" instead of "export { ${propName} }"`)}return target[prop]}})};let functionBody=`
|
|
945
948
|
var exports = {};
|
|
@@ -949,7 +952,7 @@ If "${propName}" is a type, use "export type { ${propName} }" instead of "export
|
|
|
949
952
|
${compiledCode};
|
|
950
953
|
return module;`.trim();return Function(functionBody).call(globalThis)}var debug13=(0,import_debug22.default)("tsci:eval:import-local-file"),getFileExtension2=fsPath=>{let ext=fsPath.split(".").pop();return ext?ext.toLowerCase():""},getStaticFileLoader=(platform,fsPath)=>{let ext=getFileExtension2(fsPath);if(ext)return platform?.staticFileLoaderMap?.[ext]??platform?.staticFileLoaderMap?.[`.${ext}`]},normalizeStaticFileLoaderResult=result=>result&&typeof result=="object"&&result.__esModule?result:{__esModule:!0,default:result},resolveStaticFileLoaderInput=async(fileContent,fsPath,platform)=>{let isStaticAssetMarker=fileContent==="__STATIC_ASSET__",isBlobUrl=fileContent.startsWith("blob:");if(!isStaticAssetMarker&&!isBlobUrl)return fileContent;let assetUrl=fileContent;if(isStaticAssetMarker){let projectBaseUrl=platform?.projectBaseUrl?.replace(/\/$/,"");if(!projectBaseUrl)return fileContent;let normalizedPath=fsPath.startsWith("./")?fsPath.slice(2):fsPath;assetUrl=`${projectBaseUrl}/${normalizedPath}`}let response=await(platform?.platformFetch??globalThis.fetch)(assetUrl);if(!response.ok)throw new Error(`Failed to fetch static file content from "${assetUrl}" (HTTP ${response.status})`);return response.arrayBuffer()},importLocalFile=async(importName,ctx,depth=0)=>{debug13("importLocalFile called with:",{importName});let{fsMap,preSuppliedImports,importStack,currentlyImporting}=ctx,fsPath=resolveFilePathOrThrow(importName,fsMap,void 0,{tsConfig:ctx.tsConfig});if(debug13("fsPath:",fsPath),currentlyImporting.has(fsPath)){let cycleStartIndex=importStack.indexOf(fsPath),cyclePath=cycleStartIndex>=0?importStack.slice(cycleStartIndex).concat(fsPath):[...importStack,fsPath];throw new Error(`Circular dependency detected while importing "${fsPath}". The following import chain forms a cycle:
|
|
951
954
|
|
|
952
|
-
${cyclePath.join(" -> ")}`)}if(!ctx.fsMap[fsPath])throw debug13("fsPath not found in fsMap:",fsPath),new Error(`File "${fsPath}" not found`);let fileContent=fsMap[fsPath];debug13("fileContent:",fileContent?.slice(0,100)),currentlyImporting.add(fsPath),importStack.push(fsPath);try{let staticFileLoader=getStaticFileLoader(ctx.circuit.platform,fsPath);if(staticFileLoader)try{let loaderInput=await resolveStaticFileLoaderInput(fileContent,fsPath,ctx.circuit.platform);preSuppliedImports[fsPath]=normalizeStaticFileLoaderResult(await staticFileLoader(loaderInput))}catch(error2){let ext=getFileExtension2(fsPath);throw new Error(`Failed to load static file "${fsPath}" with platformConfig.staticFileLoaderMap["${ext}"]: ${error2.message}`)}else if(fsPath.endsWith(".json")){let jsonData=JSON.parse(fileContent);preSuppliedImports[fsPath]={__esModule:!0,default:jsonData}}else if(isStaticAssetPath2(fsPath)){let staticUrl;if(fileContent==="__STATIC_ASSET__")staticUrl=`${ctx.circuit.platform?.projectBaseUrl??""}/${fsPath.startsWith("./")?fsPath.slice(2):fsPath}`;else if(fileContent.startsWith("blob:"))staticUrl=`${fileContent}#ext=${fsPath.split(".").pop()}`;else{let blob=new Blob([fileContent],{type:fsPath.endsWith(".kicad_mod")?"text/plain":"application/octet-stream"}),ext=fsPath.split(".").pop()?.toLowerCase(),isStepFile=ext==="step"||ext==="stp",blobUrl=URL.createObjectURL(blob);staticUrl=isStepFile?`${blobUrl}#ext=${ext}`:blobUrl}preSuppliedImports[fsPath]={__esModule:!0,default:staticUrl}}else if(fsPath.endsWith(".tsx")||fsPath.endsWith(".ts")){let importNames=getImportsFromCode(fileContent);for(let importName2 of importNames)hasPreSuppliedImport(preSuppliedImports,importName2)||await importEvalPath(importName2,ctx,depth+1,{cwd:dirname(fsPath)});
|
|
955
|
+
${cyclePath.join(" -> ")}`)}if(!ctx.fsMap[fsPath])throw debug13("fsPath not found in fsMap:",fsPath),new Error(`File "${fsPath}" not found`);let fileContent=fsMap[fsPath];debug13("fileContent:",fileContent?.slice(0,100)),currentlyImporting.add(fsPath),importStack.push(fsPath);try{let staticFileLoader=getStaticFileLoader(ctx.circuit.platform,fsPath);if(staticFileLoader)try{let loaderInput=await resolveStaticFileLoaderInput(fileContent,fsPath,ctx.circuit.platform);preSuppliedImports[fsPath]=normalizeStaticFileLoaderResult(await staticFileLoader(loaderInput))}catch(error2){let ext=getFileExtension2(fsPath);throw new Error(`Failed to load static file "${fsPath}" with platformConfig.staticFileLoaderMap["${ext}"]: ${error2.message}`)}else if(fsPath.endsWith(".json")){let jsonData=JSON.parse(fileContent);preSuppliedImports[fsPath]={__esModule:!0,default:jsonData}}else if(isStaticAssetPath2(fsPath)){let staticUrl;if(fileContent==="__STATIC_ASSET__")staticUrl=`${ctx.circuit.platform?.projectBaseUrl??""}/${fsPath.startsWith("./")?fsPath.slice(2):fsPath}`;else if(fileContent.startsWith("blob:"))staticUrl=`${fileContent}#ext=${fsPath.split(".").pop()}`;else{let blob=new Blob([fileContent],{type:fsPath.endsWith(".kicad_mod")?"text/plain":"application/octet-stream"}),ext=fsPath.split(".").pop()?.toLowerCase(),isStepFile=ext==="step"||ext==="stp",blobUrl=URL.createObjectURL(blob);staticUrl=isStepFile?`${blobUrl}#ext=${ext}`:blobUrl}preSuppliedImports[fsPath]={__esModule:!0,default:staticUrl}}else if(fsPath.endsWith(".tsx")||fsPath.endsWith(".ts")){let importNames=getImportsFromCode(fileContent);for(let importName2 of importNames)hasPreSuppliedImport(preSuppliedImports,importName2)||await importEvalPath(importName2,ctx,depth+1,{cwd:dirname(fsPath)});let transformedCode=transformWithSucrase(fileContent,fsPath);try{debug13("evalCompiledJs called with:",{code:transformedCode.slice(0,100),dirname:dirname(fsPath)});let typeExports=getTypeExportsFromCode(fileContent),importRunResult=evalCompiledJs(transformedCode,preSuppliedImports,dirname(fsPath));debug13("importRunResult:",{fsPath,importRunResult});let moduleExports=importRunResult.exports;typeExports.length>0&&(moduleExports.__typeOnlyExports__=typeExports),preSuppliedImports[fsPath]=moduleExports}catch(error2){throw new Error(`Error evaluating "${fsPath}": ${error2.message}`)}}else if(fsPath.endsWith(".js")||fsPath.endsWith(".mjs")){let importNames=getImportsFromCode(fileContent);for(let importName2 of importNames)hasPreSuppliedImport(preSuppliedImports,importName2)||await importEvalPath(importName2,ctx,depth+1,{cwd:dirname(fsPath)});preSuppliedImports[fsPath]=evalCompiledJs(transformWithSucrase(fileContent,fsPath),preSuppliedImports,dirname(fsPath)).exports}else throw new Error(`Unsupported file extension "${fsPath.split(".").pop()}" for "${fsPath}"`)}finally{importStack.pop(),currentlyImporting.delete(fsPath)}};async function importSnippet(importName,ctx,depth=0){let{preSuppliedImports}=ctx,fullSnippetName=importName.replace("@tsci/","").replace(".","/"),fetchOptions={};ctx.tscircuitSessionToken&&(fetchOptions.headers={Authorization:`Bearer ${ctx.tscircuitSessionToken}`});let{cjs,error:error2}=await globalThis.fetch(`${ctx.cjsRegistryUrl}/${fullSnippetName}`,fetchOptions).then(async res2=>({cjs:await res2.text(),error:null})).catch(e6=>({error:e6,cjs:null}));if(error2){console.error("Error fetching import",importName,error2);return}if(cjs?.startsWith("{"))try{let jsonResponse=JSON.parse(cjs);if(jsonResponse.ok===!1&&jsonResponse.error)throw new Error(`"${importName}" has no files in dist, it may not be built`)}catch(e6){throw e6 instanceof Error&&e6.message.includes("has no files in dist")?e6:new Error(`Error parsing cjs response: ${e6}`)}let importNames=getImportsFromCode(cjs),staticAssetImports=[],otherImports=[];for(let subImportName of importNames)if(!hasPreSuppliedImport(preSuppliedImports,subImportName))if(subImportName.startsWith("./")&&isStaticAssetPath2(subImportName)){let assetPath=subImportName.slice(2),assetUrl=`${ctx.cjsRegistryUrl}/${importName}/${assetPath}`;staticAssetImports.push({subImportName,assetUrl})}else otherImports.push(subImportName);await Promise.all(staticAssetImports.map(async({subImportName,assetUrl})=>{try{let response=await globalThis.fetch(assetUrl,fetchOptions);if(!response.ok)throw new Error(`Failed to fetch asset: ${response.statusText}`);let blob=await response.blob(),extension=subImportName.split(".").pop()||"",blobUrl=`${URL.createObjectURL(blob)}#ext=${extension}`;preSuppliedImports[subImportName]={__esModule:!0,default:blobUrl}}catch(e6){console.error(`Error fetching static asset ${assetUrl}:`,e6),preSuppliedImports[subImportName]={__esModule:!0,default:assetUrl}}}));for(let subImportName of otherImports)hasPreSuppliedImport(preSuppliedImports,subImportName)||await importEvalPath(subImportName,ctx,depth+1);try{preSuppliedImports[importName]=evalCompiledJs(cjs,preSuppliedImports).exports}catch(e6){console.error("Error importing snippet",e6)}}var import_debug23=__toESM(require_browser(),1);function extractBasePackageName(importName){let basePackageName=importName;if(importName.startsWith("@")){let parts=importName.split("/");basePackageName=parts.length>=2?`${parts[0]}/${parts[1]}`:importName}else basePackageName=importName.split("/")[0];return basePackageName}function getNodeModulePackageRoot(cwd){if(!cwd)return null;let nodeModulesMarker="node_modules/",nodeModulesIndex=cwd.lastIndexOf(nodeModulesMarker);if(nodeModulesIndex===-1)return null;let packagePrefix=cwd.slice(0,nodeModulesIndex+nodeModulesMarker.length),packagePathParts=cwd.slice(nodeModulesIndex+nodeModulesMarker.length).split("/"),packageName=packagePathParts[0]?.startsWith("@")?packagePathParts.slice(0,2).join("/"):packagePathParts[0];return packageName?`${packagePrefix}${packageName}`:null}function isPackageDeclaredInManifest(packageName,packageJsonContent){if(!packageJsonContent)return null;try{let packageJson=JSON.parse(packageJsonContent),dependencies=packageJson.dependencies||{},devDependencies=packageJson.devDependencies||{},peerDependencies=packageJson.peerDependencies||{},basePackageName=extractBasePackageName(packageName);return basePackageName in dependencies||basePackageName in devDependencies||basePackageName in peerDependencies}catch{return!0}}function isPackageDeclaredInPackageJson(packageName,fsMap,opts={}){let packageRoot=getNodeModulePackageRoot(opts.cwd),packageManifestResult=packageRoot?isPackageDeclaredInManifest(packageName,fsMap[`${packageRoot}/package.json`]):null;if(packageManifestResult)return!0;let rootManifestResult=isPackageDeclaredInManifest(packageName,fsMap["package.json"]);return rootManifestResult===null&&packageManifestResult===null?!0:rootManifestResult===!0}function getNodeModuleDirectory(packageName,fsMap){let nodeModulePath=`node_modules/${extractBasePackageName(packageName)}`;return Object.keys(fsMap).some(path=>path.startsWith(nodeModulePath+"/")||path===nodeModulePath)?nodeModulePath:null}function getPackageJsonEntrypoint(packageName,fsMap){let packageJsonPath=`node_modules/${extractBasePackageName(packageName)}/package.json`,packageJsonContent=fsMap[packageJsonPath];if(!packageJsonContent)return null;try{let packageJson=JSON.parse(packageJsonContent);if(packageJson.browser&&typeof packageJson.browser=="object"){let entrypoint=packageJson.module||packageJson.main,normalizedEntrypoint=entrypoint?.replace(/^\.\//,""),browserEntrypoint=packageJson.browser[entrypoint]||packageJson.browser[`./${normalizedEntrypoint}`]||packageJson.browser[normalizedEntrypoint];if(typeof browserEntrypoint=="string")return browserEntrypoint}return typeof packageJson.browser=="string"&&packageJson.browser||packageJson.module||packageJson.main||null}catch{return null}}function isDistDirEmpty(packageName,fsMap){let distPath=`node_modules/${extractBasePackageName(packageName)}/dist`;return!Object.keys(fsMap).some(path=>path.startsWith(distPath+"/"))}var moduleExtensions=[".js",".jsx",".ts",".tsx",".json"],resolveEntrypointPath=(packageName,entrypoint,fsMap)=>{let basePackageName=extractBasePackageName(packageName),normalizedEntrypoint=normalizePackageEntrypoint(entrypoint),entrypointPath=`node_modules/${basePackageName}/${normalizedEntrypoint}`;if(fsMap[entrypointPath])return entrypointPath;for(let ext of moduleExtensions){let pathWithExt=entrypointPath.replace(/\.js$|\.jsx$/,"")+ext;if(fsMap[pathWithExt])return pathWithExt}return null};var debug14=(0,import_debug23.default)("tsci:eval:import-node-module"),importNodeModule=async(importName,ctx,depth=0,opts={})=>{let{preSuppliedImports,fsMap}=ctx;if(hasPreSuppliedImport(preSuppliedImports,importName))return;let hasPackageJson=!!fsMap["package.json"];if(hasPackageJson&&!isPackageDeclaredInPackageJson(importName,fsMap,opts))throw new Error(`Node module imported but not in package.json "${importName}"
|
|
953
956
|
|
|
954
957
|
${ctx.logger.stringifyLogs()}`);let nodeModuleDir=hasPackageJson?getNodeModuleDirectory(importName,fsMap):null,resolvedNodeModulePath=resolveNodeModule(importName,ctx.fsMap,opts.cwd||"");if(hasPackageJson&&resolvedNodeModulePath){if(!nodeModuleDir)throw new Error(`Node module "${importName}" has no files in the node_modules directory
|
|
955
958
|
|