@prettier-ai/dsh-client-ui-settings 0.1.2-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.i18n.yaml +6 -0
- package/README.md +107 -0
- package/README.zh.md +107 -0
- package/lib/client.js +1377 -0
- package/lib/index.js +6 -0
- package/lib/invariant.js +25 -0
- package/lib/types/client/contract/slots.d.ts +161 -0
- package/lib/types/client/index.d.ts +36 -0
- package/lib/types/client/schema.d.ts +72 -0
- package/lib/types/client/settings-contract.d.ts +86 -0
- package/lib/types/client/settings-mirror.d.ts +130 -0
- package/lib/types/client/settings-scope.d.ts +139 -0
- package/lib/types/index.d.ts +4 -0
- package/lib/types/invariant.d.ts +16 -0
- package/package.json +74 -0
package/lib/client.js
ADDED
|
@@ -0,0 +1,1377 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: "@prettier-ai/dsh-client-ui-settings",
|
|
3
|
+
factory: (require) => {
|
|
4
|
+
var module = { exports: {} };
|
|
5
|
+
var exports = module.exports;
|
|
6
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
7
|
+
let _prettier_ai_cordis = require("@prettier-ai/cordis");
|
|
8
|
+
let _prettier_ai_dsh_client_store = require("@prettier-ai/dsh-client-store");
|
|
9
|
+
//#region ../../../vendor/cosmokit/src/misc.ts
|
|
10
|
+
/** Return true when a value is `null` or `undefined`. */
|
|
11
|
+
function isNullable(value) {
|
|
12
|
+
return value === null || value === void 0;
|
|
13
|
+
}
|
|
14
|
+
/** Return true for non-array object values. */
|
|
15
|
+
function isPlainObject(data) {
|
|
16
|
+
return data && typeof data === "object" && !Array.isArray(data);
|
|
17
|
+
}
|
|
18
|
+
/** Filter object entries and return a new object. */
|
|
19
|
+
function filterKeys(object, filter) {
|
|
20
|
+
return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
|
|
21
|
+
}
|
|
22
|
+
/** Map object values while preserving the original key set. */
|
|
23
|
+
function mapValues(object, transform) {
|
|
24
|
+
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
|
|
25
|
+
}
|
|
26
|
+
/** Pick selected keys from an object, optionally including `undefined` values. */
|
|
27
|
+
function pick(source, keys, forced) {
|
|
28
|
+
if (!keys) return { ...source };
|
|
29
|
+
const result = {};
|
|
30
|
+
for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region ../../../vendor/cosmokit/src/types.ts
|
|
35
|
+
/** Test values using `instanceof` with a `toStringTag` fallback. */
|
|
36
|
+
function is(type, value) {
|
|
37
|
+
if (arguments.length === 1) return (value) => is(type, value);
|
|
38
|
+
return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
|
|
39
|
+
}
|
|
40
|
+
function isArrayBufferLike(value) {
|
|
41
|
+
return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
|
|
42
|
+
}
|
|
43
|
+
function isArrayBufferSource(value) {
|
|
44
|
+
return isArrayBufferLike(value) || ArrayBuffer.isView(value);
|
|
45
|
+
}
|
|
46
|
+
let Binary;
|
|
47
|
+
(function(_Binary) {
|
|
48
|
+
_Binary.is = isArrayBufferLike;
|
|
49
|
+
_Binary.isSource = isArrayBufferSource;
|
|
50
|
+
function fromSource(source) {
|
|
51
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
52
|
+
else return source;
|
|
53
|
+
}
|
|
54
|
+
_Binary.fromSource = fromSource;
|
|
55
|
+
function toBase64(source) {
|
|
56
|
+
source = fromSource(source);
|
|
57
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
|
|
58
|
+
let binary = "";
|
|
59
|
+
const bytes = new Uint8Array(source);
|
|
60
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
|
61
|
+
return btoa(binary);
|
|
62
|
+
}
|
|
63
|
+
_Binary.toBase64 = toBase64;
|
|
64
|
+
function fromBase64(source) {
|
|
65
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
|
|
66
|
+
return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
|
|
67
|
+
}
|
|
68
|
+
_Binary.fromBase64 = fromBase64;
|
|
69
|
+
function toHex(source) {
|
|
70
|
+
source = fromSource(source);
|
|
71
|
+
if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
|
|
72
|
+
return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
73
|
+
}
|
|
74
|
+
_Binary.toHex = toHex;
|
|
75
|
+
function fromHex(source) {
|
|
76
|
+
if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
|
|
77
|
+
const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
|
|
78
|
+
const buffer = [];
|
|
79
|
+
for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
|
|
80
|
+
return Uint8Array.from(buffer).buffer;
|
|
81
|
+
}
|
|
82
|
+
_Binary.fromHex = fromHex;
|
|
83
|
+
})(Binary || (Binary = {}));
|
|
84
|
+
Binary.fromBase64;
|
|
85
|
+
Binary.toBase64;
|
|
86
|
+
Binary.fromHex;
|
|
87
|
+
Binary.toHex;
|
|
88
|
+
/** Deep-clone common JavaScript values while preserving prototypes and cycles. */
|
|
89
|
+
function clone(source, refs = /* @__PURE__ */ new Map()) {
|
|
90
|
+
if (!source || typeof source !== "object") return source;
|
|
91
|
+
if (is("Date", source)) return new Date(source.valueOf());
|
|
92
|
+
if (is("RegExp", source)) return new RegExp(source.source, source.flags);
|
|
93
|
+
if (isArrayBufferLike(source)) return source.slice(0);
|
|
94
|
+
if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
95
|
+
const cached = refs.get(source);
|
|
96
|
+
if (cached) return cached;
|
|
97
|
+
if (Array.isArray(source)) {
|
|
98
|
+
const result = [];
|
|
99
|
+
refs.set(source, result);
|
|
100
|
+
source.forEach((value, index) => {
|
|
101
|
+
result[index] = Reflect.apply(clone, null, [value, refs]);
|
|
102
|
+
});
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
const result = Object.create(Object.getPrototypeOf(source));
|
|
106
|
+
refs.set(source, result);
|
|
107
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
108
|
+
const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
|
|
109
|
+
if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
|
|
110
|
+
Reflect.defineProperty(result, key, descriptor);
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
|
|
115
|
+
function deepEqual(a, b, strict) {
|
|
116
|
+
if (a === b) return true;
|
|
117
|
+
if (!strict && isNullable(a) && isNullable(b)) return true;
|
|
118
|
+
if (typeof a !== typeof b) return false;
|
|
119
|
+
if (typeof a !== "object") return false;
|
|
120
|
+
if (!a || !b) return false;
|
|
121
|
+
function check(test, then) {
|
|
122
|
+
return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
|
|
123
|
+
}
|
|
124
|
+
return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
|
|
125
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
126
|
+
const viewA = new Uint8Array(a);
|
|
127
|
+
const viewB = new Uint8Array(b);
|
|
128
|
+
for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
|
|
129
|
+
return true;
|
|
130
|
+
}) ?? Object.keys({
|
|
131
|
+
...a,
|
|
132
|
+
...b
|
|
133
|
+
}).every((key) => deepEqual(a[key], b[key], strict));
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region ../../../vendor/cosmokit/src/time.ts
|
|
137
|
+
let Time;
|
|
138
|
+
(function(_Time) {
|
|
139
|
+
_Time.millisecond = 1;
|
|
140
|
+
const second = _Time.second = 1e3;
|
|
141
|
+
const minute = _Time.minute = second * 60;
|
|
142
|
+
const hour = _Time.hour = minute * 60;
|
|
143
|
+
const day = _Time.day = hour * 24;
|
|
144
|
+
const week = _Time.week = day * 7;
|
|
145
|
+
let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
|
|
146
|
+
function setTimezoneOffset(offset) {
|
|
147
|
+
timezoneOffset = offset;
|
|
148
|
+
}
|
|
149
|
+
_Time.setTimezoneOffset = setTimezoneOffset;
|
|
150
|
+
function getTimezoneOffset() {
|
|
151
|
+
return timezoneOffset;
|
|
152
|
+
}
|
|
153
|
+
_Time.getTimezoneOffset = getTimezoneOffset;
|
|
154
|
+
function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
|
|
155
|
+
if (typeof date === "number") date = new Date(date);
|
|
156
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
157
|
+
return Math.floor((date.valueOf() / minute - offset) / 1440);
|
|
158
|
+
}
|
|
159
|
+
_Time.getDateNumber = getDateNumber;
|
|
160
|
+
function fromDateNumber(value, offset) {
|
|
161
|
+
const date = new Date(value * day);
|
|
162
|
+
if (offset === void 0) offset = timezoneOffset;
|
|
163
|
+
return new Date(+date + offset * minute);
|
|
164
|
+
}
|
|
165
|
+
_Time.fromDateNumber = fromDateNumber;
|
|
166
|
+
const numeric = /\d+(?:\.\d+)?/.source;
|
|
167
|
+
const timeRegExp = new RegExp(`^${[
|
|
168
|
+
"w(?:eek(?:s)?)?",
|
|
169
|
+
"d(?:ay(?:s)?)?",
|
|
170
|
+
"h(?:our(?:s)?)?",
|
|
171
|
+
"m(?:in(?:ute)?(?:s)?)?",
|
|
172
|
+
"s(?:ec(?:ond)?(?:s)?)?"
|
|
173
|
+
].map((unit) => `(${numeric}${unit})?`).join("")}$`);
|
|
174
|
+
function parseTime(source) {
|
|
175
|
+
const capture = timeRegExp.exec(source);
|
|
176
|
+
if (!capture) return 0;
|
|
177
|
+
return (parseFloat(capture[1]) * week || 0) + (parseFloat(capture[2]) * day || 0) + (parseFloat(capture[3]) * hour || 0) + (parseFloat(capture[4]) * minute || 0) + (parseFloat(capture[5]) * second || 0);
|
|
178
|
+
}
|
|
179
|
+
_Time.parseTime = parseTime;
|
|
180
|
+
function parseDate(date) {
|
|
181
|
+
const parsed = parseTime(date);
|
|
182
|
+
if (parsed) date = Date.now() + parsed;
|
|
183
|
+
else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
|
|
184
|
+
else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
|
|
185
|
+
return date ? new Date(date) : /* @__PURE__ */ new Date();
|
|
186
|
+
}
|
|
187
|
+
_Time.parseDate = parseDate;
|
|
188
|
+
function format(ms) {
|
|
189
|
+
const abs = Math.abs(ms);
|
|
190
|
+
if (abs >= day - hour / 2) return Math.round(ms / day) + "d";
|
|
191
|
+
else if (abs >= hour - minute / 2) return Math.round(ms / hour) + "h";
|
|
192
|
+
else if (abs >= minute - second / 2) return Math.round(ms / minute) + "m";
|
|
193
|
+
else if (abs >= second) return Math.round(ms / second) + "s";
|
|
194
|
+
return ms + "ms";
|
|
195
|
+
}
|
|
196
|
+
_Time.format = format;
|
|
197
|
+
function toDigits(source, length = 2) {
|
|
198
|
+
return source.toString().padStart(length, "0");
|
|
199
|
+
}
|
|
200
|
+
_Time.toDigits = toDigits;
|
|
201
|
+
function template(template, time = /* @__PURE__ */ new Date()) {
|
|
202
|
+
return template.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));
|
|
203
|
+
}
|
|
204
|
+
_Time.template = template;
|
|
205
|
+
})(Time || (Time = {}));
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region ../../../vendor/schemastery/src/index.ts
|
|
208
|
+
const kSchema = Symbol.for("schemastery");
|
|
209
|
+
const kValidationError = Symbol.for("ValidationError");
|
|
210
|
+
globalThis.__schemastery_index__ ??= 0;
|
|
211
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
212
|
+
var ValidationError = class extends TypeError {
|
|
213
|
+
options;
|
|
214
|
+
name = "ValidationError";
|
|
215
|
+
constructor(message, options) {
|
|
216
|
+
let prefix = "$";
|
|
217
|
+
for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
|
|
218
|
+
else if (typeof segment === "number") prefix += "[" + segment + "]";
|
|
219
|
+
else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
|
|
220
|
+
if (prefix.startsWith(".")) prefix = prefix.slice(1);
|
|
221
|
+
super((prefix === "$" ? "" : `${prefix} `) + message);
|
|
222
|
+
this.options = options;
|
|
223
|
+
}
|
|
224
|
+
static is(error) {
|
|
225
|
+
return !!error?.[kValidationError];
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
|
|
229
|
+
const Schema = function(options) {
|
|
230
|
+
const schema = function(data, options = {}) {
|
|
231
|
+
return Schema.resolve(data, schema, options)[0];
|
|
232
|
+
};
|
|
233
|
+
if (options.refs) {
|
|
234
|
+
const refs = mapValues(options.refs, (options) => new Schema(options));
|
|
235
|
+
const getRef = (uid) => refs[uid];
|
|
236
|
+
for (const key in refs) {
|
|
237
|
+
const options = refs[key];
|
|
238
|
+
options.sKey = getRef(options.sKey);
|
|
239
|
+
options.inner = getRef(options.inner);
|
|
240
|
+
options.list = options.list && options.list.map(getRef);
|
|
241
|
+
options.dict = options.dict && mapValues(options.dict, getRef);
|
|
242
|
+
}
|
|
243
|
+
return refs[options.uid];
|
|
244
|
+
}
|
|
245
|
+
Object.assign(schema, options);
|
|
246
|
+
if (typeof schema.callback === "string") try {
|
|
247
|
+
schema.callback = new Function("return " + schema.callback)();
|
|
248
|
+
} catch {}
|
|
249
|
+
Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
|
|
250
|
+
Object.setPrototypeOf(schema, Schema.prototype);
|
|
251
|
+
schema.meta ||= {};
|
|
252
|
+
schema.toString = schema.toString.bind(schema);
|
|
253
|
+
return schema;
|
|
254
|
+
};
|
|
255
|
+
Schema.prototype = Object.create(Function.prototype);
|
|
256
|
+
Schema.prototype[kSchema] = true;
|
|
257
|
+
Object.defineProperty(Schema.prototype, "~standard", { get() {
|
|
258
|
+
return {
|
|
259
|
+
version: 1,
|
|
260
|
+
vendor: "schemastery",
|
|
261
|
+
validate: (value) => {
|
|
262
|
+
try {
|
|
263
|
+
return { value: Schema.resolve(value, this, {})[0] };
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (ValidationError.is(error)) return { issues: [{
|
|
266
|
+
message: error.message,
|
|
267
|
+
path: error.options.path
|
|
268
|
+
}] };
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
} });
|
|
274
|
+
Schema.ValidationError = ValidationError;
|
|
275
|
+
Schema.prototype.toJSON = function toJSON() {
|
|
276
|
+
if (globalThis.__schemastery_refs__) {
|
|
277
|
+
globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
278
|
+
return this.uid;
|
|
279
|
+
}
|
|
280
|
+
globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
281
|
+
globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
282
|
+
const result = {
|
|
283
|
+
uid: this.uid,
|
|
284
|
+
refs: globalThis.__schemastery_refs__
|
|
285
|
+
};
|
|
286
|
+
globalThis.__schemastery_refs__ = void 0;
|
|
287
|
+
return result;
|
|
288
|
+
};
|
|
289
|
+
Schema.prototype.set = function set(key, value) {
|
|
290
|
+
this.dict[key] = value;
|
|
291
|
+
return this;
|
|
292
|
+
};
|
|
293
|
+
Schema.prototype.push = function push(value) {
|
|
294
|
+
this.list.push(value);
|
|
295
|
+
return this;
|
|
296
|
+
};
|
|
297
|
+
function mergeDesc(original, messages) {
|
|
298
|
+
const result = typeof original === "string" ? { "": original } : { ...original };
|
|
299
|
+
for (const locale in messages) {
|
|
300
|
+
const value = messages[locale];
|
|
301
|
+
if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
|
|
302
|
+
else if (typeof value === "string") result[locale] = value;
|
|
303
|
+
}
|
|
304
|
+
return result;
|
|
305
|
+
}
|
|
306
|
+
function getInner(value) {
|
|
307
|
+
return value?.$value ?? value?.$inner;
|
|
308
|
+
}
|
|
309
|
+
function extractKeys(data) {
|
|
310
|
+
return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
|
|
311
|
+
}
|
|
312
|
+
Schema.prototype.i18n = function i18n(messages) {
|
|
313
|
+
const schema = Schema(this);
|
|
314
|
+
const desc = mergeDesc(schema.meta.description, messages);
|
|
315
|
+
if (Object.keys(desc).length) schema.meta.description = desc;
|
|
316
|
+
if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
|
|
317
|
+
return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
|
|
318
|
+
});
|
|
319
|
+
if (schema.list) schema.list = schema.list.map((inner, index) => {
|
|
320
|
+
return inner.i18n(mapValues(messages, (data = {}) => {
|
|
321
|
+
if (Array.isArray(getInner(data))) return getInner(data)[index];
|
|
322
|
+
if (Array.isArray(data)) return data[index];
|
|
323
|
+
return extractKeys(data);
|
|
324
|
+
}));
|
|
325
|
+
});
|
|
326
|
+
if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
|
|
327
|
+
if (getInner(data)) return getInner(data);
|
|
328
|
+
return extractKeys(data);
|
|
329
|
+
}));
|
|
330
|
+
if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
|
|
331
|
+
return schema;
|
|
332
|
+
};
|
|
333
|
+
Schema.prototype.extra = function extra(key, value) {
|
|
334
|
+
const schema = Schema(this);
|
|
335
|
+
schema.meta = {
|
|
336
|
+
...schema.meta,
|
|
337
|
+
[key]: value
|
|
338
|
+
};
|
|
339
|
+
return schema;
|
|
340
|
+
};
|
|
341
|
+
for (const key of [
|
|
342
|
+
"required",
|
|
343
|
+
"disabled",
|
|
344
|
+
"collapse",
|
|
345
|
+
"hidden",
|
|
346
|
+
"loose"
|
|
347
|
+
]) Object.assign(Schema.prototype, { [key](value = true) {
|
|
348
|
+
const schema = Schema(this);
|
|
349
|
+
schema.meta = {
|
|
350
|
+
...schema.meta,
|
|
351
|
+
[key]: value
|
|
352
|
+
};
|
|
353
|
+
return schema;
|
|
354
|
+
} });
|
|
355
|
+
Schema.prototype.deprecated = function deprecated() {
|
|
356
|
+
const schema = Schema(this);
|
|
357
|
+
schema.meta.badges ||= [];
|
|
358
|
+
schema.meta.badges.push({
|
|
359
|
+
text: "deprecated",
|
|
360
|
+
type: "danger"
|
|
361
|
+
});
|
|
362
|
+
return schema;
|
|
363
|
+
};
|
|
364
|
+
Schema.prototype.experimental = function experimental() {
|
|
365
|
+
const schema = Schema(this);
|
|
366
|
+
schema.meta.badges ||= [];
|
|
367
|
+
schema.meta.badges.push({
|
|
368
|
+
text: "experimental",
|
|
369
|
+
type: "warning"
|
|
370
|
+
});
|
|
371
|
+
return schema;
|
|
372
|
+
};
|
|
373
|
+
Schema.prototype.pattern = function pattern(regexp) {
|
|
374
|
+
const schema = Schema(this);
|
|
375
|
+
const pattern = pick(regexp, ["source", "flags"]);
|
|
376
|
+
schema.meta = {
|
|
377
|
+
...schema.meta,
|
|
378
|
+
pattern
|
|
379
|
+
};
|
|
380
|
+
return schema;
|
|
381
|
+
};
|
|
382
|
+
Schema.prototype.simplify = function simplify(value) {
|
|
383
|
+
if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
|
|
384
|
+
if (isNullable(value)) return value;
|
|
385
|
+
if (this.type === "object" || this.type === "dict") {
|
|
386
|
+
const result = {};
|
|
387
|
+
for (const key in value) {
|
|
388
|
+
const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
|
|
389
|
+
if (this.type === "dict" || !isNullable(item)) result[key] = item;
|
|
390
|
+
}
|
|
391
|
+
if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
|
|
392
|
+
return result;
|
|
393
|
+
} else if (this.type === "array" || this.type === "tuple") {
|
|
394
|
+
const result = [];
|
|
395
|
+
value.forEach((value, index) => {
|
|
396
|
+
const schema = this.type === "array" ? this.inner : this.list[index];
|
|
397
|
+
const item = schema ? schema.simplify(value) : value;
|
|
398
|
+
result.push(item);
|
|
399
|
+
});
|
|
400
|
+
return result;
|
|
401
|
+
} else if (this.type === "intersect") {
|
|
402
|
+
const result = {};
|
|
403
|
+
for (const item of this.list) Object.assign(result, item.simplify(value));
|
|
404
|
+
return result;
|
|
405
|
+
} else if (this.type === "union") for (const schema of this.list) try {
|
|
406
|
+
Schema.resolve(value, schema, {});
|
|
407
|
+
return schema.simplify(value);
|
|
408
|
+
} catch {}
|
|
409
|
+
return value;
|
|
410
|
+
};
|
|
411
|
+
Schema.prototype.toString = function toString(inline) {
|
|
412
|
+
return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
|
|
413
|
+
};
|
|
414
|
+
Schema.prototype.role = function role(role, extra) {
|
|
415
|
+
const schema = Schema(this);
|
|
416
|
+
schema.meta = {
|
|
417
|
+
...schema.meta,
|
|
418
|
+
role,
|
|
419
|
+
extra
|
|
420
|
+
};
|
|
421
|
+
return schema;
|
|
422
|
+
};
|
|
423
|
+
for (const key of [
|
|
424
|
+
"default",
|
|
425
|
+
"link",
|
|
426
|
+
"comment",
|
|
427
|
+
"description",
|
|
428
|
+
"max",
|
|
429
|
+
"min",
|
|
430
|
+
"step"
|
|
431
|
+
]) Object.assign(Schema.prototype, { [key](value) {
|
|
432
|
+
const schema = Schema(this);
|
|
433
|
+
schema.meta = {
|
|
434
|
+
...schema.meta,
|
|
435
|
+
[key]: value
|
|
436
|
+
};
|
|
437
|
+
return schema;
|
|
438
|
+
} });
|
|
439
|
+
const resolvers = {};
|
|
440
|
+
Schema.extend = function extend(type, resolve) {
|
|
441
|
+
resolvers[type] = resolve;
|
|
442
|
+
};
|
|
443
|
+
Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
|
|
444
|
+
if (!schema) return [data];
|
|
445
|
+
if (options.ignore?.(data, schema)) return [data];
|
|
446
|
+
if (isNullable(data) && schema.type !== "lazy") {
|
|
447
|
+
if (schema.meta.required) throw new ValidationError(`missing required value`, options);
|
|
448
|
+
let current = schema;
|
|
449
|
+
let fallback = schema.meta.default;
|
|
450
|
+
while (current?.type === "intersect" && isNullable(fallback)) {
|
|
451
|
+
current = current.list[0];
|
|
452
|
+
fallback = current?.meta.default;
|
|
453
|
+
}
|
|
454
|
+
if (isNullable(fallback)) return [data];
|
|
455
|
+
data = clone(fallback);
|
|
456
|
+
}
|
|
457
|
+
const callback = resolvers[schema.type];
|
|
458
|
+
if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
|
|
459
|
+
try {
|
|
460
|
+
return callback(data, schema, options, strict);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
if (!schema.meta.loose) throw error;
|
|
463
|
+
return [schema.meta.default];
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
Schema.from = function from(source) {
|
|
467
|
+
if (isNullable(source)) return Schema.any();
|
|
468
|
+
else if ([
|
|
469
|
+
"string",
|
|
470
|
+
"number",
|
|
471
|
+
"boolean"
|
|
472
|
+
].includes(typeof source)) return Schema.const(source).required();
|
|
473
|
+
else if (source[kSchema]) return source;
|
|
474
|
+
else if (typeof source === "function") switch (source) {
|
|
475
|
+
case String: return Schema.string().required();
|
|
476
|
+
case Number: return Schema.number().required();
|
|
477
|
+
case Boolean: return Schema.boolean().required();
|
|
478
|
+
case Function: return Schema.function().required();
|
|
479
|
+
default: return Schema.is(source).required();
|
|
480
|
+
}
|
|
481
|
+
else throw new TypeError(`cannot infer schema from ${source}`);
|
|
482
|
+
};
|
|
483
|
+
Schema.lazy = function lazy(builder) {
|
|
484
|
+
const toJSON = () => {
|
|
485
|
+
if (!schema.inner[kSchema]) {
|
|
486
|
+
schema.inner = schema.builder();
|
|
487
|
+
schema.inner.meta = {
|
|
488
|
+
...schema.meta,
|
|
489
|
+
...schema.inner.meta
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
return schema.inner.toJSON();
|
|
493
|
+
};
|
|
494
|
+
const schema = new Schema({
|
|
495
|
+
type: "lazy",
|
|
496
|
+
builder,
|
|
497
|
+
inner: { toJSON }
|
|
498
|
+
});
|
|
499
|
+
return schema;
|
|
500
|
+
};
|
|
501
|
+
Schema.natural = function natural() {
|
|
502
|
+
return Schema.number().step(1).min(0);
|
|
503
|
+
};
|
|
504
|
+
Schema.percent = function percent() {
|
|
505
|
+
return Schema.number().step(.01).min(0).max(1).role("slider");
|
|
506
|
+
};
|
|
507
|
+
Schema.date = function date() {
|
|
508
|
+
return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
|
|
509
|
+
const date = new Date(value);
|
|
510
|
+
if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
|
|
511
|
+
return date;
|
|
512
|
+
}, true)]);
|
|
513
|
+
};
|
|
514
|
+
Schema.regExp = function regExp(flag = "") {
|
|
515
|
+
return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
|
|
516
|
+
try {
|
|
517
|
+
return new RegExp(value, flag);
|
|
518
|
+
} catch (e) {
|
|
519
|
+
throw new ValidationError(e.message, options);
|
|
520
|
+
}
|
|
521
|
+
}, true)]);
|
|
522
|
+
};
|
|
523
|
+
Schema.arrayBuffer = function arrayBuffer(encoding) {
|
|
524
|
+
return Schema.union([
|
|
525
|
+
Schema.is(ArrayBuffer),
|
|
526
|
+
Schema.is(SharedArrayBuffer),
|
|
527
|
+
Schema.transform(Schema.any(), (value, options) => {
|
|
528
|
+
if (Binary.isSource(value)) return Binary.fromSource(value);
|
|
529
|
+
throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
|
|
530
|
+
}, true),
|
|
531
|
+
...encoding ? [Schema.transform(Schema.string(), (value, options) => {
|
|
532
|
+
try {
|
|
533
|
+
return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
|
|
534
|
+
} catch (e) {
|
|
535
|
+
throw new ValidationError(e.message, options);
|
|
536
|
+
}
|
|
537
|
+
}, true)] : []
|
|
538
|
+
]);
|
|
539
|
+
};
|
|
540
|
+
Schema.extend("lazy", (data, schema, options, strict) => {
|
|
541
|
+
if (!schema.inner[kSchema]) {
|
|
542
|
+
schema.inner = schema.builder();
|
|
543
|
+
schema.inner.meta = {
|
|
544
|
+
...schema.meta,
|
|
545
|
+
...schema.inner.meta
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
return Schema.resolve(data, schema.inner, options, strict);
|
|
549
|
+
});
|
|
550
|
+
Schema.extend("any", (data) => {
|
|
551
|
+
return [data];
|
|
552
|
+
});
|
|
553
|
+
Schema.extend("never", (data, _, options) => {
|
|
554
|
+
throw new ValidationError(`expected nullable but got ${data}`, options);
|
|
555
|
+
});
|
|
556
|
+
Schema.extend("const", (data, { value }, options) => {
|
|
557
|
+
if (deepEqual(data, value)) return [value];
|
|
558
|
+
throw new ValidationError(`expected ${value} but got ${data}`, options);
|
|
559
|
+
});
|
|
560
|
+
function checkWithinRange(data, meta, description, options, skipMin = false) {
|
|
561
|
+
const { max = Infinity, min = -Infinity } = meta;
|
|
562
|
+
if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
|
|
563
|
+
if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
|
|
564
|
+
}
|
|
565
|
+
Schema.extend("string", (data, { meta }, options) => {
|
|
566
|
+
if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
|
|
567
|
+
if (meta.pattern) {
|
|
568
|
+
const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
|
|
569
|
+
if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
|
|
570
|
+
}
|
|
571
|
+
checkWithinRange(data.length, meta, "string length", options);
|
|
572
|
+
return [data];
|
|
573
|
+
});
|
|
574
|
+
function decimalShift(data, digits) {
|
|
575
|
+
const str = data.toString();
|
|
576
|
+
if (str.includes("e")) return data * Math.pow(10, digits);
|
|
577
|
+
const index = str.indexOf(".");
|
|
578
|
+
if (index === -1) return data * Math.pow(10, digits);
|
|
579
|
+
const frac = str.slice(index + 1);
|
|
580
|
+
const integer = str.slice(0, index);
|
|
581
|
+
if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
|
|
582
|
+
return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
|
|
583
|
+
}
|
|
584
|
+
function isMultipleOf(data, min, step) {
|
|
585
|
+
step = Math.abs(step);
|
|
586
|
+
if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
|
|
587
|
+
const index = step.toString().indexOf(".");
|
|
588
|
+
const digits = step.toString().slice(index + 1).length;
|
|
589
|
+
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
|
|
590
|
+
}
|
|
591
|
+
Schema.extend("number", (data, { meta }, options) => {
|
|
592
|
+
if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
|
|
593
|
+
checkWithinRange(data, meta, "number", options);
|
|
594
|
+
const { step } = meta;
|
|
595
|
+
if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
|
|
596
|
+
return [data];
|
|
597
|
+
});
|
|
598
|
+
Schema.extend("boolean", (data, _, options) => {
|
|
599
|
+
if (typeof data === "boolean") return [data];
|
|
600
|
+
throw new ValidationError(`expected boolean but got ${data}`, options);
|
|
601
|
+
});
|
|
602
|
+
Schema.extend("bitset", (data, { bits, meta }, options) => {
|
|
603
|
+
let value = 0, keys = [];
|
|
604
|
+
if (typeof data === "number") {
|
|
605
|
+
value = data;
|
|
606
|
+
for (const key in bits) if (data & bits[key]) keys.push(key);
|
|
607
|
+
} else if (Array.isArray(data)) {
|
|
608
|
+
keys = data;
|
|
609
|
+
for (const key of keys) {
|
|
610
|
+
if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
|
|
611
|
+
if (key in bits) value |= bits[key];
|
|
612
|
+
}
|
|
613
|
+
} else throw new ValidationError(`expected number or array but got ${data}`, options);
|
|
614
|
+
if (value === meta.default) return [value];
|
|
615
|
+
return [value, keys];
|
|
616
|
+
});
|
|
617
|
+
Schema.extend("function", (data, _, options) => {
|
|
618
|
+
if (typeof data === "function") return [data];
|
|
619
|
+
throw new ValidationError(`expected function but got ${data}`, options);
|
|
620
|
+
});
|
|
621
|
+
Schema.extend("is", (data, { constructor }, options) => {
|
|
622
|
+
if (typeof constructor === "function") {
|
|
623
|
+
if (data instanceof constructor) return [data];
|
|
624
|
+
throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
|
|
625
|
+
} else {
|
|
626
|
+
if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
627
|
+
let prototype = Object.getPrototypeOf(data);
|
|
628
|
+
while (prototype) {
|
|
629
|
+
if (prototype.constructor?.name === constructor) return [data];
|
|
630
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
631
|
+
}
|
|
632
|
+
throw new ValidationError(`expected ${constructor} but got ${data}`, options);
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
function property(data, key, schema, options) {
|
|
636
|
+
try {
|
|
637
|
+
const [value, adapted] = Schema.resolve(data[key], schema, {
|
|
638
|
+
...options,
|
|
639
|
+
path: [...options.path || [], key]
|
|
640
|
+
});
|
|
641
|
+
if (adapted !== void 0) data[key] = adapted;
|
|
642
|
+
return value;
|
|
643
|
+
} catch (e) {
|
|
644
|
+
if (!options?.autofix) throw e;
|
|
645
|
+
delete data[key];
|
|
646
|
+
return schema.meta.default;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
Schema.extend("array", (data, { inner, meta }, options) => {
|
|
650
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
651
|
+
checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
|
|
652
|
+
return [data.map((_, index) => property(data, index, inner, options))];
|
|
653
|
+
});
|
|
654
|
+
Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
|
|
655
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
656
|
+
const result = {};
|
|
657
|
+
for (const key in data) {
|
|
658
|
+
let rKey;
|
|
659
|
+
try {
|
|
660
|
+
rKey = Schema.resolve(key, sKey, options)[0];
|
|
661
|
+
} catch (error) {
|
|
662
|
+
if (strict) continue;
|
|
663
|
+
throw error;
|
|
664
|
+
}
|
|
665
|
+
result[rKey] = property(data, key, inner, options);
|
|
666
|
+
data[rKey] = data[key];
|
|
667
|
+
if (key !== rKey) delete data[key];
|
|
668
|
+
}
|
|
669
|
+
return [result];
|
|
670
|
+
});
|
|
671
|
+
Schema.extend("tuple", (data, { list }, options, strict) => {
|
|
672
|
+
if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
|
|
673
|
+
const result = list.map((inner, index) => property(data, index, inner, options));
|
|
674
|
+
if (strict) return [result];
|
|
675
|
+
result.push(...data.slice(list.length));
|
|
676
|
+
return [result];
|
|
677
|
+
});
|
|
678
|
+
function merge(result, data) {
|
|
679
|
+
for (const key in data) {
|
|
680
|
+
if (key in result) continue;
|
|
681
|
+
result[key] = data[key];
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
Schema.extend("object", (data, { dict }, options, strict) => {
|
|
685
|
+
if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
|
|
686
|
+
const result = {};
|
|
687
|
+
for (const key in dict) {
|
|
688
|
+
const value = property(data, key, dict[key], options);
|
|
689
|
+
if (!isNullable(value) || key in data) result[key] = value;
|
|
690
|
+
}
|
|
691
|
+
if (!strict) merge(result, data);
|
|
692
|
+
return [result];
|
|
693
|
+
});
|
|
694
|
+
Schema.extend("union", (data, { list, toString }, options, strict) => {
|
|
695
|
+
const messages = [];
|
|
696
|
+
for (const inner of list) try {
|
|
697
|
+
return Schema.resolve(data, inner, options, strict);
|
|
698
|
+
} catch (error) {
|
|
699
|
+
messages.push(error);
|
|
700
|
+
}
|
|
701
|
+
throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
702
|
+
});
|
|
703
|
+
Schema.extend("intersect", (data, { list, toString }, options, strict) => {
|
|
704
|
+
if (!list.length) return [data];
|
|
705
|
+
let result;
|
|
706
|
+
for (const inner of list) {
|
|
707
|
+
const value = Schema.resolve(data, inner, options, true)[0];
|
|
708
|
+
if (isNullable(value)) continue;
|
|
709
|
+
if (isNullable(result)) result = value;
|
|
710
|
+
else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
711
|
+
else if (typeof value === "object") merge(result ??= {}, value);
|
|
712
|
+
else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
|
|
713
|
+
}
|
|
714
|
+
if (!strict && isPlainObject(data)) merge(result, data);
|
|
715
|
+
return [result];
|
|
716
|
+
});
|
|
717
|
+
Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
|
|
718
|
+
const [result, adapted = data] = Schema.resolve(data, inner, options, true);
|
|
719
|
+
if (preserve) return [callback(result)];
|
|
720
|
+
else return [callback(result), callback(adapted)];
|
|
721
|
+
});
|
|
722
|
+
const formatters = {};
|
|
723
|
+
function defineMethod(name, keys, format) {
|
|
724
|
+
formatters[name] = format;
|
|
725
|
+
Object.assign(Schema, { [name](...args) {
|
|
726
|
+
const schema = new Schema({ type: name });
|
|
727
|
+
keys.forEach((key, index) => {
|
|
728
|
+
switch (key) {
|
|
729
|
+
case "sKey":
|
|
730
|
+
schema.sKey = args[index] ?? Schema.string();
|
|
731
|
+
break;
|
|
732
|
+
case "inner":
|
|
733
|
+
schema.inner = Schema.from(args[index]);
|
|
734
|
+
break;
|
|
735
|
+
case "list":
|
|
736
|
+
schema.list = args[index].map(Schema.from);
|
|
737
|
+
break;
|
|
738
|
+
case "dict":
|
|
739
|
+
schema.dict = mapValues(args[index], Schema.from);
|
|
740
|
+
break;
|
|
741
|
+
case "bits":
|
|
742
|
+
schema.bits = {};
|
|
743
|
+
for (const key in args[index]) {
|
|
744
|
+
if (typeof args[index][key] !== "number") continue;
|
|
745
|
+
schema.bits[key] = args[index][key];
|
|
746
|
+
}
|
|
747
|
+
break;
|
|
748
|
+
case "callback": {
|
|
749
|
+
const callback = schema.callback = args[index];
|
|
750
|
+
callback["toJSON"] ||= () => callback.toString();
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
753
|
+
case "constructor": {
|
|
754
|
+
const constructor = schema.constructor = args[index];
|
|
755
|
+
if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
|
|
756
|
+
break;
|
|
757
|
+
}
|
|
758
|
+
default: schema[key] = args[index];
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
if (name === "object" || name === "dict") schema.meta.default = {};
|
|
762
|
+
else if (name === "array" || name === "tuple") schema.meta.default = [];
|
|
763
|
+
else if (name === "bitset") schema.meta.default = 0;
|
|
764
|
+
return schema;
|
|
765
|
+
} });
|
|
766
|
+
}
|
|
767
|
+
defineMethod("is", ["constructor"], ({ constructor }) => {
|
|
768
|
+
if (typeof constructor === "function") return constructor.name;
|
|
769
|
+
else return constructor;
|
|
770
|
+
});
|
|
771
|
+
defineMethod("any", [], () => "any");
|
|
772
|
+
defineMethod("never", [], () => "never");
|
|
773
|
+
defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
|
|
774
|
+
defineMethod("string", [], () => "string");
|
|
775
|
+
defineMethod("number", [], () => "number");
|
|
776
|
+
defineMethod("boolean", [], () => "boolean");
|
|
777
|
+
defineMethod("bitset", ["bits"], () => "bitset");
|
|
778
|
+
defineMethod("function", [], () => "function");
|
|
779
|
+
defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
|
|
780
|
+
defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
|
|
781
|
+
defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
|
|
782
|
+
defineMethod("object", ["dict"], ({ dict }) => {
|
|
783
|
+
if (Object.keys(dict).length === 0) return "{}";
|
|
784
|
+
return `{ ${Object.entries(dict).map(([key, inner]) => {
|
|
785
|
+
return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
|
|
786
|
+
}).join(", ")} }`;
|
|
787
|
+
});
|
|
788
|
+
defineMethod("union", ["list"], ({ list }, inline) => {
|
|
789
|
+
const result = list.map(({ toString: format }) => format()).join(" | ");
|
|
790
|
+
return inline ? `(${result})` : result;
|
|
791
|
+
});
|
|
792
|
+
defineMethod("intersect", ["list"], ({ list }) => {
|
|
793
|
+
return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
|
|
794
|
+
});
|
|
795
|
+
defineMethod("transform", [
|
|
796
|
+
"inner",
|
|
797
|
+
"callback",
|
|
798
|
+
"preserve"
|
|
799
|
+
], ({ inner }, isInner) => inner.toString(isInner));
|
|
800
|
+
//#endregion
|
|
801
|
+
//#region lib/types/client/schema.js
|
|
802
|
+
/** Synchronous schema introspection and immutable settings-draft edits. */
|
|
803
|
+
function cloneContainer(container, key) {
|
|
804
|
+
if (Array.isArray(container)) return [...container];
|
|
805
|
+
if (typeof container === "object" && container !== null) return { ...container };
|
|
806
|
+
return /^\d+$/.test(key) ? [] : {};
|
|
807
|
+
}
|
|
808
|
+
function cloneSpine(root, path) {
|
|
809
|
+
const result = { ...root };
|
|
810
|
+
let target = result;
|
|
811
|
+
for (let index = 0; index < path.length - 1; index++) {
|
|
812
|
+
const key = path[index];
|
|
813
|
+
const child = cloneContainer(Array.isArray(target) ? target[Number(key)] : target[key], path[index + 1]);
|
|
814
|
+
if (Array.isArray(target)) target[Number(key)] = child;
|
|
815
|
+
else target[key] = child;
|
|
816
|
+
target = child;
|
|
817
|
+
}
|
|
818
|
+
return {
|
|
819
|
+
result,
|
|
820
|
+
parent: target,
|
|
821
|
+
leaf: path[path.length - 1]
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Settings-owned synchronous schema service. Dynamic client plugins receive
|
|
826
|
+
* this Cordis entity instead of importing executable helpers from one another.
|
|
827
|
+
*/
|
|
828
|
+
var SettingsSchemaService = class extends _prettier_ai_cordis.Service {
|
|
829
|
+
/** @param ctx - providing ui-settings context. */
|
|
830
|
+
constructor(ctx) {
|
|
831
|
+
super(ctx, "settingsSchema");
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Rehydrate one serialized `schema.toJSON()` envelope.
|
|
835
|
+
* @param serialized - serialized Schemastery node.
|
|
836
|
+
* @returns live schema node.
|
|
837
|
+
*/
|
|
838
|
+
rehydrate(serialized) {
|
|
839
|
+
return new Schema(serialized);
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Validate a settings draft.
|
|
843
|
+
* @param schema - live schema node.
|
|
844
|
+
* @param draft - candidate settings value.
|
|
845
|
+
* @returns validation failure text, or `undefined` when valid.
|
|
846
|
+
*/
|
|
847
|
+
validate(schema, draft) {
|
|
848
|
+
try {
|
|
849
|
+
schema(draft);
|
|
850
|
+
return;
|
|
851
|
+
} catch (error) {
|
|
852
|
+
return error instanceof Error ? error.message : String(error);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Resolve an object, dict, or array schema node at a settings path.
|
|
857
|
+
* @param root - schema node to traverse.
|
|
858
|
+
* @param path - object keys or array indexes.
|
|
859
|
+
* @returns the resolved node, or `undefined` when the path is absent.
|
|
860
|
+
*/
|
|
861
|
+
nodeAtPath(root, path) {
|
|
862
|
+
let node = root;
|
|
863
|
+
for (const key of path) {
|
|
864
|
+
if (node === void 0) return void 0;
|
|
865
|
+
if (node.type === "object") node = node.dict?.[key];
|
|
866
|
+
else if (node.type === "dict" || node.type === "array") node = node.inner;
|
|
867
|
+
else return void 0;
|
|
868
|
+
}
|
|
869
|
+
return node;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Read a nested value by a string-key or array-index path.
|
|
873
|
+
* @param value - value to traverse.
|
|
874
|
+
* @param path - object keys or array indexes.
|
|
875
|
+
* @returns the resolved value, or `undefined` when the path is absent.
|
|
876
|
+
*/
|
|
877
|
+
getPath(value, path) {
|
|
878
|
+
let current = value;
|
|
879
|
+
for (const key of path) {
|
|
880
|
+
if (Array.isArray(current)) {
|
|
881
|
+
current = current[Number(key)];
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
if (typeof current !== "object" || current === null) return void 0;
|
|
885
|
+
current = current[key];
|
|
886
|
+
}
|
|
887
|
+
return current;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Report whether the final path key exists independently of its value.
|
|
891
|
+
* @param value - value to traverse.
|
|
892
|
+
* @param path - object keys or array indexes.
|
|
893
|
+
* @returns whether the path exists.
|
|
894
|
+
*/
|
|
895
|
+
hasPath(value, path) {
|
|
896
|
+
if (path.length === 0) return value !== void 0;
|
|
897
|
+
const parent = this.getPath(value, path.slice(0, -1));
|
|
898
|
+
const key = path[path.length - 1];
|
|
899
|
+
if (Array.isArray(parent)) return Number(key) < parent.length;
|
|
900
|
+
if (typeof parent !== "object" || parent === null) return false;
|
|
901
|
+
return key in parent;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Immutably set a nested value, materializing missing containers.
|
|
905
|
+
* @param root - settings object to copy.
|
|
906
|
+
* @param path - non-empty object-key or array-index path.
|
|
907
|
+
* @param value - replacement value.
|
|
908
|
+
* @returns copied root containing the replacement.
|
|
909
|
+
* @throws when `path` is empty.
|
|
910
|
+
*/
|
|
911
|
+
setPath(root, path, value) {
|
|
912
|
+
if (path.length === 0) throw new Error("ui-settings: setPath needs a non-empty path");
|
|
913
|
+
const { result, parent, leaf } = cloneSpine(root, path);
|
|
914
|
+
if (Array.isArray(parent)) parent[Number(leaf)] = value;
|
|
915
|
+
else parent[leaf] = value;
|
|
916
|
+
return result;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Immutably remove a nested key, preserving an unchanged missing root.
|
|
920
|
+
* @param root - settings object to copy.
|
|
921
|
+
* @param path - non-empty object-key or array-index path.
|
|
922
|
+
* @returns copied root without the key, or `root` when the path is absent.
|
|
923
|
+
* @throws when `path` is empty.
|
|
924
|
+
*/
|
|
925
|
+
deletePath(root, path) {
|
|
926
|
+
if (path.length === 0) throw new Error("ui-settings: deletePath needs a non-empty path");
|
|
927
|
+
if (!this.hasPath(root, path)) return root;
|
|
928
|
+
const { result, parent, leaf } = cloneSpine(root, path);
|
|
929
|
+
if (Array.isArray(parent)) parent.splice(Number(leaf), 1);
|
|
930
|
+
else Reflect.deleteProperty(parent, leaf);
|
|
931
|
+
return result;
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
//#endregion
|
|
935
|
+
//#region lib/types/client/settings-scope.js
|
|
936
|
+
/**
|
|
937
|
+
* Host transport for the settings-namespace scope contract. This file owns the
|
|
938
|
+
* per-namespace derivation over the shared {@link SettingsDescribeMirror} and
|
|
939
|
+
* the serialized write path. Reads never touch the wire here: the
|
|
940
|
+
* mirror is the one `settings.describe` reader, and every scope is a selector
|
|
941
|
+
* over its snapshot.
|
|
942
|
+
*/
|
|
943
|
+
/**
|
|
944
|
+
* One namespace's derived view over the shared describe mirror, plus that
|
|
945
|
+
* namespace's serialized Host writes. Writes carry the latest known namespace
|
|
946
|
+
* revision, fold their answers back into the mirror, and teardown waits for
|
|
947
|
+
* the operation already crossing the wire.
|
|
948
|
+
*/
|
|
949
|
+
var SettingsScopeController = class {
|
|
950
|
+
api;
|
|
951
|
+
spec;
|
|
952
|
+
mirror;
|
|
953
|
+
persistence;
|
|
954
|
+
schema;
|
|
955
|
+
store;
|
|
956
|
+
tail = Promise.resolve();
|
|
957
|
+
writeGeneration = 0;
|
|
958
|
+
disposed = false;
|
|
959
|
+
unsubscribe;
|
|
960
|
+
/**
|
|
961
|
+
* Revision answered by a superseded write still ahead of the mirror: the
|
|
962
|
+
* mirror only folds the LATEST settlement in, so a queued successor takes
|
|
963
|
+
* its fence from here first.
|
|
964
|
+
*/
|
|
965
|
+
pendingRevision;
|
|
966
|
+
/**
|
|
967
|
+
* @param api - settings wire face (writes only; reads ride the mirror).
|
|
968
|
+
* @param spec - namespace identity and optional narrowing decoder.
|
|
969
|
+
* @param mirror - the shared describe mirror this scope derives from.
|
|
970
|
+
* @param persistence - client-selected Host persistence; non-loopback pages may remain process-local.
|
|
971
|
+
* @param schema - settings-owned schema operations.
|
|
972
|
+
*/
|
|
973
|
+
constructor(api, spec, mirror, persistence, schema) {
|
|
974
|
+
this.api = api;
|
|
975
|
+
this.spec = spec;
|
|
976
|
+
this.mirror = mirror;
|
|
977
|
+
this.persistence = persistence;
|
|
978
|
+
this.schema = schema;
|
|
979
|
+
this.store = (0, _prettier_ai_dsh_client_store.createSnapshotStore)({
|
|
980
|
+
status: persistence === "host" ? "loading" : "unavailable",
|
|
981
|
+
value: void 0,
|
|
982
|
+
base: void 0,
|
|
983
|
+
user: void 0,
|
|
984
|
+
revision: void 0,
|
|
985
|
+
writable: false,
|
|
986
|
+
mode: persistence
|
|
987
|
+
});
|
|
988
|
+
if (persistence === "host") {
|
|
989
|
+
this.unsubscribe = mirror.subscribe(() => {
|
|
990
|
+
this.derive();
|
|
991
|
+
});
|
|
992
|
+
this.derive();
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
/** @returns the current sync snapshot (stable reference until the next change). */
|
|
996
|
+
getSnapshot() {
|
|
997
|
+
return this.store.getSnapshot();
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Observe snapshot replacements.
|
|
1001
|
+
* @param listener - invoked after each snapshot change.
|
|
1002
|
+
* @returns the disposer removing this listener.
|
|
1003
|
+
*/
|
|
1004
|
+
subscribe(listener) {
|
|
1005
|
+
return this.store.subscribe(listener);
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Queue one field write; see {@link SettingsScope.set} for the ordering,
|
|
1009
|
+
* revision, and recovery contract.
|
|
1010
|
+
* @param field - scalar field inside the namespace section.
|
|
1011
|
+
* @param value - JSON-shaped value selected by the user.
|
|
1012
|
+
* @returns settlement after the write and any latest-write recovery read.
|
|
1013
|
+
*/
|
|
1014
|
+
set(field, value) {
|
|
1015
|
+
return this.mutate([{
|
|
1016
|
+
op: "set",
|
|
1017
|
+
path: [field],
|
|
1018
|
+
value
|
|
1019
|
+
}]);
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Queue one field clear; see {@link SettingsScope.unset} for the ordering,
|
|
1023
|
+
* revision, and recovery contract.
|
|
1024
|
+
* @param field - scalar field inside the namespace section.
|
|
1025
|
+
* @returns settlement after the clear and any latest-write recovery read.
|
|
1026
|
+
*/
|
|
1027
|
+
unset(field) {
|
|
1028
|
+
return this.mutate([{
|
|
1029
|
+
op: "unset",
|
|
1030
|
+
path: [field]
|
|
1031
|
+
}]);
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Queue one atomic namespace mutation; see {@link SettingsScope.mutate}.
|
|
1035
|
+
* @param ops - ordered field operations copied when queued.
|
|
1036
|
+
* @param expectedRevision - optional fixed revision read by the domain editor.
|
|
1037
|
+
* @returns settlement after the mutation and any latest-write recovery read.
|
|
1038
|
+
*/
|
|
1039
|
+
mutate(ops, expectedRevision) {
|
|
1040
|
+
const ownedOps = structuredClone(ops);
|
|
1041
|
+
const generation = ++this.writeGeneration;
|
|
1042
|
+
return this.enqueue(async () => {
|
|
1043
|
+
const revision = expectedRevision ?? this.pendingRevision ?? this.getSnapshot().revision;
|
|
1044
|
+
let response;
|
|
1045
|
+
try {
|
|
1046
|
+
response = await this.api.settings.mutate(this.spec.namespace, ownedOps, revision);
|
|
1047
|
+
} catch (_settingsWriteFailure) {
|
|
1048
|
+
await this.recover(generation);
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
if (!response.ok) {
|
|
1052
|
+
await this.recover(generation);
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
if (this.disposed) return;
|
|
1056
|
+
if (generation === this.writeGeneration) {
|
|
1057
|
+
this.pendingRevision = void 0;
|
|
1058
|
+
this.mirror.acceptView(response.value);
|
|
1059
|
+
} else this.pendingRevision = response.value.revision;
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
/** Reload Host state for the latest failed write; superseded failures leave recovery to it. */
|
|
1063
|
+
async recover(generation) {
|
|
1064
|
+
if (this.disposed || generation !== this.writeGeneration) return;
|
|
1065
|
+
this.pendingRevision = void 0;
|
|
1066
|
+
await this.mirror.load();
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Stop queued operations, stop deriving, and wait for the current wire call
|
|
1070
|
+
* to settle.
|
|
1071
|
+
* @returns settlement after the controller reaches quiescence.
|
|
1072
|
+
*/
|
|
1073
|
+
async dispose() {
|
|
1074
|
+
this.disposed = true;
|
|
1075
|
+
this.writeGeneration += 1;
|
|
1076
|
+
this.unsubscribe?.();
|
|
1077
|
+
await this.tail;
|
|
1078
|
+
}
|
|
1079
|
+
enqueue(operation) {
|
|
1080
|
+
if (this.persistence === "memory" || this.disposed) return Promise.resolve();
|
|
1081
|
+
const task = this.tail.then(async () => {
|
|
1082
|
+
if (this.disposed) return;
|
|
1083
|
+
await operation();
|
|
1084
|
+
});
|
|
1085
|
+
this.tail = task.catch(() => {});
|
|
1086
|
+
return task;
|
|
1087
|
+
}
|
|
1088
|
+
derive() {
|
|
1089
|
+
if (this.disposed) return;
|
|
1090
|
+
const mirrored = this.mirror.getSnapshot();
|
|
1091
|
+
if (mirrored.view === void 0) return;
|
|
1092
|
+
const { writable } = mirrored.view;
|
|
1093
|
+
const view = mirrored.view.namespaces.find((candidate) => candidate.ns === this.spec.namespace);
|
|
1094
|
+
if (view === void 0) {
|
|
1095
|
+
this.store.update((draft) => {
|
|
1096
|
+
draft.status = "unavailable";
|
|
1097
|
+
draft.writable = writable;
|
|
1098
|
+
});
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const decoded = this.decode(view);
|
|
1102
|
+
this.store.update((draft) => {
|
|
1103
|
+
draft.revision = view.revision;
|
|
1104
|
+
draft.base = view.base;
|
|
1105
|
+
draft.user = view.user;
|
|
1106
|
+
draft.writable = writable;
|
|
1107
|
+
if (decoded === void 0) return;
|
|
1108
|
+
draft.status = "ready";
|
|
1109
|
+
draft.value = decoded;
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
decode(view) {
|
|
1113
|
+
if (this.spec.decode !== void 0) return this.spec.decode(view.value);
|
|
1114
|
+
if (typeof view.value !== "object" || view.value === null || Array.isArray(view.value)) return void 0;
|
|
1115
|
+
let failure;
|
|
1116
|
+
try {
|
|
1117
|
+
failure = this.schema.validate(this.schema.rehydrate(view.schema), view.value);
|
|
1118
|
+
} catch (_malformedSchemaEnvelope) {
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
return failure === void 0 ? view.value : void 0;
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
/**
|
|
1125
|
+
* The settings domain's base service. Features that own a preference reach the
|
|
1126
|
+
* settings transport through this service rather than a shared function: the
|
|
1127
|
+
* client bundle purity gate forbids cross-plugin value imports and directs
|
|
1128
|
+
* cross-plugin collaboration through cordis services
|
|
1129
|
+
* (`packages/client/tsdown.client.ts`).
|
|
1130
|
+
*/
|
|
1131
|
+
var SettingsScopeBinder = class extends _prettier_ai_cordis.Service {
|
|
1132
|
+
mirror;
|
|
1133
|
+
schema;
|
|
1134
|
+
wire;
|
|
1135
|
+
/**
|
|
1136
|
+
* @param ctx - the providing plugin's context.
|
|
1137
|
+
* @param config - the shared describe mirror every bound scope derives from,
|
|
1138
|
+
* the settings-owned schema operations, and the settings Remote namespace the
|
|
1139
|
+
* bound scopes write through. The namespace is captured here rather than read
|
|
1140
|
+
* inside {@link bind}, because a Service reads `ctx` as its *consumer's*
|
|
1141
|
+
* fiber: reading it there would make every caller declare `remote.settings`
|
|
1142
|
+
* in its own `inject`.
|
|
1143
|
+
*/
|
|
1144
|
+
constructor(ctx, config) {
|
|
1145
|
+
super(ctx, "settingsScope");
|
|
1146
|
+
this.mirror = config.mirror;
|
|
1147
|
+
this.schema = config.schema;
|
|
1148
|
+
this.wire = config.wire;
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* The shared mirror's read/fold face for cross-namespace surfaces (schema
|
|
1152
|
+
* introspection, the served-namespace directory). Per-namespace consumers
|
|
1153
|
+
* use {@link bind}; both derive from the same snapshot, so they can never
|
|
1154
|
+
* disagree about the document.
|
|
1155
|
+
* @returns the describe face over the shared mirror.
|
|
1156
|
+
*/
|
|
1157
|
+
describe() {
|
|
1158
|
+
return this.mirror;
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* Bind one namespace scope on the CALLER's plugin lifecycle — the service
|
|
1162
|
+
* proxy binds `this.ctx` to the caller at call time, so the scope's disposer
|
|
1163
|
+
* belongs to the calling fiber. The scope derives from the shared mirror
|
|
1164
|
+
* (whose invalidation subscriptions live with the providing plugin), so
|
|
1165
|
+
* binding adds no wire read of its own and activation never blocks on the
|
|
1166
|
+
* settings transport.
|
|
1167
|
+
* @param spec - domain-owned namespace contract.
|
|
1168
|
+
* @returns the bound scope consumed by the domain's services and rows.
|
|
1169
|
+
*/
|
|
1170
|
+
bind(spec) {
|
|
1171
|
+
const ctx = this.ctx;
|
|
1172
|
+
const connection = ctx.get("connection");
|
|
1173
|
+
const controller = new SettingsScopeController(this.wire, spec, this.mirror, connection.isLoopback ? "host" : "memory", this.schema);
|
|
1174
|
+
ctx.effect(() => {
|
|
1175
|
+
this.mirror.ensure();
|
|
1176
|
+
return async () => {
|
|
1177
|
+
await controller.dispose();
|
|
1178
|
+
};
|
|
1179
|
+
}, `ui-settings: ${spec.namespace} settings scope`);
|
|
1180
|
+
return controller;
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
//#endregion
|
|
1184
|
+
//#region lib/types/client/settings-mirror.js
|
|
1185
|
+
/**
|
|
1186
|
+
* Client mirror of the Host settings document: the one `settings.describe`
|
|
1187
|
+
* reader in the browser. Every settings consumer derives from this store —
|
|
1188
|
+
* per-namespace scopes through `SettingsScopeBinder.bind`, cross-namespace
|
|
1189
|
+
* surfaces through the binder's shared describe face — so startup cost and
|
|
1190
|
+
* freshness are properties of this class, not of how many features own a
|
|
1191
|
+
* preference. The Host stays the fact source: the mirror re-reads on the
|
|
1192
|
+
* invalidations its owning plugin subscribes to and folds write answers in
|
|
1193
|
+
* through {@link SettingsDescribeMirror.acceptView}.
|
|
1194
|
+
*/
|
|
1195
|
+
/**
|
|
1196
|
+
* Serializes every Host `settings.describe` read behind one snapshot store.
|
|
1197
|
+
* Concurrent {@link load} calls fold into the in-flight read plus one rerun,
|
|
1198
|
+
* so an invalidation arriving mid-read is never lost and never duplicated.
|
|
1199
|
+
*/
|
|
1200
|
+
var SettingsDescribeMirror = class {
|
|
1201
|
+
api;
|
|
1202
|
+
persistence;
|
|
1203
|
+
store;
|
|
1204
|
+
inFlight;
|
|
1205
|
+
rerun = false;
|
|
1206
|
+
generation = 0;
|
|
1207
|
+
/**
|
|
1208
|
+
* @param api - settings wire face.
|
|
1209
|
+
* @param persistence - client-selected Host persistence; non-loopback pages may remain process-local.
|
|
1210
|
+
*/
|
|
1211
|
+
constructor(api, persistence = "host") {
|
|
1212
|
+
this.api = api;
|
|
1213
|
+
this.persistence = persistence;
|
|
1214
|
+
this.store = (0, _prettier_ai_dsh_client_store.createSnapshotStore)({
|
|
1215
|
+
status: persistence === "host" ? "idle" : "unavailable",
|
|
1216
|
+
view: void 0,
|
|
1217
|
+
error: null
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
/** @returns the current sync snapshot (stable reference until the next change). */
|
|
1221
|
+
getSnapshot() {
|
|
1222
|
+
return this.store.getSnapshot();
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Observe snapshot replacements.
|
|
1226
|
+
* @param listener - invoked after each snapshot change.
|
|
1227
|
+
* @returns the disposer removing this listener.
|
|
1228
|
+
*/
|
|
1229
|
+
subscribe(listener) {
|
|
1230
|
+
return this.store.subscribe(listener);
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* Refresh from the Host. A call during an in-flight read marks one rerun
|
|
1234
|
+
* after it settles instead of racing a second wire read.
|
|
1235
|
+
* @returns settlement after this call's freshness is reflected.
|
|
1236
|
+
*/
|
|
1237
|
+
load() {
|
|
1238
|
+
if (this.persistence === "memory") return Promise.resolve();
|
|
1239
|
+
if (this.inFlight !== void 0) {
|
|
1240
|
+
this.rerun = true;
|
|
1241
|
+
return this.inFlight;
|
|
1242
|
+
}
|
|
1243
|
+
const run = Promise.resolve().then(() => this.run());
|
|
1244
|
+
this.inFlight = run;
|
|
1245
|
+
return run;
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Resolve once an answer is held (or the mirror is terminally unavailable),
|
|
1249
|
+
* reading only from `idle`. The cheap idempotent entry for surfaces that
|
|
1250
|
+
* render on first use.
|
|
1251
|
+
* @returns settlement of the current or newly started read, if any.
|
|
1252
|
+
*/
|
|
1253
|
+
ensure() {
|
|
1254
|
+
if (this.persistence === "memory") return Promise.resolve();
|
|
1255
|
+
if (this.inFlight !== void 0) return this.inFlight;
|
|
1256
|
+
if (this.getSnapshot().status === "idle") return this.load();
|
|
1257
|
+
return Promise.resolve();
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Fold one write answer's namespace view into the held view without a wire
|
|
1261
|
+
* read, and invalidate any read still in flight. With no held document, the
|
|
1262
|
+
* answer is not published as a partial document; an in-flight read reruns so
|
|
1263
|
+
* it cannot publish a document fetched before the write committed.
|
|
1264
|
+
* @param view - the namespace view a settings write answered with.
|
|
1265
|
+
*/
|
|
1266
|
+
acceptView(view) {
|
|
1267
|
+
const before = this.store.getSnapshot();
|
|
1268
|
+
this.generation += 1;
|
|
1269
|
+
if (this.inFlight !== void 0) this.rerun = true;
|
|
1270
|
+
if (before.view === void 0) return;
|
|
1271
|
+
const namespaces = before.view.namespaces.some((row) => row.ns === view.ns) ? before.view.namespaces.map((row) => row.ns === view.ns ? view : row) : [...before.view.namespaces, view];
|
|
1272
|
+
this.store.set({
|
|
1273
|
+
...before,
|
|
1274
|
+
view: {
|
|
1275
|
+
...before.view,
|
|
1276
|
+
namespaces
|
|
1277
|
+
}
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Convenience row lookup on the held view.
|
|
1282
|
+
* @param ns - namespace identity.
|
|
1283
|
+
* @returns the namespace view, or undefined while unanswered or unregistered.
|
|
1284
|
+
*/
|
|
1285
|
+
namespace(ns) {
|
|
1286
|
+
return this.store.getSnapshot().view?.namespaces.find((row) => row.ns === ns);
|
|
1287
|
+
}
|
|
1288
|
+
async run() {
|
|
1289
|
+
try {
|
|
1290
|
+
do {
|
|
1291
|
+
const before = this.store.getSnapshot();
|
|
1292
|
+
if (before.status === "idle") this.store.set({
|
|
1293
|
+
...before,
|
|
1294
|
+
status: "loading"
|
|
1295
|
+
});
|
|
1296
|
+
this.rerun = false;
|
|
1297
|
+
const generation = ++this.generation;
|
|
1298
|
+
let outcome;
|
|
1299
|
+
try {
|
|
1300
|
+
const response = await this.api.settings.describe();
|
|
1301
|
+
outcome = response.ok ? { view: response.value } : { failure: response.error.message };
|
|
1302
|
+
} catch (error) {
|
|
1303
|
+
outcome = { failure: error instanceof Error ? error.message : String(error) };
|
|
1304
|
+
}
|
|
1305
|
+
if (generation !== this.generation) continue;
|
|
1306
|
+
if ("view" in outcome) this.store.set({
|
|
1307
|
+
status: "ready",
|
|
1308
|
+
view: outcome.view,
|
|
1309
|
+
error: null
|
|
1310
|
+
});
|
|
1311
|
+
else {
|
|
1312
|
+
const held = this.store.getSnapshot();
|
|
1313
|
+
this.store.set({
|
|
1314
|
+
status: held.view === void 0 ? "idle" : "ready",
|
|
1315
|
+
view: held.view,
|
|
1316
|
+
error: outcome.failure
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
} while (this.shouldRerun());
|
|
1320
|
+
} finally {
|
|
1321
|
+
this.inFlight = void 0;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
shouldRerun() {
|
|
1325
|
+
return this.rerun;
|
|
1326
|
+
}
|
|
1327
|
+
};
|
|
1328
|
+
//#endregion
|
|
1329
|
+
//#region lib/types/client/index.js
|
|
1330
|
+
/**
|
|
1331
|
+
* Required services: the wire handle for the mirror's reads and the forwarded
|
|
1332
|
+
* settings invalidation the mirror refreshes on.
|
|
1333
|
+
*/
|
|
1334
|
+
const inject = [
|
|
1335
|
+
"connection",
|
|
1336
|
+
"remote",
|
|
1337
|
+
"remote.settings"
|
|
1338
|
+
];
|
|
1339
|
+
/**
|
|
1340
|
+
* Provide the settings-namespace scope service over one shared describe
|
|
1341
|
+
* mirror, and keep that mirror fresh on the two signals that can move the
|
|
1342
|
+
* settings document: a document commit and a (re)connect.
|
|
1343
|
+
*
|
|
1344
|
+
* Constructing the service in this plugin's fiber keeps its traced methods
|
|
1345
|
+
* bound to each consuming plugin's context.
|
|
1346
|
+
* @param ctx - client root context.
|
|
1347
|
+
*/
|
|
1348
|
+
function apply(ctx) {
|
|
1349
|
+
const schema = new SettingsSchemaService(ctx);
|
|
1350
|
+
const connection = ctx.get("connection");
|
|
1351
|
+
const wire = { settings: ctx.remote.settings };
|
|
1352
|
+
const mirror = new SettingsDescribeMirror(wire, connection.isLoopback ? "host" : "memory");
|
|
1353
|
+
ctx.effect(() => {
|
|
1354
|
+
const disposers = [ctx.remote.$on("settings/document-updated", () => {
|
|
1355
|
+
mirror.load();
|
|
1356
|
+
}), ctx.on("connection/reset", () => {
|
|
1357
|
+
mirror.load();
|
|
1358
|
+
})];
|
|
1359
|
+
mirror.ensure();
|
|
1360
|
+
return () => {
|
|
1361
|
+
for (const dispose of disposers) dispose();
|
|
1362
|
+
};
|
|
1363
|
+
}, "ui-settings: describe mirror invalidations");
|
|
1364
|
+
new SettingsScopeBinder(ctx, {
|
|
1365
|
+
mirror,
|
|
1366
|
+
schema,
|
|
1367
|
+
wire
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
//#endregion
|
|
1371
|
+
exports.apply = apply;
|
|
1372
|
+
exports.inject = inject;
|
|
1373
|
+
return module.exports;
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
|
|
1377
|
+
//# sourceMappingURL=client.js.map
|