feat(图形界面): 将OFDGo编译为WASM提供WebUI

This commit is contained in:
2026-07-03 19:55:25 +08:00
parent 23b235ded2
commit 3f32c5e048
9 changed files with 3692 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package webuiassets
import "embed"
// FS WebUI嵌入静态文件
//
//go:embed index.html ofdgo.js ofdgo.css wasm_exec.js ofdgo.wasm
var FS embed.FS
+111
View File
@@ -0,0 +1,111 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>OFDGo WebUI</title>
<link rel="stylesheet" href="./ofdgo.css">
</head>
<body>
<div class="app">
<header class="toolbar app-bar">
<input id="ofdInput" class="file-input" type="file" accept=".ofd,application/ofd,application/zip">
<button id="ofdButton" class="button primary" type="button" data-short="打开">打开 OFD</button>
<input id="fontInput" class="file-input" type="file" accept=".ttf,.otf,.ttc,font/*" multiple>
<button id="togglePagesButton" class="icon-button" type="button" title="页面栏" aria-label="页面栏" aria-pressed="true">&#9776;</button>
<button id="toggleMetaButton" class="icon-button" type="button" title="信息栏" aria-label="信息栏" aria-pressed="true">&#9432;</button>
<div class="toolbar-space"></div>
<button id="prevButton" class="icon-button" type="button" title="上一页" disabled>&lsaquo;</button>
<label class="page-control">
<input id="pageInput" type="number" min="1" value="1" disabled>
<span>/</span>
<span id="pageTotal">0</span>
</label>
<button id="nextButton" class="icon-button" type="button" title="下一页" disabled>&rsaquo;</button>
<div class="divider"></div>
<button id="zoomOutButton" class="icon-button" type="button" title="缩小" disabled>-</button>
<span id="zoomLabel" class="zoom-label">100%</span>
<button id="zoomInButton" class="icon-button" type="button" title="放大" disabled>+</button>
<button id="fitButton" class="button" type="button" data-short="宽" disabled>适宽</button>
<button id="fitHeightButton" class="button" type="button" data-short="高" disabled>适高</button>
<button id="exportButton" class="button" type="button" data-short="PDF" title="导出 PDF" aria-label="导出 PDF" disabled>PDF</button>
</header>
<main class="workspace">
<aside class="page-list-panel">
<div class="panel-title">页面</div>
<div id="pageList" class="page-list"></div>
</aside>
<section class="viewer-panel" tabindex="0">
<div id="emptyState" class="empty-state">选择 OFD 文件</div>
<div id="progressPanel" class="progress-panel" hidden>
<div class="progress-spinner"></div>
<div id="progressLabel" class="progress-label">加载中</div>
<div class="progress-track">
<div id="progressBar" class="progress-bar"></div>
</div>
</div>
<div id="pageFrame" class="page-frame" hidden>
<div id="svgHost" class="svg-host"></div>
</div>
</section>
<aside class="meta-panel">
<div class="panel-title">文档</div>
<dl class="meta-list">
<div>
<dt>标题</dt>
<dd id="metaTitle">-</dd>
</div>
<div>
<dt>作者</dt>
<dd id="metaAuthor">-</dd>
</div>
<div>
<dt>版本</dt>
<dd id="metaVersion">-</dd>
</div>
<div>
<dt>类型</dt>
<dd id="metaType">-</dd>
</div>
<div>
<dt>字体</dt>
<dd id="metaFonts">0</dd>
</div>
</dl>
<section class="doc-font-panel" aria-labelledby="docFontPanelTitle">
<div class="panel-row">
<div id="docFontPanelTitle" class="panel-title compact">OFD 字体</div>
<span id="docFontSummary" class="count-pill">0</span>
</div>
<div id="docFontList" class="doc-font-list"></div>
</section>
<section class="font-panel" aria-labelledby="fontPanelTitle">
<div class="panel-row">
<div id="fontPanelTitle" class="panel-title compact">可用字体</div>
<div class="panel-actions">
<span id="availableFontSummary" class="count-pill">0</span>
<button id="localFontButton" class="small-button" type="button">系统字体</button>
<button id="fontAddButton" class="small-button" type="button">添加</button>
</div>
</div>
<div id="fontList" class="font-list"></div>
</section>
</aside>
</main>
<footer class="app-footer app-bar">
<a class="footer-brand" href="https://github.com/xiaoqidun/ofdgo" target="_blank" rel="noreferrer">OFDGo</a>
<div id="statusText" class="status-text">正在准备渲染引擎</div>
<nav class="footer-links" aria-label="相关链接">
<a href="https://aite.me/" target="_blank" rel="noreferrer">官方网站</a>
</nav>
</footer>
</div>
<script src="./wasm_exec.js"></script>
<script type="module" src="./ofdgo.js"></script>
</body>
</html>
+900
View File
@@ -0,0 +1,900 @@
:root {
color-scheme: light;
font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
background: #eef1f4;
color: #1f2428;
--line: #cfd7dd;
--line-strong: #aab7c1;
--panel: #f8fafb;
--page: #ffffff;
--text-muted: #66737f;
--accent: #0f7b68;
--accent-strong: #095c4e;
--focus: #c9892b;
--sidebar-width: clamp(220px, 20vw, 292px);
--bar-bg: #fbfcfd;
--bar-height: 40px;
--bar-pad: 5px 10px;
--control-height: 28px;
--shadow-soft: 0 10px 28px rgba(31, 36, 40, 0.12);
--shadow-page: 0 14px 30px rgba(31, 36, 40, 0.16);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
background: #eef1f4;
}
button,
input {
font: inherit;
}
button {
border: 1px solid var(--line-strong);
background: #ffffff;
color: #1f2428;
cursor: pointer;
transition: border-color 0.16s ease, background-color 0.16s ease, color 0.16s ease;
}
button:disabled,
input:disabled {
cursor: not-allowed;
opacity: 0.48;
}
button:focus-visible,
input:focus-visible,
a:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
.app {
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
width: 100vw;
height: 100vh;
overflow: hidden;
}
.app-bar {
display: flex;
align-items: center;
flex-wrap: nowrap;
gap: 8px;
width: 100%;
min-width: 0;
height: var(--bar-height);
min-height: var(--bar-height);
flex: 0 0 var(--bar-height);
padding: var(--bar-pad);
background: var(--bar-bg);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.68) inset;
}
.toolbar {
position: relative;
z-index: 12;
border-bottom: 1px solid var(--line);
font-size: 14px;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
}
.toolbar::-webkit-scrollbar {
display: none;
}
.file-input {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
}
.button,
.icon-button {
height: var(--control-height);
border-radius: 0;
}
.button {
padding: 0 10px;
white-space: nowrap;
}
.button.primary {
border-color: var(--accent);
background: var(--accent);
color: #ffffff;
}
.button.primary:hover {
background: var(--accent-strong);
}
button:not(:disabled):hover {
border-color: var(--accent);
background: #f2faf7;
}
.button[aria-pressed="true"],
.icon-button[aria-pressed="true"] {
border-color: var(--accent);
background: #e4f3ef;
color: var(--accent-strong);
}
.icon-button {
display: inline-grid;
place-items: center;
width: var(--control-height);
padding: 0;
font-size: 14px;
line-height: 1;
}
.toolbar-space {
flex: 1 1 auto;
}
.divider {
width: 1px;
height: 22px;
background: var(--line);
}
.page-control {
display: inline-flex;
align-items: center;
gap: 6px;
height: var(--control-height);
padding: 0 7px;
border: 1px solid var(--line);
border-radius: 0;
background: #ffffff;
color: var(--text-muted);
}
.page-control input {
width: 48px;
border: 0;
outline: 0;
text-align: right;
color: #1f2428;
background: transparent;
}
.zoom-label {
min-width: 42px;
text-align: center;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.workspace {
display: grid;
grid-template-columns: var(--sidebar-width) minmax(0, 1fr) var(--sidebar-width);
min-height: 0;
}
body[data-hide-pages] .workspace {
grid-template-columns: minmax(0, 1fr) var(--sidebar-width);
}
body[data-hide-meta] .workspace {
grid-template-columns: var(--sidebar-width) minmax(0, 1fr);
}
body[data-hide-pages][data-hide-meta] .workspace {
grid-template-columns: minmax(0, 1fr);
}
body[data-hide-pages] .page-list-panel,
body[data-hide-meta] .meta-panel {
display: none;
}
.page-list-panel,
.meta-panel {
min-height: 0;
padding: 12px;
border-right: 1px solid var(--line);
background: var(--panel);
overflow: auto;
}
.meta-panel {
border-right: 0;
border-left: 1px solid var(--line);
}
.panel-title {
margin-bottom: 10px;
font-size: 12px;
font-weight: 700;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0;
}
.panel-title.compact {
margin-bottom: 0;
}
.panel-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
flex-wrap: wrap;
}
.panel-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
justify-content: flex-end;
}
.small-button {
display: inline-flex;
align-items: center;
justify-content: center;
height: 26px;
padding: 0 8px;
border-radius: 0;
font-size: 12px;
white-space: nowrap;
}
.page-list {
display: grid;
gap: 8px;
}
.page-list-item {
display: grid;
gap: 6px;
width: 100%;
height: auto;
padding: 8px;
font-variant-numeric: tabular-nums;
text-align: left;
transition: border-color 0.16s ease, background-color 0.16s ease;
}
.page-list-item[aria-current] {
border-color: var(--accent);
background: #e4f3ef;
color: var(--accent-strong);
font-weight: 700;
}
.thumb-paper {
display: grid;
place-items: center;
width: 100%;
aspect-ratio: var(--thumb-ratio, 0.707 / 1);
overflow: hidden;
border: 1px solid var(--line);
background: #ffffff;
box-shadow: 0 2px 7px rgba(31, 36, 40, 0.1);
color: #9aa6b1;
font-size: 20px;
line-height: 1;
}
.thumb-paper.pending,
.thumb-paper.error {
background:
linear-gradient(90deg, rgba(31, 36, 40, 0.04) 1px, transparent 1px),
linear-gradient(0deg, rgba(31, 36, 40, 0.04) 1px, transparent 1px),
#ffffff;
background-size: 12px 12px;
}
.thumb-svg {
display: block;
width: 100%;
height: 100%;
}
.thumb-label,
.thumb-size {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.thumb-label {
font-size: 13px;
color: #1f2428;
}
.thumb-size {
font-size: 11px;
color: var(--text-muted);
font-weight: 400;
}
.viewer-panel {
position: relative;
min-width: 0;
min-height: 0;
overflow: auto;
background:
linear-gradient(90deg, rgba(31, 36, 40, 0.05) 1px, transparent 1px),
linear-gradient(0deg, rgba(31, 36, 40, 0.05) 1px, transparent 1px),
#e5e9ed;
background-size: 24px 24px;
}
.empty-state {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 24px;
color: var(--text-muted);
font-size: 14px;
text-align: center;
}
.empty-state[hidden],
.page-frame[hidden],
.progress-panel[hidden] {
display: none;
}
.progress-panel {
position: fixed;
left: 50%;
bottom: calc(var(--bar-height) + 14px);
z-index: 20;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: 8px 10px;
width: min(420px, calc(100vw - 32px));
padding: 10px 12px;
border: 1px solid rgba(170, 183, 193, 0.82);
background: rgba(251, 252, 253, 0.96);
box-shadow: var(--shadow-soft);
transform: translateX(-50%);
backdrop-filter: blur(8px);
}
.progress-spinner {
width: 18px;
height: 18px;
border: 2px solid #d5dde3;
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.progress-label {
min-width: 0;
overflow: hidden;
color: #1f2428;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress-track {
grid-column: 1 / -1;
width: 100%;
height: 4px;
overflow: hidden;
background: #dbe2e7;
}
.progress-bar {
width: 0;
height: 100%;
background: var(--accent);
transition: width 0.18s ease;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.page-frame {
min-width: 100%;
min-height: 100%;
padding: 34px 28px;
}
.svg-host {
display: grid;
justify-items: center;
gap: 28px;
width: max-content;
margin: 0 auto;
}
.page-shell {
position: relative;
overflow: hidden;
border: 1px solid rgba(170, 183, 193, 0.55);
box-shadow: var(--shadow-page);
background: var(--page);
}
.page-shell.error {
background: #fff8f7;
}
.page-surface {
transform-origin: 0 0;
}
.page-placeholder {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--text-muted);
font-size: 13px;
background:
linear-gradient(90deg, rgba(31, 36, 40, 0.04) 1px, transparent 1px),
linear-gradient(0deg, rgba(31, 36, 40, 0.04) 1px, transparent 1px),
#ffffff;
background-size: 18px 18px;
}
.page-shell.rendered .page-placeholder {
display: none;
}
.ofd-svg {
display: block;
max-width: none;
transform-origin: 0 0;
}
.meta-list {
display: grid;
gap: 12px;
margin: 0;
}
.meta-list div {
display: grid;
gap: 3px;
}
.meta-list dt {
font-size: 12px;
color: var(--text-muted);
}
.meta-list dd {
margin: 0;
overflow-wrap: anywhere;
line-height: 1.35;
}
.font-panel,
.doc-font-panel {
margin-top: 18px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.count-pill {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 26px;
padding: 0 7px;
border: 1px solid var(--line);
background: #ffffff;
color: var(--text-muted);
font-size: 11px;
text-align: center;
white-space: nowrap;
}
.doc-font-list {
display: grid;
gap: 8px;
}
.doc-font-row {
display: grid;
gap: 6px;
padding: 9px;
border: 1px solid var(--line);
background: #ffffff;
transition: border-color 0.16s ease, background-color 0.16s ease;
}
.page-list-item:not(:disabled):hover,
.doc-font-row:hover,
.font-row:hover {
border-color: var(--line-strong);
background: #ffffff;
}
.doc-font-row.missing {
border-color: #e2c7c4;
background: #fffdfc;
}
.doc-font-row.fallback {
border-color: #ded0a6;
background: #fffdf7;
}
.doc-font-head {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: 8px;
}
.doc-font-name {
overflow: hidden;
color: #1f2428;
font-size: 13px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.doc-font-badges {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 4px;
}
.font-badge {
padding: 3px 6px;
background: #eef1f4;
color: var(--text-muted);
font-size: 11px;
line-height: 1.35;
white-space: nowrap;
}
.font-badge.embedded,
.font-badge.matched {
background: #e4f3ef;
color: var(--accent-strong);
}
.font-badge.fallback {
background: #fbefd3;
color: #705719;
}
.font-badge.missing {
background: #f9e8e5;
color: #803f38;
}
.doc-font-detail {
color: var(--text-muted);
font-size: 11px;
line-height: 1.35;
overflow-wrap: anywhere;
}
.font-list {
display: grid;
gap: 8px;
}
.font-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 6px;
padding: 6px;
border: 1px solid var(--line);
background: #ffffff;
}
.font-main {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: 7px;
min-width: 0;
}
.font-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 5px;
min-width: max-content;
}
.font-row input[type="checkbox"] {
width: 16px;
height: 16px;
margin: 0;
accent-color: var(--accent);
}
.font-name-input {
width: 100%;
min-width: 0;
height: 26px;
padding: 0 6px;
border: 1px solid var(--line);
background: #ffffff;
color: #1f2428;
font-size: 12px;
}
.font-source {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 32px;
height: 20px;
padding: 0 6px;
border: 1px solid var(--line);
background: #f8fafb;
color: var(--text-muted);
font-size: 11px;
text-align: center;
white-space: nowrap;
}
.font-toggle {
display: inline-flex;
align-items: center;
gap: 3px;
height: 26px;
color: var(--text-muted);
font-size: 11px;
white-space: nowrap;
}
.font-delete {
display: inline-grid;
place-items: center;
width: 26px;
height: 26px;
padding: 0;
color: #7c3333;
font-size: 18px;
line-height: 1;
}
.font-empty {
padding: 10px;
border: 1px dashed var(--line-strong);
color: var(--text-muted);
font-size: 13px;
text-align: center;
}
body[aria-busy="true"] .viewer-panel {
cursor: progress;
}
.app-footer {
justify-content: space-between;
border-top: 1px solid var(--line);
color: var(--text-muted);
font-size: 12px;
}
.footer-brand {
flex: 0 0 var(--sidebar-width);
font-weight: 400;
color: var(--accent-strong);
text-decoration: none;
}
.status-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
color: var(--text-muted);
line-height: 1.35;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
}
.footer-links {
display: inline-flex;
align-items: center;
gap: 12px;
flex: 0 0 var(--sidebar-width);
justify-content: flex-end;
min-width: 0;
}
.app-footer a {
color: var(--accent-strong);
font-weight: 400;
text-decoration: none;
}
.app-footer a:hover {
text-decoration: underline;
}
@media (max-width: 900px) {
:root {
--sidebar-width: min(78vw, 292px);
}
.toolbar {
flex-wrap: nowrap;
overflow-x: auto;
gap: 6px;
}
.toolbar > * {
flex: 0 0 auto;
}
.toolbar-space {
display: none;
}
.app-footer {
flex-wrap: nowrap;
}
.footer-brand,
.footer-links {
flex: 0 1 auto;
}
.status-text {
text-align: center;
}
.workspace {
position: relative;
grid-template-columns: minmax(0, 1fr);
}
body[data-hide-pages] .workspace,
body[data-hide-meta] .workspace,
body[data-hide-pages][data-hide-meta] .workspace {
grid-template-columns: minmax(0, 1fr);
}
.page-list-panel,
.meta-panel {
position: absolute;
top: 0;
bottom: 0;
z-index: 8;
width: var(--sidebar-width);
box-shadow: 0 16px 32px rgba(31, 36, 40, 0.18);
transition: transform 0.18s ease;
}
body[data-hide-pages] .page-list-panel,
body[data-hide-meta] .meta-panel {
display: block;
}
.page-list-panel {
left: 0;
}
.meta-panel {
right: 0;
}
body[data-hide-pages] .page-list-panel {
transform: translateX(-100%);
pointer-events: none;
}
body[data-hide-meta] .meta-panel {
transform: translateX(100%);
pointer-events: none;
}
}
@media (max-width: 640px) {
:root {
--bar-height: 42px;
--control-height: 28px;
--bar-pad: 5px 8px;
}
.workspace {
grid-template-columns: 1fr;
}
.toolbar {
height: var(--bar-height);
min-height: var(--bar-height);
flex-wrap: nowrap;
align-content: center;
overflow-x: auto;
overflow-y: hidden;
row-gap: 0;
}
.divider {
display: none;
}
.toolbar-space {
display: none;
}
.button {
padding: 0 7px;
}
.button[data-short] {
min-width: var(--control-height);
font-size: 0;
}
.button[data-short]::after {
content: attr(data-short);
font-size: 12px;
font-weight: 500;
}
.button.primary[data-short] {
min-width: 42px;
}
.icon-button {
font-size: 13px;
}
.page-control {
gap: 4px;
padding: 0 6px;
}
.page-control input {
width: 38px;
}
.page-frame {
padding: 22px 14px;
}
.zoom-label {
min-width: 34px;
}
#exportButton {
padding-inline: 8px;
}
.footer-links {
justify-content: flex-end;
}
}
File diff suppressed because it is too large Load Diff
+575
View File
@@ -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;
};
}
}
})();