@ecopages/codemod 0.9.0 → 0.10.1

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,49 @@
1
+ /**
2
+ * Codemod: migrate-radiant-bindings
3
+ *
4
+ * Moves `@ecopages/radiant` code off the `$name` companion bindings and the `bind` option, which Radiant 0.10.0
5
+ * removed, onto the host's binding namespace `this.$`.
6
+ *
7
+ * Before:
8
+ * class Counter extends RadiantElement {
9
+ * @prop({ type: Number, bind: true }) count = 0;
10
+ * @state label: string = 'Count';
11
+ * @attr({ source: 'data-step', type: Number, bind: 'stepBinding' }) step = 1;
12
+ * render() { return <p>{this.$label}: {this.$count} by {this.stepBinding}</p>; }
13
+ * }
14
+ *
15
+ * After:
16
+ * class Counter extends RadiantElement<{ count: number; label: string; step: number }> {
17
+ * @prop({ type: Number }) count = 0;
18
+ * @state label: string = 'Count';
19
+ * @attr({ source: 'data-step', type: Number }) step = 1;
20
+ * render() { return <p>{this.$.label}: {this.$.count} by {this.$.step}</p>; }
21
+ * }
22
+ *
23
+ * A reactive member is a field decorated with `@prop`, `@state`, `@attr` or `@signal` (as a decorator or as a
24
+ * call on `Class.prototype`), or one created with `this.createReactiveProp` or `this.createReactiveField`. In
25
+ * 0.9.0 it had a companion named `$name` when `bind` was `true`, or omitted on a class that extends
26
+ * `RadiantElement`, `RadiantController` or `FormAssociatedElement`, and one named after the string when `bind`
27
+ * was a string. A read of that companion on `this` becomes `this.$.name`, and the members it rewrote are added
28
+ * to the type argument of `extends RadiantElement` or `extends RadiantController`, typed from the annotation or
29
+ * a literal initializer. A `bind` that is `true`, `false` or a string literal is removed, with the options
30
+ * object when it ends up empty and the parameter is optional.
31
+ *
32
+ * Anything it cannot rewrite safely is left unchanged and reported with its line: `ReactiveBindingOption`
33
+ * imports, `defineReactiveBinding` and `shouldAutoBindReactiveMembers`, computed `this['$name']` access,
34
+ * writes and destructuring of a companion, companion reads outside their class, a `bind` or options value it
35
+ * cannot read, a member type it cannot tell, a read of a member that had no companion, and `$name` reads in a
36
+ * class whose base is outside the file.
37
+ *
38
+ * @remarks
39
+ * The transform splices the source text at the parsed node offsets instead of reprinting through Recast. Adding
40
+ * a type argument changes the class node, and Recast then reprints the whole class body, which re-indents it
41
+ * and drops whitespace in JSX text. Splicing keeps every untouched character, so the source's tabs or spaces,
42
+ * line endings and JSX text stay as written.
43
+ *
44
+ * 0.9.0 defined the companion on the element's prototype, so every instance read the first instance's binding.
45
+ * `this.$.name` reads the instance's own binding, which is the fix 0.10.0 makes; no other behaviour changes.
46
+ */
47
+ import type { API, FileInfo, Options } from 'jscodeshift';
48
+ export declare const parser = "tsx";
49
+ export default function transform(file: FileInfo, api: API, _options: Options): string | null;
@@ -0,0 +1,613 @@
1
+ /**
2
+ * Codemod: migrate-radiant-bindings
3
+ *
4
+ * Moves `@ecopages/radiant` code off the `$name` companion bindings and the `bind` option, which Radiant 0.10.0
5
+ * removed, onto the host's binding namespace `this.$`.
6
+ *
7
+ * Before:
8
+ * class Counter extends RadiantElement {
9
+ * @prop({ type: Number, bind: true }) count = 0;
10
+ * @state label: string = 'Count';
11
+ * @attr({ source: 'data-step', type: Number, bind: 'stepBinding' }) step = 1;
12
+ * render() { return <p>{this.$label}: {this.$count} by {this.stepBinding}</p>; }
13
+ * }
14
+ *
15
+ * After:
16
+ * class Counter extends RadiantElement<{ count: number; label: string; step: number }> {
17
+ * @prop({ type: Number }) count = 0;
18
+ * @state label: string = 'Count';
19
+ * @attr({ source: 'data-step', type: Number }) step = 1;
20
+ * render() { return <p>{this.$.label}: {this.$.count} by {this.$.step}</p>; }
21
+ * }
22
+ *
23
+ * A reactive member is a field decorated with `@prop`, `@state`, `@attr` or `@signal` (as a decorator or as a
24
+ * call on `Class.prototype`), or one created with `this.createReactiveProp` or `this.createReactiveField`. In
25
+ * 0.9.0 it had a companion named `$name` when `bind` was `true`, or omitted on a class that extends
26
+ * `RadiantElement`, `RadiantController` or `FormAssociatedElement`, and one named after the string when `bind`
27
+ * was a string. A read of that companion on `this` becomes `this.$.name`, and the members it rewrote are added
28
+ * to the type argument of `extends RadiantElement` or `extends RadiantController`, typed from the annotation or
29
+ * a literal initializer. A `bind` that is `true`, `false` or a string literal is removed, with the options
30
+ * object when it ends up empty and the parameter is optional.
31
+ *
32
+ * Anything it cannot rewrite safely is left unchanged and reported with its line: `ReactiveBindingOption`
33
+ * imports, `defineReactiveBinding` and `shouldAutoBindReactiveMembers`, computed `this['$name']` access,
34
+ * writes and destructuring of a companion, companion reads outside their class, a `bind` or options value it
35
+ * cannot read, a member type it cannot tell, a read of a member that had no companion, and `$name` reads in a
36
+ * class whose base is outside the file.
37
+ *
38
+ * @remarks
39
+ * The transform splices the source text at the parsed node offsets instead of reprinting through Recast. Adding
40
+ * a type argument changes the class node, and Recast then reprints the whole class body, which re-indents it
41
+ * and drops whitespace in JSX text. Splicing keeps every untouched character, so the source's tabs or spaces,
42
+ * line endings and JSX text stay as written.
43
+ *
44
+ * 0.9.0 defined the companion on the element's prototype, so every instance read the first instance's binding.
45
+ * `this.$.name` reads the instance's own binding, which is the fix 0.10.0 makes; no other behaviour changes.
46
+ */
47
+ import { applyEdits, isNode, keyName, lineOf, offsetsOf, parseOptions, RADIANT_SOURCE, readRadiantImports, removeNode, stringValue, } from './source-edits.js';
48
+ export const parser = 'tsx';
49
+ const TRANSFORM = 'migrate-radiant-bindings';
50
+ /** Base classes whose members had a companion when `bind` was omitted. */
51
+ const AUTO_BIND_BASES = new Set(['RadiantElement', 'RadiantController', 'FormAssociatedElement']);
52
+ /** Base classes that take the binding shape as their type argument. */
53
+ const GENERIC_BASES = new Set(['RadiantElement', 'RadiantController']);
54
+ /** Decorator factories whose first argument is the member options. */
55
+ const OPTION_FACTORIES = new Set(['prop', 'attr', 'signal']);
56
+ /** Decorators that also apply bare, as `@state` or `@signal`. */
57
+ const BARE_DECORATORS = new Set(['state', 'signal']);
58
+ /** Host methods that create a reactive member, with the index of their options argument. */
59
+ const MEMBER_HELPERS = { createReactiveProp: 1, createReactiveField: 2 };
60
+ /**
61
+ * Callees whose options parameter is optional, so an options object left empty can be dropped.
62
+ *
63
+ * @remarks
64
+ * `prop` and `createReactiveProp` require options with a `type`, so their object is kept.
65
+ */
66
+ const OPTIONAL_OPTIONS = new Set(['attr', 'signal', 'createReactiveField']);
67
+ const REMOVED_HOST_METHODS = new Set(['defineReactiveBinding', 'shouldAutoBindReactiveMembers']);
68
+ const SIGNAL_TYPES = new Set(['WritableSignal', 'Signal', 'ReadonlySignal']);
69
+ /** Types that need parentheses before `| undefined` or `& {...}` is appended to them. */
70
+ const LOOSE_TYPES = new Set(['TSFunctionType', 'TSConstructorType', 'TSConditionalType', 'TSUnionType']);
71
+ const CLASS_MEMBER_TYPES = new Set([
72
+ 'ClassMethod',
73
+ 'ClassPrivateMethod',
74
+ 'ClassProperty',
75
+ 'ClassPrivateProperty',
76
+ 'ClassAccessorProperty',
77
+ ]);
78
+ const FUNCTION_TYPES = new Set(['FunctionExpression', 'FunctionDeclaration', 'ObjectMethod']);
79
+ /** Finds the property named `bind` in an options object, or why it cannot be read. */
80
+ function readBind(options) {
81
+ if (options === undefined)
82
+ return { bind: { kind: 'auto' } };
83
+ if (!isNode(options) || options.type !== 'ObjectExpression')
84
+ return { bind: { kind: 'unknown' } };
85
+ const properties = options.properties;
86
+ if (properties.some((property) => property.type === 'SpreadElement'))
87
+ return { bind: { kind: 'unknown' } };
88
+ const property = properties.find((candidate) => candidate.type === 'ObjectProperty' && keyName(candidate) === 'bind');
89
+ if (!property)
90
+ return { bind: { kind: 'auto' } };
91
+ const value = property.value;
92
+ if (value.type === 'BooleanLiteral') {
93
+ return { bind: value.value ? { kind: 'named', name: '' } : { kind: 'none' }, property };
94
+ }
95
+ const name = stringValue(value);
96
+ return { bind: name === undefined ? { kind: 'unknown' } : { kind: 'named', name }, property };
97
+ }
98
+ /**
99
+ * Removes the `bind` property, and the options argument with it when nothing else is left and the parameter is
100
+ * optional. A required options object is left as `{}`.
101
+ */
102
+ function removeBind(ctx, call, index, property, callee) {
103
+ const { pos, source } = ctx;
104
+ const args = call.arguments;
105
+ const options = args[index];
106
+ const properties = options.properties;
107
+ const at = properties.indexOf(property);
108
+ if (properties.length > 1) {
109
+ return at < properties.length - 1
110
+ ? { start: pos.start(property), end: pos.start(properties[at + 1]), text: '' }
111
+ : { start: pos.end(properties[at - 1]), end: pos.end(property), text: '' };
112
+ }
113
+ if (!OPTIONAL_OPTIONS.has(callee) || index !== args.length - 1) {
114
+ return { start: pos.start(options), end: pos.end(options), text: '{}' };
115
+ }
116
+ if (index > 0)
117
+ return { start: pos.end(args[index - 1]), end: pos.end(options), text: '' };
118
+ const trailingComma = /^\s*,/.exec(source.slice(pos.end(options)))?.[0].length ?? 0;
119
+ return { start: pos.start(options), end: pos.end(options) + trailingComma, text: '' };
120
+ }
121
+ /**
122
+ * Returns the class whose instance `this` is at `path`, or null when `this` belongs to a function, a static
123
+ * member or no class at all.
124
+ */
125
+ function owningClass(path) {
126
+ for (let current = path.parent; current; current = current.parent) {
127
+ const node = current.node;
128
+ if (FUNCTION_TYPES.has(node.type) || node.type === 'StaticBlock')
129
+ return null;
130
+ if (CLASS_MEMBER_TYPES.has(node.type)) {
131
+ return node.static ? null : (current.parent?.parent?.node ?? null);
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+ function isWriteTarget(path) {
137
+ const parent = path.parent?.node;
138
+ if (!parent)
139
+ return false;
140
+ if (parent.type === 'AssignmentExpression' && parent.left === path.node)
141
+ return true;
142
+ if (parent.type === 'UpdateExpression')
143
+ return true;
144
+ return parent.type === 'UnaryExpression' && parent.operator === 'delete';
145
+ }
146
+ /** Whether a computed key on `this` spells a `$`-prefixed name: `'$count'`, `` `$${name}` `` or `'$' + name`. */
147
+ function isDollarKey(key) {
148
+ if (!isNode(key))
149
+ return false;
150
+ if (key.type === 'StringLiteral')
151
+ return /^\$./.test(key.value);
152
+ if (key.type === 'TemplateLiteral') {
153
+ const [first] = key.quasis;
154
+ return first?.value.raw.startsWith('$') ?? false;
155
+ }
156
+ if (key.type === 'BinaryExpression' && key.operator === '+')
157
+ return isDollarKey(key.left);
158
+ return false;
159
+ }
160
+ /** The value type of a `WritableSignal<T>` annotation on a `@signal` member, or the annotation itself. */
161
+ function signalValueType(member, annotation) {
162
+ if (member.source !== 'signal' || annotation.type !== 'TSTypeReference')
163
+ return annotation;
164
+ const typeName = annotation.typeName;
165
+ const params = annotation.typeParameters?.params;
166
+ const isSignal = typeName.type === 'Identifier' && SIGNAL_TYPES.has(typeName.name);
167
+ return isSignal && params?.length === 1 ? params[0] : annotation;
168
+ }
169
+ function includesUndefined(type) {
170
+ if (type.type === 'TSUndefinedKeyword')
171
+ return true;
172
+ return type.type === 'TSUnionType' && type.types.some((part) => part.type === 'TSUndefinedKeyword');
173
+ }
174
+ function literalType(value) {
175
+ if (!value)
176
+ return undefined;
177
+ if (value.type === 'NumericLiteral')
178
+ return 'number';
179
+ if (value.type === 'UnaryExpression' && value.operator === '-') {
180
+ return value.argument.type === 'NumericLiteral' ? 'number' : undefined;
181
+ }
182
+ if (value.type === 'StringLiteral' || value.type === 'TemplateLiteral')
183
+ return 'string';
184
+ return value.type === 'BooleanLiteral' ? 'boolean' : undefined;
185
+ }
186
+ /**
187
+ * The binding type of a member as source text, from its annotation or a literal initializer, or undefined when
188
+ * it cannot tell. A `@signal` field typed `WritableSignal<T>` binds `T`; an optional field adds `| undefined`.
189
+ */
190
+ function bindingType(ctx, member, field) {
191
+ const annotation = field?.typeAnnotation?.typeAnnotation;
192
+ if (!annotation)
193
+ return literalType((field?.value ?? member.initializer));
194
+ const type = signalValueType(member, annotation);
195
+ const text = ctx.source.slice(ctx.pos.start(type), ctx.pos.end(type));
196
+ if (!field?.optional || includesUndefined(type))
197
+ return text;
198
+ return type.type === 'TSUnionType' || !LOOSE_TYPES.has(type.type) ? `${text} | undefined` : `(${text}) | undefined`;
199
+ }
200
+ /** Collects the keys a binding type argument lists, or null when part of it lies outside this file. */
201
+ function typeArgumentKeys(ctx, type, seen = new Set()) {
202
+ if (type.type === 'TSTypeLiteral' || type.type === 'TSInterfaceBody') {
203
+ const members = (type.members ?? type.body);
204
+ return new Set(members.map(keyName).filter((name) => name !== undefined));
205
+ }
206
+ if (type.type === 'TSIntersectionType') {
207
+ const keys = new Set();
208
+ for (const part of type.types) {
209
+ const partKeys = typeArgumentKeys(ctx, part, seen);
210
+ if (!partKeys)
211
+ return null;
212
+ for (const key of partKeys)
213
+ keys.add(key);
214
+ }
215
+ return keys;
216
+ }
217
+ return referencedTypeKeys(ctx, type, seen);
218
+ }
219
+ /** Collects the keys of a type alias or interface declared in this file and named by `type`. */
220
+ function referencedTypeKeys(ctx, type, seen) {
221
+ const typeName = type.typeName;
222
+ if (type.type !== 'TSTypeReference' || typeName?.type !== 'Identifier' || type.typeParameters)
223
+ return null;
224
+ const name = typeName.name;
225
+ if (seen.has(name))
226
+ return null;
227
+ seen.add(name);
228
+ const { j, root } = ctx;
229
+ const alias = root.find(j.TSTypeAliasDeclaration, { id: { name } });
230
+ if (alias.length === 1)
231
+ return typeArgumentKeys(ctx, alias.get().node.typeAnnotation, seen);
232
+ const declaration = root.find(j.TSInterfaceDeclaration, { id: { name } });
233
+ if (declaration.length !== 1 || declaration.get().node.extends)
234
+ return null;
235
+ return typeArgumentKeys(ctx, declaration.get().node.body, seen);
236
+ }
237
+ function collectClasses(j, root) {
238
+ const classes = new Map();
239
+ for (const path of [...root.find(j.ClassDeclaration).paths(), ...root.find(j.ClassExpression).paths()]) {
240
+ const node = path.node;
241
+ const declared = new Map();
242
+ for (const member of node.body.body) {
243
+ const name = keyName(member);
244
+ if (name !== undefined && !member.static)
245
+ declared.set(name, member);
246
+ }
247
+ classes.set(node, {
248
+ node,
249
+ name: node.id?.name,
250
+ members: new Map(),
251
+ declared,
252
+ rewritten: new Set(),
253
+ overridesAutoBind: declared.has('shouldAutoBindReactiveMembers'),
254
+ });
255
+ }
256
+ return classes;
257
+ }
258
+ function classByName(ctx, name) {
259
+ return [...ctx.classes.values()].find((info) => info.name === name);
260
+ }
261
+ /** The chain of this class and its bases declared in this file, nearest first. */
262
+ function chain(ctx, info) {
263
+ const result = [info];
264
+ let base = info.node.superClass;
265
+ while (base?.type === 'Identifier') {
266
+ const parent = classByName(ctx, base.name);
267
+ if (!parent || result.includes(parent))
268
+ break;
269
+ result.push(parent);
270
+ base = parent.node.superClass;
271
+ }
272
+ return result;
273
+ }
274
+ function declaredInChain(ctx, info, name) {
275
+ return chain(ctx, info)
276
+ .map((owner) => owner.declared.get(name))
277
+ .find((node) => node !== undefined);
278
+ }
279
+ /** Whether members with `bind` omitted had a companion: yes, no, or undefined when the base is elsewhere. */
280
+ function autoBinds(ctx, info) {
281
+ for (const owner of chain(ctx, info)) {
282
+ if (owner.overridesAutoBind)
283
+ return undefined;
284
+ const base = owner.node.superClass;
285
+ if (!base)
286
+ return false;
287
+ if (base.type !== 'Identifier')
288
+ return undefined;
289
+ const imported = ctx.radiant.get(base.name);
290
+ if (imported)
291
+ return AUTO_BIND_BASES.has(imported) ? true : undefined;
292
+ }
293
+ return undefined;
294
+ }
295
+ /** Resolves `Class.prototype, 'name'` arguments to the class in this file and the member name. */
296
+ function prototypeTarget(ctx, args) {
297
+ const [target, key] = args;
298
+ const name = stringValue(key);
299
+ if (!isNode(target) || target.type !== 'MemberExpression' || name === undefined)
300
+ return undefined;
301
+ const object = target.object;
302
+ if (object.type !== 'Identifier' || target.property.name !== 'prototype')
303
+ return undefined;
304
+ const owner = classByName(ctx, object.name);
305
+ return owner ? { owner, name } : undefined;
306
+ }
307
+ /**
308
+ * Records the member a `bind`-carrying call declares and removes its `bind`, or reports a `bind` it cannot
309
+ * read or a custom name on a member it cannot place.
310
+ */
311
+ function handleOptions(ctx, call, index, callee, target, initializer) {
312
+ const { bind, property } = readBind(call.arguments[index]);
313
+ if (target) {
314
+ const line = lineOf(call) ?? 0;
315
+ target.owner.members.set(target.name, { name: target.name, bind, source: callee, initializer, line });
316
+ }
317
+ if (!property)
318
+ return;
319
+ if (bind.kind === 'unknown') {
320
+ ctx.report(property, `${callee} has a bind option this codemod cannot read; remove it and read the member through this.$.`);
321
+ return;
322
+ }
323
+ if (bind.kind === 'named' && bind.name !== '' && !target) {
324
+ ctx.report(property, `${callee} has bind: '${bind.name}' on a member this codemod cannot place; remove it and read the member through this.$.`);
325
+ return;
326
+ }
327
+ ctx.edits.push(removeBind(ctx, call, index, property, callee));
328
+ }
329
+ /** Reads the reactive members a class declares with decorators on its fields. */
330
+ function collectDecoratedMembers(ctx, owner) {
331
+ for (const field of owner.declared.values()) {
332
+ const name = keyName(field);
333
+ for (const decorator of (field.decorators ?? [])) {
334
+ const expression = decorator.expression;
335
+ const callee = expression.type === 'CallExpression' ? expression.callee : expression;
336
+ const imported = callee.type === 'Identifier' ? ctx.radiant.get(callee.name) : undefined;
337
+ if (!imported)
338
+ continue;
339
+ if (expression === callee && BARE_DECORATORS.has(imported)) {
340
+ owner.members.set(name, { name, bind: { kind: 'auto' }, source: imported, line: lineOf(field) ?? 0 });
341
+ }
342
+ else if (expression !== callee && OPTION_FACTORIES.has(imported)) {
343
+ handleOptions(ctx, expression, 0, imported, { owner, name });
344
+ }
345
+ }
346
+ }
347
+ }
348
+ /**
349
+ * Reads a decorator applied by a call, as `state(Class.prototype, 'name')` or
350
+ * `signal({ ... })(Class.prototype, 'name')`, and any other call of an options factory.
351
+ */
352
+ function collectFactoryCall(ctx, path, call, imported) {
353
+ const bare = BARE_DECORATORS.has(imported) ? prototypeTarget(ctx, call.arguments) : undefined;
354
+ if (bare) {
355
+ const line = lineOf(call) ?? 0;
356
+ bare.owner.members.set(bare.name, { name: bare.name, bind: { kind: 'auto' }, source: imported, line });
357
+ return;
358
+ }
359
+ if (!OPTION_FACTORIES.has(imported))
360
+ return;
361
+ const outer = path.parent.node;
362
+ const applied = outer.type === 'CallExpression' && outer.callee === call;
363
+ handleOptions(ctx, call, 0, imported, applied ? prototypeTarget(ctx, outer.arguments) : undefined);
364
+ }
365
+ /** Reads a `createReactiveProp` or `createReactiveField` call; only one on `this` belongs to a class. */
366
+ function collectHelperCall(ctx, path, call, method) {
367
+ const callee = call.callee;
368
+ const args = call.arguments;
369
+ const owner = callee.object.type === 'ThisExpression'
370
+ ? ctx.classes.get(owningClass(path))
371
+ : undefined;
372
+ const name = stringValue(args[0]);
373
+ const target = owner && name !== undefined ? { owner, name } : undefined;
374
+ handleOptions(ctx, call, MEMBER_HELPERS[method], method, target, method === 'createReactiveField' ? args[1] : undefined);
375
+ }
376
+ function collectMembers(ctx) {
377
+ for (const owner of ctx.classes.values())
378
+ collectDecoratedMembers(ctx, owner);
379
+ ctx.root.find(ctx.j.CallExpression).forEach((path) => {
380
+ const call = path.node;
381
+ const callee = call.callee;
382
+ if (callee.type === 'Identifier') {
383
+ const imported = ctx.radiant.get(callee.name);
384
+ if (imported)
385
+ collectFactoryCall(ctx, path, call, imported);
386
+ return;
387
+ }
388
+ const property = callee.property;
389
+ const method = callee.type === 'MemberExpression' && !callee.computed ? property?.name : undefined;
390
+ if (method && Object.hasOwn(MEMBER_HELPERS, method))
391
+ collectHelperCall(ctx, path, call, method);
392
+ });
393
+ }
394
+ function resolveBind(bind, auto) {
395
+ if (bind.kind !== 'auto')
396
+ return bind;
397
+ if (auto === undefined)
398
+ return { kind: 'unknown' };
399
+ return auto ? { kind: 'named', name: '' } : { kind: 'none' };
400
+ }
401
+ /** Maps each companion name readable in a class to its member, as 0.9.0 created them. */
402
+ function companionsOf(ctx, info) {
403
+ const result = new Map();
404
+ for (const owner of chain(ctx, info).reverse()) {
405
+ const auto = autoBinds(ctx, owner);
406
+ for (const member of owner.members.values()) {
407
+ const bind = resolveBind(member.bind, auto);
408
+ const custom = bind.kind === 'named' && bind.name !== '';
409
+ const name = custom ? bind.name : `$${member.name}`;
410
+ if (bind.kind === 'none')
411
+ result.set(name, 'none');
412
+ else
413
+ result.set(name, bind.kind === 'unknown' ? null : { member, owner });
414
+ }
415
+ }
416
+ return result;
417
+ }
418
+ /**
419
+ * Reports a `$name` read in a Radiant file whose class inherits from outside the file, where a base member's
420
+ * companion may be what it reads.
421
+ */
422
+ function reportForeignRead(ctx, property, info, name) {
423
+ if (!/^\$./.test(name) || ctx.radiant.size === 0 || autoBinds(ctx, info) !== undefined)
424
+ return;
425
+ ctx.report(property, `reads ${name} in a class whose base is outside this file; if it is a companion binding of a base member, read it as this.$.name.`);
426
+ }
427
+ /** Rewrites or reports a read of `this.<name>` inside the class `info`. */
428
+ function migrateRead(ctx, path, info, name) {
429
+ const property = path.node.property;
430
+ const companion = ctx.companions.get(info)?.get(name);
431
+ const own = declaredInChain(ctx, info, name);
432
+ if (companion === undefined) {
433
+ if (!own)
434
+ reportForeignRead(ctx, property, info, name);
435
+ return;
436
+ }
437
+ if (own && !own.declare) {
438
+ if (own.type === 'ClassProperty' && !own.value && companion !== null && companion !== 'none') {
439
+ ctx.report(property, `reads ${name}, which the class also declares as a field; remove the field and read the member through this.$.`);
440
+ }
441
+ return;
442
+ }
443
+ if (companion === 'none') {
444
+ ctx.report(property, `reads ${name}, but the member had no companion binding, so this read undefined; if it meant the binding, read it as this.$.${name.slice(1)}.`);
445
+ return;
446
+ }
447
+ if (companion === null) {
448
+ ctx.report(property, `reads ${name}, but this codemod cannot tell whether the member had a companion binding; if it did, read it through this.$.`);
449
+ return;
450
+ }
451
+ if (isWriteTarget(path)) {
452
+ ctx.report(property, `writes ${name}, a companion binding that Radiant 0.10.0 removed; companion bindings were read-only.`);
453
+ return;
454
+ }
455
+ ctx.edits.push({ start: ctx.pos.start(property), end: ctx.pos.end(property), text: `$.${companion.member.name}` });
456
+ info.rewritten.add(companion.member.name);
457
+ }
458
+ /** Rewrites companion reads on `this` and reports the member accesses this codemod cannot migrate. */
459
+ function migrateMemberAccess(ctx, fileCompanions) {
460
+ ctx.root.find(ctx.j.MemberExpression).forEach((path) => {
461
+ const node = path.node;
462
+ const object = node.object;
463
+ const property = node.property;
464
+ if (node.computed) {
465
+ if (object.type === 'ThisExpression' && isDollarKey(property)) {
466
+ ctx.report(node, 'reads a $-prefixed member through a computed key, which this codemod cannot follow; a companion binding is now read as this.$.name.');
467
+ }
468
+ return;
469
+ }
470
+ if (property.type !== 'Identifier')
471
+ return;
472
+ const name = property.name;
473
+ if (REMOVED_HOST_METHODS.has(name)) {
474
+ ctx.report(node, `uses ${name}, which Radiant 0.10.0 removed; reactive members are read through this.$.`);
475
+ return;
476
+ }
477
+ const info = object.type === 'ThisExpression' ? ctx.classes.get(owningClass(path)) : undefined;
478
+ if (info) {
479
+ migrateRead(ctx, path, info, name);
480
+ }
481
+ else if (fileCompanions.has(name)) {
482
+ ctx.report(node, `reads ${name} outside the class that declares it; read the member through the binding namespace, as element.$.name.`);
483
+ }
484
+ });
485
+ }
486
+ function reportDestructuring(ctx) {
487
+ ctx.root.find(ctx.j.VariableDeclarator, { init: { type: 'ThisExpression' } }).forEach((path) => {
488
+ const id = path.node.id;
489
+ const info = ctx.classes.get(owningClass(path));
490
+ if (id.type !== 'ObjectPattern' || !info)
491
+ return;
492
+ for (const property of id.properties) {
493
+ const name = keyName(property);
494
+ const companion = name === undefined ? undefined : ctx.companions.get(info)?.get(name);
495
+ if (companion !== undefined && companion !== 'none') {
496
+ ctx.report(property, `destructures ${name} from this; destructure the member from this.$ instead.`);
497
+ }
498
+ }
499
+ });
500
+ }
501
+ /** Adds the signatures to the type argument after `base`, creating it, extending its literal or intersecting it. */
502
+ function typeArgumentEdit(ctx, base, existing, signatures) {
503
+ const { pos, source } = ctx;
504
+ const literal = `{ ${signatures.join('; ')} }`;
505
+ if (!existing)
506
+ return { start: pos.end(base), end: pos.end(base), text: `<${literal}>` };
507
+ if (existing.type !== 'TSTypeLiteral') {
508
+ const text = source.slice(pos.start(existing), pos.end(existing));
509
+ const operand = LOOSE_TYPES.has(existing.type) ? `(${text})` : text;
510
+ return { start: pos.start(existing), end: pos.end(existing), text: `${operand} & ${literal}` };
511
+ }
512
+ const last = existing.members.at(-1);
513
+ if (!last)
514
+ return { start: pos.start(existing), end: pos.end(existing), text: literal };
515
+ const separated = /[;,]$/.test(source.slice(pos.start(last), pos.end(last)));
516
+ if (existing.loc?.start.line === existing.loc?.end.line) {
517
+ const added = signatures.join('; ');
518
+ return { start: pos.end(last), end: pos.end(last), text: separated ? ` ${added};` : `; ${added}` };
519
+ }
520
+ const lineStart = source.lastIndexOf('\n', pos.start(last) - 1) + 1;
521
+ const indent = /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? '';
522
+ const lineTerminator = source.includes('\r\n') ? '\r\n' : '\n';
523
+ const added = signatures.map((signature) => `${lineTerminator}${indent}${signature};`).join('');
524
+ return { start: pos.end(last), end: pos.end(last), text: `${separated ? '' : ';'}${added}` };
525
+ }
526
+ /** Adds each rewritten member to the binding type argument of the class's `extends`. */
527
+ function addBindingTypes(ctx, info) {
528
+ if (info.rewritten.size === 0 || !/\.[cm]?tsx?$/.test(ctx.filePath))
529
+ return;
530
+ const base = info.node.superClass;
531
+ const imported = base?.type === 'Identifier' ? ctx.radiant.get(base.name) : undefined;
532
+ if (!base || !imported || !GENERIC_BASES.has(imported)) {
533
+ const reads = [...info.rewritten].map((name) => `this.$.${name}`).join(', ');
534
+ ctx.report(info.node, `reads ${reads} in a class that does not extend RadiantElement or RadiantController directly; type those bindings on the class that does.`);
535
+ return;
536
+ }
537
+ const existing = info.node.superTypeParameters?.params?.[0];
538
+ const keys = existing ? typeArgumentKeys(ctx, existing) : new Set();
539
+ const members = [...info.rewritten]
540
+ .filter((name) => !keys?.has(name))
541
+ .map((name) => chain(ctx, info)
542
+ .map((owner) => owner.members.get(name))
543
+ .find(Boolean))
544
+ .sort((a, b) => a.line - b.line);
545
+ const signatures = [];
546
+ for (const member of members) {
547
+ const field = declaredInChain(ctx, info, member.name);
548
+ const type = bindingType(ctx, member, field);
549
+ if (type) {
550
+ signatures.push(`${member.name}: ${type}`);
551
+ }
552
+ else {
553
+ ctx.report(field ?? member.line, `cannot tell the type of ${member.name}; add ${member.name} with its type to the ${imported} type argument by hand.`);
554
+ }
555
+ }
556
+ if (signatures.length > 0)
557
+ ctx.edits.push(typeArgumentEdit(ctx, base, existing, signatures));
558
+ }
559
+ /** Reports overrides of the removed host methods and removes the `declare` fields that typed a companion. */
560
+ function finishClass(ctx, info) {
561
+ for (const name of REMOVED_HOST_METHODS) {
562
+ const member = info.declared.get(name);
563
+ if (member)
564
+ ctx.report(member, `overrides ${name}, which Radiant 0.10.0 removed; remove the override.`);
565
+ }
566
+ for (const [name, companion] of ctx.companions.get(info) ?? []) {
567
+ const own = info.declared.get(name);
568
+ if (companion && companion !== 'none' && own?.declare)
569
+ ctx.edits.push(removeNode(ctx.source, ctx.pos, own));
570
+ }
571
+ addBindingTypes(ctx, info);
572
+ }
573
+ function reportBindingOptionImports(ctx) {
574
+ ctx.root
575
+ .find(ctx.j.ImportSpecifier, { imported: { name: 'ReactiveBindingOption' } })
576
+ .filter((path) => RADIANT_SOURCE.test(String(path.parent.node.source.value)))
577
+ .forEach((path) => ctx.report(path.node, 'imports ReactiveBindingOption, which Radiant 0.10.0 removed; drop the import and the bind option it typed.'));
578
+ }
579
+ export default function transform(file, api, _options) {
580
+ const j = api.jscodeshift;
581
+ const root = j(file.source, parseOptions());
582
+ const messages = [];
583
+ const ctx = {
584
+ j,
585
+ root,
586
+ source: file.source,
587
+ filePath: file.path,
588
+ pos: offsetsOf(file.source),
589
+ radiant: readRadiantImports(j, root),
590
+ classes: collectClasses(j, root),
591
+ companions: new Map(),
592
+ edits: [],
593
+ report: (at, text) => messages.push({ line: typeof at === 'number' ? at : lineOf(at), text }),
594
+ };
595
+ collectMembers(ctx);
596
+ const fileCompanions = new Set();
597
+ for (const info of ctx.classes.values()) {
598
+ const companions = companionsOf(ctx, info);
599
+ ctx.companions.set(info, companions);
600
+ for (const [name, companion] of companions)
601
+ if (companion && companion !== 'none')
602
+ fileCompanions.add(name);
603
+ }
604
+ migrateMemberAccess(ctx, fileCompanions);
605
+ reportDestructuring(ctx);
606
+ for (const info of ctx.classes.values())
607
+ finishClass(ctx, info);
608
+ reportBindingOptionImports(ctx);
609
+ messages
610
+ .sort((a, b) => (a.line ?? 0) - (b.line ?? 0))
611
+ .forEach(({ line, text }) => api.report(`${TRANSFORM}: ${file.path}:${line ?? '?'}: ${text}`));
612
+ return ctx.edits.length > 0 ? applyEdits(file.source, ctx.edits) : null;
613
+ }