@storybook/codemod 8.0.0-beta.2 → 8.0.0-beta.4
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/transforms/csf-2-to-3.js +1 -1
- package/dist/transforms/find-implicit-spies.d.ts +6 -0
- package/dist/transforms/find-implicit-spies.js +1 -0
- package/dist/transforms/mdx-to-csf.js +1 -1
- package/dist/transforms/migrate-to-test-package.d.ts +6 -0
- package/dist/transforms/migrate-to-test-package.js +1 -0
- package/dist/transforms/storiesof-to-csf.js +1 -1
- package/dist/transforms/upgrade-deprecated-types.js +1 -1
- package/package.json +8 -4
@@ -1,3 +1,3 @@
|
|
1
1
|
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var csf_2_to_3_exports={};__export(csf_2_to_3_exports,{default:()=>transform,parser:()=>parser});module.exports=__toCommonJS(csf_2_to_3_exports);var import_prettier2=__toESM(require("prettier")),t2=__toESM(require("@babel/types")),import_types=require("@babel/types"),import_csf_tools2=require("@storybook/csf-tools"),babel2=__toESM(require("@babel/core")),import_tiny_invariant=__toESM(require("tiny-invariant"));var import_prettier=__toESM(require("prettier")),babel=__toESM(require("@babel/core")),import_csf_tools=require("@storybook/csf-tools"),t=__toESM(require("@babel/types"));var deprecatedTypes=["ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta","Story"];function migrateType(oldType){return oldType==="Story"||oldType==="ComponentStory"?"StoryFn":oldType.replace("Component","")}function upgradeDeprecatedTypes(file){let importedNamespaces=new Set,typeReferencesToUpdate=new Set,existingImports=[];file.path.traverse({ImportDeclaration:path=>{existingImports.push(...path.get("specifiers").map(specifier=>({name:specifier.node.local.name,isAlias:!(specifier.isImportSpecifier()&&t.isIdentifier(specifier.node.imported)&&specifier.node.local.name===specifier.node.imported.name),path:specifier}))),path.node.source.value.startsWith("@storybook")&&path.get("specifiers").forEach(specifier=>{if(specifier.isImportNamespaceSpecifier()&&importedNamespaces.add(specifier.node.local.name),!specifier.isImportSpecifier())return;let imported=specifier.get("imported");if(imported.isIdentifier()&&deprecatedTypes.includes(imported.node.name)){imported.node.name===specifier.node.local.name&&typeReferencesToUpdate.add(specifier.node.local.name);let newType=migrateType(imported.node.name);if(!existingImports.some(it=>it.name===newType))imported.replaceWith(t.identifier(newType)),existingImports.push({name:newType,isAlias:!1,path:specifier});else{let existingImport=existingImports.find(it=>it.name===newType&&it.isAlias);if(existingImport)throw existingImport.path.buildCodeFrameError(`This codemod does not support local imports that are called the same as a storybook import.
|
2
|
-
Rename this local import and try again.`);specifier.remove()}}})}}),file.path.traverse({TSTypeReference:path=>{let typeName=path.get("typeName");if(typeName.isIdentifier())typeReferencesToUpdate.has(typeName.node.name)&&typeName.replaceWith(t.identifier(migrateType(typeName.node.name)));else if(typeName.isTSQualifiedName()){let namespace=typeName.get("left");if(namespace.isIdentifier()&&importedNamespaces.has(namespace.node.name)){let right=typeName.get("right");deprecatedTypes.includes(right.node.name)&&right.replaceWith(t.identifier(migrateType(right.node.name)))}}}})}var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t2.isCallExpression(init)&&t2.isMemberExpression(init.callee)&&t2.isIdentifier(init.callee.object)&&t2.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t2.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t2.isExpressionStatement(stmt)&&t2.isAssignmentExpression(stmt.expression)&&t2.isMemberExpression(stmt.expression.left)&&t2.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],getNewExport=(stmt,objectExports)=>{if(t2.isExportNamedDeclaration(stmt)&&t2.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t2.isVariableDeclarator(decl)&&t2.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{if(csf._meta?.component&&t2.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t2.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t2.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t2.isJSXSpreadAttribute(attr)&&t2.isIdentifier(attr.argument)&&t2.isIdentifier(param)&¶m.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t2.isArrowFunctionExpression(init)&&init.params.length===0;function removeUnusedTemplates(csf){Object.entries(csf._templates).forEach(([template,templateExpression])=>{let references=[];if(babel2.traverse(csf._ast,{Identifier:path=>{path.node.name===template&&references.push(path)}}),references.length===1){let reference=references[0];reference.parentPath?.isVariableDeclarator()&&reference.parentPath.node.init===templateExpression&&reference.parentPath.remove()}})}async function transform(info,api,options){let makeTitle=userTitle=>userTitle||"FIXME",csf=(0,import_csf_tools2.loadCsf)(info.source,{makeTitle});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),info.source}let file=new babel2.File({filename:info.path},{code:info.source,ast:csf._ast}),importHelper=new StorybookImportHelper(file,info),objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t2.objectProperty(t2.identifier(renameAnnotation(annotation)),val));if(t2.isVariableDeclarator(decl)){let{init,id}=decl;(0,import_tiny_invariant.default)(init,"Inital value should be declared");let template=getTemplateBindVariable(init);if(!t2.isArrowFunctionExpression(init)&&!template)return;if(isSimpleCSFStory(init,annotations)){objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryFn"),init)]));return}let storyFn=template?t2.identifier(template):init,renderAnnotation=isReactGlobalRenderFn(csf,template?csf._templates[template]:storyFn)?[]:[t2.objectProperty(t2.identifier("render"),storyFn)];objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryObj"),t2.objectExpression([...renderAnnotation,...annotations]))]))}}),csf._ast.program.body=csf._ast.program.body.reduce((acc,stmt)=>{let statement=stmt;if(isStoryAnnotation(statement,objectExports))return acc;let newExport=getNewExport(statement,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(statement),acc)},[]),upgradeDeprecatedTypes(file),importHelper.removeDeprecatedStoryImport(),removeUnusedTemplates(csf);let output=(0,import_csf_tools2.printCsf)(csf).code;try{
|
2
|
+
Rename this local import and try again.`);specifier.remove()}}})}}),file.path.traverse({TSTypeReference:path=>{let typeName=path.get("typeName");if(typeName.isIdentifier())typeReferencesToUpdate.has(typeName.node.name)&&typeName.replaceWith(t.identifier(migrateType(typeName.node.name)));else if(typeName.isTSQualifiedName()){let namespace=typeName.get("left");if(namespace.isIdentifier()&&importedNamespaces.has(namespace.node.name)){let right=typeName.get("right");deprecatedTypes.includes(right.node.name)&&right.replaceWith(t.identifier(migrateType(right.node.name)))}}}})}var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t2.isCallExpression(init)&&t2.isMemberExpression(init.callee)&&t2.isIdentifier(init.callee.object)&&t2.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t2.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t2.isExpressionStatement(stmt)&&t2.isAssignmentExpression(stmt.expression)&&t2.isMemberExpression(stmt.expression.left)&&t2.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],getNewExport=(stmt,objectExports)=>{if(t2.isExportNamedDeclaration(stmt)&&t2.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t2.isVariableDeclarator(decl)&&t2.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{if(csf._meta?.component&&t2.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t2.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t2.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t2.isJSXSpreadAttribute(attr)&&t2.isIdentifier(attr.argument)&&t2.isIdentifier(param)&¶m.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t2.isArrowFunctionExpression(init)&&init.params.length===0;function removeUnusedTemplates(csf){Object.entries(csf._templates).forEach(([template,templateExpression])=>{let references=[];if(babel2.traverse(csf._ast,{Identifier:path=>{path.node.name===template&&references.push(path)}}),references.length===1){let reference=references[0];reference.parentPath?.isVariableDeclarator()&&reference.parentPath.node.init===templateExpression&&reference.parentPath.remove()}})}async function transform(info,api,options){let makeTitle=userTitle=>userTitle||"FIXME",csf=(0,import_csf_tools2.loadCsf)(info.source,{makeTitle});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),info.source}let file=new babel2.File({filename:info.path},{code:info.source,ast:csf._ast}),importHelper=new StorybookImportHelper(file,info),objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t2.objectProperty(t2.identifier(renameAnnotation(annotation)),val));if(t2.isVariableDeclarator(decl)){let{init,id}=decl;(0,import_tiny_invariant.default)(init,"Inital value should be declared");let template=getTemplateBindVariable(init);if(!t2.isArrowFunctionExpression(init)&&!template)return;if(isSimpleCSFStory(init,annotations)){objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryFn"),init)]));return}let storyFn=template?t2.identifier(template):init,renderAnnotation=isReactGlobalRenderFn(csf,template?csf._templates[template]:storyFn)?[]:[t2.objectProperty(t2.identifier("render"),storyFn)];objectExports[key]=t2.exportNamedDeclaration(t2.variableDeclaration("const",[t2.variableDeclarator(importHelper.updateTypeTo(id,"StoryObj"),t2.objectExpression([...renderAnnotation,...annotations]))]))}}),csf._ast.program.body=csf._ast.program.body.reduce((acc,stmt)=>{let statement=stmt;if(isStoryAnnotation(statement,objectExports))return acc;let newExport=getNewExport(statement,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(statement),acc)},[]),upgradeDeprecatedTypes(file),importHelper.removeDeprecatedStoryImport(),removeUnusedTemplates(csf);let output=(0,import_csf_tools2.printCsf)(csf).code;try{output=await import_prettier2.default.format(output,{...await import_prettier2.default.resolveConfig(info.path),filepath:info.path})}catch{logger.log(`Failed applying prettier to ${info.path}.`)}return output}var StorybookImportHelper=class{constructor(file,info){this.getAllSbImportDeclarations=file=>{let found=[];return file.path.traverse({ImportDeclaration:path=>{let source=path.node.source.value;if(source.startsWith("@storybook/csf")||!source.startsWith("@storybook"))return;path.get("specifiers").some(specifier=>{if(specifier.isImportNamespaceSpecifier())throw new Error(`This codemod does not support namespace imports for a ${path.node.source.value} package.
|
3
3
|
Replace the namespace import with named imports and try again.`);if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return Array.isArray(imported)?imported.some(importedSpecifier=>importedSpecifier.isIdentifier()?["Story","StoryFn","StoryObj","Meta","ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta"].includes(importedSpecifier.node.name):!1):imported.isIdentifier()?["Story","StoryFn","StoryObj","Meta","ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta"].includes(imported.node.name):!1})&&found.push(path)}}),found};this.getOrAddImport=type=>{let sbImport=this.sbImportDeclarations.find(path=>path.node.importKind==="type")??this.sbImportDeclarations[0];if(sbImport==null)return;let specifiers=sbImport.get("specifiers"),importSpecifier2=specifiers.find(specifier=>{if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return imported.isIdentifier()?imported.node.name===type:!1});return importSpecifier2?importSpecifier2.node.local.name:(specifiers[0].insertBefore(t2.importSpecifier(t2.identifier(type),t2.identifier(type))),type)};this.removeDeprecatedStoryImport=()=>{this.sbImportDeclarations.flatMap(it=>it.get("specifiers")).filter(specifier=>{if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return imported.isIdentifier()?imported.node.name==="Story":!1}).forEach(path=>path.remove())};this.getAllLocalImports=()=>this.sbImportDeclarations.flatMap(it=>it.get("specifiers")).map(it=>it.node.local.name);this.updateTypeTo=(id,type)=>{if((0,import_types.isIdentifier)(id)&&(0,import_types.isTSTypeAnnotation)(id.typeAnnotation)&&(0,import_types.isTSTypeReference)(id.typeAnnotation.typeAnnotation)&&(0,import_types.isIdentifier)(id.typeAnnotation.typeAnnotation.typeName)){let{name}=id.typeAnnotation.typeAnnotation.typeName;if(this.getAllLocalImports().includes(name)){let localTypeImport=this.getOrAddImport(type);return{...id,typeAnnotation:t2.tsTypeAnnotation(t2.tsTypeReference(t2.identifier(localTypeImport??""),id.typeAnnotation.typeAnnotation.typeParameters))}}}return id};this.sbImportDeclarations=this.getAllSbImportDeclarations(file)}},parser="tsx";0&&(module.exports={parser});
|
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var find_implicit_spies_exports={};__export(find_implicit_spies_exports,{default:()=>transform,parser:()=>parser});module.exports=__toCommonJS(find_implicit_spies_exports);var import_csf_tools=require("@storybook/csf-tools"),babel=__toESM(require("@babel/core")),import_types=require("@babel/types");function findImplicitSpies(path,file,keys){path.traverse({Identifier:identifier=>{!keys.includes(identifier.node.name)&&/^on[A-Z].*/.test(identifier.node.name)&&console.warn(identifier.buildCodeFrameError(`${file} Possible implicit spy found`).message)}})}function getAnnotationKeys(file,storyName,annotationName){let argKeys=[];return file.path.traverse({AssignmentExpression:path=>{let left=path.get("left");if(!left.isMemberExpression())return;let object=left.get("object");if(!(object.isIdentifier()&&object.node.name===storyName))return;let property=left.get("property"),right=path.get("right");property.isIdentifier()&&property.node.name===annotationName&&right.isObjectExpression()&&argKeys.push(...right.node.properties.flatMap(value=>(0,import_types.isObjectProperty)(value)&&(0,import_types.isIdentifier)(value.key)?[value.key.name]:[]))},VariableDeclarator:path=>{let id=path.get("id"),init=path.get("init");if(!(id.isIdentifier()&&id.node.name===storyName)||!init.isObjectExpression())return;let args=init.get("properties").flatMap(it=>it.isObjectProperty()?[it]:[]).find(it=>{let argKey=it.get("key");return argKey.isIdentifier()&&argKey.node.name===annotationName});if(!args)return;let argsValue=args.get("value");!argsValue||!argsValue.isObjectExpression()||argKeys.push(...argsValue.node.properties.flatMap(value=>(0,import_types.isObjectProperty)(value)&&(0,import_types.isIdentifier)(value.key)?[value.key.name]:[]))}}),argKeys}var getObjectExpressionKeys=node=>(0,import_types.isObjectExpression)(node)?node.properties.flatMap(value=>(0,import_types.isObjectProperty)(value)&&(0,import_types.isIdentifier)(value.key)?[value.key.name]:[]):[];async function transform(info){let csf=(0,import_csf_tools.loadCsf)(info.source,{makeTitle:title=>title}),fileNode=csf._ast,file=new babel.File({filename:info.path},{code:info.source,ast:fileNode});csf.parse();let metaKeys=[...getObjectExpressionKeys(csf._metaAnnotations.args),...getObjectExpressionKeys(csf._metaAnnotations.argTypes)];Object.entries(csf.stories).forEach(([key,{name}])=>{if(!name)return;let allKeys=[...metaKeys,...getAnnotationKeys(file,name,"args"),...getAnnotationKeys(file,name,"argTypes")];file.path.traverse({AssignmentExpression:path=>{let left=path.get("left");if(!left.isMemberExpression())return;let object=left.get("object");if(!(object.isIdentifier()&&object.node.name===name))return;let property=left.get("property");property.isIdentifier()&&property.node.name==="play"&&findImplicitSpies(path,info.path,allKeys)},VariableDeclarator:path=>{let id=path.get("id"),init=path.get("init");if(!(id.isIdentifier()&&id.node.name===name)||!init.isObjectExpression())return;let play=init.get("properties").flatMap(it=>it.isObjectProperty()?[it]:[]).find(it=>{let argKey=it.get("key");return argKey.isIdentifier()&&argKey.node.name==="play"});play&&findImplicitSpies(play,info.path,allKeys)}})})}var parser="tsx";0&&(module.exports={parser});
|
@@ -55,7 +55,7 @@ Defaulting to 2020, but this will stop working in the future.`)),options.ecmaVer
|
|
55
55
|
`;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return codePointToString(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),inTemplate){var codePos=this.pos-1;this.invalidStringToken(codePos,"Invalid escape sequence in template string")}default:if(ch>=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],octal=parseInt(octalStr,8);return octal>255&&(octalStr=octalStr.slice(0,-1),octal=parseInt(octalStr,8)),this.pos+=octalStr.length-1,ch=this.input.charCodeAt(this.pos),(octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)&&this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(octal)}return isNewLine(ch)?"":String.fromCharCode(ch)}};pp.readHexChar=function(len){var codePos=this.pos,n=this.readInt(16,len);return n===null&&this.invalidStringToken(codePos,"Bad character escape sequence"),n};pp.readWord1=function(){this.containsEsc=!1;for(var word="",first=!0,chunkStart=this.pos,astral=this.options.ecmaVersion>=6;this.pos<this.input.length;){var ch=this.fullCharCodeAtPos();if(isIdentifierChar(ch,astral))this.pos+=ch<=65535?1:2;else if(ch===92){this.containsEsc=!0,word+=this.input.slice(chunkStart,this.pos);var escStart=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var esc=this.readCodePoint();(first?isIdentifierStart:isIdentifierChar)(esc,astral)||this.invalidStringToken(escStart,"Invalid Unicode escape"),word+=codePointToString(esc),chunkStart=this.pos}else break;first=!1}return word+this.input.slice(chunkStart,this.pos)};pp.readWord=function(){var word=this.readWord1(),type=types$1.name;return this.keywords.test(word)&&(type=keywords[word]),this.finishToken(type,word)};var version="8.11.2";Parser.acorn={Parser,version,defaultOptions,Position,SourceLocation,getLineInfo,Node,TokenType,tokTypes:types$1,keywordTypes:keywords,TokContext,tokContexts:types,isIdentifierChar,isIdentifierStart,Token,isNewLine,lineBreak,lineBreakG,nonASCIIwhitespace};var import_acorn_jsx=__toESM(require_acorn_jsx(),1);function color2(d){return"\x1B[33m"+d+"\x1B[39m"}var own6={}.hasOwnProperty,CONTINUE2=Symbol("continue"),EXIT2=Symbol("exit"),SKIP2=Symbol("skip");function visit2(tree,visitor){let enter,leave;typeof visitor=="function"?enter=visitor:visitor&&typeof visitor=="object"&&(visitor.enter&&(enter=visitor.enter),visitor.leave&&(leave=visitor.leave)),build(tree,void 0,void 0,[])();function build(node3,key,index2,parents){return nodelike(node3)&&(visit3.displayName="node ("+color2(node3.type)+")"),visit3;function visit3(){let result=enter?toResult2(enter(node3,key,index2,parents)):[];if(result[0]===EXIT2)return result;if(result[0]!==SKIP2){let cKey;for(cKey in node3)if(own6.call(node3,cKey)&&node3[cKey]&&typeof node3[cKey]=="object"&&cKey!=="data"&&cKey!=="position"){let grandparents=parents.concat(node3),value=node3[cKey];if(Array.isArray(value)){let nodes=value,cIndex=0;for(;cIndex>-1&&cIndex<nodes.length;){let subvalue=nodes[cIndex];if(nodelike(subvalue)){let subresult=build(subvalue,cKey,cIndex,grandparents)();if(subresult[0]===EXIT2)return subresult;cIndex=typeof subresult[1]=="number"?subresult[1]:cIndex+1}else cIndex++}}else if(nodelike(value)){let subresult=build(value,cKey,void 0,grandparents)();if(subresult[0]===EXIT2)return subresult}}}return leave?toResult2(leave(node3,key,index2,parents)):result}}}function toResult2(value){return Array.isArray(value)?value:typeof value=="number"?[CONTINUE2,value]:[value]}function nodelike(value){return!!(value&&typeof value=="object"&&"type"in value&&typeof value.type=="string"&&value.type.length>0)}function eventsToAcorn(events,options){let prefix=options.prefix||"",suffix=options.suffix||"",acornOptions=Object.assign({},options.acornOptions),comments=[],tokens=[],onComment=acornOptions.onComment,onToken=acornOptions.onToken,swallow=!1,estree,exception,acornConfig=Object.assign({},acornOptions,{onComment:comments,preserveParens:!0});onToken&&(acornConfig.onToken=tokens);let collection=collect(events,options.tokenTypes),source=collection.value,value=prefix+source+suffix,isEmptyExpression=options.expression&&empty3(source);if(isEmptyExpression&&!options.allowEmpty)throw new VFileMessage("Unexpected empty expression",{place:parseOffsetToUnistPoint(0),ruleId:"unexpected-empty-expression",source:"micromark-extension-mdx-expression"});try{estree=options.expression&&!isEmptyExpression?options.acorn.parseExpressionAt(value,0,acornConfig):options.acorn.parse(value,acornConfig)}catch(error_){let error=error_,point3=parseOffsetToUnistPoint(error.pos);error.message=String(error.message).replace(/ \(\d+:\d+\)$/,""),error.pos=point3.offset,error.loc={line:point3.line,column:point3.column-1},exception=error,swallow=error.raisedAt>=prefix.length+source.length||error.message==="Unterminated comment"}if(estree&&options.expression&&!isEmptyExpression)if(empty3(value.slice(estree.end,value.length-suffix.length)))estree={type:"Program",start:0,end:prefix.length+source.length,body:[{type:"ExpressionStatement",expression:estree,start:0,end:prefix.length+source.length}],sourceType:"module",comments:[]};else{let point3=parseOffsetToUnistPoint(estree.end),error=new Error("Unexpected content after expression");error.pos=point3.offset,error.loc={line:point3.line,column:point3.column-1},exception=error,estree=void 0}if(estree){if(estree.comments=comments,visit2(estree,function(esnode,field,index2,parents){let context=parents[parents.length-1],prop=field;esnode.type==="ParenthesizedExpression"&&context&&prop&&(typeof index2=="number"&&(context=context[prop],prop=index2),context[prop]=esnode.expression),fixPosition(esnode)}),Array.isArray(onComment))onComment.push(...comments);else if(typeof onComment=="function")for(let comment of comments)onComment(comment.type==="Block",comment.value,comment.start,comment.end,comment.loc.start,comment.loc.end);for(let token of tokens)token.end<=prefix.length||token.start-prefix.length>=source.length||(fixPosition(token),Array.isArray(onToken)?onToken.push(token):onToken(token))}return{estree,error:exception,swallow};function fixPosition(nodeOrToken){let pointStart=parseOffsetToUnistPoint(nodeOrToken.start),pointEnd=parseOffsetToUnistPoint(nodeOrToken.end);nodeOrToken.start=pointStart.offset,nodeOrToken.end=pointEnd.offset,nodeOrToken.loc={start:{line:pointStart.line,column:pointStart.column-1,offset:pointStart.offset},end:{line:pointEnd.line,column:pointEnd.column-1,offset:pointEnd.offset}},nodeOrToken.range=[nodeOrToken.start,nodeOrToken.end]}function parseOffsetToUnistPoint(acornOffset){let sourceOffset=acornOffset-prefix.length;sourceOffset<0?sourceOffset=0:sourceOffset>source.length&&(sourceOffset=source.length);let point3=relativeToPoint(collection.stops,sourceOffset);return point3||(point3={line:options.start.line,column:options.start.column,offset:options.start.offset}),point3}}function empty3(value){return/^\s*$/.test(value.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\r\n]*(\r\n|\n|\r)/g,""))}function collect(events,tokenTypes){let result={value:"",stops:[]},index2=-1;for(;++index2<events.length;){let event=events[index2];if(event[0]==="enter"){let type=event[1].type;if(type==="lineEnding"||tokenTypes.includes(type)){let chunks=event[2].sliceStream(event[1]);for(;chunks.length>0&&chunks[0]===-1;)chunks.shift();let value=serializeChunks2(chunks);result.stops.push([result.value.length,event[1].start]),result.value+=value,result.stops.push([result.value.length,event[1].end])}}}return result}function relativeToPoint(stops,relative){let index2=0;for(;index2<stops.length&&stops[index2][0]<=relative;)index2+=1;if(index2===0)return;let[stopRelative,stopAbsolute]=stops[index2-1],rest=relative-stopRelative;return{line:stopAbsolute.line,column:stopAbsolute.column+rest,offset:stopAbsolute.offset+rest}}function serializeChunks2(chunks){let index2=-1,result=[],atTab;for(;++index2<chunks.length;){let chunk=chunks[index2],value;if(typeof chunk=="string")value=chunk;else switch(chunk){case-5:{value="\r";break}case-4:{value=`
|
56
56
|
`;break}case-3:{value=`\r
|
57
57
|
`;break}case-2:{value=" ";break}case-1:{if(atTab)continue;value=" ";break}default:value=String.fromCharCode(chunk)}atTab=chunk===-2,result.push(value)}return result.join("")}function positionFromEstree(node3){let nodeLike=node3||{},loc=nodeLike.loc||{},range=nodeLike.range||[void 0,void 0],start2=pointOrUndefined(loc.start,range[0]||nodeLike.start),end=pointOrUndefined(loc.end,range[1]||nodeLike.end);if(start2&&end)return{start:start2,end}}function pointOrUndefined(estreePoint,estreeOffset){if(estreePoint&&typeof estreePoint=="object"){let line="line"in estreePoint?numberOrUndefined(estreePoint.line):void 0,column="column"in estreePoint?numberOrUndefined(estreePoint.column):void 0;if(line&&column!==void 0)return{line,column:column+1,offset:numberOrUndefined(estreeOffset)}}}function numberOrUndefined(value){return typeof value=="number"&&value>-1?value:void 0}var trouble="https://github.com/micromark/micromark-extension-mdx-expression/tree/main/packages/micromark-extension-mdx-expression",unexpectedEofHash="#unexpected-end-of-file-in-expression-expected-a-corresponding-closing-brace-for-",unexpectedLazyHash="#unexpected-lazy-line-in-expression-in-container-expected-line-to-be-prefixed",nonSpreadHash="#unexpected-type-in-code-expected-an-object-spread-spread",spreadExtraHash="#unexpected-extra-content-in-spread-only-a-single-spread-is-supported",acornHash="#could-not-parse-expression-with-acorn";function factoryMdxExpression(effects,ok2,type,markerType,chunkType,acorn,acornOptions,addResult,spread,allowEmpty,allowLazy){let self2=this,eventStart=this.events.length+3,size=0,pointStart,lastCrash;return start2;function start2(code2){return effects.enter(type),effects.enter(markerType),effects.consume(code2),effects.exit(markerType),pointStart=self2.now(),before}function before(code2){if(code2===null){if(lastCrash)throw lastCrash;let error=new VFileMessage("Unexpected end of file in expression, expected a corresponding closing brace for `{`",{place:self2.now(),ruleId:"unexpected-eof",source:"micromark-extension-mdx-expression"});throw error.url=trouble+unexpectedEofHash,error}if(markdownLineEnding(code2))return effects.enter("lineEnding"),effects.consume(code2),effects.exit("lineEnding"),eolAfter;if(code2===125&&size===0){let next=acorn?mdxExpressionParse.call(self2,acorn,acornOptions,chunkType,eventStart,pointStart,allowEmpty||!1,spread||!1):{type:"ok",estree:void 0};if(next.type==="ok"){effects.enter(markerType),effects.consume(code2),effects.exit(markerType);let token=effects.exit(type);return addResult&&next.estree&&Object.assign(token,{estree:next.estree}),ok2}return lastCrash=next.message,effects.enter(chunkType),effects.consume(code2),inside}return effects.enter(chunkType),inside(code2)}function inside(code2){return code2===125&&size===0||code2===null||markdownLineEnding(code2)?(effects.exit(chunkType),before(code2)):(code2===123&&!acorn?size+=1:code2===125&&(size-=1),effects.consume(code2),inside)}function eolAfter(code2){let now=self2.now();if(now.line!==pointStart.line&&!allowLazy&&self2.parser.lazy[now.line]){let error=new VFileMessage("Unexpected lazy line in expression in container, expected line to be prefixed with `>` when in a block quote, whitespace when in a list, etc",{place:self2.now(),ruleId:"unexpected-lazy",source:"micromark-extension-mdx-expression"});throw error.url=trouble+unexpectedLazyHash,error}return before(code2)}}function mdxExpressionParse(acorn,acornOptions,chunkType,eventStart,pointStart,allowEmpty,spread){let result=eventsToAcorn(this.events.slice(eventStart),{acorn,tokenTypes:[chunkType],acornOptions,start:pointStart,expression:!0,allowEmpty,prefix:spread?"({":"",suffix:spread?"})":""}),estree=result.estree;if(spread&&estree){let head=estree.body[0];if(head.type!=="ExpressionStatement"||head.expression.type!=="ObjectExpression"){let place=positionFromEstree(head),error=new VFileMessage("Unexpected `"+head.type+"` in code: expected an object spread (`{...spread}`)",{place:place.start,ruleId:"non-spread",source:"micromark-extension-mdx-expression"});throw error.url=trouble+nonSpreadHash,error}if(head.expression.properties[1]){let place=positionFromEstree(head.expression.properties[1]),error=new VFileMessage("Unexpected extra content in spread: only a single spread is supported",{place:place.start,ruleId:"spread-extra",source:"micromark-extension-mdx-expression"});throw error.url=trouble+spreadExtraHash,error}if(head.expression.properties[0]&&head.expression.properties[0].type!=="SpreadElement"){let place=positionFromEstree(head.expression.properties[0]),error=new VFileMessage("Unexpected `"+head.expression.properties[0].type+"` in code: only spread elements are supported",{place:place.start,ruleId:"non-spread",source:"micromark-extension-mdx-expression"});throw error.url=trouble+nonSpreadHash,error}}if(result.error){let error=new VFileMessage("Could not parse expression with acorn",{cause:result.error,place:{line:result.error.loc.line,column:result.error.loc.column+1,offset:result.error.pos},ruleId:"acorn",source:"micromark-extension-mdx-expression"});return error.url=trouble+acornHash,{type:"nok",message:error}}return{type:"ok",estree}}function mdxExpression(options){let options_=options||{},addResult=options_.addResult,acorn=options_.acorn,spread=options_.spread,allowEmpty=options_.allowEmpty,acornOptions;if(allowEmpty==null&&(allowEmpty=!0),acorn){if(!acorn.parseExpressionAt)throw new Error("Expected a proper `acorn` instance passed in as `options.acorn`");acornOptions=Object.assign({ecmaVersion:2024,sourceType:"module"},options_.acornOptions)}else if(options_.acornOptions||options_.addResult)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");return{flow:{123:{name:"mdxFlowExpression",tokenize:tokenizeFlowExpression,concrete:!0}},text:{123:{name:"mdxTextExpression",tokenize:tokenizeTextExpression}}};function tokenizeFlowExpression(effects,ok2,nok){let self2=this;return start2;function start2(code2){return before(code2)}function before(code2){return factoryMdxExpression.call(self2,effects,after,"mdxFlowExpression","mdxFlowExpressionMarker","mdxFlowExpressionChunk",acorn,acornOptions,addResult,spread,allowEmpty)(code2)}function after(code2){return markdownSpace(code2)?factorySpace(effects,end,"whitespace")(code2):end(code2)}function end(code2){let lessThanValue=self2.parser.constructs.flow[60],jsxTag=(Array.isArray(lessThanValue)?lessThanValue:lessThanValue?[lessThanValue]:[]).find(function(d){return d.name==="mdxJsxFlowTag"});return code2===60&&jsxTag?effects.attempt(jsxTag,end,nok)(code2):code2===null||markdownLineEnding(code2)?ok2(code2):nok(code2)}}function tokenizeTextExpression(effects,ok2){let self2=this;return start2;function start2(code2){return factoryMdxExpression.call(self2,effects,ok2,"mdxTextExpression","mdxTextExpressionMarker","mdxTextExpressionChunk",acorn,acornOptions,addResult,spread,allowEmpty,!0)(code2)}}}var startRe=/[$_\p{ID_Start}]/u,contRe=/[$_\u{200C}\u{200D}\p{ID_Continue}]/u,contReJsx=/[-$_\u{200C}\u{200D}\p{ID_Continue}]/u;var emptyOptions3={};function start(code2){return code2?startRe.test(String.fromCodePoint(code2)):!1}function cont(code2,options){let re=(options||emptyOptions3).jsx?contReJsx:contRe;return code2?re.test(String.fromCodePoint(code2)):!1}var trouble2="https://github.com/micromark/micromark-extension-mdx-jsx";function factoryTag(effects,ok2,nok,acorn,acornOptions,addResult,allowLazy,tagType,tagMarkerType,tagClosingMarkerType,tagSelfClosingMarker,tagNameType,tagNamePrimaryType,tagNameMemberMarkerType,tagNameMemberType,tagNamePrefixMarkerType,tagNameLocalType,tagExpressionAttributeType,tagExpressionAttributeMarkerType,tagExpressionAttributeValueType,tagAttributeType,tagAttributeNameType,tagAttributeNamePrimaryType,tagAttributeNamePrefixMarkerType,tagAttributeNameLocalType,tagAttributeInitializerMarkerType,tagAttributeValueLiteralType,tagAttributeValueLiteralMarkerType,tagAttributeValueLiteralValueType,tagAttributeValueExpressionType,tagAttributeValueExpressionMarkerType,tagAttributeValueExpressionValueType){let self2=this,returnState,marker;return start2;function start2(code2){return effects.enter(tagType),effects.enter(tagMarkerType),effects.consume(code2),effects.exit(tagMarkerType),startAfter}function startAfter(code2){return markdownLineEndingOrSpace(code2)?nok(code2):(returnState=nameBefore,esWhitespaceStart(code2))}function nameBefore(code2){if(code2===47)return effects.enter(tagClosingMarkerType),effects.consume(code2),effects.exit(tagClosingMarkerType),returnState=closingTagNameBefore,esWhitespaceStart;if(code2===62)return tagEnd(code2);if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagNameType),effects.enter(tagNamePrimaryType),effects.consume(code2),primaryName;crash(code2,"before name","a character that can start a name, such as a letter, `$`, or `_`"+(code2===33?" (note: to create a comment in MDX, use `{/* text */}`)":""))}function closingTagNameBefore(code2){if(code2===62)return tagEnd(code2);if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagNameType),effects.enter(tagNamePrimaryType),effects.consume(code2),primaryName;crash(code2,"before name","a character that can start a name, such as a letter, `$`, or `_`"+(code2===42||code2===47?" (note: JS comments in JSX tags are not supported in MDX)":""))}function primaryName(code2){if(code2!==null&&code2>=0&&cont(code2,{jsx:!0}))return effects.consume(code2),primaryName;if(code2===46||code2===47||code2===58||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2))return effects.exit(tagNamePrimaryType),returnState=primaryNameAfter,esWhitespaceStart(code2);crash(code2,"in name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag"+(code2===64?" (note: to create a link in MDX, use `[text](url)`)":""))}function primaryNameAfter(code2){if(code2===46)return effects.enter(tagNameMemberMarkerType),effects.consume(code2),effects.exit(tagNameMemberMarkerType),returnState=memberNameBefore,esWhitespaceStart;if(code2===58)return effects.enter(tagNamePrefixMarkerType),effects.consume(code2),effects.exit(tagNamePrefixMarkerType),returnState=localNameBefore,esWhitespaceStart;if(code2===47||code2===62||code2===123||code2!==null&&code2>=0&&start(code2))return effects.exit(tagNameType),attributeBefore(code2);crash(code2,"after name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function memberNameBefore(code2){if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagNameMemberType),effects.consume(code2),memberName;crash(code2,"before member name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function memberName(code2){if(code2!==null&&code2>=0&&cont(code2,{jsx:!0}))return effects.consume(code2),memberName;if(code2===46||code2===47||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2))return effects.exit(tagNameMemberType),returnState=memberNameAfter,esWhitespaceStart(code2);crash(code2,"in member name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag"+(code2===64?" (note: to create a link in MDX, use `[text](url)`)":""))}function memberNameAfter(code2){if(code2===46)return effects.enter(tagNameMemberMarkerType),effects.consume(code2),effects.exit(tagNameMemberMarkerType),returnState=memberNameBefore,esWhitespaceStart;if(code2===47||code2===62||code2===123||code2!==null&&code2>=0&&start(code2))return effects.exit(tagNameType),attributeBefore(code2);crash(code2,"after member name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function localNameBefore(code2){if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagNameLocalType),effects.consume(code2),localName;crash(code2,"before local name","a character that can start a name, such as a letter, `$`, or `_`"+(code2===43||code2!==null&&code2>46&&code2<58?" (note: to create a link in MDX, use `[text](url)`)":""))}function localName(code2){if(code2!==null&&code2>=0&&cont(code2,{jsx:!0}))return effects.consume(code2),localName;if(code2===47||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2))return effects.exit(tagNameLocalType),returnState=localNameAfter,esWhitespaceStart(code2);crash(code2,"in local name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag")}function localNameAfter(code2){if(code2===47||code2===62||code2===123||code2!==null&&code2>=0&&start(code2))return effects.exit(tagNameType),attributeBefore(code2);crash(code2,"after local name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function attributeBefore(code2){if(code2===47)return effects.enter(tagSelfClosingMarker),effects.consume(code2),effects.exit(tagSelfClosingMarker),returnState=selfClosing,esWhitespaceStart;if(code2===62)return tagEnd(code2);if(code2===123)return factoryMdxExpression.call(self2,effects,attributeExpressionAfter,tagExpressionAttributeType,tagExpressionAttributeMarkerType,tagExpressionAttributeValueType,acorn,acornOptions,addResult,!0,!1,allowLazy)(code2);if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagAttributeType),effects.enter(tagAttributeNameType),effects.enter(tagAttributeNamePrimaryType),effects.consume(code2),attributePrimaryName;crash(code2,"before attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function attributeExpressionAfter(code2){return returnState=attributeBefore,esWhitespaceStart(code2)}function attributePrimaryName(code2){if(code2!==null&&code2>=0&&cont(code2,{jsx:!0}))return effects.consume(code2),attributePrimaryName;if(code2===47||code2===58||code2===61||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2))return effects.exit(tagAttributeNamePrimaryType),returnState=attributePrimaryNameAfter,esWhitespaceStart(code2);crash(code2,"in attribute name","an attribute name character such as letters, digits, `$`, or `_`; `=` to initialize a value; whitespace before attributes; or the end of the tag")}function attributePrimaryNameAfter(code2){if(code2===58)return effects.enter(tagAttributeNamePrefixMarkerType),effects.consume(code2),effects.exit(tagAttributeNamePrefixMarkerType),returnState=attributeLocalNameBefore,esWhitespaceStart;if(code2===61)return effects.exit(tagAttributeNameType),effects.enter(tagAttributeInitializerMarkerType),effects.consume(code2),effects.exit(tagAttributeInitializerMarkerType),returnState=attributeValueBefore,esWhitespaceStart;if(code2===47||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2)||code2!==null&&code2>=0&&start(code2))return effects.exit(tagAttributeNameType),effects.exit(tagAttributeType),returnState=attributeBefore,esWhitespaceStart(code2);crash(code2,"after attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function attributeLocalNameBefore(code2){if(code2!==null&&code2>=0&&start(code2))return effects.enter(tagAttributeNameLocalType),effects.consume(code2),attributeLocalName;crash(code2,"before local attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function attributeLocalName(code2){if(code2!==null&&code2>=0&&cont(code2,{jsx:!0}))return effects.consume(code2),attributeLocalName;if(code2===47||code2===61||code2===62||code2===123||markdownLineEndingOrSpace(code2)||unicodeWhitespace(code2))return effects.exit(tagAttributeNameLocalType),effects.exit(tagAttributeNameType),returnState=attributeLocalNameAfter,esWhitespaceStart(code2);crash(code2,"in local attribute name","an attribute name character such as letters, digits, `$`, or `_`; `=` to initialize a value; whitespace before attributes; or the end of the tag")}function attributeLocalNameAfter(code2){if(code2===61)return effects.enter(tagAttributeInitializerMarkerType),effects.consume(code2),effects.exit(tagAttributeInitializerMarkerType),returnState=attributeValueBefore,esWhitespaceStart;if(code2===47||code2===62||code2===123||code2!==null&&code2>=0&&start(code2))return effects.exit(tagAttributeType),attributeBefore(code2);crash(code2,"after local attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function attributeValueBefore(code2){if(code2===34||code2===39)return effects.enter(tagAttributeValueLiteralType),effects.enter(tagAttributeValueLiteralMarkerType),effects.consume(code2),effects.exit(tagAttributeValueLiteralMarkerType),marker=code2,attributeValueQuotedStart;if(code2===123)return factoryMdxExpression.call(self2,effects,attributeValueExpressionAfter,tagAttributeValueExpressionType,tagAttributeValueExpressionMarkerType,tagAttributeValueExpressionValueType,acorn,acornOptions,addResult,!1,!1,allowLazy)(code2);crash(code2,"before attribute value","a character that can start an attribute value, such as `\"`, `'`, or `{`"+(code2===60?" (note: to use an element or fragment as a prop value in MDX, use `{<element />}`)":""))}function attributeValueExpressionAfter(code2){return effects.exit(tagAttributeType),returnState=attributeBefore,esWhitespaceStart(code2)}function attributeValueQuotedStart(code2){return code2===null&&crash(code2,"in attribute value","a corresponding closing quote `"+String.fromCodePoint(marker)+"`"),code2===marker?(effects.enter(tagAttributeValueLiteralMarkerType),effects.consume(code2),effects.exit(tagAttributeValueLiteralMarkerType),effects.exit(tagAttributeValueLiteralType),effects.exit(tagAttributeType),marker=void 0,returnState=attributeBefore,esWhitespaceStart):markdownLineEnding(code2)?(returnState=attributeValueQuotedStart,esWhitespaceStart(code2)):(effects.enter(tagAttributeValueLiteralValueType),attributeValueQuoted(code2))}function attributeValueQuoted(code2){return code2===null||code2===marker||markdownLineEnding(code2)?(effects.exit(tagAttributeValueLiteralValueType),attributeValueQuotedStart(code2)):(effects.consume(code2),attributeValueQuoted)}function selfClosing(code2){if(code2===62)return tagEnd(code2);crash(code2,"after self-closing slash","`>` to end the tag"+(code2===42||code2===47?" (note: JS comments in JSX tags are not supported in MDX)":""))}function tagEnd(code2){return effects.enter(tagMarkerType),effects.consume(code2),effects.exit(tagMarkerType),effects.exit(tagType),ok2}function esWhitespaceStart(code2){return markdownLineEnding(code2)?(effects.enter("lineEnding"),effects.consume(code2),effects.exit("lineEnding"),esWhitespaceEolAfter):markdownSpace(code2)||unicodeWhitespace(code2)?(effects.enter("esWhitespace"),esWhitespaceInside(code2)):returnState(code2)}function esWhitespaceInside(code2){return markdownLineEnding(code2)?(effects.exit("esWhitespace"),esWhitespaceStart(code2)):markdownSpace(code2)||unicodeWhitespace(code2)?(effects.consume(code2),esWhitespaceInside):(effects.exit("esWhitespace"),returnState(code2))}function esWhitespaceEolAfter(code2){if(!allowLazy&&self2.parser.lazy[self2.now().line]){let error=new VFileMessage("Unexpected lazy line in container, expected line to be prefixed with `>` when in a block quote, whitespace when in a list, etc",self2.now(),"micromark-extension-mdx-jsx:unexpected-lazy");throw error.url=trouble2+"#unexpected-lazy-line-in-container-expected-line-to-be",error}return esWhitespaceStart(code2)}function crash(code2,at2,expect){let error=new VFileMessage("Unexpected "+(code2===null?"end of file":"character `"+(code2===96?"` ` `":String.fromCodePoint(code2))+"` ("+serializeCharCode(code2)+")")+" "+at2+", expected "+expect,self2.now(),"micromark-extension-mdx-jsx:unexpected-"+(code2===null?"eof":"character"));throw error.url=trouble2+(code2===null?"#unexpected-end-of-file-at-expected-expect":"#unexpected-character-at-expected-expect"),error}}function serializeCharCode(code2){return"U+"+code2.toString(16).toUpperCase().padStart(4,"0")}function jsxText(acorn,options){return{name:"mdxJsxTextTag",tokenize:tokenizeJsxText};function tokenizeJsxText(effects,ok2,nok){return factoryTag.call(this,effects,ok2,nok,acorn,options.acornOptions,options.addResult,!0,"mdxJsxTextTag","mdxJsxTextTagMarker","mdxJsxTextTagClosingMarker","mdxJsxTextTagSelfClosingMarker","mdxJsxTextTagName","mdxJsxTextTagNamePrimary","mdxJsxTextTagNameMemberMarker","mdxJsxTextTagNameMember","mdxJsxTextTagNamePrefixMarker","mdxJsxTextTagNameLocal","mdxJsxTextTagExpressionAttribute","mdxJsxTextTagExpressionAttributeMarker","mdxJsxTextTagExpressionAttributeValue","mdxJsxTextTagAttribute","mdxJsxTextTagAttributeName","mdxJsxTextTagAttributeNamePrimary","mdxJsxTextTagAttributeNamePrefixMarker","mdxJsxTextTagAttributeNameLocal","mdxJsxTextTagAttributeInitializerMarker","mdxJsxTextTagAttributeValueLiteral","mdxJsxTextTagAttributeValueLiteralMarker","mdxJsxTextTagAttributeValueLiteralValue","mdxJsxTextTagAttributeValueExpression","mdxJsxTextTagAttributeValueExpressionMarker","mdxJsxTextTagAttributeValueExpressionValue")}}function jsxFlow(acorn,options){return{name:"mdxJsxFlowTag",tokenize:tokenizeJsxFlow,concrete:!0};function tokenizeJsxFlow(effects,ok2,nok){let self2=this;return start2;function start2(code2){return before(code2)}function before(code2){return factoryTag.call(self2,effects,after,nok,acorn,options.acornOptions,options.addResult,!1,"mdxJsxFlowTag","mdxJsxFlowTagMarker","mdxJsxFlowTagClosingMarker","mdxJsxFlowTagSelfClosingMarker","mdxJsxFlowTagName","mdxJsxFlowTagNamePrimary","mdxJsxFlowTagNameMemberMarker","mdxJsxFlowTagNameMember","mdxJsxFlowTagNamePrefixMarker","mdxJsxFlowTagNameLocal","mdxJsxFlowTagExpressionAttribute","mdxJsxFlowTagExpressionAttributeMarker","mdxJsxFlowTagExpressionAttributeValue","mdxJsxFlowTagAttribute","mdxJsxFlowTagAttributeName","mdxJsxFlowTagAttributeNamePrimary","mdxJsxFlowTagAttributeNamePrefixMarker","mdxJsxFlowTagAttributeNameLocal","mdxJsxFlowTagAttributeInitializerMarker","mdxJsxFlowTagAttributeValueLiteral","mdxJsxFlowTagAttributeValueLiteralMarker","mdxJsxFlowTagAttributeValueLiteralValue","mdxJsxFlowTagAttributeValueExpression","mdxJsxFlowTagAttributeValueExpressionMarker","mdxJsxFlowTagAttributeValueExpressionValue")(code2)}function after(code2){return markdownSpace(code2)?factorySpace(effects,end,"whitespace")(code2):end(code2)}function end(code2){let leftBraceValue=self2.parser.constructs.flow[123],expression=(Array.isArray(leftBraceValue)?leftBraceValue:leftBraceValue?[leftBraceValue]:[]).find(d=>d.name==="mdxFlowExpression");return code2===60?start2(code2):code2===123&&expression?effects.attempt(expression,end,nok)(code2):code2===null||markdownLineEnding(code2)?ok2(code2):nok(code2)}}}function mdxJsx(options){let settings=options||{},acorn=settings.acorn,acornOptions;if(acorn){if(!acorn.parse||!acorn.parseExpressionAt)throw new Error("Expected a proper `acorn` instance passed in as `options.acorn`");acornOptions=Object.assign({ecmaVersion:2024,sourceType:"module"},settings.acornOptions,{locations:!0})}else if(settings.acornOptions||settings.addResult)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");return{flow:{60:jsxFlow(acorn||void 0,{acornOptions,addResult:settings.addResult||void 0})},text:{60:jsxText(acorn||void 0,{acornOptions,addResult:settings.addResult||void 0})}}}function mdxMd(){return{disable:{null:["autolink","codeIndented","htmlFlow","htmlText"]}}}var blankLineBefore2={tokenize:tokenizeNextBlank,partial:!0},trouble3="https://github.com/micromark/micromark-extension-mdxjs-esm",allowedAcornTypes=new Set(["ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ImportDeclaration"]);function mdxjsEsm(options){let exportImportConstruct={tokenize:tokenizeExportImport,concrete:!0};if(!options||!options.acorn||!options.acorn.parse)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");let acorn=options.acorn,acornOptions=Object.assign({ecmaVersion:2024,sourceType:"module"},options.acornOptions,{locations:!0});return{flow:{101:exportImportConstruct,105:exportImportConstruct}};function tokenizeExportImport(effects,ok2,nok){let self2=this,definedModuleSpecifiers=self2.parser.definedModuleSpecifiers||(self2.parser.definedModuleSpecifiers=[]),eventStart=this.events.length+1,buffer="";return self2.interrupt?nok:start2;function start2(code2){return self2.now().column>1?nok(code2):(effects.enter("mdxjsEsm"),effects.enter("mdxjsEsmData"),effects.consume(code2),buffer+=String.fromCharCode(code2),word)}function word(code2){return asciiAlpha(code2)?(effects.consume(code2),buffer+=String.fromCharCode(code2),word):(buffer==="import"||buffer==="export")&&code2===32?(effects.consume(code2),inside):nok(code2)}function inside(code2){return code2===null||markdownLineEnding(code2)?(effects.exit("mdxjsEsmData"),lineStart(code2)):(effects.consume(code2),inside)}function lineStart(code2){return code2===null?atEnd(code2):markdownLineEnding(code2)?effects.check(blankLineBefore2,atEnd,continuationStart)(code2):(effects.enter("mdxjsEsmData"),inside(code2))}function continuationStart(code2){return effects.enter("lineEnding"),effects.consume(code2),effects.exit("lineEnding"),lineStart}function atEnd(code2){let result=eventsToAcorn(self2.events.slice(eventStart),{acorn,acornOptions,tokenTypes:["mdxjsEsmData"],prefix:definedModuleSpecifiers.length>0?"var "+definedModuleSpecifiers.join(",")+`
|
58
|
-
`:""});if(result.error){if(code2!==null&&result.swallow)return continuationStart(code2);let error=new VFileMessage("Could not parse import/exports with acorn",{cause:result.error,place:{line:result.error.loc.line,column:result.error.loc.column+1,offset:result.error.pos},ruleId:"acorn",source:"micromark-extension-mdxjs-esm"});throw error.url=trouble3+"#could-not-parse-importexports-with-acorn",error}if(definedModuleSpecifiers.length>0){let declaration=result.estree.body.shift()}let index2=-1;for(;++index2<result.estree.body.length;){let node3=result.estree.body[index2];if(!allowedAcornTypes.has(node3.type)){let error=new VFileMessage("Unexpected `"+node3.type+"` in code: only import/exports are supported",{place:positionFromEstree(node3),ruleId:"non-esm",source:"micromark-extension-mdxjs-esm"});throw error.url=trouble3+"#unexpected-type-in-code-only-importexports-are-supported",error}if(node3.type==="ImportDeclaration"&&!self2.interrupt){let index3=-1;for(;++index3<node3.specifiers.length;){let specifier=node3.specifiers[index3];definedModuleSpecifiers.push(specifier.local.name)}}}return Object.assign(effects.exit("mdxjsEsm"),options.addResult?{estree:result.estree}:void 0),ok2(code2)}}}function tokenizeNextBlank(effects,ok2,nok){return start2;function start2(code2){return effects.enter("lineEndingBlank"),effects.consume(code2),effects.exit("lineEndingBlank"),effects.attempt(blankLine,ok2,nok)}}function mdxjs(options){let settings=Object.assign({acorn:Parser.extend((0,import_acorn_jsx.default)()),acornOptions:{ecmaVersion:2024,sourceType:"module"},addResult:!0},options);return combineExtensions([mdxjsEsm(settings),mdxExpression(settings),mdxJsx(settings),mdxMd()])}var emptyOptions4={};function remarkMdx(options){let self2=this,settings=options||emptyOptions4,data2=self2.data(),micromarkExtensions=data2.micromarkExtensions||(data2.micromarkExtensions=[]),fromMarkdownExtensions=data2.fromMarkdownExtensions||(data2.fromMarkdownExtensions=[]),toMarkdownExtensions=data2.toMarkdownExtensions||(data2.toMarkdownExtensions=[]);micromarkExtensions.push(mdxjs(settings)),fromMarkdownExtensions.push(mdxFromMarkdown()),toMarkdownExtensions.push(mdxToMarkdown(settings))}var t=__toESM(require("@babel/types")),babel=__toESM(require("@babel/core")),recast=__toESM(require("recast")),path=__toESM(require("path")),import_prettier=__toESM(require("prettier")),fs=__toESM(require("fs")),import_camelCase=__toESM(require("lodash/camelCase")),mdxProcessor=remark().use(remarkMdx);async function jscodeshift(info){let parsed=path.parse(info.path),baseName=path.join(parsed.dir,parsed.name.replace(".mdx","").replace(".stories","").replace(".story",""));for(;fs.existsSync(`${baseName}.stories.js`);)baseName+="_";let result=await transform(info,path.basename(baseName)),[mdx,csf]=result;return csf!=null&&fs.writeFileSync(`${baseName}.stories.js`,csf),mdx}async function transform(info,baseName){let root2=mdxProcessor.parse(info.source),storyNamespaceName=nameToValidExport(`${baseName}Stories`),metaAttributes=[],storiesMap=new Map;visit(root2,["mdxjsEsm"],node3=>{node3.value=node3.value.replaceAll("@storybook/addon-docs/blocks","@storybook/blocks").replaceAll("@storybook/addon-docs","@storybook/blocks")});let file=getEsmAst(root2);visit(root2,["mdxJsxFlowElement","mdxJsxTextElement"],(node3,index2,parent)=>{if((node3.type==="mdxJsxFlowElement"||node3.type==="mdxJsxTextElement")&&(is(node3,{name:"Meta"})&&(metaAttributes.push(...node3.attributes),node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:storyNamespaceName}}]),is(node3,{name:"Story"}))){let nameAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="name"),idAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="id"),storyAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="story");if(typeof nameAttribute?.value=="string"){let name2=nameToValidExport(nameAttribute.value);for(;variableNameExists(name2);)name2+="_";storiesMap.set(name2,{type:"value",attributes:node3.attributes,children:node3.children}),node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:`${storyNamespaceName}.${name2}`}}],node3.children=[]}else if(idAttribute?.value){let newNode={type:"mdxFlowExpression",value:`/* ${mdxProcessor.stringify({type:"root",children:[node3]}).trim()} is deprecated, please migrate it to <Story of={referenceToStory} /> see: https://storybook.js.org/migration-guides/7.0 */`};return storiesMap.set(idAttribute.value,{type:"id"}),parent?.children.splice(index2,0,newNode),[SKIP,index2+2]}else if(storyAttribute?.type==="mdxJsxAttribute"&&typeof storyAttribute.value=="object"&&storyAttribute.value?.type==="mdxJsxAttributeValueExpression"){let name2=storyAttribute.value?.value;node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:`${storyNamespaceName}.${name2}`}}],node3.children=[],storiesMap.set(name2??"",{type:"reference"})}else return parent?.children.splice(index2,1),[SKIP,index2]}});let metaProperties=metaAttributes.flatMap(attribute=>attribute.type==="mdxJsxAttribute"?typeof attribute.value=="string"?[t.objectProperty(t.identifier(attribute.name),t.stringLiteral(attribute.value))]:[t.objectProperty(t.identifier(attribute.name),(0,import_csf_tools.babelParseExpression)(attribute.value?.value??""))]:[]);if(file.path.traverse({ImportDeclaration(
|
58
|
+
`:""});if(result.error){if(code2!==null&&result.swallow)return continuationStart(code2);let error=new VFileMessage("Could not parse import/exports with acorn",{cause:result.error,place:{line:result.error.loc.line,column:result.error.loc.column+1,offset:result.error.pos},ruleId:"acorn",source:"micromark-extension-mdxjs-esm"});throw error.url=trouble3+"#could-not-parse-importexports-with-acorn",error}if(definedModuleSpecifiers.length>0){let declaration=result.estree.body.shift()}let index2=-1;for(;++index2<result.estree.body.length;){let node3=result.estree.body[index2];if(!allowedAcornTypes.has(node3.type)){let error=new VFileMessage("Unexpected `"+node3.type+"` in code: only import/exports are supported",{place:positionFromEstree(node3),ruleId:"non-esm",source:"micromark-extension-mdxjs-esm"});throw error.url=trouble3+"#unexpected-type-in-code-only-importexports-are-supported",error}if(node3.type==="ImportDeclaration"&&!self2.interrupt){let index3=-1;for(;++index3<node3.specifiers.length;){let specifier=node3.specifiers[index3];definedModuleSpecifiers.push(specifier.local.name)}}}return Object.assign(effects.exit("mdxjsEsm"),options.addResult?{estree:result.estree}:void 0),ok2(code2)}}}function tokenizeNextBlank(effects,ok2,nok){return start2;function start2(code2){return effects.enter("lineEndingBlank"),effects.consume(code2),effects.exit("lineEndingBlank"),effects.attempt(blankLine,ok2,nok)}}function mdxjs(options){let settings=Object.assign({acorn:Parser.extend((0,import_acorn_jsx.default)()),acornOptions:{ecmaVersion:2024,sourceType:"module"},addResult:!0},options);return combineExtensions([mdxjsEsm(settings),mdxExpression(settings),mdxJsx(settings),mdxMd()])}var emptyOptions4={};function remarkMdx(options){let self2=this,settings=options||emptyOptions4,data2=self2.data(),micromarkExtensions=data2.micromarkExtensions||(data2.micromarkExtensions=[]),fromMarkdownExtensions=data2.fromMarkdownExtensions||(data2.fromMarkdownExtensions=[]),toMarkdownExtensions=data2.toMarkdownExtensions||(data2.toMarkdownExtensions=[]);micromarkExtensions.push(mdxjs(settings)),fromMarkdownExtensions.push(mdxFromMarkdown()),toMarkdownExtensions.push(mdxToMarkdown(settings))}var t=__toESM(require("@babel/types")),babel=__toESM(require("@babel/core")),recast=__toESM(require("recast")),path=__toESM(require("path")),import_prettier=__toESM(require("prettier")),fs=__toESM(require("fs")),import_camelCase=__toESM(require("lodash/camelCase")),mdxProcessor=remark().use(remarkMdx);async function jscodeshift(info){let parsed=path.parse(info.path),baseName=path.join(parsed.dir,parsed.name.replace(".mdx","").replace(".stories","").replace(".story",""));for(;fs.existsSync(`${baseName}.stories.js`);)baseName+="_";let result=await transform(info,path.basename(baseName)),[mdx,csf]=result;return csf!=null&&fs.writeFileSync(`${baseName}.stories.js`,csf),mdx}async function transform(info,baseName){let root2=mdxProcessor.parse(info.source),storyNamespaceName=nameToValidExport(`${baseName}Stories`),metaAttributes=[],storiesMap=new Map;visit(root2,["mdxjsEsm"],node3=>{node3.value=node3.value.replaceAll("@storybook/addon-docs/blocks","@storybook/blocks").replaceAll("@storybook/addon-docs","@storybook/blocks")});let file=getEsmAst(root2);visit(root2,["mdxJsxFlowElement","mdxJsxTextElement"],(node3,index2,parent)=>{if((node3.type==="mdxJsxFlowElement"||node3.type==="mdxJsxTextElement")&&(is(node3,{name:"Meta"})&&(metaAttributes.push(...node3.attributes),node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:storyNamespaceName}}]),is(node3,{name:"Story"}))){let nameAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="name"),idAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="id"),storyAttribute=node3.attributes.find(it=>it.type==="mdxJsxAttribute"&&it.name==="story");if(typeof nameAttribute?.value=="string"){let name2=nameToValidExport(nameAttribute.value);for(;variableNameExists(name2);)name2+="_";storiesMap.set(name2,{type:"value",attributes:node3.attributes,children:node3.children}),node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:`${storyNamespaceName}.${name2}`}}],node3.children=[]}else if(idAttribute?.value){let newNode={type:"mdxFlowExpression",value:`/* ${mdxProcessor.stringify({type:"root",children:[node3]}).trim()} is deprecated, please migrate it to <Story of={referenceToStory} /> see: https://storybook.js.org/migration-guides/7.0 */`};return storiesMap.set(idAttribute.value,{type:"id"}),parent?.children.splice(index2,0,newNode),[SKIP,index2+2]}else if(storyAttribute?.type==="mdxJsxAttribute"&&typeof storyAttribute.value=="object"&&storyAttribute.value?.type==="mdxJsxAttributeValueExpression"){let name2=storyAttribute.value?.value;node3.attributes=[{type:"mdxJsxAttribute",name:"of",value:{type:"mdxJsxAttributeValueExpression",value:`${storyNamespaceName}.${name2}`}}],node3.children=[],storiesMap.set(name2??"",{type:"reference"})}else return parent?.children.splice(index2,1),[SKIP,index2]}});let metaProperties=metaAttributes.flatMap(attribute=>attribute.type==="mdxJsxAttribute"?typeof attribute.value=="string"?[t.objectProperty(t.identifier(attribute.name),t.stringLiteral(attribute.value))]:[t.objectProperty(t.identifier(attribute.name),(0,import_csf_tools.babelParseExpression)(attribute.value?.value??""))]:[]);if(file.path.traverse({ImportDeclaration(path3){path3.node.source.value==="@storybook/blocks"&&path3.remove()},ExportNamedDeclaration(path3){path3.replaceWith(path3.node.declaration)}}),storiesMap.size===0&&metaAttributes.length===0)return[mdxProcessor.stringify(root2),""];addStoriesImport(root2,baseName,storyNamespaceName);let newStatements=[t.exportDefaultDeclaration(t.objectExpression(metaProperties))];function mapChildrenToRender(children){let child=children[0];if(!child)return;if(child.type==="text")return t.arrowFunctionExpression([],t.stringLiteral(child.value));if(child.type==="mdxFlowExpression"||child.type==="mdxTextExpression"){let expression2=(0,import_csf_tools.babelParseExpression)(child.value);return/\.bind\(.*\)/.test(child.value)||t.isIdentifier(expression2)||t.isArrowFunctionExpression(expression2)?expression2:t.arrowFunctionExpression([],expression2)}let expression=(0,import_csf_tools.babelParseExpression)(mdxProcessor.stringify({type:"root",children:[child]}));return t.arrowFunctionExpression([],expression)}function variableNameExists(name2){let found=!1;return file.path.traverse({VariableDeclarator:path3=>{let lVal=path3.node.id;t.isIdentifier(lVal)&&lVal.name===name2&&(found=!0)}}),found}newStatements.push(...[...storiesMap].flatMap(([key,value])=>{if(value.type==="id")return[];if(value.type==="reference")return[t.exportNamedDeclaration(null,[t.exportSpecifier(t.identifier(key),t.identifier(key))])];let renderProperty=mapChildrenToRender(value.children),newObject=t.objectExpression([...renderProperty?[t.objectProperty(t.identifier("render"),renderProperty)]:[],...value.attributes.flatMap(attribute=>attribute.type==="mdxJsxAttribute"?typeof attribute.value=="string"?[t.objectProperty(t.identifier(attribute.name),t.stringLiteral(attribute.value))]:[t.objectProperty(t.identifier(attribute.name),(0,import_csf_tools.babelParseExpression)(attribute.value?.value??""))]:[])]);return[t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(key),newObject)]))]})),file.path.node.body=[...file.path.node.body,...newStatements];let newMdx=mdxProcessor.stringify(root2),output=recast.print(file.path.node).code,path2=`${info.path}.jsx`;return output=await import_prettier.default.format(output.trim(),{...await import_prettier.default.resolveConfig(path2),filepath:path2}),[newMdx,output]}function getEsmAst(root2){let esm=[];visit(root2,"mdxjsEsm",node3=>{esm.push(node3.value)});let esmSource=`${esm.join(`
|
59
59
|
|
60
60
|
`)}`;return new babel.File({filename:"info.path"},{code:esmSource,ast:(0,import_csf_tools.babelParse)(esmSource)})}function addStoriesImport(root2,baseName,storyNamespaceName){let found=!1;visit(root2,"mdxjsEsm",node3=>{found||(node3.value+=`
|
61
61
|
import * as ${storyNamespaceName} from './${baseName}.stories';`,found=!0)})}function nameToValidExport(name2){let[first,...rest]=Array.from((0,import_camelCase.default)(name2));return`${first.match(/[a-zA-Z_$]/)?first.toUpperCase():`$${first}`}${rest.join("")}`}0&&(module.exports={nameToValidExport,transform});
|
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var migrate_to_test_package_exports={};__export(migrate_to_test_package_exports,{default:()=>transform,parser:()=>parser});module.exports=__toCommonJS(migrate_to_test_package_exports);var import_csf_tools=require("@storybook/csf-tools"),babel=__toESM(require("@babel/core")),t=__toESM(require("@babel/types")),import_prettier=__toESM(require("prettier"));async function transform(info){let csf=(0,import_csf_tools.loadCsf)(info.source,{makeTitle:title=>title}),fileNode=csf._ast;new babel.File({filename:info.path},{code:info.source,ast:fileNode}).path.traverse({ImportDeclaration:path=>{(path.node.source.value==="@storybook/jest"||path.node.source.value==="@storybook/testing-library")&&(path.node.source.value==="@storybook/jest"&&path.get("specifiers").forEach(specifier=>{if(specifier.isImportSpecifier()){let imported=specifier.get("imported");if(!imported.isIdentifier())return;imported.node.name==="jest"&&(specifier.remove(),path.insertAfter(t.importDeclaration([t.importNamespaceSpecifier(t.identifier("test"))],t.stringLiteral("@storybook/test"))))}}),path.get("source").replaceWith(t.stringLiteral("@storybook/test")))},Identifier:path=>{path.node.name==="jest"&&path.replaceWith(t.identifier("test"))}});let output=(0,import_csf_tools.printCsf)(csf).code;try{output=await import_prettier.default.format(output,{...await import_prettier.default.resolveConfig(info.path),filepath:info.path})}catch{console.warn(`Failed applying prettier to ${info.path}.`)}return output}var parser="tsx";0&&(module.exports={parser});
|
@@ -1 +1 @@
|
|
1
|
-
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var storiesof_to_csf_exports={};__export(storiesof_to_csf_exports,{default:()=>transformer});module.exports=__toCommonJS(storiesof_to_csf_exports);var import_prettier=__toESM(require("prettier")),import_node_logger=require("@storybook/node-logger"),import_csf=require("@storybook/csf");var import_camelCase=__toESM(require("lodash/camelCase.js")),import_upperFirst=__toESM(require("lodash/upperFirst.js")),sanitizeName=name=>{let key=(0,import_upperFirst.default)((0,import_camelCase.default)(name));return/^\d/.test(key)&&(key=`_${key}`),/^\d/.test(key)&&(key=`_${key}`),key};function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}async function transformer(file,api,options){let LITERAL=["ts","tsx"].includes(options.parser)?"StringLiteral":"Literal",j=api.jscodeshift,root=j(file.source);function extractDecorators(parameters){if(!parameters)return{};if(!parameters.properties)return{storyParams:parameters};let storyDecorators=parameters.properties.find(p=>p.key.name==="decorators");if(!storyDecorators)return{storyParams:parameters};storyDecorators=storyDecorators.value;let storyParams={...parameters};return storyParams.properties=storyParams.properties.filter(p=>p.key.name!=="decorators"),storyParams.properties.length===0?{storyDecorators}:{storyParams,storyDecorators}}function convertToModuleExports(path,originalExports2){let base=j(path),statements=[],extraExports=[],decorators=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addDecorator").forEach(add=>{let decorator=add.node.arguments[0];decorators.push(decorator)}),decorators.length>0&&(decorators.reverse(),extraExports.push(j.property("init",j.identifier("decorators"),j.arrayExpression(decorators))));let parameters=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addParameters").forEach(add=>{let params=[...add.node.arguments[0].properties];params.reverse(),params.forEach(prop=>parameters.push(prop))}),parameters.length>0&&(parameters.reverse(),extraExports.push(j.property("init",j.identifier("parameters"),j.objectExpression(parameters)))),originalExports2.length>0&&extraExports.push(j.property("init",j.identifier("excludeStories"),j.arrayExpression(originalExports2.map(exp=>j.literal(exp))))),base.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type===LITERAL).forEach(storiesOf=>{let title=storiesOf.node.arguments[0].value;statements.push(j.exportDefaultDeclaration(j.objectExpression([j.property("init",j.identifier("title"),j.literal(title)),...extraExports])))});let adds=[];base.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).forEach(add=>adds.push(add)),adds.reverse(),adds.push(path);let identifiers=new Set;root.find(j.Identifier).forEach(({value})=>identifiers.add(value.name)),adds.forEach(add=>{let name=add.node.arguments[0].value,key=sanitizeName(name);for(;identifiers.has(key);)key=`_${key}`;identifiers.add(key),(0,import_csf.storyNameFromExport)(key)===name&&(name=null);let val=add.node.arguments[1];statements.push(j.exportDeclaration(!1,j.variableDeclaration("const",[j.variableDeclarator(j.identifier(key),val)])));let storyAnnotations=[];if(name&&storyAnnotations.push(j.property("init",j.identifier("name"),j.literal(name))),add.node.arguments.length>2){let originalStoryParams=add.node.arguments[2],{storyParams,storyDecorators}=extractDecorators(originalStoryParams);storyParams&&storyAnnotations.push(j.property("init",j.identifier("parameters"),storyParams)),storyDecorators&&storyAnnotations.push(j.property("init",j.identifier("decorators"),storyDecorators))}storyAnnotations.length>0&&statements.push(j.assignmentStatement("=",j.memberExpression(j.identifier(key),j.identifier("story")),j.objectExpression(storyAnnotations)))});let stmt=path.parent.node.type==="VariableDeclarator"?path.parent.parent:path.parent;statements.reverse(),statements.forEach(s=>stmt.insertAfter(s)),j(stmt).remove()}let initialStoriesOf=root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf");if(root.find(j.ExportDefaultDeclaration).size()>0)return initialStoriesOf.size()>0&&import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls but existing default export, SKIPPING: '${file.path}'`),root.toSource();let originalExports=[];root.find(j.ExportNamedDeclaration).forEach(exp=>{let{declaration,specifiers}=exp.node;if(declaration){let{id,declarations}=declaration;declarations?declarations.forEach(decl=>{let{name,properties}=decl.id;name?originalExports.push(name):properties&&properties.forEach(prop=>originalExports.push(prop.key.name))}):id&&originalExports.push(id.name)}else specifiers&&specifiers.forEach(spec=>originalExports.push(spec.exported.name))}),root.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).filter(add=>["ExpressionStatement","VariableDeclarator"].includes(add.parentPath.node.type)).forEach(path=>convertToModuleExports(path,originalExports)),root.find(j.ImportSpecifier).filter(spec=>spec.node.imported.name==="storiesOf"&&spec.parent.node.source.value.startsWith("@storybook/")).forEach(spec=>{let toRemove=spec.parent.node.specifiers.length>1?spec:spec.parent;j(toRemove).remove()});let source=root.toSource({trailingComma:!0,quote:"single",tabWidth:2});if(initialStoriesOf.size()>1)return import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`),source;let output=source;try{let prettierConfig=await import_prettier.default.resolveConfig(file.path)
|
1
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var storiesof_to_csf_exports={};__export(storiesof_to_csf_exports,{default:()=>transformer});module.exports=__toCommonJS(storiesof_to_csf_exports);var import_prettier=__toESM(require("prettier")),import_node_logger=require("@storybook/node-logger"),import_csf=require("@storybook/csf");var import_camelCase=__toESM(require("lodash/camelCase.js")),import_upperFirst=__toESM(require("lodash/upperFirst.js")),sanitizeName=name=>{let key=(0,import_upperFirst.default)((0,import_camelCase.default)(name));return/^\d/.test(key)&&(key=`_${key}`),/^\d/.test(key)&&(key=`_${key}`),key};function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}async function transformer(file,api,options){let LITERAL=["ts","tsx"].includes(options.parser)?"StringLiteral":"Literal",j=api.jscodeshift,root=j(file.source);function extractDecorators(parameters){if(!parameters)return{};if(!parameters.properties)return{storyParams:parameters};let storyDecorators=parameters.properties.find(p=>p.key.name==="decorators");if(!storyDecorators)return{storyParams:parameters};storyDecorators=storyDecorators.value;let storyParams={...parameters};return storyParams.properties=storyParams.properties.filter(p=>p.key.name!=="decorators"),storyParams.properties.length===0?{storyDecorators}:{storyParams,storyDecorators}}function convertToModuleExports(path,originalExports2){let base=j(path),statements=[],extraExports=[],decorators=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addDecorator").forEach(add=>{let decorator=add.node.arguments[0];decorators.push(decorator)}),decorators.length>0&&(decorators.reverse(),extraExports.push(j.property("init",j.identifier("decorators"),j.arrayExpression(decorators))));let parameters=[];base.find(j.CallExpression).filter(call=>call.node.callee.property&&call.node.callee.property.name==="addParameters").forEach(add=>{let params=[...add.node.arguments[0].properties];params.reverse(),params.forEach(prop=>parameters.push(prop))}),parameters.length>0&&(parameters.reverse(),extraExports.push(j.property("init",j.identifier("parameters"),j.objectExpression(parameters)))),originalExports2.length>0&&extraExports.push(j.property("init",j.identifier("excludeStories"),j.arrayExpression(originalExports2.map(exp=>j.literal(exp))))),base.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type===LITERAL).forEach(storiesOf=>{let title=storiesOf.node.arguments[0].value;statements.push(j.exportDefaultDeclaration(j.objectExpression([j.property("init",j.identifier("title"),j.literal(title)),...extraExports])))});let adds=[];base.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).forEach(add=>adds.push(add)),adds.reverse(),adds.push(path);let identifiers=new Set;root.find(j.Identifier).forEach(({value})=>identifiers.add(value.name)),adds.forEach(add=>{let name=add.node.arguments[0].value,key=sanitizeName(name);for(;identifiers.has(key);)key=`_${key}`;identifiers.add(key),(0,import_csf.storyNameFromExport)(key)===name&&(name=null);let val=add.node.arguments[1];statements.push(j.exportDeclaration(!1,j.variableDeclaration("const",[j.variableDeclarator(j.identifier(key),val)])));let storyAnnotations=[];if(name&&storyAnnotations.push(j.property("init",j.identifier("name"),j.literal(name))),add.node.arguments.length>2){let originalStoryParams=add.node.arguments[2],{storyParams,storyDecorators}=extractDecorators(originalStoryParams);storyParams&&storyAnnotations.push(j.property("init",j.identifier("parameters"),storyParams)),storyDecorators&&storyAnnotations.push(j.property("init",j.identifier("decorators"),storyDecorators))}storyAnnotations.length>0&&statements.push(j.assignmentStatement("=",j.memberExpression(j.identifier(key),j.identifier("story")),j.objectExpression(storyAnnotations)))});let stmt=path.parent.node.type==="VariableDeclarator"?path.parent.parent:path.parent;statements.reverse(),statements.forEach(s=>stmt.insertAfter(s)),j(stmt).remove()}let initialStoriesOf=root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf");if(root.find(j.ExportDefaultDeclaration).size()>0)return initialStoriesOf.size()>0&&import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls but existing default export, SKIPPING: '${file.path}'`),root.toSource();let originalExports=[];root.find(j.ExportNamedDeclaration).forEach(exp=>{let{declaration,specifiers}=exp.node;if(declaration){let{id,declarations}=declaration;declarations?declarations.forEach(decl=>{let{name,properties}=decl.id;name?originalExports.push(name):properties&&properties.forEach(prop=>originalExports.push(prop.key.name))}):id&&originalExports.push(id.name)}else specifiers&&specifiers.forEach(spec=>originalExports.push(spec.exported.name))}),root.find(j.CallExpression).filter(add=>add.node.callee.property&&add.node.callee.property.name==="add").filter(add=>add.node.arguments.length>=2&&add.node.arguments[0].type===LITERAL).filter(add=>["ExpressionStatement","VariableDeclarator"].includes(add.parentPath.node.type)).forEach(path=>convertToModuleExports(path,originalExports)),root.find(j.ImportSpecifier).filter(spec=>spec.node.imported.name==="storiesOf"&&spec.parent.node.source.value.startsWith("@storybook/")).forEach(spec=>{let toRemove=spec.parent.node.specifiers.length>1?spec:spec.parent;j(toRemove).remove()});let source=root.toSource({trailingComma:!0,quote:"single",tabWidth:2});if(initialStoriesOf.size()>1)return import_node_logger.logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`),source;let output=source;try{let prettierConfig=await import_prettier.default.resolveConfig(file.path);output=import_prettier.default.format(source,{...prettierConfig,parser:jscodeshiftToPrettierParser(options.parser)})}catch{import_node_logger.logger.warn(`Failed to format ${file.path} with prettier`)}return output}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var upgrade_deprecated_types_exports={};__export(upgrade_deprecated_types_exports,{default:()=>transform,parser:()=>parser,upgradeDeprecatedTypes:()=>upgradeDeprecatedTypes});module.exports=__toCommonJS(upgrade_deprecated_types_exports);var import_prettier=__toESM(require("prettier")),babel=__toESM(require("@babel/core")),import_csf_tools=require("@storybook/csf-tools"),t=__toESM(require("@babel/types")),logger=console,deprecatedTypes=["ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta","Story"];function migrateType(oldType){return oldType==="Story"||oldType==="ComponentStory"?"StoryFn":oldType.replace("Component","")}async function transform(info,api,options){let csf=(0,import_csf_tools.loadCsf)(info.source,{makeTitle:title=>title}),fileNode=csf._ast,file=new babel.File({filename:info.path},{code:info.source,ast:fileNode});upgradeDeprecatedTypes(file);let output=(0,import_csf_tools.printCsf)(csf).code;try{
|
1
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var upgrade_deprecated_types_exports={};__export(upgrade_deprecated_types_exports,{default:()=>transform,parser:()=>parser,upgradeDeprecatedTypes:()=>upgradeDeprecatedTypes});module.exports=__toCommonJS(upgrade_deprecated_types_exports);var import_prettier=__toESM(require("prettier")),babel=__toESM(require("@babel/core")),import_csf_tools=require("@storybook/csf-tools"),t=__toESM(require("@babel/types")),logger=console,deprecatedTypes=["ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta","Story"];function migrateType(oldType){return oldType==="Story"||oldType==="ComponentStory"?"StoryFn":oldType.replace("Component","")}async function transform(info,api,options){let csf=(0,import_csf_tools.loadCsf)(info.source,{makeTitle:title=>title}),fileNode=csf._ast,file=new babel.File({filename:info.path},{code:info.source,ast:fileNode});upgradeDeprecatedTypes(file);let output=(0,import_csf_tools.printCsf)(csf).code;try{output=await import_prettier.default.format(output,{...await import_prettier.default.resolveConfig(info.path),filepath:info.path})}catch{logger.log(`Failed applying prettier to ${info.path}.`)}return output}var parser="tsx";function upgradeDeprecatedTypes(file){let importedNamespaces=new Set,typeReferencesToUpdate=new Set,existingImports=[];file.path.traverse({ImportDeclaration:path=>{existingImports.push(...path.get("specifiers").map(specifier=>({name:specifier.node.local.name,isAlias:!(specifier.isImportSpecifier()&&t.isIdentifier(specifier.node.imported)&&specifier.node.local.name===specifier.node.imported.name),path:specifier}))),path.node.source.value.startsWith("@storybook")&&path.get("specifiers").forEach(specifier=>{if(specifier.isImportNamespaceSpecifier()&&importedNamespaces.add(specifier.node.local.name),!specifier.isImportSpecifier())return;let imported=specifier.get("imported");if(imported.isIdentifier()&&deprecatedTypes.includes(imported.node.name)){imported.node.name===specifier.node.local.name&&typeReferencesToUpdate.add(specifier.node.local.name);let newType=migrateType(imported.node.name);if(!existingImports.some(it=>it.name===newType))imported.replaceWith(t.identifier(newType)),existingImports.push({name:newType,isAlias:!1,path:specifier});else{let existingImport=existingImports.find(it=>it.name===newType&&it.isAlias);if(existingImport)throw existingImport.path.buildCodeFrameError(`This codemod does not support local imports that are called the same as a storybook import.
|
2
2
|
Rename this local import and try again.`);specifier.remove()}}})}}),file.path.traverse({TSTypeReference:path=>{let typeName=path.get("typeName");if(typeName.isIdentifier())typeReferencesToUpdate.has(typeName.node.name)&&typeName.replaceWith(t.identifier(migrateType(typeName.node.name)));else if(typeName.isTSQualifiedName()){let namespace=typeName.get("left");if(namespace.isIdentifier()&&importedNamespaces.has(namespace.node.name)){let right=typeName.get("right");deprecatedTypes.includes(right.node.name)&&right.replaceWith(t.identifier(migrateType(right.node.name)))}}}})}0&&(module.exports={parser,upgradeDeprecatedTypes});
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storybook/codemod",
|
3
|
-
"version": "8.0.0-beta.
|
3
|
+
"version": "8.0.0-beta.4",
|
4
4
|
"description": "A collection of codemod scripts written with JSCodeshift",
|
5
5
|
"keywords": [
|
6
6
|
"storybook"
|
@@ -29,8 +29,10 @@
|
|
29
29
|
"./dist/transforms/add-component-parameters.js": "./dist/transforms/add-component-parameters.js",
|
30
30
|
"./dist/transforms/csf-2-to-3.js": "./dist/transforms/csf-2-to-3.js",
|
31
31
|
"./dist/transforms/csf-hoist-story-annotations.js": "./dist/transforms/csf-hoist-story-annotations.js",
|
32
|
+
"./dist/transforms/find-implicit-spies.js": "./dist/transforms/find-implicit-spies.js",
|
32
33
|
"./dist/transforms/move-builtin-addons.js": "./dist/transforms/move-builtin-addons.js",
|
33
34
|
"./dist/transforms/mdx-to-csf.js": "./dist/transforms/mdx-to-csf.js",
|
35
|
+
"./dist/transforms/migrate-to-test-package.js": "./dist/transforms/migrate-to-test-package.js",
|
34
36
|
"./dist/transforms/storiesof-to-csf.js": "./dist/transforms/storiesof-to-csf.js",
|
35
37
|
"./dist/transforms/update-addon-info.js": "./dist/transforms/update-addon-info.js",
|
36
38
|
"./dist/transforms/update-organisation-name.js": "./dist/transforms/update-organisation-name.js",
|
@@ -56,9 +58,9 @@
|
|
56
58
|
"@babel/preset-env": "^7.23.2",
|
57
59
|
"@babel/types": "^7.23.0",
|
58
60
|
"@storybook/csf": "^0.1.2",
|
59
|
-
"@storybook/csf-tools": "8.0.0-beta.
|
60
|
-
"@storybook/node-logger": "8.0.0-beta.
|
61
|
-
"@storybook/types": "8.0.0-beta.
|
61
|
+
"@storybook/csf-tools": "8.0.0-beta.4",
|
62
|
+
"@storybook/node-logger": "8.0.0-beta.4",
|
63
|
+
"@storybook/types": "8.0.0-beta.4",
|
62
64
|
"@types/cross-spawn": "^6.0.2",
|
63
65
|
"cross-spawn": "^7.0.3",
|
64
66
|
"globby": "^11.0.2",
|
@@ -92,7 +94,9 @@
|
|
92
94
|
"./src/transforms/add-component-parameters.js",
|
93
95
|
"./src/transforms/csf-2-to-3.ts",
|
94
96
|
"./src/transforms/csf-hoist-story-annotations.js",
|
97
|
+
"./src/transforms/find-implicit-spies.ts",
|
95
98
|
"./src/transforms/mdx-to-csf.ts",
|
99
|
+
"./src/transforms/migrate-to-test-package.ts",
|
96
100
|
"./src/transforms/move-builtin-addons.js",
|
97
101
|
"./src/transforms/storiesof-to-csf.js",
|
98
102
|
"./src/transforms/update-addon-info.js",
|