diff --git a/.chronus/changes/python-module-loading-2026-3-29-14-53-8.md b/.chronus/changes/python-module-loading-2026-3-29-14-53-8.md new file mode 100644 index 00000000000..ad1db7ca43d --- /dev/null +++ b/.chronus/changes/python-module-loading-2026-3-29-14-53-8.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/http-client-python" +--- + +Update Python emitter browser behavior to only load Pyodide once instead of on every emit diff --git a/packages/http-client-python/emitter/src/emitter.ts b/packages/http-client-python/emitter/src/emitter.ts index 49110135355..3ecd85c5f57 100644 --- a/packages/http-client-python/emitter/src/emitter.ts +++ b/packages/http-client-python/emitter/src/emitter.ts @@ -235,11 +235,21 @@ async function onEmitMain(context: EmitContext) { if (typeof window !== "undefined") { // Running in browser with Pyodide - fileURLToPath and other filesystem operations are browser-incompatible - const pyodide = await setupPyodideCallBrowser(); + const pyodide = await browserPyodidePromise; + + if (!pyodide) { + reportDiagnostic(program, { + code: "browser-runtime-load-failed", + target: NoTarget, + format: { details: "" }, + }); + return; + } const yamlFilePath = "/yaml/python-yaml-path.yaml"; pyodide.FS.mkdirTree("/yaml"); pyodide.FS.mkdirTree("/output"); + clearMemfsDirectory(pyodide, "/output"); pyodide.FS.writeFile(yamlFilePath, jsyaml.dump(parsedYamlMap)); await runPyodideGeneration(pyodide, "/output", yamlFilePath, commandArgs); @@ -325,6 +335,25 @@ async function onEmitMain(context: EmitContext) { } } +const browserPyodidePromise: Promise | null = + typeof window !== "undefined" ? setupPyodideCallBrowser() : null; + +function clearMemfsDirectory(pyodide: PyodideInterface, dir: string): void { + const entries: string[] = pyodide.FS.readdir(dir).filter( + (entry: string) => entry !== "." && entry !== "..", + ); + for (const entry of entries) { + const fullPath = `${dir}/${entry}`; + const stats = pyodide.FS.stat(fullPath); + if (pyodide.FS.isDir(stats.mode)) { + clearMemfsDirectory(pyodide, fullPath); + pyodide.FS.rmdir(fullPath); + } else { + pyodide.FS.unlink(fullPath); + } + } +} + async function setupPyodideCallBrowser() { const pyodide = await loadPyodide({ indexURL: `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`, diff --git a/website/src/components/playground-component/playground.tsx b/website/src/components/playground-component/playground.tsx index dc55e0f64cc..14bab6ced4d 100644 --- a/website/src/components/playground-component/playground.tsx +++ b/website/src/components/playground-component/playground.tsx @@ -37,7 +37,7 @@ export const WebsitePlayground = ({ versionData }: WebsitePlaygroundProps) => { libraries={imports} emitterViewers={{ "@typespec/openapi3": [SwaggerUIViewer] }} emitterOptions={{ - "@typespec/http-client-python": { debounce: 500 }, + "@typespec/http-client-python": { debounce: 1000 }, "@typespec/http-client-csharp": { debounce: 500 }, }} importConfig={{ useShim: true }}