tscircuit 0.0.1823-libonly → 0.0.1824-libonly
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/browser.min.js +2 -2
- package/dist/webworker.min.js +6 -6
- package/package.json +3 -3
package/dist/webworker.min.js
CHANGED
|
@@ -796,7 +796,7 @@ ${spiceString}`)}catch(error2){debug11(`Failed to convert circuit JSON to SPICE:
|
|
|
796
796
|
${Object.keys(fsMapOrAllFilePaths).join(", ")}`);return resolvedFilePath};var stripComments=code=>{let out="",i3=0,inSingle=!1,inDouble=!1,inTemplate=!1;for(;i3<code.length;){let ch3=code[i3],next2=code[i3+1];if(!inDouble&&!inTemplate&&ch3==="'"&&code[i3-1]!=="\\"){inSingle=!inSingle,out+=ch3,i3++;continue}if(!inSingle&&!inTemplate&&ch3==='"'&&code[i3-1]!=="\\"){inDouble=!inDouble,out+=ch3,i3++;continue}if(!inSingle&&!inDouble&&ch3==="`"&&code[i3-1]!=="\\"){inTemplate=!inTemplate,out+=ch3,i3++;continue}if(!inSingle&&!inDouble&&!inTemplate){if(ch3==="/"&&next2==="/"){for(out+=" ",i3+=2;i3<code.length&&code[i3]!==`
|
|
797
797
|
`;)out+=" ",i3++;continue}if(ch3==="/"&&next2==="*"){for(out+=" ",i3+=2;i3<code.length;){if(code[i3]===`
|
|
798
798
|
`?out+=`
|
|
799
|
-
`:out+=" ",code[i3]==="*"&&code[i3+1]==="/"){out+=" ",i3+=2;break}i3++}continue}}out+=ch3,i3++}return out};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)}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&&preSuppliedImports
|
|
799
|
+
`:out+=" ",code[i3]==="*"&&code[i3+1]==="/"){out+=" ",i3+=2;break}i3++}continue}}out+=ch3,i3++}return out};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.
|
|
800
800
|
Use "export type { ${propName} }" instead of "export { ${propName} }"`):new Error(`"${propName}" is not exported by "${name}".
|
|
801
801
|
If "${propName}" is a type, use "export type { ${propName} }" instead of "export { ${propName} }"`)}return target[prop]}})};let functionBody=`
|
|
802
802
|
var exports = {};
|
|
@@ -939,7 +939,7 @@ ${namesToRegister.map(({variableName,uniqueLocalName})=>` reactHotLoader.regist
|
|
|
939
939
|
`);return newlineIndex===-1&&(newlineIndex=code.length,code+=`
|
|
940
940
|
`),{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(s3=>`${s3}, `).join("")}${className})`):classInfo.staticInitializerNames.length>0&&this.tokens.appendCode(` ${staticInitializerStatements.map(s3=>`${s3};`).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 i3=0;i3<mappings.length;i3++){let mapping=mappings[i3];mapping!==void 0&&(mappings[i3]=mapping+prefixLength)}return mappings}};var import_lines_and_columns=__toESM(require_build());function getTSImportedNames(tokens){let importedNames=new Set;for(let i3=0;i3<tokens.tokens.length;i3++)tokens.matches1AtIndex(i3,TokenType._import)&&!tokens.matches3AtIndex(i3,TokenType._import,TokenType.name,TokenType.eq)&&collectNamesForImport(tokens,i3,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 transform5(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(e5){throw options.filePath&&(e5.message=`Error transforming ${options.filePath}: ${e5.message}`),e5}}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}=transform5(sanitizedCode,{filePath,disableESTransforms:!0,production:!0,transforms});return transformedCode};var debug14=(0,import_debug24.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},importLocalFile=async(importName,ctx,depth=0)=>{debug14("importLocalFile called with:",{importName});let{fsMap,preSuppliedImports,importStack,currentlyImporting}=ctx,fsPath=resolveFilePathOrThrow(importName,fsMap,void 0,{tsConfig:ctx.tsConfig});if(debug14("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:
|
|
941
941
|
|
|
942
|
-
${cyclePath.join(" -> ")}`)}if(!ctx.fsMap[fsPath])throw debug14("fsPath not found in fsMap:",fsPath),new Error(`File "${fsPath}" not found`);let fileContent=fsMap[fsPath];debug14("fileContent:",fileContent?.slice(0,100)),currentlyImporting.add(fsPath),importStack.push(fsPath);try{let staticFileLoader=getStaticFileLoader(ctx.circuit.platform,fsPath);if(staticFileLoader)try{preSuppliedImports[fsPath]=normalizeStaticFileLoaderResult(await staticFileLoader(fileContent))}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)preSuppliedImports
|
|
942
|
+
${cyclePath.join(" -> ")}`)}if(!ctx.fsMap[fsPath])throw debug14("fsPath not found in fsMap:",fsPath),new Error(`File "${fsPath}" not found`);let fileContent=fsMap[fsPath];debug14("fileContent:",fileContent?.slice(0,100)),currentlyImporting.add(fsPath),importStack.push(fsPath);try{let staticFileLoader=getStaticFileLoader(ctx.circuit.platform,fsPath);if(staticFileLoader)try{preSuppliedImports[fsPath]=normalizeStaticFileLoaderResult(await staticFileLoader(fileContent))}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)});try{let transformedCode=transformWithSucrase(fileContent,fsPath);debug14("evalCompiledJs called with:",{code:transformedCode.slice(0,100),dirname:dirname(fsPath)});let typeExports=getTypeExportsFromCode(fileContent),importRunResult=evalCompiledJs(transformedCode,preSuppliedImports,dirname(fsPath));debug14("importRunResult:",{fsPath,importRunResult});let moduleExports=importRunResult.exports;typeExports.length>0&&(moduleExports.__typeOnlyExports__=typeExports),preSuppliedImports[fsPath]=moduleExports}catch(error2){throw new Error(`Eval compiled js error for "${importName}": ${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(e5=>({error:e5,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(e5){throw e5 instanceof Error&&e5.message.includes("has no files in dist")?e5:new Error(`Error parsing cjs response: ${e5}`)}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(e5){console.error(`Error fetching static asset ${assetUrl}:`,e5),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(e5){console.error("Error importing snippet",e5)}}var import_debug25=__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 debug15=(0,import_debug25.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}"
|
|
943
943
|
|
|
944
944
|
${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
|
|
945
945
|
|
|
@@ -949,15 +949,15 @@ ${ctx.logger.stringifyLogs()}`)}if(!resolvedNodeModulePath){if(hasPackageJson&&n
|
|
|
949
949
|
|
|
950
950
|
${ctx.logger.stringifyLogs()}`);if(entrypoint&&!resolveEntrypointPath(importName,entrypoint,fsMap))throw new Error(`${importName}'s main path (${entrypoint}) was not found, it may not be built
|
|
951
951
|
|
|
952
|
-
${ctx.logger.stringifyLogs()}`)}let platform=ctx.circuit?.platform;if(platform?.nodeModulesResolver){debug15(`Attempting to resolve "${importName}" using nodeModulesResolver`);try{let fileContent=await platform.nodeModulesResolver(importName);if(fileContent){debug15(`Successfully resolved "${importName}" via nodeModulesResolver`);let syntheticPath=`node_modules/${importName}.ts`;ctx.fsMap[syntheticPath]=fileContent,await importLocalFile(syntheticPath,ctx,depth),preSuppliedImports[importName]=preSuppliedImports[syntheticPath];let unprefixedPath2=syntheticPath.replace(/^node_modules\//,"");preSuppliedImports[unprefixedPath2]=preSuppliedImports[syntheticPath];return}debug15(`nodeModulesResolver returned null for "${importName}"`)}catch(error2){debug15(`nodeModulesResolver failed for "${importName}":`,error2)}}throw new Error(`Node module "${importName}" not found`)}await importLocalFile(resolvedNodeModulePath,ctx,depth),preSuppliedImports[importName]=preSuppliedImports[resolvedNodeModulePath];let unprefixedPath=resolvedNodeModulePath.replace(/^node_modules\//,"");if(preSuppliedImports[unprefixedPath]=preSuppliedImports[resolvedNodeModulePath],resolvedNodeModulePath.endsWith("/index.tsx")||resolvedNodeModulePath.endsWith("/index.ts")||resolvedNodeModulePath.endsWith("/index.js")){let unprefixedDirPath=resolvedNodeModulePath.replace(/\/index\.(tsx?|js)$/,"").replace(/^node_modules\//,"");if(preSuppliedImports[unprefixedDirPath]=preSuppliedImports[resolvedNodeModulePath],unprefixedDirPath.startsWith("@")){let scopeParts=unprefixedDirPath.split("/");if(scopeParts.length>=2){let scopedName=`${scopeParts[0]}/${scopeParts[1]}`;preSuppliedImports[scopedName]=preSuppliedImports[resolvedNodeModulePath]}}}};var import_debug26=__toESM(require_browser(),1);var debug16=(0,import_debug26.default)("tsci:eval:import-npm-package");function extractPackagePathFromCdnUrl(url2,importName){return url2.startsWith("https://cdn.jsdelivr.net/npm/")?url2.substring(29).replace(/\/\+esm$/,""):url2.startsWith("https://jscdn.tscircuit.com/")?importName:url2}async function importNpmPackageFromCdn({importName,depth=0},ctx){debug16(`importing npm package from CDN: ${importName}`);let{preSuppliedImports}=ctx;if(preSuppliedImports
|
|
952
|
+
${ctx.logger.stringifyLogs()}`)}let platform=ctx.circuit?.platform;if(platform?.nodeModulesResolver){debug15(`Attempting to resolve "${importName}" using nodeModulesResolver`);try{let fileContent=await platform.nodeModulesResolver(importName);if(fileContent){debug15(`Successfully resolved "${importName}" via nodeModulesResolver`);let syntheticPath=`node_modules/${importName}.ts`;ctx.fsMap[syntheticPath]=fileContent,await importLocalFile(syntheticPath,ctx,depth),preSuppliedImports[importName]=preSuppliedImports[syntheticPath];let unprefixedPath2=syntheticPath.replace(/^node_modules\//,"");preSuppliedImports[unprefixedPath2]=preSuppliedImports[syntheticPath];return}debug15(`nodeModulesResolver returned null for "${importName}"`)}catch(error2){debug15(`nodeModulesResolver failed for "${importName}":`,error2)}}throw new Error(`Node module "${importName}" not found`)}await importLocalFile(resolvedNodeModulePath,ctx,depth),preSuppliedImports[importName]=preSuppliedImports[resolvedNodeModulePath];let unprefixedPath=resolvedNodeModulePath.replace(/^node_modules\//,"");if(preSuppliedImports[unprefixedPath]=preSuppliedImports[resolvedNodeModulePath],resolvedNodeModulePath.endsWith("/index.tsx")||resolvedNodeModulePath.endsWith("/index.ts")||resolvedNodeModulePath.endsWith("/index.js")){let unprefixedDirPath=resolvedNodeModulePath.replace(/\/index\.(tsx?|js)$/,"").replace(/^node_modules\//,"");if(preSuppliedImports[unprefixedDirPath]=preSuppliedImports[resolvedNodeModulePath],unprefixedDirPath.startsWith("@")){let scopeParts=unprefixedDirPath.split("/");if(scopeParts.length>=2){let scopedName=`${scopeParts[0]}/${scopeParts[1]}`;preSuppliedImports[scopedName]=preSuppliedImports[resolvedNodeModulePath]}}}};var import_debug26=__toESM(require_browser(),1);var debug16=(0,import_debug26.default)("tsci:eval:import-npm-package");function extractPackagePathFromCdnUrl(url2,importName){return url2.startsWith("https://cdn.jsdelivr.net/npm/")?url2.substring(29).replace(/\/\+esm$/,""):url2.startsWith("https://jscdn.tscircuit.com/")?importName:url2}async function importNpmPackageFromCdn({importName,depth=0},ctx){debug16(`importing npm package from CDN: ${importName}`);let{preSuppliedImports}=ctx;if(hasPreSuppliedImport(preSuppliedImports,importName))return;let npmCdnUrls=[`${getJscdnPackageUrl(importName)}/+esm`,`https://cdn.jsdelivr.net/npm/${importName}/+esm`],lastCdnError;for(let npmCdnUrl of npmCdnUrls)try{let response=await globalThis.fetch(npmCdnUrl);if(!response.ok)throw new Error(`Could not fetch "${importName}" from ${npmCdnUrl}: ${response.statusText}
|
|
953
953
|
|
|
954
|
-
${ctx.logger.stringifyLogs()}`);let content=await response.text(),finalImportName=extractPackagePathFromCdnUrl(response.url,importName),cwd=dirname(finalImportName),importNames=getImportsFromCode(content);for(let subImportName of importNames)preSuppliedImports
|
|
954
|
+
${ctx.logger.stringifyLogs()}`);let content=await response.text(),finalImportName=extractPackagePathFromCdnUrl(response.url,importName),cwd=dirname(finalImportName),importNames=getImportsFromCode(content);for(let subImportName of importNames)hasPreSuppliedImport(preSuppliedImports,subImportName)||await importEvalPath(subImportName,ctx,depth+1,{cwd});let transformedCode=transformWithSucrase(content,finalImportName||importName),exports=evalCompiledJs(transformedCode,preSuppliedImports,cwd).exports;preSuppliedImports[importName]=exports,preSuppliedImports[finalImportName]=exports,preSuppliedImports[response.url]=exports;return}catch(error2){lastCdnError=error2}throw lastCdnError instanceof Error?new Error(`Eval npm package error for "${importName}": ${lastCdnError.message}
|
|
955
955
|
|
|
956
956
|
${ctx.logger.stringifyLogs()}`):new Error(`Eval npm package error for "${importName}"
|
|
957
957
|
|
|
958
|
-
${ctx.logger.stringifyLogs()}`)}var import_debug27=__toESM(require_browser(),1);var debug17=(0,import_debug27.default)("tsci:eval:import-eval-path"),PATH_EXT_RE=/\.[a-zA-Z0-9]+$/,getNodeModuleSpecifierFromRelativeImport=(importName,cwd)=>{if(!cwd||!importName.startsWith("./")&&!importName.startsWith("../"))return null;let resolvedPath=resolveRelativePath(importName,cwd),nodeModulesPrefix="node_modules/";return resolvedPath.startsWith(nodeModulesPrefix)?resolvedPath.slice(nodeModulesPrefix.length).replace(/\.(tsx?|jsx?|mjs|json)$/,""):null},getSyntheticNodeModulePath=moduleSpecifier=>PATH_EXT_RE.test(moduleSpecifier)?`node_modules/${moduleSpecifier}`:`node_modules/${moduleSpecifier}.ts`;async function importEvalPath(importName,ctx,depth=0,opts={}){debug17("importEvalPath called with:",{importName,depth,opts}),ctx.logger.info(`importEvalPath("${importName}", {cwd: "${opts.cwd}", depth: ${depth}})`),debug17(`${" ".repeat(depth)}\u27A1\uFE0F`,importName);let{preSuppliedImports}=ctx,disableCdnLoading=ctx.disableCdnLoading||globalThis.__DISABLE_CDN_LOADING__;if(preSuppliedImports
|
|
958
|
+
${ctx.logger.stringifyLogs()}`)}var import_debug27=__toESM(require_browser(),1);var debug17=(0,import_debug27.default)("tsci:eval:import-eval-path"),PATH_EXT_RE=/\.[a-zA-Z0-9]+$/,getNodeModuleSpecifierFromRelativeImport=(importName,cwd)=>{if(!cwd||!importName.startsWith("./")&&!importName.startsWith("../"))return null;let resolvedPath=resolveRelativePath(importName,cwd),nodeModulesPrefix="node_modules/";return resolvedPath.startsWith(nodeModulesPrefix)?resolvedPath.slice(nodeModulesPrefix.length).replace(/\.(tsx?|jsx?|mjs|json)$/,""):null},getSyntheticNodeModulePath=moduleSpecifier=>PATH_EXT_RE.test(moduleSpecifier)?`node_modules/${moduleSpecifier}`:`node_modules/${moduleSpecifier}.ts`;async function importEvalPath(importName,ctx,depth=0,opts={}){debug17("importEvalPath called with:",{importName,depth,opts}),ctx.logger.info(`importEvalPath("${importName}", {cwd: "${opts.cwd}", depth: ${depth}})`),debug17(`${" ".repeat(depth)}\u27A1\uFE0F`,importName);let{preSuppliedImports}=ctx,disableCdnLoading=ctx.disableCdnLoading||globalThis.__DISABLE_CDN_LOADING__;if(hasPreSuppliedImport(preSuppliedImports,importName)){ctx.logger.info(`Import "${importName}" in preSuppliedImports[1]`);return}if(importName.startsWith("./")&&hasPreSuppliedImport(preSuppliedImports,importName.slice(2))){ctx.logger.info(`Import "${importName}" in preSuppliedImports[2]`);return}if(importName.includes("/")&&!importName.startsWith(".")&&!importName.startsWith("/")){let basePkg=importName.split("/")[0],isScoped=basePkg.startsWith("@"),pkgName=isScoped?importName.split("/").slice(0,2).join("/"):basePkg,subpath=isScoped?importName.split("/").slice(2).join("/"):importName.split("/").slice(1).join("/");if(hasPreSuppliedImport(preSuppliedImports,pkgName))try{let resolved=await import(`${pkgName}/${subpath}`);preSuppliedImports[importName]=resolved,ctx.logger.info(`Import "${importName}" resolved from preSuppliedImports base package "${pkgName}"`);return}catch{ctx.logger.info(`Failed to resolve "${importName}" from preSuppliedImports package "${pkgName}", falling back to normal resolution`)}}if(depth>30)throw new Error(`Max depth for imports reached (30) Import Path: ${ctx.importStack.join(" -> ")}`);if(importName.startsWith("/npm/")){let pkgName=importName.replace(/^\/npm\//,"").replace(/\/\+esm$/,"");if(disableCdnLoading)throw new Error(`Cannot find module "${pkgName}". The package is not available in the local environment.
|
|
959
959
|
|
|
960
|
-
${ctx.logger.stringifyLogs()}`);ctx.logger.info(`importNpmPackageFromCdn("${pkgName}")`),await importNpmPackageFromCdn({importName:pkgName,depth},ctx)
|
|
960
|
+
${ctx.logger.stringifyLogs()}`);ctx.logger.info(`importNpmPackageFromCdn("${pkgName}")`),await importNpmPackageFromCdn({importName:pkgName,depth},ctx),hasPreSuppliedImport(preSuppliedImports,pkgName)&&(preSuppliedImports[importName]=preSuppliedImports[pkgName]);return}let tsconfigDir=".",tsConfigToUse=ctx.tsConfig;if(ctx.tsConfig&&opts.cwd){let nodeModulesMatch=opts.cwd.match(/^(node_modules\/[^\/]+)/);nodeModulesMatch&&(tsconfigDir=nodeModulesMatch[1],tsConfigToUse=null)}let resolvedLocalImportPath=resolveFilePath(importName,ctx.fsMap,opts.cwd,{tsConfig:tsConfigToUse,tsconfigDir});if(resolvedLocalImportPath){ctx.logger.info(`importLocalFile("${resolvedLocalImportPath}")`),await importLocalFile(resolvedLocalImportPath,ctx,depth),importName!==resolvedLocalImportPath&&(preSuppliedImports[importName]=preSuppliedImports[resolvedLocalImportPath]);return}let tsConfig=ctx.tsConfig??getTsConfig(ctx.fsMap);if(!ctx.tsConfig&&tsConfig&&(ctx.tsConfig=tsConfig),matchesTsconfigPathPattern(importName,tsConfig))throw new Error(`Import "${importName}" matches a tsconfig path alias but could not be resolved to an existing file${opts.cwd?` from directory "${opts.cwd}"`:""}
|
|
961
961
|
|
|
962
962
|
${ctx.logger.stringifyLogs()}`);let resolvedNodeModulePath=resolveNodeModule(importName,ctx.fsMap,opts.cwd||"");if(resolvedNodeModulePath)return ctx.logger.info(`resolvedNodeModulePath="${resolvedNodeModulePath}"`),ctx.logger.info(`importNodeModule("${importName}")`),importNodeModule(importName,ctx,depth,{cwd:opts.cwd});let platform=ctx.circuit?.platform,resolverModuleSpecifier=getNodeModuleSpecifierFromRelativeImport(importName,opts.cwd);if(resolverModuleSpecifier&&platform?.nodeModulesResolver)try{ctx.logger.info(`nodeModulesResolver("${resolverModuleSpecifier}") for relative import "${importName}"`);let fileContent=await platform.nodeModulesResolver(resolverModuleSpecifier);if(fileContent){let syntheticPath=getSyntheticNodeModulePath(resolverModuleSpecifier);ctx.fsMap[syntheticPath]=fileContent,await importLocalFile(syntheticPath,ctx,depth);return}}catch{ctx.logger.info(`nodeModulesResolver failed for relative import "${importName}" from "${opts.cwd}"`)}if(!importName.startsWith(".")&&!importName.startsWith("/")&&!importName.startsWith("@tsci/")&&platform?.nodeModulesResolver){ctx.logger.info(`importNodeModule("${importName}") via nodeModulesResolver`);try{await importNodeModule(importName,ctx,depth);return}catch{if(ctx.logger.info(`nodeModulesResolver failed for "${importName}", falling back to npm CDN`),disableCdnLoading)throw new Error(`Cannot find module "${importName}". The package is not available in the local environment and automatic npm resolution is disabled.
|
|
963
963
|
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"main": "dist/index.js",
|
|
4
4
|
"types": "dist/index.d.ts",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"version": "0.0.
|
|
6
|
+
"version": "0.0.1824-libonly",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"@tscircuit/circuit-json-util": "^0.0.95",
|
|
53
53
|
"@tscircuit/copper-pour-solver": "^0.0.29",
|
|
54
54
|
"@tscircuit/core": "^0.0.1295",
|
|
55
|
-
"@tscircuit/eval": "^0.0.
|
|
55
|
+
"@tscircuit/eval": "^0.0.897",
|
|
56
56
|
"@tscircuit/footprinter": "^0.0.357",
|
|
57
57
|
"@tscircuit/infer-cable-insertion-point": "^0.0.2",
|
|
58
58
|
"@tscircuit/infgrid-ijump-astar": "^0.0.35",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"@tscircuit/miniflex": "^0.0.4",
|
|
64
64
|
"@tscircuit/ngspice-spice-engine": "^0.0.8",
|
|
65
65
|
"@tscircuit/props": "^0.0.542",
|
|
66
|
-
"@tscircuit/runframe": "^0.0.
|
|
66
|
+
"@tscircuit/runframe": "^0.0.2038",
|
|
67
67
|
"@tscircuit/schematic-match-adapt": "^0.0.18",
|
|
68
68
|
"@tscircuit/schematic-trace-solver": "^0.0.60",
|
|
69
69
|
"@tscircuit/simple-3d-svg": "^0.0.41",
|