The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { ImportDeclaration, Program } from "@oxc-project/types"; |
| 2 | import picomatch from "picomatch"; |
| 3 | import type * as rolldown from "rolldown"; |
| 4 | |
| 5 | /** |
| 6 | * `rolldown` and `rolldown/parseAst` load `@rolldown/binding-*` at module |
| 7 | * scope, so they are imported lazily on first use (#562). |
| 8 | */ |
| 9 | const loadRolldown = () => import("rolldown"); |
| 10 | const loadParseAst = () => import("rolldown/parseAst"); |
| 11 | |
| 12 | /** |
| 13 | * Packages whose namespace imports are rewritten by default. Their root |
| 14 | * modules re-export every service (`export * as Lambda from "./Lambda/index.ts"`), |
| 15 | * and every one of them declares `"sideEffects": false`. |
| 16 | */ |
| 17 | export const DEFAULT_NAMESPACE_IMPORT_PACKAGES: ReadonlyArray<string> = [ |
| 18 | "alchemy", |
| 19 | "@alchemy.run/*", |
| 20 | ]; |
| 21 | |
| 22 | /** |
| 23 | * Options for {@link namespaceImportPlugin}. |
| 24 | */ |
| 25 | export interface NamespaceImportPluginOptions { |
| 26 | /** |
| 27 | * Extra package names or globs whose namespace imports are rewritten, in |
| 28 | * addition to {@link DEFAULT_NAMESPACE_IMPORT_PACKAGES}. Matched with |
| 29 | * picomatch against the package name of the import specifier. Only list |
| 30 | * packages that declare `"sideEffects": false`. |
| 31 | */ |
| 32 | readonly packages?: ReadonlyArray<string>; |
| 33 | } |
| 34 | |
| 35 | const SUPPORTED_FILE_RE = /\.(?:m?[jt]sx?|cjs|cts)$/; |
| 36 | |
| 37 | /** |
| 38 | * Rolldown plugin that rewrites namespace imports of barrel packages into |
| 39 | * named imports, so `experimental.lazyBarrel` only compiles the re-exports |
| 40 | * a module actually uses. |
| 41 | * |
| 42 | * ```ts |
| 43 | * import * as AWS from "@alchemy.run/aws"; |
| 44 | * AWS.Lambda.Function; |
| 45 | * // becomes |
| 46 | * import { Lambda as AWS$Lambda } from "@alchemy.run/aws"; |
| 47 | * AWS$Lambda.Function; |
| 48 | * ``` |
| 49 | * |
| 50 | * Rolldown loads every export of a barrel imported with `import * as ns`, |
| 51 | * even when only `ns.X` is read, so without this rewrite one |
| 52 | * `import * as AWS from "@alchemy.run/aws"` parses every AWS service. |
| 53 | * |
| 54 | * A namespace is only rewritten when every reference to its name is a |
| 55 | * static member access (`ns.X`, or `ns.X` in a type). Anything else — |
| 56 | * passing the namespace around, computed access, a shadowing binding, |
| 57 | * JSX — leaves the import untouched. |
| 58 | */ |
| 59 | export const namespaceImportPlugin = ( |
| 60 | options: NamespaceImportPluginOptions = {}, |
| 61 | ): rolldown.Plugin => { |
| 62 | const isMatch = picomatch([...DEFAULT_NAMESPACE_IMPORT_PACKAGES, ...(options.packages ?? [])]); |
| 63 | const matchesSpecifier = (specifier: string) => { |
| 64 | const name = packageNameOf(specifier); |
| 65 | return name !== null && isMatch(name); |
| 66 | }; |
| 67 | |
| 68 | return { |
| 69 | name: "alchemy:namespace-imports", |
| 70 | transform: { |
| 71 | filter: { id: SUPPORTED_FILE_RE, code: /import\s*\*\s*as\s/ }, |
| 72 | async handler(code, id, meta) { |
| 73 | const edits = await collectNamespaceImportEdits(code, id, matchesSpecifier); |
| 74 | if (edits.length === 0) return null; |
| 75 | const s = meta.magicString ?? new (await loadRolldown()).RolldownMagicString(code); |
| 76 | for (const edit of edits) s.overwrite(edit.start, edit.end, edit.text); |
| 77 | return { code: s }; |
| 78 | }, |
| 79 | }, |
| 80 | }; |
| 81 | }; |
| 82 | |
| 83 | /** A source replacement over `[start, end)`. */ |
| 84 | export interface NamespaceImportEdit { |
| 85 | readonly start: number; |
| 86 | readonly end: number; |
| 87 | readonly text: string; |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Returns the edits that rewrite each eligible namespace import in `code` |
| 92 | * (see {@link namespaceImportPlugin}), or an empty array when nothing is |
| 93 | * rewritten. |
| 94 | */ |
| 95 | export async function collectNamespaceImportEdits( |
| 96 | code: string, |
| 97 | filename: string, |
| 98 | matchesSpecifier: (specifier: string) => boolean, |
| 99 | ): Promise<NamespaceImportEdit[]> { |
| 100 | const { parseAst } = await loadParseAst(); |
| 101 | let program: Program; |
| 102 | try { |
| 103 | program = parseAst(code, { sourceType: "module", lang: langOf(filename) }, filename); |
| 104 | } catch { |
| 105 | return []; |
| 106 | } |
| 107 | |
| 108 | const candidates = new Map<string, ImportDeclaration>(); |
| 109 | for (const statement of program.body) { |
| 110 | if (statement.type !== "ImportDeclaration") continue; |
| 111 | if (statement.importKind === "type" || statement.phase) continue; |
| 112 | if (statement.attributes.length > 0) continue; |
| 113 | const [specifier, ...rest] = statement.specifiers; |
| 114 | if (specifier?.type !== "ImportNamespaceSpecifier" || rest.length > 0) continue; |
| 115 | if (!matchesSpecifier(statement.source.value)) continue; |
| 116 | // Two imports binding the same name is a syntax error; skip defensively. |
| 117 | if (candidates.has(specifier.local.name)) { |
| 118 | candidates.delete(specifier.local.name); |
| 119 | continue; |
| 120 | } |
| 121 | candidates.set(specifier.local.name, statement); |
| 122 | } |
| 123 | if (candidates.size === 0) return []; |
| 124 | |
| 125 | interface Usage { |
| 126 | /** Identifier nodes with the namespace's name, wherever they appear. */ |
| 127 | identifiers: number; |
| 128 | /** Rewritable member accesses: `[start, end, member, isType]`. */ |
| 129 | members: Array<readonly [number, number, string, boolean]>; |
| 130 | /** A reference that can't be rewritten (JSX). */ |
| 131 | blocked: boolean; |
| 132 | } |
| 133 | const usages = new Map<string, Usage>( |
| 134 | [...candidates.keys()].map((name) => [name, { identifiers: 0, members: [], blocked: false }]), |
| 135 | ); |
| 136 | |
| 137 | // `inType` is set once the walk enters a type: everything below it is |
| 138 | // erased by the TypeScript transform, so its members import as `type`. |
| 139 | const visit = (node: unknown, inType: boolean): void => { |
| 140 | if (Array.isArray(node)) { |
| 141 | for (const child of node) visit(child, inType); |
| 142 | return; |
| 143 | } |
| 144 | if (node === null || typeof node !== "object") return; |
| 145 | const n = node as { type?: unknown } & Record<string, unknown>; |
| 146 | const type = n.type as string; |
| 147 | if (type === "Identifier" || type === "JSXIdentifier") { |
| 148 | const usage = usages.get(n.name as string); |
| 149 | if (usage) { |
| 150 | usage.identifiers++; |
| 151 | if (type === "JSXIdentifier") usage.blocked = true; |
| 152 | } |
| 153 | // Fall through: a binding's `typeAnnotation` hangs off its Identifier. |
| 154 | } else if (type === "TSImportEqualsDeclaration") { |
| 155 | // `import L = AWS.Lambda` aliases a value through a type-shaped name. |
| 156 | const usage = usages.get(rootName(n.moduleReference)); |
| 157 | if (usage) usage.blocked = true; |
| 158 | } else if (type === "MemberExpression" || type === "TSQualifiedName") { |
| 159 | const [object, property] = |
| 160 | type === "MemberExpression" ? [n.object, n.property] : [n.left, n.right]; |
| 161 | const o = object as { type: string; name?: string }; |
| 162 | const p = property as { type: string; name?: string }; |
| 163 | const usage = o.type === "Identifier" ? usages.get(o.name!) : undefined; |
| 164 | if (usage && p.type === "Identifier" && n.computed !== true) { |
| 165 | usage.members.push([n.start as number, n.end as number, p.name!, inType]); |
| 166 | } |
| 167 | } |
| 168 | const childInType = inType || TYPE_NODES.has(type); |
| 169 | for (const key in n) { |
| 170 | if (key === "parent" || key === "type" || key === "start" || key === "end") continue; |
| 171 | visit(n[key], childInType); |
| 172 | } |
| 173 | }; |
| 174 | visit(program.body, false); |
| 175 | |
| 176 | const edits: NamespaceImportEdit[] = []; |
| 177 | const taken = new Set<string>(); |
| 178 | for (const [name, declaration] of candidates) { |
| 179 | const usage = usages.get(name)!; |
| 180 | // One identifier is the import's own binding; every other one must be |
| 181 | // the object of a rewritable member access. |
| 182 | if (usage.blocked || usage.members.length === 0) continue; |
| 183 | if (usage.identifiers !== usage.members.length + 1) continue; |
| 184 | |
| 185 | const aliases = new Map<string, { alias: string; value: boolean }>(); |
| 186 | for (const [, , member, isType] of usage.members) { |
| 187 | const existing = aliases.get(member); |
| 188 | if (existing) { |
| 189 | existing.value ||= !isType; |
| 190 | continue; |
| 191 | } |
| 192 | const alias = uniqueAlias(code, taken, `${name}$${member}`); |
| 193 | taken.add(alias); |
| 194 | aliases.set(member, { alias, value: !isType }); |
| 195 | } |
| 196 | const specifiers = [...aliases] |
| 197 | .map(([member, { alias, value }]) => `${value ? "" : "type "}${member} as ${alias}`) |
| 198 | .join(", "); |
| 199 | const source = code.slice(declaration.source.start, declaration.source.end); |
| 200 | edits.push({ |
| 201 | start: declaration.start, |
| 202 | end: declaration.end, |
| 203 | text: `import { ${specifiers} } from ${source};`, |
| 204 | }); |
| 205 | for (const [start, end, member] of usage.members) { |
| 206 | edits.push({ start, end, text: aliases.get(member)!.alias }); |
| 207 | } |
| 208 | } |
| 209 | return edits; |
| 210 | } |
| 211 | |
| 212 | /** |
| 213 | * Nodes whose descendants are all types. `typeof ns.X` is a type query over |
| 214 | * a value, which a `type` import still satisfies. |
| 215 | */ |
| 216 | const TYPE_NODES = new Set([ |
| 217 | "TSTypeAnnotation", |
| 218 | "TSTypeReference", |
| 219 | "TSTypeQuery", |
| 220 | "TSInterfaceDeclaration", |
| 221 | "TSInterfaceHeritage", |
| 222 | "TSClassImplements", |
| 223 | "TSTypeAliasDeclaration", |
| 224 | "TSTypeParameterInstantiation", |
| 225 | "TSTypeParameterDeclaration", |
| 226 | ]); |
| 227 | |
| 228 | /** The leftmost identifier of `a.b.c` (or `a`), or `""`. */ |
| 229 | const rootName = (node: unknown): string => { |
| 230 | let n = node as { type?: string; name?: string; left?: unknown; object?: unknown } | null; |
| 231 | while (n && (n.type === "TSQualifiedName" || n.type === "MemberExpression")) { |
| 232 | n = (n.left ?? n.object) as typeof n; |
| 233 | } |
| 234 | return n?.type === "Identifier" ? n.name! : ""; |
| 235 | }; |
| 236 | |
| 237 | /** The package name of a bare import specifier, or `null` for relative/absolute ones. */ |
| 238 | const packageNameOf = (specifier: string): string | null => { |
| 239 | if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.includes(":")) { |
| 240 | return null; |
| 241 | } |
| 242 | const parts = specifier.split("/"); |
| 243 | return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!; |
| 244 | }; |
| 245 | |
| 246 | const langOf = (filename: string): "js" | "jsx" | "ts" | "tsx" => { |
| 247 | const clean = filename.replace(/[?#].*$/, ""); |
| 248 | if (clean.endsWith(".tsx")) return "tsx"; |
| 249 | if (clean.endsWith(".jsx")) return "jsx"; |
| 250 | // TS is a superset of JS for parsing published `.js` files. |
| 251 | return "ts"; |
| 252 | }; |
| 253 | |
| 254 | /** `base`, suffixed until it occurs nowhere in `code` and isn't already `taken`. */ |
| 255 | const uniqueAlias = (code: string, taken: ReadonlySet<string>, base: string): string => { |
| 256 | let alias = base; |
| 257 | while (code.includes(alias) || taken.has(alias)) alias += "$"; |
| 258 | return alias; |
| 259 | }; |