@storybook/codemod 7.0.0-beta.12 → 7.0.0-beta.13

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 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 src_exports={};__export(src_exports,{listCodemods:()=>listCodemods,packageNames:()=>packageNames,runCodemod:()=>runCodemod,updateAddonInfo:()=>transformer2,updateOrganisationName:()=>transformer});module.exports=__toCommonJS(src_exports);var import_fs=__toESM(require("fs")),import_path=__toESM(require("path")),import_util=require("util"),import_globby=__toESM(require("globby")),import_cross_spawn=require("cross-spawn");var import_camelCase=__toESM(require("lodash/camelCase")),import_upperFirst=__toESM(require("lodash/upperFirst"));function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}function transformer2(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return import_fs.default.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=(0,import_util.promisify)(import_fs.default.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=import_path.default.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await(0,import_globby.default)([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];(0,import_cross_spawn.sync)("npx",["jscodeshift","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}0&&(module.exports={listCodemods,packageNames,runCodemod,updateAddonInfo,updateOrganisationName});
1
+ 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 src_exports={};__export(src_exports,{listCodemods:()=>listCodemods,packageNames:()=>packageNames,runCodemod:()=>runCodemod,updateAddonInfo:()=>transformer2,updateOrganisationName:()=>transformer});module.exports=__toCommonJS(src_exports);var import_fs=__toESM(require("fs")),import_path=__toESM(require("path")),import_util=require("util"),import_globby=__toESM(require("globby")),import_cross_spawn=require("cross-spawn");var import_camelCase=__toESM(require("lodash/camelCase")),import_upperFirst=__toESM(require("lodash/upperFirst"));function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var packageNames={"@kadira/react-storybook-decorator-centered":"@storybook/addon-centered","@kadira/storybook-addons":"@storybook/preview-api","@kadira/storybook-addon-actions":"@storybook/addon-actions","@kadira/storybook-addon-comments":"@storybook/addon-comments","@kadira/storybook-addon-graphql":"@storybook/addon-graphql","@kadira/storybook-addon-info":"@storybook/addon-info","@kadira/storybook-addon-knobs":"@storybook/addon-knobs","@kadira/storybook-addon-links":"@storybook/addon-links","@kadira/storybook-addon-notes":"@storybook/addon-notes","@kadira/storybook-addon-options":"@storybook/addon-options","@kadira/storybook-channels":"@storybook/channels","@kadira/storybook-channel-postmsg":"@storybook/channel-postmessage","@kadira/storybook-channel-websocket":"@storybook/channel-websocket","@kadira/storybook-ui":"@storybook/manager","@kadira/react-native-storybook":"@storybook/react-native","@kadira/react-storybook":"@storybook/react","@kadira/getstorybook":"@storybook/cli","@kadira/storybook":"@storybook/react",storyshots:"@storybook/addon-storyshots",getstorybook:"@storybook/cli"};function transformer(file,api){let j=api.jscodeshift,packageNamesKeys=Object.keys(packageNames),getMatch=oldpart=>packageNamesKeys.find(newpart=>oldpart.match(newpart)),getNewPackageName=oldPackageName=>{let match=getMatch(oldPackageName);if(match){let replacement=packageNames[match];return oldPackageName.replace(match,replacement)}return oldPackageName},updatePackageName=declaration=>(declaration.node.source.value=getNewPackageName(declaration.node.source.value),declaration.node);return j(file.source).find(j.ImportDeclaration).replaceWith(updatePackageName).toSource({quote:"single"})}function transformer2(file,api){let j=api.jscodeshift,root=j(file.source),getOptions=args=>args[3]===void 0?args[2]===void 0?[args[0]]:[args[1]]:[j.objectExpression([j.property("init",j.identifier("text"),args[1]),...args[3].properties])],withInfo=addWithInfoExpression=>{let{node}=addWithInfoExpression,args=node.arguments,storyComponent=args[2]?args[2]:args[1];return node.callee.property.name="add",node.arguments=[args[0],j.callExpression(j.callExpression(j.identifier("withInfo"),getOptions(args)),[storyComponent])],node},checkWithInfoImport=()=>{root.find(j.ImportDeclaration).filter(imp=>imp.node.source.value==="@storybook/addon-info").size()||root.find(j.ImportDeclaration).at(-1).insertAfter(j.importDeclaration([j.importSpecifier(j.identifier("withInfo"))],j.literal("@storybook/addon-info")))},addWithInfoExpressions=root.find(j.CallExpression,{callee:{property:{name:"addWithInfo"}}});return addWithInfoExpressions.size()&&(checkWithInfoImport(),addWithInfoExpressions.replaceWith(withInfo)),root.toSource()}var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return import_fs.default.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=(0,import_util.promisify)(import_fs.default.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=import_path.default.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await(0,import_globby.default)([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];(0,import_cross_spawn.sync)("npx",["jscodeshift","--no-babel","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}0&&(module.exports={listCodemods,packageNames,runCodemod,updateAddonInfo,updateOrganisationName});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{packageNames,transformer}from"./chunk-3OPQTROG.mjs";import{jscodeshiftToPrettierParser}from"./chunk-CO6EPEMB.mjs";import{transformer as transformer2}from"./chunk-B5FMQ3BX.mjs";import fs from"fs";import path from"path";import{promisify}from"util";import globby from"globby";import{sync as spawnSync}from"cross-spawn";var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return fs.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=promisify(fs.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=path.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await globby([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];spawnSync("npx",["jscodeshift","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}export{listCodemods,packageNames,runCodemod,transformer2 as updateAddonInfo,transformer as updateOrganisationName};
1
+ import{packageNames,transformer}from"./chunk-3OPQTROG.mjs";import{jscodeshiftToPrettierParser}from"./chunk-CO6EPEMB.mjs";import{transformer as transformer2}from"./chunk-B5FMQ3BX.mjs";import fs from"fs";import path from"path";import{promisify}from"util";import globby from"globby";import{sync as spawnSync}from"cross-spawn";var TRANSFORM_DIR=`${__dirname}/transforms`;function listCodemods(){return fs.readdirSync(TRANSFORM_DIR).filter(fname=>fname.endsWith(".js")).map(fname=>fname.slice(0,-3))}var renameAsync=promisify(fs.rename);async function renameFile(file,from,to,{logger}){let newFile=file.replace(from,to);return logger.log(`Rename: ${file} ${newFile}`),renameAsync(file,newFile)}async function runCodemod(codemod,{glob,logger,dryRun,rename,parser}){if(!listCodemods().includes(codemod))throw new Error(`Unknown codemod ${codemod}. Run --list for options.`);let renameParts=null;if(rename&&(renameParts=rename.split(":"),renameParts.length!==2))throw new Error(`Codemod rename: expected format "from:to", got "${rename}"`);let inferredParser=parser;if(!parser){let extension=path.extname(glob).slice(1);jscodeshiftToPrettierParser(extension)!=="babel"&&(inferredParser=extension)}let files=await globby([glob,"!**/node_modules","!**/dist"]);if(logger.log(`=> Applying ${codemod}: ${files.length} files`),!dryRun){let parserArgs=inferredParser?["--parser",inferredParser]:[];spawnSync("npx",["jscodeshift","--no-babel","-t",`${TRANSFORM_DIR}/${codemod}.js`,...parserArgs,...files],{stdio:"inherit",shell:!0})}if(renameParts){let[from,to]=renameParts;logger.log(`=> Renaming ${rename}: ${files.length} files`),await Promise.all(files.map(file=>renameFile(file,new RegExp(`${from}$`),to,{logger})))}}export{listCodemods,packageNames,runCodemod,transformer2 as updateAddonInfo,transformer as updateOrganisationName};
@@ -1,7 +1,6 @@
1
- declare function transform({ source }: {
2
- source: string;
3
- }, api: any, options: {
4
- parser?: string;
5
- }): string;
1
+ import { FileInfo, API, Options } from 'jscodeshift';
6
2
 
7
- export { transform as default };
3
+ declare function transform({ source, path }: FileInfo, api: API, options: Options): string;
4
+ declare const parser = "tsx";
5
+
6
+ export { transform as default, parser };
@@ -1 +1 @@
1
- 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:()=>csf_2_to_3_default});module.exports=__toCommonJS(csf_2_to_3_exports);var import_prettier=__toESM(require("prettier")),t=__toESM(require("@babel/types")),import_csf_tools=require("@storybook/csf-tools");var import_camelCase=__toESM(require("lodash/camelCase")),import_upperFirst=__toESM(require("lodash/upperFirst"));function jscodeshiftToPrettierParser(parser){let parserMap={babylon:"babel",flow:"flow",ts:"typescript",tsx:"typescript"};return parser&&parserMap[parser]||"babel"}var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t.isCallExpression(init)&&t.isMemberExpression(init.callee)&&t.isIdentifier(init.callee.object)&&t.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{var _a;if((_a=csf._meta)!=null&&_a.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source},api,options){let csf=(0,import_csf_tools.loadCsf)(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=(0,import_csf_tools.formatCsf)(csf),prettierConfig=import_prettier.default.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};return import_prettier.default.format(output,{...prettierConfig,parser:jscodeshiftToPrettierParser(options==null?void 0:options.parser)})}var csf_2_to_3_default=transform;0&&(module.exports={});
1
+ 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_prettier=__toESM(require("prettier")),t=__toESM(require("@babel/types")),import_csf_tools=require("@storybook/csf-tools"),logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t.isCallExpression(init)&&t.isMemberExpression(init.callee)&&t.isIdentifier(init.callee.object)&&t.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{var _a;if((_a=csf._meta)!=null&&_a.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source,path},api,options){let csf=(0,import_csf_tools.loadCsf)(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=(0,import_csf_tools.formatCsf)(csf);try{let prettierConfig=import_prettier.default.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=import_prettier.default.format(output,{...prettierConfig,filepath:path})}catch{logger.log(`Failed applying prettier to ${path}.`)}return output}var parser="tsx";0&&(module.exports={parser});
@@ -1 +1 @@
1
- import{jscodeshiftToPrettierParser}from"../chunk-CO6EPEMB.mjs";import prettier from"prettier";import*as t from"@babel/types";import{formatCsf,loadCsf}from"@storybook/csf-tools";var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t.isCallExpression(init)&&t.isMemberExpression(init.callee)&&t.isIdentifier(init.callee.object)&&t.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{if(csf._meta?.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source},api,options){let csf=loadCsf(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=formatCsf(csf),prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};return prettier.format(output,{...prettierConfig,parser:jscodeshiftToPrettierParser(options?.parser)})}var csf_2_to_3_default=transform;export{csf_2_to_3_default as default};
1
+ import prettier from"prettier";import*as t from"@babel/types";import{formatCsf,loadCsf}from"@storybook/csf-tools";var logger=console,renameAnnotation=annotation=>annotation==="storyName"?"name":annotation,getTemplateBindVariable=init=>t.isCallExpression(init)&&t.isMemberExpression(init.callee)&&t.isIdentifier(init.callee.object)&&t.isIdentifier(init.callee.property)&&init.callee.property.name==="bind"&&(init.arguments.length===0||init.arguments.length===1&&t.isObjectExpression(init.arguments[0])&&init.arguments[0].properties.length===0)?init.callee.object.name:null,isStoryAnnotation=(stmt,objectExports)=>t.isExpressionStatement(stmt)&&t.isAssignmentExpression(stmt.expression)&&t.isMemberExpression(stmt.expression.left)&&t.isIdentifier(stmt.expression.left.object)&&objectExports[stmt.expression.left.object.name],isTemplateDeclaration=(stmt,templates)=>t.isVariableDeclaration(stmt)&&stmt.declarations.length===1&&t.isIdentifier(stmt.declarations[0].id)&&templates[stmt.declarations[0].id.name],getNewExport=(stmt,objectExports)=>{if(t.isExportNamedDeclaration(stmt)&&t.isVariableDeclaration(stmt.declaration)&&stmt.declaration.declarations.length===1){let decl=stmt.declaration.declarations[0];if(t.isVariableDeclarator(decl)&&t.isIdentifier(decl.id))return objectExports[decl.id.name]}return null},isReactGlobalRenderFn=(csf,storyFn)=>{if(csf._meta?.component&&t.isArrowFunctionExpression(storyFn)&&storyFn.params.length===1&&t.isJSXElement(storyFn.body)){let{openingElement}=storyFn.body;if(openingElement.selfClosing&&t.isJSXIdentifier(openingElement.name)&&openingElement.attributes.length===1){let attr=openingElement.attributes[0],param=storyFn.params[0];if(t.isJSXSpreadAttribute(attr)&&t.isIdentifier(attr.argument)&&t.isIdentifier(param)&&param.name===attr.argument.name&&csf._meta.component===openingElement.name.name)return!0}}return!1},isSimpleCSFStory=(init,annotations)=>annotations.length===0&&t.isArrowFunctionExpression(init)&&init.params.length===0;function transform({source,path},api,options){let csf=loadCsf(source,{makeTitle:userTitle=>userTitle||"FIXME"});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),source}let objectExports={};Object.entries(csf._storyExports).forEach(([key,decl])=>{let annotations=Object.entries(csf._storyAnnotations[key]).map(([annotation,val])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template||isSimpleCSFStory(init,annotations))return;let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let keyId=t.identifier(key),{typeAnnotation}=id;typeAnnotation&&(keyId.typeAnnotation=typeAnnotation);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(keyId,t.objectExpression([...renderAnnotation,...annotations]))]))}});let updatedBody=csf._ast.program.body.reduce((acc,stmt)=>{if(isStoryAnnotation(stmt,objectExports)||isTemplateDeclaration(stmt,csf._templates))return acc;let newExport=getNewExport(stmt,objectExports);return newExport?(acc.push(newExport),acc):(acc.push(stmt),acc)},[]);csf._ast.program.body=updatedBody;let output=formatCsf(csf);try{let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=prettier.format(output,{...prettierConfig,filepath:path})}catch{logger.log(`Failed applying prettier to ${path}.`)}return output}var parser="tsx";export{transform as default,parser};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/codemod",
3
- "version": "7.0.0-beta.12",
3
+ "version": "7.0.0-beta.13",
4
4
  "description": "A collection of codemod scripts written with JSCodeshift",
5
5
  "keywords": [
6
6
  "storybook"
@@ -48,9 +48,9 @@
48
48
  "@babel/preset-env": "^7.20.2",
49
49
  "@babel/types": "^7.20.2",
50
50
  "@storybook/csf": "next",
51
- "@storybook/csf-tools": "7.0.0-beta.12",
52
- "@storybook/node-logger": "7.0.0-beta.12",
53
- "@storybook/types": "7.0.0-beta.12",
51
+ "@storybook/csf-tools": "7.0.0-beta.13",
52
+ "@storybook/node-logger": "7.0.0-beta.13",
53
+ "@storybook/types": "7.0.0-beta.13",
54
54
  "cross-spawn": "^7.0.3",
55
55
  "globby": "^11.0.2",
56
56
  "jscodeshift": "^0.13.1",
@@ -60,6 +60,7 @@
60
60
  "util": "^0.12.4"
61
61
  },
62
62
  "devDependencies": {
63
+ "@types/jscodeshift": "^0.11.6",
63
64
  "jest": "^29.3.1",
64
65
  "jest-specific-snapshot": "^7.0.0",
65
66
  "typescript": "~4.9.3"
@@ -82,5 +83,5 @@
82
83
  "./src/transforms/upgrade-hierarchy-separators.js"
83
84
  ]
84
85
  },
