Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support standard Web APIs in the kernel plugin sandbox https://github.com/siyuan-note/siyuan/issues/20118

Yingyi / 颖逸2d0a77e73858
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 83bea8b33b..0e9a15b366 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2578,7 +2578,7 @@ export interface APIGETRoutes {
response: Blob | JSONValue | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "raw";
output: "pluginService";
- pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
+ pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"stream","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
};
"/ws/broadcast": {
request: EmptyRequestInput;
@@ -5942,7 +5942,7 @@ export interface APIPOSTRoutes {
response: Blob | JSONValue | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "raw";
output: "pluginService";
- pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
+ pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"stream","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
};
}
diff --git a/kernel/apicontract/plugin_service_protocol.go b/kernel/apicontract/plugin_service_protocol.go
index 974c5761f8..ad9c05c9d0 100644
--- a/kernel/apicontract/plugin_service_protocol.go
+++ b/kernel/apicontract/plugin_service_protocol.go
@@ -32,6 +32,7 @@ const (
PluginServiceFile PluginServiceMode = "file"
PluginServiceString PluginServiceMode = "string"
PluginServiceRaw PluginServiceMode = "raw"
+ PluginServiceStream PluginServiceMode = "stream"
PluginServiceRedirect PluginServiceMode = "redirect"
PluginServiceProxy PluginServiceMode = "proxy"
PluginServiceEmpty PluginServiceMode = "empty"
@@ -74,6 +75,7 @@ func PluginServiceOptions() ResponseOptions {
{PluginServiceFile, "file", []string{"dynamic"}, "bytes", true},
{PluginServiceString, "plugin", []string{"text/plain"}, "text", true},
{PluginServiceRaw, "plugin", []string{"dynamic"}, "bytes", true},
+ {PluginServiceStream, "plugin", []string{"dynamic"}, "bytes", true},
{PluginServiceRedirect, "redirect", []string{"text/html"}, "redirect", true},
{PluginServiceProxy, "proxy", []string{"upstream"}, "bytes", true},
{PluginServiceEmpty, "plugin", []string{"optional"}, "none", true},
diff --git a/kernel/apicontract/plugin_service_protocol_test.go b/kernel/apicontract/plugin_service_protocol_test.go
index 93d78d4f6d..3ca601bae9 100644
--- a/kernel/apicontract/plugin_service_protocol_test.go
+++ b/kernel/apicontract/plugin_service_protocol_test.go
@@ -23,7 +23,7 @@ func TestPluginServiceProtocolVariants(t *testing.T) {
t.Fatalf("incomplete mode declaration: %+v", variant)
}
}
- if len(seen) != 19 {
+ if len(seen) != 20 {
t.Fatal("service modes missing")
}
for _, tt := range []struct {
@@ -51,6 +51,8 @@ func TestPluginServiceProtocolVariants(t *testing.T) {
{PluginServiceSecureJSON, 200, "while(1);[1]", true},
{PluginServiceSecureJSON, 200, "while(1);invalid", false},
{PluginServiceRaw, 999, "\x00\xff", true},
+ {PluginServiceStream, 200, "\x00\xff", true},
+ {PluginServiceStream, 204, "unexpected", false},
{PluginServiceProxy, 404, "upstream error", true},
{PluginServiceEmpty, 200, "", true},
{PluginServiceEmpty, 200, "unexpected", false},
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 8041647d0c..afa6fffffb 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -112986,6 +112986,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -113478,6 +113487,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -115252,6 +115270,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -116093,6 +116120,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -116585,6 +116621,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -117077,6 +117122,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -168793,6 +168847,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -169285,6 +169348,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
@@ -169777,6 +169849,15 @@
"payload": "bytes",
"headersOverrideMedia": true
},
+ {
+ "mode": "stream",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
{
"mode": "redirect",
"statusPolicy": "redirect",
diff --git a/kernel/plugin/abort/abort_test.go b/kernel/plugin/abort/abort_test.go
new file mode 100644
index 0000000000..1c5f299825
--- /dev/null
+++ b/kernel/plugin/abort/abort_test.go
@@ -0,0 +1,326 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package abort
+
+import (
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+)
+
+// abortTestRuntime 启动注入了 AbortController/AbortSignal 的事件循环,提供运行脚本的辅助方法。
+type abortTestRuntime struct {
+ t *testing.T
+ loop *eventloop.EventLoop
+}
+
+func newAbortTestRuntime(t *testing.T) *abortTestRuntime {
+ t.Helper()
+
+ loop := eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ loop.Start()
+ t.Cleanup(func() { loop.Stop() })
+
+ done := make(chan struct{})
+ loop.RunOnLoop(func(rt *goja.Runtime) {
+ defer close(done)
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ Enable(rt)
+ })
+ <-done
+
+ return &abortTestRuntime{t: t, loop: loop}
+}
+
+// run 在事件循环上同步执行脚本并返回结果,脚本出错时直接 Fatal。
+func (r *abortTestRuntime) run(script string) goja.Value {
+ r.t.Helper()
+
+ var value goja.Value
+ var runErr error
+ done := make(chan struct{})
+ r.loop.RunOnLoop(func(rt *goja.Runtime) {
+ defer close(done)
+ value, runErr = rt.RunString(script)
+ })
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ r.t.Fatalf("timed out running script:\n%s", script)
+ }
+ if runErr != nil {
+ r.t.Fatalf("script failed: %v\n%s", runErr, script)
+ }
+ return value
+}
+
+func TestAbortControllerAbort(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const events = [];
+ signal.onabort = () => events.push("onabort");
+ signal.addEventListener("abort", (e) => events.push("listener:" + e.type + ":" + (e.target === signal)));
+
+ const before = [signal.aborted, signal.reason];
+ controller.abort("custom reason");
+ const after = [signal.aborted, signal.reason, signal === controller.signal];
+
+ // 二次调用是幂等的,不会重复触发监听器或覆盖 reason。
+ controller.abort("ignored");
+
+ return JSON.stringify([before, after, events, signal.reason]);
+ })()`)
+ want := `[[false,null],[true,"custom reason",true],["listener:abort:true","onabort"],"custom reason"]`
+ if got.String() != want {
+ t.Fatalf("abort = %s, want %s", got.String(), want)
+ }
+}
+
+// addEventListener 的选项可以是缺少成员的字典或布尔值(以及会被转换为布尔值的其他原始值),缺少的成员按缺省值处理;
+// dispatchEvent 的参数缺少 type 成员时不派发。这些调用都不能让宿主因读取不存在的成员而崩溃。
+func TestAbortSignalListenerOptionDefaults(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ const signal = controller.signal;
+ const events = [];
+ signal.addEventListener("abort", () => events.push("empty"), {});
+ signal.addEventListener("abort", () => events.push("capture"), true);
+ signal.addEventListener("abort", () => events.push("string"), "yes");
+ signal.addEventListener("abort", () => events.push("once"), { once: true });
+ const dispatched = [signal.dispatchEvent({}), signal.dispatchEvent("abort")];
+ events.push("|");
+ controller.abort();
+ events.push("|");
+ signal.dispatchEvent({ type: "abort" });
+ return JSON.stringify([dispatched, events]);
+ })()`)
+ want := `[[true,true],["|","empty","capture","string","once","|","empty","capture","string"]]`
+ if got.String() != want {
+ t.Fatalf("listener options = %s, want %s", got.String(), want)
+ }
+}
+
+func TestAbortSignalDefaultReasonIsAbortError(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ controller.abort();
+ return [controller.signal.reason.name, typeof controller.signal.reason.message].join(",");
+ })()`)
+ if got.String() != "AbortError,string" {
+ t.Fatalf("default reason = %s, want AbortError,string", got.String())
+ }
+}
+
+func TestAbortSignalThrowIfAborted(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ const results = [];
+ try {
+ controller.signal.throwIfAborted();
+ results.push("no throw before abort");
+ } catch (e) {
+ results.push("unexpected throw: " + e);
+ }
+
+ controller.abort("stop");
+ try {
+ controller.signal.throwIfAborted();
+ results.push("no throw after abort");
+ } catch (e) {
+ results.push(e);
+ }
+ return results.join(",");
+ })()`)
+ if got.String() != "no throw before abort,stop" {
+ t.Fatalf("throwIfAborted = %s, want %q", got.String(), "no throw before abort,stop")
+ }
+}
+
+func TestAbortSignalStaticAbort(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const withReason = AbortSignal.abort("boom");
+ const withoutReason = AbortSignal.abort();
+ return [withReason.aborted, withReason.reason, withoutReason.reason.name].join(",");
+ })()`)
+ if got.String() != "true,boom,AbortError" {
+ t.Fatalf("AbortSignal.abort = %s, want true,boom,AbortError", got.String())
+ }
+}
+
+func TestAbortSignalTimeout(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const signal = AbortSignal.timeout(10);
+ const before = signal.aborted;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ return [before, signal.aborted, signal.reason.name].join(",");
+ })()`)
+ if got != "false,true,TimeoutError" {
+ t.Fatalf("AbortSignal.timeout = %s, want false,true,TimeoutError", got)
+ }
+}
+
+func TestAbortSignalAny(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const a = new AbortController();
+ const b = new AbortController();
+ const combined = AbortSignal.any([a.signal, b.signal]);
+ const before = combined.aborted;
+
+ b.abort("b aborted");
+ const after = [combined.aborted, combined.reason];
+
+ // 源信号已中止时,any() 立即返回已中止的信号。
+ const alreadyAborted = AbortSignal.any([a.signal, b.signal]).aborted;
+
+ return JSON.stringify([before, after, alreadyAborted]);
+ })()`)
+ want := `[false,[true,"b aborted"],true]`
+ if got.String() != want {
+ t.Fatalf("AbortSignal.any = %s, want %s", got.String(), want)
+ }
+}
+
+func TestAbortSignalRemoveEventListenerAndOnce(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ const calls = [];
+ const onAbort = () => calls.push("normal");
+ const onceAbort = () => calls.push("once");
+ const removed = () => calls.push("removed");
+
+ controller.signal.addEventListener("abort", onAbort);
+ controller.signal.addEventListener("abort", onceAbort, {once: true});
+ controller.signal.addEventListener("abort", removed);
+ controller.signal.removeEventListener("abort", removed);
+ // 重复添加同一个监听器是幂等的。
+ controller.signal.addEventListener("abort", onAbort);
+
+ controller.abort();
+ controller.signal.dispatchEvent({type: "abort"});
+
+ return calls.join(",");
+ })()`)
+ // 第一次 abort() 触发一次(once 监听器随之移除),之后手动 dispatchEvent 只剩普通监听器再触发一次。
+ if want := "normal,once,normal"; got.String() != want {
+ t.Fatalf("listeners = %s, want %s", got.String(), want)
+ }
+}
+
+func TestAbortSignalRejectsIncompatibleReceiver(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const results = [];
+ for (const fn of [
+ () => AbortSignal.prototype.aborted,
+ () => Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get.call({}),
+ () => AbortController.prototype.abort.call({}),
+ ]) {
+ try {
+ fn();
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name);
+ }
+ }
+ return results.join(",");
+ })()`)
+ if want := "TypeError,TypeError,TypeError"; got.String() != want {
+ t.Fatalf("incompatible receiver = %s, want %s", got.String(), want)
+ }
+}
+
+func TestAbortSignalInstanceofAndIllegalConstructor(t *testing.T) {
+ rt := newAbortTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const controller = new AbortController();
+ const results = [
+ controller.signal instanceof AbortSignal,
+ controller instanceof AbortController,
+ Object.prototype.toString.call(controller.signal),
+ Object.prototype.toString.call(controller),
+ ];
+ try {
+ new AbortSignal();
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name + ":" + e.message);
+ }
+ return JSON.stringify(results);
+ })()`)
+ want := `[true,true,"[object AbortSignal]","[object AbortController]","TypeError:Illegal constructor"]`
+ if got.String() != want {
+ t.Fatalf("instanceof/illegal constructor = %s, want %s", got.String(), want)
+ }
+}
+
+// await 执行一段返回 Promise 的异步脚本,等待其完成后返回结果的字符串形式;被拒绝时以 "rejected:" 开头。
+func (r *abortTestRuntime) await(script string) string {
+ r.t.Helper()
+
+ result := make(chan string, 1)
+ r.loop.RunOnLoop(func(rt *goja.Runtime) {
+ value, err := rt.RunString(script)
+ if err != nil {
+ r.t.Fatalf("script failed: %v\n%s", err, script)
+ return
+ }
+ promiseObj := value.ToObject(rt)
+ then, ok := goja.AssertFunction(promiseObj.Get("then"))
+ if !ok {
+ r.t.Fatalf("script did not return a promise:\n%s", script)
+ return
+ }
+ if _, err := then(promiseObj, rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- call.Argument(0).String()
+ return goja.Undefined()
+ }), rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- "rejected:" + call.Argument(0).String()
+ return goja.Undefined()
+ })); err != nil {
+ r.t.Fatalf("promise.then: %v", err)
+ }
+ })
+
+ select {
+ case got := <-result:
+ return got
+ case <-time.After(5 * time.Second):
+ r.t.Fatalf("timed out waiting for:\n%s", script)
+ return ""
+ }
+}
diff --git a/kernel/plugin/abort/controller.go b/kernel/plugin/abort/controller.go
new file mode 100644
index 0000000000..e2287b61a5
--- /dev/null
+++ b/kernel/plugin/abort/controller.go
@@ -0,0 +1,370 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package abort
+
+import (
+ "fmt"
+ "reflect"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+)
+
+// controllerState 是 AbortController 的宿主对象实现:自身不暴露任何属性,signal/abort 由共享原型上的访问器与方法提供。
+type controllerState struct {
+ signal *SignalState
+}
+
+func (c *controllerState) Get(string) goja.Value { return nil }
+func (c *controllerState) Set(string, goja.Value) bool { return false }
+func (c *controllerState) Has(string) bool { return false }
+func (c *controllerState) Delete(string) bool { return false }
+func (c *controllerState) Keys() []string { return nil }
+
+// controllerStateType 用于在 Object.Export() 前用 Object.ExportType() 做判定,原因见 signalStateType
+// 的注释:AbortController.prototype 本身作为 receiver 时,直接 Export() 会因 signal 访问器无限递归。
+var controllerStateType = reflect.TypeOf((*controllerState)(nil))
+
+// Enable 把 AbortController 与 AbortSignal 挂到 runtime 的 globalThis,调用方式与
+// url、buffer、console、encoding 一致,失败时 panic。
+//
+// 与规范的已知差异(与本沙箱其它构造函数一致):实例不是 AbortController/AbortSignal 的真正
+// ECMAScript 类,不用 new 直接调用 AbortController 也不会抛错(goja 的原生构造函数无法区分两种调用);
+// AbortSignal 与规范一致,无论是否使用 new 都抛出 TypeError: Illegal constructor。
+// addEventListener 的 options 只支持 {once},capture/passive/signal 会被静默忽略。
+func Enable(rt *goja.Runtime) {
+ if err := register(rt); err != nil {
+ panic(err)
+ }
+}
+
+// register 构造并挂载 AbortController 与 AbortSignal。
+func register(rt *goja.Runtime) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("abort.Enable: %v", r)
+ }
+ }()
+
+ signalPrototype := lo.Must(newSignalPrototype(rt))
+ signalCtor := lo.Must(newSignalConstructor(rt, signalPrototype))
+ lo.Must0(rt.Set("AbortSignal", signalCtor))
+
+ controllerPrototype := lo.Must(newControllerPrototype(rt, signalCtor))
+ controllerCtor := newControllerConstructor(rt, controllerPrototype, signalCtor)
+ lo.Must0(rt.Set("AbortController", controllerCtor))
+ return
+}
+
+// newSignalObject 创建一个包装给定状态的 AbortSignal 对象,并绑定到共享原型。
+func newSignalObject(rt *goja.Runtime, prototype *goja.Object, state *SignalState) *goja.Object {
+ object := rt.NewDynamicObject(state)
+ lo.Must0(object.SetPrototype(prototype))
+ state.self = object
+ return object
+}
+
+// newSignalConstructor 构造 AbortSignal 全局构造函数及其静态方法 abort/timeout/any。
+func newSignalConstructor(rt *goja.Runtime, prototype *goja.Object) (*goja.Object, error) {
+ ctor := rt.ToValue(func(call goja.ConstructorCall) *goja.Object {
+ panic(rt.NewTypeError("Illegal constructor"))
+ }).(*goja.Object)
+
+ if err := ctor.Set("prototype", prototype); err != nil {
+ return nil, err
+ }
+ if err := prototype.Set("constructor", ctor); err != nil {
+ return nil, err
+ }
+
+ // AbortSignal.abort(reason?) -> 返回一个已经中止的新信号。
+ if err := ctor.Set("abort", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ state := &SignalState{}
+ object := newSignalObject(rt, prototype, state)
+ reason := call.Argument(0)
+ if goja.IsUndefined(reason) {
+ reason = nil // 让 triggerAbort 套用默认的 AbortError
+ }
+ state.triggerAbort(rt, reason)
+ return object
+ })); err != nil {
+ return nil, err
+ }
+
+ // AbortSignal.timeout(milliseconds) -> 到时后以 TimeoutError 中止的新信号。
+ if err := ctor.Set("timeout", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ milliseconds := call.Argument(0).ToInteger()
+ if milliseconds < 0 {
+ milliseconds = 0
+ }
+
+ state := &SignalState{}
+ object := newSignalObject(rt, prototype, state)
+
+ setTimeout, ok := goja.AssertFunction(rt.GlobalObject().Get("setTimeout"))
+ if !ok {
+ panic(rt.NewTypeError("globalThis.setTimeout is not available"))
+ }
+ if _, err := setTimeout(goja.Undefined(), rt.ToValue(func(goja.FunctionCall) goja.Value {
+ state.triggerAbort(rt, newSignalError(rt, "TimeoutError", "signal timed out"))
+ return goja.Undefined()
+ }), rt.ToValue(milliseconds)); err != nil {
+ panic(err)
+ }
+ return object
+ })); err != nil {
+ return nil, err
+ }
+
+ // AbortSignal.any(signals) -> 任一源信号中止时跟随中止的新信号;源信号已中止则立即中止。
+ if err := ctor.Set("any", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ sources := signalArrayOf(rt, call.Argument(0))
+
+ state := &SignalState{}
+ object := newSignalObject(rt, prototype, state)
+
+ for _, source := range sources {
+ if source.aborted {
+ state.triggerAbort(rt, source.reason)
+ break
+ }
+ }
+ if !state.aborted {
+ for _, source := range sources {
+ source.dependents = append(source.dependents, state)
+ }
+ }
+ return object
+ })); err != nil {
+ return nil, err
+ }
+
+ return ctor, nil
+}
+
+// signalArrayOf 读取 AbortSignal.any() 的 signals 参数:接受数组,数组之外的可迭代对象未支持。
+func signalArrayOf(rt *goja.Runtime, value goja.Value) []*SignalState {
+ if !isJsArray(rt, value) {
+ panic(rt.NewTypeError("signals must be an array of AbortSignal"))
+ }
+ object := value.ToObject(rt)
+ length := int64(object.Get("length").ToInteger())
+
+ states := make([]*SignalState, 0, length)
+ for i := int64(0); i < length; i++ {
+ state, err := SignalOf(rt, object.Get(fmt.Sprint(i)), fmt.Sprintf("signals[%d]", i))
+ if err != nil {
+ panic(rt.NewTypeError(err.Error()))
+ }
+ states = append(states, state)
+ }
+ return states
+}
+
+// newSignalPrototype 构造 AbortSignal.prototype:aborted/reason/onabort 访问器,
+// throwIfAborted、addEventListener、removeEventListener、dispatchEvent 方法。
+func newSignalPrototype(rt *goja.Runtime) (*goja.Object, error) {
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *SignalState {
+ state, err := SignalOf(rt, call.This, "this")
+ if err != nil {
+ panic(rt.NewTypeError("AbortSignal.prototype.%s called on an incompatible receiver", method))
+ }
+ return state
+ }
+
+ accessor := func(name string, get func(*SignalState) goja.Value) error {
+ getter := rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ return get(self(call, name))
+ })
+ return prototype.DefineAccessorProperty(name, getter, nil, goja.FLAG_TRUE, goja.FLAG_TRUE)
+ }
+
+ if err := accessor("aborted", func(s *SignalState) goja.Value { return rt.ToValue(s.aborted) }); err != nil {
+ return nil, err
+ }
+ if err := accessor("reason", func(s *SignalState) goja.Value {
+ if s.reason == nil {
+ return goja.Undefined()
+ }
+ return s.reason
+ }); err != nil {
+ return nil, err
+ }
+
+ onabortGetter := rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "onabort")
+ if s.onabort == nil {
+ return goja.Null()
+ }
+ return s.onabort
+ })
+ onabortSetter := rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "onabort")
+ handler := call.Argument(0)
+ if _, ok := goja.AssertFunction(handler); ok {
+ s.onabort = handler
+ } else {
+ s.onabort = nil
+ }
+ return goja.Undefined()
+ })
+ if err := prototype.DefineAccessorProperty("onabort", onabortGetter, onabortSetter, goja.FLAG_TRUE, goja.FLAG_TRUE); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.Set("throwIfAborted", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "throwIfAborted")
+ if s.aborted {
+ panic(s.reason)
+ }
+ return goja.Undefined()
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.Set("addEventListener", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "addEventListener")
+ if call.Argument(0).String() != "abort" {
+ return goja.Undefined()
+ }
+ callback := call.Argument(1)
+ if !isJsValueNotNull(callback) {
+ return goja.Undefined()
+ }
+
+ once := false
+ if options := call.Argument(2); isJsValueNotNull(options) {
+ if optionsObj := options.ToObject(rt); optionsObj != nil {
+ if value := dictMember(optionsObj, "once"); value != nil {
+ once = value.ToBoolean()
+ }
+ }
+ }
+
+ for _, existing := range s.listeners {
+ if existing.callback.SameAs(callback) {
+ return goja.Undefined()
+ }
+ }
+ s.listeners = append(s.listeners, signalListener{callback: callback, once: once})
+ return goja.Undefined()
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.Set("removeEventListener", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "removeEventListener")
+ if call.Argument(0).String() != "abort" {
+ return goja.Undefined()
+ }
+ callback := call.Argument(1)
+
+ remaining := make([]signalListener, 0, len(s.listeners))
+ for _, existing := range s.listeners {
+ if !existing.callback.SameAs(callback) {
+ remaining = append(remaining, existing)
+ }
+ }
+ s.listeners = remaining
+ return goja.Undefined()
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.Set("dispatchEvent", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ s := self(call, "dispatchEvent")
+ eventType := ""
+ if event := call.Argument(0); isJsValueNotNull(event) {
+ if eventObj := event.ToObject(rt); eventObj != nil {
+ if value := dictMember(eventObj, "type"); value != nil {
+ eventType = value.String()
+ }
+ }
+ }
+ if eventType == "abort" {
+ s.dispatchAbortEvent(rt)
+ }
+ return rt.ToValue(true)
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.DefineDataPropertySymbol(goja.SymToStringTag, rt.ToValue("AbortSignal"),
+ goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE); err != nil {
+ return nil, err
+ }
+ return prototype, nil
+}
+
+// newControllerConstructor 构造 AbortController 全局构造函数。
+func newControllerConstructor(rt *goja.Runtime, prototype *goja.Object, signalCtor *goja.Object) *goja.Object {
+ signalPrototype := signalCtor.Get("prototype").ToObject(rt)
+
+ ctor := rt.ToValue(func(call goja.ConstructorCall) *goja.Object {
+ signalState := &SignalState{}
+ newSignalObject(rt, signalPrototype, signalState)
+
+ state := &controllerState{signal: signalState}
+ object := rt.NewDynamicObject(state)
+ lo.Must0(object.SetPrototype(call.This.Prototype()))
+ return object
+ }).(*goja.Object)
+
+ lo.Must0(ctor.Set("prototype", prototype))
+ lo.Must0(prototype.Set("constructor", ctor))
+ return ctor
+}
+
+// newControllerPrototype 构造 AbortController.prototype:signal 访问器与 abort 方法。
+func newControllerPrototype(rt *goja.Runtime, signalCtor *goja.Object) (*goja.Object, error) {
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *controllerState {
+ if call.This != nil {
+ if object := call.This.ToObject(rt); object != nil && object.ExportType() == controllerStateType {
+ if state, ok := object.Export().(*controllerState); ok {
+ return state
+ }
+ }
+ }
+ panic(rt.NewTypeError("AbortController.prototype.%s called on an incompatible receiver", method))
+ }
+
+ getter := rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ state := self(call, "signal")
+ return state.signal.self
+ })
+ if err := prototype.DefineAccessorProperty("signal", getter, nil, goja.FLAG_TRUE, goja.FLAG_TRUE); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.Set("abort", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ state := self(call, "abort")
+ state.signal.triggerAbort(rt, call.Argument(0))
+ return goja.Undefined()
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := prototype.DefineDataPropertySymbol(goja.SymToStringTag, rt.ToValue("AbortController"),
+ goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE); err != nil {
+ return nil, err
+ }
+ return prototype, nil
+}
diff --git a/kernel/plugin/abort/signal.go b/kernel/plugin/abort/signal.go
new file mode 100644
index 0000000000..e769b24a96
--- /dev/null
+++ b/kernel/plugin/abort/signal.go
@@ -0,0 +1,206 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package abort
+
+import (
+ "fmt"
+ "reflect"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+)
+
+// signalStateType 是 SignalState 指针的反射类型:SignalOf 在调用 Object.Export() 前先用
+// Object.ExportType() 判定接收者是否为本包创建的 AbortSignal。ExportType() 对普通对象返回固定的 map 类型、
+// 对动态对象返回宿主类型,都不会访问任何属性;而 Object.Export() 对普通对象会遍历其所有自有可枚举属性并调用
+// 它们的访问器:当接收者是 AbortSignal.prototype 本身时(aborted 等访问器就定义在它自己身上),直接 Export()
+// 会再次进入这些访问器而无限递归,因此必须先用 ExportType() 过滤。
+var signalStateType = reflect.TypeOf((*SignalState)(nil))
+
+// signalListener 是 addEventListener("abort", ...) 登记的一个监听器。
+type signalListener struct {
+ callback goja.Value // 可调用值,或带 handleEvent 方法的对象
+ once bool
+}
+
+// SignalState 是 AbortSignal 的宿主对象实现:自身不暴露任何属性,属性由共享原型上的访问器提供
+// (与 CryptoKey 一致),因此 Object.keys()/JSON.stringify() 的结果与浏览器一致。
+// 除下面说明的 reason 外,所有字段只在事件循环线程上读写(JS 调用、setTimeout 回调都运行在循环线程),
+// 因此不需要加锁。唯一的跨线程访问是 reason:goHooks 的回调可能在取消请求的 goroutine 上执行,随后该
+// goroutine 会读取 reason 作为 Promise 的拒绝原因;triggerAbort 在调用 goHooks 之前就写入 reason 且此后再不修改,
+// 配合调用方以原子变量记录回调是否已触发,这一读取是安全的(见 siyuan.client.fetch 的 abortHookFired)。
+// goHooks 回调自身(例如 context.CancelFunc)由调用方保证并发安全。
+type SignalState struct {
+ self *goja.Object // 包装自身的 JS 对象,构造后立即回填,用于派发事件时作为 target
+
+ aborted bool
+ reason goja.Value
+
+ onabort goja.Value // EventHandler:null 或可调用值
+ listeners []signalListener
+
+ // goHooks 在 triggerAbort 时按注册顺序同步调用一次,用于让 Go 侧(如 siyuan.client.fetch)
+ // 在中止发生的瞬间收到通知;调用点必须在事件循环线程上完成注册,因为可能需要立即触发。
+ goHooks []func()
+
+ // dependents 是通过 AbortSignal.any() 以当前信号为源创建的下游信号,中止时按序传播。
+ dependents []*SignalState
+}
+
+func (s *SignalState) Get(string) goja.Value { return nil }
+func (s *SignalState) Set(string, goja.Value) bool { return false }
+func (s *SignalState) Has(string) bool { return false }
+func (s *SignalState) Delete(string) bool { return false }
+func (s *SignalState) Keys() []string { return nil }
+
+// triggerAbort 执行中止流程:仅在尚未中止时生效,设置 aborted/reason,依次调用 Go 回调、
+// onabort 与 addEventListener 注册的监听器,并将中止传播给依赖信号。
+func (s *SignalState) triggerAbort(rt *goja.Runtime, reason goja.Value) {
+ if s.aborted {
+ return
+ }
+ s.aborted = true
+ if reason == nil || goja.IsUndefined(reason) {
+ reason = newSignalError(rt, "AbortError", "signal is aborted without reason")
+ }
+ s.reason = reason
+
+ hooks := s.goHooks
+ s.goHooks = nil
+ for _, hook := range hooks {
+ hook()
+ }
+
+ s.dispatchAbortEvent(rt)
+
+ dependents := s.dependents
+ s.dependents = nil
+ for _, dependent := range dependents {
+ dependent.triggerAbort(rt, s.reason)
+ }
+}
+
+// dispatchAbortEvent 构造一个 type 为 "abort" 的事件对象,依次调用通过 addEventListener 登记的
+// 监听器与 onabort;异常只记录日志,不中断后续监听器与依赖信号的通知。
+func (s *SignalState) dispatchAbortEvent(rt *goja.Runtime) {
+ event := newAbortEvent(rt, s.self)
+
+ invoke := func(callback goja.Value) {
+ if callback == nil || goja.IsUndefined(callback) || goja.IsNull(callback) {
+ return
+ }
+ if fn, ok := goja.AssertFunction(callback); ok {
+ if _, err := fn(s.self, event); err != nil {
+ logging.LogErrorf("AbortSignal abort listener: %v", err)
+ }
+ return
+ }
+ if obj := callback.ToObject(rt); obj != nil {
+ if fn, ok := goja.AssertFunction(obj.Get("handleEvent")); ok {
+ if _, err := fn(obj, event); err != nil {
+ logging.LogErrorf("AbortSignal abort listener: %v", err)
+ }
+ }
+ }
+ }
+
+ // 登记时拷贝一份快照:触发中的监听器删除自身(once)或新增监听器都不应影响本轮派发。
+ listeners := s.listeners
+ remaining := make([]signalListener, 0, len(listeners))
+ for _, listener := range listeners {
+ invoke(listener.callback)
+ if !listener.once {
+ remaining = append(remaining, listener)
+ }
+ }
+ s.listeners = remaining
+
+ invoke(s.onabort)
+}
+
+// Aborted 返回信号是否已经中止。调用方必须在事件循环线程上调用本方法。
+func (s *SignalState) Aborted() bool {
+ return s.aborted
+}
+
+// Reason 返回中止原因,信号尚未中止时为 nil。应在事件循环线程上调用;唯一的例外见 SignalState 的文档:
+// AddAbortHook 登记的回调触发之后,其他 goroutine 也可以安全读取。
+func (s *SignalState) Reason() goja.Value {
+ return s.reason
+}
+
+// AddAbortHook 登记一个中止时在事件循环线程调用一次的 Go 回调;若信号已经中止,立即调用。
+// 调用方必须在事件循环线程上调用本方法。
+func (s *SignalState) AddAbortHook(hook func()) {
+ if s.aborted {
+ hook()
+ return
+ }
+ s.goHooks = append(s.goHooks, hook)
+}
+
+// newSignalError 构造一个 name 为给定值的 Error,供未显式提供 reason 时使用。
+// 沙箱没有 DOMException,约定与 globalThis.crypto 一致:用普通 Error 并覆盖 name 属性,
+// 调用方应按 error.name 分支而不是 instanceof 判断。
+func newSignalError(rt *goja.Runtime, name, message string) goja.Value {
+ err := rt.NewGoError(fmt.Errorf("%s", message))
+ if setErr := err.Set("name", rt.ToValue(name)); setErr != nil {
+ logging.LogErrorf("newSignalError: set name: %v", setErr)
+ }
+ return err
+}
+
+// newAbortEvent 构造派发给 abort 监听器的事件对象。字段与方法参照 DOM Event,但本身是一个冻结的
+// 普通对象,不是 Event 的实例;AbortSignal 的 abort 事件从不冒泡、不可取消,因此传播相关方法均为空操作。
+func newAbortEvent(rt *goja.Runtime, target *goja.Object) *goja.Object {
+ event := rt.NewObject()
+ noop := rt.ToValue(func(goja.FunctionCall) goja.Value { return goja.Undefined() })
+
+ lo.Must0(event.Set("type", rt.ToValue("abort")))
+ lo.Must0(event.Set("target", target))
+ lo.Must0(event.Set("currentTarget", target))
+ lo.Must0(event.Set("bubbles", rt.ToValue(false)))
+ lo.Must0(event.Set("cancelable", rt.ToValue(false)))
+ lo.Must0(event.Set("composed", rt.ToValue(false)))
+ lo.Must0(event.Set("defaultPrevented", rt.ToValue(false)))
+ lo.Must0(event.Set("isTrusted", rt.ToValue(true)))
+ lo.Must0(event.Set("timeStamp", rt.ToValue(float64(time.Now().UnixMilli()))))
+ lo.Must0(event.Set("preventDefault", noop))
+ lo.Must0(event.Set("stopPropagation", noop))
+ lo.Must0(event.Set("stopImmediatePropagation", noop))
+
+ lo.Must0(objectFreeze(rt, event))
+ return event
+}
+
+// SignalOf 从 JS 值取出 AbortSignal 的宿主状态,只接受由本包创建的 AbortSignal 对象。
+func SignalOf(rt *goja.Runtime, value goja.Value, name string) (*SignalState, error) {
+ if !isJsValueNotNull(value) {
+ return nil, fmt.Errorf("%s must be an AbortSignal", name)
+ }
+ object := value.ToObject(rt)
+ if object == nil || object.ExportType() != signalStateType {
+ return nil, fmt.Errorf("%s must be an AbortSignal", name)
+ }
+ state, ok := object.Export().(*SignalState)
+ if !ok {
+ return nil, fmt.Errorf("%s must be an AbortSignal", name)
+ }
+ return state, nil
+}
diff --git a/kernel/plugin/abort/util.go b/kernel/plugin/abort/util.go
new file mode 100644
index 0000000000..acc69898e8
--- /dev/null
+++ b/kernel/plugin/abort/util.go
@@ -0,0 +1,87 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package abort
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+)
+
+// isJsValueNotUndefined、isJsValueNotNull、isJsArray、isJsObjectArray 与 objectFreeze 分别与 kernel/plugin/sandbox.go
+// 的同名函数及 ObjectFreeze 同构:本包不依赖 plugin 包,避免循环依赖,因此复制一份这些通用、不含业务逻辑的辅助。
+
+func isJsValueNotUndefined(jsValue goja.Value) bool {
+ return jsValue != nil && !goja.IsUndefined(jsValue)
+}
+
+func isJsValueNotNull(jsValue goja.Value) bool {
+ return isJsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)
+}
+
+func isJsArray(rt *goja.Runtime, jsValue goja.Value) bool {
+ if jsValue == nil {
+ return false
+ }
+
+ if goja.IsUndefined(jsValue) || goja.IsNull(jsValue) {
+ return false
+ }
+
+ jsObject := jsValue.ToObject(rt)
+ return isJsObjectArray(jsObject)
+}
+
+func isJsObjectArray(jsObject *goja.Object) bool {
+ if jsObject == nil {
+ return false
+ }
+
+ switch jsObject.ClassName() {
+ case "Array":
+ return true
+ default:
+ return false
+ }
+}
+
+// dictMember 读取字典对象 object 上名为 name 的成员,缺失或为 undefined 时返回 nil;调用方据此套用默认值,
+// 不能直接对 Get 的结果调用 ToBoolean/String 等方法——goja 的 Get 在属性不存在时返回 Go 的 nil(不是脚本
+// 意义上的 undefined 值),对 nil 调用这些方法会触发 nil 指针解引用而不是产生一个"假值"。
+func dictMember(object *goja.Object, name string) goja.Value {
+ value := object.Get(name)
+ if value == nil || goja.IsUndefined(value) {
+ return nil
+ }
+ return value
+}
+
+// objectFreeze 调用 Object.freeze()。
+func objectFreeze(rt *goja.Runtime, obj *goja.Object) error {
+ Object := rt.GlobalObject().Get("Object").ToObject(rt)
+ if Object == nil {
+ return fmt.Errorf("globalThis.Object is not an object")
+ }
+
+ freeze, ok := goja.AssertFunction(Object.Get("freeze"))
+ if !ok {
+ return fmt.Errorf("globalThis.Object.freeze is not a function")
+ }
+
+ _, err := freeze(Object, obj)
+ return err
+}
diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.go
index 726ef5e32e..59c03d9e90 100644
--- a/kernel/plugin/api_client.go
+++ b/kernel/plugin/api_client.go
@@ -30,11 +30,14 @@ import (
"time"
"github.com/dop251/goja"
+ "github.com/imroc/req/v3"
"github.com/lxzan/gws"
sse "github.com/r3labs/sse/v2"
"github.com/samber/lo"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/plugin/abort"
+ "github.com/siyuan-note/siyuan/kernel/plugin/formdata"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -57,7 +60,9 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
headers := map[string]string{}
var bodyString *string
var bodyBytes *[]byte
- timeout := fetchDefaultTimeout
+ var bodyContentType string // 请求体自带的媒体类型(如 FormData 的 multipart boundary),调用方未显式设置 Content-Type 时使用
+ timeout := fetchDefaultTimeout // 只约束到收到响应头为止,不覆盖读取响应体的过程,与浏览器 fetch 的 timeout/signal 分离语义一致
+ var signal *abort.SignalState
if goja.IsString(call.Argument(0)) {
path = call.Argument(0).String()
@@ -84,6 +89,11 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
if b := initObj.Get("body"); isJsValueNotNull(b) {
if goja.IsString(b) {
bodyString = new(b.String())
+ } else if formData, ok := formdata.StateOf(b); ok {
+ // 在调用时完成编码,之后对 FormData 的修改不影响本次请求(与 fetch 规范一致)。
+ body, contentType := formData.EncodeMultipart()
+ bodyBytes = &body
+ bodyContentType = contentType
} else {
body := b.Export()
if arrayBuffer, ok := body.(goja.ArrayBuffer); ok {
@@ -99,6 +109,12 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
timeout, argErr = fetchTimeoutOf(t)
}
}
+
+ if argErr == nil {
+ if s := initObj.Get("signal"); isJsValueNotNull(s) {
+ signal, argErr = abort.SignalOf(rt, s, "signal")
+ }
+ }
}
}
}
@@ -109,38 +125,76 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
return
}
+ // 请求发出前 signal 已经中止:不发送请求,直接以 reason reject。
+ if signal != nil && signal.Aborted() {
+ if rejectErr := reject(signal.Reason()); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ return
+ }
+
+ // 以插件上下文为父上下文,使插件停止时取消未完成的请求(包括之后读取响应体的过程);signal 中止时
+ // 额外取消。timeout 改由下面的计时器手动驱动,只在收到响应头之前触发一次取消,收到响应头后计时器
+ // 被停掉,ctx 之后只受插件停止与 signal 中止约束,不再因为 timeout 打断正在读取的响应体。
+ ctx, cancel := context.WithCancel(p.context)
+
+ var timedOut atomic.Bool
+ var timeoutTimer *time.Timer
+ if timeout > 0 {
+ timeoutTimer = time.AfterFunc(timeout, func() {
+ timedOut.Store(true)
+ cancel()
+ })
+ }
+
+ // abortHookFired 记录取消是否来自 signal 中止,与超时、插件停止等其他取消来源区开;
+ // 依赖 Store/Load 建立的 happens-before 关系,该标记为 true 之后再读取 signal.Reason() 是安全的
+ // (triggerAbort 在调用 goHooks 前已写入 reason,且其后不再修改)。
+ var abortHookFired atomic.Bool
+ if signal != nil {
+ signal.AddAbortHook(func() {
+ abortHookFired.Store(true)
+ cancel()
+ })
+ }
+
+ rejectWith := func(reason goja.Value, err error) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if reason == nil {
+ reason = rt.NewGoError(err)
+ }
+ if rejectErr := reject(reason); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ return
+ }, nil)
+ }
+
go func() {
var err error
+ var rejectReason goja.Value // 中止时改用它而不是 err(包装成 Error)进行 reject,reason 可以是任意值
+
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic during siyuan.client.fetch: %v", r)
+ rejectReason = nil
}
-
- if err != nil {
- p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
- if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
- logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
- }
- return
- }, nil)
+ if err != nil || rejectReason != nil {
+ cancel() // 请求失败或被中止,没有响应体需要保留,直接释放 ctx
+ rejectWith(rejectReason, err)
}
}()
- // 以插件上下文为父上下文,使插件停止时取消未完成的请求。
- var ctx context.Context
- var cancel context.CancelFunc
- if timeout > 0 {
- ctx, cancel = context.WithTimeout(p.context, timeout)
- } else {
- ctx, cancel = context.WithCancel(p.context)
- }
- defer cancel()
-
targetURL := fmt.Sprintf("http://127.0.0.1:%s%s", util.ServerPort, path)
- r := httpClient.R().SetContext(ctx)
+ // 禁用自动读取响应体:Send 只负责等到响应头,响应体留给 response.body/text() 等按需读取,
+ // 从而让 fetch() 的 Promise 在收到响应头时就 resolve,不必等整个响应体传完。
+ r := httpClient.R().SetContext(ctx).DisableAutoReadResponse()
for k, v := range headers {
r.SetHeader(k, v)
}
+ if bodyContentType != "" && r.Headers.Get("Content-Type") == "" {
+ r.SetHeader("Content-Type", bodyContentType)
+ }
r.SetHeader(model.XAuthTokenKey, p.token)
if bodyString != nil {
@@ -149,28 +203,28 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
r.SetBody(*bodyBytes)
}
- // req 在 Send 内读完响应体,因此读取响应体时超时也会在这里返回。
resp, sendErr := r.Send(method, targetURL)
+ if timeoutTimer != nil {
+ timeoutTimer.Stop() // 响应头已经到达(或者发送已经失败),此后不再因为 timeout 取消 ctx
+ }
if sendErr != nil {
+ if abortHookFired.Load() {
+ rejectReason = signal.Reason()
+ return
+ }
err = sendErr
- if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ if timedOut.Load() {
err = fmt.Errorf("request timed out after %s: %w", timeout, sendErr)
}
return
}
- defer resp.Body.Close()
- body, readErr := io.ReadAll(resp.Body)
- if readErr != nil {
- err = fmt.Errorf("failed to read response body: %w", readErr)
- return
- }
-
responseHeader := map[string]string{}
for k, vs := range resp.Header {
responseHeader[k] = strings.Join(vs, ", ")
}
+ body := &fetchResponseBody{resp: resp, cancel: cancel}
runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
response := rt.NewObject()
lo.Must0(response.Set("url", rt.ToValue(path)))
@@ -178,7 +232,10 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
lo.Must0(response.Set("status", rt.ToValue(resp.StatusCode)))
lo.Must0(response.Set("statusText", rt.ToValue(resp.Status)))
lo.Must0(response.Set("headers", rt.ToValue(responseHeader)))
- lo.Must0(ObjectSetDataMethods(p, rt, response, body))
+ if setErr := setFetchResponseBodyMethods(p, rt, response, body); setErr != nil {
+ err = setErr
+ return
+ }
result = response
return
}, func(rt *goja.Runtime, result any, err error) {
@@ -187,6 +244,7 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
logging.LogErrorf("[plugin:%s] siyuan.client.fetch resolve: %v", p.Name, resolveErr)
}
} else {
+ cancel()
if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
}
@@ -826,3 +884,225 @@ func fetchTimeoutOf(value goja.Value) (timeout time.Duration, err error) {
timeout = time.Duration(nanoseconds)
return
}
+
+// fetchStreamChunkSize 是 siyuan.client.fetch 流式读取响应体时每次向底层连接请求的字节数。
+const fetchStreamChunkSize = 32 * 1024
+
+// fetchResponseBody 管理一次 fetch 响应体的消费:response.body 的 ReadableStream 与 text()/json()/buffer()/
+// arrayBuffer()/bytes()/blob() 共享同一个只能读一次的底层字节源(resp.Body),哪个先开始读就"认领"它,
+// 其余路径都会得到"响应体已经被读取"的错误——与真实 fetch 的 bodyUsed 语义一致,而不是像本沙箱其它数据对象
+// 那样允许反复调用:响应体现在是真正流式到达、边读边释放的,不会先整体缓存一份供多次读取。claimed 只在
+// 事件循环线程上读写,不需要加锁。
+type fetchResponseBody struct {
+ resp *req.Response
+ cancel context.CancelFunc
+ claimed bool
+}
+
+// claim 第一次调用时把 claimed 置真并返回 true;此后调用返回 false。
+func (b *fetchResponseBody) claim() bool {
+ if b.claimed {
+ return false
+ }
+ b.claimed = true
+ return true
+}
+
+// finish 关闭底层连接并释放请求的 ctx;body 读完、出错或被取消后都应该调用一次。
+func (b *fetchResponseBody) finish() {
+ b.resp.Body.Close()
+ b.cancel()
+}
+
+// setFetchResponseBodyMethods 给 fetch 的响应对象设置 body 属性与 text()/json()/buffer()/arrayBuffer()/
+// bytes()/blob() 方法。body 是一个按需、分块读取 resp.Body 的 ReadableStream<Uint8Array>;六个数据方法里
+// 最先被调用的一个会把响应体整体读入内存后再转换成对应形式,和 body 的流式读取互斥,谁先开始读谁赢。
+func setFetchResponseBodyMethods(p *KernelPlugin, rt *goja.Runtime, response *goja.Object, body *fetchResponseBody) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("setFetchResponseBodyMethods: %v", r)
+ }
+ }()
+
+ lo.Must0(response.Set("body", newFetchResponseBodyStream(p, rt, body)))
+
+ contentType := body.resp.Header.Get("Content-Type")
+ for _, name := range []string{"text", "json", "buffer", "arrayBuffer", "bytes", "blob"} {
+ methodName := name
+ lo.Must0(response.Set(methodName, rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+ if !body.claim() {
+ if rejectErr := reject(rt.NewTypeError("body stream already read")); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch %s() reject: %v", p.Name, methodName, rejectErr)
+ }
+ return rt.ToValue(promise)
+ }
+
+ go func() {
+ data, readErr := io.ReadAll(body.resp.Body)
+ body.finish()
+
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if readErr != nil {
+ if rejectErr := reject(rt.NewGoError(fmt.Errorf("failed to read response body: %w", readErr))); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch %s() reject: %v", p.Name, methodName, rejectErr)
+ }
+ return
+ }
+
+ // 复用既有数据对象的六个方法实现,避免在这里重复一遍 text/json/buffer/arrayBuffer/bytes/blob
+ // 各自的转换逻辑;data 已经是这次响应体专属的切片,不会被其它调用方共享或改写。
+ inner, innerErr := NewDataObject(p, rt, data, contentType)
+ if innerErr != nil {
+ if rejectErr := reject(rt.NewGoError(innerErr)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch %s() reject: %v", p.Name, methodName, rejectErr)
+ }
+ return
+ }
+ innerMethod, ok := goja.AssertFunction(inner.Get(methodName))
+ if !ok {
+ if rejectErr := reject(rt.NewTypeError("internal error: %s is not callable", methodName)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch %s() reject: %v", p.Name, methodName, rejectErr)
+ }
+ return
+ }
+ innerResult, callErr := innerMethod(inner)
+ if callErr != nil {
+ if rejectErr := reject(rt.NewGoError(callErr)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch %s() reject: %v", p.Name, methodName, rejectErr)
+ }
+ return
+ }
+ forwardPromise(rt, innerResult, resolve, reject)
+ return
+ }, nil)
+ }()
+
+ return rt.ToValue(promise)
+ })))
+ }
+ return
+}
+
+// newFetchResponseBodyStream 构造 response.body:按 fetchStreamChunkSize 分块、按需从 resp.Body 读取的
+// ReadableStream<Uint8Array>。第一次拉取数据时才会去抢 body 的"认领权",抢输了(某个数据方法先拿到)就把
+// controller 错误化;拉到 EOF 时关闭底层连接并 close() controller;读取出错时同样关闭连接并 error()。
+// cancel() 时直接关闭底层连接,不再继续读取。highWaterMark 必须是 0:非 0 时 desiredSize>0 会让流一构造出来
+// 就主动 pull 一次,不等任何 reader 读取就先把响应体读掉,和 text()/blob() 等方法抢着认领 body;0 时只有
+// reader 真正调用 read() 之后才会触发第一次 pull。
+func newFetchResponseBodyStream(p *KernelPlugin, rt *goja.Runtime, body *fetchResponseBody) *goja.Object {
+ started := false
+ finished := false // 已经读到过 EOF/出错/被取消:这几种情况都不该再发起下一次网络读取或再 close()/error() 一次
+ return p.streamsHost.NewReadableStream(nil, func(controller goja.Value) goja.Value {
+ if finished {
+ return nil
+ }
+ if !started {
+ if !body.claim() {
+ finished = true
+ callControllerMethod(rt, controller, "error", rt.NewTypeError("body stream already read"))
+ return nil
+ }
+ started = true
+ }
+
+ // pull 算法要返回一个在这一块真正读完前都不落定的 Promise:readableController 用它的落定状态判断
+ // "这次拉取有没有结束",如果提前返回已经落定的值(nil 会被当成 undefined,立即算结束),背压机制会
+ // 认为可以立刻再拉一次,导致还没读完上一块就对同一个 resp.Body 并发发起下一次 Read,彼此踩踏。
+ promise, resolve, _ := rt.NewPromise()
+ go func() {
+ buf := make([]byte, fetchStreamChunkSize)
+ n, readErr := body.resp.Body.Read(buf)
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ defer func() {
+ if resolveErr := resolve(goja.Undefined()); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch response.body pull resolve: %v", p.Name, resolveErr)
+ }
+ }()
+ if finished {
+ return
+ }
+ if n > 0 {
+ callControllerMethod(rt, controller, "enqueue", uint8ArrayOf(p, rt, buf[:n]))
+ }
+ switch {
+ case readErr == io.EOF:
+ finished = true
+ body.finish()
+ callControllerMethod(rt, controller, "close")
+ case readErr != nil:
+ finished = true
+ body.finish()
+ callControllerMethod(rt, controller, "error", rt.NewGoError(readErr))
+ }
+ return
+ }, nil)
+ }()
+ return rt.ToValue(promise)
+ }, func(reason goja.Value) goja.Value {
+ finished = true
+ body.finish()
+ return nil
+ }, 0, nil)
+}
+
+// uint8ArrayOf 把 data 包装为 Uint8Array:data 已经是不会再被其它调用方共享或改写的独立切片,直接作为
+// ArrayBuffer 的底层存储,不需要再复制一次。
+func uint8ArrayOf(p *KernelPlugin, rt *goja.Runtime, data []byte) goja.Value {
+ value, err := p.formDataHost.NewUint8Array(rt, data)
+ if err != nil {
+ panic(err)
+ }
+ return value
+}
+
+// callControllerMethod 调用 ReadableStream controller 上的方法(enqueue/close/error),用于 Go 驱动的
+// pull/cancel 算法把结果交回 controller;方法不存在或调用失败只记录日志,不中断调用方。
+func callControllerMethod(rt *goja.Runtime, controller goja.Value, method string, args ...goja.Value) {
+ obj := controller.ToObject(rt)
+ fn, ok := goja.AssertFunction(obj.Get(method))
+ if !ok {
+ logging.LogErrorf("controller.%s is not a function", method)
+ return
+ }
+ if _, err := fn(obj, args...); err != nil {
+ logging.LogErrorf("controller.%s(): %v", method, err)
+ }
+}
+
+// forwardPromise 把 value(预期是一个 Promise)的落定结果转发给 resolve/reject;value 不是 Promise 时直接
+// 用它的值调用 resolve。
+func forwardPromise(rt *goja.Runtime, value goja.Value, resolve, reject func(any) error) {
+ promise, ok := value.Export().(*goja.Promise)
+ if !ok {
+ if err := resolve(value); err != nil {
+ logging.LogErrorf("forwardPromise resolve: %v", err)
+ }
+ return
+ }
+
+ object := rt.ToValue(promise).ToObject(rt)
+ then, ok := goja.AssertFunction(object.Get("then"))
+ if !ok {
+ if err := resolve(value); err != nil {
+ logging.LogErrorf("forwardPromise resolve: %v", err)
+ }
+ return
+ }
+ if _, err := then(object,
+ rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ if err := resolve(call.Argument(0)); err != nil {
+ logging.LogErrorf("forwardPromise resolve: %v", err)
+ }
+ return goja.Undefined()
+ }),
+ rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ if err := reject(call.Argument(0)); err != nil {
+ logging.LogErrorf("forwardPromise reject: %v", err)
+ }
+ return goja.Undefined()
+ }),
+ ); err != nil {
+ panic(err)
+ }
+}
diff --git a/kernel/plugin/api_client_test.go b/kernel/plugin/api_client_test.go
index 8142a65de4..42a2c598e0 100644
--- a/kernel/plugin/api_client_test.go
+++ b/kernel/plugin/api_client_test.go
@@ -25,6 +25,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "slices"
"strings"
"sync"
"testing"
@@ -34,6 +35,9 @@ import (
"github.com/dop251/goja_nodejs/eventloop"
"github.com/imroc/req/v3"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/plugin/abort"
+ "github.com/siyuan-note/siyuan/kernel/plugin/formdata"
+ "github.com/siyuan-note/siyuan/kernel/plugin/streams"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -74,6 +78,12 @@ func runClientFetchScript(t *testing.T, p *KernelPlugin, script string) <-chan s
settled := make(chan string, 1)
_, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ // 与生产环境一致先启用 AbortController、FormData、Streams 等全局,供脚本中的 init.signal、init.body、
+ // response.body 使用。
+ abort.Enable(rt)
+ p.formDataHost = formdata.Enable(rt)
+ p.streamsHost = streams.Enable(rt)
+
siyuan := rt.NewObject()
if injectErr := injectClient(p, rt, siyuan); injectErr != nil {
return nil, injectErr
@@ -180,6 +190,238 @@ func TestClientFetchCopiesArrayBufferBody(t *testing.T) {
}
}
+// multipartRequest 是内核替身收到的 multipart 请求:Content-Type 头与按 Go 的 mime/multipart 解析出的表单。
+type multipartRequest struct {
+ contentTypes []string
+ values string // 按字段名排序的 fmt 格式输出
+ files map[string][]string // 同名文件按请求中的顺序排列
+ err error
+}
+
+// receiveMultipart 返回解析 multipart 请求并把结果发到 requests 的处理函数;文件以 "文件名|类型|内容" 记录。
+func receiveMultipart(requests chan<- multipartRequest) http.HandlerFunc {
+ return func(_ http.ResponseWriter, r *http.Request) {
+ received := multipartRequest{contentTypes: r.Header.Values("Content-Type")}
+ if received.err = r.ParseMultipartForm(1 << 20); received.err == nil {
+ received.values = fmt.Sprint(r.MultipartForm.Value)
+ received.files = map[string][]string{}
+ for name, headers := range r.MultipartForm.File {
+ for _, header := range headers {
+ file, err := header.Open()
+ if err != nil {
+ received.err = err
+ break
+ }
+ content, err := io.ReadAll(file)
+ file.Close()
+ if err != nil {
+ received.err = err
+ break
+ }
+ received.files[name] = append(received.files[name],
+ header.Filename+"|"+header.Header.Get("Content-Type")+"|"+string(content))
+ }
+ }
+ }
+ requests <- received
+ }
+}
+
+// waitMultipartRequest 等待内核替身收到请求。
+func waitMultipartRequest(t *testing.T, requests <-chan multipartRequest) multipartRequest {
+ t.Helper()
+
+ select {
+ case received := <-requests:
+ return received
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ return multipartRequest{}
+ }
+}
+
+func TestClientFetchSendsFormDataAsMultipart(t *testing.T) {
+ requests := make(chan multipartRequest, 1)
+ p := startClientFetchTest(t, receiveMultipart(requests))
+
+ settled := runClientFetchScript(t, p, `
+ const body = new FormData();
+ body.append("assetsDirPath", "/assets/");
+ body.append("file[]", new File(["hello"], "hello.txt", {type: "text/plain"}));
+ body.append("file[]", new Blob([new Uint8Array([0, 255])]), "raw.bin");
+ siyuan.client.fetch("/api/asset/upload", {method: "POST", body})
+ .then(() => settle(""), (e) => settle(String(e)));
+ `)
+
+ received := waitMultipartRequest(t, requests)
+ if received.err != nil {
+ t.Fatalf("parse multipart request: %v (Content-Type %q)", received.err, received.contentTypes)
+ }
+ if len(received.contentTypes) != 1 || !strings.HasPrefix(received.contentTypes[0], "multipart/form-data; boundary=") {
+ t.Fatalf("Content-Type = %q, want a single multipart/form-data type with the generated boundary",
+ received.contentTypes)
+ }
+ if want := "map[assetsDirPath:[/assets/]]"; received.values != want {
+ t.Fatalf("form values = %s, want %s", received.values, want)
+ }
+ want := []string{"hello.txt|text/plain|hello", "raw.bin|application/octet-stream|\x00\xff"}
+ if got := received.files["file[]"]; !slices.Equal(got, want) {
+ t.Fatalf("form files = %q, want %q", got, want)
+ }
+ if reason := waitClientFetchSettled(t, settled); reason != "" {
+ t.Fatalf("fetch rejected: %s", reason)
+ }
+}
+
+func TestClientFetchKeepsExplicitContentTypeForFormData(t *testing.T) {
+ contentTypes := make(chan []string, 1)
+ p := startClientFetchTest(t, func(_ http.ResponseWriter, r *http.Request) {
+ contentTypes <- r.Header.Values("Content-Type")
+ })
+
+ settled := runClientFetchScript(t, p, `
+ const body = new FormData();
+ body.append("a", "1");
+ const headers = {"content-type": "multipart/form-data; boundary=caller"};
+ siyuan.client.fetch("/", {method: "POST", body, headers}).then(() => settle(""), (e) => settle(String(e)));
+ `)
+
+ select {
+ case got := <-contentTypes:
+ if len(got) != 1 || got[0] != "multipart/form-data; boundary=caller" {
+ t.Fatalf("Content-Type = %q, want only the caller's value", got)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ }
+ if reason := waitClientFetchSettled(t, settled); reason != "" {
+ t.Fatalf("fetch rejected: %s", reason)
+ }
+}
+
+func TestClientFetchEncodesFormDataAtCallTime(t *testing.T) {
+ requests := make(chan multipartRequest, 1)
+ p := startClientFetchTest(t, receiveMultipart(requests))
+
+ // fetch 之后的修改与 fetch 位于同一段同步脚本中,请求任务只能在脚本结束后执行,
+ // 因此推迟到请求任务里才编码的实现必然发送修改后的内容。
+ settled := runClientFetchScript(t, p, `
+ const body = new FormData();
+ body.append("a", "1");
+ siyuan.client.fetch("/", {method: "POST", body}).then(() => settle(""), (e) => settle(String(e)));
+ body.set("a", "changed");
+ body.append("late", "x");
+ `)
+
+ received := waitMultipartRequest(t, requests)
+ if received.err != nil {
+ t.Fatalf("parse multipart request: %v", received.err)
+ }
+ if want := "map[a:[1]]"; received.values != want {
+ t.Fatalf("form values = %s, want the entries at call time %s", received.values, want)
+ }
+ if reason := waitClientFetchSettled(t, settled); reason != "" {
+ t.Fatalf("fetch rejected: %s", reason)
+ }
+}
+
+func TestClientFetchResponseBytesAndBlob(t *testing.T) {
+ p := startClientFetchTest(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "Image/PNG")
+ w.Write([]byte{0x89, 'P', 'N', 'G'})
+ })
+
+ // response.blob() 整体读完响应体并认领它;blob 本身不是一次性的,可以反复调用其方法;
+ // 响应体被认领后,response 上的另一个数据方法(这里用 bytes())必须按 bodyUsed 语义拒绝。
+ got := waitClientFetchSettled(t, runClientFetchScript(t, p, `
+ siyuan.client.fetch("/image").then(async (response) => {
+ const blob = await response.blob();
+ const bytesFromBlob = Array.from(await blob.bytes());
+ const bytesFromBlobAgain = Array.from(new Uint8Array(await blob.arrayBuffer()));
+ let secondCallRejected = false;
+ try { await response.bytes(); } catch (e) { secondCallRejected = e instanceof TypeError; }
+ settle(JSON.stringify([blob.type, bytesFromBlob, bytesFromBlobAgain, secondCallRejected]));
+ }).catch((e) => settle(String(e)));
+ `))
+ if want := `["image/png",[137,80,78,71],[137,80,78,71],true]`; got != want {
+ t.Fatalf("response bytes() and blob() = %s, want %s", got, want)
+ }
+}
+
+// TestClientFetchResponseBodyStreamsChunks 验证 response.body 是真正边到边读的流:第一块数据到达时
+// fetch() 已经 resolve,第二块数据要等服务端继续写入才会出现,不是构造响应对象时就已经整体读完。
+func TestClientFetchResponseBodyStreamsChunks(t *testing.T) {
+ secondChunk := make(chan struct{})
+ p := startClientFetchTest(t, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "first-")
+ w.(http.Flusher).Flush()
+ select {
+ case <-secondChunk:
+ case <-r.Context().Done():
+ return
+ }
+ io.WriteString(w, "second")
+ })
+
+ // 必须在运行主脚本之前就把这个 Go 回调挂到 globalThis 上:主脚本是异步的(先等 fetch 的 Promise resolve
+ // 再读 body),调用它时才去设置回调会有时间窗口竞争,脚本可能在回调还没挂上去之前就先调用到它。
+ // p.worker 的事件循环只有一个 goja.Runtime,这里设置的全局在后续 runClientFetchScript 里仍然可见。
+ if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ return nil, rt.Set("__unblockSecondChunk", func(goja.FunctionCall) goja.Value {
+ close(secondChunk)
+ return goja.Undefined()
+ })
+ }); err != nil {
+ t.Fatalf("expose __unblockSecondChunk: %v", err)
+ }
+
+ settled := runClientFetchScript(t, p, `
+ siyuan.client.fetch("/chunks").then(async (response) => {
+ const reader = response.body.getReader();
+ const first = await reader.read();
+ const firstBytes = Array.from(first.value);
+ __unblockSecondChunk();
+ const second = await reader.read();
+ const third = await reader.read();
+ settle(JSON.stringify([firstBytes, Array.from(second.value), third.done]));
+ }, (e) => settle("fetch-rejected:" + String(e))).catch((e) => settle("script-threw:" + String(e)));
+ `)
+
+ reason := waitClientFetchSettled(t, settled)
+ if want := `[[102,105,114,115,116,45],[115,101,99,111,110,100],true]`; reason != want {
+ t.Fatalf("response.body chunks = %s, want %s", reason, want)
+ }
+}
+
+// TestClientFetchResponseBodyCancelReleasesConnection 验证取消 response.body 的 reader 会关闭底层连接,
+// 不需要把响应体读完。
+func TestClientFetchResponseBodyCancelReleasesConnection(t *testing.T) {
+ serverSawCancellation := make(chan struct{})
+ p := startClientFetchTest(t, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "first-")
+ w.(http.Flusher).Flush()
+ <-r.Context().Done() // reader.cancel() 关闭连接后,服务端的请求 context 会被取消
+ close(serverSawCancellation)
+ })
+
+ settled := runClientFetchScript(t, p, `
+ siyuan.client.fetch("/cancel-me").then(async (response) => {
+ const reader = response.body.getReader();
+ await reader.read();
+ await reader.cancel("not interested");
+ settle("cancelled");
+ }, (e) => settle("fetch-rejected:" + String(e)));
+ `)
+ if reason := waitClientFetchSettled(t, settled); reason != "cancelled" {
+ t.Fatalf("fetch settled with %q, want \"cancelled\"", reason)
+ }
+ select {
+ case <-serverSawCancellation:
+ case <-time.After(5 * time.Second):
+ t.Fatal("server did not observe the connection closing after reader.cancel()")
+ }
+}
+
func TestClientFetchAppliesDefaultTimeout(t *testing.T) {
setClientFetchDefaultTimeout(t, 50*time.Millisecond)
@@ -217,16 +459,129 @@ func TestClientFetchTimeoutOverridesDefault(t *testing.T) {
}
}
-func TestClientFetchTimeoutCoversResponseBody(t *testing.T) {
+// timeout 现在只约束到收到响应头为止:响应头已经到达后,即便响应体一直不来,fetch() 本身也必须 resolve,
+// 之后读取响应体不再受这个已经停掉的计时器约束,与浏览器 fetch 的 timeout/AbortSignal 分离语义一致。
+func TestClientFetchTimeoutCoversOnlyHeadersNotResponseBody(t *testing.T) {
p := startClientFetchTest(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "partial")
w.(http.Flusher).Flush()
<-r.Context().Done()
})
- reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/stalled", "{timeout: 100}")))
- if !strings.Contains(reason, "timed out after 100ms") {
- t.Fatalf("fetch settled with %q, want the timeout while reading the response body", reason)
+ settled := runClientFetchScript(t, p, `
+ siyuan.client.fetch("/stalled", {timeout: 50}).then((response) => {
+ const textPromise = response.text();
+ const stillPending = new Promise((resolve) => setTimeout(() => resolve("still-pending"), 150));
+ Promise.race([textPromise, stillPending]).then(
+ (result) => settle("resolved:" + response.status + ":" + result),
+ (e) => settle("text-rejected:" + String(e)),
+ );
+ }, (e) => settle("fetch-rejected:" + String(e)));
+ `)
+ reason := waitClientFetchSettled(t, settled)
+ if want := "resolved:200:still-pending"; reason != want {
+ t.Fatalf("fetch settled with %q, want %q (fetch() resolves at headers, and reading the body is not bounded "+
+ "by the already-expired timeout)", reason, want)
+ }
+}
+
+func TestClientFetchRejectsImmediatelyWhenSignalAlreadyAborted(t *testing.T) {
+ p := startClientFetchTest(t, func(http.ResponseWriter, *http.Request) {
+ t.Error("fetch sent a request although its signal was already aborted")
+ })
+
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, `
+ const controller = new AbortController();
+ controller.abort("already gone");
+ siyuan.client.fetch("/", {signal: controller.signal}).then(() => settle(""), (e) => settle(String(e)));
+ `))
+ if reason != "already gone" {
+ t.Fatalf("fetch settled with %q, want the signal's reason", reason)
+ }
+}
+
+func TestClientFetchRejectsWithSignalReasonWhenAbortedMidFlight(t *testing.T) {
+ started := make(chan struct{})
+ cancelled := make(chan struct{})
+ p := startClientFetchTest(t, func(_ http.ResponseWriter, r *http.Request) {
+ close(started)
+ <-r.Context().Done()
+ close(cancelled)
+ })
+
+ settled := runClientFetchScript(t, p, `
+ const controller = new AbortController();
+ siyuan.client.fetch("/pending", {signal: controller.signal, timeout: 0})
+ .then(() => settle(""), (e) => settle(String(e)));
+ globalThis.__controller = controller;
+ `)
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ }
+
+ if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ controller := rt.GlobalObject().Get("__controller")
+ fn, _ := goja.AssertFunction(controller.ToObject(rt).Get("abort"))
+ _, callErr := fn(controller, rt.ToValue("mid-flight abort"))
+ return nil, callErr
+ }); err != nil {
+ t.Fatalf("controller.abort(): %v", err)
+ }
+
+ select {
+ case <-cancelled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("pending request was not cancelled by the signal")
+ }
+ if reason := waitClientFetchSettled(t, settled); reason != "mid-flight abort" {
+ t.Fatalf("fetch settled with %q, want the signal's reason", reason)
+ }
+}
+
+func TestClientFetchSignalAbortDoesNotMaskUnrelatedCancellation(t *testing.T) {
+ // 插件停止(父上下文取消)与 signal 中止是不同的取消来源,前者仍应保留原有的 "context canceled" 行为。
+ started := make(chan struct{})
+ cancelled := make(chan struct{})
+ p := startClientFetchTest(t, func(_ http.ResponseWriter, r *http.Request) {
+ close(started)
+ <-r.Context().Done()
+ close(cancelled)
+ })
+
+ settled := runClientFetchScript(t, p, `
+ const controller = new AbortController();
+ siyuan.client.fetch("/pending", {signal: controller.signal, timeout: 0})
+ .then(() => settle(""), (e) => settle(String(e)));
+ `)
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ }
+
+ p.cancel()
+ select {
+ case <-cancelled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("pending request was not cancelled with the plugin context")
+ }
+ if reason := waitClientFetchSettled(t, settled); !strings.Contains(reason, "context canceled") {
+ t.Fatalf("fetch settled with %q, want cancellation unrelated to the signal", reason)
+ }
+}
+
+func TestClientFetchRejectsNonAbortSignalInit(t *testing.T) {
+ p := startClientFetchTest(t, func(http.ResponseWriter, *http.Request) {
+ t.Error("fetch sent a request with an invalid signal")
+ })
+
+ for _, signal := range []string{"{}", `"not a signal"`, "123"} {
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/", "{signal: "+signal+"}")))
+ if !strings.Contains(reason, "signal must be an AbortSignal") {
+ t.Errorf("signal %s: fetch settled with %q", signal, reason)
+ }
}
}
diff --git a/kernel/plugin/api_crypto.go b/kernel/plugin/api_crypto.go
index 7116740660..1250be68d6 100644
--- a/kernel/plugin/api_crypto.go
+++ b/kernel/plugin/api_crypto.go
@@ -30,10 +30,10 @@ import (
// randomValuesMaxLength 是 getRandomValues 单次可填充的最大字节数,与浏览器一致。
const randomValuesMaxLength = 65536
-// injectCrypto 注入 siyuan.crypto,实现 Web Crypto API 的 Crypto 接口。
+// injectCrypto 实现 Web Crypto API 的 Crypto 接口,以标准全局名 globalThis.crypto 提供。
// 密钥材料只保存在内核侧,插件通过 CryptoKey 句柄引用;运算在事件循环之外执行,
// 结果回到事件循环后再转换为 JS 值。
-func injectCrypto(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+func injectCrypto(p *KernelPlugin, rt *goja.Runtime) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("injectCrypto: %v", r)
@@ -44,7 +44,7 @@ func injectCrypto(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
cryptoObj := rt.NewObject()
- // siyuan.crypto.getRandomValues(typedArray) -> typedArray
+ // crypto.getRandomValues(typedArray) -> typedArray
lo.Must0(cryptoObj.Set("getRandomValues", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
value := call.Argument(0)
data, err := randomValuesTarget(rt, value)
@@ -58,7 +58,7 @@ func injectCrypto(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
return value
})))
- // siyuan.crypto.randomUUID() -> string
+ // crypto.randomUUID() -> string
lo.Must0(cryptoObj.Set("randomUUID", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
return rt.ToValue(uuid.NewString())
})))
@@ -67,7 +67,7 @@ func injectCrypto(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
lo.Must0(cryptoObj.Set("subtle", subtle))
lo.Must0(ObjectFreeze(rt, cryptoObj))
- lo.Must0(siyuan.Set("crypto", cryptoObj))
+ lo.Must0(rt.GlobalObject().Set("crypto", cryptoObj))
return
}
@@ -96,7 +96,7 @@ func randomValuesTarget(rt *goja.Runtime, value goja.Value) ([]byte, error) {
return data, nil
}
-// newSubtleObject 构造 siyuan.crypto.subtle。
+// newSubtleObject 构造 crypto.subtle。
func (h *cryptoHost) newSubtleObject(rt *goja.Runtime) (*goja.Object, error) {
subtle := rt.NewObject()
@@ -217,7 +217,7 @@ func (h *cryptoHost) run(rt *goja.Runtime, name string,
rejectWith := func(rt *goja.Runtime, err error) {
if rejectErr := reject(h.toJsError(rt, err)); rejectErr != nil {
- logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s reject: %v", p.Name, name, rejectErr)
+ logging.LogErrorf("[plugin:%s] crypto.subtle.%s reject: %v", p.Name, name, rejectErr)
}
}
@@ -240,7 +240,7 @@ func (h *cryptoHost) run(rt *goja.Runtime, name string,
defer func() {
if r := recover(); r != nil {
computeErr = crypto.NewError(crypto.ErrNameOperation,
- "panic during siyuan.crypto.subtle.%s: %v", name, r)
+ "panic during crypto.subtle.%s: %v", name, r)
}
runErr := p.worker.Run(func(rt *goja.Runtime) (any, error) {
@@ -255,12 +255,12 @@ func (h *cryptoHost) run(rt *goja.Runtime, name string,
return nil, nil
}
if resolveErr := resolve(value); resolveErr != nil {
- logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s resolve: %v", p.Name, name, resolveErr)
+ logging.LogErrorf("[plugin:%s] crypto.subtle.%s resolve: %v", p.Name, name, resolveErr)
}
return nil, nil
}, nil)
if runErr != nil {
- logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s worker run: %v", p.Name, name, runErr)
+ logging.LogErrorf("[plugin:%s] crypto.subtle.%s worker run: %v", p.Name, name, runErr)
}
}()
diff --git a/kernel/plugin/api_crypto_asymmetric_test.go b/kernel/plugin/api_crypto_asymmetric_test.go
index d2766fdfc5..5d2699ecfb 100644
--- a/kernel/plugin/api_crypto_asymmetric_test.go
+++ b/kernel/plugin/api_crypto_asymmetric_test.go
@@ -23,7 +23,7 @@ func TestCryptoGenerateKeyPairShape(t *testing.T) {
// 非对称算法返回含 publicKey 与 privateKey 的 CryptoKeyPair。
got := rt.await(`(async () => {
- const pair = await siyuan.crypto.subtle.generateKey(
+ const pair = await crypto.subtle.generateKey(
{name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]);
report([
typeof pair,
@@ -44,7 +44,7 @@ func TestCryptoGenerateKeyPairShape(t *testing.T) {
// RSA 的 algorithm 暴露 modulusLength 与 publicExponent。
got = rt.await(`(async () => {
- const pair = await siyuan.crypto.subtle.generateKey(
+ const pair = await crypto.subtle.generateKey(
{name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
true, ["encrypt", "decrypt"]);
const alg = pair.publicKey.algorithm;
@@ -65,7 +65,7 @@ func TestCryptoGenerateKeyPairShape(t *testing.T) {
// 不可导出时只有私钥不可导出,公钥始终可导出。
got = rt.await(`(async () => {
- const pair = await siyuan.crypto.subtle.generateKey({name: "Ed25519"}, false, ["sign", "verify"]);
+ const pair = await crypto.subtle.generateKey({name: "Ed25519"}, false, ["sign", "verify"]);
report([pair.privateKey.extractable, pair.publicKey.extractable].join(","));
})()`)
if got != "false,true" {
@@ -78,7 +78,7 @@ func TestCryptoPublicExponentIsNotAliased(t *testing.T) {
// publicExponent 由内核保留并被公私钥共享,脚本修改它不应影响后续读取。
got := rt.await(`(async () => {
- const pair = await siyuan.crypto.subtle.generateKey(
+ const pair = await crypto.subtle.generateKey(
{name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
true, ["encrypt", "decrypt"]);
@@ -114,7 +114,7 @@ func TestCryptoAsymmetricSignVerify(t *testing.T) {
for _, c := range cases {
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey(` + c.generate + `, true, ["sign", "verify"]);
const data = new TextEncoderLike("sign me");
@@ -139,7 +139,7 @@ func TestCryptoECDSAUsesOperationHash(t *testing.T) {
// ECDSA 密钥不携带 hash,摘要算法由签名参数指定,同一密钥可配不同摘要。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]);
const data = new TextEncoderLike("hash choice");
@@ -165,7 +165,7 @@ func TestCryptoRSAOAEPEncryptDecrypt(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey(
{name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
true, ["encrypt", "decrypt"]);
@@ -194,7 +194,7 @@ func TestCryptoRSAOAEPEncryptDecrypt(t *testing.T) {
// 公钥不能解密,私钥不能加密。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey(
{name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
true, ["encrypt", "decrypt"]);
@@ -219,7 +219,7 @@ func TestCryptoECDHDeriveInSandbox(t *testing.T) {
for _, generate := range []string{`{name: "ECDH", namedCurve: "P-256"}`, `{name: "X25519"}`} {
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const alice = await subtle.generateKey(` + generate + `, true, ["deriveBits", "deriveKey"]);
const bob = await subtle.generateKey(` + generate + `, true, ["deriveBits", "deriveKey"]);
const name = alice.privateKey.algorithm.name;
@@ -231,7 +231,7 @@ func TestCryptoECDHDeriveInSandbox(t *testing.T) {
// 派生出的 AES 密钥可用于加解密。
const key = await subtle.deriveKey({name, public: bob.publicKey}, alice.privateKey,
{name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
- const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
const payload = new TextEncoderLike("shared");
const ciphertext = await subtle.encrypt({name: "AES-GCM", iv}, key, payload);
const plaintext = await subtle.decrypt({name: "AES-GCM", iv}, key, ciphertext);
@@ -251,7 +251,7 @@ func TestCryptoECDHDeriveInSandbox(t *testing.T) {
// 对方公钥算法不符时报 InvalidAccessError。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const ecdh = await subtle.generateKey({name: "ECDH", namedCurve: "P-256"}, true, ["deriveBits"]);
const x = await subtle.generateKey({name: "X25519"}, true, ["deriveBits"]);
try {
@@ -267,7 +267,7 @@ func TestCryptoECDHDeriveInSandbox(t *testing.T) {
// public 成员必须是 CryptoKey。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const ecdh = await subtle.generateKey({name: "ECDH", namedCurve: "P-256"}, true, ["deriveBits"]);
try {
await subtle.deriveBits({name: "ECDH", public: {}}, ecdh.privateKey, 128);
@@ -286,7 +286,7 @@ func TestCryptoKeyFormatsInSandbox(t *testing.T) {
// spki 与 pkcs8 往返。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const alg = {name: "ECDSA", namedCurve: "P-256"};
const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
@@ -309,7 +309,7 @@ func TestCryptoKeyFormatsInSandbox(t *testing.T) {
// jwk 往返,私钥含 d 成员。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const alg = {name: "ECDSA", namedCurve: "P-256"};
const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
@@ -329,7 +329,7 @@ func TestCryptoKeyFormatsInSandbox(t *testing.T) {
// raw 格式导出 Ed25519 与 ECDH 公钥。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const ed = await subtle.generateKey({name: "Ed25519"}, true, ["sign", "verify"]);
const raw = await subtle.exportKey("raw", ed.publicKey);
const reimported = await subtle.importKey("raw", raw, {name: "Ed25519"}, true, ["verify"]);
@@ -353,7 +353,7 @@ func TestCryptoKeyFormatsInSandbox(t *testing.T) {
// 算法不支持的格式报 NotSupportedError,不受密钥数据影响。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const results = [];
const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
for (const format of ["spki", "pkcs8"]) {
@@ -382,7 +382,7 @@ func TestCryptoAESKWInSandbox(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const wrapping = await subtle.generateKey({name: "AES-KW", length: 256}, true, ["wrapKey", "unwrapKey"]);
const target = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]);
@@ -417,11 +417,11 @@ func TestCryptoWrapsAsymmetricKeys(t *testing.T) {
// 用 AES-GCM 包装 pkcs8 私钥,解包装后仍能签名。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const alg = {name: "ECDSA", namedCurve: "P-256"};
const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
const wrapping = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["wrapKey", "unwrapKey"]);
- const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
const wrapped = await subtle.wrapKey("pkcs8", pair.privateKey, wrapping, {name: "AES-GCM", iv});
const unwrapped = await subtle.unwrapKey("pkcs8", wrapped, wrapping, {name: "AES-GCM", iv},
@@ -443,7 +443,7 @@ func TestCryptoAsymmetricLimits(t *testing.T) {
// RSA 的公开指数限制。
got := rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey(
+ await crypto.subtle.generateKey(
{name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([3]), hash: "SHA-256"},
true, ["sign"]);
report("resolved");
@@ -457,7 +457,7 @@ func TestCryptoAsymmetricLimits(t *testing.T) {
// RSA-PSS 的零长度盐。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey(
{name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
true, ["sign"]);
@@ -475,7 +475,7 @@ func TestCryptoAsymmetricLimits(t *testing.T) {
// 未知曲线。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-224"}, true, ["sign"]);
+ await crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-224"}, true, ["sign"]);
report("resolved");
} catch (e) {
report(e.name);
@@ -488,7 +488,7 @@ func TestCryptoAsymmetricLimits(t *testing.T) {
// 生成密钥对时必须至少有一个私钥用法。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, true, ["verify"]);
+ await crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, true, ["verify"]);
report("resolved");
} catch (e) {
report(e.name);
diff --git a/kernel/plugin/api_crypto_legacy_test.go b/kernel/plugin/api_crypto_legacy_test.go
index a89568083e..b688748ce7 100644
--- a/kernel/plugin/api_crypto_legacy_test.go
+++ b/kernel/plugin/api_crypto_legacy_test.go
@@ -25,7 +25,7 @@ func TestCryptoMD5InSandbox(t *testing.T) {
// digest 可以使用 MD5,结果与 RFC 1321 一致。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const digest = await subtle.digest("MD5", new TextEncoderLike("abc"));
@@ -39,7 +39,7 @@ func TestCryptoMD5InSandbox(t *testing.T) {
// HMAC-MD5 可用,向量来自 RFC 2202 用例 2。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const key = await subtle.importKey("raw", new TextEncoderLike("Jefe"),
@@ -57,7 +57,7 @@ func TestCryptoMD5InSandbox(t *testing.T) {
// HKDF 与 PBKDF2 也接受 MD5。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const results = [];
for (const params of [
{name: "HKDF", hash: "MD5", salt: new Uint8Array(8), info: new TextEncoderLike("ctx")},
@@ -80,7 +80,7 @@ func TestCryptoMD5RejectedBySignaturesInSandbox(t *testing.T) {
// RSA 生成密钥时拒绝 MD5。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const results = [];
for (const name of ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP"]) {
const usages = name === "RSA-OAEP" ? ["encrypt", "decrypt"] : ["sign", "verify"];
@@ -101,7 +101,7 @@ func TestCryptoMD5RejectedBySignaturesInSandbox(t *testing.T) {
// ECDSA 在签名与校验时拒绝 MD5,同一密钥用 SHA-256 仍然可用。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const pair = await subtle.generateKey({name: "ECDSA", namedCurve: "P-256"},
true, ["sign", "verify"]);
const data = new TextEncoderLike("md5 is rejected");
@@ -131,7 +131,7 @@ func TestCryptoMD5RejectedBySignaturesInSandbox(t *testing.T) {
// 错误消息说明原因,便于插件作者定位。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey({name: "RSA-PSS", modulusLength: 2048,
+ await crypto.subtle.generateKey({name: "RSA-PSS", modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), hash: "MD5"}, true, ["sign"]);
report("resolved");
} catch (e) {
@@ -148,7 +148,7 @@ func TestCryptoAESECBInSandbox(t *testing.T) {
// NIST SP 800-38A F.1.1 的第一个分组,密钥与明文都取自该向量。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const unhex = (s) => new Uint8Array(s.match(/../g).map((x) => parseInt(x, 16)));
@@ -175,7 +175,7 @@ func TestCryptoAESECBInSandbox(t *testing.T) {
// 相同明文分组产生相同密文分组,且不需要 iv。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const key = await subtle.generateKey({name: "AES-ECB", length: 256}, true, ["encrypt", "decrypt"]);
@@ -192,7 +192,7 @@ func TestCryptoAESECBInSandbox(t *testing.T) {
// 填充被破坏时报 OperationError。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-ECB", length: 128}, true, ["encrypt", "decrypt"]);
const ciphertext = await subtle.encrypt({name: "AES-ECB"}, key, new TextEncoderLike("legacy"));
@@ -224,7 +224,7 @@ func TestCryptoAESECBRejectsWrappingInSandbox(t *testing.T) {
// AES-ECB 不支持包装密钥,声明该用法时即报错。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const results = [];
for (const usages of [["wrapKey"], ["unwrapKey"], ["encrypt", "wrapKey"]]) {
try {
@@ -257,7 +257,7 @@ func TestCryptoAESECBKeyFormatsInSandbox(t *testing.T) {
// raw 与 jwk 往返,jwk 不含 alg 成员。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const key = await subtle.generateKey({name: "AES-ECB", length: 256}, true, ["encrypt", "decrypt"]);
@@ -288,7 +288,7 @@ func TestCryptoAESECBKeyFormatsInSandbox(t *testing.T) {
// 对称密钥不支持 spki 与 pkcs8。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-ECB", length: 128}, true, ["encrypt"]);
const results = [];
for (const format of ["spki", "pkcs8"]) {
diff --git a/kernel/plugin/api_crypto_test.go b/kernel/plugin/api_crypto_test.go
index b3116fc5d1..4a230b21ed 100644
--- a/kernel/plugin/api_crypto_test.go
+++ b/kernel/plugin/api_crypto_test.go
@@ -27,7 +27,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/model"
)
-// cryptoTestRuntime 启动一个注入了 siyuan.crypto 的事件循环,
+// cryptoTestRuntime 启动一个注入了 crypto 的事件循环,
// 并提供在循环上执行脚本、等待异步结果的辅助方法。
type cryptoTestRuntime struct {
t *testing.T
@@ -52,11 +52,7 @@ func newCryptoTestRuntime(t *testing.T) *cryptoTestRuntime {
ret := &cryptoTestRuntime{t: t, plugin: p, loop: loop, done: make(chan string, 8)}
if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
- siyuan := rt.NewObject()
- if err := injectCrypto(p, rt, siyuan); err != nil {
- return nil, err
- }
- if err := rt.Set("siyuan", siyuan); err != nil {
+ if err := injectCrypto(p, rt); err != nil {
return nil, err
}
// report 供脚本回传结果,done 供等待异步完成。
@@ -66,7 +62,7 @@ func newCryptoTestRuntime(t *testing.T) *cryptoTestRuntime {
}); err != nil {
return nil, err
}
- // 沙箱没有 TextEncoder,测试脚本用它把 ASCII 字符串转为 Uint8Array。
+ // 这里只注入 crypto,没有启用 TextEncoder,测试脚本用它把 ASCII 字符串转为 Uint8Array。
if _, err := rt.RunString(`function TextEncoderLike(text) {
const bytes = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
@@ -78,7 +74,7 @@ func newCryptoTestRuntime(t *testing.T) *cryptoTestRuntime {
}
return nil, nil
}); err != nil {
- t.Fatalf("inject siyuan.crypto: %v", err)
+ t.Fatalf("inject crypto: %v", err)
}
return ret
}
@@ -137,7 +133,7 @@ func TestCryptoGetRandomValues(t *testing.T) {
// 返回值必须是传入的同一个数组,且已被填充。
got := rt.run(`(() => {
const array = new Uint8Array(32);
- const returned = siyuan.crypto.getRandomValues(array);
+ const returned = crypto.getRandomValues(array);
const filled = array.some((v) => v !== 0);
return [returned === array, filled].join(",");
})()`)
@@ -150,7 +146,7 @@ func TestCryptoGetRandomValues(t *testing.T) {
const types = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
Int32Array, Uint32Array, BigInt64Array, BigUint64Array];
return types.every((T) => {
- siyuan.crypto.getRandomValues(new T(4));
+ crypto.getRandomValues(new T(4));
return true;
});
})()`)
@@ -163,42 +159,55 @@ func TestCryptoGetRandomValues(t *testing.T) {
"new Float32Array(4)", "new Float64Array(4)",
"new DataView(new ArrayBuffer(4))", "new ArrayBuffer(4)", "[1,2,3]", "null",
} {
- message := rt.runError("siyuan.crypto.getRandomValues(" + expr + ")")
+ message := rt.runError("crypto.getRandomValues(" + expr + ")")
if !strings.Contains(message, "TypeMismatchError") {
t.Errorf("getRandomValues(%s) threw %q, want TypeMismatchError", expr, message)
}
}
// 超过 65536 字节应报 QuotaExceededError。
- message := rt.runError("siyuan.crypto.getRandomValues(new Uint8Array(65537))")
+ message := rt.runError("crypto.getRandomValues(new Uint8Array(65537))")
if !strings.Contains(message, "QuotaExceededError") {
t.Fatalf("threw %q, want QuotaExceededError", message)
}
// 边界值 65536 字节应当接受。
- rt.run("siyuan.crypto.getRandomValues(new Uint8Array(65536))")
+ rt.run("crypto.getRandomValues(new Uint8Array(65536))")
}
func TestCryptoRandomUUID(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.run(`(() => {
- const uuid = siyuan.crypto.randomUUID();
+ const uuid = crypto.randomUUID();
const pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
- return [uuid.length, pattern.test(uuid), uuid !== siyuan.crypto.randomUUID()].join(",");
+ return [uuid.length, pattern.test(uuid), uuid !== crypto.randomUUID()].join(",");
})()`)
if got.String() != "36,true,true" {
t.Fatalf("randomUUID = %s, want 36,true,true", got.String())
}
}
+func TestCryptoIsInstalledAsGlobal(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // crypto 以标准全局名安装在 globalThis 上,按标准全局名访问的代码可直接使用。
+ got := rt.run(`(() => {
+ const random = crypto.getRandomValues(new Uint8Array(4));
+ return [typeof globalThis.crypto, random.length, typeof crypto.subtle.digest].join(",");
+ })()`)
+ if got.String() != "object,4,function" {
+ t.Fatalf("globalThis.crypto = %s, want object,4,function", got.String())
+ }
+}
+
func TestCryptoDigest(t *testing.T) {
rt := newCryptoTestRuntime(t)
// 摘要结果以 ArrayBuffer 返回,内容与已知向量一致。
got := rt.await(`(async () => {
const data = new Uint8Array([0x61, 0x62, 0x63]);
- const digest = await siyuan.crypto.subtle.digest("SHA-256", data);
+ const digest = await crypto.subtle.digest("SHA-256", data);
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
report([digest instanceof ArrayBuffer, hex].join(","));
})()`)
@@ -210,8 +219,8 @@ func TestCryptoDigest(t *testing.T) {
// 算法名称大小写不敏感,且接受 {name} 形式。
got = rt.await(`(async () => {
const data = new Uint8Array(0);
- const a = await siyuan.crypto.subtle.digest("sha-1", data);
- const b = await siyuan.crypto.subtle.digest({name: "SHA-1"}, data);
+ const a = await crypto.subtle.digest("sha-1", data);
+ const b = await crypto.subtle.digest({name: "SHA-1"}, data);
report([a.byteLength, b.byteLength].join(","));
})()`)
if got != "20,20" {
@@ -221,7 +230,7 @@ func TestCryptoDigest(t *testing.T) {
// 未知算法应 reject 且错误名为 NotSupportedError。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.digest("SHA-3", new Uint8Array(1));
+ await crypto.subtle.digest("SHA-3", new Uint8Array(1));
report("resolved");
} catch (e) {
report(e.name);
@@ -234,7 +243,7 @@ func TestCryptoDigest(t *testing.T) {
// 参数类型错误应 reject 为 TypeError。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.digest("SHA-256", "not a buffer");
+ await crypto.subtle.digest("SHA-256", "not a buffer");
report("resolved");
} catch (e) {
report(e.constructor.name + ":" + e.name);
@@ -249,9 +258,9 @@ func TestCryptoAESGCMRoundTrip(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
- const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
const plaintext = new TextEncoderLike("hello siyuan");
const ciphertext = await subtle.encrypt({name: "AES-GCM", iv}, key, plaintext);
@@ -273,9 +282,9 @@ func TestCryptoImportIgnoresAESParameterLength(t *testing.T) {
// 同一个 AES-CTR 参数对象可以同时用于导入与加解密,其中的 length 是计数器位长,
// 不影响导入:密钥位长取自密钥数据。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const params = {name: "AES-CTR", counter: new Uint8Array(16), length: 64};
- const raw = siyuan.crypto.getRandomValues(new Uint8Array(16));
+ const raw = crypto.getRandomValues(new Uint8Array(16));
try {
const key = await subtle.importKey("raw", raw, params, true, ["encrypt", "decrypt"]);
@@ -301,7 +310,7 @@ func TestCryptoKeyObjectShape(t *testing.T) {
// CryptoKey 不暴露自有属性,密钥材料不可从 JS 读取。
got := rt.await(`(async () => {
- const key = await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ const key = await crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
report([
Object.keys(key).length,
JSON.stringify(key),
@@ -320,7 +329,7 @@ func TestCryptoKeyObjectShape(t *testing.T) {
// 属性是只读访问器,赋值在严格模式下抛错。
got = rt.await(`(async () => {
"use strict";
- const key = await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ const key = await crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
try {
key.extractable = false;
report("assigned");
@@ -336,7 +345,7 @@ func TestCryptoKeyObjectShape(t *testing.T) {
got = rt.await(`(async () => {
const fake = {type: "secret", extractable: true, algorithm: {name: "AES-GCM"}, usages: ["encrypt"]};
try {
- await siyuan.crypto.subtle.encrypt({name: "AES-GCM", iv: new Uint8Array(12)}, fake, new Uint8Array(1));
+ await crypto.subtle.encrypt({name: "AES-GCM", iv: new Uint8Array(12)}, fake, new Uint8Array(1));
report("resolved");
} catch (e) {
report(e.constructor.name);
@@ -351,7 +360,7 @@ func TestCryptoHMACSignVerify(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const raw = new Uint8Array([0x4a, 0x65, 0x66, 0x65]); // "Jefe"
const key = await subtle.importKey("raw", raw, {name: "HMAC", hash: "SHA-256"}, true, ["sign", "verify"]);
const data = new TextEncoderLike("what do ya want for nothing?");
@@ -377,8 +386,8 @@ func TestCryptoImportExportKey(t *testing.T) {
// raw 往返保持密钥材料不变。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
- const raw = siyuan.crypto.getRandomValues(new Uint8Array(32));
+ const subtle = crypto.subtle;
+ const raw = crypto.getRandomValues(new Uint8Array(32));
const key = await subtle.importKey("raw", raw, "AES-CBC", true, ["encrypt", "decrypt"]);
const exported = await subtle.exportKey("raw", key);
const same = [...new Uint8Array(exported)].join(",") === [...raw].join(",");
@@ -390,7 +399,7 @@ func TestCryptoImportExportKey(t *testing.T) {
// jwk 导出为普通对象,可直接再次导入。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
const jwk = await subtle.exportKey("jwk", key);
const reimported = await subtle.importKey("jwk", jwk, "AES-GCM", true, ["encrypt", "decrypt"]);
@@ -405,7 +414,7 @@ func TestCryptoImportExportKey(t *testing.T) {
// 不可导出的密钥不能导出。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 128}, false, ["encrypt"]);
try {
await subtle.exportKey("raw", key);
@@ -421,7 +430,7 @@ func TestCryptoImportExportKey(t *testing.T) {
// 未实现的格式应报 NotSupportedError,而不是参数错误。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.importKey("spki", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
+ await crypto.subtle.importKey("spki", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
report("resolved");
} catch (e) {
report(e.name);
@@ -434,7 +443,7 @@ func TestCryptoImportExportKey(t *testing.T) {
// 非法格式名属于参数错误。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.importKey("pem", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
+ await crypto.subtle.importKey("pem", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
report("resolved");
} catch (e) {
report(e.constructor.name);
@@ -450,7 +459,7 @@ func TestCryptoJWKKeyOpsPresence(t *testing.T) {
// key_ops 缺失时不限制用法;为空数组或含重复值时报 DataError。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
const {key_ops, ...withoutKeyOps} = await subtle.exportKey("jwk", key);
@@ -485,7 +494,7 @@ func TestCryptoJWKUseOfKeyAgreement(t *testing.T) {
// ECDH 与 X25519 的私钥用于派生,use 必须是 enc,sig 报 DataError。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const results = [];
for (const alg of [{name: "ECDH", namedCurve: "P-256"}, {name: "X25519"}]) {
const pair = await subtle.generateKey(alg, true, ["deriveBits"]);
@@ -512,7 +521,7 @@ func TestCryptoDeriveKeyAndBits(t *testing.T) {
// PBKDF2 派生比特串,相同参数结果一致。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const password = new TextEncoderLike("password");
const base = await subtle.importKey("raw", password, "PBKDF2", false, ["deriveBits", "deriveKey"]);
const params = {name: "PBKDF2", hash: "SHA-1", salt: new TextEncoderLike("salt"), iterations: 2};
@@ -530,7 +539,7 @@ func TestCryptoDeriveKeyAndBits(t *testing.T) {
// HKDF 需要 salt 与 info 成员。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const base = await subtle.importKey("raw", new Uint8Array(16), "HKDF", false, ["deriveBits"]);
try {
await subtle.deriveBits({name: "HKDF", hash: "SHA-256"}, base, 128);
@@ -546,7 +555,7 @@ func TestCryptoDeriveKeyAndBits(t *testing.T) {
// KDF 密钥要求 extractable 为 false。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.importKey("raw", new Uint8Array(16), "HKDF", true, ["deriveBits"]);
+ await crypto.subtle.importKey("raw", new Uint8Array(16), "HKDF", true, ["deriveBits"]);
report("resolved");
} catch (e) {
report(e.name);
@@ -561,10 +570,10 @@ func TestCryptoWrapUnwrapKey(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const wrapping = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["wrapKey", "unwrapKey"]);
const target = await subtle.generateKey({name: "AES-CBC", length: 128}, true, ["encrypt", "decrypt"]);
- const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
const wrapped = await subtle.wrapKey("raw", target, wrapping, {name: "AES-GCM", iv});
const unwrapped = await subtle.unwrapKey("raw", wrapped, wrapping, {name: "AES-GCM", iv},
@@ -586,7 +595,7 @@ func TestCryptoUsageEnforcement(t *testing.T) {
// 未声明的用法应报 InvalidAccessError。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["decrypt"]);
try {
await subtle.encrypt({name: "AES-GCM", iv: new Uint8Array(12)}, key, new Uint8Array(1));
@@ -602,7 +611,7 @@ func TestCryptoUsageEnforcement(t *testing.T) {
// 算法不允许的用法应报 SyntaxError。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["sign"]);
+ await crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["sign"]);
report("resolved");
} catch (e) {
report(e.name);
@@ -615,7 +624,7 @@ func TestCryptoUsageEnforcement(t *testing.T) {
// 非法用法字符串属于参数错误。
got = rt.await(`(async () => {
try {
- await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["Encrypt"]);
+ await crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["Encrypt"]);
report("resolved");
} catch (e) {
report(e.constructor.name);
@@ -632,7 +641,7 @@ func TestCryptoInputIsCopiedBeforeComputation(t *testing.T) {
// 调用后立即修改输入缓冲区,结果必须对应调用时的内容。
got := rt.await(`(async () => {
const data = new Uint8Array([0x61, 0x62, 0x63]);
- const promise = siyuan.crypto.subtle.digest("SHA-256", data);
+ const promise = crypto.subtle.digest("SHA-256", data);
data.fill(0);
const digest = await promise;
@@ -652,7 +661,7 @@ func TestCryptoRespectsTypedArrayViews(t *testing.T) {
got := rt.run(`(() => {
const buffer = new ArrayBuffer(16);
const view = new Uint8Array(buffer, 4, 8);
- siyuan.crypto.getRandomValues(view);
+ crypto.getRandomValues(view);
const all = new Uint8Array(buffer);
const before = all.slice(0, 4).every((v) => v === 0);
@@ -666,7 +675,7 @@ func TestCryptoRespectsTypedArrayViews(t *testing.T) {
// 摘要只覆盖视图范围,结果与同内容的独立数组一致。
result := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const buffer = new Uint8Array([0, 0, 0x61, 0x62, 0x63, 0, 0]).buffer;
const view = new Uint8Array(buffer, 2, 3);
@@ -683,7 +692,7 @@ func TestCryptoRespectsTypedArrayViews(t *testing.T) {
// DataView 也是合法的 BufferSource。
result = rt.await(`(async () => {
const buffer = new Uint8Array([0x61, 0x62, 0x63]).buffer;
- const digest = await siyuan.crypto.subtle.digest("SHA-256", new DataView(buffer));
+ const digest = await crypto.subtle.digest("SHA-256", new DataView(buffer));
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
report(hex);
})()`)
@@ -698,7 +707,7 @@ func TestCryptoAcceptsEmptyBufferSource(t *testing.T) {
// 长度为 0 的 BufferSource 是合法取值,必须与成员缺失区分开:
// RFC 5869 允许 HKDF 的 salt 与 info 为空,浏览器同样接受。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const base = await subtle.importKey("raw", new TextEncoderLike("password"),
{name: "HKDF"}, false, ["deriveBits"]);
@@ -733,9 +742,9 @@ func TestCryptoAcceptsEmptyBufferSource(t *testing.T) {
// 空明文与空的附加认证数据同样可用。
got = rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]);
- const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await subtle.encrypt(
{name: "AES-GCM", iv, additionalData: new Uint8Array(0)}, key, new Uint8Array(0));
@@ -758,7 +767,7 @@ func TestCryptoArgumentExceptionsRejectThePromise(t *testing.T) {
// 读取参数时脚本抛出的异常不能同步抛出,而要以原值拒绝 Promise,
// 这样调用方的 .catch(...) 才能处理。
got := rt.await(`(async () => {
- const subtle = siyuan.crypto.subtle;
+ const subtle = crypto.subtle;
const thrown = new Error("boom");
const fail = () => { throw thrown; };
const data = new Uint8Array(1);
@@ -807,7 +816,7 @@ func TestCryptoArgumentInterruptPropagates(t *testing.T) {
if err := r.Set("interruptNow", func() { r.Interrupt("stop") }); err != nil {
return nil, err
}
- _, runErr = r.RunString(`siyuan.crypto.subtle.digest({get name() { interruptNow(); for (;;) {} }}, new Uint8Array(1))`)
+ _, runErr = r.RunString(`crypto.subtle.digest({get name() { interruptNow(); for (;;) {} }}, new Uint8Array(1))`)
r.ClearInterrupt()
return nil, nil
}); err != nil {
@@ -822,13 +831,13 @@ func TestCryptoSurfaceIsFrozen(t *testing.T) {
rt := newCryptoTestRuntime(t)
got := rt.run(`(() => {
- const results = [Object.isFrozen(siyuan.crypto), Object.isFrozen(siyuan.crypto.subtle)];
+ const results = [Object.isFrozen(crypto), Object.isFrozen(crypto.subtle)];
try {
- siyuan.crypto.subtle.digest = () => {};
+ crypto.subtle.digest = () => {};
} catch (e) {
results.push("throws");
}
- results.push(typeof siyuan.crypto.subtle.digest === "function");
+ results.push(typeof crypto.subtle.digest === "function");
return results.join(",");
})()`)
if got.String() != "true,true,true" {
diff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.go
index 314836855e..65151e6e41 100644
--- a/kernel/plugin/api_storage.go
+++ b/kernel/plugin/api_storage.go
@@ -146,7 +146,7 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err
storage := rt.NewObject()
- // siyuan.storage.get(path) -> Promise<{text, json, arrayBuffer}>
+ // siyuan.storage.get(path) -> Promise<{text, json, buffer, arrayBuffer, bytes, blob}>
lo.Must0(storage.Set("get", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
promise, resolve, reject := rt.NewPromise()
@@ -179,9 +179,11 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err
return nil, err
}
+ // 存储文件没有媒体类型,blob() 返回的 Blob 的 type 为空串。
+ // 错误存入局部变量而不是外层的 err:外层 goroutine 返回时会读取 err,在事件循环上写入它会构成数据竞争。
content := rt.NewObject()
- if err = ObjectSetDataMethods(p, rt, content, result); err != nil {
- return nil, err
+ if setErr := ObjectSetDataMethods(p, rt, content, result, ""); setErr != nil {
+ return nil, setErr
}
return content, nil
diff --git a/kernel/plugin/api_storage_test.go b/kernel/plugin/api_storage_test.go
new file mode 100644
index 0000000000..4c582e76a1
--- /dev/null
+++ b/kernel/plugin/api_storage_test.go
@@ -0,0 +1,54 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/dop251/goja"
+)
+
+func TestStorageGetResolvesFileContents(t *testing.T) {
+ p, r := newDataObjectTestPlugin(t)
+ p.storageDir = t.TempDir()
+ if err := os.WriteFile(filepath.Join(p.storageDir, "icon.png"), []byte("png"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ siyuan := rt.NewObject()
+ if err = injectStorage(p, rt, siyuan); err == nil {
+ err = rt.Set("siyuan", siyuan)
+ }
+ })
+ if err != nil {
+ t.Fatalf("inject storage: %v", err)
+ }
+
+ // 存储文件没有媒体类型:即使扩展名对应某种类型,blob() 的 type 也为空串。
+ got := r.await(`(async () => {
+ const data = await siyuan.storage.get("icon.png");
+ const blob = await data.blob();
+ return JSON.stringify([await data.text(), Array.from(await data.bytes()), blob.type, await blob.text()]);
+ })()`)
+ if want := `["png",[112,110,103],"","png"]`; got != want {
+ t.Fatalf("storage data = %s, want %s", got, want)
+ }
+}
diff --git a/kernel/plugin/crypto/errors.go b/kernel/plugin/crypto/errors.go
index 59c9b905a3..014e84b06f 100644
--- a/kernel/plugin/crypto/errors.go
+++ b/kernel/plugin/crypto/errors.go
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-// Package crypto 以 Go 标准库实现 Web Crypto API 的算法层,供内核插件沙箱的 siyuan.crypto 绑定调用。
+// Package crypto 以 Go 标准库实现 Web Crypto API 的算法层,供内核插件沙箱的 globalThis.crypto 绑定调用。
// 该包不依赖 goja,密钥材料只保存在 Go 侧,不向插件脚本暴露。
package crypto
diff --git a/kernel/plugin/encoding/LICENSE b/kernel/plugin/encoding/LICENSE
new file mode 100644
index 0000000000..43533e246a
--- /dev/null
+++ b/kernel/plugin/encoding/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Grafana Labs
+
+ 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.
diff --git a/kernel/plugin/encoding/doc.go b/kernel/plugin/encoding/doc.go
new file mode 100644
index 0000000000..005a443814
--- /dev/null
+++ b/kernel/plugin/encoding/doc.go
@@ -0,0 +1,55 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/doc.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek。
+
+// Package encoding implements the WHATWG Encoding Standard for goja runtimes.
+//
+// This package provides TextEncoder and TextDecoder implementations that can be
+// registered with a goja runtime to provide Web-compatible text encoding/decoding
+// capabilities in JavaScript.
+//
+// # Supported Encodings
+//
+// The package supports the following encodings:
+// - UTF-8 (default)
+// - UTF-16LE (little-endian)
+// - UTF-16BE (big-endian)
+//
+// # Usage
+//
+// RegisterRuntime reads TextDecoder/TextDecoder.decode options (e.g. "fatal",
+// "ignoreBOM", "stream") from JS objects by matching their spec names against
+// this package's Go struct fields. goja only does that matching when a
+// [goja.FieldNameMapper] is configured on the runtime, and
+// RegisterRuntime deliberately leaves that choice to the caller: it is a
+// runtime-wide setting, and forcing one here would override a field name
+// mapper the host application has already configured for its own use (for
+// example a JS runtime embedding goja for other purposes). Callers must set
+// one themselves, such as [goja.TagFieldNameMapper] configured for the "js"
+// tag used by this package's option structs, before relying on any TextDecoder
+// option. The option structs retain equivalent "json" tags for callers that
+// already use a JSON-tag mapper.
+//
+// rt := goja.New()
+// rt.SetFieldNameMapper(goja.TagFieldNameMapper("js", true))
+// if err := encoding.RegisterRuntime(rt); err != nil {
+// log.Fatal(err)
+// }
+//
+// Without a field name mapper, options such as {fatal: true} are silently
+// ignored: ExportTo falls back to matching the exact exported Go field name
+// (e.g. "Fatal"), which no spec-compliant JS caller will ever pass.
+//
+// After registration, TextEncoder and TextDecoder are available in JavaScript:
+//
+// const encoder = new TextEncoder();
+// const encoded = encoder.encode("Hello, World!");
+//
+// const decoder = new TextDecoder("utf-8");
+// const decoded = decoder.decode(encoded);
+//
+// # Specification
+//
+// This implementation follows the WHATWG Encoding Standard:
+// https://encoding.spec.whatwg.org/
+package encoding
diff --git a/kernel/plugin/encoding/error.go b/kernel/plugin/encoding/error.go
new file mode 100644
index 0000000000..218f2d02af
--- /dev/null
+++ b/kernel/plugin/encoding/error.go
@@ -0,0 +1,72 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/error.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek。
+
+package encoding
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+)
+
+// ErrorName identifies the category of an encoding error.
+type ErrorName string
+
+const (
+ // RangeError is thrown if the value of label is unknown, or
+ // is one of the values leading to a 'replacement' decoding
+ // algorithm ("iso-2022-cn" or "iso-2022-cn-ext").
+ RangeError ErrorName = "RangeError"
+
+ // TypeError is thrown if the value if the Decoder fatal option
+ // is set and the input data cannot be decoded.
+ TypeError ErrorName = "TypeError"
+)
+
+// Error represents an encoding error.
+type Error struct {
+ // Name contains one of the strings associated with an error name.
+ Name ErrorName `json:"name"`
+
+ // Message represents message or description associated with the given error name.
+ Message string `json:"message"`
+}
+
+// JSError creates a JavaScript error object that can be thrown
+func (e *Error) JSError(rt *goja.Runtime) *goja.Object {
+ var constructor *goja.Object
+
+ switch e.Name {
+ case TypeError:
+ constructor = rt.Get("TypeError").ToObject(rt)
+ case RangeError:
+ constructor = rt.Get("RangeError").ToObject(rt)
+ default:
+ constructor = rt.Get("Error").ToObject(rt)
+ }
+
+ errorObj, err := rt.New(constructor, rt.ToValue(e.Message))
+ if err != nil {
+ // Fallback to generic error
+ errorObj = rt.ToValue(fmt.Errorf("%s: %s", e.Name, e.Message)).ToObject(rt)
+ }
+
+ return errorObj
+}
+
+// Error implements the `error` interface.
+func (e *Error) Error() string {
+ return fmt.Sprintf("%s: %s", e.Name, e.Message)
+}
+
+// NewError returns a new Error instance.
+func NewError(name ErrorName, message string) *Error {
+ return &Error{
+ Name: name,
+ Message: message,
+ }
+}
+
+// Ensure Error implements the error interface at compile time.
+var _ error = (*Error)(nil)
diff --git a/kernel/plugin/encoding/goja.go b/kernel/plugin/encoding/goja.go
new file mode 100644
index 0000000000..c2fca7b592
--- /dev/null
+++ b/kernel/plugin/encoding/goja.go
@@ -0,0 +1,219 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/sobek.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek,文件由 sobek.go 更名为 goja.go。
+
+package encoding
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/dop251/goja"
+)
+
+// RegisterRuntime exports the TextDecoder and TextEncoder constructors into the provided goja runtime.
+//
+// It does not configure rt's [goja.FieldNameMapper]: doing so unconditionally
+// would override a mapper the host application may have already set for its
+// own purposes. Callers must set a mapper that resolves this package's "js"
+// (or equivalent "json") tags for "fatal", "ignoreBOM", and "stream". For
+// example, configure
+// rt.SetFieldNameMapper(goja.TagFieldNameMapper("js", true)) before
+// registering, or TextDecoder/TextDecoder.decode options will be silently
+// ignored. See the package documentation for details.
+func RegisterRuntime(rt *goja.Runtime) error {
+ if err := bindTextDecoder(rt); err != nil {
+ return err
+ }
+
+ return bindTextEncoder(rt)
+}
+
+func bindTextDecoder(rt *goja.Runtime) error {
+ constructor := func(call goja.ConstructorCall) *goja.Object {
+ label := "utf-8"
+ if arg := call.Argument(0); arg != nil && !isNullish(arg) {
+ // Per the WebIDL USVString conversion rules, a Symbol cannot be
+ // coerced to a string and must throw a TypeError; unlike real
+ // string coercion, goja's ExportTo would otherwise silently
+ // convert it to its description instead of erroring.
+ if _, isSymbol := arg.(*goja.Symbol); isSymbol {
+ throwAsJSError(rt, NewError(TypeError, "the provided label value cannot be converted to a string"))
+ }
+
+ if err := rt.ExportTo(arg, &label); err != nil {
+ throwAsJSError(rt, NewError(RangeError, "extracting label from the first argument: "+err.Error()))
+ }
+ }
+
+ var options TextDecoderOptions
+ if arg := call.Argument(1); arg != nil && !isNullish(arg) {
+ if err := rt.ExportTo(arg, &options); err != nil {
+ panic(rt.NewGoError(err))
+ }
+ }
+
+ td, err := NewTextDecoder(label, options)
+ if err != nil {
+ throwAsJSError(rt, err)
+ }
+
+ return newTextDecoderObject(rt, td)
+ }
+
+ return rt.Set("TextDecoder", constructor)
+}
+
+func bindTextEncoder(rt *goja.Runtime) error {
+ constructor := func(_ goja.ConstructorCall) *goja.Object {
+ return newTextEncoderObject(rt, NewTextEncoder())
+ }
+
+ return rt.Set("TextEncoder", constructor)
+}
+
+// newTextDecoderObject converts the given TextDecoder instance into a JS object.
+//
+// It is used by the TextDecoder constructor to convert the Go instance into a JS,
+// and will also set the relevant properties as read-only as per the spec.
+//
+// In the event setting the properties on the object where to fail, the function
+// will throw a JS exception.
+func newTextDecoderObject(rt *goja.Runtime, td *TextDecoder) *goja.Object {
+ obj := rt.NewObject()
+
+ // Wrap the Go TextDecoder.Decode method in a JS function
+ decodeMethod := func(call goja.FunctionCall) goja.Value {
+ // Handle variable arguments - buffer can be undefined/missing
+ var buffer goja.Value
+ if len(call.Arguments) > 0 {
+ buffer = call.Arguments[0]
+ }
+
+ // Handle options parameter
+ var options TextDecodeOptions
+ if len(call.Arguments) > 1 && !isNullish(call.Arguments[1]) {
+ if err := rt.ExportTo(call.Arguments[1], &options); err != nil {
+ panic(rt.NewGoError(err))
+ }
+ }
+
+ data, err := exportArrayBuffer(rt, buffer)
+ if err != nil {
+ panic(rt.NewGoError(err))
+ }
+
+ decoded, err := td.Decode(data, options)
+ if err != nil {
+ throwAsJSError(rt, err)
+ }
+
+ return rt.ToValue(decoded)
+ }
+
+ // Set the decode method to the wrapper function we just created
+ if err := setReadOnlyPropertyOf(obj, "decode", rt.ToValue(decodeMethod)); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining decode read-only property on TextDecoder object: %w", err)))
+ }
+
+ // Set the encoding property
+ if err := setReadOnlyPropertyOf(obj, "encoding", rt.ToValue(string(td.Encoding))); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining encoding read-only property on TextDecoder object: %w", err)))
+ }
+
+ // Set the fatal property
+ if err := setReadOnlyPropertyOf(obj, "fatal", rt.ToValue(td.Fatal)); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining fatal read-only property on TextDecoder object: %w", err)))
+ }
+
+ // Set the ignoreBOM property
+ if err := setReadOnlyPropertyOf(obj, "ignoreBOM", rt.ToValue(td.IgnoreBOM)); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining ignoreBOM read-only property on TextDecoder object: %w", err)))
+ }
+
+ return obj
+}
+
+func newTextEncoderObject(rt *goja.Runtime, te *TextEncoder) *goja.Object {
+ obj := rt.NewObject()
+
+ // Wrap the Go TextEncoder.Encode method in a JS function
+ encodeMethod := func(value goja.Value) *goja.Object {
+ // Handle undefined/null values by defaulting to empty string
+ var text string
+ if isNullish(value) {
+ text = ""
+ } else {
+ text = value.String()
+ }
+
+ buffer, err := te.Encode(text)
+ if err != nil {
+ throwAsJSError(rt, err)
+ }
+
+ // Create a new Uint8Array from the buffer
+ u, err := rt.New(rt.Get("Uint8Array"), rt.ToValue(rt.NewArrayBuffer(buffer)))
+ if err != nil {
+ panic(rt.NewGoError(err))
+ }
+
+ return u
+ }
+
+ // Set the encode property by wrapping the Go function in a JS function
+ if err := setReadOnlyPropertyOf(obj, "encode", rt.ToValue(encodeMethod)); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining encode read-only method on TextEncoder object: %w", err)))
+ }
+
+ // Set the encoding property
+ if err := setReadOnlyPropertyOf(obj, "encoding", rt.ToValue(string(te.Encoding))); err != nil {
+ panic(rt.NewGoError(fmt.Errorf("defining encoding read-only property on TextEncoder object: %w", err)))
+ }
+
+ return obj
+}
+
+func throwAsJSError(rt *goja.Runtime, err error) {
+ var encErr *Error
+ if errors.As(err, &encErr) {
+ panic(encErr.JSError(rt))
+ }
+
+ panic(rt.NewGoError(err))
+}
+
+// setReadOnlyPropertyOf sets a read-only property on the given [goja.Object].
+func setReadOnlyPropertyOf(obj *goja.Object, name string, value goja.Value) error {
+ err := obj.DefineDataProperty(name,
+ value,
+ goja.FLAG_FALSE,
+ goja.FLAG_FALSE,
+ goja.FLAG_TRUE,
+ )
+ if err != nil {
+ return fmt.Errorf("defining %s read-only property: %w", name, err)
+ }
+
+ return nil
+}
+
+// exportArrayBuffer interprets the given value as an ArrayBuffer, TypedArray or DataView
+// and returns the underlying byte slice, backed by the original data (no copy is
+// performed, per [goja.Runtime.ExportTo]'s documented behavior for these types).
+func exportArrayBuffer(rt *goja.Runtime, v goja.Value) ([]byte, error) {
+ if isNullish(v) {
+ return []byte{}, nil
+ }
+
+ var data []byte
+ if err := rt.ExportTo(v, &data); err != nil {
+ return nil, errors.New("data is not an ArrayBuffer, typed array, or DataView")
+ }
+
+ return data, nil
+}
+
+func isNullish(v goja.Value) bool {
+ return v == nil || goja.IsUndefined(v) || goja.IsNull(v)
+}
diff --git a/kernel/plugin/encoding/module.go b/kernel/plugin/encoding/module.go
new file mode 100644
index 0000000000..3ef50f9faa
--- /dev/null
+++ b/kernel/plugin/encoding/module.go
@@ -0,0 +1,27 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package encoding
+
+import "github.com/dop251/goja"
+
+// Enable 把 TextEncoder 与 TextDecoder 构造函数挂到 runtime 的 globalThis,调用方式与 goja_nodejs 的 url、buffer、console
+// 一致,失败时 panic。TextDecoder 的 fatal、ignoreBOM、stream 选项依赖 runtime 已设置能识别 json 或 js 标签的字段名映射。
+func Enable(runtime *goja.Runtime) {
+ if err := RegisterRuntime(runtime); err != nil {
+ panic(err)
+ }
+}
diff --git a/kernel/plugin/encoding/module_test.go b/kernel/plugin/encoding/module_test.go
new file mode 100644
index 0000000000..fda81809c8
--- /dev/null
+++ b/kernel/plugin/encoding/module_test.go
@@ -0,0 +1,116 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 register_test.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek,文件由 register_test.go 更名为 module_test.go,
+// 改为测试本包的 Enable。
+
+package encoding
+
+import (
+ "testing"
+
+ "github.com/dop251/goja"
+)
+
+// TestEnable exercises Enable end to end against a plain goja runtime.
+func TestEnable(t *testing.T) {
+ t.Parallel()
+
+ rt := goja.New()
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+
+ Enable(rt)
+
+ v, err := rt.RunString(`
+ const encoder = new TextEncoder();
+ const encoded = encoder.encode("Hello, World!");
+
+ const decoder = new TextDecoder("utf-8");
+ const decoded = decoder.decode(encoded);
+
+ if (decoded !== "Hello, World!") {
+ throw new Error("unexpected decoded value: " + decoded);
+ }
+
+ decoded;
+ `)
+ if err != nil {
+ t.Fatalf("unexpected error running script: %v", err)
+ }
+
+ if got := v.String(); got != "Hello, World!" {
+ t.Fatalf("expected %q, got %q", "Hello, World!", got)
+ }
+}
+
+// TestEnableFatalOption guards against Enable leaving
+// TextDecoder options such as "fatal" inert when the caller has configured a
+// field name mapper as documented.
+func TestEnableFatalOption(t *testing.T) {
+ t.Parallel()
+
+ rt := goja.New()
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+
+ Enable(rt)
+
+ _, err := rt.RunString(`
+ const decoder = new TextDecoder("utf-8", { fatal: true });
+ if (decoder.fatal !== true) {
+ throw new Error("expected decoder.fatal to be true");
+ }
+
+ let threw = false;
+ try {
+ decoder.decode(new Uint8Array([0xFF]));
+ } catch (e) {
+ threw = e instanceof TypeError;
+ }
+ if (!threw) {
+ throw new Error("expected decode() to throw a TypeError for invalid input");
+ }
+ `)
+ if err != nil {
+ t.Fatalf("unexpected error running script: %v", err)
+ }
+}
+
+// TestEnableJSOptions guards the option names used by k6's
+// JavaScript field-name mapper.
+func TestEnableJSOptions(t *testing.T) {
+ t.Parallel()
+
+ rt := goja.New()
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("js", true))
+
+ Enable(rt)
+
+ _, err := rt.RunString(`
+ const decoder = new TextDecoder("utf-8", {
+ fatal: true,
+ ignoreBOM: true,
+ });
+ if (decoder.fatal !== true) {
+ throw new Error("expected decoder.fatal to be true");
+ }
+ if (decoder.ignoreBOM !== true) {
+ throw new Error("expected decoder.ignoreBOM to be true");
+ }
+
+ const streamingDecoder = new TextDecoder();
+ const first = streamingDecoder.decode(
+ new Uint8Array([0xE2, 0x82]),
+ { stream: true },
+ );
+ if (first !== "") {
+ throw new Error("expected incomplete streaming input to be buffered");
+ }
+
+ const second = streamingDecoder.decode(new Uint8Array([0xAC]));
+ if (second !== "€") {
+ throw new Error("expected buffered streaming input to decode to the euro sign");
+ }
+ `)
+ if err != nil {
+ t.Fatalf("unexpected error running script: %v", err)
+ }
+}
diff --git a/kernel/plugin/encoding/test_setup_test.go b/kernel/plugin/encoding/test_setup_test.go
new file mode 100644
index 0000000000..6f13305371
--- /dev/null
+++ b/kernel/plugin/encoding/test_setup_test.go
@@ -0,0 +1,51 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/test_setup_test.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek,去掉加载 WPT 测试框架与夹具的部分。
+
+package encoding
+
+import (
+ "testing"
+
+ "github.com/dop251/goja"
+)
+
+// testSetup wraps a goja runtime configured with the encoding Web API.
+type testSetup struct {
+ rt *goja.Runtime
+}
+
+func newTestSetup(t testing.TB) *testSetup {
+ t.Helper()
+
+ rt := goja.New()
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+
+ mustNoError(t, RegisterRuntime(rt))
+
+ return &testSetup{rt: rt}
+}
+
+func mustNoError(t testing.TB, err error) {
+ t.Helper()
+
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func mustError(t testing.TB, err error) {
+ t.Helper()
+
+ if err == nil {
+ t.Fatal("expected error")
+ }
+}
+
+func mustEqual[T comparable](t testing.TB, expected, actual T) {
+ t.Helper()
+
+ if expected != actual {
+ t.Fatalf("expected %#v, got %#v", expected, actual)
+ }
+}
diff --git a/kernel/plugin/encoding/text_decoder.go b/kernel/plugin/encoding/text_decoder.go
new file mode 100644
index 0000000000..eee309562b
--- /dev/null
+++ b/kernel/plugin/encoding/text_decoder.go
@@ -0,0 +1,532 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/text_decoder.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek。
+
+package encoding
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "golang.org/x/text/encoding"
+ "golang.org/x/text/encoding/unicode"
+ "golang.org/x/text/transform"
+)
+
+// TextDecoder represents a decoder for a specific text encoding, such
+// as UTF-8, UTF-16LE, or UTF-16BE.
+//
+// A decoder takes a stream of bytes as input and emits a stream of code points.
+//
+// See https://encoding.spec.whatwg.org/#textdecoder
+type TextDecoder struct {
+ TextDecoderCommon
+
+ decoder encoding.Encoding
+ transform transform.Transformer
+
+ buffer []byte
+}
+
+// TextDecoderOptions represents the options that can be passed to the
+// TextDecoder constructor.
+type TextDecoderOptions struct {
+ // Fatal holds a boolean value indicating if the TextDecoder.decode()
+ // method must throw a TypeError when decoding invalid data.
+ //
+ // It defaults to false, which means that the decoder will substitute
+ // malformed data with a replacement character (U+FFFD).
+ Fatal bool `json:"fatal" js:"fatal"`
+
+ // IgnoreBOM holds a boolean value indicating whether the byte order
+ // mark (BOM) is ignored.
+ IgnoreBOM bool `json:"ignoreBOM" js:"ignoreBOM"`
+}
+
+// TextDecoderCommon represents the common subset of the TextDecoder interface
+// that is shared between the TextDecoder and TextDecoderStream interfaces.
+//
+// See https://encoding.spec.whatwg.org/#textdecodercommon
+type TextDecoderCommon struct {
+ // Encoding holds the name of the decoder, which is a string describing
+ // the method the TextDecoder will use.
+ Encoding Name `json:"encoding"`
+
+ // Fatal holds a boolean value indicating if the TextDecoder.decode()
+ // method must throw a TypeError when decoding invalid data.
+ //
+ // It defaults to false, which means that the decoder will substitute
+ // malformed data with a replacement character (U+FFFD).
+ Fatal bool `json:"fatal"`
+
+ // IgnoreBOM holds a boolean value indicating whether the byte order
+ // mark (BOM) is ignored.
+ IgnoreBOM bool `json:"ignoreBOM"`
+}
+
+// NewTextDecoder returns a new TextDecoder object instance that will
+// generate a string from a byte stream with a specific encoding.
+//
+// Implementation follows the WHATWG Encoding spec:
+// https://encoding.spec.whatwg.org/#dom-textdecoder
+func NewTextDecoder(label string, options TextDecoderOptions) (*TextDecoder, error) {
+ // Pick the encoding BOM policy accordingly
+ bomPolicy := unicode.IgnoreBOM
+ if !options.IgnoreBOM {
+ bomPolicy = unicode.UseBOM
+ }
+
+ // Step 1: Let encoding be the result of getting an encoding from label.
+ var enc Name
+ var decoder encoding.Encoding
+ // Trim ASCII whitespace only (TAB, LF, FF, CR, SPACE); it's narrower than
+ // Unicode whitespace, which get-an-encoding's label trimming step needs.
+ switch strings.Trim(strings.ToLower(label), "\t\n\f\r ") {
+ case "",
+ "unicode-1-1-utf-8",
+ "unicode11utf8",
+ "unicode20utf8",
+ "utf-8",
+ "utf8",
+ "x-unicode20utf8":
+ enc = UTF8EncodingFormat
+ decoder = unicode.UTF8
+ case "csunicode",
+ "iso-10646-ucs-2",
+ "ucs-2",
+ "unicode",
+ "unicodefeff",
+ "utf-16",
+ "utf-16le":
+ enc = UTF16LEEncodingFormat
+ decoder = unicode.UTF16(unicode.LittleEndian, bomPolicy)
+ case "unicodefffe", "utf-16be":
+ enc = UTF16BEEncodingFormat
+ decoder = unicode.UTF16(unicode.BigEndian, bomPolicy)
+ default:
+ // Step 2: If encoding is failure or replacement, throw a RangeError.
+ return nil, NewError(RangeError, fmt.Sprintf("unsupported encoding: %s", label))
+ }
+
+ // Step 3: Set this's encoding to encoding.
+ td := &TextDecoder{}
+ td.Encoding = enc
+ td.decoder = decoder
+
+ // Step 4: If options["fatal"] is true, set this's error mode to "fatal".
+ if options.Fatal {
+ td.Fatal = true
+ }
+
+ // Step 5: Set this's ignore BOM to options["ignoreBOM"].
+ td.IgnoreBOM = options.IgnoreBOM
+
+ return td, nil
+}
+
+// appendReplacementCharUTF8 appends the UTF-8 encoded form of U+FFFD.
+func appendReplacementCharUTF8(dst []byte) []byte {
+ return append(dst, 0xEF, 0xBF, 0xBD)
+}
+
+const (
+ // utf8MaxBytesPerCodePoint is the max expansion factor for UTF-8 decoding.
+ utf8MaxBytesPerCodePoint = 4
+ // minTransformBufferSize is the minimum buffer used for streaming transforms.
+ minTransformBufferSize = 64
+)
+
+// Decode takes a byte stream as input and returns a string.
+func (td *TextDecoder) Decode(buffer []byte, options TextDecodeOptions) (string, error) {
+ if td.decoder == nil {
+ return "", errors.New("encoding not set")
+ }
+
+ if td.Encoding == UTF8EncodingFormat {
+ return td.decodeUTF8(buffer, options)
+ }
+
+ return td.decodeUTF16(buffer, options)
+}
+
+func (td *TextDecoder) decodeUTF8(buffer []byte, options TextDecodeOptions) (string, error) {
+ stream := options.Stream
+
+ if td.transform == nil {
+ decoder := td.decoder.NewDecoder()
+ if !td.IgnoreBOM {
+ td.transform = unicode.BOMOverride(decoder)
+ } else {
+ td.transform = decoder
+ }
+ }
+
+ combined := append(append([]byte{}, td.buffer...), buffer...)
+ td.buffer = td.buffer[:0]
+
+ processed, leftover, hadInvalid := sanitizeUTF8Bytes(combined, stream)
+ if len(leftover) > 0 {
+ td.buffer = append(td.buffer, leftover...)
+ }
+
+ atEOF := !stream
+ if stream && len(td.buffer) == 0 {
+ atEOF = true
+ }
+
+ decoded, _, err := td.applyTransform(processed, atEOF)
+ if err != nil && !errors.Is(err, transform.ErrShortDst) && !errors.Is(err, transform.ErrShortSrc) {
+ if td.Fatal {
+ td.resetState()
+ return "", NewError(TypeError, "decoding text: "+err.Error())
+ }
+ return "", err
+ }
+
+ if td.Fatal && hadInvalid {
+ td.resetState()
+ return "", NewError(TypeError, "decoding text: invalid byte sequence")
+ }
+
+ if !stream {
+ td.resetState()
+ }
+
+ return decoded, nil
+}
+
+func (td *TextDecoder) decodeUTF16(buffer []byte, options TextDecodeOptions) (string, error) {
+ stream := options.Stream
+
+ if td.transform == nil {
+ td.transform = td.decoder.NewDecoder()
+ }
+
+ // Keep td.buffer as the canonical byte queue so sequences that span multiple
+ // calls (e.g., surrogate pairs) remain intact until the transformer consumes
+ // them.
+ td.buffer = append(td.buffer, buffer...)
+
+ processLen := len(td.buffer)
+ var pending []byte
+
+ if stream {
+ if processLen%2 == 1 {
+ processLen--
+ }
+ } else if processLen%2 == 1 {
+ pending = append(pending, td.buffer[processLen-1])
+ processLen--
+ }
+
+ var decoded string
+ var err error
+ var consumed int
+ var hadInvalid bool
+
+ if processLen > 0 {
+ toDecode := td.buffer[:processLen]
+ decoded, consumed, err = td.applyTransform(toDecode, !stream)
+ if consumed > 0 {
+ hadInvalid = hasInvalidUTF16Surrogate(toDecode[:consumed], td.Encoding == UTF16BEEncodingFormat)
+ }
+ td.buffer = append(td.buffer[:0], td.buffer[consumed:]...)
+ } else {
+ decoded, _, err = td.applyTransform(nil, !stream)
+ }
+ if err != nil && !errors.Is(err, transform.ErrShortDst) && !errors.Is(err, transform.ErrShortSrc) {
+ if td.Fatal {
+ td.resetState()
+ return "", NewError(TypeError, "decoding text: "+err.Error())
+ }
+ return "", err
+ }
+
+ var builder strings.Builder
+ builder.WriteString(decoded)
+
+ if len(pending) > 0 {
+ if td.Fatal {
+ td.resetState()
+ return "", NewError(TypeError, "decoding text: invalid byte sequence")
+ }
+ builder.WriteRune('\uFFFD')
+ }
+
+ result := builder.String()
+
+ if td.Fatal && hadInvalid {
+ td.resetState()
+ return "", NewError(TypeError, "decoding text: invalid byte sequence")
+ }
+
+ if !stream {
+ td.resetState()
+ }
+
+ return result, nil
+}
+
+// hasInvalidUTF16Surrogate reports whether data (a sequence of 2-byte code
+// units in the given endianness) contains a lone/unpaired UTF-16 surrogate.
+//
+// The x/text UTF-16 decoder substitutes such sequences with U+FFFD without
+// surfacing an error, so this scans the source bytes directly rather than
+// inferring invalidity from the decoded output (which cannot distinguish a
+// substitution from a legitimately-encoded U+FFFD character).
+func hasInvalidUTF16Surrogate(data []byte, bigEndian bool) bool {
+ for i := 0; i+1 < len(data); i += 2 {
+ unit := decodeUTF16CodeUnit(data[i], data[i+1], bigEndian)
+
+ switch {
+ case isUTF16HighSurrogate(unit):
+ if i+3 >= len(data) {
+ return true
+ }
+
+ next := decodeUTF16CodeUnit(data[i+2], data[i+3], bigEndian)
+ if !isUTF16LowSurrogate(next) {
+ return true
+ }
+
+ i += 2
+ case isUTF16LowSurrogate(unit):
+ return true
+ }
+ }
+
+ return false
+}
+
+func decodeUTF16CodeUnit(b0, b1 byte, bigEndian bool) uint16 {
+ if bigEndian {
+ return uint16(b0)<<8 | uint16(b1)
+ }
+ return uint16(b1)<<8 | uint16(b0)
+}
+
+func isUTF16HighSurrogate(u uint16) bool {
+ return u >= 0xD800 && u <= 0xDBFF
+}
+
+func isUTF16LowSurrogate(u uint16) bool {
+ return u >= 0xDC00 && u <= 0xDFFF
+}
+
+// applyTransform applies the decoder's transformer to the input bytes and returns
+// the decoded string along with the number of bytes consumed.
+//
+// The atEOF parameter indicates whether this is the final chunk of input. When true,
+// the transformer will flush any pending state and report errors for incomplete sequences.
+// The function handles transform.ErrShortDst by growing the destination buffer as needed.
+func (td *TextDecoder) applyTransform(input []byte, atEOF bool) (string, int, error) {
+ if td.transform == nil {
+ return "", 0, errors.New("transformer not initialized")
+ }
+
+ if len(input) == 0 {
+ if atEOF {
+ empty := make([]byte, 0)
+ if _, _, err := td.transform.Transform(empty, empty, true); err != nil &&
+ !errors.Is(err, transform.ErrShortDst) &&
+ !errors.Is(err, transform.ErrShortSrc) {
+ return "", 0, err
+ }
+ }
+ return "", 0, nil
+ }
+
+ destSize := max(len(input)*utf8MaxBytesPerCodePoint+minTransformBufferSize, minTransformBufferSize)
+ dest := make([]byte, destSize)
+
+ var (
+ builder strings.Builder
+ src = input
+ consumed int
+ )
+
+ for len(src) > 0 {
+ nDst, nSrc, err := td.transform.Transform(dest, src, atEOF)
+ builder.Write(dest[:nDst])
+ src = src[nSrc:]
+ consumed += nSrc
+
+ if err == nil {
+ continue
+ }
+
+ if errors.Is(err, transform.ErrShortDst) {
+ if nSrc == 0 {
+ dest = make([]byte, len(dest)*2)
+ }
+ continue
+ }
+
+ if errors.Is(err, transform.ErrShortSrc) && !atEOF {
+ break
+ }
+
+ if !errors.Is(err, transform.ErrShortSrc) && !errors.Is(err, transform.ErrShortDst) {
+ return "", consumed, err
+ }
+ }
+
+ return builder.String(), consumed, nil
+}
+
+func (td *TextDecoder) resetState() {
+ if td.transform != nil {
+ td.transform.Reset()
+ td.transform = nil
+ }
+ td.buffer = nil
+}
+
+// sanitizeUTF8Bytes validates and processes UTF-8 byte sequences, handling
+// incomplete and invalid sequences according to the WHATWG Encoding spec.
+//
+// It returns:
+// - processed: valid UTF-8 bytes with invalid sequences replaced by U+FFFD
+// - leftover: incomplete trailing bytes (only when stream=true)
+// - hadInvalid: true if any invalid sequences were encountered
+//
+// When stream is true, incomplete multi-byte sequences at the end of the input
+// are preserved in leftover for the next chunk. When stream is false (final chunk),
+// incomplete sequences are replaced with U+FFFD.
+//
+// This function implements the "replacement" error mode behavior where malformed
+// byte sequences are replaced with the Unicode replacement character (U+FFFD).
+//
+// This duplicates validation logic golang.org/x/text/encoding/unicode's own
+// UTF-8 decoder already contains, but that decoder's Transform cannot be used
+// here directly: when it is short on source bytes and atEOF is false, it
+// always waits for more data via transform.ErrShortSrc, even if the bytes
+// already available prove the sequence malformed (e.g. a lead byte followed
+// by a byte outside the valid continuation range). It only resolves such a
+// sequence once atEOF is true. The WHATWG spec instead requires detecting an
+// invalid continuation byte as soon as it is seen, independent of whether the
+// caller is still streaming (see TestTextDecoderUTF8StreamingStateMachine's
+// IncompleteThenInvalidContinuation case). Hence this package needs its own
+// incremental scan rather than delegating to the transform's error signal.
+func sanitizeUTF8Bytes(data []byte, stream bool) (processed []byte, leftover []byte, hadInvalid bool) {
+ if len(data) == 0 {
+ return nil, nil, false
+ }
+
+ processed = make([]byte, 0, len(data))
+
+ for i := 0; i < len(data); {
+ b := data[i]
+
+ if b < 0x80 {
+ processed = append(processed, b)
+ i++
+ continue
+ }
+
+ var needed int
+ switch {
+ case b >= 0xC2 && b <= 0xDF:
+ needed = 2
+ case b >= 0xE0 && b <= 0xEF:
+ needed = 3
+ case b >= 0xF0 && b <= 0xF4:
+ needed = 4
+ default:
+ hadInvalid = true
+ processed = appendReplacementCharUTF8(processed)
+ i++
+ continue
+ }
+
+ validCount := 0
+ incomplete := false
+ invalidSeq := false
+ for j := 1; j < needed; j++ {
+ idx := i + j
+ if idx >= len(data) {
+ if stream {
+ leftover = append([]byte{}, data[i:]...)
+ return processed, leftover, hadInvalid
+ }
+ incomplete = true
+ break
+ }
+
+ cb := data[idx]
+ if !isValidContinuationByte(cb) || !passesUTF8RangeChecks(b, j, cb) {
+ invalidSeq = true
+ break
+ }
+ validCount++
+ }
+
+ if invalidSeq {
+ hadInvalid = true
+ processed = appendReplacementCharUTF8(processed)
+ i += 1 + validCount
+ continue
+ }
+
+ if incomplete {
+ hadInvalid = true
+ processed = appendReplacementCharUTF8(processed)
+ i += 1 + validCount
+ continue
+ }
+
+ processed = append(processed, data[i:i+needed]...)
+ i += needed
+ continue
+ }
+
+ return processed, leftover, hadInvalid
+}
+
+// isValidContinuationByte checks if a byte is a valid UTF-8 continuation byte.
+// Continuation bytes have the bit pattern 10xxxxxx (0x80-0xBF).
+func isValidContinuationByte(b byte) bool {
+ return b&0xC0 == 0x80
+}
+
+// passesUTF8RangeChecks validates that continuation bytes fall within valid ranges
+// for specific UTF-8 start bytes. This rejects overlong encodings and surrogate pairs.
+//
+// The checks are:
+// - 0xE0: First continuation must be >= 0xA0 (rejects overlong 2-byte forms of U+0000-U+07FF)
+// - 0xED: First continuation must be <= 0x9F (rejects surrogate pairs U+D800-U+DFFF)
+// - 0xF0: First continuation must be >= 0x90 (rejects overlong 3-byte forms of U+0000-U+FFFF)
+// - 0xF4: First continuation must be <= 0x8F (rejects code points > U+10FFFF)
+func passesUTF8RangeChecks(start byte, position int, cont byte) bool {
+ switch start {
+ case 0xE0:
+ if position == 1 {
+ return cont >= 0xA0 && cont <= 0xBF
+ }
+ case 0xED:
+ if position == 1 {
+ return cont >= 0x80 && cont <= 0x9F
+ }
+ case 0xF0:
+ if position == 1 {
+ return cont >= 0x90 && cont <= 0xBF
+ }
+ case 0xF4:
+ if position == 1 {
+ return cont >= 0x80 && cont <= 0x8F
+ }
+ }
+ return true
+}
+
+// TextDecodeOptions represents the options that can be passed to the
+// TextDecoder.decode() method.
+type TextDecodeOptions struct {
+ // A boolean flag indicating whether additional data
+ // will follow in subsequent calls to decode().
+ //
+ // Set to true if processing the data in chunks, and
+ // false for the final chunk or if the data is not chunked.
+ Stream bool `json:"stream" js:"stream"`
+}
diff --git a/kernel/plugin/encoding/text_decoder_test.go b/kernel/plugin/encoding/text_decoder_test.go
new file mode 100644
index 0000000000..f4ac212a74
--- /dev/null
+++ b/kernel/plugin/encoding/text_decoder_test.go
@@ -0,0 +1,288 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/text_decoder_test.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek,去掉依赖 WPT 夹具的 TestTextDecoder。
+
+package encoding
+
+import (
+ "strings"
+ "testing"
+
+ "golang.org/x/text/encoding/unicode"
+)
+
+func TestTextDecoderUTF8StreamingStateMachine(t *testing.T) {
+ t.Parallel()
+
+ t.Run("IncompleteThenInvalidContinuation", func(t *testing.T) {
+ t.Parallel()
+ td := &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF8EncodingFormat,
+ },
+ decoder: unicode.UTF8,
+ }
+
+ out, err := td.Decode([]byte{0xF0, 0x9F}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+
+ out, err = td.Decode([]byte{0x41}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "\uFFFDA", out)
+
+ out, err = td.Decode(nil, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+ })
+
+ t.Run("ImmediateInvalidStartByte", func(t *testing.T) {
+ t.Parallel()
+ td := &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF8EncodingFormat,
+ },
+ decoder: unicode.UTF8,
+ }
+
+ out, err := td.Decode([]byte{0xC1}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "\uFFFD", out)
+
+ out, err = td.Decode(nil, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+ })
+
+ t.Run("ASCIIStreamingProducesOutput", func(t *testing.T) {
+ t.Parallel()
+ td := &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF8EncodingFormat,
+ },
+ decoder: unicode.UTF8,
+ }
+
+ out, err := td.Decode([]byte("A"), TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "A", out)
+
+ out, err = td.Decode([]byte("B"), TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "B", out)
+
+ out, err = td.Decode(nil, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+ })
+
+ t.Run("FatalFlushOnTruncatedSequence", func(t *testing.T) {
+ t.Parallel()
+ td := &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF8EncodingFormat,
+ Fatal: true,
+ },
+ decoder: unicode.UTF8,
+ }
+
+ _, err := td.Decode([]byte{0xF0, 0x9F}, TextDecodeOptions{})
+ mustError(t, err)
+ })
+}
+
+func TestTextDecoderUTF16FatalStreaming(t *testing.T) {
+ t.Parallel()
+
+ newFatalDecoder := func() *TextDecoder {
+ return &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF16LEEncodingFormat,
+ Fatal: true,
+ },
+ decoder: unicode.UTF16(unicode.LittleEndian, unicode.UseBOM),
+ }
+ }
+
+ t.Run("OddFollowedByOddCompletes", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ out, err := td.Decode([]byte{0x00}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+
+ out, err = td.Decode([]byte{0x00}, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "\u0000", out)
+ })
+
+ t.Run("EvenThenOddThrows", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ out, err := td.Decode([]byte{0x00, 0x00}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "\u0000", out)
+
+ _, err = td.Decode([]byte{0x00}, TextDecodeOptions{})
+ mustError(t, err)
+ })
+
+ t.Run("OddThenEvenThrows", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ out, err := td.Decode([]byte{0x00}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "", out)
+
+ _, err = td.Decode([]byte{0x00, 0x00}, TextDecodeOptions{})
+ mustError(t, err)
+ })
+
+ t.Run("EvenChunksStreamSuccessfully", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ out, err := td.Decode([]byte{0x00, 0x00}, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ mustEqual(t, "\u0000", out)
+
+ out, err = td.Decode([]byte{0x00, 0x00}, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "\u0000", out)
+ })
+
+ t.Run("LegitimateReplacementCharacterDoesNotThrow", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ // 0xFD, 0xFF little-endian is U+FFFD, a legitimately-encoded
+ // character, not a decode failure.
+ out, err := td.Decode([]byte{0xFD, 0xFF}, TextDecodeOptions{})
+ mustNoError(t, err)
+ mustEqual(t, "\uFFFD", out)
+ })
+
+ t.Run("LoneHighSurrogateThrows", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ // 0x00, 0xD8 little-endian is an unpaired high surrogate.
+ _, err := td.Decode([]byte{0x00, 0xD8}, TextDecodeOptions{})
+ mustError(t, err)
+ })
+
+ t.Run("LoneLowSurrogateThrows", func(t *testing.T) {
+ t.Parallel()
+ td := newFatalDecoder()
+
+ // 0x00, 0xDC little-endian is an unpaired low surrogate.
+ _, err := td.Decode([]byte{0x00, 0xDC}, TextDecodeOptions{})
+ mustError(t, err)
+ })
+}
+
+func TestTextDecoderUTF16LEStreamingSingleByteWindow(t *testing.T) {
+ t.Parallel()
+
+ encoded := []byte{
+ 0x00, 0x00, 0x31, 0x00, 0x32, 0x00, 0x33, 0x00,
+ 0x41, 0x00, 0x42, 0x00, 0x43, 0x00, 0x61, 0x00,
+ 0x62, 0x00, 0x63, 0x00, 0x80, 0x00, 0xFF, 0x00,
+ 0x00, 0x01, 0x00, 0x10, 0xFD, 0xFF, 0x00, 0xD8,
+ 0x00, 0xDC, 0xFF, 0xDB, 0xFF, 0xDF,
+ }
+ expected := "\x00123ABCabc\u0080\u00FF\u0100\u1000\uFFFD\U00010000\U0010FFFF"
+
+ td := &TextDecoder{
+ TextDecoderCommon: TextDecoderCommon{
+ Encoding: UTF16LEEncodingFormat,
+ },
+ decoder: unicode.UTF16(unicode.LittleEndian, unicode.UseBOM),
+ }
+
+ var out strings.Builder
+ for _, b := range encoded {
+ chunk := []byte{b}
+ part, err := td.Decode(chunk, TextDecodeOptions{Stream: true})
+ mustNoError(t, err)
+ out.WriteString(part)
+ }
+
+ part, err := td.Decode(nil, TextDecodeOptions{})
+ mustNoError(t, err)
+ out.WriteString(part)
+
+ mustEqual(t, expected, out.String())
+}
+
+// TestTextDecoderDecodeZeroLengthDataViewAtBufferEnd guards against an
+// off-by-one in exportArrayBuffer's byte extraction that rejected a valid
+// zero-length DataView placed exactly at the end of its buffer.
+func TestTextDecoderDecodeZeroLengthDataViewAtBufferEnd(t *testing.T) {
+ t.Parallel()
+
+ ts := newTestSetup(t)
+
+ v, err := ts.rt.RunScript("test.js", `
+ const decoder = new TextDecoder();
+ decoder.decode(new DataView(new ArrayBuffer(4), 4, 0));
+ `)
+ mustNoError(t, err)
+ mustEqual(t, "", v.String())
+}
+
+// TestExportArrayBufferAliasesBuffer guards exportArrayBuffer's documented
+// contract that it returns a slice aliasing the live ArrayBuffer's backing
+// store, not a copy: mutating the source buffer after the call must be
+// visible through the returned slice. Callers that need to retain the data
+// past a point where JS code could run must copy it themselves.
+func TestExportArrayBufferAliasesBuffer(t *testing.T) {
+ t.Parallel()
+
+ ts := newTestSetup(t)
+
+ v, err := ts.rt.RunScript("test.js", `
+ var buf = new ArrayBuffer(3);
+ var view = new Uint8Array(buf);
+ view[0] = 1;
+ view[1] = 2;
+ view[2] = 3;
+ view;
+ `)
+ mustNoError(t, err)
+
+ data, err := exportArrayBuffer(ts.rt, v)
+ mustNoError(t, err)
+ mustEqual(t, string([]byte{1, 2, 3}), string(data))
+
+ _, err = ts.rt.RunScript("mutate.js", `view[0] = 0xFF; view[1] = 0xFF; view[2] = 0xFF;`)
+ mustNoError(t, err)
+
+ mustEqual(t, string([]byte{0xFF, 0xFF, 0xFF}), string(data))
+}
+
+// TestTextDecoderConstructorSymbolLabelThrowsTypeError guards against
+// the TextDecoder constructor throwing a RangeError for a Symbol label,
+// which per WebIDL USVString conversion rules should be a TypeError since a
+// Symbol cannot be coerced to a string at all.
+func TestTextDecoderConstructorSymbolLabelThrowsTypeError(t *testing.T) {
+ t.Parallel()
+
+ ts := newTestSetup(t)
+
+ _, err := ts.rt.RunScript("test.js", `
+ let threw;
+ try {
+ new TextDecoder(Symbol("x"));
+ } catch (e) {
+ threw = e;
+ }
+ if (!(threw instanceof TypeError)) {
+ throw new Error("expected a TypeError, got " + threw);
+ }
+ `)
+ mustNoError(t, err)
+}
diff --git a/kernel/plugin/encoding/text_encoder.go b/kernel/plugin/encoding/text_encoder.go
new file mode 100644
index 0000000000..0046beb1dc
--- /dev/null
+++ b/kernel/plugin/encoding/text_encoder.go
@@ -0,0 +1,48 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/text_encoder.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek。
+
+package encoding
+
+import (
+ "errors"
+
+ "golang.org/x/text/encoding"
+ "golang.org/x/text/encoding/unicode"
+)
+
+// TextEncoder represents an encoder that will generate a byte stream
+// with UTF-8 encoding.
+//
+// See https://encoding.spec.whatwg.org/#textencoder
+type TextEncoder struct {
+ // Encoding holds the encoding format name, which is always "utf-8"
+ // as per the WHATWG Encoding spec.
+ Encoding Name
+
+ encoder encoding.Encoding
+}
+
+// NewTextEncoder returns a new TextEncoder object instance that will
+// generate a byte stream with UTF-8 encoding.
+func NewTextEncoder() *TextEncoder {
+ return &TextEncoder{
+ encoder: unicode.UTF8,
+ Encoding: UTF8EncodingFormat,
+ }
+}
+
+// Encode takes a string as input and returns an encoded byte stream.
+func (te *TextEncoder) Encode(text string) ([]byte, error) {
+ if te.encoder == nil {
+ return nil, errors.New("encoding not set")
+ }
+
+ enc := te.encoder.NewEncoder()
+ encoded, err := enc.String(text)
+ if err != nil {
+ return nil, NewError(TypeError, "encoding text: "+err.Error())
+ }
+
+ return []byte(encoded), nil
+}
diff --git a/kernel/plugin/encoding/types.go b/kernel/plugin/encoding/types.go
new file mode 100644
index 0000000000..7c398fde69
--- /dev/null
+++ b/kernel/plugin/encoding/types.go
@@ -0,0 +1,20 @@
+// 本文件移植自 https://github.com/grafana/sobek-webapi-encoding 的 encoding/types.go(提交 5785852a34),
+// 按 Apache License 2.0 使用,许可证全文见同目录 LICENSE。
+// 修改:以 github.com/dop251/goja 替换 github.com/grafana/sobek。
+
+package encoding
+
+// Name is the identifier of an encoding format as defined by the WHATWG Encoding spec.
+// See https://encoding.spec.whatwg.org/#names-and-labels
+type Name string
+
+const (
+ // UTF8EncodingFormat is the encoding format for UTF-8.
+ UTF8EncodingFormat Name = "utf-8"
+
+ // UTF16LEEncodingFormat is the encoding format for UTF-16LE (little-endian).
+ UTF16LEEncodingFormat Name = "utf-16le"
+
+ // UTF16BEEncodingFormat is the encoding format for UTF-16BE (big-endian).
+ UTF16BEEncodingFormat Name = "utf-16be"
+)
diff --git a/kernel/plugin/formdata/blob.go b/kernel/plugin/formdata/blob.go
new file mode 100644
index 0000000000..e08cfb31b5
--- /dev/null
+++ b/kernel/plugin/formdata/blob.go
@@ -0,0 +1,364 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import (
+ "math"
+ "reflect"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/plugin/encoding"
+)
+
+var (
+ // blobStateType 用于在 Object.Export() 前先以 Object.ExportType() 做品牌判定,原因见 kernel/plugin/abort 中
+ // signalStateType 的注释。
+ blobStateType = reflect.TypeOf((*blobState)(nil))
+ // arrayBufferExportType 是 ArrayBuffer 对象的导出类型,用于在不调用 Export() 的前提下识别 ArrayBuffer。
+ arrayBufferExportType = reflect.TypeOf(goja.ArrayBuffer{})
+)
+
+var (
+ // crlfReplacer 把 CRLF、单独的 CR 与单独的 LF 统一替换为 CRLF。
+ crlfReplacer = newLineBreakReplacer("\r\n")
+ // nativeLineBreakReplacer 把各种换行统一替换为平台换行符:Windows 为 CRLF,其他平台为 LF。
+ nativeLineBreakReplacer = newLineBreakReplacer(lo.Ternary(runtime.GOOS == "windows", "\r\n", "\n"))
+)
+
+// newLineBreakReplacer 返回把 CRLF、单独的 CR 与单独的 LF 都替换为 lineBreak 的替换器;CRLF 排在最前,作为整体替换。
+func newLineBreakReplacer(lineBreak string) *strings.Replacer {
+ return strings.NewReplacer("\r\n", lineBreak, "\r", lineBreak, "\n", lineBreak)
+}
+
+// blobState 是 Blob 与 File 的宿主对象实现,isFile 为 true 时表示 File。字节序列构造后不再修改,可以在多个对象之间
+// 共享(slice() 直接引用原数组的一段);交给脚本的 ArrayBuffer 一律复制,避免脚本改写内核保留的数据。
+type blobState struct {
+ expandoProperties
+
+ data []byte
+ typ string
+
+ isFile bool
+ name string
+ lastModified int64 // 自 Unix 纪元起的毫秒数
+}
+
+// blobStateOf 取出 Blob(含 File)的宿主状态,只接受由本包创建的对象。
+func blobStateOf(value goja.Value) (*blobState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != blobStateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*blobState)
+ return state, ok
+}
+
+// newBlobObject 创建包装 state 的 Blob 或 File 对象。
+func newBlobObject(rt *goja.Runtime, prototype *goja.Object, state *blobState) *goja.Object {
+ object := rt.NewDynamicObject(state)
+ lo.Must0(object.SetPrototype(prototype))
+ return object
+}
+
+// blobPart 是 BlobPart 联合类型转换后的值:Blob、BufferSource(字节在处理各部分时才复制)或字符串。
+type blobPart struct {
+ blob *blobState
+ buffer *goja.Object
+ text string
+}
+
+// blobPropertyBag 是 BlobPropertyBag 字典转换后的值。
+type blobPropertyBag struct {
+ typ string
+ native bool // endings 为 "native"
+}
+
+// blobPartsOf 按 WebIDL 把值转换为 sequence<BlobPart>,各项依次按 Blob、ArrayBuffer、ArrayBuffer 视图、USVString 识别。
+func (h *Host) blobPartsOf(rt *goja.Runtime, value goja.Value, context string) (parts []blobPart) {
+ iterateSequence(rt, value, context, func(element goja.Value) {
+ if state, ok := blobStateOf(element); ok {
+ parts = append(parts, blobPart{blob: state})
+ } else if h.IsBufferSource(element) {
+ parts = append(parts, blobPart{buffer: element.(*goja.Object)})
+ } else {
+ parts = append(parts, blobPart{text: usvStringOf(rt, element)})
+ }
+ })
+ return
+}
+
+// IsBufferSource 判断值是不是 ArrayBuffer 或 ArrayBuffer 视图(TypedArray、DataView),不会触发对象上的访问器。
+func (h *Host) IsBufferSource(value goja.Value) bool {
+ object, ok := value.(*goja.Object)
+ if !ok {
+ return false
+ }
+ if object.ExportType() == arrayBufferExportType {
+ return true
+ }
+ isView, err := h.isView(goja.Undefined(), object)
+ return err == nil && isView.ToBoolean()
+}
+
+// BufferSourceBytes 返回 BufferSource 当前的字节(与引擎共享内存,调用方须自行复制),ArrayBuffer 已分离时返回空。
+// 视图先经注册时捕获的内建 buffer 访问器取出其 ArrayBuffer,确认未分离后再导出:goja 导出已分离缓冲区上的视图
+// 会触发 Go 运行时 panic,而不是抛出 JS 异常。
+func (h *Host) BufferSourceBytes(rt *goja.Runtime, object *goja.Object) []byte {
+ if object.ExportType() == arrayBufferExportType {
+ return object.Export().(goja.ArrayBuffer).Bytes()
+ }
+
+ buffer, err := h.typedArrayBuffer(object)
+ if err != nil {
+ // 调用方已用 ArrayBuffer.isView 判定过,不是 TypedArray 时只能是 DataView。
+ if buffer, err = h.dataViewBuffer(object); err != nil {
+ panic(err)
+ }
+ }
+ if arrayBuffer, ok := buffer.Export().(goja.ArrayBuffer); !ok || arrayBuffer.Detached() {
+ return nil
+ }
+
+ var view []byte
+ if err := rt.ExportTo(object, &view); err != nil {
+ panic(rt.NewTypeError("failed to read the bytes of a BufferSource: %v", err))
+ }
+ return view
+}
+
+// processBlobParts 按 File API 规范拼接各部分的字节:BufferSource 在此时才复制其当前内容(已分离的为空),
+// 字符串按 UTF-8 编码,native 为 true 时先把字符串中的换行统一为平台换行符。
+func (h *Host) processBlobParts(rt *goja.Runtime, parts []blobPart, native bool) []byte {
+ data := []byte{}
+ for _, part := range parts {
+ switch {
+ case part.blob != nil:
+ data = append(data, part.blob.data...)
+ case part.buffer != nil:
+ data = append(data, h.BufferSourceBytes(rt, part.buffer)...)
+ default:
+ text := part.text
+ if native {
+ text = nativeLineBreakReplacer.Replace(text)
+ }
+ data = append(data, text...)
+ }
+ }
+ return data
+}
+
+// blobPropertyBagOf 按 WebIDL 转换 BlobPropertyBag:undefined 与 null 视为空字典,其他非对象值抛 TypeError,成员按
+// 字典序读取(endings、type)。同时返回字典对象,供 File 随后读取 FilePropertyBag 自身的 lastModified。
+func blobPropertyBagOf(rt *goja.Runtime, value goja.Value, context string) (blobPropertyBag, *goja.Object) {
+ var bag blobPropertyBag
+ if !isJsValueNotNull(value) {
+ return bag, nil
+ }
+ dictionary, ok := value.(*goja.Object)
+ if !ok {
+ panic(rt.NewTypeError("%s: options can't be converted to a dictionary", context))
+ }
+
+ if endings := dictionary.Get("endings"); isJsValueNotUndefined(endings) {
+ switch value := usvStringOf(rt, endings); value {
+ case "transparent":
+ case "native":
+ bag.native = true
+ default:
+ panic(rt.NewTypeError("%s: '%s' (value of 'endings' member of BlobPropertyBag) is not a valid value for "+
+ "enumeration EndingType", context, value))
+ }
+ }
+ if typ := dictionary.Get("type"); isJsValueNotUndefined(typ) {
+ bag.typ = usvStringOf(rt, typ)
+ }
+ return bag, dictionary
+}
+
+// normalizeBlobType 按 File API 规范规范化媒体类型:含 U+0020 到 U+007E 之外的字符时为空串,否则转为 ASCII 小写。
+func normalizeBlobType(typ string) string {
+ for i := 0; i < len(typ); i++ {
+ if typ[i] < 0x20 || typ[i] > 0x7E {
+ return ""
+ }
+ }
+ return strings.ToLower(typ)
+}
+
+// relativeBlobPosition 按 slice blob 算法把 slice() 的 start 或 end 归一化到 [0, size]:负数从末尾倒数。
+func relativeBlobPosition(position, size float64) float64 {
+ if position < 0 {
+ return math.Max(size+position, 0)
+ }
+ return math.Min(position, size)
+}
+
+// cloneBytes 复制字节切片,输入为空时也返回非 nil 切片。
+func cloneBytes(data []byte) []byte {
+ return append(make([]byte, 0, len(data)), data...)
+}
+
+// newBlobConstructor 构造 Blob 全局构造函数:new Blob(blobParts?, options?)。
+func (h *Host) newBlobConstructor(rt *goja.Runtime) *goja.Object {
+ return newInterfaceConstructor(rt, "Blob", 0, h.blobPrototype, func(call goja.ConstructorCall) *goja.Object {
+ var parts []blobPart
+ if blobParts := call.Argument(0); !goja.IsUndefined(blobParts) {
+ parts = h.blobPartsOf(rt, blobParts, "Blob constructor")
+ }
+ options, _ := blobPropertyBagOf(rt, call.Argument(1), "Blob constructor")
+ state := &blobState{data: h.processBlobParts(rt, parts, options.native), typ: normalizeBlobType(options.typ)}
+ return newBlobObject(rt, call.This.Prototype(), state)
+ })
+}
+
+// newFileConstructor 构造继承自 Blob 的 File 全局构造函数:new File(fileBits, fileName, options?)。
+func (h *Host) newFileConstructor(rt *goja.Runtime, blobConstructor *goja.Object) *goja.Object {
+ constructor := newInterfaceConstructor(rt, "File", 2, h.filePrototype, func(call goja.ConstructorCall) *goja.Object {
+ if len(call.Arguments) < 2 {
+ panic(rt.NewTypeError("File constructor: At least 2 arguments required, but only %d passed",
+ len(call.Arguments)))
+ }
+ parts := h.blobPartsOf(rt, call.Arguments[0], "File constructor")
+ name := usvStringOf(rt, call.Arguments[1])
+ options, dictionary := blobPropertyBagOf(rt, call.Argument(2), "File constructor")
+ lastModified := time.Now().UnixMilli()
+ if dictionary != nil {
+ if value := dictionary.Get("lastModified"); isJsValueNotUndefined(value) {
+ lastModified = longLongOf(value)
+ }
+ }
+
+ state := &blobState{
+ data: h.processBlobParts(rt, parts, options.native),
+ typ: normalizeBlobType(options.typ),
+ isFile: true,
+ name: name,
+ lastModified: lastModified,
+ }
+ return newBlobObject(rt, call.This.Prototype(), state)
+ })
+ lo.Must0(constructor.SetPrototype(blobConstructor))
+ return constructor
+}
+
+// newBlobPrototype 构造 Blob.prototype:size、type 访问器与 slice、text、arrayBuffer、bytes 方法。
+// 沙箱没有 ReadableStream,因此不提供 stream()。
+func (h *Host) newBlobPrototype(rt *goja.Runtime) *goja.Object {
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, member string) *blobState {
+ if state, ok := blobStateOf(call.This); ok {
+ return state
+ }
+ panic(rt.NewTypeError("Blob.prototype.%s called on an incompatible receiver", member))
+ }
+
+ defineGetter(rt, prototype, "size", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(len(self(call, "size").data))
+ })
+ defineGetter(rt, prototype, "type", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(self(call, "type").typ)
+ })
+
+ defineMethod(rt, prototype, "slice", 0, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "slice")
+ size := float64(len(state.data))
+ relativeStart := 0.0
+ if start := call.Argument(0); !goja.IsUndefined(start) {
+ relativeStart = relativeBlobPosition(clampedLongLongOf(start), size)
+ }
+ relativeEnd := size
+ if end := call.Argument(1); !goja.IsUndefined(end) {
+ relativeEnd = relativeBlobPosition(clampedLongLongOf(end), size)
+ }
+ contentType := ""
+ if value := call.Argument(2); !goja.IsUndefined(value) {
+ contentType = normalizeBlobType(usvStringOf(rt, value))
+ }
+
+ start := int(relativeStart)
+ end := start + int(math.Max(relativeEnd-relativeStart, 0))
+ return newBlobObject(rt, h.blobPrototype, &blobState{data: state.data[start:end:end], typ: contentType})
+ })
+
+ // 读取方法返回 Promise:接收者不兼容时返回被拒绝的 Promise 而不是同步抛出(与 WebIDL 一致)。
+ defineReader := func(name string, read func(state *blobState) (goja.Value, error)) {
+ defineMethod(rt, prototype, name, 0, func(call goja.FunctionCall) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+ var settleErr error
+ if state, ok := blobStateOf(call.This); !ok {
+ settleErr = reject(rt.NewTypeError("Blob.prototype.%s called on an incompatible receiver", name))
+ } else if value, err := read(state); err != nil {
+ settleErr = reject(rt.NewGoError(err))
+ } else {
+ settleErr = resolve(value)
+ }
+ if settleErr != nil {
+ logging.LogErrorf("Blob.prototype.%s: settle promise: %v", name, settleErr)
+ }
+ return rt.ToValue(promise)
+ })
+ }
+ defineReader("text", func(state *blobState) (goja.Value, error) {
+ // 与 TextDecoder 默认行为相同的 UTF-8 解码:去掉开头的 BOM,无效字节序列替换为 U+FFFD。
+ decoder, err := encoding.NewTextDecoder("utf-8", encoding.TextDecoderOptions{})
+ if err != nil {
+ return nil, err
+ }
+ text, err := decoder.Decode(state.data, encoding.TextDecodeOptions{})
+ if err != nil {
+ return nil, err
+ }
+ return rt.ToValue(text), nil
+ })
+ defineReader("arrayBuffer", func(state *blobState) (goja.Value, error) {
+ return rt.ToValue(rt.NewArrayBuffer(cloneBytes(state.data))), nil
+ })
+ defineReader("bytes", func(state *blobState) (goja.Value, error) {
+ return rt.New(h.uint8Array, rt.ToValue(rt.NewArrayBuffer(cloneBytes(state.data))))
+ })
+
+ defineToStringTag(rt, prototype, "Blob")
+ return prototype
+}
+
+// newFilePrototype 构造继承自 Blob.prototype 的 File.prototype:name 与 lastModified 访问器。
+func (h *Host) newFilePrototype(rt *goja.Runtime) *goja.Object {
+ prototype := rt.NewObject()
+ lo.Must0(prototype.SetPrototype(h.blobPrototype))
+
+ self := func(call goja.FunctionCall, member string) *blobState {
+ if state, ok := blobStateOf(call.This); ok && state.isFile {
+ return state
+ }
+ panic(rt.NewTypeError("File.prototype.%s called on an incompatible receiver", member))
+ }
+ defineGetter(rt, prototype, "name", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(self(call, "name").name)
+ })
+ defineGetter(rt, prototype, "lastModified", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(self(call, "lastModified").lastModified)
+ })
+
+ defineToStringTag(rt, prototype, "File")
+ return prototype
+}
diff --git a/kernel/plugin/formdata/blob_test.go b/kernel/plugin/formdata/blob_test.go
new file mode 100644
index 0000000000..7d99332c5c
--- /dev/null
+++ b/kernel/plugin/formdata/blob_test.go
@@ -0,0 +1,519 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import (
+ "fmt"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/dop251/goja_nodejs/url"
+)
+
+// formDataTestRuntime 启动注入了 Blob、File、FormData 与 URLSearchParams 的事件循环,提供运行脚本的辅助方法。
+type formDataTestRuntime struct {
+ t *testing.T
+ loop *eventloop.EventLoop
+}
+
+func newFormDataTestRuntime(t *testing.T) *formDataTestRuntime {
+ t.Helper()
+
+ loop := eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ loop.Start()
+ t.Cleanup(func() { loop.Stop() })
+
+ r := &formDataTestRuntime{t: t, loop: loop}
+ r.withRuntime(func(rt *goja.Runtime) {
+ url.Enable(rt)
+ Enable(rt)
+ })
+ return r
+}
+
+// withRuntime 在事件循环上同步执行 fn。fn 运行在事件循环的 goroutine 上,不能调用 t.Fatal。
+func (r *formDataTestRuntime) withRuntime(fn func(rt *goja.Runtime)) {
+ r.t.Helper()
+
+ done := make(chan struct{})
+ r.loop.RunOnLoop(func(rt *goja.Runtime) {
+ defer close(done)
+ fn(rt)
+ })
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ r.t.Fatal("timed out waiting for the event loop")
+ }
+}
+
+// run 在事件循环上同步执行脚本并返回结果的字符串形式,脚本抛出异常时 Fatal。
+func (r *formDataTestRuntime) run(script string) string {
+ r.t.Helper()
+
+ var result string
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ var value goja.Value
+ if value, err = rt.RunString(script); err == nil {
+ result = value.String()
+ }
+ })
+ if err != nil {
+ r.t.Fatalf("script failed: %v\n%s", err, script)
+ }
+ return result
+}
+
+// await 执行一段返回 Promise 的脚本,等待其完成后返回结果的字符串形式;被拒绝时以 "rejected:" 开头。
+func (r *formDataTestRuntime) await(script string) string {
+ r.t.Helper()
+
+ result := make(chan string, 1)
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ var value goja.Value
+ if value, err = rt.RunString(script); err != nil {
+ return
+ }
+ promise := value.ToObject(rt)
+ then, ok := goja.AssertFunction(promise.Get("then"))
+ if !ok {
+ err = fmt.Errorf("script did not return a promise")
+ return
+ }
+ _, err = then(promise, rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- call.Argument(0).String()
+ return goja.Undefined()
+ }), rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- "rejected:" + call.Argument(0).String()
+ return goja.Undefined()
+ }))
+ })
+ if err != nil {
+ r.t.Fatalf("script failed: %v\n%s", err, script)
+ }
+
+ select {
+ case got := <-result:
+ return got
+ case <-time.After(5 * time.Second):
+ r.t.Fatalf("timed out waiting for:\n%s", script)
+ return ""
+ }
+}
+
+func TestBlobConstructorConcatenatesParts(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const buffer = new Uint8Array([0x41, 0x42, 0x43, 0x44]).buffer;
+ const blob = new Blob([
+ "a\u00e9\ud83d\ude00", // 1、2、4 字节的 UTF-8 字符
+ "\ud800", // 未配对的代理项替换为 U+FFFD
+ buffer,
+ new Uint8Array(buffer, 1, 2),
+ new DataView(buffer, 3, 1),
+ new Blob(["<", ">"], {type: "text/ignored"}),
+ 12, null, undefined, {toString() { return "!"; }},
+ ]);
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ return [blob.size, blob.type, Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")].join("|");
+ })()`)
+ want := "35||" + "61" + "c3a9" + "f09f9880" + "efbfbd" + "41424344" + "4243" + "44" + "3c3e" + "3132" +
+ "6e756c6c" + "756e646566696e6564" + "21"
+ if got != want {
+ t.Fatalf("blob = %s, want %s", got, want)
+ }
+}
+
+func TestBlobCopiesBufferSourcesAndReturnsCopies(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const source = new Uint8Array([1, 2, 3]);
+ const blob = new Blob([source]);
+ source[0] = 9;
+ const first = new Uint8Array(await blob.arrayBuffer());
+ first[1] = 9;
+ const second = await blob.bytes();
+ second[2] = 9;
+ return Array.from(new Uint8Array(await blob.arrayBuffer())).join(",");
+ })()`)
+ if got != "1,2,3" {
+ t.Fatalf("blob content after mutating the source and the read results = %s, want 1,2,3", got)
+ }
+}
+
+func TestBlobTreatsDetachedBuffersAsEmpty(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ // 沙箱脚本目前无法分离 ArrayBuffer,这里由宿主分离,覆盖将来引入 transfer 等能力后的情形:
+ // goja 导出已分离缓冲区上的视图会触发 Go 运行时 panic,实现必须先判断缓冲区是否已分离。
+ var setErr error
+ rt.withRuntime(func(rt *goja.Runtime) {
+ setErr = rt.Set("detach", func(call goja.FunctionCall) goja.Value {
+ call.Argument(0).Export().(goja.ArrayBuffer).Detach()
+ return goja.Undefined()
+ })
+ })
+ if setErr != nil {
+ t.Fatal(setErr)
+ }
+
+ got := rt.await(`(async () => {
+ const parts = [];
+ for (const view of [
+ (buffer) => buffer,
+ (buffer) => new Uint8Array(buffer),
+ (buffer) => new Uint16Array(buffer, 2, 1),
+ (buffer) => new DataView(buffer, 1, 2),
+ ]) {
+ const buffer = new Uint8Array([0x41, 0x42, 0x43, 0x44]).buffer;
+ parts.push(view(buffer));
+ detach(buffer);
+ }
+ return new Blob([...parts, "ok"]).text();
+ })()`)
+ if got != "ok" {
+ t.Fatalf("blob from detached buffers = %q, want only the string part", got)
+ }
+}
+
+func TestBlobTypeNormalization(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`[
+ new Blob([], {type: "Text/HTML; Charset=UTF-8"}).type,
+ new Blob([], {type: "a\u00e9"}).type,
+ new Blob([], {type: "a\nb"}).type,
+ new Blob([]).type,
+ new Blob([], {type: 5}).type,
+ new Blob([], null).type,
+ ].join("|")`)
+ if want := "text/html; charset=utf-8||||5|"; got != want {
+ t.Fatalf("types = %q, want %q", got, want)
+ }
+}
+
+func TestBlobEndings(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => JSON.stringify([
+ await new Blob(["a\r\nb\rc\nd"], {endings: "native"}).text(),
+ await new Blob(["a\r\nb\rc\nd"], {endings: "transparent"}).text(),
+ await new Blob(["a\r\nb"]).text(),
+ Array.from(await new Blob([new Uint8Array([13, 10, 13])], {endings: "native"}).bytes()),
+ ]))()`)
+ native := `\n`
+ if runtime.GOOS == "windows" {
+ native = `\r\n`
+ }
+ want := `["a` + native + `b` + native + `c` + native + `d","a\r\nb\rc\nd","a\r\nb",[13,10,13]]`
+ if got != want {
+ t.Fatalf("endings = %s, want %s", got, want)
+ }
+
+ if got := rt.run(`(() => {
+ try {
+ new Blob([], {endings: "NATIVE"});
+ return "no throw";
+ } catch (e) {
+ return e.constructor.name;
+ }
+ })()`); got != "TypeError" {
+ t.Fatalf("invalid endings = %s, want TypeError", got)
+ }
+}
+
+func TestBlobSlice(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const blob = new File(["0123456789"], "digits.txt", {type: "text/plain"});
+ const slices = [
+ blob.slice(),
+ blob.slice(2),
+ blob.slice(2, 5),
+ blob.slice(-3),
+ blob.slice(-3, -1),
+ blob.slice(5, 2),
+ blob.slice(-20, 20),
+ blob.slice(2.5, 4.5), // [Clamp] 就近取整,恰在中间时取偶数:2.5 -> 2,4.5 -> 4
+ blob.slice(NaN, "4"),
+ blob.slice(0, Infinity),
+ blob.slice(1, 3, "Text/X"),
+ blob.slice(1, 3, "\u00e9"),
+ blob.slice(undefined, undefined, undefined),
+ blob.slice(2, 8).slice(1, -1),
+ ];
+ const texts = await Promise.all(slices.map((s) => s.text()));
+ return JSON.stringify([
+ texts,
+ slices.map((s) => s.type),
+ slices.every((s) => s instanceof Blob && !(s instanceof File)),
+ ]);
+ })()`)
+ want := `[["0123456789","23456789","234","789","78","","0123456789","23","0123","0123456789","12","12",` +
+ `"0123456789","3456"],["","","","","","","","","","","text/x","","",""],true]`
+ if got != want {
+ t.Fatalf("slices = %s, want %s", got, want)
+ }
+}
+
+func TestBlobTextDecodesUTF8LikeTextDecoder(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ // 开头的 BOM 被去掉;被截断的多字节序列(E2 82)整体替换为一个 U+FFFD,单独的无效字节(FF)也替换为 U+FFFD。
+ got := rt.await(`(async () => {
+ const blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF, 0x61, 0xE2, 0x82, 0x62, 0xFF, 0x63])]);
+ return JSON.stringify(await blob.text());
+ })()`)
+ if want := "\"a\uFFFDb\uFFFDc\""; got != want {
+ t.Fatalf("text() = %s, want %s", got, want)
+ }
+}
+
+func TestBlobEmptyReads(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const blob = new Blob();
+ const bytes = await blob.bytes();
+ return JSON.stringify([
+ blob.size,
+ await blob.text(),
+ (await blob.arrayBuffer()).byteLength,
+ bytes instanceof Uint8Array,
+ bytes.length,
+ ]);
+ })()`)
+ if want := `[0,"",0,true,0]`; got != want {
+ t.Fatalf("empty blob = %s, want %s", got, want)
+ }
+}
+
+func TestBlobRejectsInvalidArguments(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const results = [];
+ for (const fn of [
+ () => new Blob("string"),
+ () => new Blob(1),
+ () => new Blob(null),
+ () => new Blob({}),
+ () => new Blob({0: "x", length: 1}),
+ () => new Blob(new Date()),
+ () => new Blob([Symbol("part")]),
+ () => new Blob([], 1),
+ () => new Blob([], "text/plain"),
+ () => new Blob([], {type: Symbol("type")}),
+ () => new File([]),
+ () => new File(undefined, "name"),
+ ]) {
+ try {
+ fn();
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name);
+ }
+ }
+ return results.join(",");
+ })()`)
+ if want := strings.TrimSuffix(strings.Repeat("TypeError,", 12), ","); got != want {
+ t.Fatalf("invalid arguments = %s, want %s", got, want)
+ }
+}
+
+func TestBlobConvertsArgumentsInOrder(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ // Symbol.iterator 只读取一次,各项取值后立即转换,出错时停止(与 WPT 的 Blob-constructor 用例一致)。
+ got := rt.run(`(() => {
+ const received = [];
+ const parts = {
+ get [Symbol.iterator]() {
+ received.push("Symbol.iterator");
+ return Array.prototype[Symbol.iterator];
+ },
+ get length() {
+ received.push("length getter");
+ return {valueOf() { received.push("length valueOf"); return 3; }};
+ },
+ get 0() {
+ received.push("0 getter");
+ return {toString() { received.push("0 toString"); return "a"; }};
+ },
+ get 1() {
+ received.push("1 getter");
+ throw new Error("stop");
+ },
+ get 2() {
+ received.push("2 getter");
+ return "unreachable";
+ },
+ };
+ try {
+ new Blob(parts);
+ } catch (e) {
+ received.push(e.message);
+ }
+ return received.join(",");
+ })()`)
+ if want := "Symbol.iterator,length getter,length valueOf,0 getter,0 toString,length getter,length valueOf,1 getter,stop"; got != want {
+ t.Fatalf("conversion order = %s, want %s", got, want)
+ }
+
+ // 选项在各部分之后转换,字典成员按字典序读取;File 先读取继承自 BlobPropertyBag 的成员,再读取 lastModified。
+ got = rt.run(`(() => {
+ const order = [];
+ const part = {toString() { order.push("part"); return ""; }};
+ const options = {
+ get type() { order.push("type"); return ""; },
+ get endings() { order.push("endings"); return "transparent"; },
+ get lastModified() { order.push("lastModified"); return 0; },
+ };
+ new Blob([part], options);
+ order.push("|");
+ new File([part], {toString() { order.push("name"); return "name"; }}, options);
+ return order.join(",");
+ })()`)
+ if want := "part,endings,type,|,part,name,endings,type,lastModified"; got != want {
+ t.Fatalf("option order = %s, want %s", got, want)
+ }
+}
+
+func TestFileConstructor(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const file = new File(["abc"], "dir/name.txt", {type: "Text/Plain", lastModified: 123.9});
+ const before = Date.now();
+ const defaulted = new File([], "now");
+ const after = Date.now();
+ return JSON.stringify([
+ file.name, file.type, file.size, file.lastModified,
+ new File([], "date", {lastModified: new Date(42)}).lastModified,
+ new File([], "negative", {lastModified: -1.5}).lastModified,
+ new File([], "nan", {lastModified: NaN}).lastModified,
+ defaulted.lastModified >= before && defaulted.lastModified <= after,
+ new File([], "\ud800").name,
+ file instanceof File && file instanceof Blob,
+ Object.prototype.toString.call(file),
+ ]);
+ })()`)
+ want := "[\"dir/name.txt\",\"text/plain\",3,123,42,-1,0,true,\"\uFFFD\",true,\"[object File]\"]"
+ if got != want {
+ t.Fatalf("file = %s, want %s", got, want)
+ }
+}
+
+func TestBlobInterfaceShape(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`JSON.stringify([
+ Blob.name, Blob.length, File.name, File.length, FormData.name, FormData.length,
+ Object.getPrototypeOf(File) === Blob,
+ Object.getPrototypeOf(File.prototype) === Blob.prototype,
+ Blob.prototype.constructor === Blob,
+ Object.getOwnPropertyDescriptor(Blob, "prototype").writable,
+ Object.getOwnPropertyDescriptor(Blob.prototype, "constructor").enumerable,
+ Blob.prototype.slice.name, Blob.prototype.slice.length,
+ Object.getOwnPropertyDescriptor(Blob.prototype, "size").get.name,
+ Object.keys(Blob.prototype),
+ typeof Blob.prototype.stream,
+ Object.keys(new Blob(["x"])),
+ JSON.stringify(new Blob(["x"])),
+ Object.prototype.toString.call(new Blob()),
+ Object.prototype.toString.call(Blob.prototype),
+ ])`)
+ want := `["Blob",0,"File",2,"FormData",0,true,true,true,false,false,"slice",0,"get size",` +
+ `["size","type","slice","text","arrayBuffer","bytes"],"undefined",[],"{}","[object Blob]","[object Blob]"]`
+ if got != want {
+ t.Fatalf("interface shape = %s, want %s", got, want)
+ }
+}
+
+func TestBlobRejectsIncompatibleReceivers(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const results = [];
+ for (const fn of [
+ () => Blob.prototype.size,
+ () => Object.getOwnPropertyDescriptor(Blob.prototype, "type").get.call({}),
+ () => Blob.prototype.slice.call({}),
+ () => Object.getOwnPropertyDescriptor(File.prototype, "name").get.call(new Blob()),
+ ]) {
+ try {
+ fn();
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name);
+ }
+ }
+ // 返回 Promise 的方法以被拒绝的 Promise 报告错误,而不是同步抛出。
+ const promise = Blob.prototype.text.call({});
+ results.push(await promise.then(() => "resolved", (e) => "rejected " + e.constructor.name));
+ return results.join(",");
+ })()`)
+ if want := "TypeError,TypeError,TypeError,TypeError,rejected TypeError"; got != want {
+ t.Fatalf("incompatible receivers = %s, want %s", got, want)
+ }
+}
+
+func TestBlobSupportsSubclassesAndExpandoProperties(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ class LabeledBlob extends Blob {
+ label = "default";
+ constructor(parts, label) {
+ super(parts);
+ this.label = label;
+ }
+ describe() {
+ return this.label + ":" + this.size;
+ }
+ }
+ const blob = new LabeledBlob(["abc"], "custom");
+ blob.extra = 1;
+ const keys = Object.keys(blob);
+ delete blob.extra;
+ const assignToGetter = (() => {
+ "use strict";
+ try {
+ blob.size = 5;
+ return "no throw";
+ } catch (e) {
+ return e.constructor.name;
+ }
+ })();
+ return JSON.stringify([
+ blob instanceof LabeledBlob, blob instanceof Blob, blob.describe(), keys, "extra" in blob,
+ assignToGetter, blob.size,
+ ]);
+ })()`)
+ if want := `[true,true,"custom:3",["label","extra"],false,"TypeError",3]`; got != want {
+ t.Fatalf("subclass = %s, want %s", got, want)
+ }
+}
diff --git a/kernel/plugin/formdata/bridge.go b/kernel/plugin/formdata/bridge.go
new file mode 100644
index 0000000000..810a82c117
--- /dev/null
+++ b/kernel/plugin/formdata/bridge.go
@@ -0,0 +1,31 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import "github.com/dop251/goja"
+
+// NewUint8Array 用注册时捕获的 Uint8Array 构造函数把 data 包装为 Uint8Array,不复制 data:新实例的 ArrayBuffer
+// 直接以 data 为底层存储。
+func (h *Host) NewUint8Array(rt *goja.Runtime, data []byte) (goja.Value, error) {
+ return rt.New(h.uint8Array, rt.ToValue(rt.NewArrayBuffer(data)))
+}
+
+// NewBlob 用注册时捕获的 Blob 原型构造一个内容为 data 副本的 Blob,其 type 是按 Blob 构造函数的 type 选项
+// 规范化后的 contentType(见 normalizeBlobType,不按 MIME 类型解析)。
+func (h *Host) NewBlob(rt *goja.Runtime, data []byte, contentType string) *goja.Object {
+ return newBlobObject(rt, h.blobPrototype, &blobState{data: cloneBytes(data), typ: normalizeBlobType(contentType)})
+}
diff --git a/kernel/plugin/formdata/formdata.go b/kernel/plugin/formdata/formdata.go
new file mode 100644
index 0000000000..4ac4b25594
--- /dev/null
+++ b/kernel/plugin/formdata/formdata.go
@@ -0,0 +1,387 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import (
+ "bytes"
+ "crypto/rand"
+ "fmt"
+ "reflect"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+)
+
+var (
+ // stateType 与 iteratorStateType 用于在 Object.Export() 前先以 Object.ExportType() 做品牌判定,
+ // 原因见 kernel/plugin/abort 中 signalStateType 的注释。
+ stateType = reflect.TypeOf((*State)(nil))
+ iteratorStateType = reflect.TypeOf((*iteratorState)(nil))
+)
+
+// multipartNameEscaper 按 HTML 规范转义 Content-Disposition 的 name 与 filename 参数:只把 LF、CR、双引号替换为百分号编码。
+var multipartNameEscaper = strings.NewReplacer("\n", "%0A", "\r", "%0D", `"`, "%22")
+
+// Host 保存注册时捕获的内建对象与 Blob、File、FormData 迭代器的原型,供各原生函数共享,
+// 避免插件脚本事后改写 ArrayBuffer.isView、Uint8Array 等全局影响内部行为。
+type Host struct {
+ isView goja.Callable // ArrayBuffer.isView
+ typedArrayBuffer goja.Callable // %TypedArray%.prototype.buffer 的 getter
+ dataViewBuffer goja.Callable // DataView.prototype.buffer 的 getter
+ uint8Array *goja.Object // Uint8Array 构造函数
+
+ blobPrototype *goja.Object
+ filePrototype *goja.Object
+ formDataIteratorPrototype *goja.Object
+}
+
+// Enable 把 Blob、File 与 FormData 挂到 runtime 的 globalThis,调用方式与 url、buffer、console、encoding
+// 一致,失败时 panic。FormData 的文件条目依赖 Blob 与 File,三者共享同一组原型,因此一起注册。返回的 Host 供内核
+// 在该 runtime 中创建 Blob 与 Uint8Array、读取 BufferSource,调用方应保留它。
+//
+// 与规范的已知差异:不用 new 直接调用构造函数不会抛错(goja 的原生构造函数无法区分两种调用);沙箱没有
+// ReadableStream,Blob 不提供 stream();沙箱没有 HTMLFormElement,FormData 构造函数的 form 参数只能省略或为
+// undefined;实例可以添加自定义属性,但不能被冻结,也不能带自有的 Symbol 属性。
+func Enable(rt *goja.Runtime) *Host {
+ h, err := register(rt)
+ if err != nil {
+ panic(err)
+ }
+ return h
+}
+
+// register 捕获所需的内建对象,构造并挂载 Blob、File 与 FormData,返回宿主状态。
+func register(rt *goja.Runtime) (h *Host, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ h, err = nil, fmt.Errorf("formdata.Enable: %v", r)
+ }
+ }()
+
+ h = &Host{}
+ isView, ok := goja.AssertFunction(rt.Get("ArrayBuffer").ToObject(rt).Get("isView"))
+ if !ok {
+ return nil, fmt.Errorf("globalThis.ArrayBuffer.isView is not a function")
+ }
+ h.isView = isView
+ h.uint8Array = rt.Get("Uint8Array").ToObject(rt)
+ h.typedArrayBuffer = builtinGetter(rt, h.uint8Array.Get("prototype").ToObject(rt).Prototype(), "buffer")
+ h.dataViewBuffer = builtinGetter(rt, rt.Get("DataView").ToObject(rt).Get("prototype").ToObject(rt), "buffer")
+
+ h.blobPrototype = h.newBlobPrototype(rt)
+ h.filePrototype = h.newFilePrototype(rt)
+ h.formDataIteratorPrototype = h.newFormDataIteratorPrototype(rt)
+
+ blobConstructor := h.newBlobConstructor(rt)
+ lo.Must0(rt.Set("Blob", blobConstructor))
+ lo.Must0(rt.Set("File", h.newFileConstructor(rt, blobConstructor)))
+ lo.Must0(rt.Set("FormData", h.newFormDataConstructor(rt)))
+ return
+}
+
+// entry 是 FormData 条目列表中的一项:file 非 nil 时为文件条目,值为该 File 对象;否则为字符串条目。
+type entry struct {
+ name string
+ value string
+
+ file *goja.Object
+ fileState *blobState
+}
+
+// jsValue 返回条目的值:文件条目返回其 File 对象本身,字符串条目返回字符串。
+func (e entry) jsValue(rt *goja.Runtime) goja.Value {
+ if e.file != nil {
+ return e.file
+ }
+ return rt.ToValue(e.value)
+}
+
+// State 是 FormData 的宿主对象实现,条目列表只在事件循环线程上读写。
+type State struct {
+ expandoProperties
+
+ entries []entry
+}
+
+// StateOf 取出 FormData 的宿主状态,只接受由本包创建的对象。
+func StateOf(value goja.Value) (*State, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != stateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*State)
+ return state, ok
+}
+
+// iteratorKind 区分 entries()、keys()、values() 返回的迭代器。
+type iteratorKind int
+
+const (
+ iterateEntries iteratorKind = iota
+ iterateKeys
+ iterateValues
+)
+
+// iteratorState 是 FormData 迭代器的宿主对象实现:每次 next() 都按下标读取当前的条目列表,
+// 迭代期间对 FormData 的增删会体现在后续结果中(与 WebIDL 一致)。
+type iteratorState struct {
+ expandoProperties
+
+ formData *State
+ kind iteratorKind
+ index int
+}
+
+// iteratorStateOf 取出 FormData 迭代器的宿主状态,只接受由本包创建的对象。
+func iteratorStateOf(value goja.Value) (*iteratorState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != iteratorStateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*iteratorState)
+ return state, ok
+}
+
+// newFormDataConstructor 构造 FormData 全局构造函数:new FormData()。
+func (h *Host) newFormDataConstructor(rt *goja.Runtime) *goja.Object {
+ prototype := h.newFormDataPrototype(rt)
+ return newInterfaceConstructor(rt, "FormData", 0, prototype, func(call goja.ConstructorCall) *goja.Object {
+ // 沙箱没有 HTMLFormElement,任何非 undefined 的 form 参数都无法转换。
+ if !goja.IsUndefined(call.Argument(0)) {
+ panic(rt.NewTypeError("FormData constructor: Argument 1 is not an HTMLFormElement; " +
+ "form elements are not available in kernel plugins"))
+ }
+ object := rt.NewDynamicObject(&State{})
+ lo.Must0(object.SetPrototype(call.This.Prototype()))
+ return object
+ })
+}
+
+// entryOf 读取 append()/set() 的参数并按 HTML 规范的 create an entry 创建条目:参数不少于 3 个或值为 Blob 时
+// 按 (name, blobValue, filename?) 重载处理,否则把值转换为 USVString。Blob 值转为 File:不是 File 时以 "blob" 为文件名,
+// 给出 filename 时以其为文件名,类型保持不变,改名的 File 还保留 lastModified。
+func (h *Host) entryOf(rt *goja.Runtime, call goja.FunctionCall, method string) entry {
+ if len(call.Arguments) < 2 {
+ panic(rt.NewTypeError("FormData.%s: At least 2 arguments required, but only %d passed", method,
+ len(call.Arguments)))
+ }
+ e := entry{name: usvStringOf(rt, call.Arguments[0])}
+
+ value := call.Arguments[1]
+ blob, isBlob := blobStateOf(value)
+ if !isBlob {
+ if len(call.Arguments) >= 3 {
+ panic(rt.NewTypeError("FormData.%s: Argument 2 is not a Blob", method))
+ }
+ e.value = usvStringOf(rt, value)
+ return e
+ }
+
+ file := value.(*goja.Object)
+ if filename := call.Argument(2); !goja.IsUndefined(filename) {
+ lastModified := time.Now().UnixMilli()
+ if blob.isFile {
+ lastModified = blob.lastModified
+ }
+ blob = &blobState{data: blob.data, typ: blob.typ, isFile: true, name: usvStringOf(rt, filename),
+ lastModified: lastModified}
+ file = newBlobObject(rt, h.filePrototype, blob)
+ } else if !blob.isFile {
+ blob = &blobState{data: blob.data, typ: blob.typ, isFile: true, name: "blob",
+ lastModified: time.Now().UnixMilli()}
+ file = newBlobObject(rt, h.filePrototype, blob)
+ }
+ e.file, e.fileState = file, blob
+ return e
+}
+
+// newFormDataPrototype 构造 FormData.prototype:append、delete、get、getAll、has、set、entries、keys、values、forEach,
+// 以及与 entries 为同一函数的 Symbol.iterator。
+func (h *Host) newFormDataPrototype(rt *goja.Runtime) *goja.Object {
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *State {
+ if state, ok := StateOf(call.This); ok {
+ return state
+ }
+ panic(rt.NewTypeError("FormData.prototype.%s called on an incompatible receiver", method))
+ }
+ nameOf := func(call goja.FunctionCall, method string) string {
+ if len(call.Arguments) < 1 {
+ panic(rt.NewTypeError("FormData.%s: At least 1 argument required, but only 0 passed", method))
+ }
+ return usvStringOf(rt, call.Arguments[0])
+ }
+
+ defineMethod(rt, prototype, "append", 2, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "append")
+ state.entries = append(state.entries, h.entryOf(rt, call, "append"))
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "delete", 1, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "delete")
+ name := nameOf(call, "delete")
+ state.entries = slices.DeleteFunc(state.entries, func(e entry) bool { return e.name == name })
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "get", 1, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "get")
+ name := nameOf(call, "get")
+ for _, e := range state.entries {
+ if e.name == name {
+ return e.jsValue(rt)
+ }
+ }
+ return goja.Null()
+ })
+ defineMethod(rt, prototype, "getAll", 1, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "getAll")
+ name := nameOf(call, "getAll")
+ values := []any{}
+ for _, e := range state.entries {
+ if e.name == name {
+ values = append(values, e.jsValue(rt))
+ }
+ }
+ return rt.NewArray(values...)
+ })
+ defineMethod(rt, prototype, "has", 1, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "has")
+ name := nameOf(call, "has")
+ return rt.ToValue(slices.ContainsFunc(state.entries, func(e entry) bool { return e.name == name }))
+ })
+ defineMethod(rt, prototype, "set", 2, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "set")
+ e := h.entryOf(rt, call, "set")
+ index := slices.IndexFunc(state.entries, func(existing entry) bool { return existing.name == e.name })
+ if index < 0 {
+ state.entries = append(state.entries, e)
+ return goja.Undefined()
+ }
+ // 替换第一个同名条目,并移除其后的其他同名条目。
+ state.entries[index] = e
+ rest := slices.DeleteFunc(state.entries[index+1:], func(existing entry) bool {
+ return existing.name == e.name
+ })
+ state.entries = state.entries[:index+1+len(rest)]
+ return goja.Undefined()
+ })
+
+ newIterator := func(kind iteratorKind, method string) func(goja.FunctionCall) goja.Value {
+ return func(call goja.FunctionCall) goja.Value {
+ object := rt.NewDynamicObject(&iteratorState{formData: self(call, method), kind: kind})
+ lo.Must0(object.SetPrototype(h.formDataIteratorPrototype))
+ return object
+ }
+ }
+ entries := newMethod(rt, "entries", 0, newIterator(iterateEntries, "entries"))
+ lo.Must0(prototype.DefineDataProperty("entries", entries, goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_TRUE))
+ defineMethod(rt, prototype, "keys", 0, newIterator(iterateKeys, "keys"))
+ defineMethod(rt, prototype, "values", 0, newIterator(iterateValues, "values"))
+ defineMethod(rt, prototype, "forEach", 1, func(call goja.FunctionCall) goja.Value {
+ state := self(call, "forEach")
+ callback, ok := goja.AssertFunction(call.Argument(0))
+ if !ok {
+ panic(rt.NewTypeError("FormData.forEach: Argument 1 is not callable"))
+ }
+ thisArg := call.Argument(1)
+ // 每轮都重新读取条目列表:回调中的增删会影响后续迭代(与 WebIDL 一致)。
+ for i := 0; i < len(state.entries); i++ {
+ e := state.entries[i]
+ if _, err := callback(thisArg, e.jsValue(rt), rt.ToValue(e.name), call.This); err != nil {
+ panic(err)
+ }
+ }
+ return goja.Undefined()
+ })
+ lo.Must0(prototype.DefineDataPropertySymbol(goja.SymIterator, entries, goja.FLAG_TRUE, goja.FLAG_TRUE,
+ goja.FLAG_FALSE))
+
+ defineToStringTag(rt, prototype, "FormData")
+ return prototype
+}
+
+// newFormDataIteratorPrototype 构造 FormData 迭代器的原型:继承 %IteratorPrototype%,提供 next 与 Symbol.toStringTag。
+func (h *Host) newFormDataIteratorPrototype(rt *goja.Runtime) *goja.Object {
+ prototype := rt.NewObject()
+ lo.Must0(prototype.SetPrototype(iteratorPrototypeOf(rt)))
+
+ defineMethod(rt, prototype, "next", 0, func(call goja.FunctionCall) goja.Value {
+ state, ok := iteratorStateOf(call.This)
+ if !ok {
+ panic(rt.NewTypeError("FormData Iterator.prototype.next called on an incompatible receiver"))
+ }
+
+ result := rt.NewObject()
+ if state.index >= len(state.formData.entries) {
+ lo.Must0(result.Set("value", goja.Undefined()))
+ lo.Must0(result.Set("done", true))
+ return result
+ }
+ e := state.formData.entries[state.index]
+ state.index++
+
+ var value goja.Value
+ switch state.kind {
+ case iterateKeys:
+ value = rt.ToValue(e.name)
+ case iterateValues:
+ value = e.jsValue(rt)
+ default:
+ value = rt.NewArray(e.name, e.jsValue(rt))
+ }
+ lo.Must0(result.Set("value", value))
+ lo.Must0(result.Set("done", false))
+ return result
+ })
+
+ defineToStringTag(rt, prototype, "FormData Iterator")
+ return prototype
+}
+
+// EncodeMultipart 按 HTML 规范的 multipart/form-data 编码算法把条目序列化为 UTF-8 请求体,字节格式与浏览器、
+// Node.js(undici)一致:名称与字符串值中的 CR、LF 先统一为 CRLF,名称与文件名再转义 LF、CR、双引号;
+// 文件条目带 filename 与 Content-Type(类型为空时为 application/octet-stream),字符串条目不带 Content-Type。
+// 返回请求体以及带 boundary 参数的 Content-Type。
+func (s *State) EncodeMultipart() (body []byte, contentType string) {
+ boundary := "----formdata-siyuan-" + rand.Text()
+
+ var buffer bytes.Buffer
+ for _, e := range s.entries {
+ buffer.WriteString("--" + boundary + "\r\n")
+ buffer.WriteString(`Content-Disposition: form-data; name="` +
+ multipartNameEscaper.Replace(crlfReplacer.Replace(e.name)) + `"`)
+ if e.fileState == nil {
+ buffer.WriteString("\r\n\r\n" + crlfReplacer.Replace(e.value) + "\r\n")
+ continue
+ }
+
+ fileType := e.fileState.typ
+ if fileType == "" {
+ fileType = "application/octet-stream"
+ }
+ buffer.WriteString(`; filename="` + multipartNameEscaper.Replace(e.fileState.name) + `"` +
+ "\r\nContent-Type: " + fileType + "\r\n\r\n")
+ buffer.Write(e.fileState.data)
+ buffer.WriteString("\r\n")
+ }
+ buffer.WriteString("--" + boundary + "--\r\n")
+ return buffer.Bytes(), "multipart/form-data; boundary=" + boundary
+}
diff --git a/kernel/plugin/formdata/formdata_test.go b/kernel/plugin/formdata/formdata_test.go
new file mode 100644
index 0000000000..e65e41276e
--- /dev/null
+++ b/kernel/plugin/formdata/formdata_test.go
@@ -0,0 +1,343 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import (
+ "bytes"
+ "io"
+ "mime"
+ "mime/multipart"
+ "strings"
+ "testing"
+
+ "github.com/dop251/goja"
+)
+
+func TestFormDataAppendGetGetAllHas(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const fd = new FormData();
+ fd.append("a", "1");
+ fd.append("b", 2);
+ fd.append("a", "3");
+ fd.append("\ud800", "\udc00x");
+ return JSON.stringify([
+ fd.get("a"), fd.get("b"), fd.get("missing"), fd.getAll("a"), fd.getAll("missing"),
+ fd.has("a"), fd.has("missing"), fd.get("\ufffd"),
+ ]);
+ })()`)
+ if want := "[\"1\",\"2\",null,[\"1\",\"3\"],[],true,false,\"\uFFFDx\"]"; got != want {
+ t.Fatalf("entries = %s, want %s", got, want)
+ }
+}
+
+func TestFormDataSetAndDelete(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const fd = new FormData();
+ fd.append("a", "1");
+ fd.append("b", "2");
+ fd.append("a", "3");
+ fd.append("c", "4");
+ fd.append("a", "5");
+ // set 替换第一个同名条目并移除其余同名条目,没有同名条目时追加到末尾。
+ fd.set("a", "x");
+ fd.set("d", "y");
+ const afterSet = [...fd];
+ fd.append("b", "6");
+ fd.delete("b");
+ fd.delete("missing");
+ return JSON.stringify([afterSet, [...fd]]);
+ })()`)
+ want := `[[["a","x"],["b","2"],["c","4"],["d","y"]],[["a","x"],["c","4"],["d","y"]]]`
+ if got != want {
+ t.Fatalf("set/delete = %s, want %s", got, want)
+ }
+}
+
+func TestFormDataBlobValuesBecomeFiles(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const fd = new FormData();
+ const file = new File(["f"], "orig.txt", {type: "text/plain", lastModified: 123});
+ const blob = new Blob(["b"], {type: "image/png"});
+ fd.append("file", file);
+ fd.append("blob", blob);
+ fd.append("renamed", file, "new.txt");
+ fd.append("blobNamed", blob, "pic.png");
+ fd.append("undefinedName", blob, undefined);
+
+ const fromBlob = fd.get("blob");
+ const renamed = fd.get("renamed");
+ const results = [
+ fd.get("file") === file, fd.get("blob") === fromBlob,
+ fromBlob instanceof File, fromBlob.name, fromBlob.type, fromBlob !== blob,
+ renamed !== file, renamed.name, renamed.type, renamed.lastModified,
+ fd.get("blobNamed").name, fd.get("blobNamed").type,
+ fd.get("undefinedName").name,
+ await fromBlob.text(), await renamed.text(),
+ ];
+ try {
+ fd.append("bad", "not a blob", "name.txt");
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name);
+ }
+ return JSON.stringify(results);
+ })()`)
+ want := `[true,true,true,"blob","image/png",true,true,"new.txt","text/plain",123,"pic.png","image/png","blob",` +
+ `"b","f","TypeError"]`
+ if got != want {
+ t.Fatalf("blob entries = %s, want %s", got, want)
+ }
+}
+
+func TestFormDataIteration(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const fd = new FormData();
+ fd.append("a", "1");
+ fd.append("b", new Blob(["x"]));
+ const describe = (value) => typeof value === "string" ? value : value.name;
+ const iterator = fd.entries();
+ const result = {
+ sameFunction: FormData.prototype[Symbol.iterator] === FormData.prototype.entries,
+ tag: Object.prototype.toString.call(iterator),
+ selfIterable: iterator[Symbol.iterator]() === iterator,
+ keys: [...fd.keys()],
+ values: [...fd.values()].map(describe),
+ entries: Array.from(fd, ([key, value]) => key + "=" + describe(value)),
+ };
+
+ // 迭代按下标读取当前条目:迭代过程中追加的条目也会被遍历到。
+ const live = [];
+ for (const [key] of fd) {
+ live.push(key);
+ if (key === "a") {
+ fd.append("c", "3");
+ }
+ }
+ result.live = live;
+
+ // forEach 的回调参数为 (value, key, formData),第二个参数作为回调的 this;回调中追加的条目同样会被遍历到。
+ const seen = [];
+ fd.forEach(function (value, key, target) {
+ seen.push([describe(value), key, target === fd, this.marker]);
+ if (key === "a") {
+ fd.append("d", "4");
+ }
+ }, {marker: "this"});
+ result.seen = seen;
+
+ const keys = fd.keys();
+ for (let i = 0; i < 4; i++) {
+ keys.next();
+ }
+ result.exhausted = keys.next();
+ return JSON.stringify(result);
+ })()`)
+ want := `{"sameFunction":true,"tag":"[object FormData Iterator]","selfIterable":true,"keys":["a","b"],` +
+ `"values":["1","blob"],"entries":["a=1","b=blob"],"live":["a","b","c"],` +
+ `"seen":[["1","a",true,"this"],["blob","b",true,"this"],["3","c",true,"this"],["4","d",true,"this"]],` +
+ `"exhausted":{"done":true}}`
+ if got != want {
+ t.Fatalf("iteration = %s, want %s", got, want)
+ }
+}
+
+func TestFormDataRejectsInvalidArguments(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const results = [];
+ for (const fn of [
+ () => new FormData({}),
+ () => new FormData(null),
+ () => new FormData().append("a"),
+ () => new FormData().set(),
+ () => new FormData().get(),
+ () => new FormData().append(Symbol("name"), "x"),
+ () => FormData.prototype.append.call({}, "a", "b"),
+ () => FormData.prototype.entries.call({}),
+ () => new FormData().forEach(null),
+ () => new FormData().entries().next.call({}),
+ ]) {
+ try {
+ fn();
+ results.push("no throw");
+ } catch (e) {
+ results.push(e.constructor.name);
+ }
+ }
+ results.push(new FormData(undefined) instanceof FormData);
+ return results.join(",");
+ })()`)
+ if want := strings.Repeat("TypeError,", 10) + "true"; got != want {
+ t.Fatalf("invalid arguments = %s, want %s", got, want)
+ }
+}
+
+func TestFormDataInterfaceShape(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+
+ got := rt.run(`(() => {
+ class ExtendedFormData extends FormData {
+ extra = "field";
+ }
+ const extended = new ExtendedFormData();
+ extended.append("a", "1");
+ return JSON.stringify([
+ Object.keys(FormData.prototype),
+ FormData.prototype.append.length,
+ FormData.prototype.forEach.length,
+ Object.prototype.toString.call(new FormData()),
+ JSON.stringify(new FormData()),
+ extended instanceof ExtendedFormData, extended.get("a"), Object.keys(extended),
+ new URLSearchParams(extended).toString(),
+ ]);
+ })()`)
+ want := `[["append","delete","get","getAll","has","set","entries","keys","values","forEach"],2,1,` +
+ `"[object FormData]","{}",true,"1",["extra"],"a=1"]`
+ if got != want {
+ t.Fatalf("interface shape = %s, want %s", got, want)
+ }
+}
+
+// encodeFormDataGlobal 对全局变量 name 引用的 FormData 编码,返回请求体与 boundary。
+func encodeFormDataGlobal(t *testing.T, rt *formDataTestRuntime, name string) (body []byte, boundary string) {
+ t.Helper()
+
+ var contentType string
+ found := false
+ rt.withRuntime(func(rt *goja.Runtime) {
+ var state *State
+ if state, found = StateOf(rt.Get(name)); found {
+ body, contentType = state.EncodeMultipart()
+ }
+ })
+ if !found {
+ t.Fatalf("globalThis.%s is not a FormData", name)
+ }
+
+ mediaType, params, err := mime.ParseMediaType(contentType)
+ if err != nil || mediaType != "multipart/form-data" {
+ t.Fatalf("content type = %q (%v), want multipart/form-data", contentType, err)
+ }
+ boundary = params["boundary"]
+ if !strings.HasPrefix(boundary, "----formdata-siyuan-") || len(boundary) > 70 {
+ t.Fatalf("boundary = %q, want a random boundary of at most 70 characters", boundary)
+ }
+ return body, boundary
+}
+
+func TestFormDataEncodeMultipart(t *testing.T) {
+ rt := newFormDataTestRuntime(t)
+ rt.run(`
+ globalThis.fd = new FormData();
+ fd.append("text", "line1\nline2\rline3\r\nend");
+ fd.append("we\"ird\nname", "v");
+ fd.append("file", new File(["hello"], "a\"b\r\n.txt", {type: "Text/Plain"}));
+ fd.append("blob", new Blob([new Uint8Array([0, 255])]));
+ fd.append("renamed", new Blob(["x"], {type: "image/png"}), "pic.png");
+ fd.append("\u4e2d\u6587", "\u503c");
+ globalThis.empty = new FormData();
+ `)
+
+ body, boundary := encodeFormDataGlobal(t, rt, "fd")
+ want := strings.Join([]string{
+ "--" + boundary,
+ `Content-Disposition: form-data; name="text"`,
+ "",
+ "line1\r\nline2\r\nline3\r\nend",
+ "--" + boundary,
+ `Content-Disposition: form-data; name="we%22ird%0D%0Aname"`,
+ "",
+ "v",
+ "--" + boundary,
+ `Content-Disposition: form-data; name="file"; filename="a%22b%0D%0A.txt"`,
+ "Content-Type: text/plain",
+ "",
+ "hello",
+ "--" + boundary,
+ `Content-Disposition: form-data; name="blob"; filename="blob"`,
+ "Content-Type: application/octet-stream",
+ "",
+ "\x00\xff",
+ "--" + boundary,
+ `Content-Disposition: form-data; name="renamed"; filename="pic.png"`,
+ "Content-Type: image/png",
+ "",
+ "x",
+ "--" + boundary,
+ `Content-Disposition: form-data; name="中文"`,
+ "",
+ "值",
+ "--" + boundary + "--",
+ "",
+ }, "\r\n")
+ if string(body) != want {
+ t.Fatalf("body = %q, want %q", body, want)
+ }
+
+ // 内核用 Go 的 mime/multipart 解析表单,编码结果必须能被它还原;与浏览器一样,名称中的转义不会被解码。
+ form, err := multipart.NewReader(bytes.NewReader(body), boundary).ReadForm(1 << 20)
+ if err != nil {
+ t.Fatalf("parse multipart body: %v", err)
+ }
+ t.Cleanup(func() { form.RemoveAll() })
+ for name, want := range map[string]string{
+ "text": "line1\r\nline2\r\nline3\r\nend",
+ "we%22ird%0D%0Aname": "v",
+ "中文": "值",
+ } {
+ if got := form.Value[name]; len(got) != 1 || got[0] != want {
+ t.Fatalf("form value %q = %q, want [%q]", name, got, want)
+ }
+ }
+ for name, want := range map[string][3]string{
+ "file": {"a%22b%0D%0A.txt", "text/plain", "hello"},
+ "blob": {"blob", "application/octet-stream", "\x00\xff"},
+ "renamed": {"pic.png", "image/png", "x"},
+ } {
+ files := form.File[name]
+ if len(files) != 1 {
+ t.Fatalf("form file %q count = %d, want 1", name, len(files))
+ }
+ file, err := files[0].Open()
+ if err != nil {
+ t.Fatalf("open form file %q: %v", name, err)
+ }
+ content, err := io.ReadAll(file)
+ file.Close()
+ if err != nil {
+ t.Fatalf("read form file %q: %v", name, err)
+ }
+ got := [3]string{files[0].Filename, files[0].Header.Get("Content-Type"), string(content)}
+ if got != want {
+ t.Fatalf("form file %q = %q, want %q", name, got, want)
+ }
+ }
+
+ body, boundary = encodeFormDataGlobal(t, rt, "empty")
+ if want := "--" + boundary + "--\r\n"; string(body) != want {
+ t.Fatalf("empty body = %q, want %q", body, want)
+ }
+}
diff --git a/kernel/plugin/formdata/webidl.go b/kernel/plugin/formdata/webidl.go
new file mode 100644
index 0000000000..1b06ca1609
--- /dev/null
+++ b/kernel/plugin/formdata/webidl.go
@@ -0,0 +1,220 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package formdata
+
+import (
+ "math"
+ "slices"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+)
+
+// expandoProperties 保存脚本在宿主对象上自行添加的属性,使 Blob、File、FormData 能像浏览器中的平台对象一样
+// 挂载自定义属性、被子类用类字段扩展;内建成员都由原型上的访问器与方法提供,不经过这里。
+type expandoProperties struct {
+ keys []string
+ values map[string]goja.Value
+}
+
+func (e *expandoProperties) Get(key string) goja.Value { return e.values[key] }
+
+func (e *expandoProperties) Set(key string, value goja.Value) bool {
+ if e.values == nil {
+ e.values = map[string]goja.Value{}
+ }
+ if _, ok := e.values[key]; !ok {
+ e.keys = append(e.keys, key)
+ }
+ e.values[key] = value
+ return true
+}
+
+func (e *expandoProperties) Has(key string) bool {
+ _, ok := e.values[key]
+ return ok
+}
+
+func (e *expandoProperties) Delete(key string) bool {
+ if _, ok := e.values[key]; ok {
+ delete(e.values, key)
+ e.keys = slices.DeleteFunc(e.keys, func(k string) bool { return k == key })
+ }
+ return true
+}
+
+func (e *expandoProperties) Keys() []string { return slices.Clone(e.keys) }
+
+// usvStringOf 按 WebIDL 把值转换为 USVString:执行 ECMAScript ToString(对象会调用其 toString/valueOf,Symbol 抛
+// TypeError),未配对的代理项替换为 U+FFFD(goja 把 UTF-16 字符串转为 Go 字符串时即如此处理)。
+func usvStringOf(rt *goja.Runtime, value goja.Value) string {
+ str := value.ToString()
+ if _, ok := str.(*goja.Symbol); ok {
+ panic(rt.NewTypeError("Cannot convert a Symbol value to a string"))
+ }
+ return str.String()
+}
+
+// longLongOf 按 WebIDL 把值转换为 long long(无 [Clamp] 与 [EnforceRange]):ToNumber 后 NaN 与无穷大视为 0,
+// 截断小数部分,超出 64 位有符号范围时按 2^64 取模回绕。
+func longLongOf(value goja.Value) int64 {
+ x := value.ToFloat()
+ if math.IsNaN(x) || math.IsInf(x, 0) {
+ return 0
+ }
+ x = math.Trunc(x)
+ if x < math.MinInt64 || x >= math.MaxInt64 {
+ x = math.Mod(x, 1<<64)
+ if x < math.MinInt64 {
+ x += 1 << 64
+ } else if x >= math.MaxInt64 {
+ x -= 1 << 64
+ }
+ }
+ return int64(x)
+}
+
+// clampedLongLongOf 按 WebIDL [Clamp] long long 转换:NaN 视为 0,超出范围取边界,就近取整且恰在中间时取偶数。
+// 返回 float64,调用方再与不超过 2^53 的长度比较,因此不会损失精度。
+func clampedLongLongOf(value goja.Value) float64 {
+ x := value.ToFloat()
+ if math.IsNaN(x) {
+ return 0
+ }
+ x = math.Min(math.Max(x, math.MinInt64), math.MaxInt64)
+ // 加 0 把 -0 规范化为 +0。
+ return math.RoundToEven(x) + 0
+}
+
+// iterateSequence 按 WebIDL 把值转换为 sequence:值必须是对象,Symbol.iterator 方法只读取一次,随后逐项取值并立即
+// 交给 convert 转换;转换出错时异常直接向上传播,不关闭迭代器(与 WebIDL 一致)。
+func iterateSequence(rt *goja.Runtime, value goja.Value, context string, convert func(goja.Value)) {
+ object, ok := value.(*goja.Object)
+ if !ok {
+ panic(rt.NewTypeError("%s: Argument 1 can't be converted to a sequence", context))
+ }
+ getIterator, ok := goja.AssertFunction(object.GetSymbol(goja.SymIterator))
+ if !ok {
+ panic(rt.NewTypeError("%s: Argument 1 can't be converted to a sequence", context))
+ }
+ iteratorValue, err := getIterator(object)
+ if err != nil {
+ panic(err)
+ }
+ iterator, ok := iteratorValue.(*goja.Object)
+ if !ok {
+ panic(rt.NewTypeError("%s: Result of the Symbol.iterator method is not an object", context))
+ }
+ next, ok := goja.AssertFunction(iterator.Get("next"))
+ if !ok {
+ panic(rt.NewTypeError("%s: The iterator's next method is not callable", context))
+ }
+
+ for {
+ resultValue, err := next(iterator)
+ if err != nil {
+ panic(err)
+ }
+ result, ok := resultValue.(*goja.Object)
+ if !ok {
+ panic(rt.NewTypeError("%s: Iterator result is not an object", context))
+ }
+ if done := result.Get("done"); done != nil && done.ToBoolean() {
+ return
+ }
+ element := result.Get("value")
+ if element == nil {
+ element = goja.Undefined()
+ }
+ convert(element)
+ }
+}
+
+// newMethod 创建 name 与 length 符合规范的原生函数;goja 默认以 Go 函数的完整限定名作为函数的 name。
+func newMethod(rt *goja.Runtime, name string, length int, fn func(goja.FunctionCall) goja.Value) *goja.Object {
+ method := rt.ToValue(fn).(*goja.Object)
+ lo.Must0(method.DefineDataProperty("name", rt.ToValue(name), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ lo.Must0(method.DefineDataProperty("length", rt.ToValue(length), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return method
+}
+
+// defineMethod 按 WebIDL 操作的属性特性(可写、可配置、可枚举)在 target 上定义方法。
+func defineMethod(rt *goja.Runtime, target *goja.Object, name string, length int, fn func(goja.FunctionCall) goja.Value) {
+ method := newMethod(rt, name, length, fn)
+ lo.Must0(target.DefineDataProperty(name, method, goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_TRUE))
+}
+
+// defineGetter 按 WebIDL 只读属性的特性(无 setter、可配置、可枚举)在 target 上定义访问器。
+func defineGetter(rt *goja.Runtime, target *goja.Object, name string, get func(goja.FunctionCall) goja.Value) {
+ getter := newMethod(rt, "get "+name, 0, get)
+ lo.Must0(target.DefineAccessorProperty(name, getter, nil, goja.FLAG_TRUE, goja.FLAG_TRUE))
+}
+
+// defineToStringTag 定义 Symbol.toStringTag,使 Object.prototype.toString 返回 [object <tag>]。
+func defineToStringTag(rt *goja.Runtime, target *goja.Object, tag string) {
+ lo.Must0(target.DefineDataPropertySymbol(goja.SymToStringTag, rt.ToValue(tag), goja.FLAG_FALSE, goja.FLAG_TRUE,
+ goja.FLAG_FALSE))
+}
+
+// newInterfaceConstructor 创建接口的构造函数,并按 WebIDL 设置 name、length、prototype 与 prototype.constructor 的
+// 属性特性。construct 应以 call.This.Prototype() 作为实例原型,使子类构造的实例继承子类的原型。
+func newInterfaceConstructor(rt *goja.Runtime, name string, length int, prototype *goja.Object,
+ construct func(goja.ConstructorCall) *goja.Object) *goja.Object {
+ constructor := rt.ToValue(construct).(*goja.Object)
+ lo.Must0(constructor.DefineDataProperty("name", rt.ToValue(name), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ lo.Must0(constructor.DefineDataProperty("length", rt.ToValue(length), goja.FLAG_FALSE, goja.FLAG_TRUE,
+ goja.FLAG_FALSE))
+ lo.Must0(constructor.DefineDataProperty("prototype", prototype, goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_FALSE))
+ lo.Must0(prototype.DefineDataProperty("constructor", constructor, goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return constructor
+}
+
+// builtinGetter 取出 object 上自有访问器属性 name 的 getter,供注册时捕获内建访问器,避免插件脚本事后改写。
+func builtinGetter(rt *goja.Runtime, object *goja.Object, name string) goja.Callable {
+ objectConstructor := rt.Get("Object").ToObject(rt)
+ getOwnPropertyDescriptor, ok := goja.AssertFunction(objectConstructor.Get("getOwnPropertyDescriptor"))
+ if !ok {
+ panic(rt.NewTypeError("Object.getOwnPropertyDescriptor is not a function"))
+ }
+ descriptor := lo.Must(getOwnPropertyDescriptor(objectConstructor, object, rt.ToValue(name))).ToObject(rt)
+ getter, ok := goja.AssertFunction(descriptor.Get("get"))
+ if !ok {
+ panic(rt.NewTypeError("the %s property has no getter", name))
+ }
+ return getter
+}
+
+// iteratorPrototypeOf 返回 %IteratorPrototype%(数组迭代器原型的原型),以它为原型的迭代器自身也是可迭代对象。
+func iteratorPrototypeOf(rt *goja.Runtime) *goja.Object {
+ array := rt.NewArray()
+ values, ok := goja.AssertFunction(array.GetSymbol(goja.SymIterator))
+ if !ok {
+ panic(rt.NewTypeError("Array.prototype[Symbol.iterator] is not a function"))
+ }
+ iterator := lo.Must(values(array)).ToObject(rt)
+ return iterator.Prototype().Prototype()
+}
+
+// isJsValueNotUndefined 与 isJsValueNotNull 和 kernel/plugin/sandbox.go 的同名函数同构:本包不依赖 plugin 包,避免
+// 循环依赖,因此复制一份。
+func isJsValueNotUndefined(jsValue goja.Value) bool {
+ return jsValue != nil && !goja.IsUndefined(jsValue)
+}
+
+func isJsValueNotNull(jsValue goja.Value) bool {
+ return isJsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)
+}
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
index d9100c0052..ffdae6232c 100644
--- a/kernel/plugin/plugin.go
+++ b/kernel/plugin/plugin.go
@@ -39,6 +39,8 @@ import (
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/mcp/tools"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/plugin/formdata"
+ "github.com/siyuan-note/siyuan/kernel/plugin/streams"
"github.com/siyuan-note/siyuan/kernel/util"
"github.com/smallnest/chanx"
)
@@ -103,6 +105,9 @@ type KernelPlugin struct {
worker Worker // Worker for serializing plugin js-call-go (e.g. logger) and go-call-js (e.g. RPC calls) tasks on a single goroutine
runtime *eventloop.EventLoop // goja event loop runtime for this plugin
+ formDataHost *formdata.Host // 当前 runtime 中 Blob、File 与 FormData 的宿主状态,由 EnableExtendModules 设置
+ streamsHost *streams.Host // 当前 runtime 中 ReadableStream/WritableStream/TransformStream 的宿主状态,由 EnableExtendModules 设置
+
watcherMu sync.Mutex
watcher *fsnotify.Watcher // watcher for kernel plugin storage file changes
watcherDone chan struct{}
@@ -959,8 +964,11 @@ func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope
return
}
- // convert response.body?.raw?.data from (string | Buffer | ArrayBuffer) to []byte
+ // convert response.body?.raw?.data from (string | Buffer | ArrayBuffer) to []byte, and pull out
+ // response.body?.stream?.stream (a ReadableStream instance) before the JSON round trip below:
+ // 两者都不能走 JSON 编解码,前者要转换成 []byte,后者是活的流对象,序列化不出有意义的结果。
var raw *[]byte
+ var stream *goja.Object
if bodyValue := responseObj.Get("body"); isJsValueNotNull(bodyValue) {
// response.body
if bodyObj := bodyValue.ToObject(rt); bodyObj != nil {
@@ -977,6 +985,18 @@ func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope
}
}
}
+ if streamValue := bodyObj.Get("stream"); isJsValueNotNull(streamValue) {
+ // response.body.stream
+ if streamObj := streamValue.ToObject(rt); streamObj != nil {
+ if innerValue := streamObj.Get("stream"); isJsValueNotNull(innerValue) {
+ // response.body.stream.stream
+ if innerObj := innerValue.ToObject(rt); innerObj != nil && p.streamsHost.IsReadableStream(innerObj) {
+ stream = innerObj
+ streamObj.Set("stream", goja.Null())
+ }
+ }
+ }
+ }
}
}
@@ -1002,6 +1022,9 @@ func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope
if raw != nil && response.Body != nil && response.Body.Raw != nil {
response.Body.Raw.Data = *raw
}
+ if stream != nil && response.Body != nil && response.Body.Stream != nil {
+ response.Body.Stream.Stream = stream
+ }
done <- &handleResult{Value: &response}
}, rt, true, handler, handlerObj, jsRequest)
diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.go
index 944745f7bb..045cd046f8 100644
--- a/kernel/plugin/sandbox.go
+++ b/kernel/plugin/sandbox.go
@@ -18,8 +18,15 @@ package plugin
import (
"encoding/json"
+ "errors"
"fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "path/filepath"
"strconv"
+ "strings"
"time"
"github.com/dop251/goja"
@@ -30,6 +37,10 @@ import (
"github.com/imroc/req/v3"
"github.com/samber/lo"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/plugin/abort"
+ "github.com/siyuan-note/siyuan/kernel/plugin/encoding"
+ "github.com/siyuan-note/siyuan/kernel/plugin/formdata"
+ "github.com/siyuan-note/siyuan/kernel/plugin/streams"
)
type WebSocketState int64
@@ -84,7 +95,7 @@ func EnableExtendModules(p *KernelPlugin, rt *goja.Runtime) (err error) {
}
}()
- registry := require.NewRegistry()
+ registry := require.NewRegistry(require.WithLoader(pluginSourceLoader(p)))
registry.Enable(rt)
registry.RegisterNativeModule(
@@ -95,9 +106,54 @@ func EnableExtendModules(p *KernelPlugin, rt *goja.Runtime) (err error) {
url.Enable(rt)
buffer.Enable(rt)
console.Enable(rt)
+ encoding.Enable(rt)
+ abort.Enable(rt)
+ p.formDataHost = formdata.Enable(rt)
+ p.streamsHost = streams.Enable(rt)
return
}
+// pluginSourceLoader 返回 require 的源码加载器,只读取插件目录(kernel.js 所在目录)内的普通文件。
+// require 以调用方脚本名为基准解析相对路径,kernel.js 的脚本名是 p.file,因此 p.file 所在目录对应插件目录;
+// 绝对路径、越出插件目录的路径以及向上查找到的 node_modules 都视为模块文件不存在,解析器会继续尝试其他候选路径。
+// 文件经插件目录句柄打开,指向插件目录之外的符号链接无法读取。
+func pluginSourceLoader(p *KernelPlugin) require.SourceLoader {
+ prefix := filepath.Dir(p.file) + string(filepath.Separator)
+ return func(name string) ([]byte, error) {
+ rel, ok := strings.CutPrefix(name, prefix)
+ if !ok || !filepath.IsLocal(rel) {
+ return nil, require.ModuleFileDoesNotExistError
+ }
+
+ root, err := os.OpenRoot(p.pluginDir)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, require.ModuleFileDoesNotExistError
+ }
+ return nil, err
+ }
+ defer root.Close()
+
+ file, err := root.Open(rel)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, require.ModuleFileDoesNotExistError
+ }
+ return nil, err
+ }
+ defer file.Close()
+
+ info, err := file.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, require.ModuleFileDoesNotExistError
+ }
+ return io.ReadAll(file)
+ }
+}
+
// EnableSiyuanModule injects all siyuan.* APIs into the plugin's goja global context.
func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {
defer func() {
@@ -117,7 +173,7 @@ func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {
lo.Must0(injectClient(p, rt, siyuan))
lo.Must0(injectServer(p, rt, siyuan))
lo.Must0(injectSecretsVars(p, rt, siyuan))
- lo.Must0(injectCrypto(p, rt, siyuan))
+ lo.Must0(injectCrypto(p, rt))
lo.Must0(ObjectFreeze(rt, siyuan))
@@ -157,15 +213,20 @@ func ObjectSeal(rt *goja.Runtime, obj *goja.Object) error {
return err
}
-// ObjectSetDataMethods attaches text(), json(), buffer() and arrayBuffer() methods to a JS object,
-// each returning a Promise that resolves with the corresponding representation of data.
-func ObjectSetDataMethods(p *KernelPlugin, rt *goja.Runtime, object *goja.Object, data []byte) (err error) {
+// ObjectSetDataMethods 给 JS 对象添加 text()、json()、buffer()、arrayBuffer()、bytes() 与 blob() 方法,各方法返回以
+// data 的相应形式完成的 Promise。buffer()、arrayBuffer() 与 bytes() 的结果直接引用 data,不做复制;blob()
+// 返回 data 的副本,脚本修改其他方法的结果不会改变 Blob 的内容,Blob 的 type 是按 Blob 构造函数的 type 选项
+// 规范化后的 contentType(不按 MIME 类型解析)。
+func ObjectSetDataMethods(p *KernelPlugin, rt *goja.Runtime, object *goja.Object, data []byte, contentType string) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("ObjectSetDataMethods: %v", r)
}
}()
+ // 使用注册时捕获的 Blob 原型与 Uint8Array 构造函数,插件脚本改写同名全局不影响返回的对象。
+ host := p.formDataHost
+
lo.Must0(object.Set("text", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
promise, resolve, reject := rt.NewPromise()
@@ -276,13 +337,65 @@ func ObjectSetDataMethods(p *KernelPlugin, rt *goja.Runtime, object *goja.Object
return rt.ToValue(promise)
})))
+ lo.Must0(object.Set("bytes", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ result, err = host.NewUint8Array(rt, data)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(rt.ToValue(result)); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.bytes() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.bytes() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] bytes worker run: %v", p.Name, runErr)
+ if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.bytes() reject: %v", p.Name, rejectErr)
+ }
+ }
+
+ return rt.ToValue(promise)
+ })))
+ lo.Must0(object.Set("blob", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ result = host.NewBlob(rt, data, contentType)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(rt.ToValue(result)); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.blob() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.blob() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] blob worker run: %v", p.Name, runErr)
+ if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.blob() reject: %v", p.Name, rejectErr)
+ }
+ }
+
+ return rt.ToValue(promise)
+ })))
return
}
-// NewDataObject creates a new JS object with text(), json(), buffer() and arrayBuffer() methods for the given data.
-func NewDataObject(p *KernelPlugin, rt *goja.Runtime, data []byte) (*goja.Object, error) {
+// NewDataObject 创建带有 ObjectSetDataMethods 所述数据方法的 JS 对象,contentType 为 blob() 返回的 Blob 的媒体类型。
+func NewDataObject(p *KernelPlugin, rt *goja.Runtime, data []byte, contentType string) (*goja.Object, error) {
obj := rt.NewObject()
- if err := ObjectSetDataMethods(p, rt, obj, data); err != nil {
+ if err := ObjectSetDataMethods(p, rt, obj, data, contentType); err != nil {
return nil, err
}
return obj, nil
@@ -549,7 +662,8 @@ func getRequestHandler(rt *goja.Runtime, scope AccessScope, requestType RequestT
func requestGoToJs(p *KernelPlugin, rt *goja.Runtime, request *Request) (jsRequest goja.Value, err error) {
// convert body raw data to js object
if data, ok := request.Request.Body.Data.(*[]byte); ok && data != nil {
- request.Request.Body.Data, err = NewDataObject(p, rt, *data)
+ contentType := http.Header(request.Request.Headers).Get("Content-Type")
+ request.Request.Body.Data, err = NewDataObject(p, rt, *data, contentType)
if err != nil {
return
}
@@ -560,7 +674,8 @@ func requestGoToJs(p *KernelPlugin, rt *goja.Runtime, request *Request) (jsReque
for _, fileList := range request.Request.Body.Form.File {
for _, file := range fileList {
if data, ok := file.Data.(*[]byte); ok && data != nil {
- file.Data, err = NewDataObject(p, rt, *data)
+ contentType := http.Header(file.Headers).Get("Content-Type")
+ file.Data, err = NewDataObject(p, rt, *data, contentType)
if err != nil {
return
}
diff --git a/kernel/plugin/sandbox_test.go b/kernel/plugin/sandbox_test.go
new file mode 100644
index 0000000000..e67c027277
--- /dev/null
+++ b/kernel/plugin/sandbox_test.go
@@ -0,0 +1,422 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/dop251/goja_nodejs/require"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+const requireTestSecret = "require-test-secret"
+
+// newRequireTestPlugin 构造 require 测试用插件,脚本名与 NewKernelPlugin 的约定一致。
+func newRequireTestPlugin(pluginsDir, name string) *KernelPlugin {
+ return &KernelPlugin{
+ Petal: &model.Petal{Name: name},
+ file: fmt.Sprintf("%s/kernel.js", name),
+ pluginDir: filepath.Join(pluginsDir, name),
+ }
+}
+
+// writeRequireTestFiles 按斜杠分隔的相对路径在 dir 下写入文件。
+func writeRequireTestFiles(t *testing.T, dir string, files map[string]string) {
+ t.Helper()
+ for name, content := range files {
+ path := filepath.Join(dir, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// requireFromKernelJS 按 InitRuntime 的方式创建事件循环并启用扩展模块,再在 kernel.js 的脚本名下调用 require,
+// 返回 "ok:" 加导出值的 JSON,或 "error:" 加捕获到的异常。
+func requireFromKernelJS(t *testing.T, p *KernelPlugin, specifier string) string {
+ t.Helper()
+
+ var result string
+ var runErr error
+ loop := eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ loop.Run(func(rt *goja.Runtime) {
+ if runErr = EnableExtendModules(p, rt); runErr != nil {
+ return
+ }
+ if runErr = rt.Set("specifier", specifier); runErr != nil {
+ return
+ }
+ var value goja.Value
+ value, runErr = rt.RunScript(p.file, `(() => {
+ try {
+ return "ok:" + JSON.stringify(require(specifier));
+ } catch (e) {
+ return "error:" + e;
+ }
+ })()`)
+ if runErr == nil {
+ result = value.String()
+ }
+ })
+ if runErr != nil {
+ t.Fatalf("require(%q): %v", specifier, runErr)
+ }
+ return result
+}
+
+func TestPluginRequireLoadsFromPluginDir(t *testing.T) {
+ root := t.TempDir()
+ pluginsDir := filepath.Join(root, "plugins")
+ p := newRequireTestPlugin(pluginsDir, "test-require")
+ writeRequireTestFiles(t, p.pluginDir, map[string]string{
+ "index.js": `module.exports = "root-index";`,
+ "lib/a.js": `module.exports = "a+" + require("./b");`,
+ "lib/b.js": `module.exports = "b";`,
+ "lib/sub/index.js": `module.exports = "sub-index";`,
+ "data.json": `{"value": "inside"}`,
+ "node_modules/dep/package.json": `{"main": "main.js"}`,
+ "node_modules/dep/main.js": `module.exports = "dep";`,
+ })
+
+ for _, tt := range []struct {
+ name string
+ specifier string
+ want string
+ }{
+ {"relative file with nested extensionless require", "./lib/a.js", `ok:"a+b"`},
+ {"directory index", "./lib/sub", `ok:"sub-index"`},
+ // 解析插件目录本身时会先尝试插件目录外的同名 .js/.json,这些候选必须按不存在处理才能继续解析
+ {"plugin directory as a module", "./", `ok:"root-index"`},
+ {"json file", "./data.json", `ok:{"value":"inside"}`},
+ {"node_modules inside the plugin directory", "dep", `ok:"dep"`},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := requireFromKernelJS(t, p, tt.specifier); got != tt.want {
+ t.Fatalf("require(%q) = %s, want %s", tt.specifier, got, tt.want)
+ }
+ })
+ }
+
+ t.Run("symlink pointing outside the plugin directory", func(t *testing.T) {
+ outside := filepath.Join(root, "outside.json")
+ writeRequireTestFiles(t, root, map[string]string{"outside.json": fmt.Sprintf(`{"secret": %q}`, requireTestSecret)})
+ if err := os.Symlink(outside, filepath.Join(p.pluginDir, "escape.json")); err != nil {
+ // Windows 未开启开发者模式时创建符号链接需要特权
+ t.Skipf("symlink is unavailable: %s", err)
+ }
+ got := requireFromKernelJS(t, p, "./escape.json")
+ if !strings.HasPrefix(got, "error:") || strings.Contains(got, requireTestSecret) {
+ t.Fatalf("require followed a symlink outside the plugin directory: %s", got)
+ }
+ })
+
+ t.Run("plugin directory is a symlink", func(t *testing.T) {
+ target := filepath.Join(root, "dev", "linked-plugin")
+ writeRequireTestFiles(t, target, map[string]string{"lib/b.js": `module.exports = "linked";`})
+ linked := newRequireTestPlugin(pluginsDir, "test-require-linked")
+ if err := os.Symlink(target, linked.pluginDir); err != nil {
+ t.Skipf("symlink is unavailable: %s", err)
+ }
+ if got := requireFromKernelJS(t, linked, "./lib/b.js"); got != `ok:"linked"` {
+ t.Fatalf("require from a symlinked plugin directory = %s", got)
+ }
+ })
+}
+
+func TestPluginRequireRejectsPathsOutsidePluginDir(t *testing.T) {
+ root := t.TempDir()
+ pluginsDir := filepath.Join(root, "plugins")
+ p := newRequireTestPlugin(pluginsDir, "test-require")
+ secretJSON := fmt.Sprintf(`{"secret": %q}`, requireTestSecret)
+ writeRequireTestFiles(t, root, map[string]string{
+ "outside.json": secretJSON,
+ "plugins/test-require/kernel.js": "",
+ "plugins/test-require-other/secret.json": secretJSON,
+ "plugins/node_modules/hoisted/index.js": fmt.Sprintf(`module.exports = %q;`, requireTestSecret),
+ })
+ // 工作目录切到插件根目录后,不受限的加载器能按相对路径读到同级插件与上级 node_modules,用例因此能发现限制失效
+ t.Chdir(pluginsDir)
+
+ for _, tt := range []struct {
+ name string
+ specifier string
+ }{
+ {"absolute path", filepath.ToSlash(filepath.Join(root, "outside.json"))},
+ {"relative traversal", "../../outside.json"},
+ {"sibling plugin sharing the name prefix", "../test-require-other/secret.json"},
+ {"node_modules above the plugin directory", "hoisted"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got := requireFromKernelJS(t, p, tt.specifier)
+ if strings.Contains(got, requireTestSecret) {
+ t.Fatalf("require(%q) loaded a file outside the plugin directory: %s", tt.specifier, got)
+ }
+ // 插件目录外的文件与不存在的模块无法区分
+ if !strings.HasPrefix(got, "error:") || !strings.Contains(got, require.InvalidModuleError.Error()) {
+ t.Fatalf("require(%q) = %s, want %q", tt.specifier, got, require.InvalidModuleError)
+ }
+ })
+ }
+}
+
+func TestEnableExtendModulesInstallsTextEncoderAndDecoder(t *testing.T) {
+ p := &KernelPlugin{Petal: &model.Petal{Name: "test-text-encoding"}}
+
+ var got string
+ var runErr error
+ loop := eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ loop.Run(func(rt *goja.Runtime) {
+ // 与 InitRuntime 一致先设置字段名映射,TextDecoder 依赖它读取 fatal 等选项
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ if runErr = EnableExtendModules(p, rt); runErr != nil {
+ return
+ }
+ var value goja.Value
+ value, runErr = rt.RunString(`(() => {
+ const bytes = new TextEncoder().encode("思源 ✓");
+ const fatal = new TextDecoder("utf-8", {fatal: true});
+ let threw = false;
+ try {
+ fatal.decode(new Uint8Array([0xff]));
+ } catch (e) {
+ threw = e instanceof TypeError;
+ }
+ return [new TextDecoder().decode(bytes), bytes.length, fatal.fatal, threw].join(",");
+ })()`)
+ if runErr == nil {
+ got = value.String()
+ }
+ })
+ if runErr != nil {
+ t.Fatalf("run script: %v", runErr)
+ }
+ if want := "思源 ✓,10,true,true"; got != want {
+ t.Fatalf("TextEncoder/TextDecoder = %s, want %s", got, want)
+ }
+}
+
+// dataObjectTestRuntime 是在事件循环上执行脚本的辅助对象,与 kernel/plugin/formdata 测试中的 formDataTestRuntime
+// 同构:其他包的测试文件对本包不可见,因此复制一份。
+type dataObjectTestRuntime struct {
+ t *testing.T
+ loop *eventloop.EventLoop
+}
+
+// withRuntime 在事件循环上同步执行 fn。fn 运行在事件循环的 goroutine 上,不能调用 t.Fatal。
+func (r *dataObjectTestRuntime) withRuntime(fn func(rt *goja.Runtime)) {
+ r.t.Helper()
+
+ done := make(chan struct{})
+ r.loop.RunOnLoop(func(rt *goja.Runtime) {
+ defer close(done)
+ fn(rt)
+ })
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ r.t.Fatal("timed out waiting for the event loop")
+ }
+}
+
+// await 执行一段返回 Promise 的脚本,等待其完成后返回结果的字符串形式;被拒绝时以 "rejected:" 开头。
+func (r *dataObjectTestRuntime) await(script string) string {
+ r.t.Helper()
+
+ result := make(chan string, 1)
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ var value goja.Value
+ if value, err = rt.RunString(script); err != nil {
+ return
+ }
+ promise := value.ToObject(rt)
+ then, ok := goja.AssertFunction(promise.Get("then"))
+ if !ok {
+ err = fmt.Errorf("script did not return a promise")
+ return
+ }
+ _, err = then(promise, rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- call.Argument(0).String()
+ return goja.Undefined()
+ }), rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ result <- "rejected:" + call.Argument(0).String()
+ return goja.Undefined()
+ }))
+ })
+ if err != nil {
+ r.t.Fatalf("script failed: %v\n%s", err, script)
+ }
+
+ select {
+ case got := <-result:
+ return got
+ case <-time.After(5 * time.Second):
+ r.t.Fatalf("timed out waiting for:\n%s", script)
+ return ""
+ }
+}
+
+// newDataObjectTestPlugin 按 InitRuntime 的方式启用扩展模块,返回事件循环已启动的测试插件,以及在其 runtime 中执行
+// 脚本的辅助对象。
+func newDataObjectTestPlugin(t *testing.T) (*KernelPlugin, *dataObjectTestRuntime) {
+ t.Helper()
+
+ loop := eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ loop.Start()
+ t.Cleanup(func() { loop.Stop() })
+
+ p := &KernelPlugin{Petal: &model.Petal{Name: "test-data-object"}}
+ p.worker.Start(loop)
+ r := &dataObjectTestRuntime{t: t, loop: loop}
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ err = EnableExtendModules(p, rt)
+ })
+ if err != nil {
+ t.Fatalf("EnableExtendModules: %v", err)
+ }
+ return p, r
+}
+
+// setDataObjects 为 contentTypes 的每个键创建内容为 data 副本的数据对象,挂到同名全局变量。
+func setDataObjects(t *testing.T, p *KernelPlugin, r *dataObjectTestRuntime, data []byte, contentTypes map[string]string) {
+ t.Helper()
+
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ for name, contentType := range contentTypes {
+ var object *goja.Object
+ if object, err = NewDataObject(p, rt, bytes.Clone(data), contentType); err != nil {
+ return
+ }
+ if err = rt.Set(name, object); err != nil {
+ return
+ }
+ }
+ })
+ if err != nil {
+ t.Fatalf("create data objects: %v", err)
+ }
+}
+
+func TestDataObjectBytesAndBlob(t *testing.T) {
+ p, r := newDataObjectTestPlugin(t)
+ setDataObjects(t, p, r, []byte("hi\x00\xff"), map[string]string{
+ "typed": "Text/Plain; Charset=UTF-8",
+ "untyped": "",
+ "invalid": "text/plain; name=\u00e9",
+ })
+
+ got := r.await(`(async () => {
+ const bytes = await typed.bytes();
+ const blob = await typed.blob();
+ const bytesBefore = Array.from(bytes);
+ // arrayBuffer() 与 bytes() 的结果和数据对象共享内存,改写其中一个会反映到另一个,但不影响此前由 blob() 复制出的 Blob。
+ new Uint8Array(await typed.arrayBuffer()).fill(0);
+ return JSON.stringify([
+ Object.getPrototypeOf(bytes) === Uint8Array.prototype, bytesBefore, Array.from(bytes),
+ Object.getPrototypeOf(blob) === Blob.prototype, blob.type, blob.size, Array.from(await blob.bytes()),
+ (await untyped.blob()).type, (await invalid.blob()).type,
+ ]);
+ })()`)
+ want := `[true,[104,105,0,255],[0,0,0,0],true,"text/plain; charset=utf-8",4,[104,105,0,255],"",""]`
+ if got != want {
+ t.Fatalf("bytes() and blob() = %s, want %s", got, want)
+ }
+}
+
+func TestDataObjectIgnoresReplacedGlobals(t *testing.T) {
+ p, r := newDataObjectTestPlugin(t)
+ setDataObjects(t, p, r, []byte("x"), map[string]string{"data": ""})
+
+ got := r.await(`(async () => {
+ const OriginalBlob = Blob;
+ const OriginalUint8Array = Uint8Array;
+ globalThis.Blob = class {};
+ globalThis.Uint8Array = class {};
+ return JSON.stringify([
+ (await data.blob()) instanceof OriginalBlob,
+ (await data.bytes()) instanceof OriginalUint8Array,
+ ]);
+ })()`)
+ if want := `[true,true]`; got != want {
+ t.Fatalf("results after replacing globals = %s, want %s", got, want)
+ }
+}
+
+func TestRequestDataObjectsUseContentTypes(t *testing.T) {
+ p, r := newDataObjectTestPlugin(t)
+ body := []byte(`{"a":1}`)
+ typedFile := []byte("hello")
+ untypedFile := []byte("x")
+ requests := map[string]*Request{
+ "bodyRequest": {Request: RequestContent{
+ Headers: map[string][]string{"Content-Type": {"Application/JSON; Charset=UTF-8"}},
+ Body: RequestBody{Data: &body},
+ }},
+ "formRequest": {Request: RequestContent{
+ Headers: map[string][]string{"Content-Type": {"multipart/form-data; boundary=x"}},
+ Body: RequestBody{Form: &RequestForm{File: map[string][]*RequestFile{"file": {
+ {Headers: map[string][]string{"Content-Type": {"Text/Plain"}}, Data: &typedFile},
+ {Headers: map[string][]string{}, Data: &untypedFile},
+ }}}},
+ }},
+ }
+
+ var err error
+ r.withRuntime(func(rt *goja.Runtime) {
+ for name, request := range requests {
+ var value goja.Value
+ if value, err = requestGoToJs(p, rt, request); err != nil {
+ return
+ }
+ if err = rt.Set(name, value); err != nil {
+ return
+ }
+ }
+ })
+ if err != nil {
+ t.Fatalf("convert requests: %v", err)
+ }
+
+ // 请求体使用请求的 Content-Type;表单文件使用各自分段的 Content-Type,分段没有 Content-Type 时为空串。
+ got := r.await(`(async () => {
+ const files = formRequest.request.body.form.files.file;
+ const blobs = [
+ await bodyRequest.request.body.data.blob(),
+ await files[0].data.blob(),
+ await files[1].data.blob(),
+ ];
+ return JSON.stringify(await Promise.all(blobs.map(async (blob) => [blob.type, await blob.text()])));
+ })()`)
+ want := `[["application/json; charset=utf-8","{\"a\":1}"],["text/plain","hello"],["","x"]]`
+ if got != want {
+ t.Fatalf("request blobs = %s, want %s", got, want)
+ }
+}
diff --git a/kernel/plugin/server.go b/kernel/plugin/server.go
index 542503b031..a0705b53d7 100644
--- a/kernel/plugin/server.go
+++ b/kernel/plugin/server.go
@@ -17,6 +17,7 @@
package plugin
import (
+ "bytes"
"fmt"
"io"
"net/http"
@@ -27,6 +28,7 @@ import (
"github.com/dop251/goja"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/plugin/streams"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -150,6 +152,7 @@ type ResponseBody struct {
Raw *ResponseRawData `json:"raw"` // if the response is raw data, Raw will be non-nil.
Redirect *ResponseRedirect `json:"redirect"` // if the response is a redirect, Redirect will be non-nil.
Proxy *ResponseProxy `json:"proxy"` // if the response is a streaming proxy, Proxy will be non-nil.
+ Stream *ResponseStream `json:"stream"` // if the response body is a ReadableStream, Stream will be non-nil.
}
type ResponseSerializedData struct {
@@ -182,6 +185,13 @@ type ResponseProxy struct {
Headers map[string][]string `json:"headers"` // request headers forwarded to the target
}
+// ResponseStream 对应插件处理函数返回的 response.body.stream:Stream 字段在 handleHttpRequest 里从脚本对象上
+// 单独取出赋值,不经过 JSON 编解码(ReadableStream 实例无法序列化),其余字段走正常的 JSON 转换。
+type ResponseStream struct {
+ ContentType string `json:"contentType"` // e.g. "text/event-stream"
+ Stream *goja.Object `json:"-"` // the ReadableStream<Uint8Array | ArrayBuffer | string> providing the response body
+}
+
// isSseRequest checks if the incoming HTTP request is a Server-Sent Events (SSE) request by inspecting the "Accept" header for the "text/event-stream" value.
func isSseRequest(c *gin.Context) bool {
return c.GetHeader(SseHeaderAcceptName) == SseHeaderAcceptValue
@@ -300,6 +310,125 @@ func writeProxyResponse(c *gin.Context, proxy *ResponseProxy) {
}
}
+// streamChunk 是从拉取一块数据的 Go 回调传给响应写入循环的一条消息:done 为真时表示流已经结束(err 非 nil
+// 说明是异常结束),否则 data 是这一块要写入响应体的字节。
+type streamChunk struct {
+ data []byte
+ done bool
+ err error
+}
+
+// writeStreamResponse 把插件处理函数返回的 response.body.stream 逐块写入 HTTP 响应,statusCode 是插件在
+// HttpResponse.statusCode 中指定的状态码(而不是固定 200):写入循环每写完一块、Flush 之后才向事件循环请求
+// 下一块,不提前拉取——这是背压的关键,避免插件在没有人消费数据的情况下把响应体生产得远远超前;一块数据的
+// 请求与到达都经由 p.worker.Run 异步完成,不占用事件循环线程等待任何 I/O,不会因为写入循环暂时写不出数据
+// (例如客户端读取缓慢)而卡住插件的其它脚本任务。chunk 必须是 BufferSource(ArrayBuffer 或其视图,如
+// Uint8Array)或字符串(按 UTF-8 写入),和 siyuan.client.fetch 的 response.body 用同一套鸭子类型。客户端
+// 提前断开连接时取消 reader,不再继续向一个没有人读的响应体生产数据。
+func (p *KernelPlugin) writeStreamResponse(c *gin.Context, statusCode int, response *ResponseStream) {
+ c.Writer.WriteHeader(statusCode)
+ if response.ContentType != "" {
+ c.Header("Content-Type", response.ContentType)
+ }
+
+ chunks := make(chan streamChunk, 1)
+ var consumer *streams.StreamConsumer
+
+ // pullNext 在事件循环线程上请求下一块数据,调用方必须等上一次请求的结果(通过 chunks 收到)之后才能
+ // 再次调用,不能连续发起多次拉取。
+ pullNext := func() {
+ if runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ consumer.PullOnVMThread(func(chunk goja.Value) error {
+ data, convertErr := streamChunkBytes(p, rt, chunk)
+ if convertErr != nil {
+ return convertErr
+ }
+ select {
+ case chunks <- streamChunk{data: data}:
+ case <-c.Request.Context().Done():
+ case <-p.context.Done():
+ }
+ return nil
+ }, func(doneErr error) {
+ select {
+ case chunks <- streamChunk{done: true, err: doneErr}:
+ case <-c.Request.Context().Done():
+ case <-p.context.Done():
+ }
+ })
+ return nil, nil
+ }, nil); runErr != nil {
+ select {
+ case chunks <- streamChunk{done: true, err: runErr}:
+ case <-c.Request.Context().Done():
+ case <-p.context.Done():
+ }
+ }
+ }
+
+ _, runErr := p.worker.RunSync(func(rt *goja.Runtime) (_ any, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic while starting response stream: %v", r)
+ }
+ }()
+ consumer, err = p.streamsHost.OpenReadableStreamConsumer(response.Stream)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] start response stream: %v", p.Name, runErr)
+ return
+ }
+
+ // cancelConsumer 让 reader 取消,不必等它自然读完,避免插件继续为无人读取的响应体生产数据;
+ // 写入循环的每一条退出路径(流自然结束之外)都要走这里,不止客户端断开连接那一条。
+ cancelConsumer := func(reason string) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ consumer.CancelOnVMThread(rt.NewTypeError(reason))
+ return nil, nil
+ }, nil)
+ }
+
+ pullNext()
+ for {
+ select {
+ case chunk := <-chunks:
+ if chunk.done {
+ if chunk.err != nil {
+ logging.LogWarnf("[plugin:%s] response stream ended with an error: %s", p.Name, chunk.err)
+ }
+ return
+ }
+ if _, writeErr := c.Writer.Write(chunk.data); writeErr != nil {
+ logging.LogWarnf("[plugin:%s] write response stream chunk failed: %s", p.Name, writeErr)
+ cancelConsumer("failed to write the response stream chunk")
+ return
+ }
+ c.Writer.Flush()
+ pullNext()
+ case <-c.Request.Context().Done():
+ cancelConsumer("client disconnected")
+ return
+ case <-p.context.Done():
+ cancelConsumer("plugin stopped")
+ return
+ }
+ }
+}
+
+// streamChunkBytes 把 response.body.stream 的一个 chunk 转换为要写入响应体的字节:接受 ArrayBuffer、
+// ArrayBuffer 视图(如 Uint8Array)或字符串(按 UTF-8 编码),与 siyuan.client.fetch 的 response.body
+// 的 chunk 形态保持一致;返回的切片是独立拷贝,不与引擎内存共享。
+func streamChunkBytes(p *KernelPlugin, rt *goja.Runtime, chunk goja.Value) ([]byte, error) {
+ if object, ok := chunk.(*goja.Object); ok && p.formDataHost.IsBufferSource(chunk) {
+ return bytes.Clone(p.formDataHost.BufferSourceBytes(rt, object)), nil
+ }
+ if goja.IsString(chunk) {
+ return []byte(chunk.String()), nil
+ }
+ return nil, fmt.Errorf("stream chunk must be a BufferSource or a string, got %T", chunk.Export())
+}
+
func parseRequest(c *gin.Context) (request *Request, err error) {
var form *RequestForm
var data *[]byte
diff --git a/kernel/plugin/service_contract.go b/kernel/plugin/service_contract.go
index 291715816a..19563d0876 100644
--- a/kernel/plugin/service_contract.go
+++ b/kernel/plugin/service_contract.go
@@ -76,10 +76,10 @@ func preparePluginService(c *gin.Context, scope AccessScope) apicontract.Respons
if response == nil {
return pluginServiceStream(apicontract.PluginServiceEmpty, 500, func() { c.Status(500) })
}
- return pluginServiceHTTPResponse(c, name, response)
+ return pluginServiceHTTPResponse(p, c, name, response)
}
-func pluginServiceHTTPResponse(c *gin.Context, name string, response *HttpResponse) apicontract.Response[apicontract.PluginServiceContent] {
+func pluginServiceHTTPResponse(p *KernelPlugin, c *gin.Context, name string, response *HttpResponse) apicontract.Response[apicontract.PluginServiceContent] {
// 插件头的重复值依次覆盖,Cookie 则逐个追加。
for headerKey, headerValues := range response.Headers {
@@ -144,6 +144,8 @@ func pluginServiceHTTPResponse(c *gin.Context, name string, response *HttpRespon
return pluginServiceStream(apicontract.PluginServiceRedirect, response.StatusCode, func() { c.Redirect(response.StatusCode, response.Body.Redirect.Location) })
} else if response.Body.Proxy != nil {
return pluginServiceStream(apicontract.PluginServiceProxy, 200, func() { writeProxyResponse(c, response.Body.Proxy) })
+ } else if response.Body.Stream != nil {
+ return pluginServiceStream(apicontract.PluginServiceStream, response.StatusCode, func() { p.writeStreamResponse(c, response.StatusCode, response.Body.Stream) })
}
}
return pluginServiceStream(apicontract.PluginServiceEmpty, response.StatusCode, func() { c.Status(response.StatusCode) })
diff --git a/kernel/plugin/service_contract_test.go b/kernel/plugin/service_contract_test.go
index 8f681d818d..ac0d1f25a9 100644
--- a/kernel/plugin/service_contract_test.go
+++ b/kernel/plugin/service_contract_test.go
@@ -19,6 +19,8 @@ import (
"github.com/gorilla/websocket"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/plugin/formdata"
+ "github.com/siyuan-note/siyuan/kernel/plugin/streams"
"github.com/siyuan-note/siyuan/kernel/util"
"google.golang.org/protobuf/types/known/wrapperspb"
)
@@ -51,6 +53,8 @@ func newServiceTestPlugin(t *testing.T, script string) (*KernelPlugin, context.C
var runErr error
loop.Run(func(rt *goja.Runtime) {
rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ p.formDataHost = formdata.Enable(rt)
+ p.streamsHost = streams.Enable(rt)
_, runErr = rt.RunString(script)
})
if runErr != nil {
@@ -96,7 +100,7 @@ func TestPluginServiceHTTPBranches(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
engine := gin.New()
engine.GET("/plugin/private/:name/*path", func(c *gin.Context) {
- serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: 200, Headers: map[string][]string{"X-Value": {"first", "last"}}, Cookies: []*http.Cookie{{Name: "a", Value: "1"}, {Name: "b", Value: "2"}}, Body: tt.body}))
+ serviceTestWrite(c, pluginServiceHTTPResponse(nil, c, "test", &HttpResponse{StatusCode: 200, Headers: map[string][]string{"X-Value": {"first", "last"}}, Cookies: []*http.Cookie{{Name: "a", Value: "1"}, {Name: "b", Value: "2"}}, Body: tt.body}))
})
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/test/value?callback=callback", nil))
@@ -177,7 +181,7 @@ func TestPluginServiceProxyAndFiles(t *testing.T) {
defer upstream.Close()
engine := gin.New()
engine.Any("/plugin/private/:name/*path", func(c *gin.Context) {
- serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: 202, Body: &ResponseBody{Proxy: &ResponseProxy{URL: upstream.URL}}}))
+ serviceTestWrite(c, pluginServiceHTTPResponse(nil, c, "test", &HttpResponse{StatusCode: 202, Body: &ResponseBody{Proxy: &ResponseProxy{URL: upstream.URL}}}))
})
for _, method := range []string{"GET", "HEAD", "POST"} {
recorder := httptest.NewRecorder()
@@ -218,7 +222,7 @@ func TestPluginServiceFileRangesRedirectAndPriority(t *testing.T) {
status = 200
body = &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeJSON, Data: 1}, Raw: &ResponseRawData{Data: []byte("ignored")}}
}
- serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: status, Body: body}))
+ serviceTestWrite(c, pluginServiceHTTPResponse(nil, c, "test", &HttpResponse{StatusCode: status, Body: body}))
})
request := httptest.NewRequest("GET", "/plugin/private/test/range", nil)
request.Header.Set("Range", "bytes=2-4")
@@ -294,6 +298,243 @@ func TestPluginServiceStreamingLifecycle(t *testing.T) {
}
}
+// TestPluginServiceStreamResponse 验证 response.body.stream:第一块数据到达时响应已经在传输(没有等整个流
+// 读完才一次性写出),第二块要等插件自己(通过一个暴露给脚本的 Promise)决定产出才会出现。
+func TestPluginServiceStreamResponse(t *testing.T) {
+ p, cancel := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{http:{handler:(r)=>{
+ let pulled = false;
+ const stream = new ReadableStream({
+ start(controller) { controller.enqueue(new Uint8Array([102,105,114,115,116,45])); },
+ pull(controller) {
+ if (!pulled) { pulled = true; return; }
+ return __secondChunkReady().then(() => {
+ controller.enqueue(new Uint8Array([115,101,99,111,110,100]));
+ controller.close();
+ });
+ },
+ });
+ return {statusCode: 200, headers: {"X-Stream": ["yes"]}, body: {stream: {contentType: "text/plain", stream}}};
+ }}}}};`)
+ defer cancel()
+
+ var resolveSecondChunk func(any) error
+ if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ return nil, rt.Set("__secondChunkReady", func(goja.FunctionCall) goja.Value {
+ promise, resolve, _ := rt.NewPromise()
+ resolveSecondChunk = resolve
+ return rt.ToValue(promise)
+ })
+ }); err != nil {
+ t.Fatalf("expose __secondChunkReady: %v", err)
+ }
+
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+
+ response, err := http.Get(server.URL + "/plugin/private/" + p.Name + "/chunks")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ if response.StatusCode != 200 || response.Header.Get("X-Stream") != "yes" || response.Header.Get("Content-Type") != "text/plain" {
+ t.Fatalf("stream response headers changed: %d %v", response.StatusCode, response.Header)
+ }
+
+ first := make([]byte, 6)
+ if _, err = io.ReadFull(response.Body, first); err != nil || string(first) != "first-" {
+ t.Fatalf("first chunk changed: %q %v", first, err)
+ }
+
+ // 这时候第二块还没有被放行;用一个短超时确认连接仍然卡在第一块之后,证明不是整体缓冲后一次性写出的。
+ readSecond := make(chan []byte, 1)
+ go func() {
+ buf := make([]byte, 6)
+ if _, readErr := io.ReadFull(response.Body, buf); readErr == nil {
+ readSecond <- buf
+ }
+ }()
+ select {
+ case <-readSecond:
+ t.Fatal("second chunk arrived before the plugin produced it")
+ case <-time.After(100 * time.Millisecond):
+ }
+
+ if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ return nil, resolveSecondChunk(goja.Undefined())
+ }); err != nil {
+ t.Fatalf("resolve __secondChunkReady: %v", err)
+ }
+
+ select {
+ case second := <-readSecond:
+ if string(second) != "second" {
+ t.Fatalf("second chunk changed: %q", second)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("timed out waiting for the second chunk after it was produced")
+ }
+
+ rest, err := io.ReadAll(response.Body)
+ if err != nil || len(rest) != 0 {
+ t.Fatalf("stream response did not end after close(): %q %v", rest, err)
+ }
+}
+
+// serviceTestEval 在插件的事件循环上求值 script 并导出结果;3 秒内没有完成说明事件循环被阻塞。
+func serviceTestEval(t *testing.T, p *KernelPlugin, script string) any {
+ t.Helper()
+ result := make(chan any, 1)
+ go func() {
+ value, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ value, err := rt.RunString(script)
+ if err != nil {
+ return nil, err
+ }
+ return value.Export(), nil
+ })
+ if err != nil {
+ value = err
+ }
+ result <- value
+ }()
+ select {
+ case value := <-result:
+ if err, ok := value.(error); ok {
+ t.Fatalf("evaluate %q: %v", script, err)
+ }
+ return value
+ case <-time.After(3 * time.Second):
+ t.Fatalf("plugin event loop did not respond while evaluating %q", script)
+ }
+ return nil
+}
+
+// TestPluginServiceStreamResponseQueuedChunksAndStatus 验证插件在 start() 中一次性入队多块数据时,响应既不会卡住
+// 请求,也不会卡住插件的事件循环,并且使用插件指定的状态码,没有任何数据块的空流也不例外。
+func TestPluginServiceStreamResponseQueuedChunksAndStatus(t *testing.T) {
+ p, cancel := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{http:{handler:(r)=>{
+ const count = Number(r.context.path.slice(1));
+ const stream = new ReadableStream({
+ start(controller) {
+ for (let i = 0; i < count; i++) controller.enqueue(new Uint8Array([48 + i]));
+ controller.close();
+ },
+ });
+ return {statusCode: 201, body: {stream: {contentType: "text/plain", stream}}};
+ }}}}};`)
+ defer cancel()
+
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ client := &http.Client{Timeout: 5 * time.Second}
+
+ for _, tt := range []struct{ path, want string }{{"/8", "01234567"}, {"/0", ""}} {
+ response, err := client.Get(server.URL + "/plugin/private/" + p.Name + tt.path)
+ if err != nil {
+ t.Fatalf("GET %s: %v", tt.path, err)
+ }
+ data, err := io.ReadAll(response.Body)
+ response.Body.Close()
+ if err != nil || response.StatusCode != http.StatusCreated || string(data) != tt.want {
+ t.Fatalf("GET %s = %d %q %v, want %d %q", tt.path, response.StatusCode, data, err, http.StatusCreated, tt.want)
+ }
+ serviceTestEval(t, p, "0")
+ }
+}
+
+// TestPluginServiceStreamResponseBackpressure 验证客户端不读取响应体时,内核只按写出进度向流拉取数据,插件的
+// 事件循环保持可用;客户端断开连接后流被取消。每块 1 MiB,写满连接缓冲区后写出被阻塞,拉取次数随之停止增长。
+func TestPluginServiceStreamResponseBackpressure(t *testing.T) {
+ p, cancel := newServiceTestPlugin(t, `globalThis.__pulls = 0; globalThis.__cancelled = false;
+ globalThis.siyuan={server:{private:{http:{handler:()=>({statusCode: 200, body: {stream: {stream: new ReadableStream({
+ pull(controller) { globalThis.__pulls++; controller.enqueue(new Uint8Array(1 << 20)); },
+ cancel() { globalThis.__cancelled = true; },
+ })}}})}}}};`)
+ defer cancel()
+
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ client := &http.Client{Timeout: 5 * time.Second}
+
+ response, err := client.Get(server.URL + "/plugin/private/" + p.Name + "/endless")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ pulls := func() int64 { return serviceTestEval(t, p, "globalThis.__pulls").(int64) }
+ deadline := time.Now().Add(3 * time.Second)
+ previous := pulls()
+ for {
+ time.Sleep(200 * time.Millisecond)
+ current := pulls()
+ if current == previous {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("stream kept being pulled while the client was not reading: %d pulls", current)
+ }
+ previous = current
+ }
+ if previous > 64 {
+ t.Fatalf("stream was pulled far ahead of the client: %d pulls", previous)
+ }
+
+ response.Body.Close()
+ for !serviceTestEval(t, p, "globalThis.__cancelled").(bool) {
+ if time.Now().After(deadline.Add(3 * time.Second)) {
+ t.Fatal("stream was not cancelled after the client disconnected")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// 插件上下文取消后,等待下一块数据的流式请求必须退出,不依赖客户端断开连接。
+func TestPluginServiceStreamResponsePluginStopped(t *testing.T) {
+ p, cancel := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{http:{handler:()=>({
+ statusCode: 200,
+ body: {stream: {stream: new ReadableStream({
+ start(c) { c.enqueue("ready"); },
+ pull() { return new Promise(() => {}); },
+ }, {highWaterMark: 0})}},
+ })}}}};`)
+ defer cancel()
+
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ client := &http.Client{Timeout: 5 * time.Second}
+ response, err := client.Get(server.URL + "/plugin/private/" + p.Name + "/pending")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ first := make([]byte, 5)
+ if _, err = io.ReadFull(response.Body, first); err != nil || string(first) != "ready" {
+ t.Fatalf("initial chunk = %q %v", first, err)
+ }
+ finished := make(chan error, 1)
+ go func() {
+ _, readErr := io.Copy(io.Discard, response.Body)
+ finished <- readErr
+ }()
+ cancel()
+ select {
+ case err = <-finished:
+ if err != nil {
+ t.Fatalf("response did not end cleanly: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("response remained open after the plugin stopped")
+ }
+}
+
// TestPluginServiceFileConfinedToWorkspace 校验插件私有服务只能服务工作空间内的文件。
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-phmw-4rgv-r4xv
func TestPluginServiceFileConfinedToWorkspace(t *testing.T) {
@@ -313,7 +554,7 @@ func TestPluginServiceFileConfinedToWorkspace(t *testing.T) {
request := func(path string) *httptest.ResponseRecorder {
engine := gin.New()
engine.Any("/plugin/private/:name/*path", func(c *gin.Context) {
- serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{
+ serviceTestWrite(c, pluginServiceHTTPResponse(nil, c, "test", &HttpResponse{
StatusCode: 200,
Body: &ResponseBody{File: &ResponseFile{Path: path}},
}))
diff --git a/kernel/plugin/streams/bridge.go b/kernel/plugin/streams/bridge.go
new file mode 100644
index 0000000000..17d1e30409
--- /dev/null
+++ b/kernel/plugin/streams/bridge.go
@@ -0,0 +1,121 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+)
+
+// StreamConsumer 是 Go 侧消费一个 JS ReadableStream 的句柄(与 NewReadableStream 相反的桥接方向),
+// 由 OpenReadableStreamConsumer 创建,供 kernel/plugin 把插件返回的流写成 HTTP 响应等场景使用。调用方按
+// 自己的节奏(例如每写完一块、Flush 之后)调用 PullOnVMThread 请求下一块,而不是由本包自行连续调用
+// reader.read():这是实现背压的关键——如果本包在 onChunk 回调返回后立即发起下一次 read(),底层 pull
+// 算法会在没有人真正消费数据的情况下被反复调用,使插件远远跑在 Go 侧消费进度之前。PullOnVMThread 与
+// CancelOnVMThread 都必须在 runtime 所在的事件循环线程上调用。
+type StreamConsumer struct {
+ rt *goja.Runtime
+ reader *goja.Object
+ read goja.Callable
+ cancelFn goja.Callable
+ finished bool
+}
+
+// OpenReadableStreamConsumer 获取 stream 的 reader,不发起任何读取;返回的 consumer 由调用方通过
+// PullOnVMThread 按需驱动。stream 必须是本 Host 构造的 ReadableStream,否则返回错误。
+func (h *Host) OpenReadableStreamConsumer(stream *goja.Object) (*StreamConsumer, error) {
+ rt := h.rt
+ if !h.IsReadableStream(stream) {
+ return nil, fmt.Errorf("OpenReadableStreamConsumer: value is not a ReadableStream")
+ }
+
+ getReader, ok := goja.AssertFunction(stream.Get("getReader"))
+ if !ok {
+ return nil, fmt.Errorf("OpenReadableStreamConsumer: getReader is not a function")
+ }
+ readerValue, err := getReader(stream)
+ if err != nil {
+ return nil, err
+ }
+ reader := readerValue.ToObject(rt)
+ read, ok := goja.AssertFunction(reader.Get("read"))
+ if !ok {
+ return nil, fmt.Errorf("OpenReadableStreamConsumer: reader.read is not a function")
+ }
+ cancelFn, _ := goja.AssertFunction(reader.Get("cancel"))
+
+ return &StreamConsumer{rt: rt, reader: reader, read: read, cancelFn: cancelFn}, nil
+}
+
+// PullOnVMThread 请求下一块数据:调用一次 reader.read(),并在其 Promise 落定后调用一次 onChunk(有数据时)
+// 或 onDone(流结束/出错,或本次 read() 调用本身失败时,nil 表示正常结束)。已经调用过 onDone 之后再调用
+// PullOnVMThread 是空操作。onChunk 返回非 nil 错误会取消底层 reader 并以该错误调用 onDone,不再继续读取;
+// 调用方必须等 onChunk/onDone 被调用之后才能再次调用 PullOnVMThread,不能提前发起下一次拉取,这正是背压
+// 得以生效的地方。onChunk/onDone 的实际调用可能在本次调用返回之后才发生,取决于 read() 的 Promise 何时
+// 落定(见包文档),不保证同步完成。
+func (c *StreamConsumer) PullOnVMThread(onChunk func(chunk goja.Value) error, onDone func(err error)) {
+ if c.finished {
+ return
+ }
+ result, callErr := c.read(c.reader)
+ if callErr != nil {
+ c.finished = true
+ onDone(callErr)
+ return
+ }
+ awaitResult(c.rt, result, func(value goja.Value) {
+ if c.finished {
+ return
+ }
+ object := value.ToObject(c.rt)
+ if done := object.Get("done"); done != nil && done.ToBoolean() {
+ c.finished = true
+ onDone(nil)
+ return
+ }
+ if chunkErr := onChunk(object.Get("value")); chunkErr != nil {
+ c.cancel(c.rt.NewGoError(chunkErr))
+ c.finished = true
+ onDone(chunkErr)
+ return
+ }
+ }, func(reason goja.Value) {
+ if c.finished {
+ return
+ }
+ c.finished = true
+ onDone(fmt.Errorf("%s", reason))
+ })
+}
+
+// CancelOnVMThread 提前终止消费(例如客户端提前断开连接);多次调用是安全的,流已经结束/出错之后调用是空操作。
+func (c *StreamConsumer) CancelOnVMThread(reason goja.Value) {
+ if c.finished {
+ return
+ }
+ c.cancel(reason)
+}
+
+func (c *StreamConsumer) cancel(reason goja.Value) {
+ if c.cancelFn == nil {
+ return
+ }
+ if _, err := c.cancelFn(c.reader, reason); err != nil {
+ panic(err)
+ }
+}
diff --git a/kernel/plugin/streams/doc.go b/kernel/plugin/streams/doc.go
new file mode 100644
index 0000000000..bc822f8e5b
--- /dev/null
+++ b/kernel/plugin/streams/doc.go
@@ -0,0 +1,36 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// Package streams 为 goja 运行时原生实现 WHATWG Streams Standard 的默认(非字节流)子集:ReadableStream、
+// WritableStream、TransformStream 及其默认 controller/reader/writer,以及 CountQueuingStrategy 与
+// ByteLengthQueuingStrategy。不实现字节流相关接口(ReadableByteStreamController、
+// ReadableStreamBYOBReader、ReadableStreamBYOBRequest),插件脚本中 getReader({mode: "byob"}) 会报错。
+//
+// 本包不依赖 kernel/plugin 包,避免循环依赖;Enable 的调用方(kernel/plugin)反过来依赖本包。与仓库里
+// Blob/FormData/AbortController 的既有写法一致:实例用 rt.NewDynamicObject 包装 Go 状态,方法与访问器
+// 定义在每个 Host 构造时新建的共享原型上,不依赖 goja 的结构体字段名反射映射。
+//
+// Go 侧桥接(供 kernel/plugin 的 fetch 响应体、HTTP 服务流式响应等场景使用)见 Host.NewReadableStream/
+// NewWritableStream/NewTransformStream:Go 驱动的数据源把 start/pull/write/close/cancel/abort 实现为普通
+// Go 函数,返回值按与 JS 版本相同的方式经由 awaitResult 处理,真正跨线程的调度(开 goroutine 读取、通过
+// 事件循环的 RunOnLoop 回到 VM 线程)由调用方自己完成,本包只提供"已经在 VM 线程内"可以安全调用的操作。
+//
+// # 参考
+//
+// 实现参考 WHATWG Streams Standard(https://streams.spec.whatwg.org/)的算法步骤,但不是逐字移植:
+// 本包是独立编写的 Go 实现,仅在算法顺序上贴合规范,用以避免 Promise 同步 settle 时的重入隐患(规范算法
+// 本身就是按"先更新内部状态、再触发回调"的顺序写的)。
+package streams
diff --git a/kernel/plugin/streams/module.go b/kernel/plugin/streams/module.go
new file mode 100644
index 0000000000..b8dc700097
--- /dev/null
+++ b/kernel/plugin/streams/module.go
@@ -0,0 +1,75 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+)
+
+// Host 捕获 Enable 构造出的全部构造函数、原型,供同一 runtime 内后续创建实例、识别实例类型,以及 kernel/plugin
+// 的 Go 桥接代码(bridge.go)使用。调用方必须在同一个 runtime 上保留并复用 Enable 返回的 Host,不要重复调用
+// Enable。
+type Host struct {
+ rt *goja.Runtime
+
+ readableStreamPrototype *goja.Object
+ readableReaderProto *goja.Object
+ readableControllerProto *goja.Object
+
+ writableStreamPrototype *goja.Object
+ writableWriterProto *goja.Object
+ writableControllerProto *goja.Object
+
+ transformStreamPrototype *goja.Object
+ transformControllerProto *goja.Object
+}
+
+// Enable 把 ReadableStream、WritableStream、TransformStream 及其默认 controller/reader/writer,以及
+// CountQueuingStrategy、ByteLengthQueuingStrategy 挂到 runtime 的 globalThis,调用方式与本沙箱其它 Web API
+// 一致,失败时 panic。返回的 Host 供同一 runtime 内的 Go 桥接代码使用(见 bridge.go),调用方应保留它。
+func Enable(rt *goja.Runtime) (h *Host) {
+ defer func() {
+ if r := recover(); r != nil {
+ panic(fmt.Errorf("streams.Enable: %v", r))
+ }
+ }()
+
+ h = &Host{rt: rt}
+ h.readableControllerProto = newReadableControllerPrototype(h)
+ h.readableReaderProto = newReadableReaderPrototype(h)
+ h.readableStreamPrototype = newReadableStreamPrototype(h)
+ readableStreamCtor := h.newReadableStreamConstructor()
+ must(readableStreamCtor.Set("from", rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ return h.readableStreamFrom(call.Argument(0))
+ })))
+ must(rt.Set("ReadableStream", readableStreamCtor))
+
+ h.writableControllerProto = newWritableControllerPrototype(h)
+ h.writableWriterProto = newWritableWriterPrototype(h)
+ h.writableStreamPrototype = newWritableStreamPrototype(h)
+ must(rt.Set("WritableStream", h.newWritableStreamConstructor()))
+
+ h.transformControllerProto = newTransformControllerPrototype(h)
+ h.transformStreamPrototype = newTransformStreamPrototype(h)
+ must(rt.Set("TransformStream", h.newTransformStreamConstructor()))
+
+ must(rt.Set("CountQueuingStrategy", newCountQueuingStrategyConstructor(h)))
+ must(rt.Set("ByteLengthQueuingStrategy", newByteLengthQueuingStrategyConstructor(h)))
+ return
+}
diff --git a/kernel/plugin/streams/pipe.go b/kernel/plugin/streams/pipe.go
new file mode 100644
index 0000000000..417ef0fb87
--- /dev/null
+++ b/kernel/plugin/streams/pipe.go
@@ -0,0 +1,419 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import "github.com/dop251/goja"
+
+// pipeOptions 对应 StreamPipeOptions:pipeTo/pipeThrough 的第二个参数。
+type pipeOptions struct {
+ preventClose, preventAbort, preventCancel bool
+ signal goja.Value // 实现 .aborted / .addEventListener("abort", ...) 的任意对象,鸭子类型
+}
+
+func pipeOptionsOf(rt *goja.Runtime, value goja.Value) pipeOptions {
+ var options pipeOptions
+ if !isJsValueNotNull(value) {
+ return options
+ }
+ object, ok := value.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "pipeTo: options can't be converted to a dictionary"))
+ }
+ boolMember := func(name string) bool {
+ v := object.Get(name)
+ return v != nil && !goja.IsUndefined(v) && v.ToBoolean()
+ }
+ options.preventClose = boolMember("preventClose")
+ options.preventAbort = boolMember("preventAbort")
+ options.preventCancel = boolMember("preventCancel")
+ if signal := object.Get("signal"); isJsValueNotNull(signal) {
+ options.signal = signal
+ }
+ return options
+}
+
+// pipeSignalAborted/pipeSignalAddAbortListener 用鸭子类型读取 signal 参数:只要求有 aborted 属性与
+// addEventListener 方法,不要求是本包或 kernel/plugin/abort 的 AbortSignal 实例,这样宿主注入的任意实现都能用。
+func pipeSignalAborted(signal goja.Value) bool {
+ object, ok := signal.(*goja.Object)
+ if !ok {
+ return false
+ }
+ aborted := object.Get("aborted")
+ return aborted != nil && aborted.ToBoolean()
+}
+
+func pipeSignalReason(rt *goja.Runtime, signal goja.Value) goja.Value {
+ object, ok := signal.(*goja.Object)
+ if !ok {
+ return typeErrorf(rt, "The operation was aborted")
+ }
+ if reason := object.Get("reason"); isJsValueNotNull(reason) {
+ return reason
+ }
+ return typeErrorf(rt, "The operation was aborted")
+}
+
+func pipeSignalOnAbort(rt *goja.Runtime, signal goja.Value, fn func()) {
+ object, ok := signal.(*goja.Object)
+ if !ok {
+ return
+ }
+ addEventListener, ok := goja.AssertFunction(object.Get("addEventListener"))
+ if !ok {
+ return
+ }
+ if _, err := addEventListener(object, rt.ToValue("abort"), rt.ToValue(func(goja.FunctionCall) goja.Value {
+ fn()
+ return goja.Undefined()
+ })); err != nil {
+ panic(err)
+ }
+}
+
+// readableStreamPipeTo 对应 ReadableStream.prototype.pipeTo + ReadableStreamPipeTo:把 source 的每个 chunk
+// 写入 dest,直至 source 关闭/出错或 dest 关闭/出错或 signal 中止;按 preventClose/preventAbort/preventCancel
+// 决定对侧是否跟随收尾。简化之处:源与目的地几乎同时失败时按"先到者生效"处理,不追加规范里针对该竞态的额外
+// 分支(真实场景里两侧几乎不会在同一个微任务内同时失败)。
+func readableStreamPipeTo(h *Host, source *readableState, destValue, optionsValue goja.Value) goja.Value {
+ rt := h.rt
+ dest, ok := writableStateOf(destValue)
+ if !ok {
+ return newRejectedPromise(rt, typeErrorf(rt, "ReadableStream.prototype.pipeTo's argument must be a WritableStream"))
+ }
+ if isReadableStreamLocked(source) || isWritableStreamLocked(dest) {
+ return newRejectedPromise(rt, typeErrorf(rt, "ReadableStream.prototype.pipeTo cannot be used on a locked stream"))
+ }
+ options := pipeOptionsOf(rt, optionsValue)
+
+ reader := acquireReadableStreamDefaultReader(h, source)
+ writer := acquireWritableStreamDefaultWriter(h, dest)
+ source.disturbed = true
+
+ // 对应规范"If destination starts out closed or closing":开始管道时目的地已经关闭或正在关闭,即使源流
+ // 没有任何数据也要立即以 TypeError 收尾,不能一直等待源数据。
+ destStartedClosed := dest.status == writableClosed || writableCloseQueuedOrInFlight(dest)
+
+ promise, resolve, reject := rt.NewPromise()
+ var shuttingDown bool
+ var currentWrite goja.Value
+ var reading, sourceClosed bool
+
+ finalized := false
+ finalize := func(ok bool, reason goja.Value) {
+ if finalized {
+ return
+ }
+ finalized = true
+ shuttingDown = true
+ writableWriterRelease(writer)
+ readableStreamReaderGenericRelease(h, reader)
+ if ok {
+ must0(resolve(goja.Undefined()))
+ } else {
+ must0(reject(reason))
+ }
+ }
+
+ var shutdown func(reason goja.Value, ok bool)
+ shutdown = func(reason goja.Value, ok bool) {
+ if shuttingDown {
+ return
+ }
+ shuttingDown = true
+
+ complete := func() {
+ actions := []func() goja.Value{}
+ if ok {
+ if !options.preventClose {
+ actions = append(actions, func() goja.Value { return writableStreamClose(h, dest) })
+ }
+ } else {
+ if !options.preventAbort && dest.status == writableWritable {
+ actions = append(actions, func() goja.Value { return writableStreamAbort(h, dest, reason) })
+ }
+ if !options.preventCancel && source.status == statusReadable {
+ actions = append(actions, func() goja.Value { return readableStreamCancel(h, source, reason) })
+ }
+ }
+ if len(actions) == 0 {
+ finalize(ok, reason)
+ return
+ }
+ remaining := len(actions)
+ var firstErr goja.Value
+ settleOne := func(err goja.Value) {
+ remaining--
+ if err != nil && firstErr == nil {
+ firstErr = err
+ }
+ if remaining == 0 {
+ if firstErr != nil {
+ finalize(false, firstErr)
+ } else {
+ finalize(ok, reason)
+ }
+ }
+ }
+ for _, action := range actions {
+ awaitResult(rt, action(), func(goja.Value) { settleOne(nil) }, func(r goja.Value) { settleOne(r) })
+ }
+ }
+
+ // 写入按队列顺序完成,等待最后一次写入即可排空所有已提交的分块;收尾期间不再发起新的读取。
+ // 正常结束时写入失败要传递给调用方,错误收尾时保留先触发收尾的原因。
+ if currentWrite != nil && (ok || (dest.status == writableWritable && !writableCloseQueuedOrInFlight(dest))) {
+ awaitResult(rt, currentWrite, func(goja.Value) { complete() }, func(writeReason goja.Value) {
+ if ok {
+ ok = false
+ reason = writeReason
+ }
+ complete()
+ })
+ } else {
+ complete()
+ }
+ }
+
+ if destStartedClosed {
+ shutdown(typeErrorf(rt, "Cannot pipe to a writable stream that is closed or closing"), false)
+ return rt.ToValue(promise)
+ }
+
+ if options.signal != nil {
+ if pipeSignalAborted(options.signal) {
+ reason := pipeSignalReason(rt, options.signal)
+ shutdown(reason, false)
+ return rt.ToValue(promise)
+ }
+ pipeSignalOnAbort(rt, options.signal, func() {
+ shutdown(pipeSignalReason(rt, options.signal), false)
+ })
+ }
+
+ // 目的地出错必须立即触发收尾(对应规范"Errors must be propagated backward: if dest becomes errored"),
+ // 不能只等当前这一次 write() 的结果——此时管道可能正卡在等待源数据(reader.read() 未落定)或等待
+ // writer.ready 解除背压,这两种等待都不会主动去看 write() 的结果,若不单独监听会一直挂起。因为管道
+ // 持有 dest 唯一的 writer(acquireWritableStreamDefaultWriter 要求其未被锁定),writer.closed 不会
+ // 被管道之外的代码正常 resolve,所以只需处理它的拒绝分支;shutdown 本身是幂等的,重复调用是安全的。
+ awaitResult(rt, writer.closed.value(rt), func(goja.Value) {}, func(reason goja.Value) {
+ shutdown(reason, false)
+ })
+
+ // 源流的结束和错误独立于目的地的背压通知。最后一块出队时 closed 会先于 read() 完成,
+ // 因此有挂起读取时先让读取回调提交该分块,再开始正常收尾。
+ awaitResult(rt, reader.closed.value(rt), func(goja.Value) {
+ sourceClosed = true
+ if !reading {
+ shutdown(nil, true)
+ }
+ }, func(reason goja.Value) {
+ shutdown(reason, false)
+ })
+
+ var pump func()
+ pump = func() {
+ if shuttingDown {
+ return
+ }
+ if writer.ready.isPending() {
+ awaitResult(rt, writer.ready.value(rt), func(goja.Value) { pump() }, func(reason goja.Value) { shutdown(reason, false) })
+ return
+ }
+
+ readPromise, readResolve, readReject := rt.NewPromise()
+ reading = true
+ readableStreamDefaultReaderRead(h, reader, readRequest{resolve: readResolve, reject: readReject})
+ awaitResult(rt, rt.ToValue(readPromise), func(result goja.Value) {
+ reading = false
+ if shuttingDown {
+ return
+ }
+ resultObj := result.ToObject(rt)
+ if done := resultObj.Get("done"); done != nil && done.ToBoolean() {
+ shutdown(nil, true)
+ return
+ }
+ // 不等待这一次 write() 落定就继续循环:真正的节流由下一轮 writer.ready 的背压信号负责,
+ // 与规范"读取和写入独立并行推进"的描述一致。
+ currentWrite = writableWriterWrite(h, writer, resultObj.Get("value"))
+ awaitResult(rt, currentWrite, func(goja.Value) {}, func(reason goja.Value) { shutdown(reason, false) })
+ if sourceClosed {
+ shutdown(nil, true)
+ } else {
+ pump()
+ }
+ }, func(reason goja.Value) {
+ reading = false
+ shutdown(reason, false)
+ })
+ }
+ pump()
+
+ return rt.ToValue(promise)
+}
+
+// readableStreamPipeThrough 对应 ReadableStream.prototype.pipeThrough:把 source pipeTo 到 transform.writable,
+// 忽略结果 Promise(规范不把它暴露给调用方),返回 transform.readable。
+func readableStreamPipeThrough(h *Host, source *readableState, transformValue, optionsValue goja.Value) goja.Value {
+ rt := h.rt
+ transform, ok := transformStateOf(transformValue)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.prototype.pipeThrough's argument must be a TransformStream"))
+ }
+ if isReadableStreamLocked(source) {
+ panic(typeErrorf(rt, "ReadableStream.prototype.pipeThrough cannot be used on a locked stream"))
+ }
+ if isWritableStreamLocked(transform.writable) {
+ panic(typeErrorf(rt, "ReadableStream.prototype.pipeThrough's argument cannot be used on a locked stream"))
+ }
+ readableStreamPipeTo(h, source, transform.writable.self, optionsValue)
+ return transform.readable.self
+}
+
+// readableStreamTee 对应 ReadableStream.prototype.tee + ReadableStreamDefaultTee:返回两个共享同一数据源的
+// 新 ReadableStream;一侧的 pull 请求同时驱动两条分支入队,一侧 cancel 时若另一侧也已 cancel 才真正取消源。
+func readableStreamTee(h *Host, source *readableState) (branch1, branch2 *goja.Object) {
+ rt := h.rt
+ reader := acquireReadableStreamDefaultReader(h, source)
+
+ var reading, readAgain bool
+ var canceled1, canceled2 bool
+ var reason1, reason2 goja.Value
+ cancelPromise := newDeferred(rt)
+ var branch1Controller, branch2Controller *readableController
+
+ var pullAlgorithm func()
+ pullAlgorithm = func() {
+ if reading {
+ readAgain = true
+ return
+ }
+ reading = true
+ readPromise, resolve, reject := rt.NewPromise()
+ readableStreamDefaultReaderRead(h, reader, readRequest{resolve: resolve, reject: reject})
+ awaitResult(rt, rt.ToValue(readPromise), func(result goja.Value) {
+ reading = false
+ if readAgain {
+ readAgain = false
+ pullAlgorithm()
+ }
+ resultObj := result.ToObject(rt)
+ if done := resultObj.Get("done"); done != nil && done.ToBoolean() {
+ if !canceled1 {
+ readableControllerClose(h, branch1Controller)
+ }
+ if !canceled2 {
+ readableControllerClose(h, branch2Controller)
+ }
+ if !canceled1 || !canceled2 {
+ must0(cancelPromise.resolve(goja.Undefined()))
+ }
+ return
+ }
+ chunk := resultObj.Get("value")
+ if !canceled1 {
+ readableControllerEnqueue(h, branch1Controller, chunk)
+ }
+ if !canceled2 {
+ readableControllerEnqueue(h, branch2Controller, chunk)
+ }
+ }, func(reason goja.Value) {
+ reading = false
+ if !canceled1 {
+ readableControllerError(h, branch1Controller, reason)
+ }
+ if !canceled2 {
+ readableControllerError(h, branch2Controller, reason)
+ }
+ if !canceled1 || !canceled2 {
+ must0(cancelPromise.resolve(goja.Undefined()))
+ }
+ })
+ }
+
+ cancel1Algorithm := func(reason goja.Value) goja.Value {
+ canceled1 = true
+ reason1 = reason
+ if canceled2 {
+ must0(cancelPromise.resolve(readableStreamCancel(h, source, rt.NewArray(reason1, reason2))))
+ }
+ return cancelPromise.value(rt)
+ }
+ cancel2Algorithm := func(reason goja.Value) goja.Value {
+ canceled2 = true
+ reason2 = reason
+ if canceled1 {
+ must0(cancelPromise.resolve(readableStreamCancel(h, source, rt.NewArray(reason1, reason2))))
+ }
+ return cancelPromise.value(rt)
+ }
+
+ branch1Obj := h.NewReadableStream(nil, func(goja.Value) goja.Value { pullAlgorithm(); return nil },
+ cancel1Algorithm, 1, nil)
+ branch1State, _ := readableStateOf(branch1Obj)
+ branch1Controller = branch1State.controller
+
+ branch2Obj := h.NewReadableStream(nil, func(goja.Value) goja.Value { pullAlgorithm(); return nil },
+ cancel2Algorithm, 1, nil)
+ branch2State, _ := readableStateOf(branch2Obj)
+ branch2Controller = branch2State.controller
+
+ return branch1Obj, branch2Obj
+}
+
+// newReadableStreamAsyncIterator 对应 4.3.9 节的 Readable Stream Asynchronous Iterator:返回一个带 next()/
+// return() 方法、且自身可迭代([Symbol.for("Symbol.asyncIterator")] 返回自身)的对象。由于本沙箱固定的 goja
+// 版本没有原生 Symbol.asyncIterator,这个符号键同样退化为 Symbol.for("Symbol.asyncIterator"),脚本只能手动
+// 调用 next(),不能用 for-await 语法消费(该语法在这版 goja 下直接报语法错误)。
+func newReadableStreamAsyncIterator(h *Host, stream *readableState, preventCancel bool) *goja.Object {
+ rt := h.rt
+ reader := acquireReadableStreamDefaultReader(h, stream)
+
+ iterator := rt.NewObject()
+ defineMethod(rt, iterator, "next", 0, func(call goja.FunctionCall) goja.Value {
+ if reader.stream == nil {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot get the next iteration result once the reader has been released"))
+ }
+ promise, resolve, reject := rt.NewPromise()
+ readableStreamDefaultReaderRead(h, reader, readRequest{resolve: resolve, reject: reject})
+ return rt.ToValue(promise)
+ })
+ defineMethod(rt, iterator, "return", 1, func(call goja.FunctionCall) goja.Value {
+ value := call.Argument(0)
+ if reader.stream == nil {
+ return newResolvedPromiseResult(rt, value, true)
+ }
+ if !preventCancel {
+ cancelResult := readableStreamCancel(h, reader.stream, value)
+ readableStreamReaderGenericRelease(h, reader)
+ promise, resolve, reject := rt.NewPromise()
+ awaitResult(rt, cancelResult, func(goja.Value) {
+ result := rt.NewObject()
+ must(result.Set("value", value))
+ must(result.Set("done", rt.ToValue(true)))
+ must0(resolve(result))
+ }, func(reason goja.Value) { must0(reject(reason)) })
+ return rt.ToValue(promise)
+ }
+ readableStreamReaderGenericRelease(h, reader)
+ return newResolvedPromiseResult(rt, value, true)
+ })
+ must(iterator.DefineDataPropertySymbol(asyncIteratorSymbol(rt), rt.ToValue(func(goja.FunctionCall) goja.Value { return iterator }),
+ goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return iterator
+}
diff --git a/kernel/plugin/streams/promise.go b/kernel/plugin/streams/promise.go
new file mode 100644
index 0000000000..17a62fa051
--- /dev/null
+++ b/kernel/plugin/streams/promise.go
@@ -0,0 +1,107 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import "github.com/dop251/goja"
+
+// deferred 包装 rt.NewPromise() 返回的三元组,供需要重复创建、随时 resolve/reject 的内部 Promise
+// (如 reader/writer 的 closed、ready)使用。
+type deferred struct {
+ promise *goja.Promise
+ resolve func(any) error
+ reject func(any) error
+}
+
+func newDeferred(rt *goja.Runtime) deferred {
+ p, resolve, reject := rt.NewPromise()
+ return deferred{promise: p, resolve: resolve, reject: reject}
+}
+
+// value 返回可暴露给脚本的 Promise 值。
+func (d deferred) value(rt *goja.Runtime) goja.Value { return rt.ToValue(d.promise) }
+
+// isPending 返回该 Promise 当前是否仍处于 pending 状态。
+func (d deferred) isPending() bool { return d.promise.State() == goja.PromiseStatePending }
+
+// newResolvedPromise 返回一个已经以 value 兑定的 Promise 值。
+func newResolvedPromise(rt *goja.Runtime, value goja.Value) goja.Value {
+ p, resolve, _ := rt.NewPromise()
+ if err := resolve(value); err != nil {
+ panic(err)
+ }
+ return rt.ToValue(p)
+}
+
+// newRejectedPromise 返回一个已经以 reason 拒绝的 Promise 值。
+func newRejectedPromise(rt *goja.Runtime, reason goja.Value) goja.Value {
+ p, _, reject := rt.NewPromise()
+ if err := reject(reason); err != nil {
+ panic(err)
+ }
+ return rt.ToValue(p)
+}
+
+// awaitResult 统一处理"可能是 Promise,也可能是普通值"的结果:result 不是 Promise 时直接以其值调用
+// onFulfilled;是 Promise 时注册 then 回调。goja 把 Promise 反应(包括已经 settle 的 Promise 上新注册的
+// then 回调)排进内部 job 队列,只在最外层脚本调用整体返回、控制权交还给 Go 的那一刻才循环排空(而不是
+// 在 then()/resolve() 调用的当下同步触发),因此 onFulfilled/onRejected 的实际调用时机既不是
+// awaitResult 返回前,也不保证在当前 Go 调用栈内——只保证最终会被调用(除非对应的 Promise 永不 settle)。
+func awaitResult(rt *goja.Runtime, result goja.Value, onFulfilled func(value goja.Value), onRejected func(reason goja.Value)) {
+ promise, ok := asPromise(result)
+ if !ok {
+ onFulfilled(result)
+ return
+ }
+
+ object := rt.ToValue(promise).ToObject(rt)
+ then, ok := goja.AssertFunction(object.Get("then"))
+ if !ok {
+ // 不应该发生:goja 的 Promise 对象总有可调用的 then。退化为直接按当前导出值处理,不中断调用方。
+ onFulfilled(result)
+ return
+ }
+
+ if _, err := then(object,
+ rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ onFulfilled(call.Argument(0))
+ return goja.Undefined()
+ }),
+ rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ onRejected(call.Argument(0))
+ return goja.Undefined()
+ }),
+ ); err != nil {
+ panic(err)
+ }
+}
+
+// asPromise 判断 value 是否导出为 *goja.Promise。
+func asPromise(value goja.Value) (*goja.Promise, bool) {
+ if value == nil {
+ return nil, false
+ }
+ p, ok := value.Export().(*goja.Promise)
+ return p, ok
+}
+
+// callOptional 调用可能为 nil 的 goja.Callable;fn 为 nil 时视为返回 undefined 的空操作,不调用 this/传参。
+func callOptional(fn goja.Callable, this goja.Value, args ...goja.Value) (result goja.Value, err error) {
+ if fn == nil {
+ return goja.Undefined(), nil
+ }
+ return fn(this, args...)
+}
diff --git a/kernel/plugin/streams/queue.go b/kernel/plugin/streams/queue.go
new file mode 100644
index 0000000000..5f8a88894f
--- /dev/null
+++ b/kernel/plugin/streams/queue.go
@@ -0,0 +1,80 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import "github.com/dop251/goja"
+
+// queueEntry 是内部队列中的一项:value 是入队的 chunk,size 是调用 size 算法后得到的大小(出队时累计扣减)。
+// isClose 为 true 表示这一项是 WritableStream 的关闭请求哨兵(size 恒为 0,value 不使用),用来和常规写入
+// 共用同一条队列、按入队顺序保持写入与关闭的相对次序;比用某个特殊 goja.Value 当哨兵更直接,不依赖 goja 对
+// 任意 Go 值的包装/还原是否保持指针恒等。
+type queueEntry struct {
+ value goja.Value
+ size float64
+ isClose bool
+}
+
+// valueQueue 对应规范里 controller 的 [[queue]] 与 [[queueTotalSize]] 两个内部槛:一个先进先出队列,以及
+// 按 size 算法累计的总大小。规范用一个双字段元组列表 + 独立总量变量实现,这里直接用切片 + 累计值。
+type valueQueue struct {
+ entries []queueEntry
+ total float64
+}
+
+// enqueue 把 value 以给定 size 加入队尾,并把 size 累加进总量。
+func (q *valueQueue) enqueue(value goja.Value, size float64) {
+ q.entries = append(q.entries, queueEntry{value: value, size: size})
+ q.total += size
+}
+
+// enqueueClose 把一个关闭请求哨兵加入队尾(size 为 0,不占用队列容量)。
+func (q *valueQueue) enqueueClose() {
+ q.entries = append(q.entries, queueEntry{isClose: true})
+}
+
+// peekIsClose 返回队首项是否是关闭请求哨兵;调用方必须先确认队列非空。
+func (q *valueQueue) peekIsClose() bool {
+ return q.entries[0].isClose
+}
+
+// dequeue 取出并移除队首项,返回其 value;调用方必须先确认队列非空。
+func (q *valueQueue) dequeue() goja.Value {
+ entry := q.entries[0]
+ q.entries = q.entries[1:]
+ // 累计量按浮点减法可能产生微小负数误差,钳制为 0 与规范的处理意图一致(总量不应为负)。
+ q.total -= entry.size
+ if q.total < 0 {
+ q.total = 0
+ }
+ return entry.value
+}
+
+// peek 返回队首项的 value,不移除;调用方必须先确认队列非空。
+func (q *valueQueue) peek() goja.Value {
+ return q.entries[0].value
+}
+
+// len 返回队列中的项数。
+func (q *valueQueue) len() int {
+ return len(q.entries)
+}
+
+// reset 清空队列与总量。
+func (q *valueQueue) reset() {
+ q.entries = nil
+ q.total = 0
+}
diff --git a/kernel/plugin/streams/readable.go b/kernel/plugin/streams/readable.go
new file mode 100644
index 0000000000..d773599991
--- /dev/null
+++ b/kernel/plugin/streams/readable.go
@@ -0,0 +1,602 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "fmt"
+ "reflect"
+
+ "github.com/dop251/goja"
+)
+
+// streamStatus 对应规范里流的 [[state]]:readable、closed 或 errored 三态(不含字节流特有的中间态)。
+type streamStatus int
+
+const (
+ statusReadable streamStatus = iota
+ statusClosed
+ statusErrored
+)
+
+// readableState 对应 ReadableStream 的内部槛,只实现默认(非字节流)controller。
+type readableState struct {
+ expandoProperties
+
+ host *Host
+
+ status streamStatus
+ storedError goja.Value
+ disturbed bool
+
+ reader *readableReaderState // 非 nil 表示已被某个 reader 锁定
+ controller *readableController
+
+ self *goja.Object
+}
+
+// readableController 对应 ReadableStreamDefaultController 的内部槛。
+type readableController struct {
+ expandoProperties
+
+ host *Host
+ stream *readableState
+ queue valueQueue
+
+ started bool
+ closeRequested bool
+ pullAgain bool
+ pulling bool
+ strategyHWM float64
+
+ sizeAlgorithm func(chunk goja.Value) float64
+ pullAlgorithm func(controller goja.Value) goja.Value
+ cancelAlgorithm func(reason goja.Value) goja.Value
+
+ self *goja.Object
+}
+
+// readableReaderState 对应 ReadableStreamDefaultReader 的内部槛。
+type readableReaderState struct {
+ expandoProperties
+
+ host *Host
+ stream *readableState
+ readRequests []readRequest
+ closed deferred
+
+ self *goja.Object
+}
+
+// readRequest 对应规范 Read Request 记录:chunkSteps 对应 resolve,closeSteps/errorSteps 都通过 resolve/reject
+// 一个 {value, done} 结构或直接 reject 来表达,分别在 resolveReadResult/reject 调用处体现。
+type readRequest struct {
+ resolve func(any) error
+ reject func(any) error
+}
+
+var (
+ readableStateType = reflect.TypeOf((*readableState)(nil))
+ readableControllerType = reflect.TypeOf((*readableController)(nil))
+ readableReaderType = reflect.TypeOf((*readableReaderState)(nil))
+)
+
+// readableStateOf 取出 ReadableStream 的内部状态,只接受本包创建的对象。
+func readableStateOf(value goja.Value) (*readableState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != readableStateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*readableState)
+ return state, ok
+}
+
+// readableReaderOf 取出 ReadableStreamDefaultReader 的内部状态,只接受本包创建的对象。
+func readableReaderOf(value goja.Value) (*readableReaderState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != readableReaderType {
+ return nil, false
+ }
+ state, ok := object.Export().(*readableReaderState)
+ return state, ok
+}
+
+// readableControllerOf 取出 ReadableStreamDefaultController 的内部状态,只接受本包创建的对象。
+func readableControllerOf(value goja.Value) (*readableController, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != readableControllerType {
+ return nil, false
+ }
+ state, ok := object.Export().(*readableController)
+ return state, ok
+}
+
+// IsReadableStream 判断 value 是否是本 Host 构造出的 ReadableStream 实例。
+func (h *Host) IsReadableStream(value goja.Value) bool {
+ s, ok := readableStateOf(value)
+ return ok && s != nil
+}
+
+// jsValue 返回 controller 对应的脚本可见对象,首次调用时创建并缓存。
+func (c *readableController) jsValue() *goja.Object {
+ if c.self == nil {
+ object := c.host.rt.NewDynamicObject(c)
+ must(object.SetPrototype(c.host.readableControllerProto))
+ c.self = object
+ }
+ return c.self
+}
+
+// streamError 构造一个供内部状态使用的普通 Error(本沙箱不提供 DOMException,与既有实现一致,用普通 Error
+// 覆盖 name 表达特定错误类型)。
+func streamError(rt *goja.Runtime, name, message string) goja.Value {
+ err := rt.NewTypeError(message)
+ if name != "" && name != "TypeError" {
+ must(err.Set("name", rt.ToValue(name)))
+ }
+ return err
+}
+
+func typeErrorf(rt *goja.Runtime, format string, args ...any) goja.Value {
+ return rt.NewTypeError(fmt.Sprintf(format, args...))
+}
+
+// panicToReason 把 recover() 得到的值转换为可用作 reject reason 的 goja.Value:goja 异常原样传递,其余错误
+// 包装为新的 Error,否则按字符串兜底,避免二次 panic 掩盖原始错误路径。
+func panicToReason(rt *goja.Runtime, r any) (reason goja.Value) {
+ if v, ok := r.(goja.Value); ok {
+ return v
+ }
+ if err, ok := r.(error); ok {
+ if ex, ok := err.(*goja.Exception); ok {
+ return ex.Value()
+ }
+ return rt.NewGoError(err)
+ }
+ defer func() {
+ if recover() != nil {
+ reason = goja.Undefined()
+ }
+ }()
+ return rt.ToValue(fmt.Sprint(r))
+}
+
+// ──────────────────────────── ReadableStreamDefaultController 内部算法 ────────────────────────────
+
+// setUpReadableStreamDefaultController 对应规范 SetUpReadableStreamDefaultController:构造并挂载 controller,
+// 调用 start 算法,并在其完成/出错后据此调用一次 pull-if-needed 或把流置为出错状态。
+func setUpReadableStreamDefaultController(h *Host, stream *readableState,
+ start, pull, cancel func(controller goja.Value) goja.Value, highWaterMark float64, sizeAlgorithm func(goja.Value) float64) {
+ controller := &readableController{
+ host: h,
+ stream: stream,
+ strategyHWM: highWaterMark,
+ sizeAlgorithm: sizeAlgorithm,
+ pullAlgorithm: pull,
+ cancelAlgorithm: cancel,
+ }
+ stream.controller = controller
+
+ var startResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ readableControllerError(h, controller, panicToReason(h.rt, r))
+ ok = false
+ }
+ }()
+ startResult = start(controller.jsValue())
+ return true
+ }()
+ if !settled {
+ return
+ }
+
+ awaitResult(h.rt, orUndefined(startResult), func(goja.Value) {
+ controller.started = true
+ readableControllerCallPullIfNeeded(h, controller)
+ }, func(reason goja.Value) {
+ readableControllerError(h, controller, reason)
+ })
+}
+
+// readableControllerCanCloseOrEnqueue 对应 ReadableStreamDefaultControllerCanCloseOrEnqueue。
+func readableControllerCanCloseOrEnqueue(c *readableController) bool {
+ return !c.closeRequested && c.stream.status == statusReadable
+}
+
+// readableControllerDesiredSize 对应 ReadableStreamDefaultControllerGetDesiredSize;流出错时返回 ok=false。
+func readableControllerDesiredSize(c *readableController) (size float64, ok bool) {
+ switch c.stream.status {
+ case statusErrored:
+ return 0, false
+ case statusClosed:
+ return 0, true
+ default:
+ return c.strategyHWM - c.queue.total, true
+ }
+}
+
+// readableControllerShouldCallPull 对应 ReadableStreamDefaultControllerShouldCallPull。
+func readableControllerShouldCallPull(c *readableController) bool {
+ if !readableControllerCanCloseOrEnqueue(c) {
+ return false
+ }
+ if !c.started {
+ return false
+ }
+ if c.stream.reader != nil && len(c.stream.reader.readRequests) > 0 {
+ return true
+ }
+ desiredSize, ok := readableControllerDesiredSize(c)
+ return ok && desiredSize > 0
+}
+
+// readableControllerCallPullIfNeeded 对应 ReadableStreamDefaultControllerCallPullIfNeeded。
+func readableControllerCallPullIfNeeded(h *Host, c *readableController) {
+ if !readableControllerShouldCallPull(c) {
+ return
+ }
+ if c.pulling {
+ c.pullAgain = true
+ return
+ }
+ c.pulling = true
+
+ var pullResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ readableControllerError(h, c, panicToReason(h.rt, r))
+ ok = false
+ }
+ }()
+ pullResult = c.pullAlgorithm(c.jsValue())
+ return true
+ }()
+ if !settled {
+ return
+ }
+
+ awaitResult(h.rt, orUndefined(pullResult), func(goja.Value) {
+ c.pulling = false
+ if c.pullAgain {
+ c.pullAgain = false
+ readableControllerCallPullIfNeeded(h, c)
+ }
+ }, func(reason goja.Value) {
+ readableControllerError(h, c, reason)
+ })
+}
+
+// readableControllerClearAlgorithms 对应 ReadableStreamDefaultControllerClearAlgorithms:置空算法引用,
+// 避免结束后仍持有闭包。
+func readableControllerClearAlgorithms(c *readableController) {
+ c.pullAlgorithm = nil
+ c.cancelAlgorithm = nil
+ c.sizeAlgorithm = nil
+}
+
+// readableControllerClose 对应 ReadableStreamDefaultControllerClose。
+func readableControllerClose(h *Host, c *readableController) {
+ if !readableControllerCanCloseOrEnqueue(c) {
+ return
+ }
+ stream := c.stream
+ c.closeRequested = true
+ if c.queue.len() == 0 {
+ readableControllerClearAlgorithms(c)
+ readableStreamClose(h, stream)
+ }
+}
+
+// readableControllerEnqueue 对应 ReadableStreamDefaultControllerEnqueue。
+func readableControllerEnqueue(h *Host, c *readableController, chunk goja.Value) {
+ if !readableControllerCanCloseOrEnqueue(c) {
+ return
+ }
+ stream := c.stream
+ if stream.reader != nil && len(stream.reader.readRequests) > 0 {
+ readableStreamFulfillReadRequest(h, stream, chunk, false)
+ } else {
+ var size float64
+ ok := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ readableControllerError(h, c, panicToReason(h.rt, r))
+ panic(r) // 按规范,size 算法抛出的异常同时要向调用 enqueue() 的脚本重新抛出
+ }
+ }()
+ size = c.sizeAlgorithm(chunk)
+ return true
+ }()
+ if !ok {
+ return
+ }
+ c.queue.enqueue(chunk, size)
+ }
+ readableControllerCallPullIfNeeded(h, c)
+}
+
+// readableControllerError 对应 ReadableStreamDefaultControllerError。
+func readableControllerError(h *Host, c *readableController, reason goja.Value) {
+ stream := c.stream
+ if stream.status != statusReadable {
+ return
+ }
+ c.queue.reset()
+ readableControllerClearAlgorithms(c)
+ readableStreamError(h, stream, reason)
+}
+
+// readableControllerCancelSteps 对应 [[CancelSteps]]。
+func readableControllerCancelSteps(h *Host, c *readableController, reason goja.Value) goja.Value {
+ c.queue.reset()
+ cancel := c.cancelAlgorithm
+ var result goja.Value
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ result = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ }
+ }()
+ if cancel != nil {
+ result = cancel(reason)
+ } else {
+ result = newResolvedPromise(h.rt, goja.Undefined())
+ }
+ }()
+ readableControllerClearAlgorithms(c)
+ return result
+}
+
+// readableControllerPullSteps 对应 [[PullSteps]]:队列有数据直接满足请求,否则登记等待并尝试拉取更多数据。
+func readableControllerPullSteps(h *Host, c *readableController, request readRequest) {
+ stream := c.stream
+ if c.queue.len() > 0 {
+ chunk := c.queue.dequeue()
+ if c.closeRequested && c.queue.len() == 0 {
+ readableControllerClearAlgorithms(c)
+ readableStreamClose(h, stream)
+ } else {
+ readableControllerCallPullIfNeeded(h, c)
+ }
+ resolveReadResult(h.rt, request, chunk, false)
+ return
+ }
+ stream.reader.readRequests = append(stream.reader.readRequests, request)
+ readableControllerCallPullIfNeeded(h, c)
+}
+
+// resolveReadResult 用 {value, done} 兑定一次 read() 请求。
+func resolveReadResult(rt *goja.Runtime, request readRequest, value goja.Value, done bool) {
+ result := rt.NewObject()
+ if value == nil {
+ value = goja.Undefined()
+ }
+ must(result.Set("value", value))
+ must(result.Set("done", rt.ToValue(done)))
+ if err := request.resolve(result); err != nil {
+ panic(err)
+ }
+}
+
+// ──────────────────────────── ReadableStream 内部算法 ────────────────────────────
+
+// readableStreamClose 对应 ReadableStreamClose:置为 closed,兑定 reader 的 closed Promise,并把所有挂起的
+// read() 请求以 {value: undefined, done: true} 兑定。
+func readableStreamClose(h *Host, stream *readableState) {
+ stream.status = statusClosed
+ reader := stream.reader
+ if reader == nil {
+ return
+ }
+ if err := reader.closed.resolve(goja.Undefined()); err != nil {
+ panic(err)
+ }
+ for _, request := range reader.readRequests {
+ resolveReadResult(h.rt, request, goja.Undefined(), true)
+ }
+ reader.readRequests = nil
+}
+
+// readableStreamError 对应 ReadableStreamError:置为 errored,拒绝 reader 的 closed Promise,并以同一 reason
+// 拒绝所有挂起的 read() 请求。
+func readableStreamError(h *Host, stream *readableState, reason goja.Value) {
+ stream.status = statusErrored
+ stream.storedError = reason
+ reader := stream.reader
+ if reader == nil {
+ return
+ }
+ if err := reader.closed.reject(reason); err != nil {
+ panic(err)
+ }
+ for _, request := range reader.readRequests {
+ if err := request.reject(reason); err != nil {
+ panic(err)
+ }
+ }
+ reader.readRequests = nil
+}
+
+// readableStreamFulfillReadRequest 对应 ReadableStreamFulfillReadRequest:取出最早挂起的 read() 请求并兑定。
+func readableStreamFulfillReadRequest(h *Host, stream *readableState, chunk goja.Value, done bool) {
+ reader := stream.reader
+ request := reader.readRequests[0]
+ reader.readRequests = reader.readRequests[1:]
+ resolveReadResult(h.rt, request, chunk, done)
+}
+
+// readableStreamDefaultReaderRead 对应 ReadableStreamDefaultReaderRead:标记已扰动,流已关闭/出错时直接按
+// {done: true}/拒绝原因兑定 request,否则才委派给 controller 的 [[PullSteps]]。所有驱动读取的代码路径
+// (reader.read()、pipeTo 的拉取循环、tee 的共享拉取、异步迭代器的 next())都必须经过这个函数,不能直接调用
+// readableControllerPullSteps:一旦跳过这个短路检查,流关闭后队列已空时的读取请求会被当成"等待更多数据"
+// 一直挂起,永远不会被满足。
+func readableStreamDefaultReaderRead(h *Host, reader *readableReaderState, request readRequest) {
+ stream := reader.stream
+ stream.disturbed = true
+ switch stream.status {
+ case statusClosed:
+ resolveReadResult(h.rt, request, goja.Undefined(), true)
+ case statusErrored:
+ if err := request.reject(stream.storedError); err != nil {
+ panic(err)
+ }
+ default:
+ readableControllerPullSteps(h, stream.controller, request)
+ }
+}
+
+// readableStreamCancel 对应 ReadableStreamCancel:标记已扰动、按当前状态短路,否则关闭流并调用 controller 的
+// 取消算法;返回的 Promise 的拒绝原样传播,兑定值统一替换为 undefined。
+func readableStreamCancel(h *Host, stream *readableState, reason goja.Value) goja.Value {
+ stream.disturbed = true
+ switch stream.status {
+ case statusClosed:
+ return newResolvedPromise(h.rt, goja.Undefined())
+ case statusErrored:
+ return newRejectedPromise(h.rt, stream.storedError)
+ }
+ readableStreamClose(h, stream)
+
+ sourceCancelResult := readableControllerCancelSteps(h, stream.controller, reason)
+ result, resolve, reject := h.rt.NewPromise()
+ awaitResult(h.rt, sourceCancelResult, func(goja.Value) {
+ if err := resolve(goja.Undefined()); err != nil {
+ panic(err)
+ }
+ }, func(innerReason goja.Value) {
+ if err := reject(innerReason); err != nil {
+ panic(err)
+ }
+ })
+ return h.rt.ToValue(result)
+}
+
+// ──────────────────────────── ReadableStreamDefaultReader 内部算法 ────────────────────────────
+
+// isReadableStreamLocked 对应 IsReadableStreamLocked。
+func isReadableStreamLocked(stream *readableState) bool { return stream.reader != nil }
+
+// acquireReadableStreamDefaultReader 对应 AcquireReadableStreamDefaultReader + SetUpReadableStreamDefaultReader:
+// 流已被锁定时抛出 TypeError。
+func acquireReadableStreamDefaultReader(h *Host, stream *readableState) *readableReaderState {
+ if isReadableStreamLocked(stream) {
+ panic(typeErrorf(h.rt, "ReadableStreamDefaultReader constructor can only accept readable streams that are not yet locked to a reader"))
+ }
+ reader := &readableReaderState{host: h, stream: stream}
+ readableStreamReaderGenericInitialize(h, reader, stream)
+ return reader
+}
+
+// readableStreamReaderGenericInitialize 对应 ReadableStreamReaderGenericInitialize。
+func readableStreamReaderGenericInitialize(h *Host, reader *readableReaderState, stream *readableState) {
+ reader.stream = stream
+ stream.reader = reader
+ switch stream.status {
+ case statusReadable:
+ reader.closed = newDeferred(h.rt)
+ case statusClosed:
+ reader.closed = newDeferred(h.rt)
+ must0(reader.closed.resolve(goja.Undefined()))
+ default:
+ reader.closed = newDeferred(h.rt)
+ must0(reader.closed.reject(stream.storedError))
+ }
+}
+
+// readableStreamReaderGenericRelease 对应 ReadableStreamReaderGenericRelease:解除锁定,并把 closed Promise
+// 替换为一个新的、已拒绝的 Promise(流仍 readable 时拒绝原有的,否则直接换新的),均用 TypeError 表达
+// "锁已释放"。
+func readableStreamReaderGenericRelease(h *Host, reader *readableReaderState) {
+ stream := reader.stream
+ releaseErr := typeErrorf(h.rt, "Reader was released")
+ if stream.status == statusReadable {
+ must0(reader.closed.reject(releaseErr))
+ } else {
+ reader.closed = newDeferred(h.rt)
+ must0(reader.closed.reject(releaseErr))
+ }
+ stream.reader = nil
+ reader.stream = nil
+}
+
+// readableStreamDefaultReaderErrorReadRequests 对应 ReadableStreamDefaultReaderErrorReadRequests。
+func readableStreamDefaultReaderErrorReadRequests(reader *readableReaderState, reason goja.Value) {
+ for _, request := range reader.readRequests {
+ if err := request.reject(reason); err != nil {
+ panic(err)
+ }
+ }
+ reader.readRequests = nil
+}
+
+// must0 丢弃返回值地调用 must,便于在表达式语境中复用。
+func must0(err error) { must(err) }
+
+// jsValue 返回 reader 对应的脚本可见对象,首次调用时创建并缓存。
+func (reader *readableReaderState) jsValue() *goja.Object {
+ if reader.self == nil {
+ object := reader.host.rt.NewDynamicObject(reader)
+ must(object.SetPrototype(reader.host.readableReaderProto))
+ reader.self = object
+ }
+ return reader.self
+}
+
+// newReadableStreamObject 创建包装 state 的 ReadableStream 对象并绑定到共享原型。
+func (h *Host) newReadableStreamObject(state *readableState) *goja.Object {
+ object := h.rt.NewDynamicObject(state)
+ must(object.SetPrototype(h.readableStreamPrototype))
+ state.self = object
+ return object
+}
+
+// NewReadableStream 是 Go 侧构造默认(非字节流)ReadableStream 的入口,供 kernel/plugin 的 Go 桥接代码使用
+// (如把 fetch 的响应体包装为流)。start/pull/cancel 对应规范同名算法,均可为 nil(视为未提供);返回值可以
+// 是任意值或一个 Promise(经 awaitResult 等待),仅用其 settle 状态驱动 controller 的内部状态机,不作为
+// 流本身的数据。sizeAlgorithm 为 nil 时使用默认的"每个 chunk 大小为 1"算法。调用方必须已经在 runtime 所在
+// 的事件循环线程上。
+func (h *Host) NewReadableStream(start, pull, cancel func(controller goja.Value) goja.Value, highWaterMark float64,
+ sizeAlgorithm func(goja.Value) float64) *goja.Object {
+ if sizeAlgorithm == nil {
+ sizeAlgorithm = defaultSizeAlgorithm
+ }
+ stream := &readableState{host: h, status: statusReadable}
+ object := h.newReadableStreamObject(stream)
+ setUpReadableStreamDefaultController(h, stream, orNoOp(start), orNoOp(pull), orNoOp(cancel), highWaterMark, sizeAlgorithm)
+ return object
+}
+
+// orNoOp 把可能为 nil 的算法函数替换为返回 undefined 的空操作,匹配规范里"算法未提供"时的默认行为:该返回值会被
+// awaitResult 当作已经就绪的普通值处理,同步进入 onFulfilled 分支,驱动状态机继续往前走。
+func orNoOp(fn func(goja.Value) goja.Value) func(goja.Value) goja.Value {
+ if fn != nil {
+ return fn
+ }
+ return func(goja.Value) goja.Value { return goja.Undefined() }
+}
+
+// orUndefined 把 nil 规范化为 goja.Undefined(),防止算法实现疏漏返回值时 awaitResult 收到裸 nil。
+func orUndefined(v goja.Value) goja.Value {
+ if v == nil {
+ return goja.Undefined()
+ }
+ return v
+}
+
+func defaultSizeAlgorithm(goja.Value) float64 { return 1 }
diff --git a/kernel/plugin/streams/readable_prototype.go b/kernel/plugin/streams/readable_prototype.go
new file mode 100644
index 0000000000..812a880c43
--- /dev/null
+++ b/kernel/plugin/streams/readable_prototype.go
@@ -0,0 +1,363 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "github.com/dop251/goja"
+)
+
+// newReadableControllerPrototype 构造 ReadableStreamDefaultController.prototype:desiredSize 访问器,
+// enqueue/close/error 方法。
+func newReadableControllerPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *readableController {
+ c, ok := readableControllerOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStreamDefaultController.prototype.%s called on an incompatible receiver", method))
+ }
+ return c
+ }
+
+ defineGetter(rt, prototype, "desiredSize", func(call goja.FunctionCall) goja.Value {
+ size, ok := readableControllerDesiredSize(self(call, "desiredSize"))
+ if !ok {
+ return goja.Null()
+ }
+ return rt.ToValue(size)
+ })
+ defineMethod(rt, prototype, "enqueue", 1, func(call goja.FunctionCall) goja.Value {
+ c := self(call, "enqueue")
+ if !readableControllerCanCloseOrEnqueue(c) {
+ panic(typeErrorf(rt, "Cannot enqueue a chunk into a readable stream that is closed or has been requested to be closed"))
+ }
+ readableControllerEnqueue(h, c, call.Argument(0))
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "close", 0, func(call goja.FunctionCall) goja.Value {
+ c := self(call, "close")
+ if !readableControllerCanCloseOrEnqueue(c) {
+ panic(typeErrorf(rt, "Cannot close a readable stream that has already been requested to be closed"))
+ }
+ readableControllerClose(h, c)
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "error", 1, func(call goja.FunctionCall) goja.Value {
+ c := self(call, "error")
+ readableControllerError(h, c, call.Argument(0))
+ return goja.Undefined()
+ })
+ defineToStringTag(rt, prototype, "ReadableStreamDefaultController")
+ return prototype
+}
+
+// newReadableReaderPrototype 构造 ReadableStreamDefaultReader.prototype:closed 访问器,cancel/read/
+// releaseLock 方法。
+func newReadableReaderPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *readableReaderState {
+ r, ok := readableReaderOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStreamDefaultReader.prototype.%s called on an incompatible receiver", method))
+ }
+ return r
+ }
+
+ defineGetter(rt, prototype, "closed", func(call goja.FunctionCall) goja.Value {
+ return self(call, "closed").closed.value(rt)
+ })
+ defineMethod(rt, prototype, "cancel", 1, func(call goja.FunctionCall) goja.Value {
+ reader := self(call, "cancel")
+ if reader.stream == nil {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot cancel a readable stream reader that has no owner stream"))
+ }
+ return h.rt.ToValue(readableStreamCancel(h, reader.stream, call.Argument(0)))
+ })
+ defineMethod(rt, prototype, "read", 0, func(call goja.FunctionCall) goja.Value {
+ reader := self(call, "read")
+ if reader.stream == nil {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot read from a reader released from its owner stream"))
+ }
+
+ promise, resolve, reject := rt.NewPromise()
+ readableStreamDefaultReaderRead(h, reader, readRequest{resolve: resolve, reject: reject})
+ return rt.ToValue(promise)
+ })
+ defineMethod(rt, prototype, "releaseLock", 0, func(call goja.FunctionCall) goja.Value {
+ reader := self(call, "releaseLock")
+ if reader.stream == nil {
+ return goja.Undefined()
+ }
+ if len(reader.readRequests) > 0 {
+ readableStreamDefaultReaderErrorReadRequests(reader,
+ typeErrorf(rt, "Reader was released and can no longer be used to monitor the stream's closedness"))
+ }
+ readableStreamReaderGenericRelease(h, reader)
+ return goja.Undefined()
+ })
+ defineToStringTag(rt, prototype, "ReadableStreamDefaultReader")
+ return prototype
+}
+
+// newResolvedPromiseResult 返回一个以 {value, done} 兑定的 Promise。
+func newResolvedPromiseResult(rt *goja.Runtime, value goja.Value, done bool) goja.Value {
+ result := rt.NewObject()
+ must(result.Set("value", value))
+ must(result.Set("done", rt.ToValue(done)))
+ return newResolvedPromise(rt, result)
+}
+
+// newReadableStreamPrototype 构造 ReadableStream.prototype:locked 访问器,cancel/getReader/pipeTo/
+// pipeThrough/tee/values 方法与 Symbol.asyncIterator 别名。
+func newReadableStreamPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *readableState {
+ s, ok := readableStateOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.prototype.%s called on an incompatible receiver", method))
+ }
+ return s
+ }
+
+ defineGetter(rt, prototype, "locked", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(isReadableStreamLocked(self(call, "locked")))
+ })
+ defineMethod(rt, prototype, "cancel", 1, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "cancel")
+ if isReadableStreamLocked(stream) {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot cancel a stream that already has a reader"))
+ }
+ return readableStreamCancel(h, stream, call.Argument(0))
+ })
+ defineMethod(rt, prototype, "getReader", 0, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "getReader")
+ if options := call.Argument(0); isJsValueNotNull(options) {
+ optionsObj, ok := options.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.prototype.getReader: Argument 1 can't be converted to a dictionary"))
+ }
+ if mode := dictMember(optionsObj, "mode"); mode != nil {
+ modeStr := mode.String()
+ if modeStr == "byob" {
+ panic(typeErrorf(rt, "ReadableStream.prototype.getReader: byte stream readers (mode: \"byob\") are not supported"))
+ }
+ panic(typeErrorf(rt, "ReadableStream.prototype.getReader: '%s' (value of 'mode' member of ReadableGetReaderOptions) is not a valid value for enumeration ReadableStreamReaderMode", modeStr))
+ }
+ }
+ return acquireReadableStreamDefaultReader(h, stream).jsValue()
+ })
+ defineMethod(rt, prototype, "pipeTo", 2, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "pipeTo")
+ return readableStreamPipeTo(h, stream, call.Argument(0), call.Argument(1))
+ })
+ defineMethod(rt, prototype, "pipeThrough", 2, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "pipeThrough")
+ return readableStreamPipeThrough(h, stream, call.Argument(0), call.Argument(1))
+ })
+ defineMethod(rt, prototype, "tee", 0, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "tee")
+ a, b := readableStreamTee(h, stream)
+ return rt.NewArray(a, b)
+ })
+ defineMethod(rt, prototype, "values", 1, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "values")
+ return newReadableStreamAsyncIterator(h, stream, readableIteratorOptionPreventCancel(rt, call.Argument(0)))
+ })
+ // goja(本沙箱固定的版本)没有原生 Symbol.asyncIterator,与 web-streams-polyfill 遇到同一问题时的做法一致,
+ // 退化为 Symbol.for("Symbol.asyncIterator"):脚本写 stream[Symbol.for("Symbol.asyncIterator")]() 可以拿到
+ // 这个方法,但 `for await (const chunk of stream)` 语法本身在这版 goja 下不被解析,不受此影响。
+ must(prototype.DefineDataPropertySymbol(asyncIteratorSymbol(rt), prototype.Get("values"), goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ defineToStringTag(rt, prototype, "ReadableStream")
+ return prototype
+}
+
+// asyncIteratorSymbol 返回与脚本里 Symbol.for("Symbol.asyncIterator") 同一个全局注册表条目的 Symbol,
+// 而不是用 goja.NewSymbol 另造一个无法被脚本按名字查到的符号。
+func asyncIteratorSymbol(rt *goja.Runtime) *goja.Symbol {
+ symbolCtor := rt.Get("Symbol").ToObject(rt)
+ forFn, ok := goja.AssertFunction(symbolCtor.Get("for"))
+ if !ok {
+ panic(typeErrorf(rt, "globalThis.Symbol.for is not a function"))
+ }
+ result, err := forFn(symbolCtor, rt.ToValue("Symbol.asyncIterator"))
+ if err != nil {
+ panic(err)
+ }
+ sym, ok := result.(*goja.Symbol)
+ if !ok {
+ panic(typeErrorf(rt, "Symbol.for did not return a Symbol"))
+ }
+ return sym
+}
+
+// readableIteratorOptionPreventCancel 读取 values()/[Symbol.asyncIterator] 的 {preventCancel} 选项;
+// undefined/null 视为缺省(false),与 WebIDL 字典参数的习惯一致。
+func readableIteratorOptionPreventCancel(rt *goja.Runtime, options goja.Value) bool {
+ if !isJsValueNotNull(options) {
+ return false
+ }
+ object, ok := options.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "values: options can't be converted to a dictionary"))
+ }
+ preventCancel := object.Get("preventCancel")
+ return preventCancel != nil && !goja.IsUndefined(preventCancel) && preventCancel.ToBoolean()
+}
+
+// newReadableStreamConstructor 构造 ReadableStream 全局构造函数:new ReadableStream(underlyingSource, strategy)。
+// 不支持 underlyingSource.type === "bytes"(字节流),遇到会抛错,是本包对规范的已知、文档化的裁剪。
+func (h *Host) newReadableStreamConstructor() *goja.Object {
+ rt := h.rt
+ return newInterfaceConstructor(rt, "ReadableStream", 0, h.readableStreamPrototype, func(call goja.ConstructorCall) *goja.Object {
+ source := call.Argument(0)
+ var sourceObj *goja.Object
+ if isJsValueNotNull(source) {
+ var ok bool
+ sourceObj, ok = source.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream: Argument 1 can't be converted to a dictionary"))
+ }
+ if typ := sourceObj.Get("type"); isJsValueNotNull(typ) {
+ panic(typeErrorf(rt, "ReadableStream: byte streams (type: \"bytes\") are not supported"))
+ }
+ }
+
+ stream := &readableState{host: h, status: statusReadable}
+ object := h.rt.NewDynamicObject(stream)
+ must(object.SetPrototype(call.This.Prototype()))
+ stream.self = object
+
+ highWaterMark := extractHighWaterMark(rt, call.Argument(1), 1)
+ sizeAlgorithm := extractSizeAlgorithm(rt, call.Argument(1))
+ start := wrapUnderlyingMethod(rt, sourceObj, "start")
+ pull := wrapUnderlyingMethod(rt, sourceObj, "pull")
+ cancel := wrapUnderlyingMethod(rt, sourceObj, "cancel")
+ setUpReadableStreamDefaultController(h, stream, orNoOp(start), orNoOp(pull), orNoOp(cancel), highWaterMark, sizeAlgorithm)
+ return object
+ })
+}
+
+// readableStreamFrom 对应 ReadableStream.from(asyncIterable):把一个同步或异步可迭代对象包装成
+// ReadableStream。优先用 Symbol.for("Symbol.asyncIterator")(与本包自己 values() 的输出互通),
+// 否则退回 Symbol.iterator;sync 迭代器的 next() 直接返回 {value, done},async 版本返回 Promise,
+// awaitResult 对两者一视同仁。cancel() 时若迭代器有 return 方法会调用一次(忽略其返回值)。
+func (h *Host) readableStreamFrom(iterable goja.Value) *goja.Object {
+ rt := h.rt
+ iterator := iteratorOf(rt, iterable)
+ next, ok := goja.AssertFunction(iterator.Get("next"))
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.from: the iterator's next method is not callable"))
+ }
+
+ return h.NewReadableStream(nil, func(controller goja.Value) goja.Value {
+ c, _ := readableControllerOf(controller)
+ result, err := next(iterator)
+ if err != nil {
+ panic(err)
+ }
+ promise, resolve, reject := rt.NewPromise()
+ awaitResult(rt, result, func(value goja.Value) {
+ // 对应规范 IteratorNext:next() 的返回值必须是对象,否则抛 TypeError。只用 ToObject 转换会把
+ // 数字、字符串等原始值自动装箱成临时对象、悄悄放过本该报错的输入(object.Get("done") 在装箱
+ // 对象上读不到值返回裸 nil,没有命中下面的 close 分支,而是把 undefined 当成 chunk 入队),
+ // 所以要先显式检查 value 本身是不是对象。
+ object, ok := value.(*goja.Object)
+ if !ok {
+ err := typeErrorf(rt, "ReadableStream.from: the iterator result is not an object")
+ readableControllerError(h, c, err)
+ must0(reject(err))
+ return
+ }
+ if done := object.Get("done"); done != nil && done.ToBoolean() {
+ readableControllerClose(h, c)
+ } else {
+ readableControllerEnqueue(h, c, object.Get("value"))
+ }
+ must0(resolve(goja.Undefined()))
+ }, func(reason goja.Value) {
+ readableControllerError(h, c, reason)
+ must0(reject(reason))
+ })
+ return rt.ToValue(promise)
+ }, func(reason goja.Value) goja.Value {
+ if returnFn, ok := goja.AssertFunction(iterator.Get("return")); ok {
+ if _, err := returnFn(iterator, reason); err != nil {
+ panic(err)
+ }
+ }
+ return nil
+ }, 0, nil)
+}
+
+// iteratorOf 取出 iterable 的迭代器:先找 Symbol.for("Symbol.asyncIterator"),再退回 Symbol.iterator,
+// 两者都没有则抛错。
+func iteratorOf(rt *goja.Runtime, iterable goja.Value) *goja.Object {
+ object, ok := iterable.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.from: Argument 1 is not an object"))
+ }
+ getIterator, ok := goja.AssertFunction(object.GetSymbol(asyncIteratorSymbol(rt)))
+ if !ok {
+ getIterator, ok = goja.AssertFunction(object.GetSymbol(goja.SymIterator))
+ }
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.from: Argument 1 is not async-iterable or iterable"))
+ }
+ iteratorValue, err := getIterator(object)
+ if err != nil {
+ panic(err)
+ }
+ iterator, ok := iteratorValue.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "ReadableStream.from: the iterator method did not return an object"))
+ }
+ return iterator
+}
+
+// wrapUnderlyingMethod 把 underlyingSource/underlyingSink/transformer 字典上名为 name 的可选方法包装为
+// Go 函数:以 source 为 this 调用,传入单个参数(controller 或 reason),异常原样 panic 向上传播。source
+// 为 nil 或方法缺省时返回 nil(调用方据此套用默认算法)。
+func wrapUnderlyingMethod(rt *goja.Runtime, source *goja.Object, name string) func(arg goja.Value) goja.Value {
+ if source == nil {
+ return nil
+ }
+ method := source.Get(name)
+ if method == nil || goja.IsUndefined(method) {
+ return nil
+ }
+ fn, ok := goja.AssertFunction(method)
+ if !ok {
+ panic(typeErrorf(rt, "%s member of underlying source must be a function", name))
+ }
+ return func(arg goja.Value) goja.Value {
+ result, err := fn(source, arg)
+ if err != nil {
+ panic(err)
+ }
+ return result
+ }
+}
+
+// isJsValueNotNull 判断值既非 nil,也非 undefined/null。
+func isJsValueNotNull(value goja.Value) bool {
+ return value != nil && !goja.IsUndefined(value) && !goja.IsNull(value)
+}
diff --git a/kernel/plugin/streams/strategies.go b/kernel/plugin/streams/strategies.go
new file mode 100644
index 0000000000..22cc96b33f
--- /dev/null
+++ b/kernel/plugin/streams/strategies.go
@@ -0,0 +1,138 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "math"
+
+ "github.com/dop251/goja"
+)
+
+// extractHighWaterMark 对应规范 ExtractHighWaterMark:strategy.highWaterMark 缺省时取 defaultHWM;否则转换为
+// 数值并要求非 NaN、非负,否则抛 RangeError。
+func extractHighWaterMark(rt *goja.Runtime, strategy goja.Value, defaultHWM float64) float64 {
+ object, ok := strategyObjectOf(strategy)
+ if !ok {
+ return defaultHWM
+ }
+ hwm := object.Get("highWaterMark")
+ if hwm == nil || goja.IsUndefined(hwm) {
+ return defaultHWM
+ }
+ value := hwm.ToFloat()
+ if math.IsNaN(value) || value < 0 {
+ panic(rangeErrorf(rt, "Invalid highWaterMark"))
+ }
+ return value
+}
+
+// rangeErrorf 构造一个 name 为 RangeError 的普通 Error(本沙箱沿用 streamError 的做法,不提供原生 RangeError
+// 包装)。
+func rangeErrorf(rt *goja.Runtime, message string) goja.Value {
+ return streamError(rt, "RangeError", message)
+}
+
+// strategyObjectOf 把 QueuingStrategy 字典参数转换为对象:undefined/null 视为空字典,其余非对象值抛错由
+// 调用方按需处理(这里简单返回 ok=false 让调用方套用缺省值,与"空字典"等价,和规范对 undefined/null 的处理
+// 一致;真正传入非对象、非 nullish 值时 WebIDL 本应抛错,但 strategy 参数在本包内只有宿主自己构造的调用点,
+// 不会传入这类值,因此未做严格校验)。
+func strategyObjectOf(strategy goja.Value) (*goja.Object, bool) {
+ if strategy == nil || goja.IsUndefined(strategy) || goja.IsNull(strategy) {
+ return nil, false
+ }
+ object, ok := strategy.(*goja.Object)
+ return object, ok
+}
+
+// extractSizeAlgorithm 对应规范 ExtractSizeAlgorithm:strategy.size 缺省时返回"任意 chunk 大小为 1"的算法,
+// 否则返回调用该函数的算法(异常原样向上抛出)。
+func extractSizeAlgorithm(rt *goja.Runtime, strategy goja.Value) func(goja.Value) float64 {
+ object, ok := strategyObjectOf(strategy)
+ if !ok {
+ return defaultSizeAlgorithm
+ }
+ size := object.Get("size")
+ if size == nil || goja.IsUndefined(size) {
+ return defaultSizeAlgorithm
+ }
+ fn, ok := goja.AssertFunction(size)
+ if !ok {
+ panic(typeErrorf(rt, "size member of QueuingStrategy must be a function"))
+ }
+ return func(chunk goja.Value) float64 {
+ result, err := fn(goja.Undefined(), chunk)
+ if err != nil {
+ panic(err)
+ }
+ return result.ToFloat()
+ }
+}
+
+// newCountQueuingStrategyConstructor 构造 CountQueuingStrategy:{highWaterMark} -> 对象,size() 恒定为 1,
+// highWaterMark 为构造时传入的值。
+func newCountQueuingStrategyConstructor(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+ defineMethod(rt, prototype, "size", 0, func(call goja.FunctionCall) goja.Value { return rt.ToValue(1) })
+ defineToStringTag(rt, prototype, "CountQueuingStrategy")
+
+ return newInterfaceConstructor(rt, "CountQueuingStrategy", 1, prototype, func(call goja.ConstructorCall) *goja.Object {
+ instance := rt.NewObject()
+ must(instance.SetPrototype(call.This.Prototype()))
+ must(instance.DefineDataProperty("highWaterMark", rt.ToValue(highWaterMarkMemberOf(rt, call.Argument(0))),
+ goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return instance
+ })
+}
+
+// newByteLengthQueuingStrategyConstructor 构造 ByteLengthQueuingStrategy:{highWaterMark} -> 对象,
+// size(chunk) 返回 chunk.byteLength,highWaterMark 为构造时传入的值。
+func newByteLengthQueuingStrategyConstructor(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+ defineMethod(rt, prototype, "size", 1, func(call goja.FunctionCall) goja.Value {
+ chunk := call.Argument(0)
+ if chunkObj, ok := chunk.(*goja.Object); ok {
+ if byteLength := chunkObj.Get("byteLength"); byteLength != nil {
+ return byteLength
+ }
+ }
+ return rt.ToValue(0)
+ })
+ defineToStringTag(rt, prototype, "ByteLengthQueuingStrategy")
+
+ return newInterfaceConstructor(rt, "ByteLengthQueuingStrategy", 1, prototype, func(call goja.ConstructorCall) *goja.Object {
+ instance := rt.NewObject()
+ must(instance.SetPrototype(call.This.Prototype()))
+ must(instance.DefineDataProperty("highWaterMark", rt.ToValue(highWaterMarkMemberOf(rt, call.Argument(0))),
+ goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return instance
+ })
+}
+
+// highWaterMarkMemberOf 读取 QueuingStrategyInit 字典的必填 highWaterMark 成员(无默认值,必须显式提供)。
+func highWaterMarkMemberOf(rt *goja.Runtime, init goja.Value) float64 {
+ object, ok := init.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "QueuingStrategyInit: can't be converted to a dictionary"))
+ }
+ hwm := object.Get("highWaterMark")
+ if hwm == nil || goja.IsUndefined(hwm) {
+ panic(typeErrorf(rt, "QueuingStrategyInit: highWaterMark is required"))
+ }
+ return hwm.ToFloat()
+}
diff --git a/kernel/plugin/streams/streams_test.go b/kernel/plugin/streams/streams_test.go
new file mode 100644
index 0000000000..d297f64a87
--- /dev/null
+++ b/kernel/plugin/streams/streams_test.go
@@ -0,0 +1,680 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "testing"
+
+ "github.com/dop251/goja"
+)
+
+// newTestRuntime 创建已启用本包的 goja runtime:按 kernel/plugin 的实际配置设置字段名映射(本包的实现不依赖
+// 它,但与生产环境一致,便于发现潜在的隐藏耦合)。
+func newTestRuntime(t *testing.T) (*goja.Runtime, *Host) {
+ t.Helper()
+ rt := goja.New()
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ h := Enable(rt)
+ return rt, h
+}
+
+// run 执行脚本,脚本出错时直接 Fatal;不涉及 Promise 的测试直接用它取返回值。
+func run(t *testing.T, rt *goja.Runtime, script string) goja.Value {
+ t.Helper()
+ v, err := rt.RunString(script)
+ if err != nil {
+ t.Fatalf("script error: %v\nscript: %s", err, script)
+ }
+ return v
+}
+
+// runAsync 把 script 包进一个立即执行的 async 函数并运行,返回其落定结果的 JSON 字符串。
+//
+// goja(本包固定的版本)里 Promise 的反应不是在触发它们的那次调用中同步跑完,而是作为 job 排进 runtime
+// 内部队列,只在"最外层脚本调用整体返回、控制权交还给 Go"的那一刻才循环排空(runtime.go 的 leave())。
+// 所以不能在同一次 RunString 里"触发 then 链之后立刻读取结果"——这是本文件最初的写法,看起来会同步生效,
+// 实际是因为之前验证用的探针在 RunString 返回之后才读取结果,而不是 Promise 反应真的同步触发。只要整条
+// 链不依赖"稍后才会发生的新一轮 Go 回调"(定时器、另一次 RunOnLoop 等),leave() 会循环排空到链路跑完,
+// 所以把需要观察的值放进 async 函数的返回值,在 RunString 返回之后读这个已经落定的 Promise 即可,不需要
+// 事件循环。
+func runAsync(t *testing.T, rt *goja.Runtime, script string) string {
+ t.Helper()
+ got := run(t, rt, "(async () => {\n"+script+"\n})()")
+ promise, ok := got.Export().(*goja.Promise)
+ if !ok {
+ t.Fatalf("script did not return a Promise: %v", got)
+ }
+ switch promise.State() {
+ case goja.PromiseStateFulfilled:
+ return promise.Result().String()
+ case goja.PromiseStateRejected:
+ t.Fatalf("script's promise rejected: %v", promise.Result())
+ default:
+ t.Fatalf("script's promise is still pending after the script returned (likely waiting on something that " +
+ "never settles synchronously, such as a real timer)")
+ }
+ return ""
+}
+
+func TestReadableStreamBasicReadAndClose(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const rs = new ReadableStream({
+ start(controller) {
+ controller.enqueue("a");
+ controller.enqueue("b");
+ controller.close();
+ }
+ });
+ const reader = rs.getReader();
+ const results = [await reader.read(), await reader.read(), await reader.read()];
+ return JSON.stringify(results);
+ `)
+ want := `[{"value":"a","done":false},{"value":"b","done":false},{"done":true}]`
+ if got != want {
+ t.Fatalf("read results = %s, want %s", got, want)
+ }
+}
+
+func TestReadableStreamLockedAndDoubleGetReaderThrows(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := run(t, rt, `(() => {
+ const rs = new ReadableStream();
+ const before = rs.locked;
+ const reader = rs.getReader();
+ const after = rs.locked;
+ let threw = false;
+ try { rs.getReader(); } catch (e) { threw = e instanceof TypeError; }
+ return JSON.stringify([before, after, threw]);
+ })()`)
+ if want := `[false,true,true]`; got.String() != want {
+ t.Fatalf("locked/double getReader = %s, want %s", got.String(), want)
+ }
+}
+
+func TestReadableStreamCancelCallsCancelAlgorithm(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const log = [];
+ const rs = new ReadableStream({
+ cancel(reason) { log.push("cancel:" + reason); }
+ });
+ const settled = await rs.cancel("bye");
+ return JSON.stringify([log, settled === undefined]);
+ `)
+ if want := `[["cancel:bye"],true]`; got != want {
+ t.Fatalf("cancel = %s, want %s", got, want)
+ }
+}
+
+func TestReadableStreamErrorRejectsPendingReads(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ let controllerRef;
+ const rs = new ReadableStream({ start(c) { controllerRef = c; } });
+ const reader = rs.getReader();
+ const pending = reader.read();
+ controllerRef.error(new Error("boom"));
+ let caught = null;
+ await pending.catch(e => { caught = String(e); });
+ return JSON.stringify(caught);
+ `)
+ if want := `"Error: boom"`; got != want {
+ t.Fatalf("error propagation = %s, want %s", got, want)
+ }
+}
+
+func TestReadableStreamDesiredSizeAndBackpressure(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := run(t, rt, `(() => {
+ let controllerRef;
+ const rs = new ReadableStream({ start(c) { controllerRef = c; } }, { highWaterMark: 2 });
+ const before = controllerRef.desiredSize;
+ controllerRef.enqueue(1);
+ const afterOne = controllerRef.desiredSize;
+ controllerRef.enqueue(2);
+ const afterTwo = controllerRef.desiredSize;
+ return JSON.stringify([before, afterOne, afterTwo]);
+ })()`)
+ if want := `[2,1,0]`; got.String() != want {
+ t.Fatalf("desiredSize sequence = %s, want %s", got.String(), want)
+ }
+}
+
+func TestWritableStreamWriteCloseAndDesiredSize(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const chunks = [];
+ const ws = new WritableStream({
+ write(chunk) { chunks.push(chunk); },
+ });
+ const writer = ws.getWriter();
+ const sizeBefore = writer.desiredSize;
+ await writer.write("a");
+ await writer.close();
+ return JSON.stringify([sizeBefore, chunks]);
+ `)
+ if want := `[1,["a"]]`; got != want {
+ t.Fatalf("writable write/close = %s, want %s", got, want)
+ }
+}
+
+func TestWritableStreamWriteAfterCloseRejects(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const ws = new WritableStream();
+ const writer = ws.getWriter();
+ await writer.close();
+ let reason = null;
+ await writer.write("x").catch(e => { reason = e instanceof TypeError; });
+ return JSON.stringify(reason);
+ `)
+ if want := `true`; got != want {
+ t.Fatalf("write after close = %s, want %s", got, want)
+ }
+}
+
+func TestWritableStreamAbortRejectsPendingWrite(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ let rejectWrite;
+ const ws = new WritableStream({
+ write(chunk) { return new Promise((_, reject) => { rejectWrite = reject; }); },
+ });
+ const writer = ws.getWriter();
+ let writeErr = null;
+ const writePromise = writer.write("x").catch(e => { writeErr = String(e); });
+ const abortPromise = writer.abort("stop");
+ rejectWrite(new Error("underlying failure"));
+ await writePromise;
+ let abortOk = null;
+ await abortPromise.then(() => { abortOk = true; });
+ return JSON.stringify([writeErr, abortOk]);
+ `)
+ if want := `["Error: underlying failure",true]`; got != want {
+ t.Fatalf("abort pending write = %s, want %s", got, want)
+ }
+}
+
+func TestTransformStreamIdentityDefault(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const ts = new TransformStream();
+ const writer = ts.writable.getWriter();
+ const reader = ts.readable.getReader();
+ writer.write("x");
+ writer.close();
+ const results = [await reader.read(), await reader.read()];
+ return JSON.stringify(results);
+ `)
+ if want := `[{"value":"x","done":false},{"done":true}]`; got != want {
+ t.Fatalf("transform identity = %s, want %s", got, want)
+ }
+}
+
+func TestTransformStreamCustomTransformAndFlush(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const ts = new TransformStream({
+ transform(chunk, controller) { controller.enqueue(chunk.toUpperCase()); },
+ flush(controller) { controller.enqueue("END"); },
+ });
+ const writer = ts.writable.getWriter();
+ const reader = ts.readable.getReader();
+ writer.write("a");
+ writer.close();
+ const results = [await reader.read(), await reader.read(), await reader.read()];
+ return JSON.stringify(results);
+ `)
+ want := `[{"value":"A","done":false},{"value":"END","done":false},{"done":true}]`
+ if got != want {
+ t.Fatalf("transform custom = %s, want %s", got, want)
+ }
+}
+
+// 按规范,取消 TransformStream 的 readable 侧不会调用 transformer 的 cancel 选项(那是 writable 侧 abort 时
+// 才用的算法);取消 readable 侧只应把 writable 侧也一并错误化,使后续写入失败。
+func TestTransformStreamReadableCancelErrorsWritableWithoutInvokingTransformerCancel(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const log = [];
+ const ts = new TransformStream({ cancel(reason) { log.push("cancel:" + reason); } });
+ const reader = ts.readable.getReader();
+ await reader.cancel("nope");
+ let writeErr = null;
+ // cancel 的 reason 可以是任意值,不要求是 Error:这里直接比较拒绝原因本身,而不是检查其类型。
+ await ts.writable.getWriter().write("x").catch(e => { writeErr = e; });
+ return JSON.stringify([log, writeErr]);
+ `)
+ if want := `[[],"nope"]`; got != want {
+ t.Fatalf("transform readable cancel = %s, want %s", got, want)
+ }
+}
+
+// transformer 的 cancel 选项由 writable 侧的 abort() 触发(内部走 TransformStreamDefaultSinkAbortAlgorithm)。
+func TestTransformStreamWritableAbortInvokesTransformerCancel(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const log = [];
+ const ts = new TransformStream({ cancel(reason) { log.push("cancel:" + reason); } });
+ await ts.writable.getWriter().abort("nope");
+ return JSON.stringify(log);
+ `)
+ if want := `["cancel:nope"]`; got != want {
+ t.Fatalf("transform writable abort = %s, want %s", got, want)
+ }
+}
+
+func TestPipeToCopiesChunksAndCloses(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const rs = new ReadableStream({
+ start(c) { c.enqueue(1); c.enqueue(2); c.close(); }
+ });
+ const chunks = [];
+ let closed = false;
+ const ws = new WritableStream({
+ write(chunk) { chunks.push(chunk); },
+ close() { closed = true; },
+ });
+ await rs.pipeTo(ws);
+ return JSON.stringify([chunks, closed]);
+ `)
+ if want := `[[1,2],true]`; got != want {
+ t.Fatalf("pipeTo = %s, want %s", got, want)
+ }
+}
+
+func TestPipeToPreventCloseLeavesDestOpen(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const rs = new ReadableStream({ start(c) { c.enqueue(1); c.close(); } });
+ let closed = false;
+ const ws = new WritableStream({ close() { closed = true; } });
+ await rs.pipeTo(ws, { preventClose: true });
+ return JSON.stringify([closed, ws.locked]);
+ `)
+ if want := `[false,false]`; got != want {
+ t.Fatalf("pipeTo preventClose = %s, want %s", got, want)
+ }
+}
+
+func TestPipeToPropagatesSourceErrorAndAbortsDest(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ let controllerRef;
+ const rs = new ReadableStream({ start(c) { controllerRef = c; } });
+ let abortReason = null;
+ const ws = new WritableStream({ abort(r) { abortReason = String(r); } });
+ const pending = rs.pipeTo(ws);
+ controllerRef.error(new Error("source failed"));
+ let caught = null;
+ await pending.catch(e => { caught = String(e); });
+ return JSON.stringify([caught, abortReason]);
+ `)
+ want := `["Error: source failed","Error: source failed"]`
+ if got != want {
+ t.Fatalf("pipeTo error propagation = %s, want %s", got, want)
+ }
+}
+
+// 目的地在 pipeTo 等待源数据期间出错:管道必须以目的地的错误拒绝并释放两端的锁;未设置 preventCancel 时以同一
+// 错误取消源流,设置时源流保持可读,之后的数据交给新的 reader 而不是被管道遗留的读取请求截走。源流的
+// highWaterMark 为 0,pull 只在有挂起的读取请求时调用,日志里的 "pull" 证明出错时管道正在等待源数据。
+func TestPipeToPropagatesDestinationErrorWhileWaitingForSource(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const run = async (options) => {
+ const log = [];
+ let source, dest;
+ const rs = new ReadableStream({
+ start(c) { source = c; },
+ pull() { log.push("pull"); },
+ cancel(reason) { log.push("cancel:" + reason.message); },
+ }, { highWaterMark: 0 });
+ const ws = new WritableStream({ start(c) { dest = c; } });
+ const piping = rs.pipeTo(ws, options);
+ await null;
+ await null;
+ dest.error(new Error("dest failed"));
+ log.push(await piping.then(() => "resolved", (e) => "rejected:" + e.message));
+ log.push("locked:" + rs.locked + "," + ws.locked);
+ const reading = rs.getReader().read();
+ if (options) source.enqueue("later");
+ log.push("read:" + JSON.stringify(await reading));
+ return log;
+ };
+ return JSON.stringify([await run(), await run({ preventCancel: true })]);
+ `)
+ want := `[["pull","cancel:dest failed","rejected:dest failed","locked:false,false","read:{\"done\":true}"],` +
+ `["pull","rejected:dest failed","locked:false,false","pull","read:{\"value\":\"later\",\"done\":false}"]]`
+ if got != want {
+ t.Fatalf("pipeTo destination error = %s, want %s", got, want)
+ }
+}
+
+// 目的地一直施加背压时,源流的关闭和错误仍要传递,收尾后释放两端的锁。
+func TestPipeToSourceSettlesWhileWaitingForBackpressure(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const results = [];
+ for (const initial of [false, true]) {
+ for (const error of [false, true]) {
+ for (const preventAbort of [false, true]) {
+ let source;
+ const log = [];
+ const rs = new ReadableStream({ start(c) {
+ source = c;
+ if (initial) {
+ if (error) c.error("source failed"); else c.close();
+ }
+ } });
+ const ws = new WritableStream({
+ abort(reason) { log.push("abort:" + reason); },
+ close() { log.push("close"); },
+ }, { highWaterMark: 0 });
+ const piping = rs.pipeTo(ws, { preventAbort });
+ if (!initial) {
+ await null;
+ if (error) source.error("source failed"); else source.close();
+ }
+ log.push(await piping.then(() => "resolved", reason => "rejected:" + reason));
+ log.push(rs.locked, ws.locked);
+ results.push(log);
+ }
+ }
+ }
+ return JSON.stringify(results);
+ `)
+ want := `[["close","resolved",false,false],["close","resolved",false,false],` +
+ `["abort:source failed","rejected:source failed",false,false],["rejected:source failed",false,false],` +
+ `["close","resolved",false,false],["close","resolved",false,false],` +
+ `["abort:source failed","rejected:source failed",false,false],["rejected:source failed",false,false]]`
+ if got != want {
+ t.Fatalf("source settlement under backpressure = %s, want %s", got, want)
+ }
+}
+
+// 源流结束时所有已提交的异步写入都要完成,preventClose 只决定是否关闭目的地,不能跳过排空或丢失写入错误。
+func TestPipeToWaitsForQueuedWrites(t *testing.T) {
+ for _, preventClose := range []bool{false, true} {
+ for _, fail := range []bool{false, true} {
+ rt, _ := newTestRuntime(t)
+ must(rt.Set("preventClose", preventClose))
+ run(t, rt, `
+ globalThis.finishWrite = null;
+ globalThis.failWrite = null;
+ globalThis.chunks = [];
+ globalThis.closed = false;
+ globalThis.rs = new ReadableStream({ start(c) { c.enqueue("first"); c.enqueue("last"); c.close(); } });
+ globalThis.ws = new WritableStream({
+ write(chunk) {
+ chunks.push(chunk);
+ return new Promise((resolve, reject) => { finishWrite = resolve; failWrite = reject; });
+ },
+ close() { closed = true; },
+ }, { highWaterMark: 3 });
+ globalThis.piping = rs.pipeTo(ws, { preventClose });
+ `)
+ promise := rt.Get("piping").Export().(*goja.Promise)
+ if promise.State() != goja.PromiseStatePending || !rt.Get("ws").ToObject(rt).Get("locked").ToBoolean() {
+ t.Fatalf("pipe settled before its first write: preventClose=%v fail=%v", preventClose, fail)
+ }
+ run(t, rt, "finishWrite();")
+ if promise.State() != goja.PromiseStatePending || run(t, rt, "JSON.stringify(chunks)").String() != `["first","last"]` {
+ t.Fatalf("pipe did not wait for its last write: preventClose=%v fail=%v", preventClose, fail)
+ }
+ if fail {
+ run(t, rt, `failWrite("write failed");`)
+ if promise.State() != goja.PromiseStateRejected || promise.Result().String() != "write failed" {
+ t.Fatalf("write failure was lost: %v %v", promise.State(), promise.Result())
+ }
+ } else {
+ run(t, rt, "finishWrite();")
+ if promise.State() != goja.PromiseStateFulfilled || rt.Get("closed").ToBoolean() == preventClose {
+ t.Fatalf("pipe did not finish correctly: preventClose=%v state=%v", preventClose, promise.State())
+ }
+ }
+ if run(t, rt, "rs.locked || ws.locked").ToBoolean() {
+ t.Fatal("pipe kept a stream locked after settlement")
+ }
+ }
+ }
+}
+
+// 源流在异步写入期间出错时先排空已提交的分块,再以源错误中止目的地。
+func TestPipeToSourceErrorDrainsQueuedWrites(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ run(t, rt, `
+ globalThis.source = null;
+ globalThis.finishWrite = null;
+ globalThis.log = [];
+ globalThis.rs = new ReadableStream({ start(c) { source = c; c.enqueue(1); c.enqueue(2); } });
+ globalThis.ws = new WritableStream({
+ write(chunk) {
+ log.push(chunk);
+ return new Promise(resolve => { finishWrite = resolve; });
+ },
+ abort(reason) { log.push("abort:" + reason); },
+ }, { highWaterMark: 3 });
+ globalThis.piping = rs.pipeTo(ws);
+ `)
+ promise := rt.Get("piping").Export().(*goja.Promise)
+ run(t, rt, `source.error("source failed");`)
+ if promise.State() != goja.PromiseStatePending || run(t, rt, "JSON.stringify(log)").String() != `[1]` {
+ t.Fatal("pipe did not wait for its pending writes before aborting")
+ }
+ run(t, rt, "finishWrite();")
+ if promise.State() != goja.PromiseStatePending || run(t, rt, "JSON.stringify(log)").String() != `[1,2]` {
+ t.Fatal("pipe did not drain its queued write")
+ }
+ run(t, rt, "finishWrite();")
+ if promise.State() != goja.PromiseStateRejected || promise.Result().String() != "source failed" ||
+ run(t, rt, "JSON.stringify(log)").String() != `[1,2,"abort:source failed"]` {
+ t.Fatalf("source error was not propagated after draining: %v %v", promise.State(), promise.Result())
+ }
+}
+
+// 目的地在 pipeTo 开始前已经关闭:即使源流没有任何数据,管道也要以 TypeError 拒绝、取消源流并释放两端的锁,
+// 不能一直等待源数据。
+func TestPipeToDestinationClosedBeforePipe(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const log = [];
+ const rs = new ReadableStream({
+ cancel(reason) { log.push("cancel:" + (reason instanceof TypeError)); },
+ }, { highWaterMark: 0 });
+ const ws = new WritableStream();
+ const writer = ws.getWriter();
+ await writer.close();
+ writer.releaseLock();
+ log.push(await rs.pipeTo(ws).then(() => "resolved", (e) => "rejected:" + (e instanceof TypeError)));
+ log.push("locked:" + rs.locked + "," + ws.locked);
+ return JSON.stringify(log);
+ `)
+ if want := `["cancel:true","rejected:true","locked:false,false"]`; got != want {
+ t.Fatalf("pipeTo closed destination = %s, want %s", got, want)
+ }
+}
+
+// getReader 的选项字典缺少 mode 成员(或为 undefined/null)时按缺省值返回默认 reader;无法转换为字典的值与不支持
+// 的 mode 抛出 TypeError。
+func TestReadableStreamGetReaderOptionDefaults(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const results = [];
+ for (const options of [undefined, null, {}, { mode: undefined }]) {
+ const rs = new ReadableStream({ start(c) { c.enqueue("x"); c.close(); } });
+ results.push((await rs.getReader(options).read()).value);
+ }
+ for (const options of [{ mode: "byob" }, { mode: "other" }, 1]) {
+ try {
+ new ReadableStream().getReader(options);
+ results.push("no error");
+ } catch (e) {
+ results.push(e instanceof TypeError);
+ }
+ }
+ return JSON.stringify(results);
+ `)
+ if want := `["x","x","x","x",true,true,true]`; got != want {
+ t.Fatalf("getReader options = %s, want %s", got, want)
+ }
+}
+
+// ReadableStream.from 的迭代结果缺少 value 成员时按 undefined 入队;结果不是对象时流以 TypeError 出错。
+func TestReadableStreamFromIteratorResultMembers(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const iterable = (next) => ({ [Symbol.iterator]() { return { next }; } });
+ let count = 0;
+ const missing = ReadableStream.from(iterable(() => (count++ ? { done: true } : { done: false })));
+ const first = await missing.getReader().read();
+ const results = ["value" in first, first.value === undefined, first.done];
+ for (const result of [1, undefined]) {
+ try {
+ await ReadableStream.from(iterable(() => result)).getReader().read();
+ results.push("no error");
+ } catch (e) {
+ results.push(e instanceof TypeError);
+ }
+ }
+ return JSON.stringify(results);
+ `)
+ if want := `[true,true,false,true,true]`; got != want {
+ t.Fatalf("ReadableStream.from iterator results = %s, want %s", got, want)
+ }
+}
+
+func TestTeeBothBranchesReceiveSameChunks(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const rs = new ReadableStream({ start(c) { c.enqueue(1); c.enqueue(2); c.close(); } });
+ const [a, b] = rs.tee();
+ const readAll = async (stream) => {
+ const reader = stream.getReader();
+ const out = [];
+ for (;;) {
+ const r = await reader.read();
+ if (r.done) break;
+ out.push(r.value);
+ }
+ return out;
+ };
+ const [resultA, resultB] = await Promise.all([readAll(a), readAll(b)]);
+ return JSON.stringify([resultA, resultB]);
+ `)
+ if want := `[[1,2],[1,2]]`; got != want {
+ t.Fatalf("tee = %s, want %s", got, want)
+ }
+}
+
+func TestTeeCancelOnlyTakesEffectWhenBothBranchesCancel(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const log = [];
+ const rs = new ReadableStream({
+ start(c) { c.enqueue(1); },
+ cancel(reason) { log.push("source-cancel:" + JSON.stringify(reason)); },
+ });
+ const [a, b] = rs.tee();
+ // 不能 await a.cancel(...):它返回的 Promise 要等两条分支都 cancel 之后才会落定,在此之前 await 会卡死。
+ const pendingA = a.cancel("a-reason");
+ const afterOnlyOne = log.length;
+ await b.cancel("b-reason");
+ await pendingA;
+ return JSON.stringify([afterOnlyOne, log]);
+ `)
+ if want := `[0,["source-cancel:[\"a-reason\",\"b-reason\"]"]]`; got != want {
+ t.Fatalf("tee cancel = %s, want %s", got, want)
+ }
+}
+
+func TestReadableStreamFromSyncAndAsyncIterable(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := runAsync(t, rt, `
+ const readAll = async (stream) => {
+ const reader = stream.getReader();
+ const out = [];
+ for (;;) {
+ const r = await reader.read();
+ if (r.done) break;
+ out.push(r.value);
+ }
+ return out;
+ };
+ const fromArray = await readAll(ReadableStream.from([1, 2, 3]));
+ const fromAsyncIterator = await readAll(ReadableStream.from(ReadableStream.from(["a", "b"]).values()));
+ return JSON.stringify([fromArray, fromAsyncIterator]);
+ `)
+ if want := `[[1,2,3],["a","b"]]`; got != want {
+ t.Fatalf("ReadableStream.from = %s, want %s", got, want)
+ }
+}
+
+func TestCountAndByteLengthQueuingStrategy(t *testing.T) {
+ rt, _ := newTestRuntime(t)
+ got := run(t, rt, `(() => {
+ const count = new CountQueuingStrategy({ highWaterMark: 3 });
+ const byteLength = new ByteLengthQueuingStrategy({ highWaterMark: 10 });
+ return JSON.stringify([
+ count.highWaterMark, count.size("anything"),
+ byteLength.highWaterMark, byteLength.size({ byteLength: 7 }),
+ ]);
+ })()`)
+ if want := `[3,1,10,7]`; got.String() != want {
+ t.Fatalf("queuing strategies = %s, want %s", got.String(), want)
+ }
+}
+
+func TestNewReadableStreamFromGoBridgePushesChunks(t *testing.T) {
+ rt, h := newTestRuntime(t)
+ stream := h.NewReadableStream(nil, func(controller goja.Value) goja.Value {
+ c, _ := readableControllerOf(controller)
+ readableControllerEnqueue(h, c, rt.ToValue("from-go"))
+ readableControllerClose(h, c)
+ return nil
+ }, nil, 1, nil)
+ must(rt.Set("rs", stream))
+
+ got := runAsync(t, rt, `
+ const reader = rs.getReader();
+ const results = [await reader.read(), await reader.read()];
+ return JSON.stringify(results);
+ `)
+ want := `[{"value":"from-go","done":false},{"done":true}]`
+ if got != want {
+ t.Fatalf("Go bridge readable = %s, want %s", got, want)
+ }
+}
+
+func TestIsReadableAndWritableStreamIdentity(t *testing.T) {
+ rt, h := newTestRuntime(t)
+ run(t, rt, `globalThis.rs = new ReadableStream(); globalThis.ws = new WritableStream(); globalThis.plain = {};`)
+ if !h.IsReadableStream(rt.Get("rs")) {
+ t.Fatal("IsReadableStream(rs) = false, want true")
+ }
+ if h.IsReadableStream(rt.Get("ws")) {
+ t.Fatal("IsReadableStream(ws) = true, want false")
+ }
+ if !h.IsWritableStream(rt.Get("ws")) {
+ t.Fatal("IsWritableStream(ws) = false, want true")
+ }
+ if h.IsReadableStream(rt.Get("plain")) || h.IsWritableStream(rt.Get("plain")) {
+ t.Fatal("plain object misidentified as a stream")
+ }
+}
diff --git a/kernel/plugin/streams/transform.go b/kernel/plugin/streams/transform.go
new file mode 100644
index 0000000000..cb14651f09
--- /dev/null
+++ b/kernel/plugin/streams/transform.go
@@ -0,0 +1,324 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "reflect"
+
+ "github.com/dop251/goja"
+)
+
+// transformState 对应 TransformStream 的内部槛:readable 与 writable 一对流,由 controller 的 enqueue/
+// terminate/error 操作桥接。
+type transformState struct {
+ expandoProperties
+
+ host *Host
+
+ readable *readableState
+ writable *writableState
+
+ backpressure bool
+ backpressureChange deferred
+
+ controller *transformController
+
+ self *goja.Object
+}
+
+// transformController 对应 TransformStreamDefaultController 的内部槛。
+type transformController struct {
+ expandoProperties
+
+ host *Host
+ stream *transformState
+
+ transformAlgorithm func(chunk goja.Value) goja.Value
+ flushAlgorithm func() goja.Value
+ cancelAlgorithm func(reason goja.Value) goja.Value
+
+ finishPromise *deferred // 非 nil 表示 abort/close 已经在排空,避免重复触发
+
+ self *goja.Object
+}
+
+var (
+ transformStateType = reflect.TypeOf((*transformState)(nil))
+ transformControllerType = reflect.TypeOf((*transformController)(nil))
+)
+
+func transformStateOf(value goja.Value) (*transformState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != transformStateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*transformState)
+ return state, ok
+}
+
+func transformControllerOf(value goja.Value) (*transformController, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != transformControllerType {
+ return nil, false
+ }
+ state, ok := object.Export().(*transformController)
+ return state, ok
+}
+
+func (c *transformController) jsValue() *goja.Object {
+ if c.self == nil {
+ object := c.host.rt.NewDynamicObject(c)
+ must(object.SetPrototype(c.host.transformControllerProto))
+ c.self = object
+ }
+ return c.self
+}
+
+// transformStreamSetBackpressure 对应 TransformStreamSetBackpressure:兑定旧的 backpressureChange Promise
+// 并换上一个新的 pending Promise。
+func transformStreamSetBackpressure(stream *transformState, backpressure bool) {
+ if stream.backpressureChange.promise != nil {
+ must0(stream.backpressureChange.resolve(goja.Undefined()))
+ }
+ stream.backpressureChange = newDeferred(stream.host.rt)
+ stream.backpressure = backpressure
+}
+
+// transformStreamErrorWritableAndUnblockWrite 对应 TransformStreamErrorWritableAndUnblockWrite。
+func transformStreamErrorWritableAndUnblockWrite(h *Host, stream *transformState, reason goja.Value) {
+ transformControllerClearAlgorithms(stream.controller)
+ writableControllerErrorIfNeeded(h, stream.writable.controller, reason)
+ if stream.backpressure {
+ transformStreamSetBackpressure(stream, false)
+ }
+}
+
+// transformStreamError 对应 TransformStreamError。
+func transformStreamError(h *Host, stream *transformState, reason goja.Value) {
+ readableControllerError(h, stream.readable.controller, reason)
+ transformStreamErrorWritableAndUnblockWrite(h, stream, reason)
+}
+
+func transformControllerClearAlgorithms(c *transformController) {
+ c.transformAlgorithm = nil
+ c.flushAlgorithm = nil
+ c.cancelAlgorithm = nil
+}
+
+// transformStreamDefaultSinkWriteAlgorithm 对应 TransformStreamDefaultSinkWriteAlgorithm:writable 侧的
+// write() 落到这里,若当前存在背压需要等待 readable 侧消费后才能继续转换。
+func transformStreamDefaultSinkWriteAlgorithm(h *Host, stream *transformState, chunk goja.Value) goja.Value {
+ if !stream.backpressure {
+ return transformControllerPerformTransform(h, stream.controller, chunk)
+ }
+
+ wait := stream.backpressureChange
+ promise, resolve, reject := h.rt.NewPromise()
+ awaitResult(h.rt, wait.value(h.rt), func(goja.Value) {
+ if stream.writable.status == writableErroring {
+ must0(reject(stream.writable.storedError))
+ return
+ }
+ result := transformControllerPerformTransform(h, stream.controller, chunk)
+ awaitResult(h.rt, result, func(v goja.Value) { must0(resolve(v)) }, func(r goja.Value) { must0(reject(r)) })
+ }, func(reason goja.Value) { must0(reject(reason)) })
+ return h.rt.ToValue(promise)
+}
+
+// transformControllerPerformTransform 对应 TransformStreamDefaultControllerPerformTransform:转换算法出错时
+// 把错误同时灌给整条 TransformStream。
+func transformControllerPerformTransform(h *Host, c *transformController, chunk goja.Value) goja.Value {
+ var result goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ reason := panicToReason(h.rt, r)
+ transformStreamError(h, c.stream, reason)
+ result = newRejectedPromise(h.rt, reason)
+ ok = true
+ }
+ }()
+ result = c.transformAlgorithm(chunk)
+ return true
+ }()
+ if !settled {
+ return newRejectedPromise(h.rt, goja.Undefined())
+ }
+
+ promise, resolve, reject := h.rt.NewPromise()
+ awaitResult(h.rt, orUndefined(result), func(v goja.Value) {
+ must0(resolve(v))
+ }, func(reason goja.Value) {
+ transformStreamError(h, c.stream, reason)
+ must0(reject(reason))
+ })
+ return h.rt.ToValue(promise)
+}
+
+// transformStreamDefaultSinkAbortAlgorithm 对应 TransformStreamDefaultSinkAbortAlgorithm。
+func transformStreamDefaultSinkAbortAlgorithm(h *Host, stream *transformState, reason goja.Value) goja.Value {
+ c := stream.controller
+ if c.finishPromise != nil {
+ return c.finishPromise.value(h.rt)
+ }
+ finish := newDeferred(h.rt)
+ c.finishPromise = &finish
+
+ cancel := c.cancelAlgorithm
+ var cancelResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ cancelResult = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ ok = true
+ }
+ }()
+ if cancel != nil {
+ cancelResult = cancel(reason)
+ } else {
+ cancelResult = newResolvedPromise(h.rt, goja.Undefined())
+ }
+ return true
+ }()
+ transformControllerClearAlgorithms(c)
+ if !settled {
+ return finish.value(h.rt)
+ }
+
+ readable := stream.readable
+ awaitResult(h.rt, orUndefined(cancelResult), func(goja.Value) {
+ if readable.status == statusErrored {
+ must0(finish.reject(readable.storedError))
+ } else {
+ readableControllerError(h, readable.controller, reason)
+ must0(finish.resolve(goja.Undefined()))
+ }
+ }, func(r goja.Value) {
+ readableControllerError(h, readable.controller, r)
+ must0(finish.reject(r))
+ })
+ return finish.value(h.rt)
+}
+
+// transformStreamDefaultSinkCloseAlgorithm 对应 TransformStreamDefaultSinkCloseAlgorithm。
+func transformStreamDefaultSinkCloseAlgorithm(h *Host, stream *transformState) goja.Value {
+ c := stream.controller
+ if c.finishPromise != nil {
+ return c.finishPromise.value(h.rt)
+ }
+ finish := newDeferred(h.rt)
+ c.finishPromise = &finish
+
+ flush := c.flushAlgorithm
+ var flushResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ flushResult = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ ok = true
+ }
+ }()
+ if flush != nil {
+ flushResult = flush()
+ } else {
+ flushResult = newResolvedPromise(h.rt, goja.Undefined())
+ }
+ return true
+ }()
+ transformControllerClearAlgorithms(c)
+ if !settled {
+ return finish.value(h.rt)
+ }
+
+ readable := stream.readable
+ awaitResult(h.rt, orUndefined(flushResult), func(goja.Value) {
+ if readable.status == statusErrored {
+ must0(finish.reject(readable.storedError))
+ } else {
+ readableControllerClose(h, readable.controller)
+ must0(finish.resolve(goja.Undefined()))
+ }
+ }, func(r goja.Value) {
+ readableControllerError(h, readable.controller, r)
+ must0(finish.reject(r))
+ })
+ return finish.value(h.rt)
+}
+
+// transformStreamDefaultSourcePullAlgorithm 对应 TransformStreamDefaultSourcePullAlgorithm:解除背压以放行
+// 被阻塞的 write(),返回的 Promise 在下一次背压重新建立(或流结束)时兑定。
+func transformStreamDefaultSourcePullAlgorithm(stream *transformState) goja.Value {
+ transformStreamSetBackpressure(stream, false)
+ return stream.backpressureChange.value(stream.host.rt)
+}
+
+// setUpTransformStreamDefaultController 对应 SetUpTransformStreamDefaultController。
+func setUpTransformStreamDefaultController(h *Host, stream *transformState,
+ transform func(chunk goja.Value) goja.Value, flush func() goja.Value, cancel func(reason goja.Value) goja.Value) {
+ controller := &transformController{host: h, stream: stream, transformAlgorithm: transform, flushAlgorithm: flush, cancelAlgorithm: cancel}
+ stream.controller = controller
+}
+
+// transformControllerDesiredSize 对应 controller.desiredSize:转发到 readable 侧 controller。
+func transformControllerDesiredSize(c *transformController) (float64, bool) {
+ return readableControllerDesiredSize(c.stream.readable.controller)
+}
+
+// transformControllerEnqueue 对应 TransformStreamDefaultControllerEnqueue。
+func transformControllerEnqueue(h *Host, c *transformController, chunk goja.Value) {
+ stream := c.stream
+ readableController := stream.readable.controller
+ if !readableControllerCanCloseOrEnqueue(readableController) {
+ panic(typeErrorf(h.rt, "TransformStream's readable side is not in a state that permits enqueue"))
+ }
+
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ reason := panicToReason(h.rt, r)
+ transformStreamErrorWritableAndUnblockWrite(h, stream, reason)
+ panic(reason)
+ }
+ }()
+ readableControllerEnqueue(h, readableController, chunk)
+ return true
+ }()
+ if !settled {
+ return
+ }
+
+ backpressure := !readableControllerShouldCallPull(readableController)
+ if backpressure != stream.backpressure {
+ transformStreamSetBackpressure(stream, true)
+ }
+}
+
+// transformControllerTerminate 对应 TransformStreamDefaultControllerTerminate。
+func transformControllerTerminate(h *Host, c *transformController) {
+ stream := c.stream
+ readableControllerClose(h, stream.readable.controller)
+ transformStreamErrorWritableAndUnblockWrite(h, stream, typeErrorf(h.rt, "TransformStream terminated"))
+}
+
+// NewTransformStream 是 Go 侧构造默认 TransformStream 的入口,供 kernel/plugin 的 Go 桥接代码使用(如把编码/
+// 压缩之类的转换实现为流)。transform/flush/cancel 对应规范同名算法,均可为 nil;transform 缺省时为恒等转换
+// (直接把 chunk 原样 enqueue 到 readable 侧)。
+func (h *Host) NewTransformStream(transform func(chunk, controller goja.Value) goja.Value, flush func(controller goja.Value) goja.Value,
+ cancel func(reason goja.Value) goja.Value, writableHWM, readableHWM float64,
+ writableSizeAlgorithm, readableSizeAlgorithm func(goja.Value) float64) *goja.Object {
+ return h.newTransformStreamObject(transform, flush, cancel, writableHWM, readableHWM, writableSizeAlgorithm, readableSizeAlgorithm, nil)
+}
diff --git a/kernel/plugin/streams/transform_prototype.go b/kernel/plugin/streams/transform_prototype.go
new file mode 100644
index 0000000000..c11984e6eb
--- /dev/null
+++ b/kernel/plugin/streams/transform_prototype.go
@@ -0,0 +1,229 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import "github.com/dop251/goja"
+
+// newTransformControllerPrototype 构造 TransformStreamDefaultController.prototype:desiredSize 访问器,
+// enqueue/error/terminate 方法。
+func newTransformControllerPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *transformController {
+ c, ok := transformControllerOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "TransformStreamDefaultController.prototype.%s called on an incompatible receiver", method))
+ }
+ return c
+ }
+
+ defineGetter(rt, prototype, "desiredSize", func(call goja.FunctionCall) goja.Value {
+ size, ok := transformControllerDesiredSize(self(call, "desiredSize"))
+ if !ok {
+ return goja.Null()
+ }
+ return rt.ToValue(size)
+ })
+ defineMethod(rt, prototype, "enqueue", 1, func(call goja.FunctionCall) goja.Value {
+ transformControllerEnqueue(h, self(call, "enqueue"), call.Argument(0))
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "error", 1, func(call goja.FunctionCall) goja.Value {
+ c := self(call, "error")
+ transformStreamError(h, c.stream, call.Argument(0))
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "terminate", 0, func(call goja.FunctionCall) goja.Value {
+ transformControllerTerminate(h, self(call, "terminate"))
+ return goja.Undefined()
+ })
+ defineToStringTag(rt, prototype, "TransformStreamDefaultController")
+ return prototype
+}
+
+// newTransformStreamPrototype 构造 TransformStream.prototype:readable/writable 访问器。
+func newTransformStreamPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *transformState {
+ s, ok := transformStateOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "TransformStream.prototype.%s called on an incompatible receiver", method))
+ }
+ return s
+ }
+ defineGetter(rt, prototype, "readable", func(call goja.FunctionCall) goja.Value {
+ return self(call, "readable").readable.self
+ })
+ defineGetter(rt, prototype, "writable", func(call goja.FunctionCall) goja.Value {
+ return self(call, "writable").writable.self
+ })
+ defineToStringTag(rt, prototype, "TransformStream")
+ return prototype
+}
+
+// newTransformStreamObject 按规范 InitializeTransformStream + SetUpTransformStreamDefaultController 构造一个
+// TransformStream 实例:先建好 readable/writable 两侧(其算法通过 stream.controller 延迟查找,不要求
+// controller 提前存在),再建 controller 并包装 transform/flush/cancel(可直接引用 controller,构造顺序上
+// controller 已经存在),最后用 controller 调用 start(如果提供)。
+func (h *Host) newTransformStreamObject(
+ transform func(chunk, controller goja.Value) goja.Value,
+ flush func(controller goja.Value) goja.Value,
+ cancel func(reason goja.Value) goja.Value,
+ writableHWM, readableHWM float64,
+ writableSizeAlgorithm, readableSizeAlgorithm func(goja.Value) float64,
+ start func(controller goja.Value) goja.Value,
+) *goja.Object {
+ stream := &transformState{host: h}
+
+ // readable 与 writable 两侧的 start 算法共用同一个 Promise:在 transformer 自己的 start()(如果提供)
+ // 落定前,两侧的 controller.started 都保持 false,与规范 InitializeTransformStream 一致。
+ startShared := newDeferred(h.rt)
+ sharedStart := func(goja.Value) goja.Value { return startShared.value(h.rt) }
+
+ stream.writable = &writableState{host: h, status: writableWritable}
+ h.newWritableStreamObject(stream.writable)
+ setUpWritableStreamDefaultController(h, stream.writable,
+ sharedStart,
+ func(chunk goja.Value) goja.Value { return transformStreamDefaultSinkWriteAlgorithm(h, stream, chunk) },
+ func() goja.Value { return transformStreamDefaultSinkCloseAlgorithm(h, stream) },
+ func(reason goja.Value) goja.Value { return transformStreamDefaultSinkAbortAlgorithm(h, stream, reason) },
+ writableHWM, writableSizeAlgorithm)
+
+ stream.readable = &readableState{host: h, status: statusReadable}
+ h.newReadableStreamObject(stream.readable)
+ setUpReadableStreamDefaultController(h, stream.readable,
+ sharedStart,
+ func(goja.Value) goja.Value { return transformStreamDefaultSourcePullAlgorithm(stream) },
+ func(reason goja.Value) goja.Value {
+ transformStreamErrorWritableAndUnblockWrite(h, stream, reason)
+ return nil
+ },
+ readableHWM, readableSizeAlgorithm)
+
+ transformStreamSetBackpressure(stream, true)
+
+ controller := &transformController{host: h, stream: stream}
+ controller.transformAlgorithm = func(chunk goja.Value) goja.Value {
+ if transform != nil {
+ return transform(chunk, controller.jsValue())
+ }
+ // 缺省为恒等转换:直接把 chunk 原样 enqueue 到 readable 侧。
+ transformControllerEnqueue(h, controller, chunk)
+ return nil
+ }
+ if flush != nil {
+ controller.flushAlgorithm = func() goja.Value { return flush(controller.jsValue()) }
+ }
+ controller.cancelAlgorithm = cancel
+ stream.controller = controller
+
+ object := h.rt.NewDynamicObject(stream)
+ must(object.SetPrototype(h.transformStreamPrototype))
+ stream.self = object
+
+ // 调用 transformer 自己的 start(如果提供),用其结果落定两侧共用的 startShared:readable/writable
+ // controller 的 CallPullIfNeeded/AdvanceQueueIfNeeded 都要等它落定才会真正开始工作。
+ var startResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ reason := panicToReason(h.rt, r)
+ transformStreamError(h, stream, reason)
+ must0(startShared.reject(reason))
+ ok = false
+ }
+ }()
+ if start != nil {
+ startResult = start(controller.jsValue())
+ }
+ return true
+ }()
+ if settled {
+ awaitResult(h.rt, orUndefined(startResult), func(goja.Value) {
+ must0(startShared.resolve(goja.Undefined()))
+ }, func(reason goja.Value) {
+ transformStreamError(h, stream, reason)
+ must0(startShared.reject(reason))
+ })
+ }
+ return object
+}
+
+// newTransformStreamConstructor 构造 TransformStream 全局构造函数:
+// new TransformStream(transformer, writableStrategy, readableStrategy)。不支持
+// transformer.readableType/writableType(字节流变体),遇到会抛错。
+func (h *Host) newTransformStreamConstructor() *goja.Object {
+ rt := h.rt
+ return newInterfaceConstructor(rt, "TransformStream", 0, h.transformStreamPrototype, func(call goja.ConstructorCall) *goja.Object {
+ transformer := call.Argument(0)
+ var transformerObj *goja.Object
+ if isJsValueNotNull(transformer) {
+ var ok bool
+ transformerObj, ok = transformer.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "TransformStream: Argument 1 can't be converted to a dictionary"))
+ }
+ if t := transformerObj.Get("readableType"); isJsValueNotNull(t) {
+ panic(typeErrorf(rt, "TransformStream: readableType is not supported"))
+ }
+ if t := transformerObj.Get("writableType"); isJsValueNotNull(t) {
+ panic(typeErrorf(rt, "TransformStream: writableType is not supported"))
+ }
+ }
+
+ writableHWM := extractHighWaterMark(rt, call.Argument(1), 1)
+ writableSizeAlgorithm := extractSizeAlgorithm(rt, call.Argument(1))
+ readableHWM := extractHighWaterMark(rt, call.Argument(2), 0)
+ readableSizeAlgorithm := extractSizeAlgorithm(rt, call.Argument(2))
+
+ transform := wrapTransformerTransform(rt, transformerObj)
+ flush := wrapUnderlyingMethod(rt, transformerObj, "flush")
+ cancel := wrapUnderlyingMethod(rt, transformerObj, "cancel")
+ start := wrapUnderlyingMethod(rt, transformerObj, "start")
+
+ object := h.newTransformStreamObject(transform, flush, cancel, writableHWM, readableHWM,
+ writableSizeAlgorithm, readableSizeAlgorithm, start)
+ must(object.SetPrototype(call.This.Prototype()))
+ return object
+ })
+}
+
+// wrapTransformerTransform 包装 transformer.transform(chunk, controller):以 transformer 为 this 调用,缺省
+// (未提供 transform 成员)返回 nil,交由调用方套用恒等转换。
+func wrapTransformerTransform(rt *goja.Runtime, transformer *goja.Object) func(chunk, controller goja.Value) goja.Value {
+ if transformer == nil {
+ return nil
+ }
+ method := transformer.Get("transform")
+ if method == nil || goja.IsUndefined(method) {
+ return nil
+ }
+ fn, ok := goja.AssertFunction(method)
+ if !ok {
+ panic(typeErrorf(rt, "transform member of transformer must be a function"))
+ }
+ return func(chunk, controller goja.Value) goja.Value {
+ result, err := fn(transformer, chunk, controller)
+ if err != nil {
+ panic(err)
+ }
+ return result
+ }
+}
diff --git a/kernel/plugin/streams/webidl.go b/kernel/plugin/streams/webidl.go
new file mode 100644
index 0000000000..020bdcdf64
--- /dev/null
+++ b/kernel/plugin/streams/webidl.go
@@ -0,0 +1,125 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "slices"
+
+ "github.com/dop251/goja"
+)
+
+// expandoProperties 保存脚本在宿主对象上自行添加的属性,使流对象能像浏览器中的平台对象一样挂载自定义属性、
+// 被子类用类字段扩展;内建成员都由原型上的访问器与方法提供,不经过这里。与 kernel/plugin/formdata/webidl.go
+// 的同名类型同构:本包不依赖 formdata 包,因此复制一份这些通用、不含业务逻辑的 WebIDL 辅助。
+type expandoProperties struct {
+ keys []string
+ values map[string]goja.Value
+}
+
+func (e *expandoProperties) Get(key string) goja.Value { return e.values[key] }
+
+func (e *expandoProperties) Set(key string, value goja.Value) bool {
+ if e.values == nil {
+ e.values = map[string]goja.Value{}
+ }
+ if _, ok := e.values[key]; !ok {
+ e.keys = append(e.keys, key)
+ }
+ e.values[key] = value
+ return true
+}
+
+func (e *expandoProperties) Has(key string) bool {
+ _, ok := e.values[key]
+ return ok
+}
+
+func (e *expandoProperties) Delete(key string) bool {
+ if _, ok := e.values[key]; ok {
+ delete(e.values, key)
+ e.keys = slices.DeleteFunc(e.keys, func(k string) bool { return k == key })
+ }
+ return true
+}
+
+func (e *expandoProperties) Keys() []string { return slices.Clone(e.keys) }
+
+// newMethod 创建 name 与 length 符合规范的原生函数;goja 默认以 Go 函数的完整限定名作为函数的 name。
+func newMethod(rt *goja.Runtime, name string, length int, fn func(goja.FunctionCall) goja.Value) *goja.Object {
+ method := rt.ToValue(fn).(*goja.Object)
+ must(method.DefineDataProperty("name", rt.ToValue(name), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ must(method.DefineDataProperty("length", rt.ToValue(length), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return method
+}
+
+// defineMethod 按 WebIDL 操作的属性特性(可写、可配置、可枚举)在 target 上定义方法。
+func defineMethod(rt *goja.Runtime, target *goja.Object, name string, length int, fn func(goja.FunctionCall) goja.Value) {
+ method := newMethod(rt, name, length, fn)
+ must(target.DefineDataProperty(name, method, goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_TRUE))
+}
+
+// defineGetter 按 WebIDL 只读属性的特性(无 setter、可配置、可枚举)在 target 上定义访问器。
+func defineGetter(rt *goja.Runtime, target *goja.Object, name string, get func(goja.FunctionCall) goja.Value) {
+ getter := newMethod(rt, "get "+name, 0, get)
+ must(target.DefineAccessorProperty(name, getter, nil, goja.FLAG_TRUE, goja.FLAG_TRUE))
+}
+
+// defineToStringTag 定义 Symbol.toStringTag,使 Object.prototype.toString 返回 [object <tag>]。
+func defineToStringTag(rt *goja.Runtime, target *goja.Object, tag string) {
+ must(target.DefineDataPropertySymbol(goja.SymToStringTag, rt.ToValue(tag), goja.FLAG_FALSE, goja.FLAG_TRUE,
+ goja.FLAG_FALSE))
+}
+
+// newInterfaceConstructor 创建接口的构造函数,并按 WebIDL 设置 name、length、prototype 与 prototype.constructor
+// 的属性特性。construct 应以 call.This.Prototype() 作为实例原型,使子类构造的实例继承子类的原型。
+func newInterfaceConstructor(rt *goja.Runtime, name string, length int, prototype *goja.Object,
+ construct func(goja.ConstructorCall) *goja.Object) *goja.Object {
+ constructor := rt.ToValue(construct).(*goja.Object)
+ must(constructor.DefineDataProperty("name", rt.ToValue(name), goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ must(constructor.DefineDataProperty("length", rt.ToValue(length), goja.FLAG_FALSE, goja.FLAG_TRUE,
+ goja.FLAG_FALSE))
+ must(constructor.DefineDataProperty("prototype", prototype, goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_FALSE))
+ must(prototype.DefineDataProperty("constructor", constructor, goja.FLAG_TRUE, goja.FLAG_TRUE, goja.FLAG_FALSE))
+ return constructor
+}
+
+// illegalConstructor 构造一个按 WebIDL 规范不可直接实例化的接口的构造函数:用 new 调用会抛出 TypeError,与
+// kernel/plugin/abort 的 AbortSignal 构造函数一致(goja 以 ConstructorCall 签名注册的函数本就只能通过 new 调用)。
+func illegalConstructor(rt *goja.Runtime, name string, prototype *goja.Object) *goja.Object {
+ return newInterfaceConstructor(rt, name, 0, prototype, func(goja.ConstructorCall) *goja.Object {
+ panic(rt.NewTypeError("Illegal constructor"))
+ })
+}
+
+// must 在 err 非 nil 时 panic;仅用于"失败说明调用方传参有编程错误"的内部断言场景(如重复定义同名属性),不用于
+// 可能来自脚本输入的失败路径。
+func must(err error) {
+ if err != nil {
+ panic(err)
+ }
+}
+
+// dictMember 读取字典对象 object 上名为 name 的成员,缺失或为 undefined 时返回 nil;调用方据此套用默认值,
+// 不能直接对 Get 的结果调用 ToBoolean/String/ToInteger 等方法——goja 的 Get 在属性不存在时返回 Go 的 nil
+// (不是脚本意义上的 undefined 值),对 nil 调用这些方法会触发 nil 指针解引用而不是产生一个"假值"。
+func dictMember(object *goja.Object, name string) goja.Value {
+ value := object.Get(name)
+ if value == nil || goja.IsUndefined(value) {
+ return nil
+ }
+ return value
+}
diff --git a/kernel/plugin/streams/writable.go b/kernel/plugin/streams/writable.go
new file mode 100644
index 0000000000..bbb53443cf
--- /dev/null
+++ b/kernel/plugin/streams/writable.go
@@ -0,0 +1,707 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import (
+ "reflect"
+
+ "github.com/dop251/goja"
+)
+
+// writableStatus 对应规范里流的 [[state]]:writable、erroring、closed 或 errored。
+type writableStatus int
+
+const (
+ writableWritable writableStatus = iota
+ writableErroring
+ writableClosed
+ writableErrored
+)
+
+// writePromiseCapability 是一次 write() 调用或 close 请求对应的 Promise 三元组。
+type writePromiseCapability struct {
+ resolve func(any) error
+ reject func(any) error
+}
+
+func (c *writePromiseCapability) settle(ok bool, value goja.Value) {
+ if c == nil {
+ return
+ }
+ var err error
+ if ok {
+ err = c.resolve(value)
+ } else {
+ err = c.reject(value)
+ }
+ if err != nil {
+ panic(err)
+ }
+}
+
+// pendingAbortRequest 对应规范 [[pendingAbortRequest]]。
+type pendingAbortRequest struct {
+ promise deferred
+ reason goja.Value
+ wasAlreadyErroring bool
+}
+
+// writableState 对应 WritableStream 的内部槛。
+type writableState struct {
+ expandoProperties
+
+ host *Host
+
+ status writableStatus
+ storedError goja.Value
+ backpressure bool
+
+ writer *writableWriterState
+ controller *writableController
+
+ writeRequests []*writePromiseCapability
+ inFlightWriteRequest *writePromiseCapability
+ closeRequest *writePromiseCapability
+ inFlightCloseRequest *writePromiseCapability
+ pendingAbort *pendingAbortRequest
+
+ self *goja.Object
+}
+
+// writableController 对应 WritableStreamDefaultController 的内部槛。
+type writableController struct {
+ expandoProperties
+
+ host *Host
+ stream *writableState
+ queue valueQueue
+
+ started bool
+ strategyHWM float64
+
+ sizeAlgorithm func(chunk goja.Value) float64
+ writeAlgorithm func(chunk goja.Value) goja.Value
+ closeAlgorithm func() goja.Value
+ abortAlgorithm func(reason goja.Value) goja.Value
+
+ self *goja.Object
+}
+
+// writableWriterState 对应 WritableStreamDefaultWriter 的内部槛。
+type writableWriterState struct {
+ expandoProperties
+
+ host *Host
+ stream *writableState
+ ready deferred
+ closed deferred
+
+ self *goja.Object
+}
+
+var (
+ writableStateType = reflect.TypeOf((*writableState)(nil))
+ writableControllerType = reflect.TypeOf((*writableController)(nil))
+ writableWriterType = reflect.TypeOf((*writableWriterState)(nil))
+)
+
+func writableStateOf(value goja.Value) (*writableState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != writableStateType {
+ return nil, false
+ }
+ state, ok := object.Export().(*writableState)
+ return state, ok
+}
+
+func writableControllerOf(value goja.Value) (*writableController, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != writableControllerType {
+ return nil, false
+ }
+ state, ok := object.Export().(*writableController)
+ return state, ok
+}
+
+func writableWriterOf(value goja.Value) (*writableWriterState, bool) {
+ object, ok := value.(*goja.Object)
+ if !ok || object.ExportType() != writableWriterType {
+ return nil, false
+ }
+ state, ok := object.Export().(*writableWriterState)
+ return state, ok
+}
+
+// IsWritableStream 判断 value 是否是本 Host 构造出的 WritableStream 实例。
+func (h *Host) IsWritableStream(value goja.Value) bool {
+ s, ok := writableStateOf(value)
+ return ok && s != nil
+}
+
+func isWritableStreamLocked(stream *writableState) bool { return stream.writer != nil }
+
+func writableCloseQueuedOrInFlight(stream *writableState) bool {
+ return stream.closeRequest != nil || stream.inFlightCloseRequest != nil
+}
+
+func (c *writableController) jsValue() *goja.Object {
+ if c.self == nil {
+ object := c.host.rt.NewDynamicObject(c)
+ must(object.SetPrototype(c.host.writableControllerProto))
+ c.self = object
+ }
+ return c.self
+}
+
+func (w *writableWriterState) jsValue() *goja.Object {
+ if w.self == nil {
+ object := w.host.rt.NewDynamicObject(w)
+ must(object.SetPrototype(w.host.writableWriterProto))
+ w.self = object
+ }
+ return w.self
+}
+
+func (h *Host) newWritableStreamObject(state *writableState) *goja.Object {
+ object := h.rt.NewDynamicObject(state)
+ must(object.SetPrototype(h.writableStreamPrototype))
+ state.self = object
+ return object
+}
+
+// writableControllerGetChunkSize 对应 WritableStreamDefaultControllerGetChunkSize:size 算法抛错时按规范吞掉
+// 异常、退化为大小 1,让调用方随后按流的当前状态给出恰当的拒绝原因(通常是"流已关闭"这类更贴切的错误),
+// 而不是把 size 算法本身的异常(或者流已关闭后 sizeAlgorithm 已被清空导致的调用失败)直接抛给调用方。
+func writableControllerGetChunkSize(h *Host, c *writableController, chunk goja.Value) (size float64) {
+ defer func() {
+ if r := recover(); r != nil {
+ writableControllerErrorIfNeeded(h, c, panicToReason(h.rt, r))
+ size = 1
+ }
+ }()
+ return c.sizeAlgorithm(chunk)
+}
+
+// NewWritableStream 是 Go 侧构造默认 WritableStream 的入口,供 kernel/plugin 的 Go 桥接代码使用。start/write/
+// close/abort 对应规范同名算法,均可为 nil(视为未提供);返回值可以是任意值或一个 Promise(经 awaitResult
+// 等待)。sizeAlgorithm 为 nil 时使用默认的"每个 chunk 大小为 1"算法。调用方必须已经在 runtime 所在的事件
+// 循环线程上。
+func (h *Host) NewWritableStream(start, write func(arg goja.Value) goja.Value, close func() goja.Value,
+ abort func(reason goja.Value) goja.Value, highWaterMark float64, sizeAlgorithm func(goja.Value) float64) *goja.Object {
+ if sizeAlgorithm == nil {
+ sizeAlgorithm = defaultSizeAlgorithm
+ }
+ stream := &writableState{host: h, status: writableWritable}
+ object := h.newWritableStreamObject(stream)
+ setUpWritableStreamDefaultController(h, stream, orNoOp(start), orNoOp(write), close, orNoOp(abort), highWaterMark, sizeAlgorithm)
+ return object
+}
+
+// ──────────────────────────── WritableStreamDefaultController 内部算法 ────────────────────────────
+
+// setUpWritableStreamDefaultController 对应 SetUpWritableStreamDefaultController:本包不暴露 controller.signal
+// (规范允许的底层 sink 通过 AbortSignal 感知中止的途径),sink 只能通过 abort 算法的 reason 参数感知中止,
+// 是对规范的已知裁剪。
+func setUpWritableStreamDefaultController(h *Host, stream *writableState,
+ start func(controller goja.Value) goja.Value, write func(chunk goja.Value) goja.Value,
+ close func() goja.Value, abort func(reason goja.Value) goja.Value,
+ highWaterMark float64, sizeAlgorithm func(goja.Value) float64) {
+ controller := &writableController{
+ host: h, stream: stream, strategyHWM: highWaterMark, sizeAlgorithm: sizeAlgorithm,
+ writeAlgorithm: write, closeAlgorithm: close, abortAlgorithm: abort,
+ }
+ stream.controller = controller
+
+ backpressure := writableControllerBackpressure(controller)
+ writableStreamUpdateBackpressure(stream, backpressure)
+
+ var startResult goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ controller.started = true
+ writableStreamDealWithRejection(h, stream, panicToReason(h.rt, r))
+ ok = false
+ }
+ }()
+ startResult = start(controller.jsValue())
+ return true
+ }()
+ if !settled {
+ return
+ }
+ awaitResult(h.rt, orUndefined(startResult), func(goja.Value) {
+ controller.started = true
+ writableControllerAdvanceQueueIfNeeded(h, controller)
+ }, func(reason goja.Value) {
+ controller.started = true
+ writableStreamDealWithRejection(h, stream, reason)
+ })
+}
+
+func writableControllerDesiredSize(c *writableController) float64 {
+ return c.strategyHWM - c.queue.total
+}
+
+func writableControllerBackpressure(c *writableController) bool {
+ return writableControllerDesiredSize(c) <= 0
+}
+
+func writableControllerClearAlgorithms(c *writableController) {
+ c.writeAlgorithm = nil
+ c.closeAlgorithm = nil
+ c.abortAlgorithm = nil
+ c.sizeAlgorithm = nil
+}
+
+// writableControllerErrorIfNeeded 对应 WritableStreamDefaultControllerErrorIfNeeded。
+func writableControllerErrorIfNeeded(h *Host, c *writableController, reason goja.Value) {
+ if c.stream.status == writableWritable {
+ writableControllerError(h, c, reason)
+ }
+}
+
+// writableControllerError 对应 WritableStreamDefaultControllerError。
+func writableControllerError(h *Host, c *writableController, reason goja.Value) {
+ writableControllerClearAlgorithms(c)
+ writableStreamStartErroring(h, c.stream, reason)
+}
+
+// writableControllerWrite 对应 WritableStreamDefaultControllerWrite。
+func writableControllerWrite(h *Host, c *writableController, chunk goja.Value, size float64) {
+ c.queue.enqueue(chunk, size)
+ stream := c.stream
+ if !writableCloseQueuedOrInFlight(stream) && stream.status == writableWritable {
+ writableStreamUpdateBackpressure(stream, writableControllerBackpressure(c))
+ }
+ writableControllerAdvanceQueueIfNeeded(h, c)
+}
+
+// writableControllerClose 对应 WritableStreamDefaultControllerClose:入队关闭哨兵,与常规写入保持顺序。
+func writableControllerClose(h *Host, c *writableController) {
+ c.queue.enqueueClose()
+ writableControllerAdvanceQueueIfNeeded(h, c)
+}
+
+// writableControllerAdvanceQueueIfNeeded 对应 WritableStreamDefaultControllerAdvanceQueueIfNeeded。
+func writableControllerAdvanceQueueIfNeeded(h *Host, c *writableController) {
+ stream := c.stream
+ if !c.started || stream.inFlightWriteRequest != nil {
+ return
+ }
+ if stream.status == writableErroring {
+ writableStreamFinishErroring(h, stream)
+ return
+ }
+ if c.queue.len() == 0 {
+ return
+ }
+ if c.queue.peekIsClose() {
+ writableControllerProcessClose(h, c)
+ } else {
+ writableControllerProcessWrite(h, c, c.queue.peek())
+ }
+}
+
+// writableControllerProcessWrite 对应 WritableStreamDefaultControllerProcessWrite。
+func writableControllerProcessWrite(h *Host, c *writableController, chunk goja.Value) {
+ stream := c.stream
+ stream.inFlightWriteRequest = stream.writeRequests[0]
+ stream.writeRequests = stream.writeRequests[1:]
+
+ var result goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ result = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ ok = true
+ }
+ }()
+ result = c.writeAlgorithm(chunk)
+ return true
+ }()
+ if !settled {
+ return
+ }
+
+ awaitResult(h.rt, orUndefined(result), func(goja.Value) {
+ writableStreamFinishInFlightWrite(stream)
+ c.queue.dequeue()
+ if !writableCloseQueuedOrInFlight(stream) && stream.status == writableWritable {
+ writableStreamUpdateBackpressure(stream, writableControllerBackpressure(c))
+ }
+ writableControllerAdvanceQueueIfNeeded(h, c)
+ }, func(reason goja.Value) {
+ if stream.status == writableWritable {
+ writableControllerClearAlgorithms(c)
+ }
+ writableStreamFinishInFlightWriteWithError(h, stream, reason)
+ })
+}
+
+// writableControllerProcessClose 对应 WritableStreamDefaultControllerProcessClose。
+func writableControllerProcessClose(h *Host, c *writableController) {
+ stream := c.stream
+ stream.inFlightCloseRequest = stream.closeRequest
+ stream.closeRequest = nil
+ c.queue.dequeue()
+
+ var result goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ result = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ ok = true
+ }
+ }()
+ if c.closeAlgorithm != nil {
+ result = c.closeAlgorithm()
+ } else {
+ result = newResolvedPromise(h.rt, goja.Undefined())
+ }
+ return true
+ }()
+ writableControllerClearAlgorithms(c)
+ if !settled {
+ return
+ }
+
+ awaitResult(h.rt, orUndefined(result), func(goja.Value) {
+ writableStreamFinishInFlightClose(h, stream)
+ }, func(reason goja.Value) {
+ writableStreamFinishInFlightCloseWithError(h, stream, reason)
+ })
+}
+
+// ──────────────────────────── WritableStream 内部算法 ────────────────────────────
+
+// writableStreamUpdateBackpressure 对应 WritableStreamUpdateBackpressure:backpressure 发生变化时相应地
+// 重置或兑定 writer 的 ready Promise。
+func writableStreamUpdateBackpressure(stream *writableState, backpressure bool) {
+ if writer := stream.writer; writer != nil && backpressure != stream.backpressure {
+ if backpressure {
+ writer.ready = newDeferred(writer.host.rt)
+ } else {
+ must0(writer.ready.resolve(goja.Undefined()))
+ }
+ }
+ stream.backpressure = backpressure
+}
+
+// writableStreamFinishInFlightWrite 对应 WritableStreamFinishInFlightWrite。
+func writableStreamFinishInFlightWrite(stream *writableState) {
+ stream.inFlightWriteRequest.settle(true, goja.Undefined())
+ stream.inFlightWriteRequest = nil
+}
+
+// writableStreamFinishInFlightWriteWithError 对应 WritableStreamFinishInFlightWriteWithError。
+func writableStreamFinishInFlightWriteWithError(h *Host, stream *writableState, reason goja.Value) {
+ stream.inFlightWriteRequest.settle(false, reason)
+ stream.inFlightWriteRequest = nil
+ writableStreamDealWithRejection(h, stream, reason)
+}
+
+// writableStreamFinishInFlightClose 对应 WritableStreamFinishInFlightClose。
+func writableStreamFinishInFlightClose(h *Host, stream *writableState) {
+ stream.inFlightCloseRequest.settle(true, goja.Undefined())
+ stream.inFlightCloseRequest = nil
+
+ if stream.status == writableErroring {
+ stream.storedError = nil
+ if stream.pendingAbort != nil {
+ must0(stream.pendingAbort.promise.resolve(goja.Undefined()))
+ stream.pendingAbort = nil
+ }
+ }
+ stream.status = writableClosed
+ if writer := stream.writer; writer != nil {
+ must0(writer.closed.resolve(goja.Undefined()))
+ }
+}
+
+// writableStreamFinishInFlightCloseWithError 对应 WritableStreamFinishInFlightCloseWithError。
+func writableStreamFinishInFlightCloseWithError(h *Host, stream *writableState, reason goja.Value) {
+ stream.inFlightCloseRequest.settle(false, reason)
+ stream.inFlightCloseRequest = nil
+ if stream.pendingAbort != nil {
+ must0(stream.pendingAbort.promise.reject(reason))
+ stream.pendingAbort = nil
+ }
+ writableStreamDealWithRejection(h, stream, reason)
+}
+
+// writableStreamDealWithRejection 对应 WritableStreamDealWithRejection。
+func writableStreamDealWithRejection(h *Host, stream *writableState, reason goja.Value) {
+ if stream.status == writableWritable {
+ writableStreamStartErroring(h, stream, reason)
+ return
+ }
+ writableStreamFinishErroring(h, stream)
+}
+
+// writableStreamStartErroring 对应 WritableStreamStartErroring。
+func writableStreamStartErroring(h *Host, stream *writableState, reason goja.Value) {
+ controller := stream.controller
+ stream.status = writableErroring
+ stream.storedError = reason
+ if writer := stream.writer; writer != nil {
+ writableWriterEnsureReadyPromiseRejected(writer, reason)
+ }
+ if !writableStreamHasOperationMarkedInFlight(stream) && controller.started {
+ writableStreamFinishErroring(h, stream)
+ }
+}
+
+// writableStreamHasOperationMarkedInFlight 对应 WritableStreamHasOperationMarkedInFlight。
+func writableStreamHasOperationMarkedInFlight(stream *writableState) bool {
+ return stream.inFlightWriteRequest != nil || stream.inFlightCloseRequest != nil
+}
+
+// writableStreamFinishErroring 对应 WritableStreamFinishErroring。
+func writableStreamFinishErroring(h *Host, stream *writableState) {
+ stream.status = writableErrored
+ stream.controller.queue.reset() // [[ErrorSteps]]:清空队列
+ storedError := stream.storedError
+ for _, request := range stream.writeRequests {
+ request.settle(false, storedError)
+ }
+ stream.writeRequests = nil
+
+ if stream.pendingAbort == nil {
+ writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)
+ return
+ }
+ abortRequest := stream.pendingAbort
+ stream.pendingAbort = nil
+ if abortRequest.wasAlreadyErroring {
+ must0(abortRequest.promise.reject(storedError))
+ writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)
+ return
+ }
+
+ controller := stream.controller
+ abortAlgorithm := controller.abortAlgorithm
+ controller.writeAlgorithm, controller.closeAlgorithm, controller.sizeAlgorithm = nil, nil, nil
+ var result goja.Value
+ settled := func() (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ result = newRejectedPromise(h.rt, panicToReason(h.rt, r))
+ ok = true
+ }
+ }()
+ if abortAlgorithm != nil {
+ result = abortAlgorithm(abortRequest.reason)
+ } else {
+ result = newResolvedPromise(h.rt, goja.Undefined())
+ }
+ return true
+ }()
+ controller.abortAlgorithm = nil
+ if !settled {
+ return
+ }
+
+ awaitResult(h.rt, orUndefined(result), func(goja.Value) {
+ must0(abortRequest.promise.resolve(goja.Undefined()))
+ writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)
+ }, func(reason goja.Value) {
+ must0(abortRequest.promise.reject(reason))
+ writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)
+ })
+}
+
+// writableStreamRejectCloseAndClosedPromiseIfNeeded 对应 WritableStreamRejectCloseAndClosedPromiseIfNeeded。
+func writableStreamRejectCloseAndClosedPromiseIfNeeded(stream *writableState) {
+ if stream.closeRequest != nil {
+ stream.closeRequest.settle(false, stream.storedError)
+ stream.closeRequest = nil
+ }
+ if writer := stream.writer; writer != nil {
+ must0(writer.closed.reject(stream.storedError))
+ }
+}
+
+// writableStreamAbort 对应 WritableStreamAbort。
+func writableStreamAbort(h *Host, stream *writableState, reason goja.Value) goja.Value {
+ if stream.status == writableClosed || stream.status == writableErrored {
+ return newResolvedPromise(h.rt, goja.Undefined())
+ }
+ if stream.pendingAbort != nil {
+ return stream.pendingAbort.promise.value(h.rt)
+ }
+ wasAlreadyErroring := stream.status == writableErroring
+ if wasAlreadyErroring {
+ reason = nil
+ }
+ request := &pendingAbortRequest{promise: newDeferred(h.rt), reason: reason, wasAlreadyErroring: wasAlreadyErroring}
+ stream.pendingAbort = request
+ if !wasAlreadyErroring {
+ writableStreamStartErroring(h, stream, reason)
+ }
+ return request.promise.value(h.rt)
+}
+
+// writableStreamClose 对应 WritableStreamClose。
+func writableStreamClose(h *Host, stream *writableState) goja.Value {
+ if stream.status == writableClosed || stream.status == writableErrored {
+ return newRejectedPromise(h.rt, typeErrorf(h.rt, "Cannot close an already-closed stream"))
+ }
+ capability := &writePromiseCapability{}
+ promise, resolve, reject := h.rt.NewPromise()
+ capability.resolve, capability.reject = resolve, reject
+ stream.closeRequest = capability
+
+ if writer := stream.writer; writer != nil && stream.backpressure && stream.status == writableWritable {
+ must0(writer.ready.resolve(goja.Undefined()))
+ }
+ writableControllerClose(h, stream.controller)
+ return h.rt.ToValue(promise)
+}
+
+// ──────────────────────────── WritableStreamDefaultWriter 内部算法 ────────────────────────────
+
+// acquireWritableStreamDefaultWriter 对应 AcquireWritableStreamDefaultWriter + SetUpWritableStreamDefaultWriter:
+// 流已被锁定时抛出 TypeError。
+func acquireWritableStreamDefaultWriter(h *Host, stream *writableState) *writableWriterState {
+ if isWritableStreamLocked(stream) {
+ panic(typeErrorf(h.rt, "WritableStreamDefaultWriter constructor can only accept writable streams that are not yet locked to a writer"))
+ }
+ writer := &writableWriterState{host: h, stream: stream}
+ stream.writer = writer
+
+ switch stream.status {
+ case writableWritable:
+ if !writableCloseQueuedOrInFlight(stream) && stream.backpressure {
+ writer.ready = newDeferred(h.rt)
+ } else {
+ writer.ready = newDeferred(h.rt)
+ must0(writer.ready.resolve(goja.Undefined()))
+ }
+ writer.closed = newDeferred(h.rt)
+ case writableErroring:
+ writer.ready = newDeferred(h.rt)
+ must0(writer.ready.reject(stream.storedError))
+ writer.closed = newDeferred(h.rt)
+ case writableClosed:
+ writer.ready = newDeferred(h.rt)
+ must0(writer.ready.resolve(goja.Undefined()))
+ writer.closed = newDeferred(h.rt)
+ must0(writer.closed.resolve(goja.Undefined()))
+ default: // writableErrored
+ writer.ready = newDeferred(h.rt)
+ must0(writer.ready.reject(stream.storedError))
+ writer.closed = newDeferred(h.rt)
+ must0(writer.closed.reject(stream.storedError))
+ }
+ return writer
+}
+
+// writableWriterEnsureReadyPromiseRejected 对应 WritableStreamDefaultWriterEnsureReadyPromiseRejected。
+func writableWriterEnsureReadyPromiseRejected(writer *writableWriterState, reason goja.Value) {
+ if writer.ready.isPending() {
+ must0(writer.ready.reject(reason))
+ } else {
+ writer.ready = newDeferred(writer.host.rt)
+ must0(writer.ready.reject(reason))
+ }
+}
+
+// writableWriterEnsureClosedPromiseRejected 对应 WritableStreamDefaultWriterEnsureClosedPromiseRejected。
+func writableWriterEnsureClosedPromiseRejected(writer *writableWriterState, reason goja.Value) {
+ if writer.closed.isPending() {
+ must0(writer.closed.reject(reason))
+ } else {
+ writer.closed = newDeferred(writer.host.rt)
+ must0(writer.closed.reject(reason))
+ }
+}
+
+// writableWriterDesiredSize 返回 writer 的 desiredSize:writer 已释放时 panic TypeError;流已出错/正在出错时
+// 为 null;已关闭时为 0。
+func writableWriterDesiredSize(h *Host, writer *writableWriterState) goja.Value {
+ if writer.stream == nil {
+ panic(writerReleasedError(h.rt))
+ }
+ switch writer.stream.status {
+ case writableErroring, writableErrored:
+ return goja.Null()
+ case writableClosed:
+ return h.rt.ToValue(0)
+ default:
+ return h.rt.ToValue(writableControllerDesiredSize(writer.stream.controller))
+ }
+}
+
+func writerReleasedError(rt *goja.Runtime) goja.Value {
+ return typeErrorf(rt, "Writer was released and can no longer be used to monitor the stream's closedness")
+}
+
+// writableWriterWrite 对应 WritableStreamDefaultWriterWrite。
+func writableWriterWrite(h *Host, writer *writableWriterState, chunk goja.Value) goja.Value {
+ stream := writer.stream
+ controller := stream.controller
+ size := writableControllerGetChunkSize(h, controller, chunk)
+
+ switch stream.status {
+ case writableErrored:
+ return newRejectedPromise(h.rt, stream.storedError)
+ case writableErroring:
+ return newRejectedPromise(h.rt, stream.storedError)
+ }
+ if writableCloseQueuedOrInFlight(stream) || stream.status == writableClosed {
+ return newRejectedPromise(h.rt, typeErrorf(h.rt, "The stream is closing or closed and cannot be written to"))
+ }
+
+ promise, resolve, reject := h.rt.NewPromise()
+ stream.writeRequests = append(stream.writeRequests, &writePromiseCapability{resolve: resolve, reject: reject})
+ writableControllerWrite(h, controller, chunk, size)
+ return h.rt.ToValue(promise)
+}
+
+// writableWriterClose 对应 WritableStreamDefaultWriterClose。
+func writableWriterClose(h *Host, writer *writableWriterState) goja.Value {
+ stream := writer.stream
+ if stream == nil {
+ return newRejectedPromise(h.rt, writerReleasedError(h.rt))
+ }
+ if writableCloseQueuedOrInFlight(stream) {
+ return newRejectedPromise(h.rt, typeErrorf(h.rt, "Cannot close an already-closing stream"))
+ }
+ return writableStreamClose(h, stream)
+}
+
+// writableWriterAbort 对应 WritableStreamDefaultWriterAbort。
+func writableWriterAbort(h *Host, writer *writableWriterState, reason goja.Value) goja.Value {
+ if writer.stream == nil {
+ return newRejectedPromise(h.rt, writerReleasedError(h.rt))
+ }
+ return writableStreamAbort(h, writer.stream, reason)
+}
+
+// writableWriterRelease 对应 WritableStreamDefaultWriterRelease。
+func writableWriterRelease(writer *writableWriterState) {
+ stream := writer.stream
+ if stream == nil {
+ return
+ }
+ released := writerReleasedError(writer.host.rt)
+ writableWriterEnsureReadyPromiseRejected(writer, released)
+ writableWriterEnsureClosedPromiseRejected(writer, released)
+ stream.writer = nil
+ writer.stream = nil
+}
diff --git a/kernel/plugin/streams/writable_prototype.go b/kernel/plugin/streams/writable_prototype.go
new file mode 100644
index 0000000000..1eca816a14
--- /dev/null
+++ b/kernel/plugin/streams/writable_prototype.go
@@ -0,0 +1,161 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package streams
+
+import "github.com/dop251/goja"
+
+// newWritableControllerPrototype 构造 WritableStreamDefaultController.prototype:error 方法。本包不暴露
+// controller.signal(见 setUpWritableStreamDefaultController 的注释)。
+func newWritableControllerPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *writableController {
+ c, ok := writableControllerOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "WritableStreamDefaultController.prototype.%s called on an incompatible receiver", method))
+ }
+ return c
+ }
+
+ defineMethod(rt, prototype, "error", 1, func(call goja.FunctionCall) goja.Value {
+ c := self(call, "error")
+ writableControllerErrorIfNeeded(h, c, call.Argument(0))
+ return goja.Undefined()
+ })
+ defineToStringTag(rt, prototype, "WritableStreamDefaultController")
+ return prototype
+}
+
+// newWritableWriterPrototype 构造 WritableStreamDefaultWriter.prototype:closed/desiredSize/ready 访问器,
+// abort/close/releaseLock/write 方法。
+func newWritableWriterPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *writableWriterState {
+ w, ok := writableWriterOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "WritableStreamDefaultWriter.prototype.%s called on an incompatible receiver", method))
+ }
+ return w
+ }
+
+ defineGetter(rt, prototype, "closed", func(call goja.FunctionCall) goja.Value {
+ return self(call, "closed").closed.value(rt)
+ })
+ defineGetter(rt, prototype, "desiredSize", func(call goja.FunctionCall) goja.Value {
+ return writableWriterDesiredSize(h, self(call, "desiredSize"))
+ })
+ defineGetter(rt, prototype, "ready", func(call goja.FunctionCall) goja.Value {
+ return self(call, "ready").ready.value(rt)
+ })
+ defineMethod(rt, prototype, "abort", 1, func(call goja.FunctionCall) goja.Value {
+ return writableWriterAbort(h, self(call, "abort"), call.Argument(0))
+ })
+ defineMethod(rt, prototype, "close", 0, func(call goja.FunctionCall) goja.Value {
+ return writableWriterClose(h, self(call, "close"))
+ })
+ defineMethod(rt, prototype, "releaseLock", 0, func(call goja.FunctionCall) goja.Value {
+ writableWriterRelease(self(call, "releaseLock"))
+ return goja.Undefined()
+ })
+ defineMethod(rt, prototype, "write", 1, func(call goja.FunctionCall) goja.Value {
+ return writableWriterWrite(h, self(call, "write"), call.Argument(0))
+ })
+ defineToStringTag(rt, prototype, "WritableStreamDefaultWriter")
+ return prototype
+}
+
+// newWritableStreamPrototype 构造 WritableStream.prototype:locked 访问器,abort/close/getWriter 方法。
+func newWritableStreamPrototype(h *Host) *goja.Object {
+ rt := h.rt
+ prototype := rt.NewObject()
+
+ self := func(call goja.FunctionCall, method string) *writableState {
+ s, ok := writableStateOf(call.This)
+ if !ok {
+ panic(typeErrorf(rt, "WritableStream.prototype.%s called on an incompatible receiver", method))
+ }
+ return s
+ }
+
+ defineGetter(rt, prototype, "locked", func(call goja.FunctionCall) goja.Value {
+ return rt.ToValue(isWritableStreamLocked(self(call, "locked")))
+ })
+ defineMethod(rt, prototype, "abort", 1, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "abort")
+ if isWritableStreamLocked(stream) {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot abort a stream that already has a writer"))
+ }
+ return writableStreamAbort(h, stream, call.Argument(0))
+ })
+ defineMethod(rt, prototype, "close", 0, func(call goja.FunctionCall) goja.Value {
+ stream := self(call, "close")
+ if isWritableStreamLocked(stream) {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot close a stream that already has a writer"))
+ }
+ if writableCloseQueuedOrInFlight(stream) {
+ return newRejectedPromise(rt, typeErrorf(rt, "Cannot close an already-closing stream"))
+ }
+ return writableStreamClose(h, stream)
+ })
+ defineMethod(rt, prototype, "getWriter", 0, func(call goja.FunctionCall) goja.Value {
+ return acquireWritableStreamDefaultWriter(h, self(call, "getWriter")).jsValue()
+ })
+ defineToStringTag(rt, prototype, "WritableStream")
+ return prototype
+}
+
+// newWritableStreamConstructor 构造 WritableStream 全局构造函数:new WritableStream(underlyingSink, strategy)。
+func (h *Host) newWritableStreamConstructor() *goja.Object {
+ rt := h.rt
+ return newInterfaceConstructor(rt, "WritableStream", 0, h.writableStreamPrototype, func(call goja.ConstructorCall) *goja.Object {
+ sink := call.Argument(0)
+ var sinkObj *goja.Object
+ if isJsValueNotNull(sink) {
+ var ok bool
+ sinkObj, ok = sink.(*goja.Object)
+ if !ok {
+ panic(typeErrorf(rt, "WritableStream: Argument 1 can't be converted to a dictionary"))
+ }
+ }
+
+ stream := &writableState{host: h, status: writableWritable}
+ object := h.rt.NewDynamicObject(stream)
+ must(object.SetPrototype(call.This.Prototype()))
+ stream.self = object
+
+ highWaterMark := extractHighWaterMark(rt, call.Argument(1), 1)
+ sizeAlgorithm := extractSizeAlgorithm(rt, call.Argument(1))
+ start := wrapUnderlyingMethod(rt, sinkObj, "start")
+ write := wrapUnderlyingMethod(rt, sinkObj, "write")
+ cls := wrapUnderlyingNoArgMethod(rt, sinkObj, "close")
+ abort := wrapUnderlyingMethod(rt, sinkObj, "abort")
+ setUpWritableStreamDefaultController(h, stream, orNoOp(start), orNoOp(write), cls, orNoOp(abort), highWaterMark, sizeAlgorithm)
+ return object
+ })
+}
+
+// wrapUnderlyingNoArgMethod 与 wrapUnderlyingMethod 类似,但包装的是不接收参数的方法(如 close)。
+func wrapUnderlyingNoArgMethod(rt *goja.Runtime, source *goja.Object, name string) func() goja.Value {
+ fn := wrapUnderlyingMethod(rt, source, name)
+ if fn == nil {
+ return nil
+ }
+ return func() goja.Value { return fn(goja.Undefined()) }
+}