import type { PhpModuleMeta, PhpModuleRuntimeOptions, StdoutMode } from "./types"; // ECMAScript's invalid-binding list (reserved words, the strict-mode additions, `arguments` and // `eval`), not PHP's: `define()` can hand codegen any name, and every one of these is still a legal // *export* name. Bun's transpiler tolerates the strict-mode subset, but its module loader does not. const RESERVED = new Set( `arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield`.split(/\s+/), ); const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/; export function isBindableIdentifier(name: string): boolean { return IDENTIFIER.test(name) && !RESERVED.has(name); } /** The local binding for a PHP name; the one place codegen, dts and parse agree on aliasing. */ export function bindingNameFor(name: string, kind: "function" | "constant"): string { if (isBindableIdentifier(name)) return name; const prefix = kind === "function" ? "__phpFn" : "__phpConst"; return `${prefix}_${name.replace(/[^A-Za-z0-9_$]/g, "_")}`; } /** Lines declaring `name`, re-exported through an alias when the name itself cannot be a binding. */ export function exportLines( name: string, kind: "function" | "constant", declare: (binding: string) => string, ): string[] { const binding = bindingNameFor(name, kind); if (binding === name) return [`export ${declare(name)}`]; return [declare(binding), `export { ${binding} as ${JSON.stringify(name)} };`]; } /** The trailer both generated files end with. */ export function skippedLines(meta: PhpModuleMeta): string[] { if (meta.skipped.length === 0) return []; return ["", "// Not exported:", ...meta.skipped.map((note) => `// - ${oneLine(note)}`)]; } /** * A note ends up inside a `//` comment, and `define()` accepts a name containing a line terminator, * which would end the comment and leave the rest of the note as bare tokens in a module that will * not parse. The four characters JavaScript treats as line terminators all have to go. */ function oneLine(note: string): string { return note.replace(/[\n\r\u2028\u2029]+/g, " "); } export interface CodegenOptions { /** Absolute path of the `.php` file. */ path: string; source: string; meta: PhpModuleMeta; /** Module specifier (or absolute path) for `bun-php`'s runtime. */ runtimeSpecifier: string; stdout: StdoutMode; /** Host directory to mount into the virtual filesystem, if any. */ root: string | null; /** Composer autoloader to require before the module, if any. */ autoload: string | null; /** Interpreter options for the module, if any. Emitted verbatim, so it must survive JSON. */ runtime?: PhpModuleRuntimeOptions; } /** The JavaScript module a `.php` import resolves to. */ export function generateModule(options: CodegenOptions): string { const { path, source, meta, runtimeSpecifier, stdout, root, autoload, runtime } = options; const functions = Object.fromEntries(meta.functions.map((fn) => [fn.exportName, fn.phpName])); const lines = [ `// Generated by bun-php from ${path}`, `import { createPhpModule } from ${JSON.stringify(runtimeSpecifier)};`, "", "const __mod = createPhpModule({", ` id: ${JSON.stringify(path)},`, ` source: ${JSON.stringify(source)},`, ` functions: ${JSON.stringify(functions)},`, ` meta: ${JSON.stringify(meta)},`, ` stdout: ${JSON.stringify(stdout)},`, ` root: ${JSON.stringify(root)},`, ` autoload: ${JSON.stringify(autoload)},`, // Omitted when unset, so a module without runtime options generates exactly what it always did. ...(runtime ? [` runtime: ${JSON.stringify(runtime)},`] : []), "});", "", "export default __mod;", "", ]; for (const fn of meta.functions) { const call = `(...args) => __mod.$call(${JSON.stringify(fn.exportName)}, args);`; lines.push( ...exportLines(fn.exportName, "function", (binding) => `const ${binding} = ${call}`), ); } if (meta.constants.length > 0) lines.push(""); for (const constant of meta.constants) { const value = JSON.stringify(constant.value); lines.push( ...exportLines(constant.name, "constant", (binding) => `const ${binding} = ${value};`), ); } return [...lines, ...skippedLines(meta)].join("\n") + "\n"; }