85
- "gitHead": "dd52c7e8853bc40791deb55e36473c0c18ab5957"
86
+ "gitHead": "ddf86bd126ede0c019d7c9494f99f24a5cad9908"
86
87
  }
package/src/index.js CHANGED
@@ -59,7 +59,17 @@ export async function runCodemod(codemod, { glob, logger, dryRun, rename, parser
59
59
  const parserArgs = inferredParser ? ['--parser', inferredParser] : [];
60
60
  spawnSync(
61
61
  'npx',
62
- ['jscodeshift', '-t', `${TRANSFORM_DIR}/${codemod}.js`, ...parserArgs, ...files],
62
+ [
63
+ 'jscodeshift',
64
+ // this makes sure codeshift doesn't transform our own source code with babel
65
+ // which is faster, and also makes sure the user won't see babel messages such as:
66
+ // [BABEL] Note: The code generator has deoptimised the styling of repo/node_modules/prettier/index.js as it exceeds the max of 500KB.
67
+ '--no-babel',
68
+ '-t',
69
+ `${TRANSFORM_DIR}/${codemod}.js`,
70
+ ...parserArgs,
71
+ ...files,
72
+ ],
63
73
  {
64
74
  stdio: 'inherit',
65
75
  shell: true,
@@ -1,4 +1,4 @@
1
- import global from 'global';
1
+ import { global } from '@storybook/global';
2
2
 
3
3
  const { document } = global;
4
4
 
@@ -1,7 +1,7 @@
1
1
  // Jest Snapshot v1, https://goo.gl/fbAQLP
2
2
 
3
3
  exports[`csf-to-mdx transforms correctly using "story-function.input.js" data 1`] = `
4
- "import global from 'global';
4
+ "import { global } from '@storybook/global';
5
5
  import { Meta, Story } from '@storybook/addon-docs';
6
6
 
7
7
  const {
@@ -7,8 +7,10 @@ expect.addSnapshotSerializer({
7
7
  test: () => true,
8
8
  });
9
9
 
10
- const jsTransform = (source: string) => _transform({ source }, null, {}).trim();
11
- const tsTransform = (source: string) => _transform({ source }, null, { parser: 'tsx' }).trim();
10
+ const jsTransform = (source: string) =>
11
+ _transform({ source, path: 'Component.stories.js' }, null, {}).trim();
12
+ const tsTransform = (source: string) =>
13
+ _transform({ source, path: 'Component.stories.ts' }, null, { parser: 'tsx' }).trim();
12
14
 
13
15
  describe('csf-2-to-3', () => {
14
16
  describe('javascript', () => {
@@ -3,7 +3,7 @@ import prettier from 'prettier';
3
3
  import * as t from '@babel/types';
4
4
  import type { CsfFile } from '@storybook/csf-tools';
5
5
  import { formatCsf, loadCsf } from '@storybook/csf-tools';
6
- import { jscodeshiftToPrettierParser } from '../lib/utils';
6
+ import type { API, FileInfo, Options } from 'jscodeshift';
7
7
 
8
8
  const logger = console;
9
9
 
@@ -89,7 +89,7 @@ const isReactGlobalRenderFn = (csf: CsfFile, storyFn: t.Expression) => {
89
89
  const isSimpleCSFStory = (init: t.Expression, annotations: t.ObjectProperty[]) =>
90
90
  annotations.length === 0 && t.isArrowFunctionExpression(init) && init.params.length === 0;
91
91
 
92
- function transform({ source }: { source: string }, api: any, options: { parser?: string }) {
92
+ export default function transform({ source, path }: FileInfo, api: API, options: Options) {
93
93
  const makeTitle = (userTitle?: string) => {
94
94
  return userTitle || 'FIXME';
95
95
  };
@@ -165,20 +165,27 @@ function transform({ source }: { source: string }, api: any, options: { parser?:
165
165
  return acc;
166
166
  }, []);
167
167
  csf._ast.program.body = updatedBody;
168
- const output = formatCsf(csf);
169
-
170
- const prettierConfig = prettier.resolveConfig.sync('.', { editorconfig: true }) || {
171
- printWidth: 100,
172
- tabWidth: 2,
173
- bracketSpacing: true,
174
- trailingComma: 'es5',
175
- singleQuote: true,
176
- };
168
+ let output = formatCsf(csf);
177
169
 
178
- return prettier.format(output, {
179
- ...prettierConfig,
180
- parser: jscodeshiftToPrettierParser(options?.parser),
181
- });
170
+ try {
171
+ const prettierConfig = prettier.resolveConfig.sync('.', { editorconfig: true }) || {
172
+ printWidth: 100,
173
+ tabWidth: 2,
174
+ bracketSpacing: true,
175
+ trailingComma: 'es5',
176
+ singleQuote: true,
177
+ };
178
+
179
+ output = prettier.format(output, {
180
+ ...prettierConfig,
181
+ // This will infer the parser from the filename.
182
+ filepath: path,
183
+ });
184
+ } catch (e) {
185
+ logger.log(`Failed applying prettier to ${path}.`);
186
+ }
187
+
188
+ return output;
182
189
  }
183
190
 
184
- export default transform;
191
+ export const parser = 'tsx';