dsh-provider-proxy 0.0.0-stage → 0.2.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/lib/index.js ADDED
@@ -0,0 +1,1212 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name2 in all)
4
+ __defProp(target, name2, { get: all[name2], enumerable: true });
5
+ };
6
+
7
+ // src/fetch-router.ts
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { fetch as undiciFetch } from "undici";
10
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("dsh-provider-proxy.fetch-router.v1");
11
+ function installSharedRouter() {
12
+ const current = globalThis[STATE_KEY];
13
+ if (current !== void 0) {
14
+ current.owners += 1;
15
+ return current;
16
+ }
17
+ if (typeof globalThis.fetch !== "function") {
18
+ throw new Error("dsh-provider-proxy: this Node runtime does not expose global fetch");
19
+ }
20
+ const storage = new AsyncLocalStorage();
21
+ const originalFetch = globalThis.fetch;
22
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "fetch");
23
+ const routedFetch = function routedFetch2(input, init) {
24
+ const active = storage.getStore();
25
+ if (active === void 0) return originalFetch.call(globalThis, input, init);
26
+ if (init !== void 0 && init !== null && init.dispatcher !== void 0) {
27
+ return originalFetch.call(globalThis, input, init);
28
+ }
29
+ return undiciFetch(input, {
30
+ ...init,
31
+ dispatcher: active.dispatcher
32
+ });
33
+ };
34
+ Object.defineProperty(globalThis, "fetch", {
35
+ ...descriptor ?? { configurable: true, enumerable: true, writable: true },
36
+ value: routedFetch
37
+ });
38
+ const state = { owners: 1, storage, originalFetch, routedFetch, descriptor };
39
+ Object.defineProperty(globalThis, STATE_KEY, {
40
+ configurable: true,
41
+ value: state
42
+ });
43
+ return state;
44
+ }
45
+ function contextualIterable(storage, store, factory) {
46
+ return {
47
+ [Symbol.asyncIterator]() {
48
+ let iterator;
49
+ const ensureIterator = () => {
50
+ if (iterator !== void 0) return iterator;
51
+ const iterable = factory();
52
+ if (iterable === null || typeof iterable?.[Symbol.asyncIterator] !== "function") {
53
+ throw new TypeError("dsh-provider-proxy: llm/stream next() did not return an AsyncIterable");
54
+ }
55
+ iterator = iterable[Symbol.asyncIterator]();
56
+ return iterator;
57
+ };
58
+ const invoke = (method, value) => storage.run(store, () => {
59
+ if (method === "return" && iterator === void 0) return Promise.resolve({ done: true, value });
60
+ if (method === "throw" && iterator === void 0) return Promise.reject(value);
61
+ const target = ensureIterator();
62
+ const operation = target[method];
63
+ if (typeof operation !== "function") {
64
+ if (method === "return") return Promise.resolve({ done: true, value });
65
+ return Promise.reject(value);
66
+ }
67
+ return Promise.resolve(Reflect.apply(operation, target, method === "next" ? [] : [value]));
68
+ });
69
+ return {
70
+ next: (value) => invoke("next", value),
71
+ return: (value) => invoke("return", value),
72
+ throw: (value) => invoke("throw", value),
73
+ [Symbol.asyncIterator]() {
74
+ return this;
75
+ }
76
+ };
77
+ }
78
+ };
79
+ }
80
+ function acquireFetchRouter() {
81
+ const state = installSharedRouter();
82
+ let released = false;
83
+ return {
84
+ run(dispatcher, callback) {
85
+ return state.storage.run({ dispatcher }, callback);
86
+ },
87
+ wrap(dispatcher, factory) {
88
+ return contextualIterable(state.storage, { dispatcher }, factory);
89
+ },
90
+ release() {
91
+ if (released) return;
92
+ released = true;
93
+ state.owners -= 1;
94
+ if (state.owners !== 0) return;
95
+ if (globalThis.fetch === state.routedFetch) {
96
+ if (state.descriptor === void 0) delete globalThis.fetch;
97
+ else Object.defineProperty(globalThis, "fetch", state.descriptor);
98
+ }
99
+ delete globalThis[STATE_KEY];
100
+ state.storage.disable();
101
+ }
102
+ };
103
+ }
104
+
105
+ // src/proxy-table.ts
106
+ import { ProxyAgent } from "undici";
107
+
108
+ // src/config.ts
109
+ import { createRequire } from "node:module";
110
+
111
+ // node_modules/@deepseek-ai/schemastery/lib/index.mjs
112
+ var lib_exports = {};
113
+ __export(lib_exports, {
114
+ default: () => Schema
115
+ });
116
+
117
+ // node_modules/@deepseek-ai/cosmokit/lib/index.js
118
+ function isNullable(value) {
119
+ return value === null || value === void 0;
120
+ }
121
+ function isPlainObject(data) {
122
+ return data && typeof data === "object" && !Array.isArray(data);
123
+ }
124
+ function filterKeys(object, filter) {
125
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
126
+ }
127
+ function mapValues(object, transform) {
128
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
129
+ }
130
+ function pick(source, keys, forced) {
131
+ if (!keys) return { ...source };
132
+ const result = {};
133
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
134
+ return result;
135
+ }
136
+ var write = /* @__PURE__ */ Symbol.for("cosmokit.volatile.write");
137
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
138
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
139
+ if (value === null || typeof value !== "object") return value;
140
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
141
+ ancestors.add(value);
142
+ try {
143
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
144
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
145
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
146
+ } finally {
147
+ ancestors.delete(value);
148
+ }
149
+ }
150
+ function createVolatile(value) {
151
+ let current = snapshot(value);
152
+ return Object.freeze({
153
+ get: () => current,
154
+ [write]: (value2) => {
155
+ current = value2;
156
+ }
157
+ });
158
+ }
159
+ function isVolatile(value) {
160
+ return typeof value === "object" && value !== null && write in value;
161
+ }
162
+ function is(type, value) {
163
+ if (arguments.length === 1) return (value2) => is(type, value2);
164
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
165
+ }
166
+ function isArrayBufferLike(value) {
167
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
168
+ }
169
+ function isArrayBufferSource(value) {
170
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
171
+ }
172
+ var Binary;
173
+ (function(Binary2) {
174
+ Binary2.is = isArrayBufferLike;
175
+ Binary2.isSource = isArrayBufferSource;
176
+ function fromSource(source) {
177
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
178
+ else return source;
179
+ }
180
+ Binary2.fromSource = fromSource;
181
+ function toBase64(source) {
182
+ source = fromSource(source);
183
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
184
+ let binary = "";
185
+ const bytes = new Uint8Array(source);
186
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
187
+ return btoa(binary);
188
+ }
189
+ Binary2.toBase64 = toBase64;
190
+ function fromBase64(source) {
191
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
192
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
193
+ }
194
+ Binary2.fromBase64 = fromBase64;
195
+ function toHex(source) {
196
+ source = fromSource(source);
197
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
198
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
199
+ }
200
+ Binary2.toHex = toHex;
201
+ function fromHex(source) {
202
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
203
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
204
+ const buffer = [];
205
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
206
+ return Uint8Array.from(buffer).buffer;
207
+ }
208
+ Binary2.fromHex = fromHex;
209
+ })(Binary || (Binary = {}));
210
+ var base64ToArrayBuffer = Binary.fromBase64;
211
+ var arrayBufferToBase64 = Binary.toBase64;
212
+ var hexToArrayBuffer = Binary.fromHex;
213
+ var arrayBufferToHex = Binary.toHex;
214
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
215
+ if (!source || typeof source !== "object") return source;
216
+ if (is("Date", source)) return new Date(source.valueOf());
217
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
218
+ if (isArrayBufferLike(source)) return source.slice(0);
219
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
220
+ const cached = refs.get(source);
221
+ if (cached) return cached;
222
+ if (Array.isArray(source)) {
223
+ const result2 = [];
224
+ refs.set(source, result2);
225
+ source.forEach((value, index) => {
226
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
227
+ });
228
+ return result2;
229
+ }
230
+ const result = Object.create(Object.getPrototypeOf(source));
231
+ refs.set(source, result);
232
+ for (const key of Reflect.ownKeys(source)) {
233
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
234
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
235
+ Reflect.defineProperty(result, key, descriptor);
236
+ }
237
+ return result;
238
+ }
239
+ function deepEqual(a, b, strict) {
240
+ const ancestors = /* @__PURE__ */ new Set();
241
+ function compare(a2, b2) {
242
+ if (a2 === b2) return true;
243
+ if (isVolatile(a2) || isVolatile(b2)) return isVolatile(a2) && isVolatile(b2);
244
+ if (!strict && isNullable(a2) && isNullable(b2)) return true;
245
+ if (typeof a2 !== typeof b2 || typeof a2 !== "object" || !a2 || !b2) return false;
246
+ if (ancestors.has(a2)) return false;
247
+ function check(test, then) {
248
+ return test(a2) ? test(b2) ? then(a2, b2) : false : test(b2) ? false : void 0;
249
+ }
250
+ ancestors.add(a2);
251
+ try {
252
+ return check(Array.isArray, (a3, b3) => {
253
+ if (a3.length !== b3.length) return false;
254
+ for (let index = 0; index < a3.length; index++) if (!compare(a3[index], b3[index])) return false;
255
+ return true;
256
+ }) ?? check(is("Date"), (a3, b3) => a3.valueOf() === b3.valueOf()) ?? check(is("URL"), (a3, b3) => a3.href === b3.href) ?? check(is("RegExp"), (a3, b3) => a3.source === b3.source && a3.flags === b3.flags) ?? check(isArrayBufferLike, (a3, b3) => {
257
+ if (a3.byteLength !== b3.byteLength) return false;
258
+ const viewA = new Uint8Array(a3);
259
+ const viewB = new Uint8Array(b3);
260
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
261
+ return true;
262
+ }) ?? ((!strict || [a2, b2].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
263
+ ...a2,
264
+ ...b2
265
+ }).every((key) => compare(a2[key], b2[key])));
266
+ } finally {
267
+ ancestors.delete(a2);
268
+ }
269
+ }
270
+ return compare(a, b);
271
+ }
272
+ var Time;
273
+ (function(Time2) {
274
+ Time2.millisecond = 1;
275
+ Time2.second = 1e3;
276
+ Time2.minute = Time2.second * 60;
277
+ Time2.hour = Time2.minute * 60;
278
+ Time2.day = Time2.hour * 24;
279
+ Time2.week = Time2.day * 7;
280
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
281
+ function setTimezoneOffset(offset) {
282
+ timezoneOffset = offset;
283
+ }
284
+ Time2.setTimezoneOffset = setTimezoneOffset;
285
+ function getTimezoneOffset() {
286
+ return timezoneOffset;
287
+ }
288
+ Time2.getTimezoneOffset = getTimezoneOffset;
289
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
290
+ if (typeof date2 === "number") date2 = new Date(date2);
291
+ if (offset === void 0) offset = timezoneOffset;
292
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
293
+ }
294
+ Time2.getDateNumber = getDateNumber;
295
+ function fromDateNumber(value, offset) {
296
+ const date2 = new Date(value * Time2.day);
297
+ if (offset === void 0) offset = timezoneOffset;
298
+ return new Date(+date2 + offset * Time2.minute);
299
+ }
300
+ Time2.fromDateNumber = fromDateNumber;
301
+ const numeric = /\d+(?:\.\d+)?/.source;
302
+ const timeRegExp = new RegExp(`^${[
303
+ "w(?:eek(?:s)?)?",
304
+ "d(?:ay(?:s)?)?",
305
+ "h(?:our(?:s)?)?",
306
+ "m(?:in(?:ute)?(?:s)?)?",
307
+ "s(?:ec(?:ond)?(?:s)?)?"
308
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
309
+ function parseTime(source) {
310
+ const capture = timeRegExp.exec(source);
311
+ if (!capture) return 0;
312
+ 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);
313
+ }
314
+ Time2.parseTime = parseTime;
315
+ function parseDate(date2) {
316
+ const parsed = parseTime(date2);
317
+ if (parsed) date2 = Date.now() + parsed;
318
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
319
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
320
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
321
+ }
322
+ Time2.parseDate = parseDate;
323
+ function format(ms) {
324
+ const abs = Math.abs(ms);
325
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
326
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
327
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
328
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
329
+ return ms + "ms";
330
+ }
331
+ Time2.format = format;
332
+ function toDigits(source, length = 2) {
333
+ return source.toString().padStart(length, "0");
334
+ }
335
+ Time2.toDigits = toDigits;
336
+ function template(template2, time = /* @__PURE__ */ new Date()) {
337
+ 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));
338
+ }
339
+ Time2.template = template;
340
+ })(Time || (Time = {}));
341
+
342
+ // node_modules/@deepseek-ai/schemastery/lib/index.mjs
343
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
344
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
345
+ globalThis.__schemastery_index__ ??= 0;
346
+ globalThis.__schemastery_refs__ = void 0;
347
+ var ValidationError = class extends TypeError {
348
+ options;
349
+ name = "ValidationError";
350
+ constructor(message, options) {
351
+ let prefix = "$";
352
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
353
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
354
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
355
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
356
+ super((prefix === "$" ? "" : `${prefix} `) + message);
357
+ this.options = options;
358
+ }
359
+ static is(error) {
360
+ return !!error?.[kValidationError];
361
+ }
362
+ };
363
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
364
+ var Schema = function(options) {
365
+ const schema = function(data, options2 = {}) {
366
+ return Schema.resolve(data, schema, options2)[0];
367
+ };
368
+ if (options.refs) {
369
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
370
+ const getRef = (uid) => refs[uid];
371
+ for (const key in refs) {
372
+ const options2 = refs[key];
373
+ options2.sKey = getRef(options2.sKey);
374
+ options2.inner = getRef(options2.inner);
375
+ options2.list = options2.list && options2.list.map(getRef);
376
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
377
+ }
378
+ return refs[options.uid];
379
+ }
380
+ Object.assign(schema, options);
381
+ if (typeof schema.callback === "string") try {
382
+ schema.callback = new Function("return " + schema.callback)();
383
+ } catch {
384
+ }
385
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
386
+ Object.setPrototypeOf(schema, Schema.prototype);
387
+ schema.meta ||= {};
388
+ schema.toString = schema.toString.bind(schema);
389
+ return schema;
390
+ };
391
+ Schema.prototype = Object.create(Function.prototype);
392
+ Schema.prototype[kSchema] = true;
393
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
394
+ return {
395
+ version: 1,
396
+ vendor: "schemastery",
397
+ validate: (value) => {
398
+ try {
399
+ return { value: Schema.resolve(value, this, {})[0] };
400
+ } catch (error) {
401
+ if (ValidationError.is(error)) return { issues: [{
402
+ message: error.message,
403
+ path: error.options.path
404
+ }] };
405
+ throw error;
406
+ }
407
+ }
408
+ };
409
+ } });
410
+ Schema.ValidationError = ValidationError;
411
+ Schema.prototype.toJSON = function toJSON() {
412
+ if (globalThis.__schemastery_refs__) {
413
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
414
+ return this.uid;
415
+ }
416
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
417
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
418
+ const result = {
419
+ uid: this.uid,
420
+ refs: globalThis.__schemastery_refs__
421
+ };
422
+ globalThis.__schemastery_refs__ = void 0;
423
+ return result;
424
+ };
425
+ Schema.prototype.set = function set(key, value) {
426
+ this.dict[key] = value;
427
+ return this;
428
+ };
429
+ Schema.prototype.push = function push(value) {
430
+ this.list.push(value);
431
+ return this;
432
+ };
433
+ function mergeDesc(original, messages) {
434
+ const result = typeof original === "string" ? { "": original } : { ...original };
435
+ for (const locale in messages) {
436
+ const value = messages[locale];
437
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
438
+ else if (typeof value === "string") result[locale] = value;
439
+ }
440
+ return result;
441
+ }
442
+ function getInner(value) {
443
+ return value?.$value ?? value?.$inner;
444
+ }
445
+ function extractKeys(data) {
446
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
447
+ }
448
+ Schema.prototype.i18n = function i18n(messages) {
449
+ const schema = Schema(this);
450
+ const desc = mergeDesc(schema.meta.description, messages);
451
+ if (Object.keys(desc).length) schema.meta.description = desc;
452
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
453
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
454
+ });
455
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
456
+ return inner.i18n(mapValues(messages, (data = {}) => {
457
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
458
+ if (Array.isArray(data)) return data[index];
459
+ return extractKeys(data);
460
+ }));
461
+ });
462
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
463
+ if (getInner(data)) return getInner(data);
464
+ return extractKeys(data);
465
+ }));
466
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
467
+ return schema;
468
+ };
469
+ Schema.prototype.extra = function extra(key, value) {
470
+ const schema = Schema(this);
471
+ schema.meta = {
472
+ ...schema.meta,
473
+ [key]: value
474
+ };
475
+ return schema;
476
+ };
477
+ for (const key of [
478
+ "required",
479
+ "disabled",
480
+ "collapse",
481
+ "hidden",
482
+ "loose"
483
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
484
+ const schema = Schema(this);
485
+ schema.meta = {
486
+ ...schema.meta,
487
+ [key]: value
488
+ };
489
+ return schema;
490
+ } });
491
+ Schema.prototype.deprecated = function deprecated() {
492
+ const schema = Schema(this);
493
+ schema.meta.badges ||= [];
494
+ schema.meta.badges.push({
495
+ text: "deprecated",
496
+ type: "danger"
497
+ });
498
+ return schema;
499
+ };
500
+ Schema.prototype.experimental = function experimental() {
501
+ const schema = Schema(this);
502
+ schema.meta.badges ||= [];
503
+ schema.meta.badges.push({
504
+ text: "experimental",
505
+ type: "warning"
506
+ });
507
+ return schema;
508
+ };
509
+ Schema.prototype.pattern = function pattern(regexp) {
510
+ const schema = Schema(this);
511
+ const pattern2 = pick(regexp, ["source", "flags"]);
512
+ schema.meta = {
513
+ ...schema.meta,
514
+ pattern: pattern2
515
+ };
516
+ return schema;
517
+ };
518
+ Schema.prototype.simplify = function simplify(value) {
519
+ if (isVolatile(value)) value = value.get();
520
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
521
+ if (isNullable(value)) return value;
522
+ if (this.type === "object" || this.type === "dict") {
523
+ const result = {};
524
+ for (const key in value) {
525
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
526
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
527
+ }
528
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
529
+ return result;
530
+ } else if (this.type === "array" || this.type === "tuple") {
531
+ const result = [];
532
+ value.forEach((value2, index) => {
533
+ const schema = this.type === "array" ? this.inner : this.list[index];
534
+ const item = schema ? schema.simplify(value2) : value2;
535
+ result.push(item);
536
+ });
537
+ return result;
538
+ } else if (this.type === "intersect") {
539
+ const result = {};
540
+ for (const item of this.list) Object.assign(result, item.simplify(value));
541
+ return result;
542
+ } else if (this.type === "union") for (const schema of this.list) try {
543
+ Schema.resolve(value, schema, {});
544
+ return schema.simplify(value);
545
+ } catch {
546
+ }
547
+ return value;
548
+ };
549
+ Schema.prototype.toString = function toString(inline) {
550
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
551
+ };
552
+ Schema.prototype.role = function role(role, extra2) {
553
+ const schema = Schema(this);
554
+ schema.meta = {
555
+ ...schema.meta,
556
+ role,
557
+ extra: extra2
558
+ };
559
+ return schema;
560
+ };
561
+ for (const key of [
562
+ "default",
563
+ "link",
564
+ "comment",
565
+ "description",
566
+ "max",
567
+ "min",
568
+ "step"
569
+ ]) Object.assign(Schema.prototype, { [key](value) {
570
+ const schema = Schema(this);
571
+ schema.meta = {
572
+ ...schema.meta,
573
+ [key]: value
574
+ };
575
+ return schema;
576
+ } });
577
+ Schema.prototype.volatile = function volatile() {
578
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
579
+ return this.extra("volatile", true);
580
+ };
581
+ var resolvers = {};
582
+ var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
583
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
584
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
585
+ if (states.has(blocked)) return;
586
+ states.add(blocked);
587
+ seen.set(schema, states);
588
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
589
+ const nested = blocked || !!schema.meta?.volatile;
590
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
591
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
592
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
593
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
594
+ }
595
+ Schema.extend = function extend(type, resolve2) {
596
+ resolvers[type] = resolve2;
597
+ };
598
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
599
+ if (!schema) return [data];
600
+ if (!options[checkedVolatile]) {
601
+ validateVolatileSchema(schema, options.path);
602
+ options = {
603
+ ...options,
604
+ [checkedVolatile]: true
605
+ };
606
+ }
607
+ if (schema.meta?.volatile) {
608
+ const inner = Schema(schema);
609
+ inner.meta = {
610
+ ...schema.meta,
611
+ volatile: false
612
+ };
613
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
614
+ try {
615
+ return [createVolatile(value), adapted];
616
+ } catch (error) {
617
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
618
+ }
619
+ }
620
+ if (options.ignore?.(data, schema)) return [data];
621
+ if (isNullable(data) && schema.type !== "lazy") {
622
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
623
+ let current = schema;
624
+ let fallback = schema.meta.default;
625
+ while (current?.type === "intersect" && isNullable(fallback)) {
626
+ current = current.list[0];
627
+ fallback = current?.meta.default;
628
+ }
629
+ if (isNullable(fallback)) return [data];
630
+ data = clone(fallback);
631
+ }
632
+ const callback = resolvers[schema.type];
633
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
634
+ try {
635
+ return callback(data, schema, options, strict);
636
+ } catch (error) {
637
+ if (!schema.meta.loose) throw error;
638
+ return [schema.meta.default];
639
+ }
640
+ };
641
+ Schema.from = function from(source) {
642
+ if (isNullable(source)) return Schema.any();
643
+ else if ([
644
+ "string",
645
+ "number",
646
+ "boolean"
647
+ ].includes(typeof source)) return Schema.const(source).required();
648
+ else if (source[kSchema]) return source;
649
+ else if (typeof source === "function") switch (source) {
650
+ case String:
651
+ return Schema.string().required();
652
+ case Number:
653
+ return Schema.number().required();
654
+ case Boolean:
655
+ return Schema.boolean().required();
656
+ case Function:
657
+ return Schema.function().required();
658
+ default:
659
+ return Schema.is(source).required();
660
+ }
661
+ else throw new TypeError(`cannot infer schema from ${source}`);
662
+ };
663
+ Schema.lazy = function lazy(builder) {
664
+ const toJSON2 = () => {
665
+ if (!schema.inner[kSchema]) {
666
+ schema.inner = schema.builder();
667
+ schema.inner.meta = {
668
+ ...schema.meta,
669
+ ...schema.inner.meta
670
+ };
671
+ }
672
+ return schema.inner.toJSON();
673
+ };
674
+ const schema = new Schema({
675
+ type: "lazy",
676
+ builder,
677
+ inner: { toJSON: toJSON2 }
678
+ });
679
+ return schema;
680
+ };
681
+ Schema.natural = function natural() {
682
+ return Schema.number().step(1).min(0);
683
+ };
684
+ Schema.percent = function percent() {
685
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
686
+ };
687
+ Schema.date = function date() {
688
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
689
+ const date2 = new Date(value);
690
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
691
+ return date2;
692
+ }, true)]);
693
+ };
694
+ Schema.regExp = function regExp(flag = "") {
695
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
696
+ try {
697
+ return new RegExp(value, flag);
698
+ } catch (e) {
699
+ throw new ValidationError(e.message, options);
700
+ }
701
+ }, true)]);
702
+ };
703
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
704
+ return Schema.union([
705
+ Schema.is(ArrayBuffer),
706
+ Schema.is(SharedArrayBuffer),
707
+ Schema.transform(Schema.any(), (value, options) => {
708
+ if (Binary.isSource(value)) return Binary.fromSource(value);
709
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
710
+ }, true),
711
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
712
+ try {
713
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
714
+ } catch (e) {
715
+ throw new ValidationError(e.message, options);
716
+ }
717
+ }, true)] : []
718
+ ]);
719
+ };
720
+ Schema.extend("lazy", (data, schema, options, strict) => {
721
+ if (!schema.inner[kSchema]) {
722
+ schema.inner = schema.builder();
723
+ schema.inner.meta = {
724
+ ...schema.meta,
725
+ ...schema.inner.meta
726
+ };
727
+ validateVolatileSchema(schema.inner, options.path, true);
728
+ }
729
+ return Schema.resolve(data, schema.inner, options, strict);
730
+ });
731
+ Schema.extend("any", (data) => {
732
+ return [data];
733
+ });
734
+ Schema.extend("never", (data, _, options) => {
735
+ throw new ValidationError(`expected nullable but got ${data}`, options);
736
+ });
737
+ Schema.extend("const", (data, { value }, options) => {
738
+ if (deepEqual(data, value)) return [value];
739
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
740
+ });
741
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
742
+ const { max = Infinity, min = -Infinity } = meta;
743
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
744
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
745
+ }
746
+ Schema.extend("string", (data, { meta }, options) => {
747
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
748
+ if (meta.pattern) {
749
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
750
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
751
+ }
752
+ checkWithinRange(data.length, meta, "string length", options);
753
+ return [data];
754
+ });
755
+ function decimalShift(data, digits) {
756
+ const str = data.toString();
757
+ if (str.includes("e")) return data * Math.pow(10, digits);
758
+ const index = str.indexOf(".");
759
+ if (index === -1) return data * Math.pow(10, digits);
760
+ const frac = str.slice(index + 1);
761
+ const integer = str.slice(0, index);
762
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
763
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
764
+ }
765
+ function isMultipleOf(data, min, step) {
766
+ step = Math.abs(step);
767
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
768
+ const index = step.toString().indexOf(".");
769
+ const digits = step.toString().slice(index + 1).length;
770
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
771
+ }
772
+ Schema.extend("number", (data, { meta }, options) => {
773
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
774
+ checkWithinRange(data, meta, "number", options);
775
+ const { step } = meta;
776
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
777
+ return [data];
778
+ });
779
+ Schema.extend("boolean", (data, _, options) => {
780
+ if (typeof data === "boolean") return [data];
781
+ throw new ValidationError(`expected boolean but got ${data}`, options);
782
+ });
783
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
784
+ let value = 0, keys = [];
785
+ if (typeof data === "number") {
786
+ value = data;
787
+ for (const key in bits) if (data & bits[key]) keys.push(key);
788
+ } else if (Array.isArray(data)) {
789
+ keys = data;
790
+ for (const key of keys) {
791
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
792
+ if (key in bits) value |= bits[key];
793
+ }
794
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
795
+ if (value === meta.default) return [value];
796
+ return [value, keys];
797
+ });
798
+ Schema.extend("function", (data, _, options) => {
799
+ if (typeof data === "function") return [data];
800
+ throw new ValidationError(`expected function but got ${data}`, options);
801
+ });
802
+ Schema.extend("is", (data, { constructor }, options) => {
803
+ if (typeof constructor === "function") {
804
+ if (data instanceof constructor) return [data];
805
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
806
+ } else {
807
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
808
+ let prototype = Object.getPrototypeOf(data);
809
+ while (prototype) {
810
+ if (prototype.constructor?.name === constructor) return [data];
811
+ prototype = Object.getPrototypeOf(prototype);
812
+ }
813
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
814
+ }
815
+ });
816
+ function property(data, key, schema, options) {
817
+ try {
818
+ const [value, adapted] = Schema.resolve(data[key], schema, {
819
+ ...options,
820
+ path: [...options.path || [], key]
821
+ });
822
+ if (adapted !== void 0) data[key] = adapted;
823
+ return value;
824
+ } catch (e) {
825
+ if (!options?.autofix) throw e;
826
+ delete data[key];
827
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
828
+ }
829
+ }
830
+ Schema.extend("array", (data, { inner, meta }, options) => {
831
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
832
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
833
+ return [data.map((_, index) => property(data, index, inner, options))];
834
+ });
835
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
836
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
837
+ const result = {};
838
+ for (const key in data) {
839
+ let rKey;
840
+ try {
841
+ rKey = Schema.resolve(key, sKey, options)[0];
842
+ } catch (error) {
843
+ if (strict) continue;
844
+ throw error;
845
+ }
846
+ result[rKey] = property(data, key, inner, options);
847
+ data[rKey] = data[key];
848
+ if (key !== rKey) delete data[key];
849
+ }
850
+ return [result];
851
+ });
852
+ Schema.extend("tuple", (data, { list }, options, strict) => {
853
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
854
+ const result = list.map((inner, index) => property(data, index, inner, options));
855
+ if (strict) return [result];
856
+ result.push(...data.slice(list.length));
857
+ return [result];
858
+ });
859
+ function merge(result, data) {
860
+ for (const key in data) {
861
+ if (key in result) continue;
862
+ result[key] = data[key];
863
+ }
864
+ }
865
+ Schema.extend("object", (data, { dict }, options, strict) => {
866
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
867
+ const result = {};
868
+ for (const key in dict) {
869
+ const value = property(data, key, dict[key], options);
870
+ if (!isNullable(value) || key in data) result[key] = value;
871
+ }
872
+ if (!strict) merge(result, data);
873
+ return [result];
874
+ });
875
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
876
+ const messages = [];
877
+ for (const inner of list) try {
878
+ return Schema.resolve(data, inner, options, strict);
879
+ } catch (error) {
880
+ messages.push(error);
881
+ }
882
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
883
+ });
884
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
885
+ if (!list.length) return [data];
886
+ let result;
887
+ for (const inner of list) {
888
+ const value = Schema.resolve(data, inner, options, true)[0];
889
+ if (isNullable(value)) continue;
890
+ if (isNullable(result)) result = value;
891
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
892
+ else if (typeof value === "object") merge(result ??= {}, value);
893
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
894
+ }
895
+ if (!strict && isPlainObject(data)) merge(result, data);
896
+ return [result];
897
+ });
898
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
899
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
900
+ if (preserve) return [callback(result)];
901
+ else return [callback(result), callback(adapted)];
902
+ });
903
+ var formatters = {};
904
+ function defineMethod(name2, keys, format) {
905
+ formatters[name2] = format;
906
+ Object.assign(Schema, { [name2](...args) {
907
+ const schema = new Schema({ type: name2 });
908
+ keys.forEach((key, index) => {
909
+ switch (key) {
910
+ case "sKey":
911
+ schema.sKey = args[index] ?? Schema.string();
912
+ break;
913
+ case "inner":
914
+ schema.inner = Schema.from(args[index]);
915
+ break;
916
+ case "list":
917
+ schema.list = args[index].map(Schema.from);
918
+ break;
919
+ case "dict":
920
+ schema.dict = mapValues(args[index], Schema.from);
921
+ break;
922
+ case "bits":
923
+ schema.bits = {};
924
+ for (const key2 in args[index]) {
925
+ if (typeof args[index][key2] !== "number") continue;
926
+ schema.bits[key2] = args[index][key2];
927
+ }
928
+ break;
929
+ case "callback": {
930
+ const callback = schema.callback = args[index];
931
+ callback["toJSON"] ||= () => callback.toString();
932
+ break;
933
+ }
934
+ case "constructor": {
935
+ const constructor = schema.constructor = args[index];
936
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
937
+ break;
938
+ }
939
+ default:
940
+ schema[key] = args[index];
941
+ }
942
+ });
943
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
944
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
945
+ else if (name2 === "bitset") schema.meta.default = 0;
946
+ return schema;
947
+ } });
948
+ }
949
+ defineMethod("is", ["constructor"], ({ constructor }) => {
950
+ if (typeof constructor === "function") return constructor.name;
951
+ else return constructor;
952
+ });
953
+ defineMethod("any", [], () => "any");
954
+ defineMethod("never", [], () => "never");
955
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
956
+ defineMethod("string", [], () => "string");
957
+ defineMethod("number", [], () => "number");
958
+ defineMethod("boolean", [], () => "boolean");
959
+ defineMethod("bitset", ["bits"], () => "bitset");
960
+ defineMethod("function", [], () => "function");
961
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
962
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
963
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
964
+ defineMethod("object", ["dict"], ({ dict }) => {
965
+ if (Object.keys(dict).length === 0) return "{}";
966
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
967
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
968
+ }).join(", ")} }`;
969
+ });
970
+ defineMethod("union", ["list"], ({ list }, inline) => {
971
+ const result = list.map(({ toString: format }) => format()).join(" | ");
972
+ return inline ? `(${result})` : result;
973
+ });
974
+ defineMethod("intersect", ["list"], ({ list }) => {
975
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
976
+ });
977
+ defineMethod("transform", [
978
+ "inner",
979
+ "callback",
980
+ "preserve"
981
+ ], ({ inner }, isInner) => inner.toString(isInner));
982
+
983
+ // src/config.ts
984
+ function loadSchemastery() {
985
+ try {
986
+ const require2 = createRequire(import.meta.url);
987
+ const candidate = require2("@deepseek-ai/schemastery");
988
+ const live = candidate?.default ?? candidate;
989
+ if (live && typeof live.object === "function") return live;
990
+ } catch {
991
+ }
992
+ const bundled = Schema ?? lib_exports;
993
+ if (typeof bundled.object === "function") return bundled;
994
+ throw new Error("dsh-provider-proxy: no usable @deepseek-ai/schemastery in this installation");
995
+ }
996
+ var z = loadSchemastery();
997
+ function vol(field) {
998
+ const volatile2 = field.volatile;
999
+ return typeof volatile2 === "function" ? volatile2.call(field) : field;
1000
+ }
1001
+ var PROTOCOLS = ["http", "https", "socks5"];
1002
+ var ProviderProxyRoute = z.object({
1003
+ /** Whether this provider's calls are routed through the proxy below. */
1004
+ enabled: z.boolean().default(false),
1005
+ /** Proxy transport. `socks5` is accepted but only honoured when the socks helper loaded. */
1006
+ protocol: z.union(PROTOCOLS).default("http"),
1007
+ /** Proxy host or IP, without scheme, port, or path. */
1008
+ host: z.string().default(""),
1009
+ /** Proxy port. 0 means "not configured"; enabled routes require 1-65535. */
1010
+ port: z.number().default(0),
1011
+ /** Optional proxy username. */
1012
+ username: z.string().default(""),
1013
+ /** NAME of the credentials-service record holding the proxy password. Never the password. */
1014
+ passwordRef: z.string().default("")
1015
+ });
1016
+ var Config = z.object({
1017
+ /** Per-provider proxy routes, keyed by provider route id (e.g. `sensenova`). */
1018
+ providers: vol(z.dict(ProviderProxyRoute).default({}))
1019
+ });
1020
+ function normalizeRoute(provider, raw) {
1021
+ const route = ProviderProxyRoute(raw ?? {});
1022
+ const value = typeof route.get === "function" ? route.get() : route;
1023
+ if (!value.enabled) return { ...value, port: value.port || 0 };
1024
+ const host = value.host.trim();
1025
+ if (host.length === 0) {
1026
+ throw new TypeError(`dsh-provider-proxy: provider "${provider}" \u542F\u7528\u4E86\u4EE3\u7406\uFF0C\u4F46\u672A\u586B\u5199\u4EE3\u7406\u5730\u5740`);
1027
+ }
1028
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host) || host.includes("/")) {
1029
+ throw new TypeError(`dsh-provider-proxy: provider "${provider}" \u7684\u4EE3\u7406\u5730\u5740\u53EA\u586B\u4E3B\u673A\u540D\u6216 IP\uFF0C\u4E0D\u8981\u5E26\u534F\u8BAE\u524D\u7F00\u6216\u8DEF\u5F84`);
1030
+ }
1031
+ if (!Number.isInteger(value.port) || value.port < 1 || value.port > 65535) {
1032
+ throw new TypeError(
1033
+ `dsh-provider-proxy: provider "${provider}" \u7684\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548\uFF08\u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF09`
1034
+ );
1035
+ }
1036
+ return { ...value, host, username: value.username.trim() };
1037
+ }
1038
+
1039
+ // src/proxy-table.ts
1040
+ function proxyUrl(route) {
1041
+ const auth = route.username.length === 0 ? "" : `${encodeURIComponent(route.username).replace(/%3A/gi, ":")}@`;
1042
+ const host = route.host.includes(":") && !route.host.startsWith("[") ? `[${route.host}]` : route.host;
1043
+ return `${route.protocol}://${auth}${host}:${route.port}`;
1044
+ }
1045
+ async function createProxyTable(config, options = {}) {
1046
+ const entries = /* @__PURE__ */ new Map();
1047
+ const problems = /* @__PURE__ */ new Map();
1048
+ for (const [provider, raw] of Object.entries(config ?? {})) {
1049
+ let route;
1050
+ try {
1051
+ route = normalizeRoute(provider, raw);
1052
+ } catch (error) {
1053
+ problems.set(provider, error instanceof Error ? error.message : String(error));
1054
+ continue;
1055
+ }
1056
+ if (!route.enabled) continue;
1057
+ if (route.protocol === "socks5") {
1058
+ problems.set(provider, "dsh-provider-proxy: socks5 \u6682\u672A\u5B9E\u73B0\uFF0C\u8BF7\u6539\u7528 http \u6216 https");
1059
+ continue;
1060
+ }
1061
+ const password = options.resolvePassword?.(provider, route.passwordRef);
1062
+ void password;
1063
+ const url = proxyUrl(route);
1064
+ let dispatcher;
1065
+ try {
1066
+ dispatcher = new ProxyAgent({ uri: url });
1067
+ } catch (error) {
1068
+ problems.set(provider, error instanceof Error ? error.message : String(error));
1069
+ continue;
1070
+ }
1071
+ entries.set(provider, { provider, proxyOrigin: new URL(url).origin, dispatcher });
1072
+ }
1073
+ return { entries, problems };
1074
+ }
1075
+ async function closeTable(entries) {
1076
+ const closing = [...entries.values()].map((entry) => entry.dispatcher.close().catch(() => void 0));
1077
+ await Promise.allSettled(closing);
1078
+ entries.clear();
1079
+ }
1080
+
1081
+ // src/index.ts
1082
+ var name = "dsh-provider-proxy";
1083
+ var inject = ["llm"];
1084
+ function plainProviders(config) {
1085
+ const raw = config?.providers;
1086
+ if (raw === void 0) return {};
1087
+ const snapshot2 = raw.get;
1088
+ const value = typeof snapshot2 === "function" ? snapshot2.call(raw) : raw;
1089
+ return value ?? {};
1090
+ }
1091
+ function apply(ctx, config) {
1092
+ const router = acquireFetchRouter();
1093
+ let current = /* @__PURE__ */ new Map();
1094
+ let problems = /* @__PURE__ */ new Map();
1095
+ let closed = false;
1096
+ try {
1097
+ ctx.logger.info("dsh-provider-proxy mounted (pid %d)", process.pid);
1098
+ } catch {
1099
+ }
1100
+ const rebuild = async () => {
1101
+ const next = await createProxyTable(plainProviders(config));
1102
+ const previous = current;
1103
+ current = next.entries;
1104
+ problems = next.problems;
1105
+ void closeTable(previous);
1106
+ };
1107
+ const ready = rebuild();
1108
+ const catalog = () => {
1109
+ const live = /* @__PURE__ */ new Set();
1110
+ const out = [];
1111
+ const seen = /* @__PURE__ */ new Set();
1112
+ try {
1113
+ for (const entry of ctx.llm?.listProviders?.() ?? []) {
1114
+ const id = entry?.id;
1115
+ if (typeof id !== "string" || id.length === 0) continue;
1116
+ live.add(id);
1117
+ if (seen.has(id)) continue;
1118
+ seen.add(id);
1119
+ const name2 = typeof entry?.name === "string" && entry.name.length > 0 ? entry.name : id;
1120
+ out.push({ id, name: name2, live: true });
1121
+ }
1122
+ } catch {
1123
+ }
1124
+ try {
1125
+ for (const entry of ctx.llm?.listConfigurableProviders?.() ?? []) {
1126
+ const id = entry?.provider;
1127
+ if (typeof id !== "string" || id.length === 0) continue;
1128
+ const name2 = typeof entry.displayName === "string" && entry.displayName.length > 0 ? entry.displayName : id;
1129
+ const existing = out.find((row) => row.id === id);
1130
+ if (existing === void 0) out.push({ id, name: name2, live: live.has(id) });
1131
+ else existing.name = name2;
1132
+ }
1133
+ } catch {
1134
+ }
1135
+ out.sort((a, b) => a.name.localeCompare(b.name));
1136
+ return { providers: out };
1137
+ };
1138
+ ctx.inject?.(["webServer"], (wctx) => {
1139
+ try {
1140
+ wctx?.webServer?.register?.({
1141
+ kind: "exact",
1142
+ path: "/dsh-provider-proxy/providers",
1143
+ handler: (_req, res) => {
1144
+ try {
1145
+ const text = JSON.stringify({ ...catalog(), problems: Object.fromEntries(problems) });
1146
+ res.writeHead(200, {
1147
+ "content-type": "application/json; charset=utf-8",
1148
+ "cache-control": "no-store",
1149
+ "content-length": Buffer.byteLength(text)
1150
+ });
1151
+ res.end(text);
1152
+ } catch (error) {
1153
+ res.writeHead(500, { "content-type": "application/json" });
1154
+ res.end(JSON.stringify({ providers: [], error: String(error) }));
1155
+ }
1156
+ }
1157
+ });
1158
+ } catch (error) {
1159
+ void error;
1160
+ }
1161
+ });
1162
+ ctx.effect(() => {
1163
+ const stop = ctx.on(
1164
+ "llm/stream",
1165
+ (options, next) => {
1166
+ const provider = options?.provider;
1167
+ if (typeof provider !== "string") return next();
1168
+ const route = current.get(provider);
1169
+ if (route === void 0) return next();
1170
+ return router.wrap(route.dispatcher, next);
1171
+ },
1172
+ { global: true }
1173
+ );
1174
+ const onConfig = () => {
1175
+ void rebuild();
1176
+ };
1177
+ ctx.on("loader/volatile-update", onConfig, { global: true });
1178
+ return async () => {
1179
+ stop();
1180
+ if (closed) return;
1181
+ closed = true;
1182
+ await ready.catch(() => void 0);
1183
+ await closeTable(current);
1184
+ current = /* @__PURE__ */ new Map();
1185
+ router.release();
1186
+ };
1187
+ }, "dsh-provider-proxy: provider-scoped proxy routing");
1188
+ Object.defineProperty(ctx, "providerProxyState", {
1189
+ configurable: true,
1190
+ get: () => ({
1191
+ routes: [...current.values()].map((entry) => ({
1192
+ provider: entry.provider,
1193
+ proxyOrigin: entry.proxyOrigin
1194
+ })),
1195
+ problems: Object.fromEntries(problems)
1196
+ })
1197
+ });
1198
+ }
1199
+ export {
1200
+ Config,
1201
+ PROTOCOLS,
1202
+ ProviderProxyRoute,
1203
+ acquireFetchRouter,
1204
+ apply,
1205
+ closeTable,
1206
+ createProxyTable,
1207
+ inject,
1208
+ name,
1209
+ normalizeRoute,
1210
+ proxyUrl
1211
+ };
1212
+ //# sourceMappingURL=index.js.map