|
| 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 | +const DOTFILES_OPTION = "dotfiles: 'allow' /* Express 5: preserve v4 behavior */" |
| 5 | + |
| 6 | +async function transform(root: SgRoot<Js>): Promise<string | null> { |
| 7 | + const rootNode = root.root() |
| 8 | + const edits: Edit[] = [] |
| 9 | + |
| 10 | + const nodes = rootNode.findAll({ |
| 11 | + rule: { |
| 12 | + any: [{ pattern: '$CALL.static($PATH)' }, { pattern: '$CALL.static($PATH, $OPTS)' }], |
| 13 | + }, |
| 14 | + }) |
| 15 | + |
| 16 | + if (!nodes.length) return null |
| 17 | + |
| 18 | + for (const call of nodes) { |
| 19 | + const target = call.getMatch('CALL') |
| 20 | + const pathArg = call.getMatch('PATH') |
| 21 | + const optsArg = call.getMatch('OPTS') |
| 22 | + |
| 23 | + if (!target || !pathArg) continue |
| 24 | + |
| 25 | + if (!isExpressBinding(target)) continue |
| 26 | + |
| 27 | + if (!optsArg) { |
| 28 | + edits.push(call.replace(`${target.text()}.static(${pathArg.text()}, { ${DOTFILES_OPTION} })`)) |
| 29 | + continue |
| 30 | + } |
| 31 | + |
| 32 | + const result = transformOptions(optsArg) |
| 33 | + // Skip anything that isn't an object literal (e.g. a variable reference); |
| 34 | + // we can't safely rewrite options we can't see. |
| 35 | + if (!result) continue |
| 36 | + |
| 37 | + let newOpts = result.text |
| 38 | + if (!result.hasDotfiles) { |
| 39 | + newOpts = addDotfilesOption(newOpts) |
| 40 | + } |
| 41 | + |
| 42 | + const originalOpts = optsArg.text() |
| 43 | + if (newOpts === originalOpts) continue |
| 44 | + |
| 45 | + edits.push(call.replace(call.text().replace(originalOpts, newOpts))) |
| 46 | + } |
| 47 | + |
| 48 | + if (!edits.length) return null |
| 49 | + |
| 50 | + return rootNode.commitEdits(edits) |
| 51 | +} |
| 52 | + |
| 53 | +interface TransformedOptions { |
| 54 | + text: string |
| 55 | + // True when the resulting object already carries a `dotfiles` key (either |
| 56 | + // present originally or produced by renaming a removed `hidden` option), so |
| 57 | + // the default `dotfiles: 'allow'` should NOT be appended. |
| 58 | + hasDotfiles: boolean |
| 59 | +} |
| 60 | + |
| 61 | +// Rewrites the options object for Express 5: |
| 62 | +// - renames the removed `hidden` option to `dotfiles` (true -> 'allow', false -> 'ignore') |
| 63 | +// - renames the removed `from` option to `root` |
| 64 | +// Returns null when the argument isn't an object literal. |
| 65 | +function transformOptions(optsArg: SgNode<Js>): TransformedOptions | null { |
| 66 | + if (!optsArg.is('object')) return null |
| 67 | + |
| 68 | + const edits: Edit[] = [] |
| 69 | + const pairs = optsArg.children().filter((pair: SgNode<Js>) => pair.is('pair')) |
| 70 | + |
| 71 | + // An explicit `dotfiles` key always wins: we never append a default and never |
| 72 | + // rename a `hidden` onto it (which would produce a duplicate `dotfiles` key). |
| 73 | + const hasExplicitDotfiles = pairs.some((pair) => getOptionKeyName(pair) === 'dotfiles') |
| 74 | + |
| 75 | + // A present `hidden` (even non-literal) maps onto `dotfiles`, so a default |
| 76 | + // must not be appended even when we can't rewrite its value. |
| 77 | + let hasDotfiles = hasExplicitDotfiles |
| 78 | + |
| 79 | + for (const pair of pairs) { |
| 80 | + const keyName = getOptionKeyName(pair) |
| 81 | + |
| 82 | + if (keyName === 'hidden') { |
| 83 | + hasDotfiles = true |
| 84 | + |
| 85 | + if (hasExplicitDotfiles) continue |
| 86 | + |
| 87 | + const valueNode = pair.field('value') |
| 88 | + const mapped = valueNode ? mapHiddenValue(valueNode.text()) : null |
| 89 | + if (mapped) edits.push(pair.replace(`dotfiles: ${mapped}`)) |
| 90 | + continue |
| 91 | + } |
| 92 | + |
| 93 | + if (keyName === 'from') { |
| 94 | + const keyNode = pair.field('key') |
| 95 | + if (keyNode) edits.push(keyNode.replace('root')) |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + const text = edits.length ? optsArg.commitEdits(edits) : optsArg.text() |
| 100 | + return { text, hasDotfiles } |
| 101 | +} |
| 102 | + |
| 103 | +function getOptionKeyName(pair: SgNode<Js>): string | null { |
| 104 | + const keyNode = pair.field('key') |
| 105 | + if (!keyNode) return null |
| 106 | + |
| 107 | + return keyNode.is('string') ? getStringLiteralValue(keyNode) : keyNode.text() |
| 108 | +} |
| 109 | + |
| 110 | +function mapHiddenValue(valueText: string): string | null { |
| 111 | + const trimmed = valueText.trim() |
| 112 | + if (trimmed === 'true') return "'allow'" |
| 113 | + if (trimmed === 'false') return "'ignore'" |
| 114 | + |
| 115 | + return null |
| 116 | +} |
| 117 | + |
| 118 | +function getStringLiteralValue(node: SgNode<Js> | null | undefined): string | null { |
| 119 | + if (!node || !node.is('string')) return null |
| 120 | + |
| 121 | + const text = node.text() |
| 122 | + if (text.length < 2) return null |
| 123 | + |
| 124 | + return text.slice(1, -1) |
| 125 | +} |
| 126 | + |
| 127 | +function addDotfilesOption(optsText: string): string { |
| 128 | + const trimmed = optsText.trimEnd() |
| 129 | + |
| 130 | + if (!trimmed.includes('\n')) { |
| 131 | + const inner = trimmed.slice(1, -1).trim() |
| 132 | + |
| 133 | + return inner ? `{ ${inner}, ${DOTFILES_OPTION} }` : `{ ${DOTFILES_OPTION} }` |
| 134 | + } |
| 135 | + |
| 136 | + const closingBraceIndex = trimmed.lastIndexOf('}') |
| 137 | + const body = trimmed.slice(0, closingBraceIndex).trimEnd() |
| 138 | + const closingIndent = getIndentAfterLastNewline(trimmed) |
| 139 | + const propertyIndent = getIndentAfterLastNewline(body) || ' ' |
| 140 | + |
| 141 | + return `${body}\n${propertyIndent}${DOTFILES_OPTION}\n${closingIndent}}` |
| 142 | +} |
| 143 | + |
| 144 | +function isExpressBinding(binding: SgNode<Js>): boolean { |
| 145 | + if (binding.is('call_expression')) { |
| 146 | + return isExpressRequireCall(binding) |
| 147 | + } |
| 148 | + |
| 149 | + const definition = binding.definition({ resolveExternal: false }) |
| 150 | + if (!definition) return false |
| 151 | + |
| 152 | + return isExpressDefinition(definition.node) |
| 153 | +} |
| 154 | + |
| 155 | +function isExpressDefinition(node: SgNode<Js>): boolean { |
| 156 | + const importStatement = findAncestorOrSelf(node, 'import_statement') |
| 157 | + if (importStatement) { |
| 158 | + return isExpressImport(importStatement) |
| 159 | + } |
| 160 | + |
| 161 | + const declarator = findAncestorOrSelf(node, 'variable_declarator') |
| 162 | + if (declarator) { |
| 163 | + return isExpressRequireDeclarator(declarator) |
| 164 | + } |
| 165 | + |
| 166 | + return false |
| 167 | +} |
| 168 | + |
| 169 | +function isExpressImport(importStatement: SgNode<Js>): boolean { |
| 170 | + const source = importStatement.field('source') |
| 171 | + return getStringLiteralValue(source) === 'express' |
| 172 | +} |
| 173 | + |
| 174 | +function isExpressRequireDeclarator(declarator: SgNode<Js>): boolean { |
| 175 | + if (!declarator.is('variable_declarator')) return false |
| 176 | + |
| 177 | + const value = declarator.field('value') |
| 178 | + if (!value?.is('call_expression')) return false |
| 179 | + |
| 180 | + return isExpressRequireCall(value) |
| 181 | +} |
| 182 | + |
| 183 | +function isExpressRequireCall(node: SgNode<Js>): boolean { |
| 184 | + const callFunction = node.field('function') |
| 185 | + if (!callFunction?.is('identifier') || callFunction.text() !== 'require') return false |
| 186 | + |
| 187 | + const args = node.field('arguments') |
| 188 | + if (!args) return false |
| 189 | + |
| 190 | + const expressSource = args.children().find((child) => child.is('string')) |
| 191 | + return getStringLiteralValue(expressSource) === 'express' |
| 192 | +} |
| 193 | + |
| 194 | +function findAncestorOrSelf(node: SgNode<Js>, kind: string): SgNode<Js> | null { |
| 195 | + let current: SgNode<Js> | null = node |
| 196 | + |
| 197 | + while (current) { |
| 198 | + // Assign to a typed boolean so `is()`'s type predicate doesn't narrow |
| 199 | + // `current` to `never` on the following line. |
| 200 | + const matches: boolean = current.is(kind) |
| 201 | + if (matches) return current |
| 202 | + |
| 203 | + current = current.parent() |
| 204 | + } |
| 205 | + |
| 206 | + return null |
| 207 | +} |
| 208 | + |
| 209 | +function getIndentAfterLastNewline(text: string): string { |
| 210 | + const newlineIndex = text.lastIndexOf('\n') |
| 211 | + if (newlineIndex === -1) return '' |
| 212 | + |
| 213 | + let indent = '' |
| 214 | + for (let index = newlineIndex + 1; index < text.length; index++) { |
| 215 | + const char = text[index] |
| 216 | + if (char !== ' ' && char !== '\t') break |
| 217 | + indent += char |
| 218 | + } |
| 219 | + |
| 220 | + return indent |
| 221 | +} |
| 222 | + |
| 223 | +export default transform |
0 commit comments