@storybook/codemod 7.0.0-beta.51 → 7.0.0-beta.53

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,349 @@
1
+ /* eslint-disable no-param-reassign,@typescript-eslint/no-shadow,consistent-return */
2
+ import type { FileInfo } from 'jscodeshift';
3
+ import { babelParse, babelParseExpression } from '@storybook/csf-tools';
4
+ import { remark } from 'remark';
5
+ import type { Root } from 'remark-mdx';
6
+ import remarkMdx from 'remark-mdx';
7
+ import { SKIP, visit } from 'unist-util-visit';
8
+ import { is } from 'unist-util-is';
9
+ import type {
10
+ MdxJsxAttribute,
11
+ MdxJsxExpressionAttribute,
12
+ MdxJsxFlowElement,
13
+ MdxJsxTextElement,
14
+ } from 'mdast-util-mdx-jsx';
15
+ import type { MdxjsEsm } from 'mdast-util-mdxjs-esm';
16
+ import * as t from '@babel/types';
17
+ import type { BabelFile } from '@babel/core';
18
+ import * as babel from '@babel/core';
19
+ import * as recast from 'recast';
20
+ import * as path from 'node:path';
21
+ import prettier from 'prettier';
22
+ import * as fs from 'node:fs';
23
+ import camelCase from 'lodash/camelCase';
24
+ import type { MdxFlowExpression } from 'mdast-util-mdx-expression';
25
+
26
+ const mdxProcessor = remark().use(remarkMdx) as ReturnType<typeof remark>;
27
+
28
+ export default function jscodeshift(info: FileInfo) {
29
+ const parsed = path.parse(info.path);
30
+
31
+ let baseName = path.join(
32
+ parsed.dir,
33
+ parsed.name.replace('.mdx', '').replace('.stories', '').replace('.story', '')
34
+ );
35
+
36
+ // make sure the new csf file we are going to create exists
37
+ while (fs.existsSync(`${baseName}.stories.js`)) {
38
+ baseName += '_';
39
+ }
40
+
41
+ const result = transform(info.source, path.basename(baseName));
42
+
43
+ if (result == null) {
44
+ // We can not make a valid migration.
45
+ return;
46
+ }
47
+
48
+ const [mdx, csf] = result;
49
+
50
+ fs.writeFileSync(`${baseName}.stories.js`, csf);
51
+
52
+ return mdx;
53
+ }
54
+
55
+ export function transform(source: string, baseName: string): [mdx: string, csf: string] {
56
+ const root = mdxProcessor.parse(source);
57
+ const storyNamespaceName = nameToValidExport(`${baseName}Stories`);
58
+
59
+ let containsMeta = false;
60
+ const metaAttributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute> = [];
61
+ const storiesMap = new Map<
62
+ string,
63
+ | {
64
+ type: 'value';
65
+ attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>;
66
+ children: (MdxJsxFlowElement | MdxJsxTextElement)['children'];
67
+ }
68
+ | {
69
+ type: 'reference';
70
+ }
71
+ | {
72
+ type: 'id';
73
+ }
74
+ >();
75
+
76
+ // rewrite addon docs import
77
+ visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
78
+ node.value = node.value
79
+ .replaceAll('@storybook/addon-docs', '@storybook/blocks')
80
+ .replaceAll('@storybook/addon-docs/blocks', '@storybook/blocks');
81
+ });
82
+
83
+ visit(
84
+ root,
85
+ ['mdxJsxFlowElement', 'mdxJsxTextElement'],
86
+ (node: MdxJsxFlowElement | MdxJsxTextElement, index, parent) => {
87
+ if (is(node, { name: 'Meta' })) {
88
+ containsMeta = true;
89
+ metaAttributes.push(...node.attributes);
90
+ node.attributes = [
91
+ {
92
+ type: 'mdxJsxAttribute',
93
+ name: 'of',
94
+ value: {
95
+ type: 'mdxJsxAttributeValueExpression',
96
+ value: storyNamespaceName,
97
+ },
98
+ },
99
+ ];
100
+ }
101
+ if (is(node, { name: 'Story' })) {
102
+ const nameAttribute = node.attributes.find(
103
+ (it) => it.type === 'mdxJsxAttribute' && it.name === 'name'
104
+ );
105
+ const idAttribute = node.attributes.find(
106
+ (it) => it.type === 'mdxJsxAttribute' && it.name === 'id'
107
+ );
108
+ const storyAttribute = node.attributes.find(
109
+ (it) => it.type === 'mdxJsxAttribute' && it.name === 'story'
110
+ );
111
+ if (typeof nameAttribute?.value === 'string') {
112
+ const name = nameToValidExport(nameAttribute.value);
113
+ storiesMap.set(name, {
114
+ type: 'value',
115
+ attributes: node.attributes,
116
+ children: node.children,
117
+ });
118
+ node.attributes = [
119
+ {
120
+ type: 'mdxJsxAttribute',
121
+ name: 'of',
122
+ value: {
123
+ type: 'mdxJsxAttributeValueExpression',
124
+ value: `${storyNamespaceName}.${name}`,
125
+ },
126
+ },
127
+ ];
128
+ node.children = [];
129
+ } else if (idAttribute?.value) {
130
+ // e.g. <Story id="button--primary" />
131
+ // should be migrated manually as it is very hard to find out where the definition of such a string id is located
132
+ const nodeString = mdxProcessor.stringify({ type: 'root', children: [node] }).trim();
133
+ const newNode: MdxFlowExpression = {
134
+ type: 'mdxFlowExpression',
135
+ value: `/* ${nodeString} is deprecated, please migrate it to <Story of={referenceToStory} /> */`,
136
+ };
137
+ storiesMap.set(idAttribute.value as string, { type: 'id' });
138
+ parent.children.splice(index, 0, newNode);
139
+ // current index is the new comment, and index + 1 is current node
140
+ // SKIP traversing current node, and continue with the node after that
141
+ return [SKIP, index + 2];
142
+ } else if (
143
+ storyAttribute?.type === 'mdxJsxAttribute' &&
144
+ typeof storyAttribute.value === 'object' &&
145
+ storyAttribute.value.type === 'mdxJsxAttributeValueExpression'
146
+ ) {
147
+ // e.g. <Story story={Primary} />
148
+
149
+ const name = storyAttribute.value.value;
150
+ node.attributes = [
151
+ {
152
+ type: 'mdxJsxAttribute',
153
+ name: 'of',
154
+ value: {
155
+ type: 'mdxJsxAttributeValueExpression',
156
+ value: `${storyNamespaceName}.${name}`,
157
+ },
158
+ },
159
+ ];
160
+ node.children = [];
161
+
162
+ storiesMap.set(name, { type: 'reference' });
163
+ } else {
164
+ parent.children.splice(index, 1);
165
+ // Do not traverse `node`, continue at the node *now* at `index`.
166
+ return [SKIP, index];
167
+ }
168
+ }
169
+ return undefined;
170
+ }
171
+ );
172
+
173
+ const metaProperties = metaAttributes.flatMap((attribute) => {
174
+ if (attribute.type === 'mdxJsxAttribute') {
175
+ if (typeof attribute.value === 'string') {
176
+ return [t.objectProperty(t.identifier(attribute.name), t.stringLiteral(attribute.value))];
177
+ }
178
+ return [
179
+ t.objectProperty(t.identifier(attribute.name), babelParseExpression(attribute.value.value)),
180
+ ];
181
+ }
182
+ return [];
183
+ });
184
+
185
+ const file = getEsmAst(root);
186
+
187
+ if (containsMeta || storiesMap.size > 0) {
188
+ addStoriesImport(root, baseName, storyNamespaceName);
189
+ }
190
+
191
+ file.path.traverse({
192
+ // remove mdx imports from csf
193
+ ImportDeclaration(path) {
194
+ if (path.node.source.value === '@storybook/blocks') {
195
+ path.remove();
196
+ }
197
+ },
198
+ // remove exports from csf file
199
+ ExportNamedDeclaration(path) {
200
+ path.replaceWith(path.node.declaration);
201
+ },
202
+ });
203
+
204
+ if (storiesMap.size === 0) {
205
+ // A CSF file must have at least one story, so skip migrating if this is the case.
206
+ return null;
207
+ }
208
+
209
+ const newStatements: t.Statement[] = [
210
+ t.exportDefaultDeclaration(t.objectExpression(metaProperties)),
211
+ ];
212
+
213
+ function mapChildrenToRender(children: (MdxJsxFlowElement | MdxJsxTextElement)['children']) {
214
+ const child = children[0];
215
+
216
+ if (!child) return undefined;
217
+
218
+ if (child.type === 'text') {
219
+ return t.arrowFunctionExpression([], t.stringLiteral(child.value));
220
+ }
221
+ if (child.type === 'mdxFlowExpression' || child.type === 'mdxTextExpression') {
222
+ const expression = babelParseExpression(child.value);
223
+
224
+ // Recreating those lines: https://github.com/storybookjs/mdx1-csf/blob/f408fc97e9a63097ca1ee577df9315a3cccca975/src/sb-mdx-plugin.ts#L185-L198
225
+ const BIND_REGEX = /\.bind\(.*\)/;
226
+ if (BIND_REGEX.test(child.value)) {
227
+ return expression;
228
+ }
229
+ if (t.isIdentifier(expression)) {
230
+ return expression;
231
+ }
232
+ if (t.isArrowFunctionExpression(expression)) {
233
+ return expression;
234
+ }
235
+ return t.arrowFunctionExpression([], expression);
236
+ }
237
+
238
+ const expression = babelParseExpression(
239
+ mdxProcessor.stringify({ type: 'root', children: [child] })
240
+ );
241
+ return t.arrowFunctionExpression([], expression);
242
+ }
243
+
244
+ function variableNameExists(name: string) {
245
+ let found = false;
246
+ file.path.traverse({
247
+ VariableDeclarator: (path) => {
248
+ const lVal = path.node.id;
249
+ if (t.isIdentifier(lVal) && lVal.name === name) found = true;
250
+ },
251
+ });
252
+ return found;
253
+ }
254
+
255
+ newStatements.push(
256
+ ...[...storiesMap].flatMap(([key, value]) => {
257
+ if (value.type === 'id') return [];
258
+ if (value.type === 'reference') {
259
+ return [
260
+ t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier(key), t.identifier(key))]),
261
+ ];
262
+ }
263
+ const renderProperty = mapChildrenToRender(value.children);
264
+ const newObject = t.objectExpression([
265
+ ...(renderProperty
266
+ ? [t.objectProperty(t.identifier('render'), mapChildrenToRender(value.children))]
267
+ : []),
268
+ ...value.attributes.flatMap((attribute) => {
269
+ if (attribute.type === 'mdxJsxAttribute') {
270
+ if (typeof attribute.value === 'string') {
271
+ return [
272
+ t.objectProperty(t.identifier(attribute.name), t.stringLiteral(attribute.value)),
273
+ ];
274
+ }
275
+ return [
276
+ t.objectProperty(
277
+ t.identifier(attribute.name),
278
+ babelParseExpression(attribute.value.value)
279
+ ),
280
+ ];
281
+ }
282
+ return [];
283
+ }),
284
+ ]);
285
+
286
+ let newExportName = key;
287
+ while (variableNameExists(newExportName)) {
288
+ newExportName += '_';
289
+ }
290
+
291
+ return [
292
+ t.exportNamedDeclaration(
293
+ t.variableDeclaration('const', [
294
+ t.variableDeclarator(t.identifier(newExportName), newObject),
295
+ ])
296
+ ),
297
+ ];
298
+ })
299
+ );
300
+
301
+ file.path.node.body = [...file.path.node.body, ...newStatements];
302
+
303
+ const newMdx = mdxProcessor.stringify(root);
304
+ let output = recast.print(file.path.node).code;
305
+
306
+ const prettierConfig = prettier.resolveConfig.sync('.', { editorconfig: true }) || {
307
+ printWidth: 100,
308
+ tabWidth: 2,
309
+ bracketSpacing: true,
310
+ trailingComma: 'es5',
311
+ singleQuote: true,
312
+ };
313
+
314
+ output = prettier.format(output, { ...prettierConfig, filepath: `file.jsx` });
315
+
316
+ return [newMdx, output];
317
+ }
318
+
319
+ function getEsmAst(root: Root) {
320
+ const esm: string[] = [];
321
+ visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
322
+ esm.push(node.value);
323
+ });
324
+ const esmSource = `${esm.join('\n\n')}`;
325
+
326
+ // @ts-expect-error File is not yet exposed, see https://github.com/babel/babel/issues/11350#issuecomment-644118606
327
+ const file: BabelFile = new babel.File(
328
+ { filename: 'info.path' },
329
+ { code: esmSource, ast: babelParse(esmSource) }
330
+ );
331
+ return file;
332
+ }
333
+
334
+ function addStoriesImport(root: Root, baseName: string, storyNamespaceName: string): void {
335
+ let found = false;
336
+
337
+ visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
338
+ if (!found) {
339
+ node.value += `\nimport * as ${storyNamespaceName} from './${baseName}.stories';`;
340
+ found = true;
341
+ }
342
+ });
343
+ }
344
+
345
+ export function nameToValidExport(name: string) {
346
+ const [first, ...rest] = Array.from(camelCase(name));
347
+
348
+ return `${first.match(/[a-zA-Z_$]/) ? first.toUpperCase() : `$${first}`}${rest.join('')}`;
349
+ }
@@ -1 +0,0 @@
1
- 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"})}export{packageNames,transformer};
@@ -1 +0,0 @@
1
- function transformer(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()}export{transformer};
@@ -1 +0,0 @@
1
- import camelCase from"lodash/camelCase.js";import upperFirst from"lodash/upperFirst.js";var sanitizeName=name=>{let key=upperFirst(camelCase(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"}export{sanitizeName,jscodeshiftToPrettierParser};
@@ -1,2 +0,0 @@
1
- import prettier from"prettier";import*as babel from"@babel/core";import{loadCsf}from"@storybook/csf-tools";import*as recast from"recast";import*as t from"@babel/types";var logger=console,deprecatedTypes=["ComponentStory","ComponentStoryFn","ComponentStoryObj","ComponentMeta","Story"];function migrateType(oldType){return oldType==="Story"||oldType==="ComponentStory"?"StoryFn":oldType.replace("Component","")}function transform(info,api,options){let fileNode=loadCsf(info.source,{makeTitle:title=>title})._ast,file=new babel.File({filename:info.path},{code:info.source,ast:fileNode});upgradeDeprecatedTypes(file);let output=recast.print(file.path.node).code;try{let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=prettier.format(output,{...prettierConfig,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
- 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)))}}}})}export{transform,parser,upgradeDeprecatedTypes};
package/dist/index.mjs DELETED
@@ -1 +0,0 @@
1
- import{jscodeshiftToPrettierParser}from"./chunk-HBPKIMKE.mjs";import{transformer as transformer2}from"./chunk-B5FMQ3BX.mjs";import{packageNames,transformer}from"./chunk-3OPQTROG.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 +0,0 @@
1
- function transformer(file,api){let j=api.jscodeshift,root=j(file.source),importMap={};root.find(j.ImportDeclaration).forEach(imp=>imp.node.specifiers.forEach(spec=>{importMap[spec.local.name]=!0}));function getLeafName(string){let parts=string.split(/\/|\.|\|/);return parts[parts.length-1]}function addComponentParameter(call){let{node}=call,leafName=getLeafName(node.arguments[0].value);return j.callExpression(j.memberExpression(node,j.identifier("addParameters")),[j.objectExpression([j.property("init",j.identifier("component"),j.identifier(leafName))])])}return root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&call.node.arguments[0].type==="Literal").filter(call=>{let leafName=getLeafName(call.node.arguments[0].value);return importMap[leafName]}).replaceWith(addComponentParameter),root.toSource()}export{transformer as default};
@@ -1,2 +0,0 @@
1
- import{upgradeDeprecatedTypes}from"../chunk-YH46OF24.mjs";import prettier from"prettier";import*as t from"@babel/types";import{isIdentifier as isIdentifier2,isTSTypeAnnotation,isTSTypeReference}from"@babel/types";import{loadCsf}from"@storybook/csf-tools";import*as babel from"@babel/core";import*as recast from"recast";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(info,api,options){let makeTitle=userTitle=>userTitle||"FIXME",csf=loadCsf(info.source,{makeTitle});try{csf.parse()}catch(err){return logger.log(`Error ${err}, skipping`),info.source}let file=new babel.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])=>t.objectProperty(t.identifier(renameAnnotation(annotation)),val));if(t.isVariableDeclarator(decl)){let{init,id}=decl,template=getTemplateBindVariable(init);if(!t.isArrowFunctionExpression(init)&&!template)return;if(isSimpleCSFStory(init,annotations)){objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(importHelper.updateTypeTo(id,"StoryFn"),init)]));return}let storyFn=template&&csf._templates[template];storyFn||(storyFn=init);let renderAnnotation=isReactGlobalRenderFn(csf,storyFn)?[]:[t.objectProperty(t.identifier("render"),storyFn)];objectExports[key]=t.exportNamedDeclaration(t.variableDeclaration("const",[t.variableDeclarator(importHelper.updateTypeTo(id,"StoryObj"),t.objectExpression([...renderAnnotation,...annotations]))]))}}),importHelper.removeDeprecatedStoryImport(),csf._ast.program.body=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)},[]),upgradeDeprecatedTypes(file);let output=recast.print(csf._ast,{}).code;try{let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};output=prettier.format(output,{...prettierConfig,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 path.buildCodeFrameError(`This codemod does not support namespace imports for a ${path.node.source.value} package.
2
- Replace the namespace import with named imports and try again.`);if(!specifier.isImportSpecifier())return!1;let imported=specifier.get("imported");return 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(t.importSpecifier(t.identifier(type),t.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(isIdentifier2(id)&&isTSTypeAnnotation(id.typeAnnotation)&&isTSTypeReference(id.typeAnnotation.typeAnnotation)&&isIdentifier2(id.typeAnnotation.typeAnnotation.typeName)){let{name}=id.typeAnnotation.typeAnnotation.typeName;if(this.getAllLocalImports().includes(name)){let localTypeImport=this.getOrAddImport(type);return{...id,typeAnnotation:t.tsTypeAnnotation(t.tsTypeReference(t.identifier(localTypeImport),id.typeAnnotation.typeAnnotation.typeParameters))}}}return id};this.sbImportDeclarations=this.getAllSbImportDeclarations(file)}},parser="tsx";export{transform as default,parser};
@@ -1 +0,0 @@
1
- var getContainingStatement=n=>n.node.type.endsWith("Statement")?n:getContainingStatement(n.parent);function transformer(file,api){let j=api.jscodeshift,root=j(file.source),renameKey=exp=>exp.type==="Identifier"&&exp.name==="name"?j.identifier("storyName"):exp;if(root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.type==="ObjectExpression"&&def.node.declaration.properties.map(p=>p.key.name).includes("title")).size()===0)return root.toSource();let storyAssignments=root.find(j.AssignmentExpression).filter(exp=>{let{left,right}=exp.node;return left.type==="MemberExpression"&&left.object.type==="Identifier"&&left.property.type==="Identifier"&&left.property.name==="story"&&right.type==="ObjectExpression"});return storyAssignments.forEach(exp=>{let{left,right}=exp.node;right.properties.forEach(prop=>{getContainingStatement(exp).insertBefore(j.assignmentStatement("=",j.memberExpression(left.object,renameKey(prop.key)),prop.value))})}),storyAssignments.remove(),root.find(j.AssignmentExpression).filter(exp=>{let{left}=exp.node;return left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.property.type==="Identifier"&&left.object.property.name==="story"&&left.property.type==="Identifier"}).replaceWith(exp=>{let{left,right}=exp.node;return j.assignmentExpression("=",j.memberExpression(left.object.object,renameKey(left.property)),right)}),root.toSource({quote:"single"})}export{transformer as default};
@@ -1 +0,0 @@
1
- function transformer(file,api){let j=api.jscodeshift,createImportDeclaration=(specifiers,source)=>j.importDeclaration(specifiers.map(s=>j.importSpecifier(j.identifier(s))),j.literal(source)),deprecates={action:[["action"],"@storybook/addon-actions"],linkTo:[["linkTo"],"@storybook/addon-links"]};return j(file.source).find(j.ImportDeclaration).filter(i=>i.value.source.value==="@storybook/react").forEach(i=>{let importStatement=i.value;importStatement.specifiers=importStatement.specifiers.filter(specifier=>{let item=deprecates[specifier.local.name];if(item){let[specifiers,moduleName]=item;return i.insertAfter(createImportDeclaration(specifiers,moduleName)),!1}return specifier})}).toSource({quote:"single"})}export{transformer as default};
@@ -1 +0,0 @@
1
- import{jscodeshiftToPrettierParser,sanitizeName}from"../chunk-HBPKIMKE.mjs";import prettier from"prettier";import{logger}from"@storybook/node-logger";import{storyNameFromExport}from"@storybook/csf";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),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&&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 logger.warn(`Found ${initialStoriesOf.size()} 'storiesOf' calls, PLEASE FIX BY HAND: '${file.path}'`),source;let prettierConfig=prettier.resolveConfig.sync(".",{editorconfig:!0})||{printWidth:100,tabWidth:2,bracketSpacing:!0,trailingComma:"es5",singleQuote:!0};return prettier.format(source,{...prettierConfig,parser:jscodeshiftToPrettierParser(options.parser)})}export{transformer as default};
@@ -1 +0,0 @@
1
- import{transformer}from"../chunk-B5FMQ3BX.mjs";export{transformer as default};
@@ -1 +0,0 @@
1
- import{packageNames,transformer}from"../chunk-3OPQTROG.mjs";export{transformer as default,packageNames};
@@ -1 +0,0 @@
1
- import{parser,transform,upgradeDeprecatedTypes}from"../chunk-YH46OF24.mjs";export{transform as default,parser,upgradeDeprecatedTypes};
@@ -1 +0,0 @@
1
- function upgradeSeparator(path){return path.replace(/[|.]/g,"/")}function transformer(file,api,options){let j=api.jscodeshift,root=j(file.source);return root.find(j.CallExpression).filter(call=>call.node.callee.name==="storiesOf").filter(call=>call.node.arguments.length>0&&["Literal","StringLiteral"].includes(call.node.arguments[0].type)).forEach(call=>{let arg0=call.node.arguments[0];arg0.value=upgradeSeparator(arg0.value)}),root.find(j.ExportDefaultDeclaration).filter(def=>def.node.declaration.properties.map(p=>p.key.name).includes("title")).forEach(def=>{def.node.declaration&&def.node.declaration.properties&&def.node.declaration.properties.forEach(p=>{p.key.name==="title"&&(p.value.value=upgradeSeparator(p.value.value))})}),root.toSource({quote:"single"})}export{transformer as default};