@crazyhappyone/dsh-tui 0.1.0-alpha.40 → 0.1.0-alpha.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/README.zh.md +25 -0
- package/cordis.patch.yml +11 -0
- package/dist/index.js +16 -17
- package/dist/zen-proxy.js +901 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -138,6 +138,31 @@ The TUI is a DSH profile layer, not a separate agent runtime:
|
|
|
138
138
|
|
|
139
139
|
The integration source lives on the private [`feat/deepseek-tui` DSH branch](https://github.com/zhangyang-crazy-one/deepseek-harness/tree/feat/deepseek-tui/packages/tui). Changes that affect DSH services, profile composition, assembled CLI snapshots, or Agent Notes belong in that monorepo and follow its architecture, testing, and documentation rules.
|
|
140
140
|
|
|
141
|
+
### OpenCode Zen free models
|
|
142
|
+
|
|
143
|
+
The bundled patch mounts `zen-proxy` (vendored from
|
|
144
|
+
[zhangyang-crazy-one/dsh-zen-proxy](https://github.com/zhangyang-crazy-one/dsh-zen-proxy),
|
|
145
|
+
fork of [Yee-h/dsh-zen-proxy](https://github.com/Yee-h/dsh-zen-proxy)): an in-process
|
|
146
|
+
localhost proxy that injects the official OpenCode client headers Zen requires
|
|
147
|
+
(`User-Agent`, `x-opencode-client/session/request/project`). Without it Zen answers
|
|
148
|
+
`400 MissingSessionID` / `429 FreeUsageLimitError` because dsh always sends its
|
|
149
|
+
own attribution `User-Agent`.
|
|
150
|
+
|
|
151
|
+
To use it, point the provider at the proxy in `settings.yaml` (or the TUI
|
|
152
|
+
`/settings` provider form) and keep the key in credentials:
|
|
153
|
+
|
|
154
|
+
```yaml
|
|
155
|
+
llm-pi-ai:
|
|
156
|
+
providers:
|
|
157
|
+
opencode:
|
|
158
|
+
api: openai-completions
|
|
159
|
+
baseURL: http://127.0.0.1:4097/v1
|
|
160
|
+
apiKeyEnv: OPENCODE_API_KEY
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The proxy listens on `127.0.0.1:4097` only; remove the `zen-proxy` row from
|
|
164
|
+
`cordis.patch.yml` to disable it.
|
|
165
|
+
|
|
141
166
|
-----
|
|
142
167
|
|
|
143
168
|
<a id="packages"></a>
|
|
@@ -146,6 +171,7 @@ The integration source lives on the private [`feat/deepseek-tui` DSH branch](htt
|
|
|
146
171
|
| Package | DSH shape | Responsibility |
|
|
147
172
|
|---|---|---|
|
|
148
173
|
| [`tui/`](tui/README.md) | Profile bundle plus runtime plugin | Composes the terminal layer over `dsh-base`, owns the live terminal session, and maps user actions to DSH services |
|
|
174
|
+
| [`plugins/zen-proxy/`](https://github.com/zhangyang-crazy-one/dsh-zen-proxy) | Vendored plugin (bundled as `dist/zen-proxy.js`) | In-process OpenAI-compatible proxy injecting OpenCode Zen client headers; mounted in `cordis.patch.yml` |
|
|
149
175
|
| [`tui-render/`](tui-render/README.md) | Library | Projects controller state through Ink without owning agents, persistence, or model requests |
|
|
150
176
|
|
|
151
177
|
-----
|
package/README.zh.md
CHANGED
|
@@ -138,6 +138,30 @@ TUI 是 DSH profile 层,而不是独立的 agent 运行时:
|
|
|
138
138
|
|
|
139
139
|
集成源码位于 private [`feat/deepseek-tui` DSH 分支](https://github.com/zhangyang-crazy-one/deepseek-harness/tree/feat/deepseek-tui/packages/tui)。影响 DSH 服务、profile 组合、组装后 CLI snapshot 或 Agent Note 的变更归该 monorepo 所有,并遵循其中的架构、测试与文档规则。
|
|
140
140
|
|
|
141
|
+
### OpenCode Zen 免费模型
|
|
142
|
+
|
|
143
|
+
打包后的 patch 挂载了 `zen-proxy`(vendored 自
|
|
144
|
+
[zhangyang-crazy-one/dsh-zen-proxy](https://github.com/zhangyang-crazy-one/dsh-zen-proxy),
|
|
145
|
+
fork 自 [Yee-h/dsh-zen-proxy](https://github.com/Yee-h/dsh-zen-proxy)):进程内 localhost
|
|
146
|
+
代理,注入 Zen 要求的 OpenCode 官方客户端头(`User-Agent`、
|
|
147
|
+
`x-opencode-client/session/request/project`)。没有它,Zen 会返回
|
|
148
|
+
`400 MissingSessionID` / `429 FreeUsageLimitError`,因为 dsh 始终发送自己的
|
|
149
|
+
attribution `User-Agent`。
|
|
150
|
+
|
|
151
|
+
使用方法:在 `settings.yaml`(或 TUI `/settings` provider 表单)中把 provider
|
|
152
|
+
指向该代理,并把密钥放在 credentials 中:
|
|
153
|
+
|
|
154
|
+
```yaml
|
|
155
|
+
llm-pi-ai:
|
|
156
|
+
providers:
|
|
157
|
+
opencode:
|
|
158
|
+
api: openai-completions
|
|
159
|
+
baseURL: http://127.0.0.1:4097/v1
|
|
160
|
+
apiKeyEnv: OPENCODE_API_KEY
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
代理只监听 `127.0.0.1:4097`;从 `cordis.patch.yml` 删除 `zen-proxy` 行即可禁用。
|
|
164
|
+
|
|
141
165
|
-----
|
|
142
166
|
|
|
143
167
|
<a id="packages"></a>
|
|
@@ -146,6 +170,7 @@ TUI 是 DSH profile 层,而不是独立的 agent 运行时:
|
|
|
146
170
|
| 包 | DSH 形态 | 职责 |
|
|
147
171
|
|---|---|---|
|
|
148
172
|
| [`tui/`](tui/README.zh.md) | Profile bundle 与运行时插件 | 在 `dsh-base` 上组合终端层、拥有 live 终端会话,并将用户动作映射到 DSH 服务 |
|
|
173
|
+
| [`plugins/zen-proxy/`](https://github.com/zhangyang-crazy-one/dsh-zen-proxy) | Vendored 插件(打包为 `dist/zen-proxy.js`) | 进程内 OpenAI 兼容代理,注入 OpenCode Zen 客户端头;在 `cordis.patch.yml` 中挂载 |
|
|
149
174
|
| [`tui-render/`](tui-render/README.zh.md) | Library | 通过 Ink 投影控制器状态,但不拥有 agent、持久化或模型请求 |
|
|
150
175
|
|
|
151
176
|
-----
|
package/cordis.patch.yml
CHANGED
|
@@ -64,6 +64,17 @@
|
|
|
64
64
|
- id: tool-ask-user
|
|
65
65
|
name: "@deepseek-ai/dsh-tool-ask-user"
|
|
66
66
|
|
|
67
|
+
# In-process OpenCode Zen header proxy (vendored from
|
|
68
|
+
# zhangyang-crazy-one/dsh-zen-proxy, MIT). Listens on localhost
|
|
69
|
+
# only; point an opencode provider baseURL at
|
|
70
|
+
# http://127.0.0.1:4097/v1 to reach the Zen free tier.
|
|
71
|
+
# Remove this row to disable the listener.
|
|
72
|
+
- id: zen-proxy
|
|
73
|
+
name: "./dist/zen-proxy.js"
|
|
74
|
+
config:
|
|
75
|
+
host: 127.0.0.1
|
|
76
|
+
port: 4097
|
|
77
|
+
|
|
67
78
|
- id: tui-startup
|
|
68
79
|
name: "./dist/startup.js"
|
|
69
80
|
|
package/dist/index.js
CHANGED
|
@@ -28013,16 +28013,13 @@ var init_devtools_window_polyfill = __esm({
|
|
|
28013
28013
|
}
|
|
28014
28014
|
});
|
|
28015
28015
|
|
|
28016
|
-
//
|
|
28016
|
+
// node_modules/.cache/react-devtools-core-stub.js
|
|
28017
28017
|
var react_devtools_core_stub_default;
|
|
28018
28018
|
var init_react_devtools_core_stub = __esm({
|
|
28019
|
-
"
|
|
28020
|
-
react_devtools_core_stub_default = {
|
|
28021
|
-
|
|
28022
|
-
|
|
28023
|
-
connectToDevTools() {
|
|
28024
|
-
}
|
|
28025
|
-
};
|
|
28019
|
+
"node_modules/.cache/react-devtools-core-stub.js"() {
|
|
28020
|
+
react_devtools_core_stub_default = { initialize() {
|
|
28021
|
+
}, connectToDevTools() {
|
|
28022
|
+
} };
|
|
28026
28023
|
}
|
|
28027
28024
|
});
|
|
28028
28025
|
|
|
@@ -31691,10 +31688,6 @@ var Service = class _Service {
|
|
|
31691
31688
|
}
|
|
31692
31689
|
};
|
|
31693
31690
|
|
|
31694
|
-
// packages/core/agent/src/index.ts
|
|
31695
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
31696
|
-
import { isPromise } from "node:util/types";
|
|
31697
|
-
|
|
31698
31691
|
// packages/typert/protocol/src/remote-error.ts
|
|
31699
31692
|
var RemoteError = class extends Error {
|
|
31700
31693
|
/**
|
|
@@ -33994,6 +33987,8 @@ var Session = class _Session {
|
|
|
33994
33987
|
eventsSnapshot;
|
|
33995
33988
|
/**
|
|
33996
33989
|
* Return the immutable event stored at one exact sequence number.
|
|
33990
|
+
* @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
|
|
33991
|
+
* See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
|
|
33997
33992
|
* @param seq - event sequence number.
|
|
33998
33993
|
* @returns the accepted event, or undefined when the log does not contain it.
|
|
33999
33994
|
*/
|
|
@@ -34004,6 +33999,8 @@ var Session = class _Session {
|
|
|
34004
33999
|
* Materialize an immutable snapshot of a half-open event sequence range.
|
|
34005
34000
|
* A full current snapshot is reused until the next append; every previously
|
|
34006
34001
|
* returned snapshot remains stable after later appends.
|
|
34002
|
+
* @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
|
|
34003
|
+
* See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
|
|
34007
34004
|
* @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
|
|
34008
34005
|
* @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
|
|
34009
34006
|
* @returns a frozen array of the selected deeply frozen events.
|
|
@@ -34017,6 +34014,8 @@ var Session = class _Session {
|
|
|
34017
34014
|
}
|
|
34018
34015
|
/**
|
|
34019
34016
|
* Return this Session's events after its fork-inherited prefix.
|
|
34017
|
+
* @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
|
|
34018
|
+
* See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
|
|
34020
34019
|
* @returns a fresh array containing child-owned events in log order.
|
|
34021
34020
|
*/
|
|
34022
34021
|
ownEvents() {
|
|
@@ -51361,10 +51360,10 @@ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
|
|
|
51361
51360
|
|
|
51362
51361
|
// node_modules/.pnpm/string-width@8.2.2/node_modules/string-width/index.js
|
|
51363
51362
|
var segmenter = new Intl.Segmenter();
|
|
51364
|
-
var zeroWidthClusterRegex =
|
|
51365
|
-
var leadingNonPrintingRegex =
|
|
51366
|
-
var spacingMarkRegex =
|
|
51367
|
-
var rgiEmojiRegex =
|
|
51363
|
+
var zeroWidthClusterRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Nonspacing_Mark}|\\p{Enclosing_Mark}|\\p{Surrogate})+$", "v");
|
|
51364
|
+
var leadingNonPrintingRegex = new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Nonspacing_Mark}\\p{Enclosing_Mark}\\p{Surrogate}]+", "v");
|
|
51365
|
+
var spacingMarkRegex = new RegExp("\\p{Spacing_Mark}", "v");
|
|
51366
|
+
var rgiEmojiRegex = new RegExp("^\\p{RGI_Emoji}$", "v");
|
|
51368
51367
|
var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
|
|
51369
51368
|
var extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
|
|
51370
51369
|
function isDoubleWidthNonRgiEmojiSequence(segment2) {
|
|
@@ -52375,7 +52374,7 @@ var SGR_ANSI_256_LAST_PARAMETER_OFFSET = 2;
|
|
|
52375
52374
|
var SGR_TRUECOLOR_LAST_PARAMETER_OFFSET = 4;
|
|
52376
52375
|
var VARIATION_SELECTOR_16_CODE_POINT = 65039;
|
|
52377
52376
|
var COMBINING_ENCLOSING_KEYCAP_CODE_POINT = 8419;
|
|
52378
|
-
var EMOJI_PRESENTATION_GRAPHEME_REGEX =
|
|
52377
|
+
var EMOJI_PRESENTATION_GRAPHEME_REGEX = new RegExp("\\p{Emoji_Presentation}", "v");
|
|
52379
52378
|
var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
52380
52379
|
var endCodeNumbers = /* @__PURE__ */ new Set();
|
|
52381
52380
|
for (const [, end] of ansi_styles_default.codes) {
|
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// vendor/cosmokit/src/misc.ts
|
|
4
|
+
function isNullable(value) {
|
|
5
|
+
return value === null || value === void 0;
|
|
6
|
+
}
|
|
7
|
+
function isPlainObject(data) {
|
|
8
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
9
|
+
}
|
|
10
|
+
function filterKeys(object, filter) {
|
|
11
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
12
|
+
}
|
|
13
|
+
function mapValues(object, transform) {
|
|
14
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
15
|
+
}
|
|
16
|
+
function pick(source, keys, forced) {
|
|
17
|
+
if (!keys) return { ...source };
|
|
18
|
+
const result = {};
|
|
19
|
+
for (const key of keys) {
|
|
20
|
+
if (forced || source[key] !== void 0) result[key] = source[key];
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// vendor/cosmokit/src/types.ts
|
|
26
|
+
function is(type, value) {
|
|
27
|
+
if (arguments.length === 1) return (value2) => is(type, value2);
|
|
28
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
29
|
+
}
|
|
30
|
+
function isArrayBufferLike(value) {
|
|
31
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
32
|
+
}
|
|
33
|
+
function isArrayBufferSource(value) {
|
|
34
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
35
|
+
}
|
|
36
|
+
var Binary;
|
|
37
|
+
((Binary2) => {
|
|
38
|
+
Binary2.is = isArrayBufferLike;
|
|
39
|
+
Binary2.isSource = isArrayBufferSource;
|
|
40
|
+
function fromSource(source) {
|
|
41
|
+
if (ArrayBuffer.isView(source)) {
|
|
42
|
+
return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
43
|
+
} else {
|
|
44
|
+
return source;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
Binary2.fromSource = fromSource;
|
|
48
|
+
function toBase64(source) {
|
|
49
|
+
source = fromSource(source);
|
|
50
|
+
if (typeof Buffer !== "undefined") {
|
|
51
|
+
return Buffer.from(source).toString("base64");
|
|
52
|
+
}
|
|
53
|
+
let binary = "";
|
|
54
|
+
const bytes = new Uint8Array(source);
|
|
55
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
56
|
+
binary += String.fromCharCode(bytes[i]);
|
|
57
|
+
}
|
|
58
|
+
return btoa(binary);
|
|
59
|
+
}
|
|
60
|
+
Binary2.toBase64 = toBase64;
|
|
61
|
+
function fromBase64(source) {
|
|
62
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
63
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
64
|
+
}
|
|
65
|
+
Binary2.fromBase64 = fromBase64;
|
|
66
|
+
function toHex(source) {
|
|
67
|
+
source = fromSource(source);
|
|
68
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
69
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
70
|
+
}
|
|
71
|
+
Binary2.toHex = toHex;
|
|
72
|
+
function fromHex(source) {
|
|
73
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
74
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
75
|
+
const buffer = [];
|
|
76
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
77
|
+
buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
78
|
+
}
|
|
79
|
+
return Uint8Array.from(buffer).buffer;
|
|
80
|
+
}
|
|
81
|
+
Binary2.fromHex = fromHex;
|
|
82
|
+
})(Binary || (Binary = {}));
|
|
83
|
+
var base64ToArrayBuffer = Binary.fromBase64;
|
|
84
|
+
var arrayBufferToBase64 = Binary.toBase64;
|
|
85
|
+
var hexToArrayBuffer = Binary.fromHex;
|
|
86
|
+
var arrayBufferToHex = Binary.toHex;
|
|
87
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
88
|
+
if (!source || typeof source !== "object") return source;
|
|
89
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
90
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
91
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
92
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
93
|
+
const cached = refs.get(source);
|
|
94
|
+
if (cached) return cached;
|
|
95
|
+
if (Array.isArray(source)) {
|
|
96
|
+
const result2 = [];
|
|
97
|
+
refs.set(source, result2);
|
|
98
|
+
source.forEach((value, index) => {
|
|
99
|
+
result2[index] = Reflect.apply(clone, null, [value, refs]);
|
|
100
|
+
});
|
|
101
|
+
return result2;
|
|
102
|
+
}
|
|
103
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
104
|
+
refs.set(source, result);
|
|
105
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
106
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
107
|
+
if ("value" in descriptor) {
|
|
108
|
+
descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
109
|
+
}
|
|
110
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
function deepEqual(a, b, strict) {
|
|
115
|
+
if (a === b) return true;
|
|
116
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
117
|
+
if (typeof a !== typeof b) return false;
|
|
118
|
+
if (typeof a !== "object") return false;
|
|
119
|
+
if (!a || !b) return false;
|
|
120
|
+
function check(test, then) {
|
|
121
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
122
|
+
}
|
|
123
|
+
return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
|
|
124
|
+
if (a2.byteLength !== b2.byteLength) return false;
|
|
125
|
+
const viewA = new Uint8Array(a2);
|
|
126
|
+
const viewB = new Uint8Array(b2);
|
|
127
|
+
for (let i = 0; i < viewA.length; i++) {
|
|
128
|
+
if (viewA[i] !== viewB[i]) return false;
|
|
129
|
+
}
|
|
130
|
+
return true;
|
|
131
|
+
}) ?? Object.keys({ ...a, ...b }).every((key) => deepEqual(a[key], b[key], strict));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// vendor/cosmokit/src/time.ts
|
|
135
|
+
var Time;
|
|
136
|
+
((Time2) => {
|
|
137
|
+
Time2.millisecond = 1;
|
|
138
|
+
Time2.second = 1e3;
|
|
139
|
+
Time2.minute = Time2.second * 60;
|
|
140
|
+
Time2.hour = Time2.minute * 60;
|
|
141
|
+
Time2.day = Time2.hour * 24;
|
|
142
|
+
Time2.week = Time2.day * 7;
|
|
143
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
144
|
+
function setTimezoneOffset(offset) {
|
|
145
|
+
timezoneOffset = offset;
|
|
146
|
+
}
|
|
147
|
+
Time2.setTimezoneOffset = setTimezoneOffset;
|
|
148
|
+
function getTimezoneOffset() {
|
|
149
|
+
return timezoneOffset;
|
|
150
|
+
}
|
|
151
|
+
Time2.getTimezoneOffset = getTimezoneOffset;
|
|
152
|
+
function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
|
|
153
|
+
if (typeof date2 === "number") date2 = new Date(date2);
|
|
154
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
155
|
+
return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
|
|
156
|
+
}
|
|
157
|
+
Time2.getDateNumber = getDateNumber;
|
|
158
|
+
function fromDateNumber(value, offset) {
|
|
159
|
+
const date2 = new Date(value * Time2.day);
|
|
160
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
161
|
+
return new Date(+date2 + offset * Time2.minute);
|
|
162
|
+
}
|
|
163
|
+
Time2.fromDateNumber = fromDateNumber;
|
|
164
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
165
|
+
const timeRegExp = new RegExp(`^${[
|
|
166
|
+
"w(?:eek(?:s)?)?",
|
|
167
|
+
"d(?:ay(?:s)?)?",
|
|
168
|
+
"h(?:our(?:s)?)?",
|
|
169
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
170
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
171
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
172
|
+
function parseTime(source) {
|
|
173
|
+
const capture = timeRegExp.exec(source);
|
|
174
|
+
if (!capture) return 0;
|
|
175
|
+
return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
|
|
176
|
+
}
|
|
177
|
+
Time2.parseTime = parseTime;
|
|
178
|
+
function parseDate(date2) {
|
|
179
|
+
const parsed = parseTime(date2);
|
|
180
|
+
if (parsed) {
|
|
181
|
+
date2 = Date.now() + parsed;
|
|
182
|
+
} else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) {
|
|
183
|
+
date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
|
|
184
|
+
} else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) {
|
|
185
|
+
date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
|
|
186
|
+
}
|
|
187
|
+
return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
|
|
188
|
+
}
|
|
189
|
+
Time2.parseDate = parseDate;
|
|
190
|
+
function format(ms) {
|
|
191
|
+
const abs = Math.abs(ms);
|
|
192
|
+
if (abs >= Time2.day - Time2.hour / 2) {
|
|
193
|
+
return Math.round(ms / Time2.day) + "d";
|
|
194
|
+
} else if (abs >= Time2.hour - Time2.minute / 2) {
|
|
195
|
+
return Math.round(ms / Time2.hour) + "h";
|
|
196
|
+
} else if (abs >= Time2.minute - Time2.second / 2) {
|
|
197
|
+
return Math.round(ms / Time2.minute) + "m";
|
|
198
|
+
} else if (abs >= Time2.second) {
|
|
199
|
+
return Math.round(ms / Time2.second) + "s";
|
|
200
|
+
}
|
|
201
|
+
return ms + "ms";
|
|
202
|
+
}
|
|
203
|
+
Time2.format = format;
|
|
204
|
+
function toDigits(source, length = 2) {
|
|
205
|
+
return source.toString().padStart(length, "0");
|
|
206
|
+
}
|
|
207
|
+
Time2.toDigits = toDigits;
|
|
208
|
+
function template(template2, time = /* @__PURE__ */ new Date()) {
|
|
209
|
+
return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
|
|
210
|
+
}
|
|
211
|
+
Time2.template = template;
|
|
212
|
+
})(Time || (Time = {}));
|
|
213
|
+
|
|
214
|
+
// vendor/schemastery/lib/index.mjs
|
|
215
|
+
var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
|
|
216
|
+
var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
|
|
217
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
218
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
219
|
+
var ValidationError = class extends TypeError {
|
|
220
|
+
options;
|
|
221
|
+
name = "ValidationError";
|
|
222
|
+
constructor(message, options) {
|
|
223
|
+
let prefix = "$";
|
|
224
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
225
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
226
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
227
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
228
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
229
|
+
this.options = options;
|
|
230
|
+
}
|
|
231
|
+
static is(error) {
|
|
232
|
+
return !!error?.[kValidationError];
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
236
|
+
var Schema = function(options) {
|
|
237
|
+
const schema = function(data, options2 = {}) {
|
|
238
|
+
return Schema.resolve(data, schema, options2)[0];
|
|
239
|
+
};
|
|
240
|
+
if (options.refs) {
|
|
241
|
+
const refs = mapValues(options.refs, (options2) => new Schema(options2));
|
|
242
|
+
const getRef = (uid) => refs[uid];
|
|
243
|
+
for (const key in refs) {
|
|
244
|
+
const options2 = refs[key];
|
|
245
|
+
options2.sKey = getRef(options2.sKey);
|
|
246
|
+
options2.inner = getRef(options2.inner);
|
|
247
|
+
options2.list = options2.list && options2.list.map(getRef);
|
|
248
|
+
options2.dict = options2.dict && mapValues(options2.dict, getRef);
|
|
249
|
+
}
|
|
250
|
+
return refs[options.uid];
|
|
251
|
+
}
|
|
252
|
+
Object.assign(schema, options);
|
|
253
|
+
if (typeof schema.callback === "string") try {
|
|
254
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
255
|
+
} catch {
|
|
256
|
+
}
|
|
257
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
258
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
259
|
+
schema.meta ||= {};
|
|
260
|
+
schema.toString = schema.toString.bind(schema);
|
|
261
|
+
return schema;
|
|
262
|
+
};
|
|
263
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
264
|
+
Schema.prototype[kSchema] = true;
|
|
265
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
266
|
+
return {
|
|
267
|
+
version: 1,
|
|
268
|
+
vendor: "schemastery",
|
|
269
|
+
validate: (value) => {
|
|
270
|
+
try {
|
|
271
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
274
|
+
message: error.message,
|
|
275
|
+
path: error.options.path
|
|
276
|
+
}] };
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
} });
|
|
282
|
+
Schema.ValidationError = ValidationError;
|
|
283
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
284
|
+
if (globalThis.__schemastery_refs__) {
|
|
285
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
286
|
+
return this.uid;
|
|
287
|
+
}
|
|
288
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
289
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
290
|
+
const result = {
|
|
291
|
+
uid: this.uid,
|
|
292
|
+
refs: globalThis.__schemastery_refs__
|
|
293
|
+
};
|
|
294
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
295
|
+
return result;
|
|
296
|
+
};
|
|
297
|
+
Schema.prototype.set = function set(key, value) {
|
|
298
|
+
this.dict[key] = value;
|
|
299
|
+
return this;
|
|
300
|
+
};
|
|
301
|
+
Schema.prototype.push = function push(value) {
|
|
302
|
+
this.list.push(value);
|
|
303
|
+
return this;
|
|
304
|
+
};
|
|
305
|
+
function mergeDesc(original, messages) {
|
|
306
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
307
|
+
for (const locale in messages) {
|
|
308
|
+
const value = messages[locale];
|
|
309
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
310
|
+
else if (typeof value === "string") result[locale] = value;
|
|
311
|
+
}
|
|
312
|
+
return result;
|
|
313
|
+
}
|
|
314
|
+
function getInner(value) {
|
|
315
|
+
return value?.$value ?? value?.$inner;
|
|
316
|
+
}
|
|
317
|
+
function extractKeys(data) {
|
|
318
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
319
|
+
}
|
|
320
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
321
|
+
const schema = Schema(this);
|
|
322
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
323
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
324
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
325
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
326
|
+
});
|
|
327
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
328
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
329
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
330
|
+
if (Array.isArray(data)) return data[index];
|
|
331
|
+
return extractKeys(data);
|
|
332
|
+
}));
|
|
333
|
+
});
|
|
334
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
335
|
+
if (getInner(data)) return getInner(data);
|
|
336
|
+
return extractKeys(data);
|
|
337
|
+
}));
|
|
338
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
339
|
+
return schema;
|
|
340
|
+
};
|
|
341
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
342
|
+
const schema = Schema(this);
|
|
343
|
+
schema.meta = {
|
|
344
|
+
...schema.meta,
|
|
345
|
+
[key]: value
|
|
346
|
+
};
|
|
347
|
+
return schema;
|
|
348
|
+
};
|
|
349
|
+
for (const key of [
|
|
350
|
+
"required",
|
|
351
|
+
"disabled",
|
|
352
|
+
"collapse",
|
|
353
|
+
"hidden",
|
|
354
|
+
"loose"
|
|
355
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
356
|
+
const schema = Schema(this);
|
|
357
|
+
schema.meta = {
|
|
358
|
+
...schema.meta,
|
|
359
|
+
[key]: value
|
|
360
|
+
};
|
|
361
|
+
return schema;
|
|
362
|
+
} });
|
|
363
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
364
|
+
const schema = Schema(this);
|
|
365
|
+
schema.meta.badges ||= [];
|
|
366
|
+
schema.meta.badges.push({
|
|
367
|
+
text: "deprecated",
|
|
368
|
+
type: "danger"
|
|
369
|
+
});
|
|
370
|
+
return schema;
|
|
371
|
+
};
|
|
372
|
+
Schema.prototype.experimental = function experimental() {
|
|
373
|
+
const schema = Schema(this);
|
|
374
|
+
schema.meta.badges ||= [];
|
|
375
|
+
schema.meta.badges.push({
|
|
376
|
+
text: "experimental",
|
|
377
|
+
type: "warning"
|
|
378
|
+
});
|
|
379
|
+
return schema;
|
|
380
|
+
};
|
|
381
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
382
|
+
const schema = Schema(this);
|
|
383
|
+
const pattern2 = pick(regexp, ["source", "flags"]);
|
|
384
|
+
schema.meta = {
|
|
385
|
+
...schema.meta,
|
|
386
|
+
pattern: pattern2
|
|
387
|
+
};
|
|
388
|
+
return schema;
|
|
389
|
+
};
|
|
390
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
391
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
392
|
+
if (isNullable(value)) return value;
|
|
393
|
+
if (this.type === "object" || this.type === "dict") {
|
|
394
|
+
const result = {};
|
|
395
|
+
for (const key in value) {
|
|
396
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
397
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
398
|
+
}
|
|
399
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
400
|
+
return result;
|
|
401
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
402
|
+
const result = [];
|
|
403
|
+
value.forEach((value2, index) => {
|
|
404
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
405
|
+
const item = schema ? schema.simplify(value2) : value2;
|
|
406
|
+
result.push(item);
|
|
407
|
+
});
|
|
408
|
+
return result;
|
|
409
|
+
} else if (this.type === "intersect") {
|
|
410
|
+
const result = {};
|
|
411
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
412
|
+
return result;
|
|
413
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
414
|
+
Schema.resolve(value, schema, {});
|
|
415
|
+
return schema.simplify(value);
|
|
416
|
+
} catch {
|
|
417
|
+
}
|
|
418
|
+
return value;
|
|
419
|
+
};
|
|
420
|
+
Schema.prototype.toString = function toString(inline) {
|
|
421
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
422
|
+
};
|
|
423
|
+
Schema.prototype.role = function role(role, extra2) {
|
|
424
|
+
const schema = Schema(this);
|
|
425
|
+
schema.meta = {
|
|
426
|
+
...schema.meta,
|
|
427
|
+
role,
|
|
428
|
+
extra: extra2
|
|
429
|
+
};
|
|
430
|
+
return schema;
|
|
431
|
+
};
|
|
432
|
+
for (const key of [
|
|
433
|
+
"default",
|
|
434
|
+
"link",
|
|
435
|
+
"comment",
|
|
436
|
+
"description",
|
|
437
|
+
"max",
|
|
438
|
+
"min",
|
|
439
|
+
"step"
|
|
440
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
441
|
+
const schema = Schema(this);
|
|
442
|
+
schema.meta = {
|
|
443
|
+
...schema.meta,
|
|
444
|
+
[key]: value
|
|
445
|
+
};
|
|
446
|
+
return schema;
|
|
447
|
+
} });
|
|
448
|
+
var resolvers = {};
|
|
449
|
+
Schema.extend = function extend(type, resolve2) {
|
|
450
|
+
resolvers[type] = resolve2;
|
|
451
|
+
};
|
|
452
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
453
|
+
if (!schema) return [data];
|
|
454
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
455
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
456
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
457
|
+
let current = schema;
|
|
458
|
+
let fallback = schema.meta.default;
|
|
459
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
460
|
+
current = current.list[0];
|
|
461
|
+
fallback = current?.meta.default;
|
|
462
|
+
}
|
|
463
|
+
if (isNullable(fallback)) return [data];
|
|
464
|
+
data = clone(fallback);
|
|
465
|
+
}
|
|
466
|
+
const callback = resolvers[schema.type];
|
|
467
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
468
|
+
try {
|
|
469
|
+
return callback(data, schema, options, strict);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
if (!schema.meta.loose) throw error;
|
|
472
|
+
return [schema.meta.default];
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
Schema.from = function from(source) {
|
|
476
|
+
if (isNullable(source)) return Schema.any();
|
|
477
|
+
else if ([
|
|
478
|
+
"string",
|
|
479
|
+
"number",
|
|
480
|
+
"boolean"
|
|
481
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
482
|
+
else if (source[kSchema]) return source;
|
|
483
|
+
else if (typeof source === "function") switch (source) {
|
|
484
|
+
case String:
|
|
485
|
+
return Schema.string().required();
|
|
486
|
+
case Number:
|
|
487
|
+
return Schema.number().required();
|
|
488
|
+
case Boolean:
|
|
489
|
+
return Schema.boolean().required();
|
|
490
|
+
case Function:
|
|
491
|
+
return Schema.function().required();
|
|
492
|
+
default:
|
|
493
|
+
return Schema.is(source).required();
|
|
494
|
+
}
|
|
495
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
496
|
+
};
|
|
497
|
+
Schema.lazy = function lazy(builder) {
|
|
498
|
+
const toJSON2 = () => {
|
|
499
|
+
if (!schema.inner[kSchema]) {
|
|
500
|
+
schema.inner = schema.builder();
|
|
501
|
+
schema.inner.meta = {
|
|
502
|
+
...schema.meta,
|
|
503
|
+
...schema.inner.meta
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
return schema.inner.toJSON();
|
|
507
|
+
};
|
|
508
|
+
const schema = new Schema({
|
|
509
|
+
type: "lazy",
|
|
510
|
+
builder,
|
|
511
|
+
inner: { toJSON: toJSON2 }
|
|
512
|
+
});
|
|
513
|
+
return schema;
|
|
514
|
+
};
|
|
515
|
+
Schema.natural = function natural() {
|
|
516
|
+
return Schema.number().step(1).min(0);
|
|
517
|
+
};
|
|
518
|
+
Schema.percent = function percent() {
|
|
519
|
+
return Schema.number().step(0.01).min(0).max(1).role("slider");
|
|
520
|
+
};
|
|
521
|
+
Schema.date = function date() {
|
|
522
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
523
|
+
const date2 = new Date(value);
|
|
524
|
+
if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
525
|
+
return date2;
|
|
526
|
+
}, true)]);
|
|
527
|
+
};
|
|
528
|
+
Schema.regExp = function regExp(flag = "") {
|
|
529
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
530
|
+
try {
|
|
531
|
+
return new RegExp(value, flag);
|
|
532
|
+
} catch (e) {
|
|
533
|
+
throw new ValidationError(e.message, options);
|
|
534
|
+
}
|
|
535
|
+
}, true)]);
|
|
536
|
+
};
|
|
537
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
538
|
+
return Schema.union([
|
|
539
|
+
Schema.is(ArrayBuffer),
|
|
540
|
+
Schema.is(SharedArrayBuffer),
|
|
541
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
542
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
543
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
544
|
+
}, true),
|
|
545
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
546
|
+
try {
|
|
547
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
548
|
+
} catch (e) {
|
|
549
|
+
throw new ValidationError(e.message, options);
|
|
550
|
+
}
|
|
551
|
+
}, true)] : []
|
|
552
|
+
]);
|
|
553
|
+
};
|
|
554
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
555
|
+
if (!schema.inner[kSchema]) {
|
|
556
|
+
schema.inner = schema.builder();
|
|
557
|
+
schema.inner.meta = {
|
|
558
|
+
...schema.meta,
|
|
559
|
+
...schema.inner.meta
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
563
|
+
});
|
|
564
|
+
Schema.extend("any", (data) => {
|
|
565
|
+
return [data];
|
|
566
|
+
});
|
|
567
|
+
Schema.extend("never", (data, _, options) => {
|
|
568
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
569
|
+
});
|
|
570
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
571
|
+
if (deepEqual(data, value)) return [value];
|
|
572
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
573
|
+
});
|
|
574
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
575
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
576
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
577
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
578
|
+
}
|
|
579
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
580
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
581
|
+
if (meta.pattern) {
|
|
582
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
583
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
584
|
+
}
|
|
585
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
586
|
+
return [data];
|
|
587
|
+
});
|
|
588
|
+
function decimalShift(data, digits) {
|
|
589
|
+
const str = data.toString();
|
|
590
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
591
|
+
const index = str.indexOf(".");
|
|
592
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
593
|
+
const frac = str.slice(index + 1);
|
|
594
|
+
const integer = str.slice(0, index);
|
|
595
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
596
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
597
|
+
}
|
|
598
|
+
function isMultipleOf(data, min, step) {
|
|
599
|
+
step = Math.abs(step);
|
|
600
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
601
|
+
const index = step.toString().indexOf(".");
|
|
602
|
+
const digits = step.toString().slice(index + 1).length;
|
|
603
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
604
|
+
}
|
|
605
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
606
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
607
|
+
checkWithinRange(data, meta, "number", options);
|
|
608
|
+
const { step } = meta;
|
|
609
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
610
|
+
return [data];
|
|
611
|
+
});
|
|
612
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
613
|
+
if (typeof data === "boolean") return [data];
|
|
614
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
615
|
+
});
|
|
616
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
617
|
+
let value = 0, keys = [];
|
|
618
|
+
if (typeof data === "number") {
|
|
619
|
+
value = data;
|
|
620
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
621
|
+
} else if (Array.isArray(data)) {
|
|
622
|
+
keys = data;
|
|
623
|
+
for (const key of keys) {
|
|
624
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
625
|
+
if (key in bits) value |= bits[key];
|
|
626
|
+
}
|
|
627
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
628
|
+
if (value === meta.default) return [value];
|
|
629
|
+
return [value, keys];
|
|
630
|
+
});
|
|
631
|
+
Schema.extend("function", (data, _, options) => {
|
|
632
|
+
if (typeof data === "function") return [data];
|
|
633
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
634
|
+
});
|
|
635
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
636
|
+
if (typeof constructor === "function") {
|
|
637
|
+
if (data instanceof constructor) return [data];
|
|
638
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
639
|
+
} else {
|
|
640
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
641
|
+
let prototype = Object.getPrototypeOf(data);
|
|
642
|
+
while (prototype) {
|
|
643
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
644
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
645
|
+
}
|
|
646
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
function property(data, key, schema, options) {
|
|
650
|
+
try {
|
|
651
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
652
|
+
...options,
|
|
653
|
+
path: [...options.path || [], key]
|
|
654
|
+
});
|
|
655
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
656
|
+
return value;
|
|
657
|
+
} catch (e) {
|
|
658
|
+
if (!options?.autofix) throw e;
|
|
659
|
+
delete data[key];
|
|
660
|
+
return schema.meta.default;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
664
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
665
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
666
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
667
|
+
});
|
|
668
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
669
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
670
|
+
const result = {};
|
|
671
|
+
for (const key in data) {
|
|
672
|
+
let rKey;
|
|
673
|
+
try {
|
|
674
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
675
|
+
} catch (error) {
|
|
676
|
+
if (strict) continue;
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
result[rKey] = property(data, key, inner, options);
|
|
680
|
+
data[rKey] = data[key];
|
|
681
|
+
if (key !== rKey) delete data[key];
|
|
682
|
+
}
|
|
683
|
+
return [result];
|
|
684
|
+
});
|
|
685
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
686
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
687
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
688
|
+
if (strict) return [result];
|
|
689
|
+
result.push(...data.slice(list.length));
|
|
690
|
+
return [result];
|
|
691
|
+
});
|
|
692
|
+
function merge(result, data) {
|
|
693
|
+
for (const key in data) {
|
|
694
|
+
if (key in result) continue;
|
|
695
|
+
result[key] = data[key];
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
699
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
700
|
+
const result = {};
|
|
701
|
+
for (const key in dict) {
|
|
702
|
+
const value = property(data, key, dict[key], options);
|
|
703
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
704
|
+
}
|
|
705
|
+
if (!strict) merge(result, data);
|
|
706
|
+
return [result];
|
|
707
|
+
});
|
|
708
|
+
Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
|
|
709
|
+
const messages = [];
|
|
710
|
+
for (const inner of list) try {
|
|
711
|
+
return Schema.resolve(data, inner, options, strict);
|
|
712
|
+
} catch (error) {
|
|
713
|
+
messages.push(error);
|
|
714
|
+
}
|
|
715
|
+
throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
716
|
+
});
|
|
717
|
+
Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
|
|
718
|
+
if (!list.length) return [data];
|
|
719
|
+
let result;
|
|
720
|
+
for (const inner of list) {
|
|
721
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
722
|
+
if (isNullable(value)) continue;
|
|
723
|
+
if (isNullable(result)) result = value;
|
|
724
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
725
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
726
|
+
else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
727
|
+
}
|
|
728
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
729
|
+
return [result];
|
|
730
|
+
});
|
|
731
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
732
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
733
|
+
if (preserve) return [callback(result)];
|
|
734
|
+
else return [callback(result), callback(adapted)];
|
|
735
|
+
});
|
|
736
|
+
var formatters = {};
|
|
737
|
+
function defineMethod(name2, keys, format) {
|
|
738
|
+
formatters[name2] = format;
|
|
739
|
+
Object.assign(Schema, { [name2](...args) {
|
|
740
|
+
const schema = new Schema({ type: name2 });
|
|
741
|
+
keys.forEach((key, index) => {
|
|
742
|
+
switch (key) {
|
|
743
|
+
case "sKey":
|
|
744
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
745
|
+
break;
|
|
746
|
+
case "inner":
|
|
747
|
+
schema.inner = Schema.from(args[index]);
|
|
748
|
+
break;
|
|
749
|
+
case "list":
|
|
750
|
+
schema.list = args[index].map(Schema.from);
|
|
751
|
+
break;
|
|
752
|
+
case "dict":
|
|
753
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
754
|
+
break;
|
|
755
|
+
case "bits":
|
|
756
|
+
schema.bits = {};
|
|
757
|
+
for (const key2 in args[index]) {
|
|
758
|
+
if (typeof args[index][key2] !== "number") continue;
|
|
759
|
+
schema.bits[key2] = args[index][key2];
|
|
760
|
+
}
|
|
761
|
+
break;
|
|
762
|
+
case "callback": {
|
|
763
|
+
const callback = schema.callback = args[index];
|
|
764
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
765
|
+
break;
|
|
766
|
+
}
|
|
767
|
+
case "constructor": {
|
|
768
|
+
const constructor = schema.constructor = args[index];
|
|
769
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
770
|
+
break;
|
|
771
|
+
}
|
|
772
|
+
default:
|
|
773
|
+
schema[key] = args[index];
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
if (name2 === "object" || name2 === "dict") schema.meta.default = {};
|
|
777
|
+
else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
|
|
778
|
+
else if (name2 === "bitset") schema.meta.default = 0;
|
|
779
|
+
return schema;
|
|
780
|
+
} });
|
|
781
|
+
}
|
|
782
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
783
|
+
if (typeof constructor === "function") return constructor.name;
|
|
784
|
+
else return constructor;
|
|
785
|
+
});
|
|
786
|
+
defineMethod("any", [], () => "any");
|
|
787
|
+
defineMethod("never", [], () => "never");
|
|
788
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
789
|
+
defineMethod("string", [], () => "string");
|
|
790
|
+
defineMethod("number", [], () => "number");
|
|
791
|
+
defineMethod("boolean", [], () => "boolean");
|
|
792
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
793
|
+
defineMethod("function", [], () => "function");
|
|
794
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
795
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
796
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
797
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
798
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
799
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
800
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
801
|
+
}).join(", ")} }`;
|
|
802
|
+
});
|
|
803
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
804
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
805
|
+
return inline ? `(${result})` : result;
|
|
806
|
+
});
|
|
807
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
808
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
809
|
+
});
|
|
810
|
+
defineMethod("transform", [
|
|
811
|
+
"inner",
|
|
812
|
+
"callback",
|
|
813
|
+
"preserve"
|
|
814
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
815
|
+
|
|
816
|
+
// ../dsh-tui/plugins/zen-proxy/index.js
|
|
817
|
+
import http from "node:http";
|
|
818
|
+
import https from "node:https";
|
|
819
|
+
var name = "zen-proxy";
|
|
820
|
+
var Config = Schema.object({
|
|
821
|
+
host: Schema.string().default("127.0.0.1"),
|
|
822
|
+
port: Schema.number().default(4097),
|
|
823
|
+
upstreamHost: Schema.string().default("opencode.ai"),
|
|
824
|
+
upstreamBasePath: Schema.string().default("/zen/v1"),
|
|
825
|
+
userAgent: Schema.string().default("opencode/1.15.5 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14"),
|
|
826
|
+
clientHeader: Schema.string().default("cli"),
|
|
827
|
+
projectHeader: Schema.string().default("global")
|
|
828
|
+
});
|
|
829
|
+
var inject = [];
|
|
830
|
+
var rnd = (p) => `${p}${Math.random().toString(36).slice(2, 12)}`;
|
|
831
|
+
function apply(ctx, config) {
|
|
832
|
+
const server = http.createServer((req, res) => {
|
|
833
|
+
const { method, url } = req;
|
|
834
|
+
if (method === "GET" && url === "/v1/models") {
|
|
835
|
+
forward(req, res, { method: "GET", path: `${config.upstreamBasePath}/models`, body: null });
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (method !== "POST" || url !== "/v1/chat/completions") {
|
|
839
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
840
|
+
res.end(JSON.stringify({ error: { type: "not_found", message: `zen-proxy: unsupported ${method} ${url}` } }));
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
let body = "";
|
|
844
|
+
req.on("data", (c) => body += c);
|
|
845
|
+
req.on("end", () => {
|
|
846
|
+
forward(req, res, { method: "POST", path: `${config.upstreamBasePath}/chat/completions`, body });
|
|
847
|
+
});
|
|
848
|
+
});
|
|
849
|
+
server.on("error", (error) => {
|
|
850
|
+
ctx.logger.warn(`zen-proxy: server error: ${error.message}`);
|
|
851
|
+
});
|
|
852
|
+
ctx.effect(() => {
|
|
853
|
+
server.listen(config.port, config.host, () => {
|
|
854
|
+
ctx.logger.info(
|
|
855
|
+
`zen-proxy: listening on http://${config.host}:${config.port}${config.upstreamBasePath} (upstream https://${config.upstreamHost})`
|
|
856
|
+
);
|
|
857
|
+
});
|
|
858
|
+
return () => {
|
|
859
|
+
server.close();
|
|
860
|
+
};
|
|
861
|
+
}, "zen-proxy.server");
|
|
862
|
+
function forward(req, res, { method, path, body }) {
|
|
863
|
+
const headers = {
|
|
864
|
+
"content-type": "application/json",
|
|
865
|
+
// Pass through the caller's Authorization if present; nothing else.
|
|
866
|
+
...req.headers.authorization ? { authorization: req.headers.authorization } : {},
|
|
867
|
+
"user-agent": config.userAgent,
|
|
868
|
+
"x-opencode-client": config.clientHeader,
|
|
869
|
+
"x-opencode-project": config.projectHeader,
|
|
870
|
+
"x-opencode-session": rnd("ses_"),
|
|
871
|
+
"x-opencode-request": rnd("msg_")
|
|
872
|
+
};
|
|
873
|
+
if (body !== null) headers["content-length"] = Buffer.byteLength(body);
|
|
874
|
+
const out = https.request(
|
|
875
|
+
{
|
|
876
|
+
host: config.upstreamHost,
|
|
877
|
+
port: 443,
|
|
878
|
+
method,
|
|
879
|
+
path,
|
|
880
|
+
headers
|
|
881
|
+
},
|
|
882
|
+
(up) => {
|
|
883
|
+
res.writeHead(up.statusCode, up.headers);
|
|
884
|
+
up.pipe(res);
|
|
885
|
+
}
|
|
886
|
+
);
|
|
887
|
+
out.on("error", (e) => {
|
|
888
|
+
ctx.logger.warn(`zen-proxy: upstream error: ${e.message}`);
|
|
889
|
+
res.writeHead(502);
|
|
890
|
+
res.end(String(e));
|
|
891
|
+
});
|
|
892
|
+
if (body !== null) out.end(body);
|
|
893
|
+
else out.end();
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
export {
|
|
897
|
+
Config,
|
|
898
|
+
apply,
|
|
899
|
+
inject,
|
|
900
|
+
name
|
|
901
|
+
};
|