MCPcopy Create free account
hub / github.com/arktypeio/arktype / readCommonJs

Method readCommonJs

ark/aot/scope.ts:103–156  ·  view source on GitHub ↗
(program: Program)

Source from the content-addressed store, hash-verified

101 // the getter `Object.defineProperty(exports, "a", ...)` defines for `export
102 // { a } from "./a"`. A name set any other way, or twice, is left unread
103 private readCommonJs(program: Program): void {
104 const unread = new Set<string>()
105 const set = (name: string, entry: ExportEntry | undefined) => {
106 if (!entry || name in this.exportsByName) unread.add(name)
107 this.exportsByName[name] = entry!
108 }
109 for (const statement of program.body) {
110 if (statement.type !== "ExpressionStatement") continue
111 const { expression } = statement
112 if (expression.type === "AssignmentExpression") {
113 const names: string[] = []
114 let value: Node = expression
115 while (value.type === "AssignmentExpression") {
116 const name = commonJsExportOf(value.left)
117 if (name === undefined || value.operator !== "=") break
118 names.push(name)
119 value = value.right
120 }
121 // `exports.a = void 0`, which tsc writes ahead of each export
122 if (value.type === "UnaryExpression" && value.operator === "void")
123 continue
124 const binding =
125 value.type === "Identifier" ?
126 this.root.bindings[value.name]
127 : undefined
128 const specifier = requiredBy(value, "__importStar")
129 for (const name of names) {
130 set(
131 name,
132 value.type === "AssignmentExpression" ? undefined
133 : specifier !== undefined ? { kind: "namespace", specifier }
134 : binding ? { kind: "binding", binding }
135 : { kind: "expression", node: value }
136 )
137 }
138 } else if (expression.type === "CallExpression") {
139 const [first, second, third] = expression.arguments
140 if (
141 expression.callee.type === "Identifier" &&
142 expression.callee.name === "__exportStar"
143 ) {
144 const specifier = first && requiredBy(first)
145 if (specifier !== undefined) this.starExports.push(specifier)
146 } else if (
147 isCommonJsExports(first) &&
148 second?.type === "Literal" &&
149 typeof second.value === "string" &&
150 second.value !== "__esModule"
151 )
152 set(second.value, this.reexportDefinedBy(third))
153 }
154 }
155 for (const name of unread) delete this.exportsByName[name]
156 }
157
158 // e.g. `{ enumerable: true, get: function () { return a_1.a; } }`, where
159 // `a_1` is `require("./a")`

Callers 1

constructorMethod · 0.95

Calls 6

reexportDefinedByMethod · 0.95
commonJsExportOfFunction · 0.85
requiredByFunction · 0.85
isCommonJsExportsFunction · 0.70
setFunction · 0.50
pushMethod · 0.45

Tested by

no test coverage detected