|
| 1 | +import type Js from '@codemod.com/jssg-types/src/langs/javascript' |
| 2 | +import type { Edit, SgNode, SgRoot } from '@codemod.com/jssg-types/src/main' |
| 3 | + |
| 4 | +function getStringLiteralValue(node: SgNode<Js>): string | null { |
| 5 | + if (!node.is('string')) return null |
| 6 | + |
| 7 | + const fragments = node.findAll({ rule: { kind: 'string_fragment' } }) |
| 8 | + if (fragments.length !== 1) return null |
| 9 | + return fragments[0]?.text() ?? null |
| 10 | +} |
| 11 | + |
| 12 | +function findParentFunctionParameters(node: SgNode<Js>): SgNode<Js, 'formal_parameters'> | null { |
| 13 | + let parent = node.parent() |
| 14 | + while (parent) { |
| 15 | + if (parent.is('formal_parameters')) return parent |
| 16 | + parent = parent.parent() |
| 17 | + } |
| 18 | + return null |
| 19 | +} |
| 20 | + |
| 21 | +async function transform(root: SgRoot<Js>): Promise<string | null> { |
| 22 | + const rootNode = root.root() |
| 23 | + |
| 24 | + const nodes = rootNode.findAll({ |
| 25 | + rule: { |
| 26 | + pattern: '$OBJ.$METHOD($ARG)', |
| 27 | + }, |
| 28 | + constraints: { |
| 29 | + METHOD: { regex: '^(redirect|location)$' }, |
| 30 | + ARG: { pattern: { context: "'back'", strictness: 'relaxed' } }, |
| 31 | + }, |
| 32 | + }) |
| 33 | + |
| 34 | + const edits: Edit[] = [] |
| 35 | + |
| 36 | + for (const call of nodes) { |
| 37 | + const arg = call.getMatch('ARG') |
| 38 | + const obj = call.getMatch('OBJ') |
| 39 | + if (!arg || !obj) continue |
| 40 | + |
| 41 | + if (getStringLiteralValue(arg) !== 'back') continue |
| 42 | + |
| 43 | + const objDef = obj.definition({ resolveExternal: false }) |
| 44 | + if (!objDef) continue |
| 45 | + |
| 46 | + const isParameter = objDef.node.matches({ |
| 47 | + rule: { inside: { kind: 'formal_parameters', stopBy: 'end' } }, |
| 48 | + }) |
| 49 | + if (!isParameter) continue |
| 50 | + |
| 51 | + const parameters = findParentFunctionParameters(objDef.node) |
| 52 | + if (!parameters) continue |
| 53 | + |
| 54 | + const firstParameter = parameters.find({ rule: { kind: 'identifier' } }) |
| 55 | + if (!firstParameter) continue |
| 56 | + |
| 57 | + const requestName = firstParameter.text() |
| 58 | + |
| 59 | + edits.push(arg.replace(`${requestName}.get("Referrer") || "/"`)) |
| 60 | + } |
| 61 | + |
| 62 | + if (edits.length === 0) return null |
| 63 | + return rootNode.commitEdits(edits) |
| 64 | +} |
| 65 | + |
| 66 | +export default transform |
0 commit comments