@ecopages/codemod 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Codemod: migrate-data-hooks
3
+ *
4
+ * Renames the `eco.page()` data hooks and drops their envelopes.
5
+ *
6
+ * Before:
7
+ * eco.page({
8
+ * staticPaths: async () => ({ paths: [{ params: { slug: 'a' } }] }),
9
+ * staticProps: async ({ pathname: { params } }) => ({ props: { title: params.slug } }),
10
+ * render: ...
11
+ * })
12
+ *
13
+ * After:
14
+ * eco.page({
15
+ * paths: async () => [{ params: { slug: 'a' } }],
16
+ * props: async ({ params }) => ({ title: params.slug }),
17
+ * render: ...
18
+ * })
19
+ *
20
+ * A hook is rewritten only when every value it returns can be unwrapped: an object literal holding just the
21
+ * envelope key, or any expression inside an `async` function, which becomes `(await expr).props`. A hook it
22
+ * cannot rewrite is left unchanged and reported, so the old name still fails loudly with a pointer to the migration docs.
23
+ * The `GetStaticProps`, `GetStaticPaths` and `StaticPath` types are renamed to `GetProps`, `GetPaths` and `PagePath`.
24
+ *
25
+ * The props context passes `params` where it passed `pathname: { params }`, so in the `props` hook the first
26
+ * parameter is rewritten when it is destructured as `{ pathname: { params } }` or `{ pathname }`, or is a
27
+ * plain identifier read as `ctx.pathname.params`. A hook that reads `pathname` any other way, or declares a
28
+ * `params` binding already, keeps its `pathname` and is reported.
29
+ *
30
+ * @remarks
31
+ * This file is deliberately self-contained, with no import beyond `jscodeshift` types, because
32
+ * `@ecopages/codemod` is not published: users run it from its raw GitHub URL with `npx jscodeshift`.
33
+ */
34
+ export const parser = 'tsx';
35
+ const HOOKS = [
36
+ { from: 'staticProps', to: 'props' },
37
+ { from: 'staticPaths', to: 'paths' },
38
+ ];
39
+ const TYPE_RENAMES = {
40
+ GetStaticProps: 'GetProps',
41
+ GetStaticPaths: 'GetPaths',
42
+ StaticPath: 'PagePath',
43
+ };
44
+ /**
45
+ * Recast print options, kept in step with `print-options.ts`.
46
+ *
47
+ * @remarks
48
+ * Recast ends reprinted lines with the host's line ending unless told otherwise, so the source's own
49
+ * line ending is kept. The raw output indents rewritten lines with extra tabs; run your formatter afterwards.
50
+ */
51
+ function printOptions(source) {
52
+ return {
53
+ quote: 'single',
54
+ tabWidth: 2,
55
+ useTabs: true,
56
+ lineTerminator: source.includes('\r\n') ? '\r\n' : '\n',
57
+ };
58
+ }
59
+ const FUNCTION_TYPES = new Set([
60
+ 'ArrowFunctionExpression',
61
+ 'FunctionExpression',
62
+ 'FunctionDeclaration',
63
+ 'ObjectMethod',
64
+ ]);
65
+ function isNode(value) {
66
+ return typeof value === 'object' && value !== null && typeof value.type === 'string';
67
+ }
68
+ function isFunctionNode(value) {
69
+ return isNode(value) && FUNCTION_TYPES.has(value.type);
70
+ }
71
+ function unwrapExpression(node) {
72
+ let current = node;
73
+ while (isNode(current) &&
74
+ (current.type === 'ParenthesizedExpression' ||
75
+ current.type === 'TSAsExpression' ||
76
+ current.type === 'TSSatisfiesExpression')) {
77
+ current = current.expression;
78
+ }
79
+ return current;
80
+ }
81
+ function propertyKeyName(property) {
82
+ if (property.computed)
83
+ return undefined;
84
+ const key = property.key;
85
+ if (!isNode(key))
86
+ return undefined;
87
+ if (key.type === 'Identifier')
88
+ return key.name;
89
+ if (key.type === 'StringLiteral')
90
+ return key.value;
91
+ return undefined;
92
+ }
93
+ /** Returns the one property an envelope literal holds, or null when the literal is not a plain envelope. */
94
+ function readEnvelopeValue(node, key) {
95
+ const object = unwrapExpression(node);
96
+ if (!isNode(object) || object.type !== 'ObjectExpression')
97
+ return null;
98
+ const properties = object.properties;
99
+ if (properties.length !== 1)
100
+ return null;
101
+ const [property] = properties;
102
+ if (property.type !== 'ObjectProperty' || propertyKeyName(property) !== key)
103
+ return null;
104
+ return property.value;
105
+ }
106
+ /** Collects the `return` statements of one function body, without entering nested functions. */
107
+ function collectReturns(j, fn) {
108
+ const returns = [];
109
+ j(fn.body)
110
+ .find(j.ReturnStatement)
111
+ .forEach((returnPath) => {
112
+ let parent = returnPath.parent;
113
+ while (parent && parent.node !== fn.body) {
114
+ if (isFunctionNode(parent.node))
115
+ return;
116
+ parent = parent.parent;
117
+ }
118
+ returns.push(returnPath);
119
+ });
120
+ return returns;
121
+ }
122
+ /**
123
+ * Rewrites the values a hook function returns from `{ [key]: value }` to `value`.
124
+ *
125
+ * @returns `'unwrapped'` when every return was a plain envelope, `'awaited'` when at least one became
126
+ * `(await expr).key`, and null when the function was left untouched because it is not `async`.
127
+ */
128
+ function flattenHookFunction(j, fn, key) {
129
+ const targets = [];
130
+ if (isNode(fn.body) && fn.body.type !== 'BlockStatement') {
131
+ targets.push({
132
+ read: () => fn.body,
133
+ write: (value) => {
134
+ fn.body = value;
135
+ },
136
+ });
137
+ }
138
+ else {
139
+ for (const returnPath of collectReturns(j, fn)) {
140
+ const statement = returnPath.node;
141
+ if (!statement.argument)
142
+ continue;
143
+ targets.push({
144
+ read: () => statement.argument,
145
+ write: (value) => {
146
+ statement.argument = value;
147
+ },
148
+ });
149
+ }
150
+ }
151
+ const plans = targets.map((target) => {
152
+ const expression = target.read();
153
+ return { target, expression, unwrapped: readEnvelopeValue(expression, key) };
154
+ });
155
+ const needsAwait = plans.some((plan) => plan.unwrapped === null);
156
+ if (needsAwait && !fn.async) {
157
+ return null;
158
+ }
159
+ for (const { target, expression, unwrapped } of plans) {
160
+ if (unwrapped !== null) {
161
+ target.write(unwrapped);
162
+ continue;
163
+ }
164
+ target.write(j.memberExpression(j.awaitExpression(expression), j.identifier(key)));
165
+ }
166
+ return needsAwait ? 'awaited' : 'unwrapped';
167
+ }
168
+ /** Resolves the function a hook value stands for: an inline function, or a same-file declaration it names. */
169
+ function resolveHookFunction(j, root, value) {
170
+ const target = unwrapExpression(value);
171
+ if (isFunctionNode(target))
172
+ return target;
173
+ if (!isNode(target) || target.type !== 'Identifier')
174
+ return null;
175
+ const name = target.name;
176
+ let resolved = null;
177
+ root.find(j.FunctionDeclaration, { id: { name } }).forEach((path) => {
178
+ const parentType = path.parent.node.type;
179
+ if (parentType === 'Program' || parentType === 'ExportNamedDeclaration') {
180
+ resolved = path.node;
181
+ }
182
+ });
183
+ if (resolved)
184
+ return resolved;
185
+ root.find(j.VariableDeclarator, { id: { type: 'Identifier', name } }).forEach((path) => {
186
+ const init = unwrapExpression(path.node.init);
187
+ if (isFunctionNode(init))
188
+ resolved = init;
189
+ });
190
+ return resolved;
191
+ }
192
+ function hasPathnameTypeMember(value) {
193
+ if (Array.isArray(value))
194
+ return value.some(hasPathnameTypeMember);
195
+ if (!isNode(value))
196
+ return false;
197
+ if (value.type === 'TSPropertySignature') {
198
+ const key = value.key;
199
+ if (isNode(key) && key.name === 'pathname')
200
+ return true;
201
+ }
202
+ return Object.values(value).some(hasPathnameTypeMember);
203
+ }
204
+ /**
205
+ * Whether a node is a read of `name`, as opposed to a property name or object key that merely spells it.
206
+ */
207
+ function isBindingReference(path) {
208
+ const parent = path.parent?.node;
209
+ if (!parent || !isNode(parent))
210
+ return true;
211
+ if ((parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') &&
212
+ parent.property === path.node &&
213
+ !parent.computed) {
214
+ return false;
215
+ }
216
+ if (parent.type === 'ObjectProperty' && parent.key === path.node && !parent.computed && !parent.shorthand) {
217
+ return false;
218
+ }
219
+ return true;
220
+ }
221
+ function hasIdentifier(j, node, name) {
222
+ return j(node).find(j.Identifier, { name }).length > 0;
223
+ }
224
+ /** Whether a function already uses `params` as a binding, in its parameters or as a read in its body. */
225
+ function usesParamsBinding(j, fn) {
226
+ const inParams = (fn.params ?? []).some((param) => hasIdentifier(j, param, 'params'));
227
+ const inBody = j(fn.body)
228
+ .find(j.Identifier, { name: 'params' })
229
+ .some((path) => isBindingReference(path));
230
+ return inParams || inBody;
231
+ }
232
+ function isMemberNamed(node, name) {
233
+ const member = node;
234
+ return (isNode(member) &&
235
+ member.type === 'MemberExpression' &&
236
+ !member.computed &&
237
+ isNode(member.property) &&
238
+ member.property.name === name);
239
+ }
240
+ /** Whether a nested function or declaration in the body binds `name` again, so reads of it are not the parameter's. */
241
+ function rebindsName(j, fn, name) {
242
+ const body = j(fn.body);
243
+ const inFunctions = body
244
+ .find(j.Function)
245
+ .some((path) => path.node.params.some((param) => hasIdentifier(j, param, name)));
246
+ const inDeclarations = body.find(j.VariableDeclarator).some((path) => hasIdentifier(j, path.node.id, name));
247
+ return inFunctions || inDeclarations;
248
+ }
249
+ /**
250
+ * Replaces the node at `path` inside `fn.body` with `node`.
251
+ *
252
+ * @remarks
253
+ * An expression body that is the read itself (`async ({ pathname }) => pathname.params` once unwrapped) is the
254
+ * root of `j(fn.body)`, whose path has no parent to replace it in, so the body is reassigned instead.
255
+ */
256
+ function replaceInBody(j, fn, path, node) {
257
+ if (path.node === fn.body) {
258
+ fn.body = node;
259
+ return;
260
+ }
261
+ j(path).replaceWith(node);
262
+ }
263
+ const CONTEXT_FIELDS = new Set(['pathname', 'appConfig', 'runtimeOrigin']);
264
+ /**
265
+ * Rewrites `ctx.pathname.params` reads to `ctx.params`, only when `ctx` is read as nothing but a plain member
266
+ * of the context (`pathname`, `appConfig` or `runtimeOrigin`), with `ctx.pathname` always followed by `.params`.
267
+ */
268
+ function rewriteContextIdentifier(j, fn, local) {
269
+ if (rebindsName(j, fn, local))
270
+ return 'unsafe';
271
+ const accesses = [];
272
+ let safe = true;
273
+ j(fn.body)
274
+ .find(j.Identifier, { name: local })
275
+ .forEach((path) => {
276
+ if (!isBindingReference(path))
277
+ return;
278
+ const parent = path.parent.node;
279
+ const field = isNode(parent.property) ? parent.property.name : '';
280
+ if (parent.object !== path.node || parent.computed || !CONTEXT_FIELDS.has(field)) {
281
+ safe = false;
282
+ return;
283
+ }
284
+ if (field !== 'pathname')
285
+ return;
286
+ const grand = path.parent.parent?.node;
287
+ if (grand?.object === parent && isMemberNamed(grand, 'params')) {
288
+ accesses.push(path.parent.parent);
289
+ return;
290
+ }
291
+ safe = false;
292
+ });
293
+ if (!safe)
294
+ return 'unsafe';
295
+ if (accesses.length === 0)
296
+ return 'unchanged';
297
+ for (const access of accesses) {
298
+ replaceInBody(j, fn, access, j.memberExpression(j.identifier(local), j.identifier('params')));
299
+ }
300
+ return 'rewritten';
301
+ }
302
+ /** Rewrites a `pathname` binding named `local` and read as `local.params` into a plain `params` read. */
303
+ function flattenPathnameReads(j, fn, local) {
304
+ const reads = [];
305
+ let safe = true;
306
+ j(fn.body)
307
+ .find(j.Identifier, { name: local })
308
+ .forEach((path) => {
309
+ if (!isBindingReference(path))
310
+ return;
311
+ const parent = path.parent.node;
312
+ if (parent.object === path.node && isMemberNamed(parent, 'params')) {
313
+ reads.push(path.parent);
314
+ return;
315
+ }
316
+ safe = false;
317
+ });
318
+ if (!safe)
319
+ return false;
320
+ for (const read of reads) {
321
+ replaceInBody(j, fn, read, j.identifier('params'));
322
+ }
323
+ return true;
324
+ }
325
+ /** Replaces `pathname: local` with `params` when every read of `local` is `local.params`. */
326
+ function rewriteBoundPathname(j, fn, properties, index, paramsTaken) {
327
+ const local = properties[index].value.name;
328
+ if (paramsTaken || usesParamsBinding(j, fn) || rebindsName(j, fn, local) || !flattenPathnameReads(j, fn, local)) {
329
+ return 'unsafe';
330
+ }
331
+ const replacement = j.objectProperty(j.identifier('params'), j.identifier('params'));
332
+ replacement.shorthand = true;
333
+ properties[index] = replacement;
334
+ return 'rewritten';
335
+ }
336
+ /** Rewrites the `pathname` entry of a destructured context parameter, at `index` of `properties`. */
337
+ function rewriteContextPattern(j, fn, properties, index) {
338
+ const value = properties[index].value;
339
+ const paramsTaken = properties.some((property, at) => at !== index && hasIdentifier(j, property, 'params'));
340
+ if (isNode(value) && value.type === 'ObjectPattern') {
341
+ const inner = value.properties;
342
+ const [only] = inner;
343
+ const isParams = only?.type === 'ObjectProperty' && !only.computed && isNode(only.key) && only.key.name === 'params';
344
+ if (inner.length !== 1 || !isParams || paramsTaken)
345
+ return 'unsafe';
346
+ properties[index] = only;
347
+ return 'rewritten';
348
+ }
349
+ if (isNode(value) && value.type === 'Identifier') {
350
+ return rewriteBoundPathname(j, fn, properties, index, paramsTaken);
351
+ }
352
+ return 'unsafe';
353
+ }
354
+ /**
355
+ * Rewrites the context parameter of a `props` hook from `pathname: { params }` to `params`.
356
+ *
357
+ * @returns `'rewritten'`, `'unchanged'` when the hook never reads `pathname`, or `'unsafe'` when it reads it in a
358
+ * way that cannot be rewritten and was left as written.
359
+ */
360
+ function rewritePathnameContext(j, fn) {
361
+ const [first] = fn.params ?? [];
362
+ if (!isNode(first))
363
+ return 'unchanged';
364
+ if (hasPathnameTypeMember(first.typeAnnotation))
365
+ return 'unsafe';
366
+ if (first.type === 'AssignmentPattern') {
367
+ const left = first.left;
368
+ return isNode(left) && (left.type === 'Identifier' || hasIdentifier(j, left, 'pathname'))
369
+ ? 'unsafe'
370
+ : 'unchanged';
371
+ }
372
+ if (first.type === 'Identifier')
373
+ return rewriteContextIdentifier(j, fn, first.name);
374
+ if (first.type !== 'ObjectPattern')
375
+ return 'unchanged';
376
+ const properties = first.properties;
377
+ const index = properties.findIndex((property) => property.type === 'ObjectProperty' &&
378
+ !property.computed &&
379
+ isNode(property.key) &&
380
+ (property.key.name === 'pathname' || property.key.value === 'pathname'));
381
+ return index === -1 ? 'unchanged' : rewriteContextPattern(j, fn, properties, index);
382
+ }
383
+ function renameKey(property, to) {
384
+ const mutable = property;
385
+ if (mutable.shorthand) {
386
+ mutable.shorthand = false;
387
+ mutable.value = mutable.key;
388
+ mutable.key = { type: 'Identifier', name: to };
389
+ return;
390
+ }
391
+ if (mutable.key.type === 'StringLiteral') {
392
+ mutable.key = { type: 'Identifier', name: to };
393
+ return;
394
+ }
395
+ mutable.key.name = to;
396
+ }
397
+ function isEcoPageCall(node) {
398
+ const callee = node.callee;
399
+ if (!isNode(callee) || callee.type !== 'MemberExpression')
400
+ return false;
401
+ const { object, property } = callee;
402
+ return (isNode(object) &&
403
+ object.type === 'Identifier' &&
404
+ object.name === 'eco' &&
405
+ isNode(property) &&
406
+ property.type === 'Identifier' &&
407
+ property.name === 'page');
408
+ }
409
+ export default function transform(file, api, _options) {
410
+ const j = api.jscodeshift;
411
+ const root = j(file.source);
412
+ let changed = false;
413
+ const skipped = [];
414
+ const awaited = [];
415
+ const pathnameSkipped = [];
416
+ root.find(j.CallExpression)
417
+ .filter((path) => isEcoPageCall(path.node))
418
+ .forEach((path) => {
419
+ const [argument] = path.node.arguments;
420
+ if (!isNode(argument) || argument.type !== 'ObjectExpression')
421
+ return;
422
+ const properties = argument.properties;
423
+ for (const { from, to } of HOOKS) {
424
+ const property = properties.find((candidate) => (candidate.type === 'ObjectProperty' || candidate.type === 'ObjectMethod') &&
425
+ propertyKeyName(candidate) === from);
426
+ if (!property)
427
+ continue;
428
+ const fn = property.type === 'ObjectMethod'
429
+ ? property
430
+ : resolveHookFunction(j, root, property.value);
431
+ const result = fn ? flattenHookFunction(j, fn, to) : null;
432
+ if (result === null) {
433
+ skipped.push(`${from} in ${file.path}`);
434
+ continue;
435
+ }
436
+ if (result === 'awaited') {
437
+ awaited.push(`${from} in ${file.path}`);
438
+ }
439
+ if (to === 'props' && fn && rewritePathnameContext(j, fn) === 'unsafe') {
440
+ pathnameSkipped.push(`${from} in ${file.path}`);
441
+ }
442
+ renameKey(property, to);
443
+ changed = true;
444
+ }
445
+ });
446
+ const ecopagesTypeNames = new Set();
447
+ root.find(j.ImportDeclaration)
448
+ .filter((path) => String(path.node.source.value).startsWith('@ecopages/'))
449
+ .forEach((path) => {
450
+ for (const specifier of path.node.specifiers ?? []) {
451
+ if (specifier.type !== 'ImportSpecifier')
452
+ continue;
453
+ const importedName = String(specifier.imported.name);
454
+ if (importedName in TYPE_RENAMES) {
455
+ ecopagesTypeNames.add(importedName);
456
+ }
457
+ }
458
+ });
459
+ if (ecopagesTypeNames.size > 0) {
460
+ root.find(j.Identifier)
461
+ .filter((path) => ecopagesTypeNames.has(path.node.name))
462
+ .forEach((path) => {
463
+ path.node.name = TYPE_RENAMES[path.node.name] ?? path.node.name;
464
+ changed = true;
465
+ });
466
+ }
467
+ for (const entry of skipped) {
468
+ api.report(`migrate-data-hooks: ${entry} returns a value this codemod cannot unwrap. Rename it to props or paths and return the value directly, without the { props } or { paths } envelope.`);
469
+ }
470
+ for (const entry of awaited) {
471
+ api.report(`migrate-data-hooks: ${entry} returns a value this codemod could not unwrap from a literal, so it now reads (await value).props or (await value).paths. Move the unwrap into the helper that builds the value if you want the hook to return it directly.`);
472
+ }
473
+ for (const entry of pathnameSkipped) {
474
+ api.report(`migrate-data-hooks: ${entry} reads pathname in a way this codemod cannot rewrite. The props context passes params where it passed pathname.params, so change pathname.params to params by hand.`);
475
+ }
476
+ return changed ? root.toSource(printOptions(file.source)) : null;
477
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Codemod: migrate-to-eco-component
3
+ *
4
+ * Transforms components from the legacy pattern with .config assignment to eco.component() API.
5
+ *
6
+ * Before:
7
+ * export const Counter: EcoComponent<Props> = ({ count }) => <my-counter />;
8
+ * Counter.config = { dependencies: { scripts, stylesheets } };
9
+ *
10
+ * After:
11
+ * export const Counter = eco.component<Props>({
12
+ * dependencies: { scripts, stylesheets },
13
+ * render: ({ count }) => <my-counter />,
14
+ * });
15
+ */
16
+ import type { API, FileInfo, Options } from 'jscodeshift';
17
+ export declare const parser = "tsx";
18
+ export default function transformer(file: FileInfo, api: API, _options: Options): string | null;