| 1 |
import gensync, { type Handler } from "gensync"; |
| 2 |
|
| 3 |
import loadConfig from "./config"; |
| 4 |
import type { InputOptions, ResolvedConfig } from "./config"; |
| 5 |
import { run } from "./transformation"; |
| 6 |
|
| 7 |
import type { FileResult, FileResultCallback } from "./transformation"; |
| 8 |
import { beginHiddenCallStack } from "./errors/rewrite-stack-trace"; |
| 9 |
|
| 10 |
export type { FileResult } from "./transformation"; |
| 11 |
|
| 12 |
type Transform = { |
| 13 |
(code: string, callback: FileResultCallback): void; |
| 14 |
( |
| 15 |
code: string, |
| 16 |
opts: InputOptions | undefined | null, |
| 17 |
callback: FileResultCallback, |
| 18 |
): void; |
| 19 |
(code: string, opts?: InputOptions | null): FileResult | null; |
| 20 |
}; |
| 21 |
|
| 22 |
const transformRunner = gensync(function* transform( |
| 23 |
code: string, |
| 24 |
opts?: InputOptions, |
| 25 |
): Handler<FileResult | null> { |
| 26 |
const config: ResolvedConfig | null = yield* loadConfig(opts); |
| 27 |
if (config === null) return null; |
| 28 |
|
| 29 |
return yield* run(config, code); |
| 30 |
}); |
| 31 |
|
| 32 |
export const transform: Transform = function transform( |
| 33 |
code, |
| 34 |
optsOrCallback?: InputOptions | null | undefined | FileResultCallback, |
| 35 |
maybeCallback?: FileResultCallback, |
| 36 |
) { |
| 37 |
let opts: InputOptions | undefined | null; |
| 38 |
let callback: FileResultCallback | undefined; |
| 39 |
if (typeof optsOrCallback === "function") { |
| 40 |
callback = optsOrCallback; |
| 41 |
opts = undefined; |
| 42 |
} else { |
| 43 |
opts = optsOrCallback; |
| 44 |
callback = maybeCallback; |
| 45 |
} |
| 46 |
|
| 47 |
if (callback === undefined) { |
| 48 |
if (process.env.BABEL_8_BREAKING) { |
| 49 |
throw new Error( |
| 50 |
"Starting from Babel 8.0.0, the 'transform' function expects a callback. If you need to call it synchronously, please use 'transformSync'.", |
| 51 |
); |
| 52 |
} else { |
| 53 |
// console.warn( |
| 54 |
// "Starting from Babel 8.0.0, the 'transform' function will expect a callback. If you need to call it synchronously, please use 'transformSync'.", |
| 55 |
// ); |
| 56 |
return beginHiddenCallStack(transformRunner.sync)(code, opts); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
beginHiddenCallStack(transformRunner.errback)(code, opts, callback); |
| 61 |
}; |
| 62 |
|
| 63 |
export function transformSync( |
| 64 |
...args: Parameters<typeof transformRunner.sync> |
| 65 |
) { |
| 66 |
return beginHiddenCallStack(transformRunner.sync)(...args); |
| 67 |
} |
| 68 |
export function transformAsync( |
| 69 |
...args: Parameters<typeof transformRunner.async> |
| 70 |
) { |
| 71 |
return beginHiddenCallStack(transformRunner.async)(...args); |
| 72 |
} |