diff --git a/Dockerfile b/Dockerfile index f33bc18..7d59060 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,6 +13,13 @@ RUN go mod download COPY . . +# Build do WASM do widget (regras de negócio no cliente) +# Importante: a compilação do WASM exige GOOS=js/GOARCH=wasm. +RUN GOOS=js GOARCH=wasm go build -trimpath -ldflags="-s -w" -o web/static/e-li.nps.wasm ./cmd/widgetwasm + +# Copia o runtime JS do Go para WASM (Go class, polyfills) +RUN cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js + # Build do binário RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server diff --git a/README.md b/README.md index 4c70f9f..05bc516 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,38 @@ O servidor controla o cache de `/static/e-li.nps.js` via **ETag**. Isso evita problemas de clientes com JS antigo em cache após mudanças. +### WebAssembly (WASM) — regras do widget em Go + +O widget `e-li.nps.js` carrega um módulo WASM compilado em Go, para concentrar +as regras de negócio do cliente (pré-validações, cooldown e decisão de abertura +com base na resposta do backend). + +Arquivos servidos: + +- `/static/e-li.nps.js` (arquivo único do widget) +- `/static/e-li.nps.wasm` (módulo WASM) +- `/static/wasm_exec.js` (runtime do Go para WASM) + +Regras importantes: + +- **Fail-closed**: se o WASM não carregar, o widget não abre. +- Cache é controlado por **ETag** e o browser sempre **revalida**. +- O backend Go continua sendo a **autoridade** das regras e persistência. + +#### Build local do WASM + +Para (re)gerar os arquivos do WASM localmente: + +```bash +# gera o módulo WASM +GOOS=js GOARCH=wasm go build -o web/static/e-li.nps.wasm ./cmd/widgetwasm + +# copia o runtime JS do Go para WASM +cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" web/static/wasm_exec.js +``` + +> Observação: no build via Docker, esses passos já são executados no `Dockerfile`. + ### Arquivo `.env` O servidor carrega automaticamente um arquivo `.env` na raiz do projeto (se existir) usando `godotenv`. diff --git a/cmd/server/main.go b/cmd/server/main.go index c5249a9..cf84abf 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -92,6 +92,38 @@ func main() { http.ServeFile(w, r, "web/static/e-li.nps.js") }) + + // WASM do widget. + // Regra: cache controlado por ETag e revalidação obrigatória. + // Importante: mantemos o MESMO ETag da inicialização (versaoWidget) + // para JS e WASM, garantindo que ambos "andem juntos". + r.Get("/e-li.nps.wasm", func(w http.ResponseWriter, r *http.Request) { + etag := fmt.Sprintf("\"%s\"", versaoWidget) + w.Header().Set("ETag", etag) + w.Header().Set("Cache-Control", "no-cache, must-revalidate") + w.Header().Set("Content-Type", "application/wasm") + + if r.Header.Get("If-None-Match") == etag { + w.WriteHeader(http.StatusNotModified) + return + } + http.ServeFile(w, r, "web/static/e-li.nps.wasm") + }) + + // Runtime JS do Go para WASM. + // Também fica sob ETag + revalidação. + r.Get("/wasm_exec.js", func(w http.ResponseWriter, r *http.Request) { + etag := fmt.Sprintf("\"%s\"", versaoWidget) + w.Header().Set("ETag", etag) + w.Header().Set("Cache-Control", "no-cache, must-revalidate") + w.Header().Set("Content-Type", "application/javascript") + + if r.Header.Get("If-None-Match") == etag { + w.WriteHeader(http.StatusNotModified) + return + } + http.ServeFile(w, r, "web/static/wasm_exec.js") + }) r.Handle("/*", http.StripPrefix("/static/", fileServer)) }) // Conveniência: permitir /teste.html diff --git a/cmd/widgetwasm/main.go b/cmd/widgetwasm/main.go new file mode 100644 index 0000000..1ebaebf --- /dev/null +++ b/cmd/widgetwasm/main.go @@ -0,0 +1,249 @@ +//go:build js && wasm + +package main + +import ( + "regexp" + "strings" + "syscall/js" +) + +// IMPORTANTE (.agent): o backend Go continua sendo a autoridade das regras. +// Este WASM existe para concentrar regras de negócio do widget (cliente) em Go, +// mantendo o arquivo JS pequeno e fácil de auditar. + +var dataISORe = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})-([0-9]{2})$`) + +type cfgWidget struct { + ProdutoNome string + InquilinoCodigo string + InquilinoNome string + UsuarioCodigo string + UsuarioNome string + UsuarioTelefone string + UsuarioEmail string + CooldownHours float64 + DataMinimaAbertura string +} + +func main() { + js.Global().Set("__eli_nps_wasm_preflight", js.FuncOf(preflight)) + js.Global().Set("__eli_nps_wasm_decidir", js.FuncOf(decidir)) + js.Global().Set("__eli_nps_wasm_cooldown_ativo", js.FuncOf(cooldownAtivo)) + js.Global().Set("__eli_nps_wasm_set_cooldown", js.FuncOf(setCooldown)) + js.Global().Set("__eli_nps_wasm_ready", true) + + // Mantém o módulo vivo. + select {} +} + +func cooldownAtivo(this js.Value, args []js.Value) any { + if len(args) < 1 { + return false + } + chave := strings.TrimSpace(args[0].String()) + if chave == "" { + return false + } + + // Best-effort: se der erro, tratamos como não ativo. + storage := js.Global().Get("localStorage") + if storage.IsUndefined() || storage.IsNull() { + return false + } + + v := storage.Call("getItem", chave) + if v.IsNull() || v.IsUndefined() { + return false + } + + parsed := js.Global().Get("JSON").Call("parse", v) + until := parsed.Get("until") + if until.IsUndefined() || until.IsNull() { + return false + } + + agora := js.Global().Get("Date").Call("now").Int() + return int64(agora) < int64(until.Int()) +} + +func setCooldown(this js.Value, args []js.Value) any { + if len(args) < 2 { + return nil + } + chave := strings.TrimSpace(args[0].String()) + if chave == "" { + return nil + } + ateMs := int64(args[1].Int()) + if ateMs <= 0 { + return nil + } + + storage := js.Global().Get("localStorage") + if storage.IsUndefined() || storage.IsNull() { + return nil + } + + obj := js.Global().Get("Object").New() + obj.Set("until", ateMs) + json := js.Global().Get("JSON").Call("stringify", obj) + storage.Call("setItem", chave, json) + return nil +} + +func preflight(this js.Value, args []js.Value) any { + if len(args) < 1 { + return map[string]any{"ok": false, "motivo": "sem_cfg"} + } + cfg := lerCfg(args[0]) + + // Bloqueio por data mínima. + if antesDaDataMinima(cfg.DataMinimaAbertura) { + return map[string]any{"ok": false, "motivo": "antes_da_data_minima"} + } + + // controle de exibição: produto + inquilino_codigo + usuario_codigo + if cfg.ProdutoNome == "" || cfg.InquilinoCodigo == "" || cfg.UsuarioCodigo == "" { + return map[string]any{"ok": false, "motivo": "contexto_incompleto"} + } + + chaveCooldown := chaveCooldown(cfg.ProdutoNome, cfg.InquilinoCodigo, cfg.UsuarioCodigo) + untilMs := calcularCooldownAteMs(cfg.CooldownHours) + + // Enviamos exatamente o produto_nome informado. + payload := map[string]any{ + "produto_nome": cfg.ProdutoNome, + "inquilino_codigo": cfg.InquilinoCodigo, + "inquilino_nome": cfg.InquilinoNome, + "usuario_codigo": cfg.UsuarioCodigo, + "usuario_nome": cfg.UsuarioNome, + "usuario_telefone": cfg.UsuarioTelefone, + "usuario_email": normalizarEmail(cfg.UsuarioEmail), + } + + return map[string]any{ + "ok": true, + "chave_cooldown": chaveCooldown, + "cooldown_ate_ms": untilMs, + "payload": payload, + } +} + +func decidir(this js.Value, args []js.Value) any { + // Entrada: + // - args[0] = cfg (para cooldownHours) + // - args[1] = resposta JSON do servidor (obj) + if len(args) < 2 { + return map[string]any{"abrir": false, "motivo": "sem_dados"} + } + cfg := lerCfg(args[0]) + data := args[1] + + untilMs := calcularCooldownAteMs(cfg.CooldownHours) + + // Fail-closed. + if data.IsUndefined() || data.IsNull() { + return map[string]any{"abrir": false, "motivo": "resposta_invalida", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs} + } + + // Esperado: {pode_abrir:bool, id:string, produto:string} + podeAbrir := data.Get("pode_abrir") + if !podeAbrir.Truthy() { + return map[string]any{"abrir": false, "motivo": "nao_pode_abrir", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs} + } + id := strings.TrimSpace(data.Get("id").String()) + produtoRota := strings.TrimSpace(data.Get("produto").String()) + if id == "" || produtoRota == "" { + // Não dá para montar URL segura. + return map[string]any{"abrir": false, "motivo": "sem_produto_ou_id", "aplicar_cooldown": true, "cooldown_ate_ms": untilMs} + } + + return map[string]any{ + "abrir": true, + "id": id, + "produto_rota": produtoRota, + "aplicar_cooldown": true, + "cooldown_ate_ms": untilMs, + } +} + +func lerCfg(v js.Value) cfgWidget { + // Leitura defensiva: tudo é best-effort. + getStr := func(k string) string { + if v.Type() != js.TypeObject { + return "" + } + vv := v.Get(k) + if vv.IsUndefined() || vv.IsNull() { + return "" + } + return strings.TrimSpace(vv.String()) + } + getNum := func(k string) float64 { + if v.Type() != js.TypeObject { + return 0 + } + vv := v.Get(k) + if vv.IsUndefined() || vv.IsNull() { + return 0 + } + return vv.Float() + } + + return cfgWidget{ + ProdutoNome: getStr("produto_nome"), + InquilinoCodigo: getStr("inquilino_codigo"), + InquilinoNome: getStr("inquilino_nome"), + UsuarioCodigo: getStr("usuario_codigo"), + UsuarioNome: getStr("usuario_nome"), + UsuarioTelefone: getStr("usuario_telefone"), + UsuarioEmail: getStr("usuario_email"), + CooldownHours: getNum("cooldownHours"), + DataMinimaAbertura: getStr("data_minima_abertura"), + } +} + +func normalizarEmail(email string) string { + return strings.ToLower(strings.TrimSpace(email)) +} + +func chaveCooldown(produto, inquilino, usuarioCodigo string) string { + // Prefixo de storage atualizado para o novo nome do projeto. + return "eli-nps:cooldown:" + produto + ":" + inquilino + ":" + usuarioCodigo +} + +func calcularCooldownAteMs(hours float64) int64 { + if hours <= 0 { + hours = 24 + } + agora := js.Global().Get("Date").Call("now").Int() + return int64(agora) + int64(hours*3600*1000) +} + +func antesDaDataMinima(s string) bool { + // Aceita somente ISO (data) YYYY-MM-DD. + v := strings.TrimSpace(s) + if v == "" { + return false + } + m := dataISORe.FindStringSubmatch(v) + if m == nil { + return false + } + // new Date(ano, mes-1, dia, 0, 0, 0, 0) + ano := m[1] + mes := m[2] + dia := m[3] + + // Converte para números via JS (simplifica validação e compatibilidade de timezone). + nAno := js.Global().Get("Number").Invoke(ano).Int() + nMes := js.Global().Get("Number").Invoke(mes).Int() + nDia := js.Global().Get("Number").Invoke(dia).Int() + if nAno <= 0 || nMes < 1 || nMes > 12 || nDia < 1 || nDia > 31 { + return false + } + dataMin := js.Global().Get("Date").New(nAno, nMes-1, nDia, 0, 0, 0, 0) + agora := js.Global().Get("Date").New() + return agora.Call("getTime").Int() < dataMin.Call("getTime").Int() +} diff --git a/web/static/e-li.nps.js b/web/static/e-li.nps.js index 1aff230..d3e0538 100644 --- a/web/static/e-li.nps.js +++ b/web/static/e-li.nps.js @@ -1,4 +1,14 @@ (function(){ + // Widget NPS (arquivo único). + // + // Regras do projeto (.agent): + // - sem dependências externas + // - fail-closed + // - contratos públicos estáveis + // + // Evolução: regras de negócio do cliente foram movidas para WASM (Go) + // sempre que possível. O backend continua sendo a autoridade. + const DEFAULTS = { apiBase: '', cooldownHours: 24, @@ -8,51 +18,55 @@ data_minima_abertura: '', }; - function parseDataMinima(s){ - // Aceita somente ISO (data) YYYY-MM-DD. - // Retorna um Date no início do dia (00:00) no horário local. - const v = String(s || '').trim(); - if(!v) return null; - const m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(v); - if(!m) return null; - const ano = Number(m[1]); - const mes = Number(m[2]); - const dia = Number(m[3]); - if(!ano || mes < 1 || mes > 12 || dia < 1 || dia > 31) return null; - return new Date(ano, mes-1, dia, 0, 0, 0, 0); - } - - function antesDaDataMinima(cfg){ - const d = parseDataMinima(cfg.data_minima_abertura); - if(!d) return false; - return new Date() < d; - } - - function normalizeEmail(email){ - return String(email || '').trim().toLowerCase(); - } - function cooldownKey(produto, inquilino, usuarioCodigo){ // Prefixo de storage atualizado para o novo nome do projeto. return `eli-nps:cooldown:${produto}:${inquilino}:${usuarioCodigo}`; } - function nowMs(){ return Date.now(); } + // ------------------------------------------------------------------ + // WASM (Go) + // ------------------------------------------------------------------ - function withinCooldown(key){ - try{ - const v = localStorage.getItem(key); - if(!v) return false; - const obj = JSON.parse(v); - return obj && obj.until && nowMs() < obj.until; - }catch(e){ return false; } + async function carregarWasm(apiBase){ + // fail-closed: se o WASM não carregar, o widget não abre. + if(window.__eli_nps_wasm_ready) return true; + if(window.__eli_nps_wasm_loading) return window.__eli_nps_wasm_loading; + + window.__eli_nps_wasm_loading = (async function(){ + try{ + // wasm_exec.js expõe global `Go`. + if(!window.Go){ + await carregarScript(`${apiBase}/static/wasm_exec.js`); + } + + const go = new Go(); + const res = await fetch(`${apiBase}/static/e-li.nps.wasm`, {cache: 'no-cache'}); + if(!res.ok) return false; + const bytes = await res.arrayBuffer(); + const {instance} = await WebAssembly.instantiate(bytes, go.importObject); + go.run(instance); + return !!window.__eli_nps_wasm_ready; + }catch(e){ + return false; + } + })(); + + return window.__eli_nps_wasm_loading; } - function setCooldown(key, hours){ - try{ - const until = nowMs() + hours*3600*1000; - localStorage.setItem(key, JSON.stringify({until})); - }catch(e){} + function carregarScript(src){ + return new Promise(function(resolve, reject){ + try{ + const s = document.createElement('script'); + s.src = src; + s.async = true; + s.onload = function(){ resolve(); }; + s.onerror = function(){ reject(new Error('script_fail')); }; + document.head.appendChild(s); + }catch(e){ + reject(e); + } + }); } function createModal(){ @@ -133,71 +147,43 @@ init: async function(opts){ const cfg = Object.assign({}, DEFAULTS, opts || {}); - // Bloqueio por data mínima (feature flag simples). - // Ex.: não abrir modal antes de 2026-01-01. - if(antesDaDataMinima(cfg)){ - return; - } + // Carrega WASM (Go). Sem WASM, não abrimos o widget (fail-closed). + const okWasm = await carregarWasm(cfg.apiBase); + if(!okWasm) return; - // produto_nome pode ser qualquer string (ex.: "e-licencie", "Cachaça & Churras"). - // Regra do projeto: o tratamento/normalização de caracteres deve ser feito - // apenas no backend, exclusivamente para nome de tabela/rotas. - const produtoNome = String(cfg.produto_nome || '').trim(); - const inquilino = String(cfg.inquilino_codigo || '').trim(); - const usuarioCodigo = String(cfg.usuario_codigo || '').trim(); - const email = normalizeEmail(cfg.usuario_email); + // Pré-validação e preparação do payload no WASM. + const pre = window.__eli_nps_wasm_preflight(cfg); + if(!pre || !pre.ok) return; - // controle de exibição: produto + inquilino_codigo + usuario_codigo - if(!produtoNome || !inquilino || !usuarioCodigo){ - return; // missing required context - } - - // A chave do cooldown é “best-effort” e não participa de nenhuma regra - // de segurança. Mantemos o produto como foi informado. - const chaveCooldown = cooldownKey(produtoNome, inquilino, usuarioCodigo); - if(withinCooldown(chaveCooldown)) return; - - // Enviamos exatamente o produto_nome informado. - const payload = { - produto_nome: produtoNome, - inquilino_codigo: inquilino, - inquilino_nome: String(cfg.inquilino_nome || '').trim(), - usuario_codigo: usuarioCodigo, - usuario_nome: String(cfg.usuario_nome || '').trim(), - usuario_telefone: String(cfg.usuario_telefone || '').trim(), - usuario_email: email, - }; + // Cooldown visual no browser (WASM faz storage best-effort). + // A chave do cooldown é best-effort e não participa de regra de segurança. + if(window.__eli_nps_wasm_cooldown_ativo(pre.chave_cooldown)) return; let data; try{ - const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, payload); + const res = await postJSON(`${cfg.apiBase}/api/e-li.nps/pedido`, pre.payload); if(!res.ok) return; // fail-closed data = await res.json(); }catch(e){ return; // fail-closed } - if(!data || !data.pode_abrir || !data.id){ - // small cooldown to avoid flicker if backend keeps rejecting - setCooldown(chaveCooldown, cfg.cooldownHours); - return; - } - - // Backend can return normalized product; use it for building iframe URL. - const produtoRota = data.produto; - if(!produtoRota){ - // fail-closed (não dá pra montar URL segura) - setCooldown(chaveCooldown, cfg.cooldownHours); + const dec = window.__eli_nps_wasm_decidir(cfg, data); + if(!dec || !dec.abrir){ + // cooldown para evitar flicker se o backend seguir rejeitando. + if(dec && dec.aplicar_cooldown){ + window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms); + } return; } const modal = createModal(); const iframe = document.createElement('iframe'); - iframe.src = `${cfg.apiBase}/e-li.nps/${produtoRota}/${data.id}/form`; + iframe.src = `${cfg.apiBase}/e-li.nps/${dec.produto_rota}/${dec.id}/form`; modal.panel.appendChild(iframe); // Visual cooldown so it doesn't keep popping (even if user closes). - setCooldown(chaveCooldown, cfg.cooldownHours); + window.__eli_nps_wasm_set_cooldown(pre.chave_cooldown, dec.cooldown_ate_ms); } }; })(); diff --git a/web/static/e-li.nps.wasm b/web/static/e-li.nps.wasm new file mode 100755 index 0000000..44f4b34 Binary files /dev/null and b/web/static/e-li.nps.wasm differ diff --git a/web/static/wasm_exec.js b/web/static/wasm_exec.js new file mode 100644 index 0000000..d71af9e --- /dev/null +++ b/web/static/wasm_exec.js @@ -0,0 +1,575 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +"use strict"; + +(() => { + const enosys = () => { + const err = new Error("not implemented"); + err.code = "ENOSYS"; + return err; + }; + + if (!globalThis.fs) { + let outputBuf = ""; + globalThis.fs = { + constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused + writeSync(fd, buf) { + outputBuf += decoder.decode(buf); + const nl = outputBuf.lastIndexOf("\n"); + if (nl != -1) { + console.log(outputBuf.substring(0, nl)); + outputBuf = outputBuf.substring(nl + 1); + } + return buf.length; + }, + write(fd, buf, offset, length, position, callback) { + if (offset !== 0 || length !== buf.length || position !== null) { + callback(enosys()); + return; + } + const n = this.writeSync(fd, buf); + callback(null, n); + }, + chmod(path, mode, callback) { callback(enosys()); }, + chown(path, uid, gid, callback) { callback(enosys()); }, + close(fd, callback) { callback(enosys()); }, + fchmod(fd, mode, callback) { callback(enosys()); }, + fchown(fd, uid, gid, callback) { callback(enosys()); }, + fstat(fd, callback) { callback(enosys()); }, + fsync(fd, callback) { callback(null); }, + ftruncate(fd, length, callback) { callback(enosys()); }, + lchown(path, uid, gid, callback) { callback(enosys()); }, + link(path, link, callback) { callback(enosys()); }, + lstat(path, callback) { callback(enosys()); }, + mkdir(path, perm, callback) { callback(enosys()); }, + open(path, flags, mode, callback) { callback(enosys()); }, + read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, + readdir(path, callback) { callback(enosys()); }, + readlink(path, callback) { callback(enosys()); }, + rename(from, to, callback) { callback(enosys()); }, + rmdir(path, callback) { callback(enosys()); }, + stat(path, callback) { callback(enosys()); }, + symlink(path, link, callback) { callback(enosys()); }, + truncate(path, length, callback) { callback(enosys()); }, + unlink(path, callback) { callback(enosys()); }, + utimes(path, atime, mtime, callback) { callback(enosys()); }, + }; + } + + if (!globalThis.process) { + globalThis.process = { + getuid() { return -1; }, + getgid() { return -1; }, + geteuid() { return -1; }, + getegid() { return -1; }, + getgroups() { throw enosys(); }, + pid: -1, + ppid: -1, + umask() { throw enosys(); }, + cwd() { throw enosys(); }, + chdir() { throw enosys(); }, + } + } + + if (!globalThis.path) { + globalThis.path = { + resolve(...pathSegments) { + return pathSegments.join("/"); + } + } + } + + if (!globalThis.crypto) { + throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); + } + + if (!globalThis.performance) { + throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); + } + + if (!globalThis.TextEncoder) { + throw new Error("globalThis.TextEncoder is not available, polyfill required"); + } + + if (!globalThis.TextDecoder) { + throw new Error("globalThis.TextDecoder is not available, polyfill required"); + } + + const encoder = new TextEncoder("utf-8"); + const decoder = new TextDecoder("utf-8"); + + globalThis.Go = class { + constructor() { + this.argv = ["js"]; + this.env = {}; + this.exit = (code) => { + if (code !== 0) { + console.warn("exit code:", code); + } + }; + this._exitPromise = new Promise((resolve) => { + this._resolveExitPromise = resolve; + }); + this._pendingEvent = null; + this._scheduledTimeouts = new Map(); + this._nextCallbackTimeoutID = 1; + + const setInt64 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); + } + + const setInt32 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + } + + const getInt64 = (addr) => { + const low = this.mem.getUint32(addr + 0, true); + const high = this.mem.getInt32(addr + 4, true); + return low + high * 4294967296; + } + + const loadValue = (addr) => { + const f = this.mem.getFloat64(addr, true); + if (f === 0) { + return undefined; + } + if (!isNaN(f)) { + return f; + } + + const id = this.mem.getUint32(addr, true); + return this._values[id]; + } + + const storeValue = (addr, v) => { + const nanHead = 0x7FF80000; + + if (typeof v === "number" && v !== 0) { + if (isNaN(v)) { + this.mem.setUint32(addr + 4, nanHead, true); + this.mem.setUint32(addr, 0, true); + return; + } + this.mem.setFloat64(addr, v, true); + return; + } + + if (v === undefined) { + this.mem.setFloat64(addr, 0, true); + return; + } + + let id = this._ids.get(v); + if (id === undefined) { + id = this._idPool.pop(); + if (id === undefined) { + id = this._values.length; + } + this._values[id] = v; + this._goRefCounts[id] = 0; + this._ids.set(v, id); + } + this._goRefCounts[id]++; + let typeFlag = 0; + switch (typeof v) { + case "object": + if (v !== null) { + typeFlag = 1; + } + break; + case "string": + typeFlag = 2; + break; + case "symbol": + typeFlag = 3; + break; + case "function": + typeFlag = 4; + break; + } + this.mem.setUint32(addr + 4, nanHead | typeFlag, true); + this.mem.setUint32(addr, id, true); + } + + const loadSlice = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + return new Uint8Array(this._inst.exports.mem.buffer, array, len); + } + + const loadSliceOfValues = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + const a = new Array(len); + for (let i = 0; i < len; i++) { + a[i] = loadValue(array + i * 8); + } + return a; + } + + const loadString = (addr) => { + const saddr = getInt64(addr + 0); + const len = getInt64(addr + 8); + return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); + } + + const testCallExport = (a, b) => { + this._inst.exports.testExport0(); + return this._inst.exports.testExport(a, b); + } + + const timeOrigin = Date.now() - performance.now(); + this.importObject = { + _gotest: { + add: (a, b) => a + b, + callExport: testCallExport, + }, + gojs: { + // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) + // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported + // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). + // This changes the SP, thus we have to update the SP used by the imported function. + + // func wasmExit(code int32) + "runtime.wasmExit": (sp) => { + sp >>>= 0; + const code = this.mem.getInt32(sp + 8, true); + this.exited = true; + delete this._inst; + delete this._values; + delete this._goRefCounts; + delete this._ids; + delete this._idPool; + this.exit(code); + }, + + // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) + "runtime.wasmWrite": (sp) => { + sp >>>= 0; + const fd = getInt64(sp + 8); + const p = getInt64(sp + 16); + const n = this.mem.getInt32(sp + 24, true); + fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); + }, + + // func resetMemoryDataView() + "runtime.resetMemoryDataView": (sp) => { + sp >>>= 0; + this.mem = new DataView(this._inst.exports.mem.buffer); + }, + + // func nanotime1() int64 + "runtime.nanotime1": (sp) => { + sp >>>= 0; + setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); + }, + + // func walltime() (sec int64, nsec int32) + "runtime.walltime": (sp) => { + sp >>>= 0; + const msec = (new Date).getTime(); + setInt64(sp + 8, msec / 1000); + this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); + }, + + // func scheduleTimeoutEvent(delay int64) int32 + "runtime.scheduleTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this._nextCallbackTimeoutID; + this._nextCallbackTimeoutID++; + this._scheduledTimeouts.set(id, setTimeout( + () => { + this._resume(); + while (this._scheduledTimeouts.has(id)) { + // for some reason Go failed to register the timeout event, log and try again + // (temporary workaround for https://github.com/golang/go/issues/28975) + console.warn("scheduleTimeoutEvent: missed timeout event"); + this._resume(); + } + }, + getInt64(sp + 8), + )); + this.mem.setInt32(sp + 16, id, true); + }, + + // func clearTimeoutEvent(id int32) + "runtime.clearTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this.mem.getInt32(sp + 8, true); + clearTimeout(this._scheduledTimeouts.get(id)); + this._scheduledTimeouts.delete(id); + }, + + // func getRandomData(r []byte) + "runtime.getRandomData": (sp) => { + sp >>>= 0; + crypto.getRandomValues(loadSlice(sp + 8)); + }, + + // func finalizeRef(v ref) + "syscall/js.finalizeRef": (sp) => { + sp >>>= 0; + const id = this.mem.getUint32(sp + 8, true); + this._goRefCounts[id]--; + if (this._goRefCounts[id] === 0) { + const v = this._values[id]; + this._values[id] = null; + this._ids.delete(v); + this._idPool.push(id); + } + }, + + // func stringVal(value string) ref + "syscall/js.stringVal": (sp) => { + sp >>>= 0; + storeValue(sp + 24, loadString(sp + 8)); + }, + + // func valueGet(v ref, p string) ref + "syscall/js.valueGet": (sp) => { + sp >>>= 0; + const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 32, result); + }, + + // func valueSet(v ref, p string, x ref) + "syscall/js.valueSet": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); + }, + + // func valueDelete(v ref, p string) + "syscall/js.valueDelete": (sp) => { + sp >>>= 0; + Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); + }, + + // func valueIndex(v ref, i int) ref + "syscall/js.valueIndex": (sp) => { + sp >>>= 0; + storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); + }, + + // valueSetIndex(v ref, i int, x ref) + "syscall/js.valueSetIndex": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); + }, + + // func valueCall(v ref, m string, args []ref) (ref, bool) + "syscall/js.valueCall": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const m = Reflect.get(v, loadString(sp + 16)); + const args = loadSliceOfValues(sp + 32); + const result = Reflect.apply(m, v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, result); + this.mem.setUint8(sp + 64, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, err); + this.mem.setUint8(sp + 64, 0); + } + }, + + // func valueInvoke(v ref, args []ref) (ref, bool) + "syscall/js.valueInvoke": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.apply(v, undefined, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueNew(v ref, args []ref) (ref, bool) + "syscall/js.valueNew": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.construct(v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueLength(v ref) int + "syscall/js.valueLength": (sp) => { + sp >>>= 0; + setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); + }, + + // valuePrepareString(v ref) (ref, int) + "syscall/js.valuePrepareString": (sp) => { + sp >>>= 0; + const str = encoder.encode(String(loadValue(sp + 8))); + storeValue(sp + 16, str); + setInt64(sp + 24, str.length); + }, + + // valueLoadString(v ref, b []byte) + "syscall/js.valueLoadString": (sp) => { + sp >>>= 0; + const str = loadValue(sp + 8); + loadSlice(sp + 16).set(str); + }, + + // func valueInstanceOf(v ref, t ref) bool + "syscall/js.valueInstanceOf": (sp) => { + sp >>>= 0; + this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); + }, + + // func copyBytesToGo(dst []byte, src ref) (int, bool) + "syscall/js.copyBytesToGo": (sp) => { + sp >>>= 0; + const dst = loadSlice(sp + 8); + const src = loadValue(sp + 32); + if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + // func copyBytesToJS(dst ref, src []byte) (int, bool) + "syscall/js.copyBytesToJS": (sp) => { + sp >>>= 0; + const dst = loadValue(sp + 8); + const src = loadSlice(sp + 16); + if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + "debug": (value) => { + console.log(value); + }, + } + }; + } + + async run(instance) { + if (!(instance instanceof WebAssembly.Instance)) { + throw new Error("Go.run: WebAssembly.Instance expected"); + } + this._inst = instance; + this.mem = new DataView(this._inst.exports.mem.buffer); + this._values = [ // JS values that Go currently has references to, indexed by reference id + NaN, + 0, + null, + true, + false, + globalThis, + this, + ]; + this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id + this._ids = new Map([ // mapping from JS values to reference ids + [0, 1], + [null, 2], + [true, 3], + [false, 4], + [globalThis, 5], + [this, 6], + ]); + this._idPool = []; // unused ids that have been garbage collected + this.exited = false; // whether the Go program has exited + + // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. + let offset = 4096; + + const strPtr = (str) => { + const ptr = offset; + const bytes = encoder.encode(str + "\0"); + new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); + offset += bytes.length; + if (offset % 8 !== 0) { + offset += 8 - (offset % 8); + } + return ptr; + }; + + const argc = this.argv.length; + + const argvPtrs = []; + this.argv.forEach((arg) => { + argvPtrs.push(strPtr(arg)); + }); + argvPtrs.push(0); + + const keys = Object.keys(this.env).sort(); + keys.forEach((key) => { + argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); + }); + argvPtrs.push(0); + + const argv = offset; + argvPtrs.forEach((ptr) => { + this.mem.setUint32(offset, ptr, true); + this.mem.setUint32(offset + 4, 0, true); + offset += 8; + }); + + // The linker guarantees global data starts from at least wasmMinDataAddr. + // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. + const wasmMinDataAddr = 4096 + 8192; + if (offset >= wasmMinDataAddr) { + throw new Error("total length of command line and environment variables exceeds limit"); + } + + this._inst.exports.run(argc, argv); + if (this.exited) { + this._resolveExitPromise(); + } + await this._exitPromise; + } + + _resume() { + if (this.exited) { + throw new Error("Go program has already exited"); + } + this._inst.exports.resume(); + if (this.exited) { + this._resolveExitPromise(); + } + } + + _makeFuncWrapper(id) { + const go = this; + return function () { + const event = { id: id, this: this, args: arguments }; + go._pendingEvent = event; + go._resume(); + return event.result; + }; + } + } +})();