@storybook/codemod 7.0.0-beta.52 → 7.0.0-beta.54
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.js +1 -1
- package/dist/transforms/mdx-to-csf.d.ts +7 -0
- package/dist/transforms/mdx-to-csf.js +55 -0
- package/jest.config.js +1 -0
- package/package.json +20 -9
- package/src/index.js +20 -4
- package/src/transforms/__tests__/mdx-to-csf.test.ts +587 -0
- package/src/transforms/mdx-to-csf.ts +339 -0
- package/dist/chunk-3OPQTROG.mjs +0 -1
- package/dist/chunk-B5FMQ3BX.mjs +0 -1
- package/dist/chunk-HBPKIMKE.mjs +0 -1
- package/dist/chunk-YH46OF24.mjs +0 -2
- package/dist/index.mjs +0 -1
- package/dist/transforms/add-component-parameters.mjs +0 -1
- package/dist/transforms/csf-2-to-3.mjs +0 -2
- package/dist/transforms/csf-hoist-story-annotations.mjs +0 -1
- package/dist/transforms/move-builtin-addons.mjs +0 -1
- package/dist/transforms/storiesof-to-csf.mjs +0 -1
- package/dist/transforms/update-addon-info.mjs +0 -1
- package/dist/transforms/update-organisation-name.mjs +0 -1
- package/dist/transforms/upgrade-deprecated-types.mjs +0 -1
- package/dist/transforms/upgrade-hierarchy-separators.mjs +0 -1
@@ -0,0 +1,339 @@
|
|
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
|
+
const metaAttributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute> = [];
|
60
|
+
const storiesMap = new Map<
|
61
|
+
string,
|
62
|
+
| {
|
63
|
+
type: 'value';
|
64
|
+
attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>;
|
65
|
+
children: (MdxJsxFlowElement | MdxJsxTextElement)['children'];
|
66
|
+
}
|
67
|
+
| {
|
68
|
+
type: 'reference';
|
69
|
+
}
|
70
|
+
| {
|
71
|
+
type: 'id';
|
72
|
+
}
|
73
|
+
>();
|
74
|
+
|
75
|
+
// rewrite addon docs import
|
76
|
+
visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
|
77
|
+
node.value = node.value
|
78
|
+
.replaceAll('@storybook/addon-docs', '@storybook/blocks')
|
79
|
+
.replaceAll('@storybook/addon-docs/blocks', '@storybook/blocks');
|
80
|
+
});
|
81
|
+
|
82
|
+
const file = getEsmAst(root);
|
83
|
+
addStoriesImport(root, baseName, storyNamespaceName);
|
84
|
+
|
85
|
+
visit(
|
86
|
+
root,
|
87
|
+
['mdxJsxFlowElement', 'mdxJsxTextElement'],
|
88
|
+
(node: MdxJsxFlowElement | MdxJsxTextElement, index, parent) => {
|
89
|
+
if (is(node, { name: 'Meta' })) {
|
90
|
+
metaAttributes.push(...node.attributes);
|
91
|
+
node.attributes = [
|
92
|
+
{
|
93
|
+
type: 'mdxJsxAttribute',
|
94
|
+
name: 'of',
|
95
|
+
value: {
|
96
|
+
type: 'mdxJsxAttributeValueExpression',
|
97
|
+
value: storyNamespaceName,
|
98
|
+
},
|
99
|
+
},
|
100
|
+
];
|
101
|
+
}
|
102
|
+
if (is(node, { name: 'Story' })) {
|
103
|
+
const nameAttribute = node.attributes.find(
|
104
|
+
(it) => it.type === 'mdxJsxAttribute' && it.name === 'name'
|
105
|
+
);
|
106
|
+
const idAttribute = node.attributes.find(
|
107
|
+
(it) => it.type === 'mdxJsxAttribute' && it.name === 'id'
|
108
|
+
);
|
109
|
+
const storyAttribute = node.attributes.find(
|
110
|
+
(it) => it.type === 'mdxJsxAttribute' && it.name === 'story'
|
111
|
+
);
|
112
|
+
if (typeof nameAttribute?.value === 'string') {
|
113
|
+
let name = nameToValidExport(nameAttribute.value);
|
114
|
+
while (variableNameExists(name)) name += '_';
|
115
|
+
|
116
|
+
storiesMap.set(name, {
|
117
|
+
type: 'value',
|
118
|
+
attributes: node.attributes,
|
119
|
+
children: node.children,
|
120
|
+
});
|
121
|
+
node.attributes = [
|
122
|
+
{
|
123
|
+
type: 'mdxJsxAttribute',
|
124
|
+
name: 'of',
|
125
|
+
value: {
|
126
|
+
type: 'mdxJsxAttributeValueExpression',
|
127
|
+
value: `${storyNamespaceName}.${name}`,
|
128
|
+
},
|
129
|
+
},
|
130
|
+
];
|
131
|
+
node.children = [];
|
132
|
+
} else if (idAttribute?.value) {
|
133
|
+
// e.g. <Story id="button--primary" />
|
134
|
+
// should be migrated manually as it is very hard to find out where the definition of such a string id is located
|
135
|
+
const nodeString = mdxProcessor.stringify({ type: 'root', children: [node] }).trim();
|
136
|
+
const newNode: MdxFlowExpression = {
|
137
|
+
type: 'mdxFlowExpression',
|
138
|
+
value: `/* ${nodeString} is deprecated, please migrate it to <Story of={referenceToStory} /> */`,
|
139
|
+
};
|
140
|
+
storiesMap.set(idAttribute.value as string, { type: 'id' });
|
141
|
+
parent.children.splice(index, 0, newNode);
|
142
|
+
// current index is the new comment, and index + 1 is current node
|
143
|
+
// SKIP traversing current node, and continue with the node after that
|
144
|
+
return [SKIP, index + 2];
|
145
|
+
} else if (
|
146
|
+
storyAttribute?.type === 'mdxJsxAttribute' &&
|
147
|
+
typeof storyAttribute.value === 'object' &&
|
148
|
+
storyAttribute.value.type === 'mdxJsxAttributeValueExpression'
|
149
|
+
) {
|
150
|
+
// e.g. <Story story={Primary} />
|
151
|
+
|
152
|
+
const name = storyAttribute.value.value;
|
153
|
+
node.attributes = [
|
154
|
+
{
|
155
|
+
type: 'mdxJsxAttribute',
|
156
|
+
name: 'of',
|
157
|
+
value: {
|
158
|
+
type: 'mdxJsxAttributeValueExpression',
|
159
|
+
value: `${storyNamespaceName}.${name}`,
|
160
|
+
},
|
161
|
+
},
|
162
|
+
];
|
163
|
+
node.children = [];
|
164
|
+
|
165
|
+
storiesMap.set(name, { type: 'reference' });
|
166
|
+
} else {
|
167
|
+
parent.children.splice(index, 1);
|
168
|
+
// Do not traverse `node`, continue at the node *now* at `index`.
|
169
|
+
return [SKIP, index];
|
170
|
+
}
|
171
|
+
}
|
172
|
+
return undefined;
|
173
|
+
}
|
174
|
+
);
|
175
|
+
|
176
|
+
const metaProperties = metaAttributes.flatMap((attribute) => {
|
177
|
+
if (attribute.type === 'mdxJsxAttribute') {
|
178
|
+
if (typeof attribute.value === 'string') {
|
179
|
+
return [t.objectProperty(t.identifier(attribute.name), t.stringLiteral(attribute.value))];
|
180
|
+
}
|
181
|
+
return [
|
182
|
+
t.objectProperty(t.identifier(attribute.name), babelParseExpression(attribute.value.value)),
|
183
|
+
];
|
184
|
+
}
|
185
|
+
return [];
|
186
|
+
});
|
187
|
+
|
188
|
+
file.path.traverse({
|
189
|
+
// remove mdx imports from csf
|
190
|
+
ImportDeclaration(path) {
|
191
|
+
if (path.node.source.value === '@storybook/blocks') {
|
192
|
+
path.remove();
|
193
|
+
}
|
194
|
+
},
|
195
|
+
// remove exports from csf file
|
196
|
+
ExportNamedDeclaration(path) {
|
197
|
+
path.replaceWith(path.node.declaration);
|
198
|
+
},
|
199
|
+
});
|
200
|
+
|
201
|
+
if (storiesMap.size === 0) {
|
202
|
+
// A CSF file must have at least one story, so skip migrating if this is the case.
|
203
|
+
return null;
|
204
|
+
}
|
205
|
+
|
206
|
+
const newStatements: t.Statement[] = [
|
207
|
+
t.exportDefaultDeclaration(t.objectExpression(metaProperties)),
|
208
|
+
];
|
209
|
+
|
210
|
+
function mapChildrenToRender(children: (MdxJsxFlowElement | MdxJsxTextElement)['children']) {
|
211
|
+
const child = children[0];
|
212
|
+
|
213
|
+
if (!child) return undefined;
|
214
|
+
|
215
|
+
if (child.type === 'text') {
|
216
|
+
return t.arrowFunctionExpression([], t.stringLiteral(child.value));
|
217
|
+
}
|
218
|
+
if (child.type === 'mdxFlowExpression' || child.type === 'mdxTextExpression') {
|
219
|
+
const expression = babelParseExpression(child.value);
|
220
|
+
|
221
|
+
// Recreating those lines: https://github.com/storybookjs/mdx1-csf/blob/f408fc97e9a63097ca1ee577df9315a3cccca975/src/sb-mdx-plugin.ts#L185-L198
|
222
|
+
const BIND_REGEX = /\.bind\(.*\)/;
|
223
|
+
if (BIND_REGEX.test(child.value)) {
|
224
|
+
return expression;
|
225
|
+
}
|
226
|
+
if (t.isIdentifier(expression)) {
|
227
|
+
return expression;
|
228
|
+
}
|
229
|
+
if (t.isArrowFunctionExpression(expression)) {
|
230
|
+
return expression;
|
231
|
+
}
|
232
|
+
return t.arrowFunctionExpression([], expression);
|
233
|
+
}
|
234
|
+
|
235
|
+
const expression = babelParseExpression(
|
236
|
+
mdxProcessor.stringify({ type: 'root', children: [child] })
|
237
|
+
);
|
238
|
+
return t.arrowFunctionExpression([], expression);
|
239
|
+
}
|
240
|
+
|
241
|
+
function variableNameExists(name: string) {
|
242
|
+
let found = false;
|
243
|
+
file.path.traverse({
|
244
|
+
VariableDeclarator: (path) => {
|
245
|
+
const lVal = path.node.id;
|
246
|
+
if (t.isIdentifier(lVal) && lVal.name === name) found = true;
|
247
|
+
},
|
248
|
+
});
|
249
|
+
return found;
|
250
|
+
}
|
251
|
+
|
252
|
+
newStatements.push(
|
253
|
+
...[...storiesMap].flatMap(([key, value]) => {
|
254
|
+
if (value.type === 'id') return [];
|
255
|
+
if (value.type === 'reference') {
|
256
|
+
return [
|
257
|
+
t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier(key), t.identifier(key))]),
|
258
|
+
];
|
259
|
+
}
|
260
|
+
const renderProperty = mapChildrenToRender(value.children);
|
261
|
+
const newObject = t.objectExpression([
|
262
|
+
...(renderProperty
|
263
|
+
? [t.objectProperty(t.identifier('render'), mapChildrenToRender(value.children))]
|
264
|
+
: []),
|
265
|
+
...value.attributes.flatMap((attribute) => {
|
266
|
+
if (attribute.type === 'mdxJsxAttribute') {
|
267
|
+
if (typeof attribute.value === 'string') {
|
268
|
+
return [
|
269
|
+
t.objectProperty(t.identifier(attribute.name), t.stringLiteral(attribute.value)),
|
270
|
+
];
|
271
|
+
}
|
272
|
+
return [
|
273
|
+
t.objectProperty(
|
274
|
+
t.identifier(attribute.name),
|
275
|
+
babelParseExpression(attribute.value.value)
|
276
|
+
),
|
277
|
+
];
|
278
|
+
}
|
279
|
+
return [];
|
280
|
+
}),
|
281
|
+
]);
|
282
|
+
|
283
|
+
return [
|
284
|
+
t.exportNamedDeclaration(
|
285
|
+
t.variableDeclaration('const', [t.variableDeclarator(t.identifier(key), newObject)])
|
286
|
+
),
|
287
|
+
];
|
288
|
+
})
|
289
|
+
);
|
290
|
+
|
291
|
+
file.path.node.body = [...file.path.node.body, ...newStatements];
|
292
|
+
|
293
|
+
const newMdx = mdxProcessor.stringify(root);
|
294
|
+
let output = recast.print(file.path.node).code;
|
295
|
+
|
296
|
+
const prettierConfig = prettier.resolveConfig.sync('.', { editorconfig: true }) || {
|
297
|
+
printWidth: 100,
|
298
|
+
tabWidth: 2,
|
299
|
+
bracketSpacing: true,
|
300
|
+
trailingComma: 'es5',
|
301
|
+
singleQuote: true,
|
302
|
+
};
|
303
|
+
|
304
|
+
output = prettier.format(output, { ...prettierConfig, filepath: `file.jsx` });
|
305
|
+
|
306
|
+
return [newMdx, output];
|
307
|
+
}
|
308
|
+
|
309
|
+
function getEsmAst(root: Root) {
|
310
|
+
const esm: string[] = [];
|
311
|
+
visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
|
312
|
+
esm.push(node.value);
|
313
|
+
});
|
314
|
+
const esmSource = `${esm.join('\n\n')}`;
|
315
|
+
|
316
|
+
// @ts-expect-error File is not yet exposed, see https://github.com/babel/babel/issues/11350#issuecomment-644118606
|
317
|
+
const file: BabelFile = new babel.File(
|
318
|
+
{ filename: 'info.path' },
|
319
|
+
{ code: esmSource, ast: babelParse(esmSource) }
|
320
|
+
);
|
321
|
+
return file;
|
322
|
+
}
|
323
|
+
|
324
|
+
function addStoriesImport(root: Root, baseName: string, storyNamespaceName: string): void {
|
325
|
+
let found = false;
|
326
|
+
|
327
|
+
visit(root, ['mdxjsEsm'], (node: MdxjsEsm) => {
|
328
|
+
if (!found) {
|
329
|
+
node.value += `\nimport * as ${storyNamespaceName} from './${baseName}.stories';`;
|
330
|
+
found = true;
|
331
|
+
}
|
332
|
+
});
|
333
|
+
}
|
334
|
+
|
335
|
+
export function nameToValidExport(name: string) {
|
336
|
+
const [first, ...rest] = Array.from(camelCase(name));
|
337
|
+
|
338
|
+
return `${first.match(/[a-zA-Z_$]/) ? first.toUpperCase() : `$${first}`}${rest.join('')}`;
|
339
|
+
}
|
package/dist/chunk-3OPQTROG.mjs
DELETED
@@ -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};
|
package/dist/chunk-B5FMQ3BX.mjs
DELETED
@@ -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};
|
package/dist/chunk-HBPKIMKE.mjs
DELETED
@@ -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};
|
package/dist/chunk-YH46OF24.mjs
DELETED
@@ -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)&¶m.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};
|