|
1 | 1 | import { StackReader } from '../stack' |
2 | 2 | import { MemoryInspector } from '../debug' |
3 | | -import { Bool, GoStringType, Int32 } from '../types' |
| 3 | +import { Bool, GoStringType, Int32, Int64 } from '../types' |
4 | 4 | import { type GoInstance, type ImportObject, type PendingEvent } from './interface' |
5 | 5 | import { type Func, Ref, RefType } from '../pkg/syscall/js' |
6 | 6 | import { MemoryView } from '../memory/view' |
@@ -58,17 +58,23 @@ export type CallImportHandler = (sp: number, stack: StackReader, mem: MemoryView |
58 | 58 | */ |
59 | 59 | const defaultCmdline = ['js'] |
60 | 60 |
|
| 61 | +export interface WasmWriter { |
| 62 | + writeSync: (fd: number, data: Uint8Array) => void |
| 63 | +} |
| 64 | + |
61 | 65 | export interface Options { |
62 | 66 | debug?: boolean |
63 | 67 | debugCalls?: string[] |
64 | 68 | globalValue?: any |
| 69 | + stdoutHandler?: WasmWriter |
65 | 70 | } |
66 | 71 |
|
67 | 72 | export class GoWrapper { |
68 | 73 | private _inspector: MemoryInspector | null = null |
69 | 74 | private _memView: MemoryView | null = null |
70 | 75 | private readonly _debug: boolean = false |
71 | 76 | private readonly _debugCalls: Set<string> |
| 77 | + private readonly _stdout?: Options['stdoutHandler'] |
72 | 78 | private _globalValue: object |
73 | 79 | private readonly go: GoInstance |
74 | 80 |
|
@@ -104,11 +110,12 @@ export class GoWrapper { |
104 | 110 | return this.go._inst!.exports |
105 | 111 | } |
106 | 112 |
|
107 | | - constructor(parent: GoInstance, { debug = false, debugCalls, globalValue }: Options = {}) { |
| 113 | + constructor(parent: GoInstance, { debug = false, debugCalls, globalValue, stdoutHandler }: Options = {}) { |
108 | 114 | this.go = parent |
109 | 115 | this._debug = debug |
110 | 116 | this._debugCalls = new Set(debugCalls ?? []) |
111 | 117 | this._globalValue = globalValue?.Go === GoWrapper ? globalValue : wrapGlobal() |
| 118 | + this._stdout = stdoutHandler |
112 | 119 |
|
113 | 120 | this.patchImportObject() |
114 | 121 | } |
@@ -148,6 +155,17 @@ export class GoWrapper { |
148 | 155 | this.valueCall(sp, reader) |
149 | 156 | }) |
150 | 157 |
|
| 158 | + if (this._stdout) { |
| 159 | + this.exportFunction('runtime.wasmWrite', (sp, reader, mem) => { |
| 160 | + reader.skipHeader() |
| 161 | + const fd = reader.next<number>(Int64) |
| 162 | + const bufPtr = reader.next<number>(Int64) |
| 163 | + const len = reader.next<number>(Int32) |
| 164 | + const chunk = mem.memory.buffer.slice(bufPtr, bufPtr + len) |
| 165 | + this._stdout?.writeSync(fd, new Uint8Array(chunk, 0, len)) |
| 166 | + }) |
| 167 | + } |
| 168 | + |
151 | 169 | const wasmExitFunc = getImportNamespace(this.go)['runtime.wasmExit'] |
152 | 170 | this.exportFunction('runtime.wasmExit', (sp, reader) => { |
153 | 171 | reader.skipHeader() |
|
0 commit comments