dsh-interconnect 0.1.0
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/LICENSE +21 -0
- package/README.md +63 -0
- package/cordis.patch.yml +12 -0
- package/dsh.plugin.json +9 -0
- package/lib/index.js +1342 -0
- package/lib/interconnect/index.js +1343 -0
- package/lib/interconnect/index.js.map +7 -0
- package/lib/interconnect/invariant.js +25 -0
- package/lib/interconnect/invariant.js.map +7 -0
- package/lib/tool-interconnect/index.js +84 -0
- package/lib/tool-interconnect/index.js.map +7 -0
- package/lib/tool-interconnect/invariant.js +13 -0
- package/lib/tool-interconnect/invariant.js.map +7 -0
- package/lib/types/index.d.ts +9 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/interconnect/index.d.ts +106 -0
- package/lib/types/interconnect/index.d.ts.map +1 -0
- package/lib/types/interconnect/invariant.d.ts +16 -0
- package/lib/types/interconnect/invariant.d.ts.map +1 -0
- package/lib/types/interconnect/types.d.ts +132 -0
- package/lib/types/interconnect/types.d.ts.map +1 -0
- package/lib/types/tool-interconnect/index.d.ts +21 -0
- package/lib/types/tool-interconnect/index.d.ts.map +1 -0
- package/lib/types/tool-interconnect/invariant.d.ts +16 -0
- package/lib/types/tool-interconnect/invariant.d.ts.map +1 -0
- package/package.json +76 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1342 @@
|
|
|
1
|
+
// src/interconnect/index.ts
|
|
2
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
3
|
+
import {
|
|
4
|
+
clientRequestSchema,
|
|
5
|
+
serverResponseSchema,
|
|
6
|
+
RpcId
|
|
7
|
+
} from "@deepseek-ai/dsh-host-apiproxy/api";
|
|
8
|
+
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
9
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
10
|
+
|
|
11
|
+
// ../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/misc.ts
|
|
12
|
+
function isNullable(value) {
|
|
13
|
+
return value === null || value === void 0;
|
|
14
|
+
}
|
|
15
|
+
function isPlainObject(data) {
|
|
16
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
17
|
+
}
|
|
18
|
+
function filterKeys(object, filter) {
|
|
19
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
20
|
+
}
|
|
21
|
+
function mapValues(object, transform) {
|
|
22
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
23
|
+
}
|
|
24
|
+
function pick(source, keys, forced) {
|
|
25
|
+
if (!keys) return { ...source };
|
|
26
|
+
const result = {};
|
|
27
|
+
for (const key of keys) {
|
|
28
|
+
if (forced || source[key] !== void 0) result[key] = source[key];
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/types.ts
|
|
34
|
+
function is(type, value) {
|
|
35
|
+
if (arguments.length === 1) return (value2) => is(type, value2);
|
|
36
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
37
|
+
}
|
|
38
|
+
function isArrayBufferLike(value) {
|
|
39
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
40
|
+
}
|
|
41
|
+
function isArrayBufferSource(value) {
|
|
42
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
43
|
+
}
|
|
44
|
+
var Binary;
|
|
45
|
+
((Binary2) => {
|
|
46
|
+
Binary2.is = isArrayBufferLike;
|
|
47
|
+
Binary2.isSource = isArrayBufferSource;
|
|
48
|
+
function fromSource(source) {
|
|
49
|
+
if (ArrayBuffer.isView(source)) {
|
|
50
|
+
return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
51
|
+
} else {
|
|
52
|
+
return source;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
Binary2.fromSource = fromSource;
|
|
56
|
+
function toBase64(source) {
|
|
57
|
+
source = fromSource(source);
|
|
58
|
+
if (typeof Buffer !== "undefined") {
|
|
59
|
+
return Buffer.from(source).toString("base64");
|
|
60
|
+
}
|
|
61
|
+
let binary = "";
|
|
62
|
+
const bytes = new Uint8Array(source);
|
|
63
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
64
|
+
binary += String.fromCharCode(bytes[i]);
|
|
65
|
+
}
|
|
66
|
+
return btoa(binary);
|
|
67
|
+
}
|
|
68
|
+
Binary2.toBase64 = toBase64;
|
|
69
|
+
function fromBase64(source) {
|
|
70
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
71
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
72
|
+
}
|
|
73
|
+
Binary2.fromBase64 = fromBase64;
|
|
74
|
+
function toHex(source) {
|
|
75
|
+
source = fromSource(source);
|
|
76
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
77
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
78
|
+
}
|
|
79
|
+
Binary2.toHex = toHex;
|
|
80
|
+
function fromHex(source) {
|
|
81
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
82
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
83
|
+
const buffer = [];
|
|
84
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
85
|
+
buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
86
|
+
}
|
|
87
|
+
return Uint8Array.from(buffer).buffer;
|
|
88
|
+
}
|
|
89
|
+
Binary2.fromHex = fromHex;
|
|
90
|
+
})(Binary || (Binary = {}));
|
|
91
|
+
var base64ToArrayBuffer = Binary.fromBase64;
|
|
92
|
+
var arrayBufferToBase64 = Binary.toBase64;
|
|
93
|
+
var hexToArrayBuffer = Binary.fromHex;
|
|
94
|
+
var arrayBufferToHex = Binary.toHex;
|
|
95
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
96
|
+
if (!source || typeof source !== "object") return source;
|
|
97
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
98
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
99
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
100
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
101
|
+
const cached = refs.get(source);
|
|
102
|
+
if (cached) return cached;
|
|
103
|
+
if (Array.isArray(source)) {
|
|
104
|
+
const result2 = [];
|
|
105
|
+
refs.set(source, result2);
|
|
106
|
+
source.forEach((value, index) => {
|
|
107
|
+
result2[index] = Reflect.apply(clone, null, [value, refs]);
|
|
108
|
+
});
|
|
109
|
+
return result2;
|
|
110
|
+
}
|
|
111
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
112
|
+
refs.set(source, result);
|
|
113
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
114
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
115
|
+
if ("value" in descriptor) {
|
|
116
|
+
descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
117
|
+
}
|
|
118
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
function deepEqual(a, b, strict) {
|
|
123
|
+
if (a === b) return true;
|
|
124
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
125
|
+
if (typeof a !== typeof b) return false;
|
|
126
|
+
if (typeof a !== "object") return false;
|
|
127
|
+
if (!a || !b) return false;
|
|
128
|
+
function check(test, then) {
|
|
129
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
130
|
+
}
|
|
131
|
+
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) => {
|
|
132
|
+
if (a2.byteLength !== b2.byteLength) return false;
|
|
133
|
+
const viewA = new Uint8Array(a2);
|
|
134
|
+
const viewB = new Uint8Array(b2);
|
|
135
|
+
for (let i = 0; i < viewA.length; i++) {
|
|
136
|
+
if (viewA[i] !== viewB[i]) return false;
|
|
137
|
+
}
|
|
138
|
+
return true;
|
|
139
|
+
}) ?? Object.keys({ ...a, ...b }).every((key) => deepEqual(a[key], b[key], strict));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/time.ts
|
|
143
|
+
var Time;
|
|
144
|
+
((Time2) => {
|
|
145
|
+
Time2.millisecond = 1;
|
|
146
|
+
Time2.second = 1e3;
|
|
147
|
+
Time2.minute = Time2.second * 60;
|
|
148
|
+
Time2.hour = Time2.minute * 60;
|
|
149
|
+
Time2.day = Time2.hour * 24;
|
|
150
|
+
Time2.week = Time2.day * 7;
|
|
151
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
152
|
+
function setTimezoneOffset(offset) {
|
|
153
|
+
timezoneOffset = offset;
|
|
154
|
+
}
|
|
155
|
+
Time2.setTimezoneOffset = setTimezoneOffset;
|
|
156
|
+
function getTimezoneOffset() {
|
|
157
|
+
return timezoneOffset;
|
|
158
|
+
}
|
|
159
|
+
Time2.getTimezoneOffset = getTimezoneOffset;
|
|
160
|
+
function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
|
|
161
|
+
if (typeof date2 === "number") date2 = new Date(date2);
|
|
162
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
163
|
+
return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
|
|
164
|
+
}
|
|
165
|
+
Time2.getDateNumber = getDateNumber;
|
|
166
|
+
function fromDateNumber(value, offset) {
|
|
167
|
+
const date2 = new Date(value * Time2.day);
|
|
168
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
169
|
+
return new Date(+date2 + offset * Time2.minute);
|
|
170
|
+
}
|
|
171
|
+
Time2.fromDateNumber = fromDateNumber;
|
|
172
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
173
|
+
const timeRegExp = new RegExp(`^${[
|
|
174
|
+
"w(?:eek(?:s)?)?",
|
|
175
|
+
"d(?:ay(?:s)?)?",
|
|
176
|
+
"h(?:our(?:s)?)?",
|
|
177
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
178
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
179
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
180
|
+
function parseTime(source) {
|
|
181
|
+
const capture = timeRegExp.exec(source);
|
|
182
|
+
if (!capture) return 0;
|
|
183
|
+
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);
|
|
184
|
+
}
|
|
185
|
+
Time2.parseTime = parseTime;
|
|
186
|
+
function parseDate(date2) {
|
|
187
|
+
const parsed = parseTime(date2);
|
|
188
|
+
if (parsed) {
|
|
189
|
+
date2 = Date.now() + parsed;
|
|
190
|
+
} else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) {
|
|
191
|
+
date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
|
|
192
|
+
} else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) {
|
|
193
|
+
date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
|
|
194
|
+
}
|
|
195
|
+
return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
|
|
196
|
+
}
|
|
197
|
+
Time2.parseDate = parseDate;
|
|
198
|
+
function format(ms) {
|
|
199
|
+
const abs = Math.abs(ms);
|
|
200
|
+
if (abs >= Time2.day - Time2.hour / 2) {
|
|
201
|
+
return Math.round(ms / Time2.day) + "d";
|
|
202
|
+
} else if (abs >= Time2.hour - Time2.minute / 2) {
|
|
203
|
+
return Math.round(ms / Time2.hour) + "h";
|
|
204
|
+
} else if (abs >= Time2.minute - Time2.second / 2) {
|
|
205
|
+
return Math.round(ms / Time2.minute) + "m";
|
|
206
|
+
} else if (abs >= Time2.second) {
|
|
207
|
+
return Math.round(ms / Time2.second) + "s";
|
|
208
|
+
}
|
|
209
|
+
return ms + "ms";
|
|
210
|
+
}
|
|
211
|
+
Time2.format = format;
|
|
212
|
+
function toDigits(source, length = 2) {
|
|
213
|
+
return source.toString().padStart(length, "0");
|
|
214
|
+
}
|
|
215
|
+
Time2.toDigits = toDigits;
|
|
216
|
+
function template(template2, time = /* @__PURE__ */ new Date()) {
|
|
217
|
+
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));
|
|
218
|
+
}
|
|
219
|
+
Time2.template = template;
|
|
220
|
+
})(Time || (Time = {}));
|
|
221
|
+
|
|
222
|
+
// ../.dsh/source/staging-20260807T143236Z/vendor/schemastery/lib/index.mjs
|
|
223
|
+
var kSchema = Symbol.for("schemastery");
|
|
224
|
+
var kValidationError = Symbol.for("ValidationError");
|
|
225
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
226
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
227
|
+
var ValidationError = class extends TypeError {
|
|
228
|
+
options;
|
|
229
|
+
name = "ValidationError";
|
|
230
|
+
constructor(message, options) {
|
|
231
|
+
let prefix = "$";
|
|
232
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
233
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
234
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
235
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
236
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
237
|
+
this.options = options;
|
|
238
|
+
}
|
|
239
|
+
static is(error) {
|
|
240
|
+
return !!error?.[kValidationError];
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
244
|
+
var Schema = function(options) {
|
|
245
|
+
const schema = function(data, options2 = {}) {
|
|
246
|
+
return Schema.resolve(data, schema, options2)[0];
|
|
247
|
+
};
|
|
248
|
+
if (options.refs) {
|
|
249
|
+
const refs = mapValues(options.refs, (options2) => new Schema(options2));
|
|
250
|
+
const getRef = (uid) => refs[uid];
|
|
251
|
+
for (const key in refs) {
|
|
252
|
+
const options2 = refs[key];
|
|
253
|
+
options2.sKey = getRef(options2.sKey);
|
|
254
|
+
options2.inner = getRef(options2.inner);
|
|
255
|
+
options2.list = options2.list && options2.list.map(getRef);
|
|
256
|
+
options2.dict = options2.dict && mapValues(options2.dict, getRef);
|
|
257
|
+
}
|
|
258
|
+
return refs[options.uid];
|
|
259
|
+
}
|
|
260
|
+
Object.assign(schema, options);
|
|
261
|
+
if (typeof schema.callback === "string") try {
|
|
262
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
263
|
+
} catch {
|
|
264
|
+
}
|
|
265
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
266
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
267
|
+
schema.meta ||= {};
|
|
268
|
+
schema.toString = schema.toString.bind(schema);
|
|
269
|
+
return schema;
|
|
270
|
+
};
|
|
271
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
272
|
+
Schema.prototype[kSchema] = true;
|
|
273
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
274
|
+
return {
|
|
275
|
+
version: 1,
|
|
276
|
+
vendor: "schemastery",
|
|
277
|
+
validate: (value) => {
|
|
278
|
+
try {
|
|
279
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
282
|
+
message: error.message,
|
|
283
|
+
path: error.options.path
|
|
284
|
+
}] };
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
} });
|
|
290
|
+
Schema.ValidationError = ValidationError;
|
|
291
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
292
|
+
if (globalThis.__schemastery_refs__) {
|
|
293
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
294
|
+
return this.uid;
|
|
295
|
+
}
|
|
296
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
297
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
298
|
+
const result = {
|
|
299
|
+
uid: this.uid,
|
|
300
|
+
refs: globalThis.__schemastery_refs__
|
|
301
|
+
};
|
|
302
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
303
|
+
return result;
|
|
304
|
+
};
|
|
305
|
+
Schema.prototype.set = function set(key, value) {
|
|
306
|
+
this.dict[key] = value;
|
|
307
|
+
return this;
|
|
308
|
+
};
|
|
309
|
+
Schema.prototype.push = function push(value) {
|
|
310
|
+
this.list.push(value);
|
|
311
|
+
return this;
|
|
312
|
+
};
|
|
313
|
+
function mergeDesc(original, messages) {
|
|
314
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
315
|
+
for (const locale in messages) {
|
|
316
|
+
const value = messages[locale];
|
|
317
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
318
|
+
else if (typeof value === "string") result[locale] = value;
|
|
319
|
+
}
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
function getInner(value) {
|
|
323
|
+
return value?.$value ?? value?.$inner;
|
|
324
|
+
}
|
|
325
|
+
function extractKeys(data) {
|
|
326
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
327
|
+
}
|
|
328
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
329
|
+
const schema = Schema(this);
|
|
330
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
331
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
332
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
333
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
334
|
+
});
|
|
335
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
336
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
337
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
338
|
+
if (Array.isArray(data)) return data[index];
|
|
339
|
+
return extractKeys(data);
|
|
340
|
+
}));
|
|
341
|
+
});
|
|
342
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
343
|
+
if (getInner(data)) return getInner(data);
|
|
344
|
+
return extractKeys(data);
|
|
345
|
+
}));
|
|
346
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
347
|
+
return schema;
|
|
348
|
+
};
|
|
349
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
350
|
+
const schema = Schema(this);
|
|
351
|
+
schema.meta = {
|
|
352
|
+
...schema.meta,
|
|
353
|
+
[key]: value
|
|
354
|
+
};
|
|
355
|
+
return schema;
|
|
356
|
+
};
|
|
357
|
+
for (const key of [
|
|
358
|
+
"required",
|
|
359
|
+
"disabled",
|
|
360
|
+
"collapse",
|
|
361
|
+
"hidden",
|
|
362
|
+
"loose"
|
|
363
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
364
|
+
const schema = Schema(this);
|
|
365
|
+
schema.meta = {
|
|
366
|
+
...schema.meta,
|
|
367
|
+
[key]: value
|
|
368
|
+
};
|
|
369
|
+
return schema;
|
|
370
|
+
} });
|
|
371
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
372
|
+
const schema = Schema(this);
|
|
373
|
+
schema.meta.badges ||= [];
|
|
374
|
+
schema.meta.badges.push({
|
|
375
|
+
text: "deprecated",
|
|
376
|
+
type: "danger"
|
|
377
|
+
});
|
|
378
|
+
return schema;
|
|
379
|
+
};
|
|
380
|
+
Schema.prototype.experimental = function experimental() {
|
|
381
|
+
const schema = Schema(this);
|
|
382
|
+
schema.meta.badges ||= [];
|
|
383
|
+
schema.meta.badges.push({
|
|
384
|
+
text: "experimental",
|
|
385
|
+
type: "warning"
|
|
386
|
+
});
|
|
387
|
+
return schema;
|
|
388
|
+
};
|
|
389
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
390
|
+
const schema = Schema(this);
|
|
391
|
+
const pattern2 = pick(regexp, ["source", "flags"]);
|
|
392
|
+
schema.meta = {
|
|
393
|
+
...schema.meta,
|
|
394
|
+
pattern: pattern2
|
|
395
|
+
};
|
|
396
|
+
return schema;
|
|
397
|
+
};
|
|
398
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
399
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
400
|
+
if (isNullable(value)) return value;
|
|
401
|
+
if (this.type === "object" || this.type === "dict") {
|
|
402
|
+
const result = {};
|
|
403
|
+
for (const key in value) {
|
|
404
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
405
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
406
|
+
}
|
|
407
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
408
|
+
return result;
|
|
409
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
410
|
+
const result = [];
|
|
411
|
+
value.forEach((value2, index) => {
|
|
412
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
413
|
+
const item = schema ? schema.simplify(value2) : value2;
|
|
414
|
+
result.push(item);
|
|
415
|
+
});
|
|
416
|
+
return result;
|
|
417
|
+
} else if (this.type === "intersect") {
|
|
418
|
+
const result = {};
|
|
419
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
420
|
+
return result;
|
|
421
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
422
|
+
Schema.resolve(value, schema, {});
|
|
423
|
+
return schema.simplify(value);
|
|
424
|
+
} catch {
|
|
425
|
+
}
|
|
426
|
+
return value;
|
|
427
|
+
};
|
|
428
|
+
Schema.prototype.toString = function toString(inline) {
|
|
429
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
430
|
+
};
|
|
431
|
+
Schema.prototype.role = function role(role, extra2) {
|
|
432
|
+
const schema = Schema(this);
|
|
433
|
+
schema.meta = {
|
|
434
|
+
...schema.meta,
|
|
435
|
+
role,
|
|
436
|
+
extra: extra2
|
|
437
|
+
};
|
|
438
|
+
return schema;
|
|
439
|
+
};
|
|
440
|
+
for (const key of [
|
|
441
|
+
"default",
|
|
442
|
+
"link",
|
|
443
|
+
"comment",
|
|
444
|
+
"description",
|
|
445
|
+
"max",
|
|
446
|
+
"min",
|
|
447
|
+
"step"
|
|
448
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
449
|
+
const schema = Schema(this);
|
|
450
|
+
schema.meta = {
|
|
451
|
+
...schema.meta,
|
|
452
|
+
[key]: value
|
|
453
|
+
};
|
|
454
|
+
return schema;
|
|
455
|
+
} });
|
|
456
|
+
var resolvers = {};
|
|
457
|
+
Schema.extend = function extend(type, resolve2) {
|
|
458
|
+
resolvers[type] = resolve2;
|
|
459
|
+
};
|
|
460
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
461
|
+
if (!schema) return [data];
|
|
462
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
463
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
464
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
465
|
+
let current = schema;
|
|
466
|
+
let fallback = schema.meta.default;
|
|
467
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
468
|
+
current = current.list[0];
|
|
469
|
+
fallback = current?.meta.default;
|
|
470
|
+
}
|
|
471
|
+
if (isNullable(fallback)) return [data];
|
|
472
|
+
data = clone(fallback);
|
|
473
|
+
}
|
|
474
|
+
const callback = resolvers[schema.type];
|
|
475
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
476
|
+
try {
|
|
477
|
+
return callback(data, schema, options, strict);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
if (!schema.meta.loose) throw error;
|
|
480
|
+
return [schema.meta.default];
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
Schema.from = function from(source) {
|
|
484
|
+
if (isNullable(source)) return Schema.any();
|
|
485
|
+
else if ([
|
|
486
|
+
"string",
|
|
487
|
+
"number",
|
|
488
|
+
"boolean"
|
|
489
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
490
|
+
else if (source[kSchema]) return source;
|
|
491
|
+
else if (typeof source === "function") switch (source) {
|
|
492
|
+
case String:
|
|
493
|
+
return Schema.string().required();
|
|
494
|
+
case Number:
|
|
495
|
+
return Schema.number().required();
|
|
496
|
+
case Boolean:
|
|
497
|
+
return Schema.boolean().required();
|
|
498
|
+
case Function:
|
|
499
|
+
return Schema.function().required();
|
|
500
|
+
default:
|
|
501
|
+
return Schema.is(source).required();
|
|
502
|
+
}
|
|
503
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
504
|
+
};
|
|
505
|
+
Schema.lazy = function lazy(builder) {
|
|
506
|
+
const toJSON2 = () => {
|
|
507
|
+
if (!schema.inner[kSchema]) {
|
|
508
|
+
schema.inner = schema.builder();
|
|
509
|
+
schema.inner.meta = {
|
|
510
|
+
...schema.meta,
|
|
511
|
+
...schema.inner.meta
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
return schema.inner.toJSON();
|
|
515
|
+
};
|
|
516
|
+
const schema = new Schema({
|
|
517
|
+
type: "lazy",
|
|
518
|
+
builder,
|
|
519
|
+
inner: { toJSON: toJSON2 }
|
|
520
|
+
});
|
|
521
|
+
return schema;
|
|
522
|
+
};
|
|
523
|
+
Schema.natural = function natural() {
|
|
524
|
+
return Schema.number().step(1).min(0);
|
|
525
|
+
};
|
|
526
|
+
Schema.percent = function percent() {
|
|
527
|
+
return Schema.number().step(0.01).min(0).max(1).role("slider");
|
|
528
|
+
};
|
|
529
|
+
Schema.date = function date() {
|
|
530
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
531
|
+
const date2 = new Date(value);
|
|
532
|
+
if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
533
|
+
return date2;
|
|
534
|
+
}, true)]);
|
|
535
|
+
};
|
|
536
|
+
Schema.regExp = function regExp(flag = "") {
|
|
537
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
538
|
+
try {
|
|
539
|
+
return new RegExp(value, flag);
|
|
540
|
+
} catch (e) {
|
|
541
|
+
throw new ValidationError(e.message, options);
|
|
542
|
+
}
|
|
543
|
+
}, true)]);
|
|
544
|
+
};
|
|
545
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
546
|
+
return Schema.union([
|
|
547
|
+
Schema.is(ArrayBuffer),
|
|
548
|
+
Schema.is(SharedArrayBuffer),
|
|
549
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
550
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
551
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
552
|
+
}, true),
|
|
553
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
554
|
+
try {
|
|
555
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
556
|
+
} catch (e) {
|
|
557
|
+
throw new ValidationError(e.message, options);
|
|
558
|
+
}
|
|
559
|
+
}, true)] : []
|
|
560
|
+
]);
|
|
561
|
+
};
|
|
562
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
563
|
+
if (!schema.inner[kSchema]) {
|
|
564
|
+
schema.inner = schema.builder();
|
|
565
|
+
schema.inner.meta = {
|
|
566
|
+
...schema.meta,
|
|
567
|
+
...schema.inner.meta
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
571
|
+
});
|
|
572
|
+
Schema.extend("any", (data) => {
|
|
573
|
+
return [data];
|
|
574
|
+
});
|
|
575
|
+
Schema.extend("never", (data, _, options) => {
|
|
576
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
577
|
+
});
|
|
578
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
579
|
+
if (deepEqual(data, value)) return [value];
|
|
580
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
581
|
+
});
|
|
582
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
583
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
584
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
585
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
586
|
+
}
|
|
587
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
588
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
589
|
+
if (meta.pattern) {
|
|
590
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
591
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
592
|
+
}
|
|
593
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
594
|
+
return [data];
|
|
595
|
+
});
|
|
596
|
+
function decimalShift(data, digits) {
|
|
597
|
+
const str = data.toString();
|
|
598
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
599
|
+
const index = str.indexOf(".");
|
|
600
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
601
|
+
const frac = str.slice(index + 1);
|
|
602
|
+
const integer = str.slice(0, index);
|
|
603
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
604
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
605
|
+
}
|
|
606
|
+
function isMultipleOf(data, min, step) {
|
|
607
|
+
step = Math.abs(step);
|
|
608
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
609
|
+
const index = step.toString().indexOf(".");
|
|
610
|
+
const digits = step.toString().slice(index + 1).length;
|
|
611
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
612
|
+
}
|
|
613
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
614
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
615
|
+
checkWithinRange(data, meta, "number", options);
|
|
616
|
+
const { step } = meta;
|
|
617
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
618
|
+
return [data];
|
|
619
|
+
});
|
|
620
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
621
|
+
if (typeof data === "boolean") return [data];
|
|
622
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
623
|
+
});
|
|
624
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
625
|
+
let value = 0, keys = [];
|
|
626
|
+
if (typeof data === "number") {
|
|
627
|
+
value = data;
|
|
628
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
629
|
+
} else if (Array.isArray(data)) {
|
|
630
|
+
keys = data;
|
|
631
|
+
for (const key of keys) {
|
|
632
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
633
|
+
if (key in bits) value |= bits[key];
|
|
634
|
+
}
|
|
635
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
636
|
+
if (value === meta.default) return [value];
|
|
637
|
+
return [value, keys];
|
|
638
|
+
});
|
|
639
|
+
Schema.extend("function", (data, _, options) => {
|
|
640
|
+
if (typeof data === "function") return [data];
|
|
641
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
642
|
+
});
|
|
643
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
644
|
+
if (typeof constructor === "function") {
|
|
645
|
+
if (data instanceof constructor) return [data];
|
|
646
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
647
|
+
} else {
|
|
648
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
649
|
+
let prototype = Object.getPrototypeOf(data);
|
|
650
|
+
while (prototype) {
|
|
651
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
652
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
653
|
+
}
|
|
654
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
function property(data, key, schema, options) {
|
|
658
|
+
try {
|
|
659
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
660
|
+
...options,
|
|
661
|
+
path: [...options.path || [], key]
|
|
662
|
+
});
|
|
663
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
664
|
+
return value;
|
|
665
|
+
} catch (e) {
|
|
666
|
+
if (!options?.autofix) throw e;
|
|
667
|
+
delete data[key];
|
|
668
|
+
return schema.meta.default;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
672
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
673
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
674
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
675
|
+
});
|
|
676
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
677
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
678
|
+
const result = {};
|
|
679
|
+
for (const key in data) {
|
|
680
|
+
let rKey;
|
|
681
|
+
try {
|
|
682
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
683
|
+
} catch (error) {
|
|
684
|
+
if (strict) continue;
|
|
685
|
+
throw error;
|
|
686
|
+
}
|
|
687
|
+
result[rKey] = property(data, key, inner, options);
|
|
688
|
+
data[rKey] = data[key];
|
|
689
|
+
if (key !== rKey) delete data[key];
|
|
690
|
+
}
|
|
691
|
+
return [result];
|
|
692
|
+
});
|
|
693
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
694
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
695
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
696
|
+
if (strict) return [result];
|
|
697
|
+
result.push(...data.slice(list.length));
|
|
698
|
+
return [result];
|
|
699
|
+
});
|
|
700
|
+
function merge(result, data) {
|
|
701
|
+
for (const key in data) {
|
|
702
|
+
if (key in result) continue;
|
|
703
|
+
result[key] = data[key];
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
707
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
708
|
+
const result = {};
|
|
709
|
+
for (const key in dict) {
|
|
710
|
+
const value = property(data, key, dict[key], options);
|
|
711
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
712
|
+
}
|
|
713
|
+
if (!strict) merge(result, data);
|
|
714
|
+
return [result];
|
|
715
|
+
});
|
|
716
|
+
Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
|
|
717
|
+
const messages = [];
|
|
718
|
+
for (const inner of list) try {
|
|
719
|
+
return Schema.resolve(data, inner, options, strict);
|
|
720
|
+
} catch (error) {
|
|
721
|
+
messages.push(error);
|
|
722
|
+
}
|
|
723
|
+
throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
724
|
+
});
|
|
725
|
+
Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
|
|
726
|
+
if (!list.length) return [data];
|
|
727
|
+
let result;
|
|
728
|
+
for (const inner of list) {
|
|
729
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
730
|
+
if (isNullable(value)) continue;
|
|
731
|
+
if (isNullable(result)) result = value;
|
|
732
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
733
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
734
|
+
else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
|
|
735
|
+
}
|
|
736
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
737
|
+
return [result];
|
|
738
|
+
});
|
|
739
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
740
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
741
|
+
if (preserve) return [callback(result)];
|
|
742
|
+
else return [callback(result), callback(adapted)];
|
|
743
|
+
});
|
|
744
|
+
var formatters = {};
|
|
745
|
+
function defineMethod(name, keys, format) {
|
|
746
|
+
formatters[name] = format;
|
|
747
|
+
Object.assign(Schema, { [name](...args) {
|
|
748
|
+
const schema = new Schema({ type: name });
|
|
749
|
+
keys.forEach((key, index) => {
|
|
750
|
+
switch (key) {
|
|
751
|
+
case "sKey":
|
|
752
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
753
|
+
break;
|
|
754
|
+
case "inner":
|
|
755
|
+
schema.inner = Schema.from(args[index]);
|
|
756
|
+
break;
|
|
757
|
+
case "list":
|
|
758
|
+
schema.list = args[index].map(Schema.from);
|
|
759
|
+
break;
|
|
760
|
+
case "dict":
|
|
761
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
762
|
+
break;
|
|
763
|
+
case "bits":
|
|
764
|
+
schema.bits = {};
|
|
765
|
+
for (const key2 in args[index]) {
|
|
766
|
+
if (typeof args[index][key2] !== "number") continue;
|
|
767
|
+
schema.bits[key2] = args[index][key2];
|
|
768
|
+
}
|
|
769
|
+
break;
|
|
770
|
+
case "callback": {
|
|
771
|
+
const callback = schema.callback = args[index];
|
|
772
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
case "constructor": {
|
|
776
|
+
const constructor = schema.constructor = args[index];
|
|
777
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
default:
|
|
781
|
+
schema[key] = args[index];
|
|
782
|
+
}
|
|
783
|
+
});
|
|
784
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
785
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
786
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
787
|
+
return schema;
|
|
788
|
+
} });
|
|
789
|
+
}
|
|
790
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
791
|
+
if (typeof constructor === "function") return constructor.name;
|
|
792
|
+
else return constructor;
|
|
793
|
+
});
|
|
794
|
+
defineMethod("any", [], () => "any");
|
|
795
|
+
defineMethod("never", [], () => "never");
|
|
796
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
797
|
+
defineMethod("string", [], () => "string");
|
|
798
|
+
defineMethod("number", [], () => "number");
|
|
799
|
+
defineMethod("boolean", [], () => "boolean");
|
|
800
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
801
|
+
defineMethod("function", [], () => "function");
|
|
802
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
803
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
804
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
805
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
806
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
807
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
808
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
809
|
+
}).join(", ")} }`;
|
|
810
|
+
});
|
|
811
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
812
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
813
|
+
return inline ? `(${result})` : result;
|
|
814
|
+
});
|
|
815
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
816
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
817
|
+
});
|
|
818
|
+
defineMethod("transform", [
|
|
819
|
+
"inner",
|
|
820
|
+
"callback",
|
|
821
|
+
"preserve"
|
|
822
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
823
|
+
|
|
824
|
+
// src/interconnect/index.ts
|
|
825
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
826
|
+
|
|
827
|
+
// src/interconnect/types.ts
|
|
828
|
+
var INTERCONNECT_CHANNEL = "/interconnect";
|
|
829
|
+
var INTERCONNECT_TOKEN_REF = "DSH_INTERCONNECT_TOKEN";
|
|
830
|
+
|
|
831
|
+
// src/interconnect/index.ts
|
|
832
|
+
var INVALID_REQUEST_RPC_ID = RpcId("invalid-request");
|
|
833
|
+
var MAX_REQUEST_BODY_BYTES = 1024 * 1024;
|
|
834
|
+
var LINK_CHANNEL = "/interconnect/link";
|
|
835
|
+
var notificationSchema = Schema.union([
|
|
836
|
+
Schema.object({ kind: Schema.const("agent/created"), sessionId: Schema.string() }),
|
|
837
|
+
Schema.object({ kind: Schema.const("agent/disposed"), sessionId: Schema.string() }),
|
|
838
|
+
Schema.object({ kind: Schema.const("agent/status"), sessionId: Schema.string(), status: Schema.union([Schema.const("idle"), Schema.const("running")]) }),
|
|
839
|
+
Schema.object({ kind: Schema.const("session/created"), sessionId: Schema.string(), parentSessionId: Schema.string() }),
|
|
840
|
+
Schema.object({ kind: Schema.const("session/disposed"), sessionId: Schema.string() }),
|
|
841
|
+
Schema.object({ kind: Schema.const("subagent/end"), provider: Schema.string(), childSessionId: Schema.string(), stopReason: Schema.string() })
|
|
842
|
+
]);
|
|
843
|
+
var linkFrameSchema = Schema.union([
|
|
844
|
+
Schema.object({ type: Schema.const("hello"), sender: Schema.string() }),
|
|
845
|
+
Schema.object({ type: Schema.const("event"), notification: notificationSchema })
|
|
846
|
+
]);
|
|
847
|
+
var sendPayloadSchema = Schema.object({
|
|
848
|
+
sessionId: Schema.string(),
|
|
849
|
+
text: Schema.string()
|
|
850
|
+
});
|
|
851
|
+
var eventPayloadSchema = Schema.object({
|
|
852
|
+
sender: Schema.string(),
|
|
853
|
+
notification: notificationSchema
|
|
854
|
+
});
|
|
855
|
+
var InterconnectService = class extends Service {
|
|
856
|
+
static inject = ["webServer", "agents", "credentials"];
|
|
857
|
+
static Config = Schema.object({
|
|
858
|
+
instanceId: Schema.string().default("dsh"),
|
|
859
|
+
requestTimeoutMs: Schema.natural().max(6e4).default(1e4),
|
|
860
|
+
peers: Schema.array(Schema.string()).default([]),
|
|
861
|
+
delivery: Schema.union([Schema.const("followup"), Schema.const("inject")]).default("followup")
|
|
862
|
+
});
|
|
863
|
+
instanceId;
|
|
864
|
+
requestTimeoutMs;
|
|
865
|
+
delivery;
|
|
866
|
+
peers = /* @__PURE__ */ new Set();
|
|
867
|
+
subscriptions = [];
|
|
868
|
+
server = new WebSocketServer({ noServer: true });
|
|
869
|
+
sockets = /* @__PURE__ */ new Set();
|
|
870
|
+
linkStates = /* @__PURE__ */ new Map();
|
|
871
|
+
heartbeatTimer;
|
|
872
|
+
/** Peer identity each live socket announced via its `hello` frame, if any. */
|
|
873
|
+
peerOf = /* @__PURE__ */ new WeakMap();
|
|
874
|
+
constructor(ctx, config) {
|
|
875
|
+
super(ctx, "interconnect");
|
|
876
|
+
this.instanceId = config.instanceId;
|
|
877
|
+
this.requestTimeoutMs = config.requestTimeoutMs;
|
|
878
|
+
this.delivery = config.delivery ?? "followup";
|
|
879
|
+
for (const peer of config.peers ?? []) this.peers.add(trimBase(peer));
|
|
880
|
+
const route = {
|
|
881
|
+
kind: "prefix",
|
|
882
|
+
path: INTERCONNECT_CHANNEL,
|
|
883
|
+
handler: (req, res) => this.handle(req, res)
|
|
884
|
+
};
|
|
885
|
+
ctx.effect(() => ctx.webServer.register(route), "interconnect: /interconnect route");
|
|
886
|
+
const upgrade = {
|
|
887
|
+
path: LINK_CHANNEL,
|
|
888
|
+
handler: (req, socket, head) => {
|
|
889
|
+
void this.handleUpgrade(req, socket, head);
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
ctx.effect(() => ctx.webServer.registerUpgrade(upgrade), "interconnect: /interconnect/link websocket");
|
|
893
|
+
this.heartbeatTimer = setInterval(() => {
|
|
894
|
+
for (const socket of this.sockets) {
|
|
895
|
+
if (socket.isAlive === false) {
|
|
896
|
+
socket.terminate();
|
|
897
|
+
this.sockets.delete(socket);
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
;
|
|
901
|
+
socket.isAlive = false;
|
|
902
|
+
socket.ping();
|
|
903
|
+
}
|
|
904
|
+
}, 3e4);
|
|
905
|
+
this.subscriptions.push(ctx.on("agent/status", ({ agent, status }) => {
|
|
906
|
+
this.fanout({ kind: "agent/status", sessionId: String(agent.session.id), status });
|
|
907
|
+
}));
|
|
908
|
+
this.subscriptions.push(ctx.on("agent/created", ({ agent }) => {
|
|
909
|
+
this.fanout({ kind: "agent/created", sessionId: String(agent.session.id) });
|
|
910
|
+
}));
|
|
911
|
+
this.subscriptions.push(ctx.on("agent/disposed", ({ agent }) => {
|
|
912
|
+
this.fanout({ kind: "agent/disposed", sessionId: String(agent.session.id) });
|
|
913
|
+
}));
|
|
914
|
+
this.subscriptions.push(ctx.on("session/created", (session) => {
|
|
915
|
+
const parentSessionId = session.header.parentSession === void 0 ? void 0 : String(session.header.parentSession);
|
|
916
|
+
this.fanout({
|
|
917
|
+
kind: "session/created",
|
|
918
|
+
sessionId: String(session.id),
|
|
919
|
+
...parentSessionId === void 0 ? {} : { parentSessionId }
|
|
920
|
+
});
|
|
921
|
+
}));
|
|
922
|
+
this.subscriptions.push(ctx.on("session/disposed", (session) => {
|
|
923
|
+
this.fanout({ kind: "session/disposed", sessionId: String(session.id) });
|
|
924
|
+
}));
|
|
925
|
+
this.subscriptions.push(ctx.on("subagent/end", (info) => {
|
|
926
|
+
if (!info.local) return;
|
|
927
|
+
this.fanout({
|
|
928
|
+
kind: "subagent/end",
|
|
929
|
+
provider: info.provider,
|
|
930
|
+
childSessionId: String(info.id),
|
|
931
|
+
stopReason: info.stopReason
|
|
932
|
+
});
|
|
933
|
+
}));
|
|
934
|
+
ctx.effect(() => () => {
|
|
935
|
+
for (const dispose of this.subscriptions.splice(0)) dispose();
|
|
936
|
+
}, "interconnect: event subscriptions");
|
|
937
|
+
ctx.effect(() => () => {
|
|
938
|
+
if (this.heartbeatTimer !== void 0) clearInterval(this.heartbeatTimer);
|
|
939
|
+
for (const state of this.linkStates.values()) state.close();
|
|
940
|
+
this.linkStates.clear();
|
|
941
|
+
for (const socket of this.sockets) socket.terminate();
|
|
942
|
+
this.sockets.clear();
|
|
943
|
+
this.server.close();
|
|
944
|
+
}, "interconnect: websocket teardown");
|
|
945
|
+
}
|
|
946
|
+
async send(request) {
|
|
947
|
+
const payload = { sessionId: request.sessionId, text: request.text };
|
|
948
|
+
const result = await this.post(request.baseUrl, "send", payload);
|
|
949
|
+
return result ?? { delivered: false, instance: this.instanceId };
|
|
950
|
+
}
|
|
951
|
+
async ping(baseUrl) {
|
|
952
|
+
return this.post(baseUrl, "ping", {});
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Add a peer origin to the event fan-out set at runtime. Returns a disposer
|
|
956
|
+
* that removes it. Duplicate origins are idempotent.
|
|
957
|
+
* @param peer - receiver origin, e.g. `http://127.0.0.1:3080`.
|
|
958
|
+
* @returns disposer removing the peer from the fan-out set.
|
|
959
|
+
*/
|
|
960
|
+
subscribe(peer) {
|
|
961
|
+
const trimmed = trimBase(peer);
|
|
962
|
+
this.peers.add(trimmed);
|
|
963
|
+
return () => {
|
|
964
|
+
this.peers.delete(trimmed);
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
/** Remove a peer origin from the event fan-out set. */
|
|
968
|
+
unsubscribe(peer) {
|
|
969
|
+
this.peers.delete(trimBase(peer));
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Open (and, on drop, re-open) a persistent WebSocket link to a peer. Local
|
|
973
|
+
* events stream over the link in real time, and events the peer pushes are
|
|
974
|
+
* surfaced as `interconnect/event`. Repeating for the same peer returns the
|
|
975
|
+
* existing handle.
|
|
976
|
+
* @param peer - receiver origin, e.g. `http://127.0.0.1:3080` (dialed as `ws:`).
|
|
977
|
+
* @returns a handle closing the link and cancelling reconnection.
|
|
978
|
+
*/
|
|
979
|
+
link(peer) {
|
|
980
|
+
const trimmed = trimBase(peer);
|
|
981
|
+
const existing = this.linkStates.get(trimmed);
|
|
982
|
+
if (existing !== void 0) return existing;
|
|
983
|
+
const state = new LinkState(this, trimmed);
|
|
984
|
+
this.linkStates.set(trimmed, state);
|
|
985
|
+
state.dial();
|
|
986
|
+
return state;
|
|
987
|
+
}
|
|
988
|
+
/** Remove a closed outbound link's state so a later `link` re-dials fresh. */
|
|
989
|
+
forgetLink(peer) {
|
|
990
|
+
this.linkStates.delete(peer);
|
|
991
|
+
}
|
|
992
|
+
/** Fan one serialized lifecycle fact out to every registered peer, fire-and-forget. */
|
|
993
|
+
fanout(notification) {
|
|
994
|
+
const payload = { sender: this.instanceId, notification };
|
|
995
|
+
for (const peer of this.peers) {
|
|
996
|
+
void this.post(peer, "event", payload);
|
|
997
|
+
}
|
|
998
|
+
this.broadcast(notification);
|
|
999
|
+
}
|
|
1000
|
+
/** Push one fact over every live WebSocket link, dropping closed sockets. */
|
|
1001
|
+
broadcast(notification) {
|
|
1002
|
+
if (this.sockets.size === 0) return;
|
|
1003
|
+
const frame = { type: "event", notification };
|
|
1004
|
+
const encoded = JSON.stringify(frame);
|
|
1005
|
+
for (const socket of this.sockets) {
|
|
1006
|
+
if (socket.readyState !== WebSocket.OPEN) {
|
|
1007
|
+
this.sockets.delete(socket);
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
socket.send(encoded);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
/** Inbound route handler: bearer auth first, then envelope dispatch. */
|
|
1014
|
+
async handle(req, res) {
|
|
1015
|
+
const token = await this.resolveToken();
|
|
1016
|
+
if (token === void 0) {
|
|
1017
|
+
res.writeHead(403);
|
|
1018
|
+
res.end("forbidden");
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
const expected = `Bearer ${token}`;
|
|
1022
|
+
const header = req.headers.authorization;
|
|
1023
|
+
if (header === void 0 || !timingSafeEqual(header, expected)) {
|
|
1024
|
+
res.writeHead(401);
|
|
1025
|
+
res.end("unauthorized");
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
await this.dispatch(req, res);
|
|
1029
|
+
}
|
|
1030
|
+
/** Parse the ClientRequest envelope and route to the named endpoint. */
|
|
1031
|
+
async dispatch(req, res) {
|
|
1032
|
+
const pathname = new URL(req.url ?? "/", "http://dsh.internal").pathname;
|
|
1033
|
+
const endpoint = endpointFromPath(INTERCONNECT_CHANNEL, pathname);
|
|
1034
|
+
if (req.method !== "POST" || endpoint === void 0) {
|
|
1035
|
+
res.writeHead(404);
|
|
1036
|
+
res.end("not found");
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const mediaType = (req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase();
|
|
1040
|
+
if (mediaType !== "application/json") {
|
|
1041
|
+
res.writeHead(415);
|
|
1042
|
+
res.end("content type must be application/json");
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
const body = await readBody(req);
|
|
1046
|
+
if (body === void 0) {
|
|
1047
|
+
res.writeHead(413);
|
|
1048
|
+
res.end("body too large");
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
let envelope;
|
|
1052
|
+
try {
|
|
1053
|
+
envelope = JSON.parse(body);
|
|
1054
|
+
} catch {
|
|
1055
|
+
res.writeHead(400);
|
|
1056
|
+
res.end("body is not JSON");
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
const parsed = clientRequestSchema.safeParse(envelope);
|
|
1060
|
+
const rpcId = typeof envelope.rpcId === "string" ? RpcId(envelope.rpcId) : INVALID_REQUEST_RPC_ID;
|
|
1061
|
+
if (!parsed.success) {
|
|
1062
|
+
writeError(res, rpcId, {
|
|
1063
|
+
code: "bad-request",
|
|
1064
|
+
message: "invalid client-request message",
|
|
1065
|
+
details: { issues: parsed.error.issues }
|
|
1066
|
+
});
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
if (parsed.data.method !== endpoint) {
|
|
1070
|
+
writeError(res, rpcId, {
|
|
1071
|
+
code: "bad-request",
|
|
1072
|
+
message: `method ${JSON.stringify(parsed.data.method)} does not match endpoint ${JSON.stringify(endpoint)}`,
|
|
1073
|
+
details: { issues: [] }
|
|
1074
|
+
});
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
try {
|
|
1078
|
+
const value = this.runEndpoint(endpoint, parsed.data.payload);
|
|
1079
|
+
writeFull(res, rpcId, { ok: true, value });
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
if (error instanceof UnknownEndpointError) {
|
|
1082
|
+
res.writeHead(404);
|
|
1083
|
+
res.end("not found");
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)));
|
|
1087
|
+
writeError(res, rpcId, {
|
|
1088
|
+
code: "internal",
|
|
1089
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1090
|
+
details: {}
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
/** Dispatch one authenticated business call. */
|
|
1095
|
+
runEndpoint(endpoint, payload) {
|
|
1096
|
+
if (endpoint === "ping") {
|
|
1097
|
+
return { pong: true, instance: this.instanceId };
|
|
1098
|
+
}
|
|
1099
|
+
if (endpoint === "send") {
|
|
1100
|
+
let parsed;
|
|
1101
|
+
try {
|
|
1102
|
+
parsed = Schema.resolve(payload, sendPayloadSchema, {})[0];
|
|
1103
|
+
} catch (error) {
|
|
1104
|
+
throw new Error(`send payload invalid: ${error instanceof Error ? error.message : String(error)}`);
|
|
1105
|
+
}
|
|
1106
|
+
return this.deliver(parsed);
|
|
1107
|
+
}
|
|
1108
|
+
if (endpoint === "event") {
|
|
1109
|
+
let eventPayload;
|
|
1110
|
+
try {
|
|
1111
|
+
eventPayload = Schema.resolve(payload, eventPayloadSchema, {})[0];
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
throw new Error(`event payload invalid: ${error instanceof Error ? error.message : String(error)}`);
|
|
1114
|
+
}
|
|
1115
|
+
this.receiveEvent(eventPayload);
|
|
1116
|
+
return { accepted: true };
|
|
1117
|
+
}
|
|
1118
|
+
throw new UnknownEndpointError(endpoint);
|
|
1119
|
+
}
|
|
1120
|
+
/** Surface one remote notification to local listeners and the log. */
|
|
1121
|
+
receiveEvent(eventPayload) {
|
|
1122
|
+
this.ctx.logger.info(`interconnect: remote event ${eventPayload.notification.kind} from ${eventPayload.sender}`);
|
|
1123
|
+
this.ctx.emit("interconnect/event", eventPayload.notification, eventPayload.sender);
|
|
1124
|
+
}
|
|
1125
|
+
/** Deliver one message to a live local session, if it exists. */
|
|
1126
|
+
deliver(payload) {
|
|
1127
|
+
const agent = this.ctx.agents.get(payload.sessionId);
|
|
1128
|
+
if (agent === void 0) {
|
|
1129
|
+
return { delivered: false, instance: this.instanceId };
|
|
1130
|
+
}
|
|
1131
|
+
const message = createUserMessage({
|
|
1132
|
+
source: { kind: "user" },
|
|
1133
|
+
content: [{ type: "text", text: payload.text }]
|
|
1134
|
+
});
|
|
1135
|
+
if (this.delivery === "inject") {
|
|
1136
|
+
agent.inject(message);
|
|
1137
|
+
} else {
|
|
1138
|
+
agent.followup(message);
|
|
1139
|
+
}
|
|
1140
|
+
return { delivered: true, instance: this.instanceId };
|
|
1141
|
+
}
|
|
1142
|
+
/** POST one business call to a peer instance; undefined on transport/auth failure. */
|
|
1143
|
+
async post(baseUrl, endpoint, payload) {
|
|
1144
|
+
const token = await this.resolveToken();
|
|
1145
|
+
if (token === void 0) return void 0;
|
|
1146
|
+
const url = `${trimBase(baseUrl)}${INTERCONNECT_CHANNEL}/${endpoint}`;
|
|
1147
|
+
const envelope = {
|
|
1148
|
+
type: "client-request",
|
|
1149
|
+
rpcId: crypto.randomUUID(),
|
|
1150
|
+
method: endpoint,
|
|
1151
|
+
payload
|
|
1152
|
+
};
|
|
1153
|
+
try {
|
|
1154
|
+
const response = await fetch(url, {
|
|
1155
|
+
method: "POST",
|
|
1156
|
+
headers: {
|
|
1157
|
+
"content-type": "application/json",
|
|
1158
|
+
authorization: `Bearer ${token}`
|
|
1159
|
+
},
|
|
1160
|
+
body: JSON.stringify(envelope),
|
|
1161
|
+
signal: AbortSignal.timeout(this.requestTimeoutMs)
|
|
1162
|
+
});
|
|
1163
|
+
if (!response.ok) return void 0;
|
|
1164
|
+
const body = await response.json();
|
|
1165
|
+
if (body.result?.ok !== true) return void 0;
|
|
1166
|
+
return body.result.value;
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
this.ctx.logger.warn(`interconnect: ${endpoint} to ${baseUrl} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1169
|
+
return void 0;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
async resolveToken() {
|
|
1173
|
+
const credential = await this.ctx.credentials.resolve(credentialRef(INTERCONNECT_TOKEN_REF));
|
|
1174
|
+
return credential === void 0 || credential.value.length === 0 ? void 0 : credential.value;
|
|
1175
|
+
}
|
|
1176
|
+
/** Resolve the shared token for an outbound dial (same source as inbound). */
|
|
1177
|
+
resolveTokenForDial() {
|
|
1178
|
+
return this.resolveToken();
|
|
1179
|
+
}
|
|
1180
|
+
/** Inbound WebSocket upgrade: authenticate the bearer header, then accept. */
|
|
1181
|
+
async handleUpgrade(req, socket, head) {
|
|
1182
|
+
const token = await this.resolveToken();
|
|
1183
|
+
if (token === void 0) {
|
|
1184
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 9\r\n\r\nforbidden");
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
const expected = `Bearer ${token}`;
|
|
1188
|
+
const header = req.headers.authorization;
|
|
1189
|
+
if (header === void 0 || !timingSafeEqual(header, expected)) {
|
|
1190
|
+
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 12\r\n\r\nunauthorized");
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
this.server.handleUpgrade(req, socket, head, (websocket) => {
|
|
1194
|
+
this.attachSocket(websocket);
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* Install frame + liveness handling on one socket and add it to the live
|
|
1199
|
+
* pool. Used by both the server half (accepted upgrade) and the client half
|
|
1200
|
+
* (outbound dial), so a single socket carries events both directions.
|
|
1201
|
+
*/
|
|
1202
|
+
attachSocket(websocket) {
|
|
1203
|
+
this.sockets.add(websocket);
|
|
1204
|
+
websocket.isAlive = true;
|
|
1205
|
+
websocket.on("pong", () => {
|
|
1206
|
+
;
|
|
1207
|
+
websocket.isAlive = true;
|
|
1208
|
+
});
|
|
1209
|
+
websocket.on("message", (data) => {
|
|
1210
|
+
this.handleFrame(websocket, data);
|
|
1211
|
+
});
|
|
1212
|
+
websocket.on("close", () => {
|
|
1213
|
+
this.sockets.delete(websocket);
|
|
1214
|
+
this.peerOf.delete(websocket);
|
|
1215
|
+
});
|
|
1216
|
+
websocket.on("error", () => {
|
|
1217
|
+
this.sockets.delete(websocket);
|
|
1218
|
+
});
|
|
1219
|
+
websocket.send(JSON.stringify({ type: "hello", sender: this.instanceId }));
|
|
1220
|
+
}
|
|
1221
|
+
/** Parse and route one inbound link frame, attributing events to the socket's announced peer. */
|
|
1222
|
+
handleFrame(socket, data) {
|
|
1223
|
+
if (Array.isArray(data)) return;
|
|
1224
|
+
const text = Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
|
|
1225
|
+
let frame;
|
|
1226
|
+
try {
|
|
1227
|
+
frame = Schema.resolve(JSON.parse(text), linkFrameSchema, {})[0];
|
|
1228
|
+
} catch {
|
|
1229
|
+
this.ctx.logger.warn("interconnect: dropping malformed link frame");
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
if (frame.type === "hello") {
|
|
1233
|
+
this.peerOf.set(socket, frame.sender);
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
const sender = this.peerOf.get(socket) ?? "unknown-peer";
|
|
1237
|
+
this.receiveEvent({ sender, notification: frame.notification });
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
var UnknownEndpointError = class extends Error {
|
|
1241
|
+
constructor(endpoint) {
|
|
1242
|
+
super(`unknown interconnect endpoint ${JSON.stringify(endpoint)}`);
|
|
1243
|
+
this.name = "UnknownEndpointError";
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
var LinkState = class {
|
|
1247
|
+
constructor(owner, peer) {
|
|
1248
|
+
this.owner = owner;
|
|
1249
|
+
this.peer = peer;
|
|
1250
|
+
}
|
|
1251
|
+
socket;
|
|
1252
|
+
closed = false;
|
|
1253
|
+
retry = 0;
|
|
1254
|
+
reconnectTimer;
|
|
1255
|
+
peer;
|
|
1256
|
+
/** Open the socket; reconnect is scheduled by the close handler. */
|
|
1257
|
+
dial() {
|
|
1258
|
+
if (this.closed) return;
|
|
1259
|
+
const url = new URL("/interconnect/link", this.peer);
|
|
1260
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1261
|
+
void this.owner.resolveTokenForDial().then((token) => {
|
|
1262
|
+
if (token === void 0 || this.closed) return;
|
|
1263
|
+
const socket = new WebSocket(url, {
|
|
1264
|
+
headers: { authorization: `Bearer ${token}` }
|
|
1265
|
+
});
|
|
1266
|
+
this.socket = socket;
|
|
1267
|
+
socket.once("open", () => {
|
|
1268
|
+
this.retry = 0;
|
|
1269
|
+
this.owner.attachSocket(socket);
|
|
1270
|
+
});
|
|
1271
|
+
socket.once("close", () => {
|
|
1272
|
+
if (this.closed) return;
|
|
1273
|
+
this.scheduleReconnect();
|
|
1274
|
+
});
|
|
1275
|
+
socket.on("error", () => {
|
|
1276
|
+
});
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
close() {
|
|
1280
|
+
this.closed = true;
|
|
1281
|
+
this.owner.forgetLink(this.peer);
|
|
1282
|
+
if (this.reconnectTimer !== void 0) clearTimeout(this.reconnectTimer);
|
|
1283
|
+
const socket = this.socket;
|
|
1284
|
+
if (socket !== void 0) {
|
|
1285
|
+
socket.removeAllListeners();
|
|
1286
|
+
socket.terminate();
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
scheduleReconnect() {
|
|
1290
|
+
const delay = Math.min(3e4, 1e3 * 2 ** this.retry);
|
|
1291
|
+
this.retry += 1;
|
|
1292
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1293
|
+
this.reconnectTimer = void 0;
|
|
1294
|
+
this.dial();
|
|
1295
|
+
}, delay);
|
|
1296
|
+
}
|
|
1297
|
+
};
|
|
1298
|
+
function endpointFromPath(channel, pathname) {
|
|
1299
|
+
if (!pathname.startsWith(`${channel}/`)) return void 0;
|
|
1300
|
+
return pathname.slice(channel.length + 1);
|
|
1301
|
+
}
|
|
1302
|
+
async function readBody(req) {
|
|
1303
|
+
let size = 0;
|
|
1304
|
+
const chunks = [];
|
|
1305
|
+
for await (const chunk of req) {
|
|
1306
|
+
const buffer = chunk;
|
|
1307
|
+
size += buffer.byteLength;
|
|
1308
|
+
if (size > MAX_REQUEST_BODY_BYTES) return void 0;
|
|
1309
|
+
chunks.push(buffer);
|
|
1310
|
+
}
|
|
1311
|
+
return Buffer.concat(chunks).toString();
|
|
1312
|
+
}
|
|
1313
|
+
function timingSafeEqual(a, b) {
|
|
1314
|
+
if (a.length !== b.length) return false;
|
|
1315
|
+
let diff = 0;
|
|
1316
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
1317
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1318
|
+
}
|
|
1319
|
+
return diff === 0;
|
|
1320
|
+
}
|
|
1321
|
+
function trimBase(baseUrl) {
|
|
1322
|
+
return baseUrl.replace(/\/+$/, "");
|
|
1323
|
+
}
|
|
1324
|
+
function writeFull(res, rpcId, result) {
|
|
1325
|
+
const body = serverResponseSchema.parse({
|
|
1326
|
+
type: "server-response",
|
|
1327
|
+
rpcId,
|
|
1328
|
+
result
|
|
1329
|
+
});
|
|
1330
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
1331
|
+
res.end(JSON.stringify(body));
|
|
1332
|
+
}
|
|
1333
|
+
function writeError(res, rpcId, error) {
|
|
1334
|
+
writeFull(res, rpcId, { ok: false, error });
|
|
1335
|
+
}
|
|
1336
|
+
var interconnect_default = InterconnectService;
|
|
1337
|
+
export {
|
|
1338
|
+
INTERCONNECT_CHANNEL,
|
|
1339
|
+
INTERCONNECT_TOKEN_REF,
|
|
1340
|
+
InterconnectService,
|
|
1341
|
+
interconnect_default as default
|
|
1342
|
+
};
|