dsh-wsl-workspace 0.2.2 → 0.3.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/README.de.md +49 -0
- package/README.es.md +49 -0
- package/README.fr.md +49 -0
- package/README.ja.md +49 -0
- package/README.ko.md +49 -0
- package/README.md +47 -47
- package/README.pt.md +49 -0
- package/README.ru.md +49 -0
- package/README.zh.md +46 -46
- package/lib/client.js +76 -5
- package/lib/client.js.map +1 -1
- package/lib/fs.js +188 -174
- package/lib/fs.js.map +1 -1
- package/lib/index.js +573 -541
- package/lib/index.js.map +1 -1
- package/lib/{paths-DBaSmi7x.js → paths-BDE1NVOv.js} +17 -2
- package/lib/paths-BDE1NVOv.js.map +1 -0
- package/lib/shell.js +382 -381
- package/lib/shell.js.map +1 -1
- package/lib/wsl-C5_mxGPM.js +228 -0
- package/lib/wsl-C5_mxGPM.js.map +1 -0
- package/lib/wsl-DdNPGaPo.js +1019 -0
- package/lib/wsl-DdNPGaPo.js.map +1 -0
- package/lib/wsl-credentials-BI4v5TNZ.js +109 -0
- package/lib/wsl-credentials-BI4v5TNZ.js.map +1 -0
- package/package.json +71 -61
- package/src/client/AddWslWorkspace.tsx +349 -346
- package/src/client/api.ts +124 -104
- package/src/client/index.ts +233 -194
- package/src/fs.ts +247 -228
- package/src/host/variants.ts +164 -199
- package/src/index.ts +93 -27
- package/src/shared/paths.ts +175 -159
- package/src/shared/wsl-credentials.ts +135 -85
- package/src/shell.ts +451 -441
- package/image-1.png +0 -0
- package/image.png +0 -0
- package/lib/paths-DBaSmi7x.js.map +0 -1
- package/lib/wsl-GjkUifnx.js +0 -179
- package/lib/wsl-GjkUifnx.js.map +0 -1
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
|
|
4
|
+
//#region ../../../d/DSH Desktop/resources/app.asar.unpacked/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
5
|
+
/** Return true when a value is `null` or `undefined`. */
|
|
6
|
+
function isNullable(value) {
|
|
7
|
+
return value === null || value === void 0;
|
|
8
|
+
}
|
|
9
|
+
/** Return true for non-array object values. */
|
|
10
|
+
function isPlainObject(data) {
|
|
11
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
12
|
+
}
|
|
13
|
+
/** Filter object entries and return a new object. */
|
|
14
|
+
function filterKeys(object, filter) {
|
|
15
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
16
|
+
}
|
|
17
|
+
/** Map object values while preserving the original key set. */
|
|
18
|
+
function mapValues(object, transform) {
|
|
19
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
20
|
+
}
|
|
21
|
+
/** Pick selected keys from an object, optionally including `undefined` values. */
|
|
22
|
+
function pick(source, keys, forced) {
|
|
23
|
+
if (!keys) return { ...source };
|
|
24
|
+
const result = {};
|
|
25
|
+
for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
/** Test values using `instanceof` with a `toStringTag` fallback. */
|
|
29
|
+
function is(type, value) {
|
|
30
|
+
if (arguments.length === 1) return (value$1) => is(type, value$1);
|
|
31
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
32
|
+
}
|
|
33
|
+
function isArrayBufferLike(value) {
|
|
34
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
35
|
+
}
|
|
36
|
+
function isArrayBufferSource(value) {
|
|
37
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
38
|
+
}
|
|
39
|
+
/** Binary source detection and base64/hex conversion helpers. */
|
|
40
|
+
var Binary;
|
|
41
|
+
(function(Binary$1) {
|
|
42
|
+
Binary$1.is = isArrayBufferLike;
|
|
43
|
+
Binary$1.isSource = isArrayBufferSource;
|
|
44
|
+
function fromSource(source) {
|
|
45
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
46
|
+
else return source;
|
|
47
|
+
}
|
|
48
|
+
Binary$1.fromSource = fromSource;
|
|
49
|
+
function toBase64(source) {
|
|
50
|
+
source = fromSource(source);
|
|
51
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
|
|
52
|
+
let binary = "";
|
|
53
|
+
const bytes = new Uint8Array(source);
|
|
54
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
55
|
+
return btoa(binary);
|
|
56
|
+
}
|
|
57
|
+
Binary$1.toBase64 = toBase64;
|
|
58
|
+
function fromBase64(source) {
|
|
59
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
60
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
61
|
+
}
|
|
62
|
+
Binary$1.fromBase64 = fromBase64;
|
|
63
|
+
function toHex(source) {
|
|
64
|
+
source = fromSource(source);
|
|
65
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
66
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
67
|
+
}
|
|
68
|
+
Binary$1.toHex = toHex;
|
|
69
|
+
function fromHex(source) {
|
|
70
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
71
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
72
|
+
const buffer = [];
|
|
73
|
+
for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
74
|
+
return Uint8Array.from(buffer).buffer;
|
|
75
|
+
}
|
|
76
|
+
Binary$1.fromHex = fromHex;
|
|
77
|
+
})(Binary || (Binary = {}));
|
|
78
|
+
/** Decode a base64 string into binary data. */
|
|
79
|
+
const base64ToArrayBuffer = Binary.fromBase64;
|
|
80
|
+
/** Encode binary data as base64. */
|
|
81
|
+
const arrayBufferToBase64 = Binary.toBase64;
|
|
82
|
+
/** Decode a hex string into binary data. */
|
|
83
|
+
const hexToArrayBuffer = Binary.fromHex;
|
|
84
|
+
/** Encode binary data as hex. */
|
|
85
|
+
const arrayBufferToHex = Binary.toHex;
|
|
86
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
87
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
88
|
+
if (!source || typeof source !== "object") return source;
|
|
89
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
90
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
91
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
92
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
93
|
+
const cached = refs.get(source);
|
|
94
|
+
if (cached) return cached;
|
|
95
|
+
if (Array.isArray(source)) {
|
|
96
|
+
const result$1 = [];
|
|
97
|
+
refs.set(source, result$1);
|
|
98
|
+
source.forEach((value, index) => {
|
|
99
|
+
result$1[index] = Reflect.apply(clone, null, [value, refs]);
|
|
100
|
+
});
|
|
101
|
+
return result$1;
|
|
102
|
+
}
|
|
103
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
104
|
+
refs.set(source, result);
|
|
105
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
106
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
107
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
108
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
|
|
113
|
+
function deepEqual(a, b, strict) {
|
|
114
|
+
if (a === b) return true;
|
|
115
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
116
|
+
if (typeof a !== typeof b) return false;
|
|
117
|
+
if (typeof a !== "object") return false;
|
|
118
|
+
if (!a || !b) return false;
|
|
119
|
+
function check(test, then) {
|
|
120
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
121
|
+
}
|
|
122
|
+
return check(Array.isArray, (a$1, b$1) => a$1.length === b$1.length && a$1.every((item, index) => deepEqual(item, b$1[index]))) ?? check(is("Date"), (a$1, b$1) => a$1.valueOf() === b$1.valueOf()) ?? check(is("RegExp"), (a$1, b$1) => a$1.source === b$1.source && a$1.flags === b$1.flags) ?? check(isArrayBufferLike, (a$1, b$1) => {
|
|
123
|
+
if (a$1.byteLength !== b$1.byteLength) return false;
|
|
124
|
+
const viewA = new Uint8Array(a$1);
|
|
125
|
+
const viewB = new Uint8Array(b$1);
|
|
126
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
127
|
+
return true;
|
|
128
|
+
}) ?? Object.keys({
|
|
129
|
+
...a,
|
|
130
|
+
...b
|
|
131
|
+
}).every((key) => deepEqual(a[key], b[key], strict));
|
|
132
|
+
}
|
|
133
|
+
/** Time constants plus parsing and formatting helpers. */
|
|
134
|
+
var Time;
|
|
135
|
+
(function(Time$1) {
|
|
136
|
+
Time$1.millisecond = 1;
|
|
137
|
+
Time$1.second = 1e3;
|
|
138
|
+
Time$1.minute = Time$1.second * 60;
|
|
139
|
+
Time$1.hour = Time$1.minute * 60;
|
|
140
|
+
Time$1.day = Time$1.hour * 24;
|
|
141
|
+
Time$1.week = Time$1.day * 7;
|
|
142
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
143
|
+
function setTimezoneOffset(offset) {
|
|
144
|
+
timezoneOffset = offset;
|
|
145
|
+
}
|
|
146
|
+
Time$1.setTimezoneOffset = setTimezoneOffset;
|
|
147
|
+
function getTimezoneOffset() {
|
|
148
|
+
return timezoneOffset;
|
|
149
|
+
}
|
|
150
|
+
Time$1.getTimezoneOffset = getTimezoneOffset;
|
|
151
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
152
|
+
if (typeof date === "number") date = new Date(date);
|
|
153
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
154
|
+
return Math.floor((date.valueOf() / Time$1.minute - offset) / 1440);
|
|
155
|
+
}
|
|
156
|
+
Time$1.getDateNumber = getDateNumber;
|
|
157
|
+
function fromDateNumber(value, offset) {
|
|
158
|
+
const date = new Date(value * Time$1.day);
|
|
159
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
160
|
+
return new Date(+date + offset * Time$1.minute);
|
|
161
|
+
}
|
|
162
|
+
Time$1.fromDateNumber = fromDateNumber;
|
|
163
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
164
|
+
const timeRegExp = /* @__PURE__ */ new RegExp(`^${[
|
|
165
|
+
"w(?:eek(?:s)?)?",
|
|
166
|
+
"d(?:ay(?:s)?)?",
|
|
167
|
+
"h(?:our(?:s)?)?",
|
|
168
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
169
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
170
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
171
|
+
function parseTime(source) {
|
|
172
|
+
const capture = timeRegExp.exec(source);
|
|
173
|
+
if (!capture) return 0;
|
|
174
|
+
return (parseFloat(capture[1]) * Time$1.week || 0) + (parseFloat(capture[2]) * Time$1.day || 0) + (parseFloat(capture[3]) * Time$1.hour || 0) + (parseFloat(capture[4]) * Time$1.minute || 0) + (parseFloat(capture[5]) * Time$1.second || 0);
|
|
175
|
+
}
|
|
176
|
+
Time$1.parseTime = parseTime;
|
|
177
|
+
function parseDate(date) {
|
|
178
|
+
const parsed = parseTime(date);
|
|
179
|
+
if (parsed) date = Date.now() + parsed;
|
|
180
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
181
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
182
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
183
|
+
}
|
|
184
|
+
Time$1.parseDate = parseDate;
|
|
185
|
+
function format(ms) {
|
|
186
|
+
const abs = Math.abs(ms);
|
|
187
|
+
if (abs >= Time$1.day - Time$1.hour / 2) return Math.round(ms / Time$1.day) + "d";
|
|
188
|
+
else if (abs >= Time$1.hour - Time$1.minute / 2) return Math.round(ms / Time$1.hour) + "h";
|
|
189
|
+
else if (abs >= Time$1.minute - Time$1.second / 2) return Math.round(ms / Time$1.minute) + "m";
|
|
190
|
+
else if (abs >= Time$1.second) return Math.round(ms / Time$1.second) + "s";
|
|
191
|
+
return ms + "ms";
|
|
192
|
+
}
|
|
193
|
+
Time$1.format = format;
|
|
194
|
+
function toDigits(source, length = 2) {
|
|
195
|
+
return source.toString().padStart(length, "0");
|
|
196
|
+
}
|
|
197
|
+
Time$1.toDigits = toDigits;
|
|
198
|
+
function template(template$1, time = /* @__PURE__ */ new Date()) {
|
|
199
|
+
return template$1.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));
|
|
200
|
+
}
|
|
201
|
+
Time$1.template = template;
|
|
202
|
+
})(Time || (Time = {}));
|
|
203
|
+
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region ../../../d/DSH Desktop/resources/app.asar.unpacked/node_modules/@deepseek-ai/schemastery/lib/index.mjs
|
|
206
|
+
const kSchema = Symbol.for("schemastery");
|
|
207
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
208
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
209
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
210
|
+
var ValidationError = class extends TypeError {
|
|
211
|
+
options;
|
|
212
|
+
name = "ValidationError";
|
|
213
|
+
constructor(message, options) {
|
|
214
|
+
let prefix = "$";
|
|
215
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
216
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
217
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
218
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
219
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
220
|
+
this.options = options;
|
|
221
|
+
}
|
|
222
|
+
static is(error) {
|
|
223
|
+
return !!error?.[kValidationError];
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
227
|
+
const Schema = function(options) {
|
|
228
|
+
const schema = function(data, options$1 = {}) {
|
|
229
|
+
return Schema.resolve(data, schema, options$1)[0];
|
|
230
|
+
};
|
|
231
|
+
if (options.refs) {
|
|
232
|
+
const refs = mapValues(options.refs, (options$1) => new Schema(options$1));
|
|
233
|
+
const getRef = (uid) => refs[uid];
|
|
234
|
+
for (const key in refs) {
|
|
235
|
+
const options$1 = refs[key];
|
|
236
|
+
options$1.sKey = getRef(options$1.sKey);
|
|
237
|
+
options$1.inner = getRef(options$1.inner);
|
|
238
|
+
options$1.list = options$1.list && options$1.list.map(getRef);
|
|
239
|
+
options$1.dict = options$1.dict && mapValues(options$1.dict, getRef);
|
|
240
|
+
}
|
|
241
|
+
return refs[options.uid];
|
|
242
|
+
}
|
|
243
|
+
Object.assign(schema, options);
|
|
244
|
+
if (typeof schema.callback === "string") try {
|
|
245
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
246
|
+
} catch {}
|
|
247
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
248
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
249
|
+
schema.meta ||= {};
|
|
250
|
+
schema.toString = schema.toString.bind(schema);
|
|
251
|
+
return schema;
|
|
252
|
+
};
|
|
253
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
254
|
+
Schema.prototype[kSchema] = true;
|
|
255
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
256
|
+
return {
|
|
257
|
+
version: 1,
|
|
258
|
+
vendor: "schemastery",
|
|
259
|
+
validate: (value) => {
|
|
260
|
+
try {
|
|
261
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
264
|
+
message: error.message,
|
|
265
|
+
path: error.options.path
|
|
266
|
+
}] };
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
} });
|
|
272
|
+
Schema.ValidationError = ValidationError;
|
|
273
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
274
|
+
if (globalThis.__schemastery_refs__) {
|
|
275
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
276
|
+
return this.uid;
|
|
277
|
+
}
|
|
278
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
279
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
280
|
+
const result = {
|
|
281
|
+
uid: this.uid,
|
|
282
|
+
refs: globalThis.__schemastery_refs__
|
|
283
|
+
};
|
|
284
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
285
|
+
return result;
|
|
286
|
+
};
|
|
287
|
+
Schema.prototype.set = function set(key, value) {
|
|
288
|
+
this.dict[key] = value;
|
|
289
|
+
return this;
|
|
290
|
+
};
|
|
291
|
+
Schema.prototype.push = function push(value) {
|
|
292
|
+
this.list.push(value);
|
|
293
|
+
return this;
|
|
294
|
+
};
|
|
295
|
+
function mergeDesc(original, messages) {
|
|
296
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
297
|
+
for (const locale in messages) {
|
|
298
|
+
const value = messages[locale];
|
|
299
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
300
|
+
else if (typeof value === "string") result[locale] = value;
|
|
301
|
+
}
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
function getInner(value) {
|
|
305
|
+
return value?.$value ?? value?.$inner;
|
|
306
|
+
}
|
|
307
|
+
function extractKeys(data) {
|
|
308
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
309
|
+
}
|
|
310
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
311
|
+
const schema = Schema(this);
|
|
312
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
313
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
314
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
315
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
316
|
+
});
|
|
317
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
318
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
319
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
320
|
+
if (Array.isArray(data)) return data[index];
|
|
321
|
+
return extractKeys(data);
|
|
322
|
+
}));
|
|
323
|
+
});
|
|
324
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
325
|
+
if (getInner(data)) return getInner(data);
|
|
326
|
+
return extractKeys(data);
|
|
327
|
+
}));
|
|
328
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
329
|
+
return schema;
|
|
330
|
+
};
|
|
331
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
332
|
+
const schema = Schema(this);
|
|
333
|
+
schema.meta = {
|
|
334
|
+
...schema.meta,
|
|
335
|
+
[key]: value
|
|
336
|
+
};
|
|
337
|
+
return schema;
|
|
338
|
+
};
|
|
339
|
+
for (const key of [
|
|
340
|
+
"required",
|
|
341
|
+
"disabled",
|
|
342
|
+
"collapse",
|
|
343
|
+
"hidden",
|
|
344
|
+
"loose"
|
|
345
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
346
|
+
const schema = Schema(this);
|
|
347
|
+
schema.meta = {
|
|
348
|
+
...schema.meta,
|
|
349
|
+
[key]: value
|
|
350
|
+
};
|
|
351
|
+
return schema;
|
|
352
|
+
} });
|
|
353
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
354
|
+
const schema = Schema(this);
|
|
355
|
+
schema.meta.badges ||= [];
|
|
356
|
+
schema.meta.badges.push({
|
|
357
|
+
text: "deprecated",
|
|
358
|
+
type: "danger"
|
|
359
|
+
});
|
|
360
|
+
return schema;
|
|
361
|
+
};
|
|
362
|
+
Schema.prototype.experimental = function experimental() {
|
|
363
|
+
const schema = Schema(this);
|
|
364
|
+
schema.meta.badges ||= [];
|
|
365
|
+
schema.meta.badges.push({
|
|
366
|
+
text: "experimental",
|
|
367
|
+
type: "warning"
|
|
368
|
+
});
|
|
369
|
+
return schema;
|
|
370
|
+
};
|
|
371
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
372
|
+
const schema = Schema(this);
|
|
373
|
+
const pattern$1 = pick(regexp, ["source", "flags"]);
|
|
374
|
+
schema.meta = {
|
|
375
|
+
...schema.meta,
|
|
376
|
+
pattern: pattern$1
|
|
377
|
+
};
|
|
378
|
+
return schema;
|
|
379
|
+
};
|
|
380
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
381
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
382
|
+
if (isNullable(value)) return value;
|
|
383
|
+
if (this.type === "object" || this.type === "dict") {
|
|
384
|
+
const result = {};
|
|
385
|
+
for (const key in value) {
|
|
386
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
387
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
388
|
+
}
|
|
389
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
390
|
+
return result;
|
|
391
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
392
|
+
const result = [];
|
|
393
|
+
value.forEach((value$1, index) => {
|
|
394
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
395
|
+
const item = schema ? schema.simplify(value$1) : value$1;
|
|
396
|
+
result.push(item);
|
|
397
|
+
});
|
|
398
|
+
return result;
|
|
399
|
+
} else if (this.type === "intersect") {
|
|
400
|
+
const result = {};
|
|
401
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
402
|
+
return result;
|
|
403
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
404
|
+
Schema.resolve(value, schema, {});
|
|
405
|
+
return schema.simplify(value);
|
|
406
|
+
} catch {}
|
|
407
|
+
return value;
|
|
408
|
+
};
|
|
409
|
+
Schema.prototype.toString = function toString(inline) {
|
|
410
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
411
|
+
};
|
|
412
|
+
Schema.prototype.role = function role(role$1, extra) {
|
|
413
|
+
const schema = Schema(this);
|
|
414
|
+
schema.meta = {
|
|
415
|
+
...schema.meta,
|
|
416
|
+
role: role$1,
|
|
417
|
+
extra
|
|
418
|
+
};
|
|
419
|
+
return schema;
|
|
420
|
+
};
|
|
421
|
+
for (const key of [
|
|
422
|
+
"default",
|
|
423
|
+
"link",
|
|
424
|
+
"comment",
|
|
425
|
+
"description",
|
|
426
|
+
"max",
|
|
427
|
+
"min",
|
|
428
|
+
"step"
|
|
429
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
430
|
+
const schema = Schema(this);
|
|
431
|
+
schema.meta = {
|
|
432
|
+
...schema.meta,
|
|
433
|
+
[key]: value
|
|
434
|
+
};
|
|
435
|
+
return schema;
|
|
436
|
+
} });
|
|
437
|
+
const resolvers = {};
|
|
438
|
+
Schema.extend = function extend(type, resolve) {
|
|
439
|
+
resolvers[type] = resolve;
|
|
440
|
+
};
|
|
441
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
442
|
+
if (!schema) return [data];
|
|
443
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
444
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
445
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
446
|
+
let current = schema;
|
|
447
|
+
let fallback = schema.meta.default;
|
|
448
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
449
|
+
current = current.list[0];
|
|
450
|
+
fallback = current?.meta.default;
|
|
451
|
+
}
|
|
452
|
+
if (isNullable(fallback)) return [data];
|
|
453
|
+
data = clone(fallback);
|
|
454
|
+
}
|
|
455
|
+
const callback = resolvers[schema.type];
|
|
456
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
457
|
+
try {
|
|
458
|
+
return callback(data, schema, options, strict);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (!schema.meta.loose) throw error;
|
|
461
|
+
return [schema.meta.default];
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
Schema.from = function from(source) {
|
|
465
|
+
if (isNullable(source)) return Schema.any();
|
|
466
|
+
else if ([
|
|
467
|
+
"string",
|
|
468
|
+
"number",
|
|
469
|
+
"boolean"
|
|
470
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
471
|
+
else if (source[kSchema]) return source;
|
|
472
|
+
else if (typeof source === "function") switch (source) {
|
|
473
|
+
case String: return Schema.string().required();
|
|
474
|
+
case Number: return Schema.number().required();
|
|
475
|
+
case Boolean: return Schema.boolean().required();
|
|
476
|
+
case Function: return Schema.function().required();
|
|
477
|
+
default: return Schema.is(source).required();
|
|
478
|
+
}
|
|
479
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
480
|
+
};
|
|
481
|
+
Schema.lazy = function lazy(builder) {
|
|
482
|
+
const toJSON = () => {
|
|
483
|
+
if (!schema.inner[kSchema]) {
|
|
484
|
+
schema.inner = schema.builder();
|
|
485
|
+
schema.inner.meta = {
|
|
486
|
+
...schema.meta,
|
|
487
|
+
...schema.inner.meta
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
return schema.inner.toJSON();
|
|
491
|
+
};
|
|
492
|
+
const schema = new Schema({
|
|
493
|
+
type: "lazy",
|
|
494
|
+
builder,
|
|
495
|
+
inner: { toJSON }
|
|
496
|
+
});
|
|
497
|
+
return schema;
|
|
498
|
+
};
|
|
499
|
+
Schema.natural = function natural() {
|
|
500
|
+
return Schema.number().step(1).min(0);
|
|
501
|
+
};
|
|
502
|
+
Schema.percent = function percent() {
|
|
503
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
504
|
+
};
|
|
505
|
+
Schema.date = function date() {
|
|
506
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
507
|
+
const date$1 = new Date(value);
|
|
508
|
+
if (isNaN(+date$1)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
509
|
+
return date$1;
|
|
510
|
+
}, true)]);
|
|
511
|
+
};
|
|
512
|
+
Schema.regExp = function regExp(flag = "") {
|
|
513
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
514
|
+
try {
|
|
515
|
+
return new RegExp(value, flag);
|
|
516
|
+
} catch (e) {
|
|
517
|
+
throw new ValidationError(e.message, options);
|
|
518
|
+
}
|
|
519
|
+
}, true)]);
|
|
520
|
+
};
|
|
521
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
522
|
+
return Schema.union([
|
|
523
|
+
Schema.is(ArrayBuffer),
|
|
524
|
+
Schema.is(SharedArrayBuffer),
|
|
525
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
526
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
527
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
528
|
+
}, true),
|
|
529
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
530
|
+
try {
|
|
531
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
532
|
+
} catch (e) {
|
|
533
|
+
throw new ValidationError(e.message, options);
|
|
534
|
+
}
|
|
535
|
+
}, true)] : []
|
|
536
|
+
]);
|
|
537
|
+
};
|
|
538
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
539
|
+
if (!schema.inner[kSchema]) {
|
|
540
|
+
schema.inner = schema.builder();
|
|
541
|
+
schema.inner.meta = {
|
|
542
|
+
...schema.meta,
|
|
543
|
+
...schema.inner.meta
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
547
|
+
});
|
|
548
|
+
Schema.extend("any", (data) => {
|
|
549
|
+
return [data];
|
|
550
|
+
});
|
|
551
|
+
Schema.extend("never", (data, _, options) => {
|
|
552
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
553
|
+
});
|
|
554
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
555
|
+
if (deepEqual(data, value)) return [value];
|
|
556
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
557
|
+
});
|
|
558
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
559
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
560
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
561
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
562
|
+
}
|
|
563
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
564
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
565
|
+
if (meta.pattern) {
|
|
566
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
567
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
568
|
+
}
|
|
569
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
570
|
+
return [data];
|
|
571
|
+
});
|
|
572
|
+
function decimalShift(data, digits) {
|
|
573
|
+
const str = data.toString();
|
|
574
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
575
|
+
const index = str.indexOf(".");
|
|
576
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
577
|
+
const frac = str.slice(index + 1);
|
|
578
|
+
const integer = str.slice(0, index);
|
|
579
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
580
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
581
|
+
}
|
|
582
|
+
function isMultipleOf(data, min, step) {
|
|
583
|
+
step = Math.abs(step);
|
|
584
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
585
|
+
const index = step.toString().indexOf(".");
|
|
586
|
+
const digits = step.toString().slice(index + 1).length;
|
|
587
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
588
|
+
}
|
|
589
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
590
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
591
|
+
checkWithinRange(data, meta, "number", options);
|
|
592
|
+
const { step } = meta;
|
|
593
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
594
|
+
return [data];
|
|
595
|
+
});
|
|
596
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
597
|
+
if (typeof data === "boolean") return [data];
|
|
598
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
599
|
+
});
|
|
600
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
601
|
+
let value = 0, keys = [];
|
|
602
|
+
if (typeof data === "number") {
|
|
603
|
+
value = data;
|
|
604
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
605
|
+
} else if (Array.isArray(data)) {
|
|
606
|
+
keys = data;
|
|
607
|
+
for (const key of keys) {
|
|
608
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
609
|
+
if (key in bits) value |= bits[key];
|
|
610
|
+
}
|
|
611
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
612
|
+
if (value === meta.default) return [value];
|
|
613
|
+
return [value, keys];
|
|
614
|
+
});
|
|
615
|
+
Schema.extend("function", (data, _, options) => {
|
|
616
|
+
if (typeof data === "function") return [data];
|
|
617
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
618
|
+
});
|
|
619
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
620
|
+
if (typeof constructor === "function") {
|
|
621
|
+
if (data instanceof constructor) return [data];
|
|
622
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
623
|
+
} else {
|
|
624
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
625
|
+
let prototype = Object.getPrototypeOf(data);
|
|
626
|
+
while (prototype) {
|
|
627
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
628
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
629
|
+
}
|
|
630
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
631
|
+
}
|
|
632
|
+
});
|
|
633
|
+
function property(data, key, schema, options) {
|
|
634
|
+
try {
|
|
635
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
636
|
+
...options,
|
|
637
|
+
path: [...options.path || [], key]
|
|
638
|
+
});
|
|
639
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
640
|
+
return value;
|
|
641
|
+
} catch (e) {
|
|
642
|
+
if (!options?.autofix) throw e;
|
|
643
|
+
delete data[key];
|
|
644
|
+
return schema.meta.default;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
648
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
649
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
650
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
651
|
+
});
|
|
652
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
653
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
654
|
+
const result = {};
|
|
655
|
+
for (const key in data) {
|
|
656
|
+
let rKey;
|
|
657
|
+
try {
|
|
658
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (strict) continue;
|
|
661
|
+
throw error;
|
|
662
|
+
}
|
|
663
|
+
result[rKey] = property(data, key, inner, options);
|
|
664
|
+
data[rKey] = data[key];
|
|
665
|
+
if (key !== rKey) delete data[key];
|
|
666
|
+
}
|
|
667
|
+
return [result];
|
|
668
|
+
});
|
|
669
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
670
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
671
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
672
|
+
if (strict) return [result];
|
|
673
|
+
result.push(...data.slice(list.length));
|
|
674
|
+
return [result];
|
|
675
|
+
});
|
|
676
|
+
function merge(result, data) {
|
|
677
|
+
for (const key in data) {
|
|
678
|
+
if (key in result) continue;
|
|
679
|
+
result[key] = data[key];
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
683
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
684
|
+
const result = {};
|
|
685
|
+
for (const key in dict) {
|
|
686
|
+
const value = property(data, key, dict[key], options);
|
|
687
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
688
|
+
}
|
|
689
|
+
if (!strict) merge(result, data);
|
|
690
|
+
return [result];
|
|
691
|
+
});
|
|
692
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
693
|
+
const messages = [];
|
|
694
|
+
for (const inner of list) try {
|
|
695
|
+
return Schema.resolve(data, inner, options, strict);
|
|
696
|
+
} catch (error) {
|
|
697
|
+
messages.push(error);
|
|
698
|
+
}
|
|
699
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
700
|
+
});
|
|
701
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
702
|
+
if (!list.length) return [data];
|
|
703
|
+
let result;
|
|
704
|
+
for (const inner of list) {
|
|
705
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
706
|
+
if (isNullable(value)) continue;
|
|
707
|
+
if (isNullable(result)) result = value;
|
|
708
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
709
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
710
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
711
|
+
}
|
|
712
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
713
|
+
return [result];
|
|
714
|
+
});
|
|
715
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
716
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
717
|
+
if (preserve) return [callback(result)];
|
|
718
|
+
else return [callback(result), callback(adapted)];
|
|
719
|
+
});
|
|
720
|
+
const formatters = {};
|
|
721
|
+
function defineMethod(name, keys, format) {
|
|
722
|
+
formatters[name] = format;
|
|
723
|
+
Object.assign(Schema, { [name](...args) {
|
|
724
|
+
const schema = new Schema({ type: name });
|
|
725
|
+
keys.forEach((key, index) => {
|
|
726
|
+
switch (key) {
|
|
727
|
+
case "sKey":
|
|
728
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
729
|
+
break;
|
|
730
|
+
case "inner":
|
|
731
|
+
schema.inner = Schema.from(args[index]);
|
|
732
|
+
break;
|
|
733
|
+
case "list":
|
|
734
|
+
schema.list = args[index].map(Schema.from);
|
|
735
|
+
break;
|
|
736
|
+
case "dict":
|
|
737
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
738
|
+
break;
|
|
739
|
+
case "bits":
|
|
740
|
+
schema.bits = {};
|
|
741
|
+
for (const key$1 in args[index]) {
|
|
742
|
+
if (typeof args[index][key$1] !== "number") continue;
|
|
743
|
+
schema.bits[key$1] = args[index][key$1];
|
|
744
|
+
}
|
|
745
|
+
break;
|
|
746
|
+
case "callback": {
|
|
747
|
+
const callback = schema.callback = args[index];
|
|
748
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
749
|
+
break;
|
|
750
|
+
}
|
|
751
|
+
case "constructor": {
|
|
752
|
+
const constructor = schema.constructor = args[index];
|
|
753
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
754
|
+
break;
|
|
755
|
+
}
|
|
756
|
+
default: schema[key] = args[index];
|
|
757
|
+
}
|
|
758
|
+
});
|
|
759
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
760
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
761
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
762
|
+
return schema;
|
|
763
|
+
} });
|
|
764
|
+
}
|
|
765
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
766
|
+
if (typeof constructor === "function") return constructor.name;
|
|
767
|
+
else return constructor;
|
|
768
|
+
});
|
|
769
|
+
defineMethod("any", [], () => "any");
|
|
770
|
+
defineMethod("never", [], () => "never");
|
|
771
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
772
|
+
defineMethod("string", [], () => "string");
|
|
773
|
+
defineMethod("number", [], () => "number");
|
|
774
|
+
defineMethod("boolean", [], () => "boolean");
|
|
775
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
776
|
+
defineMethod("function", [], () => "function");
|
|
777
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
778
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
779
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
780
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
781
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
782
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
783
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
784
|
+
}).join(", ")} }`;
|
|
785
|
+
});
|
|
786
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
787
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
788
|
+
return inline ? `(${result})` : result;
|
|
789
|
+
});
|
|
790
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
791
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
792
|
+
});
|
|
793
|
+
defineMethod("transform", [
|
|
794
|
+
"inner",
|
|
795
|
+
"callback",
|
|
796
|
+
"preserve"
|
|
797
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
798
|
+
|
|
799
|
+
//#endregion
|
|
800
|
+
//#region src/shared/paths.ts
|
|
801
|
+
/** The two UNC hosts WSL exposes a distribution's filesystem under. */
|
|
802
|
+
const UNC_HOSTS = ["wsl.localhost", "wsl$"];
|
|
803
|
+
/**
|
|
804
|
+
* Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2
|
|
805
|
+
* `\\wsl.localhost\<distro>\<linux>` form, the legacy `\\wsl$\<distro>\<linux>`
|
|
806
|
+
* interop form, and forward-slash spellings of either.
|
|
807
|
+
* @param raw - candidate absolute path.
|
|
808
|
+
* @returns the parsed target, or null when the path is not a WSL UNC.
|
|
809
|
+
*/
|
|
810
|
+
function parseWslUnc(raw) {
|
|
811
|
+
const normalized = raw.replace(/\\/g, "/").replace(/\/\/+/g, "//");
|
|
812
|
+
if (!normalized.startsWith("//")) return null;
|
|
813
|
+
const segments = normalized.slice(2).split("/");
|
|
814
|
+
const host = (segments[0] ?? "").toLowerCase();
|
|
815
|
+
if (!UNC_HOSTS.includes(host)) return null;
|
|
816
|
+
const distro = segments[1] ?? "";
|
|
817
|
+
if (distro === "") return null;
|
|
818
|
+
return {
|
|
819
|
+
distro,
|
|
820
|
+
linuxPath: `/${segments.slice(2).filter((segment) => segment.length > 0).join("/")}`
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Normalize a Linux absolute path for the Host: collapse repeated slashes and
|
|
825
|
+
* strip a trailing slash (root becomes `/`).
|
|
826
|
+
* @param path - absolute Linux path.
|
|
827
|
+
* @returns the normalized path.
|
|
828
|
+
*/
|
|
829
|
+
function normalizeLinuxPath(path) {
|
|
830
|
+
const collapsed = path.replace(/\/+/g, "/");
|
|
831
|
+
return collapsed === "/" ? "/" : collapsed.replace(/\/$/, "");
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Whether a path is an absolute, non-empty Linux path.
|
|
835
|
+
* @param path - candidate.
|
|
836
|
+
* @returns whether it starts with `/` and contains no NUL.
|
|
837
|
+
*/
|
|
838
|
+
function isAbsoluteLinuxPath(path) {
|
|
839
|
+
return path.startsWith("/") && !path.includes("\0");
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Join a distro and a Linux absolute path into the WSL2 UNC form used as the
|
|
843
|
+
* workspace identity (`\\wsl.localhost\<distro>\<linux>`, backslash segments).
|
|
844
|
+
* @param distro - distro name.
|
|
845
|
+
* @param linuxPath - absolute Linux path (leading `/`).
|
|
846
|
+
* @returns the UNC path.
|
|
847
|
+
*/
|
|
848
|
+
function joinUnc(distro, linuxPath) {
|
|
849
|
+
if (!isAbsoluteLinuxPath(linuxPath)) throw new Error(`wsl-workspace: cannot map a non-absolute Linux path "${linuxPath}" to UNC`);
|
|
850
|
+
if (distro === "" || distro === "." || distro === ".." || /[\\/]/.test(distro)) throw new Error(`wsl-workspace: invalid distribution name "${distro}"`);
|
|
851
|
+
const normalized = linuxPath.replace(/\/+/g, "/").replace(/\/$/, "");
|
|
852
|
+
const windowsSegments = (normalized.startsWith("/") ? normalized.slice(1) : normalized).replace(/\//g, "\\");
|
|
853
|
+
return `\\\\wsl.localhost\\${distro}${windowsSegments === "" ? "" : `\\${windowsSegments}`}`;
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Translate a Windows drive path to the drvfs mount path WSL distributions
|
|
857
|
+
* conventionally expose it at (`C:\foo` → `/mnt/c/foo`). Only single-letter
|
|
858
|
+
* drives under `/mnt` are mapped; custom mount points are out of scope.
|
|
859
|
+
* @param path - the candidate Windows path.
|
|
860
|
+
* @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.
|
|
861
|
+
*/
|
|
862
|
+
function windowsToMntPath(path) {
|
|
863
|
+
const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
|
|
864
|
+
if (match === null) return null;
|
|
865
|
+
const rest = (match[2] ?? "").replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/$/, "");
|
|
866
|
+
return `/mnt/${(match[1] ?? "").toLowerCase()}${rest === "" ? "" : `/${rest}`}`;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Translate a `/mnt/<drive>/…` path back to its Windows drive path.
|
|
870
|
+
* @param linuxPath - the candidate Linux path.
|
|
871
|
+
* @returns the `X:\…` drive path, or `null` when the path is not a drvfs mount.
|
|
872
|
+
*/
|
|
873
|
+
function mntToWindowsPath(linuxPath) {
|
|
874
|
+
const match = /^\/mnt\/([a-zA-Z])(?:\/(.*))?$/.exec(linuxPath);
|
|
875
|
+
if (match === null) return null;
|
|
876
|
+
const rest = (match[2] ?? "").replace(/\//g, "\\");
|
|
877
|
+
return `${(match[1] ?? "").toUpperCase()}:\\${rest}`;
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Canonical Windows drive path for store keys and cross-realm identity:
|
|
881
|
+
* separators unified to `\`, trailing separator stripped, and the WHOLE path
|
|
882
|
+
* lowercased — Windows paths compare case-insensitively, and the workspace
|
|
883
|
+
* registry may realpath a different casing than the caller spelled (8.3 or
|
|
884
|
+
* on-disk casing), so the store key must collide across casings.
|
|
885
|
+
* @param path - candidate Windows drive path.
|
|
886
|
+
* @returns the canonical form, or `null` when not drive-shaped.
|
|
887
|
+
*/
|
|
888
|
+
function canonicalWindowsPath(path) {
|
|
889
|
+
const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
|
|
890
|
+
if (match === null) return null;
|
|
891
|
+
const rest = (match[2] ?? "").replace(/[\\/]+/g, "\\").replace(/\\$/, "").toLowerCase();
|
|
892
|
+
return `${(match[1] ?? "").toLowerCase()}:\\${rest}`;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* True when a value is a Windows-shaped path (drive or UNC), which is how
|
|
896
|
+
* the shell executor decides the WSLENV `/p` translation flag: only Windows
|
|
897
|
+
* path values need translation when they cross into the Linux process.
|
|
898
|
+
* @param value - the environment value to classify.
|
|
899
|
+
* @returns whether the value looks like a Windows path.
|
|
900
|
+
*/
|
|
901
|
+
function isWindowsPathShaped(value) {
|
|
902
|
+
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
|
|
903
|
+
}
|
|
904
|
+
/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */
|
|
905
|
+
const WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
906
|
+
/**
|
|
907
|
+
* Whether a value is a safe Linux username for `wsl.exe -u`. The check is
|
|
908
|
+
* strict on purpose: a value starting with `-` could be parsed as a wsl.exe
|
|
909
|
+
* option instead of a username.
|
|
910
|
+
* @param value - candidate username.
|
|
911
|
+
* @returns whether it matches the Linux username shape.
|
|
912
|
+
*/
|
|
913
|
+
function isValidWslUsername(value) {
|
|
914
|
+
return WSL_USERNAME_PATTERN.test(value);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region src/shared/wsl.ts
|
|
919
|
+
const execFileAsync = promisify(execFile);
|
|
920
|
+
/** Executable timeout for the short discovery calls. */
|
|
921
|
+
const DISCOVERY_TIMEOUT_MS = 1e4;
|
|
922
|
+
const LXSS_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";
|
|
923
|
+
/** Human text for an unknown rejection. */
|
|
924
|
+
function messageOf(value) {
|
|
925
|
+
return value instanceof Error ? value.message : String(value);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE
|
|
929
|
+
* with NUL bytes interleaved — the NUL probe picks the right one.
|
|
930
|
+
* @param buffer - the raw captured output.
|
|
931
|
+
* @returns the decoded text.
|
|
932
|
+
*/
|
|
933
|
+
function decodeWslOutput(buffer) {
|
|
934
|
+
return buffer.includes(0) ? buffer.toString("utf16le") : buffer.toString("utf8");
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* List installed WSL distributions in `wsl.exe` order.
|
|
938
|
+
* @param wslPath - the `wsl.exe` executable (absolute or PATH name).
|
|
939
|
+
* @returns distribution names, blank lines dropped.
|
|
940
|
+
*/
|
|
941
|
+
async function listDistros(wslPath = "wsl.exe") {
|
|
942
|
+
let stdout;
|
|
943
|
+
try {
|
|
944
|
+
stdout = (await execFileAsync(wslPath, ["-l", "-q"], {
|
|
945
|
+
encoding: "buffer",
|
|
946
|
+
timeout: DISCOVERY_TIMEOUT_MS
|
|
947
|
+
})).stdout;
|
|
948
|
+
} catch (error) {
|
|
949
|
+
throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`);
|
|
950
|
+
}
|
|
951
|
+
return decodeWslOutput(stdout).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Read the user's default distribution from the Lxss registry. Non-fatal:
|
|
955
|
+
* returns `undefined` when the value is absent or unreadable (the caller
|
|
956
|
+
* falls back to list order).
|
|
957
|
+
* @returns the default distribution name, or `undefined`.
|
|
958
|
+
*/
|
|
959
|
+
async function defaultDistro() {
|
|
960
|
+
try {
|
|
961
|
+
const value = await execFileAsync("reg.exe", [
|
|
962
|
+
"query",
|
|
963
|
+
LXSS_KEY,
|
|
964
|
+
"/v",
|
|
965
|
+
"DefaultDistribution"
|
|
966
|
+
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
967
|
+
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(value.stdout)?.[1];
|
|
968
|
+
if (guid === void 0) return void 0;
|
|
969
|
+
const name = await execFileAsync("reg.exe", [
|
|
970
|
+
"query",
|
|
971
|
+
`${LXSS_KEY}\\${guid}`,
|
|
972
|
+
"/v",
|
|
973
|
+
"DistributionName"
|
|
974
|
+
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
975
|
+
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(name.stdout)?.[1]?.trim();
|
|
976
|
+
return distro === void 0 || distro === "" ? void 0 : distro;
|
|
977
|
+
} catch {
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
/** Module-level cache for {@link defaultDistroSync} (one registry read per process). */
|
|
982
|
+
let syncDefaultResolved = false;
|
|
983
|
+
let syncDefault;
|
|
984
|
+
/**
|
|
985
|
+
* Synchronous variant of {@link defaultDistro} for executors that must
|
|
986
|
+
* resolve a distribution inside a synchronous plan step. Cached after the
|
|
987
|
+
* first read; non-fatal (returns `undefined` when the registry is
|
|
988
|
+
* unreadable, letting the caller fail loud with its own message).
|
|
989
|
+
* @returns the default distribution name, or `undefined`.
|
|
990
|
+
*/
|
|
991
|
+
function defaultDistroSync() {
|
|
992
|
+
if (syncDefaultResolved) return syncDefault;
|
|
993
|
+
syncDefaultResolved = true;
|
|
994
|
+
try {
|
|
995
|
+
const value = execFileSync("reg.exe", [
|
|
996
|
+
"query",
|
|
997
|
+
LXSS_KEY,
|
|
998
|
+
"/v",
|
|
999
|
+
"DefaultDistribution"
|
|
1000
|
+
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
1001
|
+
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(String(value))?.[1];
|
|
1002
|
+
if (guid === void 0) return void 0;
|
|
1003
|
+
const name = execFileSync("reg.exe", [
|
|
1004
|
+
"query",
|
|
1005
|
+
`${LXSS_KEY}\\${guid}`,
|
|
1006
|
+
"/v",
|
|
1007
|
+
"DistributionName"
|
|
1008
|
+
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
1009
|
+
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(String(name))?.[1]?.trim();
|
|
1010
|
+
syncDefault = distro === void 0 || distro === "" ? void 0 : distro;
|
|
1011
|
+
} catch {
|
|
1012
|
+
syncDefault = void 0;
|
|
1013
|
+
}
|
|
1014
|
+
return syncDefault;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
//#endregion
|
|
1018
|
+
export { isAbsoluteLinuxPath as a, joinUnc as c, parseWslUnc as d, windowsToMntPath as f, canonicalWindowsPath as i, mntToWindowsPath as l, defaultDistroSync as n, isValidWslUsername as o, Schema as p, listDistros as r, isWindowsPathShaped as s, defaultDistro as t, normalizeLinuxPath as u };
|
|
1019
|
+
//# sourceMappingURL=wsl-DdNPGaPo.js.map
|