Skip to content

Commit

Permalink
feat(bindgen): embed js module bundle in the python package
Browse files Browse the repository at this point in the history
Module with embedded with WebWorker.
  • Loading branch information
thewtex committed Nov 4, 2023
1 parent 84e78df commit f46df27
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/bindgen/python/emscripten/emscripten-package.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function emscriptenPackage(outputDir, buildDir, wasmBinaries, options) {
const async = true
const sync = false
packageDunderInit(outputDir, buildDir, wasmBinaries, packageName, packageDescription, packageDir, pypackage, async, sync)
emscriptenPyodideModule(packageDir, pypackage, options)
emscriptenPyodideModule(outputDir, packageDir, pypackage, options)
emscriptenTestModule(packageDir, pypackage)

const wasmModulesDir = path.join(packageDir, pypackage, 'wasm_modules')
Expand Down
23 changes: 13 additions & 10 deletions src/bindgen/python/emscripten/emscripten-pyodide-module.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
import fs from 'fs-extra'
import path from 'path'

function emscriptenPyodideModule(packageDir, pypackage, options) {
const defaultJsPackageName = options.packageName.replace('itkwasm-', '@itk-wasm/')
const defaultJsModuleName = options.packageName.replace('itkwasm-', '')
const version = options.packageVersion ?? '0.1.0'
import writeIfOverrideNotPresent from '../../write-if-override-not-present.js'

const moduleUrl = options.jsModuleUrl ?? `https://cdn.jsdelivr.net/npm/${defaultJsPackageName}@{__version__}/dist/index.js`
function emscriptenPyodideModule(outputDir, packageDir, pypackage, options) {
const defaultJsModuleName = options.packageName.replace('itkwasm-', '')
const defaultJsModulePath = path.join(outputDir, '..', 'typescript', 'dist', `${defaultJsModuleName}-worker-embedded.js`)
const moduleUrl = options.jsModulePath ?? defaultJsModulePath
if (!fs.existsSync(moduleUrl)) {
console.error(`Could not find ${moduleUrl}`)
process.exit(1)
}
const jsModuleContent = fs.readFileSync(moduleUrl, { encoding: 'utf8', flag: 'r' })

const moduleContent = `from itkwasm.pyodide import JsPackageConfig, JsPackage
from ._version import __version__
default_config = JsPackageConfig(f"${moduleUrl}")
default_js_module = """data:text/javascript;charset=utf-8,${jsModuleContent}"""
default_config = JsPackageConfig(default_js_module)
js_package = JsPackage(default_config)
`

const modulePath = path.join(packageDir, pypackage, 'js_package.py')

if (!fs.existsSync(modulePath)) {
fs.writeFileSync(modulePath, moduleContent)
}
writeIfOverrideNotPresent(modulePath, moduleContent, '#')
}

export default emscriptenPyodideModule

0 comments on commit f46df27

Please sign in to comment.