reearth / quickjs-emscripten-sync

Provides a way to sync objects between browser and QuickJS
MIT License
62 stars 7 forks source link

include Buffer in registerdObjects #36

Closed tim-field closed 2 months ago

tim-field commented 2 months ago

Hello, I'm trying to run a script like this

return Buffer.from('abc').toString('base64')

I've tried the following approaches to this

 import {Buffer} from 'node:buffer'

  const vm = QuickJS.newContext()
  const arena = new Arena(vm, {
    isMarshalable: true,
    registeredObjects: [
      ...defaultRegisteredObjects,
      [Buffer, 'Buffer'],
      [Buffer.prototype, 'Buffer.prototype']
    ]
  })
  value = arena.evalCode(`return Buffer.from('abc').toString('base64')`)
  // throws ReferenceError: 'Buffer' is not defined

and

  import {Buffer} from 'node:buffer'

  const vm = QuickJS.newContext()
  arena.expose({
    Buffer: Buffer,
    ...payload
  })
  value = arena.evalCode(`return Buffer.from('abc').toString('base64')`)
  // throws Error running script: return Buffer.from('abc').toString('base64'): argument must be a buffer

Am I on the right track here or doing something silly ?

Thanks 🙏

tim-field commented 2 months ago

Oh this may indeed be a silly question, given Buffer is node specific

sebastianwessel commented 1 month ago

Hey @tim-field ,

I`m struggling also to get a Buffer from host into quickjs client. And idea? In fact, I get the Buffer data into QuickJS....

Did you manage to handle Buffers?

Working on this here:

https://github.com/sebastianwessel/quickjs/pull/15/files

tim-field commented 1 week ago

Hi @sebastianwessel, Yes I got this working via a module loader

  const QuickJS = await newQuickJSWASMModule(RELEASE_SYNC)

  runtime.setModuleLoader(moduleName => {
    if (moduleName in moduleStrings) {
      return moduleStrings[moduleName]
    }
    throw new Error(`Module ${moduleName} not found`)
  })
  const context = runtime.newContext()

  context.evalCode(`
   import Buffer from 'Buffer'
   globalThis.Buffer = Buffer.Buffer
  `)

moduleStrings is the result of a fs.readFile of the Buffer polyfill

I installed buffer via npm then ran the following script to bundle it for quickjs

  npx esbuild node_modules/buffer/index.js --bundle --platform=neutral --outfile=buffer.js