返回 CodeWhale
agent-presets.mjs
根目录 / crates / tui / extension-host / dist / agent-presets.mjs
1 var __defProp = Object.defineProperty;
2 var __getOwnPropNames = Object.getOwnPropertyNames;
3 var __esm = (fn, res, err) => function __init() {
4 if (err) throw err[0];
5 try {
6 return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7 } catch (e) {
8 throw err = [e], e;
9 }
10 };
11 var __export = (target, all) => {
12 for (var name in all)
13 __defProp(target, name, { get: all[name], enumerable: true });
14 };
15
16 // node_modules/@deepseek-ai/cosmokit/lib/index.js
17 function isNullable(value) {
18 return value === null || value === void 0;
19 }
20 function isNonNullable(value) {
21 return !isNullable(value);
22 }
23 function mapValues(object, transform) {
24 return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
25 }
26 function defineProperty(object, key, value) {
27 return Object.defineProperty(object, key, {
28 writable: true,
29 value,
30 enumerable: false
31 });
32 }
33 function isVolatile(value) {
34 return typeof value === "object" && value !== null && write in value;
35 }
36 function is(type2, value) {
37 if (arguments.length === 1) return (value2) => is(type2, value2);
38 return type2 in globalThis && value instanceof globalThis[type2] || Object.prototype.toString.call(value).slice(8, -1) === type2;
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 function deepEqual(a, b, strict) {
47 const ancestors = /* @__PURE__ */ new Set();
48 function compare(a2, b2) {
49 if (a2 === b2) return true;
50 if (isVolatile(a2) || isVolatile(b2)) return isVolatile(a2) && isVolatile(b2);
51 if (!strict && isNullable(a2) && isNullable(b2)) return true;
52 if (typeof a2 !== typeof b2 || typeof a2 !== "object" || !a2 || !b2) return false;
53 if (ancestors.has(a2)) return false;
54 function check(test, then) {
55 return test(a2) ? test(b2) ? then(a2, b2) : false : test(b2) ? false : void 0;
56 }
57 ancestors.add(a2);
58 try {
59 return check(Array.isArray, (a3, b3) => {
60 if (a3.length !== b3.length) return false;
61 for (let index = 0; index < a3.length; index++) if (!compare(a3[index], b3[index])) return false;
62 return true;
63 }) ?? check(is("Date"), (a3, b3) => a3.valueOf() === b3.valueOf()) ?? check(is("URL"), (a3, b3) => a3.href === b3.href) ?? check(is("RegExp"), (a3, b3) => a3.source === b3.source && a3.flags === b3.flags) ?? check(isArrayBufferLike, (a3, b3) => {
64 if (a3.byteLength !== b3.byteLength) return false;
65 const viewA = new Uint8Array(a3);
66 const viewB = new Uint8Array(b3);
67 for (let i2 = 0; i2 < viewA.length; i2++) if (viewA[i2] !== viewB[i2]) return false;
68 return true;
69 }) ?? ((!strict || [a2, b2].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
70 ...a2,
71 ...b2
72 }).every((key) => compare(a2[key], b2[key])));
73 } finally {
74 ancestors.delete(a2);
75 }
76 }
77 return compare(a, b);
78 }
79 function tokenize(source, delimiters, delimiter) {
80 const output = [];
81 let state = 0;
82 for (let i2 = 0; i2 < source.length; i2++) {
83 const code = source.charCodeAt(i2);
84 if (code >= 65 && code <= 90) {
85 if (state === 1) {
86 const next = source.charCodeAt(i2 + 1);
87 if (next >= 97 && next <= 122) output.push(delimiter);
88 output.push(code + 32);
89 } else {
90 if (state !== 0) output.push(delimiter);
91 output.push(code + 32);
92 }
93 state = 1;
94 } else if (code >= 97 && code <= 122) {
95 output.push(code);
96 state = 2;
97 } else if (delimiters.includes(code)) {
98 if (state !== 0) output.push(delimiter);
99 state = 0;
100 } else output.push(code);
101 }
102 return String.fromCharCode(...output);
103 }
104 function paramCase(source) {
105 return tokenize(source, [45, 95], 45);
106 }
107 var write, Binary, base64ToArrayBuffer, arrayBufferToBase64, hexToArrayBuffer, arrayBufferToHex, hyphenate, Time;
108 var init_lib = __esm({
109 "node_modules/@deepseek-ai/cosmokit/lib/index.js"() {
110 write = /* @__PURE__ */ Symbol.for("cosmokit.volatile.write");
111 (function(Binary2) {
112 Binary2.is = isArrayBufferLike;
113 Binary2.isSource = isArrayBufferSource;
114 function fromSource(source) {
115 if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
116 else return source;
117 }
118 Binary2.fromSource = fromSource;
119 function toBase64(source) {
120 source = fromSource(source);
121 if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
122 let binary2 = "";
123 const bytes = new Uint8Array(source);
124 for (let i2 = 0; i2 < bytes.byteLength; i2++) binary2 += String.fromCharCode(bytes[i2]);
125 return btoa(binary2);
126 }
127 Binary2.toBase64 = toBase64;
128 function fromBase64(source) {
129 if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
130 return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
131 }
132 Binary2.fromBase64 = fromBase64;
133 function toHex(source) {
134 source = fromSource(source);
135 if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
136 return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
137 }
138 Binary2.toHex = toHex;
139 function fromHex(source) {
140 if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
141 const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
142 const buffer = [];
143 for (let i2 = 0; i2 < hex.length; i2 += 2) buffer.push(parseInt(`${hex[i2]}${hex[i2 + 1]}`, 16));
144 return Uint8Array.from(buffer).buffer;
145 }
146 Binary2.fromHex = fromHex;
147 })(Binary || (Binary = {}));
148 base64ToArrayBuffer = Binary.fromBase64;
149 arrayBufferToBase64 = Binary.toBase64;
150 hexToArrayBuffer = Binary.fromHex;
151 arrayBufferToHex = Binary.toHex;
152 hyphenate = paramCase;
153 (function(Time2) {
154 Time2.millisecond = 1;
155 Time2.second = 1e3;
156 Time2.minute = Time2.second * 60;
157 Time2.hour = Time2.minute * 60;
158 Time2.day = Time2.hour * 24;
159 Time2.week = Time2.day * 7;
160 let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
161 function setTimezoneOffset(offset2) {
162 timezoneOffset = offset2;
163 }
164 Time2.setTimezoneOffset = setTimezoneOffset;
165 function getTimezoneOffset() {
166 return timezoneOffset;
167 }
168 Time2.getTimezoneOffset = getTimezoneOffset;
169 function getDateNumber(date = /* @__PURE__ */ new Date(), offset2) {
170 if (typeof date === "number") date = new Date(date);
171 if (offset2 === void 0) offset2 = timezoneOffset;
172 return Math.floor((date.valueOf() / Time2.minute - offset2) / 1440);
173 }
174 Time2.getDateNumber = getDateNumber;
175 function fromDateNumber(value, offset2) {
176 const date = new Date(value * Time2.day);
177 if (offset2 === void 0) offset2 = timezoneOffset;
178 return new Date(+date + offset2 * Time2.minute);
179 }
180 Time2.fromDateNumber = fromDateNumber;
181 const numeric = /\d+(?:\.\d+)?/.source;
182 const timeRegExp = new RegExp(`^${[
183 "w(?:eek(?:s)?)?",
184 "d(?:ay(?:s)?)?",
185 "h(?:our(?:s)?)?",
186 "m(?:in(?:ute)?(?:s)?)?",
187 "s(?:ec(?:ond)?(?:s)?)?"
188 ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
189 function parseTime(source) {
190 const capture = timeRegExp.exec(source);
191 if (!capture) return 0;
192 return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
193 }
194 Time2.parseTime = parseTime;
195 function parseDate(date) {
196 const parsed = parseTime(date);
197 if (parsed) date = Date.now() + parsed;
198 else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
199 else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
200 return date ? new Date(date) : /* @__PURE__ */ new Date();
201 }
202 Time2.parseDate = parseDate;
203 function format(ms) {
204 const abs = Math.abs(ms);
205 if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
206 else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
207 else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
208 else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
209 return ms + "ms";
210 }
211 Time2.format = format;
212 function toDigits(source, length = 2) {
213 return source.toString().padStart(length, "0");
214 }
215 Time2.toDigits = toDigits;
216 function template(template2, time = /* @__PURE__ */ new Date()) {
217 return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
218 }
219 Time2.template = template;
220 })(Time || (Time = {}));
221 }
222 });
223
224 // node_modules/@deepseek-ai/cordis/lib/index.js
225 function isConstructor(func) {
226 if (!func.prototype) return false;
227 if (func instanceof GeneratorFunction) return false;
228 if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false;
229 return true;
230 }
231 function joinPrototype(proto1, proto2) {
232 if (proto1 === Object.prototype) return proto2;
233 const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2));
234 for (const key of Reflect.ownKeys(proto1)) Object.defineProperty(result, key, Object.getOwnPropertyDescriptor(proto1, key));
235 return result;
236 }
237 function isObject(value) {
238 return value && (typeof value === "object" || typeof value === "function");
239 }
240 function getPropertyDescriptor(target, prop) {
241 let proto = target;
242 while (proto) {
243 const desc = Reflect.getOwnPropertyDescriptor(proto, prop);
244 if (desc) return desc;
245 proto = Object.getPrototypeOf(proto);
246 }
247 }
248 function getTraceable(ctx, value) {
249 if (!isObject(value)) return value;
250 if (Object.hasOwn(value, symbols.shadow)) return Object.getPrototypeOf(value);
251 const tracker = value[symbols.tracker];
252 if (!tracker) return value;
253 return createTraceable(ctx, value, tracker);
254 }
255 function withProps(target, props) {
256 if (!props) return target;
257 return new Proxy(target, {
258 get: (target2, prop, receiver) => {
259 if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver);
260 return Reflect.get(target2, prop, receiver);
261 },
262 set: (target2, prop, value, receiver) => {
263 if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver);
264 return Reflect.set(target2, prop, value, receiver);
265 }
266 });
267 }
268 function withProp(target, prop, value) {
269 return withProps(target, Object.defineProperty(/* @__PURE__ */ Object.create(null), prop, {
270 value,
271 writable: false
272 }));
273 }
274 function createShadow(ctx, target, property, receiver) {
275 if (!property) return receiver;
276 const origin = Reflect.getOwnPropertyDescriptor(target, property)?.value;
277 if (!origin) return receiver;
278 return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
279 }
280 function createShadowMethod(ctx, value, outer, shadow) {
281 return new Proxy(value, { apply: (target, thisArg, args) => {
282 if (thisArg === outer) thisArg = shadow;
283 return getTraceable(ctx, Reflect.apply(target, thisArg, args));
284 } });
285 }
286 function createTraceable(ctx, value, tracker) {
287 if (ctx[symbols.shadow] && !tracker.noShadow) ctx = Object.getPrototypeOf(ctx);
288 const proxy = new Proxy(value, {
289 get: (target, prop, receiver) => {
290 if (prop === symbols.original) return target;
291 if (prop === tracker.property) return ctx;
292 if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
293 if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
294 let shadow, innerValue;
295 const desc = getPropertyDescriptor(target, prop);
296 if (desc && "value" in desc) innerValue = desc.value;
297 else {
298 shadow = createShadow(ctx, target, tracker.property, receiver);
299 innerValue = Reflect.get(target, prop, shadow);
300 }
301 const innerTracker = innerValue?.[symbols.tracker];
302 if (innerTracker) return createTraceable(ctx, innerValue, innerTracker);
303 else if (!tracker.noShadow && typeof innerValue === "function") {
304 shadow ??= createShadow(ctx, target, tracker.property, receiver);
305 return createShadowMethod(ctx, innerValue, receiver, shadow);
306 } else return innerValue;
307 },
308 set: (target, prop, value2, receiver) => {
309 if (prop === symbols.original) return false;
310 if (prop === tracker.property) return false;
311 if (typeof prop === "symbol") return Reflect.set(target, prop, value2, receiver);
312 if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value2, withProp(ctx, symbols.receiver, receiver));
313 const shadow = createShadow(ctx, target, tracker.property, receiver);
314 return Reflect.set(target, prop, value2, shadow);
315 },
316 apply: (target, thisArg, args) => {
317 return applyTraceable(proxy, target, thisArg, args);
318 }
319 });
320 return proxy;
321 }
322 function applyTraceable(proxy, value, thisArg, args) {
323 if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args);
324 return value[symbols.invoke].apply(proxy, args);
325 }
326 function createCallable(name, proto, tracker) {
327 const self = function(...args) {
328 return applyTraceable(createTraceable(self["ctx"], self, tracker), self, this, args);
329 };
330 defineProperty(self, "name", name);
331 return Object.setPrototypeOf(self, proto);
332 }
333 function handleError(info, reason, getOuterStack) {
334 const innerLines = info.error.stack.split("\n");
335 if (typeof reason?.stack !== "string") {
336 const outerError = new Error(reason);
337 const lines2 = outerError.stack.split("\n");
338 lines2.splice(1, Infinity, ...getOuterStack());
339 outerError.stack = lines2.join("\n");
340 throw outerError;
341 }
342 const lines = reason.stack.split("\n");
343 let index = lines.indexOf(innerLines[2]);
344 if (index === -1) throw reason;
345 index -= info.offset;
346 while (index > 0) {
347 if (!lines[index - 1].endsWith(" (<anonymous>)")) break;
348 index -= 1;
349 }
350 lines.splice(index, Infinity, ...getOuterStack());
351 reason.stack = lines.join("\n");
352 throw reason;
353 }
354 function composeError(callback, getOuterStack = buildOuterStack()) {
355 const info = {
356 offset: 1,
357 error: /* @__PURE__ */ new Error()
358 };
359 try {
360 const result = callback(info);
361 if (isObject(result) && "then" in result) return result.then(void 0, (reason) => handleError(info, reason, getOuterStack));
362 else return result;
363 } catch (reason) {
364 handleError(info, reason, getOuterStack);
365 }
366 }
367 function buildOuterStack(offset2 = 0) {
368 const outerError = /* @__PURE__ */ new Error();
369 return () => outerError.stack.split("\n").slice(3 + offset2);
370 }
371 function isBailed(value) {
372 return value !== null && value !== false && value !== void 0;
373 }
374 function isAggregateError(error) {
375 return error instanceof Error && Array.isArray(error["errors"]);
376 }
377 function enhanceError(error) {
378 const lines = error.stack.split("\n");
379 lines.splice(0, 2, `Error: ${error.message}`);
380 error.stack = lines.join("\n");
381 return error;
382 }
383 function isSpecialProperty(prop) {
384 return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
385 }
386 function resolveConfig(runtime, config) {
387 if (!runtime.Config) return config;
388 const result = runtime.Config["~standard"].validate(config);
389 if ("then" in result) throw new TypeError("Async config validation is not supported");
390 if (result.issues) throw new ValidationError(result.issues);
391 else return result.value;
392 }
393 function runDisposable(dispose) {
394 const result = dispose();
395 return effectInertia.get(dispose)?.() ?? result;
396 }
397 function emitPluginDisposed(context, fiber) {
398 const args = ["internal/plugin", fiber];
399 let callbacks;
400 try {
401 callbacks = context.events.dispatch("emit", args);
402 } catch (error) {
403 context.logger.error(error);
404 return;
405 }
406 for (const callback of callbacks) try {
407 const returned = callback(...args);
408 Promise.resolve(returned).catch((error) => context.logger.error(error));
409 } catch (error) {
410 context.logger.error(error);
411 }
412 }
413 function isApplicable(object) {
414 return object && typeof object === "object" && typeof object.apply === "function";
415 }
416 function Inject(name, config) {
417 return function(value, decorator) {
418 if (decorator.kind === "class") {
419 if (!Object.hasOwn(value, "inject")) {
420 defineProperty(value, "inject", Object.create(Object.getPrototypeOf(value).inject ?? null));
421 defineProperty(value.inject, symbols.checkProto, true);
422 }
423 value.inject[name] = config;
424 } else if (decorator.kind === "method") {
425 const inject = (value[symbols.metadata] ??= {}).inject ??= /* @__PURE__ */ Object.create(null);
426 inject[name] = config;
427 decorator.addInitializer(function() {
428 const property = this[symbols.tracker]?.property;
429 (this[symbols.initHooks] ??= []).push(() => {
430 this.ctx.inject(inject, (ctx) => {
431 return value.call(property ? withProps(this, { [property]: ctx }) : this);
432 });
433 });
434 });
435 } else throw new Error("@Inject() can only be used on class or class methods");
436 };
437 }
438 var DisposableList, symbols, GeneratorFunction, AsyncGeneratorFunction, EventsService, defaultFormatters, Logger, c16, c256, LoggerService, RESERVED_WORDS, ReflectService, kValidationError, ValidationError, effectInertia, CordisError, INACTIVE, Fiber, RegistryService, Context, Service;
439 var init_lib2 = __esm({
440 "node_modules/@deepseek-ai/cordis/lib/index.js"() {
441 init_lib();
442 DisposableList = class {
443 sn = 0;
444 map = /* @__PURE__ */ new Map();
445 weak = /* @__PURE__ */ new WeakMap();
446 get length() {
447 return this.map.size;
448 }
449 push(value) {
450 const sn = ++this.sn;
451 this.map.set(sn, value);
452 this.weak.set(value, sn);
453 return () => this.map.delete(sn);
454 }
455 delete(value) {
456 const sn = this.weak.get(value);
457 if (!sn) return false;
458 return this.map.delete(sn);
459 }
460 clear() {
461 const values = [...this.map.values()];
462 this.map.clear();
463 return values.reverse();
464 }
465 [Symbol.iterator]() {
466 return this.map.values();
467 }
468 [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
469 return [...this];
470 }
471 };
472 symbols = {
473 shadow: /* @__PURE__ */ Symbol.for("cordis.shadow"),
474 receiver: /* @__PURE__ */ Symbol.for("cordis.receiver"),
475 original: /* @__PURE__ */ Symbol.for("cordis.original"),
476 metadata: /* @__PURE__ */ Symbol.for("cordis.metadata"),
477 initHooks: /* @__PURE__ */ Symbol.for("cordis.initHooks"),
478 checkProto: /* @__PURE__ */ Symbol.for("cordis.checkProto"),
479 effect: /* @__PURE__ */ Symbol.for("cordis.effect"),
480 filter: /* @__PURE__ */ Symbol.for("cordis.filter"),
481 isolate: /* @__PURE__ */ Symbol.for("cordis.isolate"),
482 intercept: /* @__PURE__ */ Symbol.for("cordis.intercept"),
483 init: /* @__PURE__ */ Symbol.for("cordis.init"),
484 check: /* @__PURE__ */ Symbol.for("cordis.check"),
485 config: /* @__PURE__ */ Symbol.for("cordis.config"),
486 invoke: /* @__PURE__ */ Symbol.for("cordis.invoke"),
487 extend: /* @__PURE__ */ Symbol.for("cordis.extend"),
488 tracker: /* @__PURE__ */ Symbol.for("cordis.tracker"),
489 resolveConfig: /* @__PURE__ */ Symbol.for("cordis.resolveConfig")
490 };
491 GeneratorFunction = function* () {
492 }.constructor;
493 AsyncGeneratorFunction = async function* () {
494 }.constructor;
495 EventsService = class {
496 ctx;
497 _hooks = {};
498 constructor(ctx) {
499 this.ctx = ctx;
500 defineProperty(this, symbols.tracker, {
501 property: "ctx",
502 noShadow: true
503 });
504 this.on("internal/listener", function(name, listener, options) {
505 if (name === "internal/update" && !options.global) return (this.fiber._hooks["internal/update"] ??= new DisposableList())[options.prepend ? "unshift" : "push"](listener);
506 });
507 this.on("internal/update", function(config, noSave, next) {
508 const cbs = [...this._hooks["internal/update"] || []];
509 const _next = () => {
510 return (cbs.shift() ?? next).call(this, config, noSave, _next);
511 };
512 return _next();
513 }, {
514 global: true,
515 prepend: true
516 });
517 }
518 /**
519 * Resolve listeners for one dispatch and apply context filtering.
520 *
521 * @param type — the dispatch mode, reported on `internal/dispatch`.
522 * @param args — the raw dispatch arguments; consumed up to the event name.
523 * @returns the matching listener callbacks, bound to the dispatch `this`.
524 */
525 dispatch(type2, args) {
526 const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
527 const name = args.shift();
528 if (!name.startsWith("internal/")) this.emit("internal/dispatch", type2, name, args, thisArg);
529 const filter = thisArg?.[Context.filter];
530 return (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback.bind(thisArg));
531 }
532 /**
533 * Run listeners concurrently and wait for all of them.
534 *
535 * @param args — optional `this`, the event name, then listener arguments.
536 * @returns a promise resolving once every listener has settled.
537 */
538 async parallel(...args) {
539 const errors = (await Promise.allSettled(this.dispatch("emit", args).map(async (cb) => cb(...args)))).filter((result) => result.status === "rejected");
540 if (errors.length) throw new AggregateError(errors.map((error) => error.reason));
541 }
542 /**
543 * Run listeners synchronously without waiting for returned promises.
544 *
545 * @param args — optional `this`, the event name, then listener arguments.
546 */
547 emit(...args) {
548 this.dispatch("emit", args).map((cb) => cb(...args));
549 }
550 /**
551 * Run listeners in order, awaiting each, until one returns a bail value.
552 *
553 * @param args — optional `this`, the event name, then listener arguments.
554 * @returns the first bail value (see {@link isBailed}), if any.
555 */
556 async serial(...args) {
557 for (const cb of this.dispatch("serial", args)) {
558 const result = await cb(...args);
559 if (isBailed(result)) return result;
560 }
561 }
562 /**
563 * Run listeners synchronously until one returns a bail value.
564 *
565 * @param args — optional `this`, the event name, then listener arguments.
566 * @returns the first bail value (see {@link isBailed}), if any.
567 */
568 bail(...args) {
569 for (const cb of this.dispatch("bail", args)) {
570 const result = cb(...args);
571 if (isBailed(result)) return result;
572 }
573 }
574 /**
575 * Compose listeners around the final `next` callback.
576 *
577 * The last dispatch argument is treated as the innermost `next`. Listeners
578 * run outermost-first; a listener that does not call `next()` vetoes the
579 * rest of the chain, including the built-in behavior.
580 *
581 * @param args — optional `this`, the event name, listener arguments, then `next`.
582 * @returns the outermost listener's return value.
583 */
584 waterfall(...args) {
585 const cbs = this.dispatch("waterfall", args);
586 const inner = args.pop();
587 const next = () => {
588 return (cbs.shift() ?? inner)(...args);
589 };
590 args.push(next);
591 return next();
592 }
593 /**
594 * Store a listener record as an effect on the current fiber.
595 *
596 * @param label — effect label shown in fiber diagnostics.
597 * @param hooks — the listener list for one event.
598 * @param callback — the listener to store.
599 * @param options — placement and filtering options.
600 * @returns a disposer that unregisters the listener.
601 */
602 register(label, hooks, callback, options) {
603 const method = options.prepend ? "unshift" : "push";
604 return this.ctx.fiber.effect(() => {
605 hooks[method]({
606 ctx: this.ctx,
607 callback,
608 ...options
609 });
610 return () => this.unregister(hooks, callback);
611 }, label);
612 }
613 /**
614 * Remove a stored listener record.
615 *
616 * @param hooks — the listener list for one event.
617 * @param callback — the listener to remove.
618 * @returns `true` if the listener was found and removed.
619 */
620 unregister(hooks, callback) {
621 const index = hooks.findIndex((hook) => hook.callback === callback);
622 if (index >= 0) {
623 hooks.splice(index, 1);
624 return true;
625 }
626 }
627 /**
628 * Register an event listener owned by the current fiber.
629 *
630 * The listener is removed automatically when the fiber unloads. Throws
631 * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
632 *
633 * @param name — the event name to listen for.
634 * @param listener — called with the dispatch arguments.
635 * @param options — listener options; a boolean is shorthand for `prepend`.
636 * @returns a disposer removing the listener; `true` if it was still registered.
637 */
638 on(name, listener, options) {
639 if (typeof options !== "object") options = { prepend: options };
640 this.ctx.fiber.assertActive();
641 listener = this.ctx.reflect.bind(listener);
642 const result = this.bail(this.ctx, "internal/listener", name, listener, options);
643 if (result) return result;
644 const hooks = this._hooks[name] ||= [];
645 const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
646 return this.register(label, hooks, listener, options);
647 }
648 /**
649 * Register an event listener that disposes itself after the first call.
650 *
651 * @param name — the event name to listen for.
652 * @param listener — called at most once with the dispatch arguments.
653 * @param options — listener options; a boolean is shorthand for `prepend`.
654 * @returns a disposer removing the listener; `true` if it was still registered.
655 */
656 once(name, listener, options) {
657 const dispose = this.on(name, function(...args) {
658 dispose();
659 return listener.apply(this, args);
660 }, options);
661 return dispose;
662 }
663 };
664 defaultFormatters = {
665 s: (value) => String(value),
666 d: (value) => Math.trunc(Number(value)),
667 i: (value) => Math.trunc(Number(value)),
668 f: (value) => Number(value),
669 o: (value) => JSON.stringify(value),
670 O: (value) => JSON.stringify(value),
671 c: () => "",
672 C: (value, exporter, message) => {
673 return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
674 }
675 };
676 Logger = class {
677 service;
678 static color(exporter, code, value, decoration = "") {
679 if (!exporter.colors) return "" + value;
680 return `\x1B[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\x1B[0m`;
681 }
682 static code(name, level) {
683 let hash2 = 0;
684 for (let i2 = 0; i2 < name.length; i2++) {
685 hash2 = (hash2 << 3) - hash2 + name.charCodeAt(i2) + 13;
686 hash2 |= 0;
687 }
688 const colors = !level ? [] : level >= 2 ? c256 : c16;
689 return colors[Math.abs(hash2) % colors.length];
690 }
691 static format(exporter, message) {
692 const args = message.args.slice();
693 if (args[0] instanceof Error) {
694 args[0] = args[0].stack || args[0].message;
695 args.unshift("%s");
696 } else if (typeof args[0] !== "string") args.unshift("%o");
697 let format = args.shift();
698 format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
699 if (match === "%%") return "%";
700 const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
701 if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
702 return match;
703 });
704 const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
705 for (let arg of args) {
706 if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
707 format += " " + arg;
708 }
709 const { maxLength = 10240 } = exporter;
710 return format.split(/\r?\n/g).map((line) => {
711 return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
712 }).join("\n");
713 }
714 constructor(options, service) {
715 this.service = service;
716 Object.assign(this, options);
717 this.error = this._method("error", 0);
718 this.info = this._method("info", 1);
719 this.warn = this._method("warn", 2);
720 this.debug = this._method("debug", 3);
721 }
722 _method(type2, level) {
723 return (...args) => {
724 if (args.length === 1 && args[0] instanceof Error) {
725 if (args[0].cause) this[type2](args[0].cause);
726 else if (isAggregateError(args[0])) {
727 args[0].errors.forEach((error) => this[type2](error));
728 return;
729 }
730 }
731 const sn = ++this.service._snMessage;
732 const ts = Date.now();
733 for (const exporter of this.service.exporters.values()) {
734 if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 1) < level) continue;
735 const message = {
736 sn,
737 ts,
738 type: type2,
739 level,
740 name: this.name,
741 ...this.meta,
742 args
743 };
744 exporter.export(message);
745 }
746 };
747 }
748 };
749 c16 = [
750 6,
751 2,
752 3,
753 4,
754 5,
755 1
756 ];
757 c256 = [
758 20,
759 21,
760 26,
761 27,
762 32,
763 33,
764 38,
765 39,
766 40,
767 41,
768 42,
769 43,
770 44,
771 45,
772 56,
773 57,
774 62,
775 63,
776 68,
777 69,
778 74,
779 75,
780 76,
781 77,
782 78,
783 79,
784 80,
785 81,
786 92,
787 93,
788 98,
789 99,
790 112,
791 113,
792 129,
793 134,
794 135,
795 148,
796 149,
797 160,
798 161,
799 162,
800 163,
801 164,
802 165,
803 166,
804 167,
805 168,
806 169,
807 170,
808 171,
809 172,
810 173,
811 178,
812 179,
813 184,
814 185,
815 196,
816 197,
817 198,
818 199,
819 200,
820 201,
821 202,
822 203,
823 204,
824 205,
825 206,
826 207,
827 208,
828 209,
829 214,
830 215,
831 220,
832 221
833 ];
834 LoggerService = class LoggerService2 {
835 bufferSize = 1e3;
836 buffer = [];
837 ctx;
838 _snMessage = 0;
839 _snExporter = 0;
840 exporters = /* @__PURE__ */ new Map();
841 constructor(ctx) {
842 const tracker = {
843 property: "ctx",
844 noShadow: true
845 };
846 const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
847 Object.assign(self, this);
848 self.ctx = ctx;
849 defineProperty(self, symbols.tracker, tracker);
850 self.exporter({
851 colors: 3,
852 export: (message) => {
853 self.buffer.push(message);
854 if (self.buffer.length > self.bufferSize) self.buffer = self.buffer.slice(-self.bufferSize);
855 }
856 });
857 return self;
858 }
859 /**
860 * Register an exporter and dispose it with the current fiber.
861 *
862 * @param exporter — the sink that receives structured log messages.
863 * @returns a disposer that removes the exporter.
864 */
865 exporter(exporter) {
866 return this.ctx.effect(() => {
867 const id = ++this._snExporter;
868 this.exporters.set(id, exporter);
869 return () => this.exporters.delete(id);
870 }, "ctx.logger.exporter()");
871 }
872 _resolveConfig() {
873 let intercept = this.ctx[symbols.intercept];
874 const configs = [];
875 while ("logger" in intercept) {
876 if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]);
877 intercept = Object.getPrototypeOf(intercept);
878 }
879 return Object.assign({}, ...configs);
880 }
881 [symbols.invoke](name) {
882 const config = this._resolveConfig();
883 const fiber = (this.ctx[symbols.shadow] ?? this.ctx).fiber;
884 name ??= config.name;
885 name ??= hyphenate(fiber.name);
886 return new Logger({
887 name,
888 level: config.level,
889 meta: { fiber: new WeakRef(fiber) }
890 }, this);
891 }
892 static {
893 for (const type2 of [
894 "error",
895 "info",
896 "warn",
897 "debug"
898 ]) LoggerService2.prototype[type2] = function(...args) {
899 return this()[type2](...args);
900 };
901 }
902 };
903 RESERVED_WORDS = ["prototype", "then"];
904 ReflectService = class {
905 ctx;
906 /** Proxy traps implementing service resolution for every context object. */
907 static handler = {
908 get: (target, prop, ctx) => {
909 if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx);
910 if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx));
911 const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`);
912 try {
913 const def = target.reflect.props[prop];
914 if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
915 if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
916 return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
917 const key = target[symbols.isolate][prop];
918 let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
919 while (true) {
920 const impl = fiber.store?.[prop];
921 if (impl) return getTraceable(ctx, impl.value);
922 if (prop in fiber.inject) {
923 error.message = `cannot get required service "${prop}" in inactive context`;
924 throw error;
925 }
926 if (!fiber.runtime) throw error;
927 if (fiber.parent[symbols.isolate][prop] !== key) throw error;
928 fiber = fiber.parent.fiber;
929 }
930 });
931 } catch (e) {
932 throw e === error ? enhanceError(e) : e;
933 }
934 },
935 set: (target, prop, value, ctx) => {
936 if (isSpecialProperty(prop)) return Reflect.set(target, prop, value, ctx);
937 const error = /* @__PURE__ */ new Error(`cannot set property "${prop}" without provide`);
938 const def = target.reflect.props[prop];
939 if (!def) {
940 if (!ctx.fiber.runtime) return Reflect.set(target, prop, value, ctx);
941 throw enhanceError(error);
942 }
943 try {
944 if (def.type === "accessor") {
945 if (!def.set) return false;
946 return def.set.call(ctx, value, ctx[symbols.receiver], error);
947 }
948 return ctx.events.waterfall("internal/set", ctx, prop, value, error, () => {
949 return ctx.reflect.set(prop, value, error);
950 });
951 } catch (e) {
952 throw e === error ? enhanceError(e) : e;
953 }
954 },
955 has: (target, prop) => {
956 if (isSpecialProperty(prop)) return Reflect.has(target, prop);
957 if (Reflect.has(target, prop)) return true;
958 return !!target.reflect.props[prop];
959 }
960 };
961 /** Service implementations, keyed by isolation label. */
962 store = /* @__PURE__ */ Object.create(null);
963 /** Declared context properties (services and accessors), by name. */
964 props = /* @__PURE__ */ Object.create(null);
965 constructor(ctx) {
966 this.ctx = ctx;
967 defineProperty(this, symbols.tracker, {
968 property: "ctx",
969 noShadow: true
970 });
971 this.mixin("reflect", [
972 "get",
973 "set",
974 "provide",
975 "accessor",
976 "mixin"
977 ]);
978 this.mixin("fiber", ["runtime", "effect"]);
979 this.mixin("registry", ["inject", "plugin"]);
980 this.mixin("events", [
981 "on",
982 "once",
983 "parallel",
984 "emit",
985 "serial",
986 "bail",
987 "waterfall"
988 ]);
989 }
990 /**
991 * Read a service from the store without the inject requirement.
992 *
993 * @param name — the service name.
994 * @param strict — when `true`, only return implementations whose providing
995 * fiber is currently active.
996 * @returns the service value, or `undefined` when not (yet) provided.
997 */
998 get(name, strict = true) {
999 return getTraceable(this.ctx, this._getImpl(name, strict)?.value);
1000 }
1001 _getImpl(name, strict = true) {
1002 const key = this.ctx[symbols.isolate][name];
1003 const impl = key && this.store[key];
1004 if (!impl) return;
1005 if (strict && impl.fiber.state !== 2) return;
1006 return impl;
1007 }
1008 /**
1009 * Overwrite a provided service's value.
1010 *
1011 * @param name — the service name.
1012 * @param value — the new service value.
1013 * @param error — carrier for the caller stack in diagnostics.
1014 * @returns `true` on success.
1015 * @throws when `name` was never provided, or was provided by another fiber.
1016 */
1017 set(name, value, error) {
1018 const key = this.ctx[symbols.isolate][name];
1019 const impl = this.store[key];
1020 if (!impl) throw new Error(`cannot set property "${name}" without provide`);
1021 if (impl.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`);
1022 impl.value = value;
1023 return true;
1024 }
1025 /**
1026 * Register a service implementation owned by the current fiber.
1027 *
1028 * See the `ctx.provide()` overload above for the full contract.
1029 *
1030 * @param name — the service name.
1031 * @param value — the service value.
1032 * @param check — optional availability predicate for dependents.
1033 * @returns a disposer that unregisters the service.
1034 */
1035 provide(name, value, check) {
1036 return this.ctx.fiber.effect(() => {
1037 if (!this.props[name]) this.props[name] ??= { type: "service" };
1038 else if (this.props[name].type !== "service") throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
1039 this.props[name] = { type: "service" };
1040 this.ctx.root[symbols.isolate][name] ??= Symbol(name);
1041 const key = this.ctx[symbols.isolate][name];
1042 const impl = {
1043 name,
1044 value,
1045 fiber: this.ctx.fiber,
1046 check
1047 };
1048 if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].fiber.name}>`);
1049 this.store[key] = impl;
1050 this.ctx.fiber.store[name] = impl;
1051 if (this.ctx.fiber.state === 2) this.notify([name]);
1052 return async () => {
1053 delete this.store[key];
1054 const fibers = this.notify([name]);
1055 await Promise.allSettled(fibers.map((fiber) => fiber.await()));
1056 delete this.ctx.fiber.store[name];
1057 };
1058 }, `ctx.provide(${JSON.stringify(name)})`);
1059 }
1060 /**
1061 * Re-evaluate every fiber that requires one of the given services.
1062 *
1063 * @param names — the service names that changed.
1064 * @param filter — restricts notification to matching isolation scopes.
1065 * @returns the fibers whose dependency state was refreshed.
1066 */
1067 notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) {
1068 const fibers = [];
1069 for (const runtime of this.ctx.registry.values()) for (const fiber of runtime.fibers) {
1070 let hasUpdate = false;
1071 for (const name of names) {
1072 if (!(name in fiber.inject)) continue;
1073 if (!filter(fiber.ctx, name)) continue;
1074 hasUpdate = true;
1075 fiber._checkImpl(name);
1076 }
1077 if (!hasUpdate) continue;
1078 fiber._refresh();
1079 fibers.push(fiber);
1080 }
1081 for (const name of names) {
1082 const self = Object.create(this.ctx);
1083 self[symbols.filter] = (target) => filter(target, name);
1084 this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value);
1085 }
1086 return fibers;
1087 }
1088 /**
1089 * Define a computed context property backed by get/set hooks.
1090 *
1091 * @param name — the context property name.
1092 * @param options — the `get` hook and optional `set` hook.
1093 * @returns a disposer that removes the accessor.
1094 */
1095 accessor(name, options) {
1096 return this.ctx.fiber.effect(() => {
1097 if (name in this.props) throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
1098 this.props[name] = {
1099 type: "accessor",
1100 ...options
1101 };
1102 return () => delete this.props[name];
1103 }, `ctx.accessor(${JSON.stringify(name)})`);
1104 }
1105 /**
1106 * Expose selected members of a service directly on `ctx`.
1107 *
1108 * See the `ctx.mixin()` overload above for the full contract.
1109 *
1110 * @param source — a context property name or a source object.
1111 * @param mixins — keys to forward, or a source-key → ctx-key map.
1112 * @returns a disposer that removes all created accessors.
1113 */
1114 mixin(source, mixins) {
1115 const self = this;
1116 return this.ctx.fiber.effect(function* () {
1117 const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins);
1118 const getTarget = (ctx, error) => {
1119 return ctx[source];
1120 };
1121 for (const [key, value] of entries) yield self.accessor(value, {
1122 get(receiver, error) {
1123 const service = getTarget(this, error);
1124 if (isNullable(service)) return service;
1125 const mixin = receiver ? withProps(receiver, service) : service;
1126 const value2 = Reflect.get(service, key, mixin);
1127 if (typeof value2 !== "function") return value2;
1128 return value2.bind(mixin ?? service);
1129 },
1130 set(value2, receiver, error) {
1131 const service = getTarget(this, error);
1132 const mixin = receiver ? withProps(receiver, service) : service;
1133 return Reflect.set(service, key, value2, mixin);
1134 }
1135 });
1136 }, `ctx.mixin(${JSON.stringify(source)})`);
1137 }
1138 /**
1139 * Attach this context's tracing wrapper to a value.
1140 *
1141 * @param value — the value to wrap.
1142 * @returns the traceable wrapper (or the value itself when not applicable).
1143 */
1144 trace(value) {
1145 return getTraceable(this.ctx, value);
1146 }
1147 /**
1148 * Wrap a callback so calls trace `this` and arguments to this context.
1149 *
1150 * @param callback — the function to wrap.
1151 * @returns a proxy delegating to `callback` with traced values.
1152 */
1153 bind(callback) {
1154 return new Proxy(callback, {
1155 apply: (target, thisArg, args) => {
1156 return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg)));
1157 },
1158 construct: (target, args, newTarget) => {
1159 return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget);
1160 }
1161 });
1162 }
1163 };
1164 kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
1165 ValidationError = class extends TypeError {
1166 name = "ValidationError";
1167 /**
1168 * Build the aggregated message from schema issues.
1169 *
1170 * @param issues — the standard-schema issues, one message line each.
1171 */
1172 constructor(issues) {
1173 super(`invalid config:
1174 ` + issues.map((issue) => {
1175 if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
1176 else return ` - ${issue.message}`;
1177 }).join("\n"));
1178 }
1179 };
1180 Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
1181 effectInertia = /* @__PURE__ */ new WeakMap();
1182 CordisError = class CordisError2 extends Error {
1183 code;
1184 /**
1185 * @param code — the stable error code; also the default message.
1186 * @param message — optional human-readable override.
1187 */
1188 constructor(code, message) {
1189 super(message ?? CordisError2.Code[code]);
1190 this.code = code;
1191 }
1192 };
1193 (function(CordisError3) {
1194 CordisError3.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" };
1195 })(CordisError || (CordisError = {}));
1196 INACTIVE = "__INACTIVE__";
1197 Fiber = class {
1198 parent;
1199 inject;
1200 runtime;
1201 /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */
1202 uid;
1203 /** The context this fiber's plugin runs in (extends the parent context). */
1204 ctx;
1205 /** The validated plugin config (updated by `update()`). */
1206 config;
1207 /** The raw plugin config, re-resolved before each activation. */
1208 _config;
1209 /** Current lifecycle state; transitions emit `internal/status`. */
1210 state = 0;
1211 /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */
1212 dispose;
1213 /** Snapshot of required service implementations while loaded; `undefined` otherwise. */
1214 store;
1215 /** The in-flight load/unload transition, if one is currently running. */
1216 inertia;
1217 _hooks = /* @__PURE__ */ Object.create(null);
1218 _disposables = new DisposableList();
1219 context;
1220 _error;
1221 _runner;
1222 _store = /* @__PURE__ */ Object.create(null);
1223 /**
1224 * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()`
1225 * rather than constructing them directly.
1226 *
1227 * @param parent — the context the plugin was loaded from.
1228 * @param config — raw config, validated against the runtime's schema.
1229 * @param inject — resolved dependency map (service name → intercept config).
1230 * @param runtime — the shared plugin runtime, or `null` for the root fiber.
1231 * @param getOuterStack — captures the caller stack for effect diagnostics.
1232 */
1233 constructor(parent, config, inject, runtime, getOuterStack) {
1234 this.parent = parent;
1235 this.inject = inject;
1236 this.runtime = runtime;
1237 this._config = config;
1238 const collect = (dispose) => {
1239 this._disposables.push(dispose);
1240 };
1241 if (runtime) {
1242 this.uid = parent.registry.counter;
1243 this.ctx = this.context = parent.extend({ fiber: this });
1244 const injectEntries = Object.entries(this.inject);
1245 if (injectEntries.length) {
1246 this.ctx[Context.intercept] = Object.create(parent[Context.intercept]);
1247 for (const [name, config2] of injectEntries) {
1248 if (isNullable(config2)) continue;
1249 this.ctx[Context.intercept][name] = config2;
1250 }
1251 }
1252 this._runner = {
1253 epoch: INACTIVE,
1254 getOuterStack,
1255 execute: function() {
1256 if (isConstructor(runtime.callback)) {
1257 const instance = new runtime.callback(this.ctx, this.config);
1258 for (const hook of instance?.[symbols.initHooks] ?? []) hook();
1259 return instance?.[symbols.init]?.();
1260 } else return runtime.callback(this.ctx, this.config);
1261 },
1262 collect
1263 };
1264 this.dispose = parent.fiber.effect(() => {
1265 const remove = runtime.fibers.push(this);
1266 return async () => {
1267 this.uid = null;
1268 emitPluginDisposed(this.context, this);
1269 if (this.ctx.registry.has(runtime.callback)) {
1270 remove();
1271 if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback);
1272 }
1273 this._setEpoch(INACTIVE);
1274 if (!this.inertia) this._updateState(() => {
1275 this.inertia = this._unload();
1276 return 5;
1277 });
1278 while (this.inertia) await this.inertia;
1279 };
1280 }, "ctx.plugin()");
1281 try {
1282 this.context.emit("internal/plugin", this);
1283 } catch (error) {
1284 Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason));
1285 throw error;
1286 }
1287 if (this.uid !== null && parent.fiber.state !== 5) {
1288 for (const name of Object.keys(this.inject)) this._checkImpl(name);
1289 this._refresh();
1290 }
1291 } else {
1292 this.uid = 0;
1293 this.ctx = this.context = parent;
1294 this.state = 2;
1295 this.store = /* @__PURE__ */ Object.create(null);
1296 this._runner = {
1297 epoch: "",
1298 getOuterStack,
1299 execute: () => {
1300 },
1301 collect
1302 };
1303 this.dispose = () => this.restart();
1304 }
1305 }
1306 /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */
1307 get name() {
1308 let fiber = this;
1309 do {
1310 if (fiber.runtime?.name) return fiber.runtime.name;
1311 fiber = fiber.parent.fiber;
1312 } while (fiber !== fiber.parent.fiber);
1313 return "root";
1314 }
1315 /**
1316 * Throw if the fiber has already been disposed.
1317 *
1318 * @returns nothing when the fiber is still active.
1319 * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared.
1320 */
1321 assertActive() {
1322 if (this.uid !== null) return;
1323 throw new CordisError("INACTIVE_EFFECT");
1324 }
1325 _execute(runner) {
1326 const oldEpoch = runner.epoch;
1327 return composeError((info) => {
1328 const safeCollect = (dispose) => {
1329 if (typeof dispose === "function") runner.collect(dispose);
1330 else if (!isNullable(dispose)) throw new TypeError("Invalid effect");
1331 };
1332 const effect = runner.execute.call(this);
1333 if (typeof effect === "function") return runner.collect(effect);
1334 else if (isNullable(effect)) {
1335 } else if (!isObject(effect)) throw new TypeError("Invalid effect");
1336 else if ("then" in effect) return effect.then(safeCollect);
1337 else if (Symbol.iterator in effect) {
1338 info.error = /* @__PURE__ */ new Error();
1339 const iter = effect[Symbol.iterator]();
1340 while (true) {
1341 const result = iter.next();
1342 safeCollect(result.value);
1343 if (result.done) return;
1344 }
1345 } else if (Symbol.asyncIterator in effect) {
1346 const iter = effect[Symbol.asyncIterator]();
1347 return (async () => {
1348 await Promise.resolve();
1349 info.error = /* @__PURE__ */ new Error();
1350 while (true) {
1351 if (runner.epoch !== oldEpoch) return;
1352 const result = await iter.next();
1353 safeCollect(result.value);
1354 if (result.done) return;
1355 }
1356 })();
1357 } else throw new TypeError("Invalid effect");
1358 }, runner.getOuterStack);
1359 }
1360 effect(execute, label = "anonymous") {
1361 this.assertActive();
1362 if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
1363 const disposables = [];
1364 let disposing = false;
1365 let disposalTask;
1366 const dispose = () => {
1367 if (disposing) return disposalTask;
1368 disposing = true;
1369 let task2;
1370 for (const disposable of disposables.splice(0).reverse()) if (task2) task2 = task2.then(() => runDisposable(disposable));
1371 else {
1372 const result = runDisposable(disposable);
1373 if (isObject(result) && "then" in result) task2 = result;
1374 }
1375 return disposalTask = task2;
1376 };
1377 const meta = {
1378 label,
1379 children: []
1380 };
1381 const runner = {
1382 execute,
1383 epoch: true,
1384 collect: (dispose2) => {
1385 disposables.push(dispose2);
1386 this._disposables.delete(dispose2);
1387 if (dispose2[symbols.effect]) meta.children.push(dispose2[symbols.effect]);
1388 },
1389 getOuterStack: buildOuterStack()
1390 };
1391 let task;
1392 let executing = true;
1393 let resolveSetup;
1394 let rejectSetup;
1395 let setupBarrier;
1396 let setupFailed = false;
1397 let inFlight;
1398 let removeWrapper = () => false;
1399 const waitForSetup = () => {
1400 setupBarrier ??= new Promise((resolve6, reject) => {
1401 resolveSetup = resolve6;
1402 rejectSetup = reject;
1403 });
1404 return setupBarrier;
1405 };
1406 const disposeAfter = (setup) => {
1407 return Promise.resolve(setup).then(() => dispose(), async (reason) => {
1408 await dispose();
1409 throw reason;
1410 });
1411 };
1412 const finalizeDisposal = (callback) => {
1413 let result;
1414 try {
1415 result = callback();
1416 } catch (error) {
1417 removeWrapper();
1418 throw error;
1419 }
1420 if (isObject(result) && "then" in result) {
1421 const pending = Promise.resolve(result).finally(() => {
1422 removeWrapper();
1423 if (inFlight === pending) inFlight = void 0;
1424 });
1425 return inFlight = pending;
1426 }
1427 removeWrapper();
1428 return result;
1429 };
1430 const wrapper = defineProperty(() => {
1431 if (!runner.epoch) return setupFailed ? inFlight : void 0;
1432 runner.epoch = false;
1433 return finalizeDisposal(() => {
1434 if (executing) return disposeAfter(waitForSetup());
1435 return task ? disposeAfter(task) : dispose();
1436 });
1437 }, symbols.effect, meta);
1438 effectInertia.set(wrapper, () => inFlight);
1439 removeWrapper = this._disposables.push(wrapper);
1440 try {
1441 task = this._execute(runner);
1442 } catch (reason) {
1443 executing = false;
1444 setupFailed = true;
1445 runner.epoch = false;
1446 let cleanup;
1447 try {
1448 cleanup = finalizeDisposal(dispose);
1449 } finally {
1450 rejectSetup?.(reason);
1451 }
1452 if (isObject(cleanup) && "then" in cleanup) cleanup.catch((error) => this.ctx.logger.error(error));
1453 throw reason;
1454 }
1455 executing = false;
1456 if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup);
1457 task?.catch(() => {
1458 if (!runner.epoch) return dispose();
1459 return finalizeDisposal(dispose);
1460 }).catch((error) => this.ctx.logger.error(error));
1461 const disposeAsync = () => {
1462 if (!runner.epoch) return;
1463 runner.epoch = false;
1464 return finalizeDisposal(dispose);
1465 };
1466 wrapper.then = async (onFulfilled, onRejected) => {
1467 return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
1468 };
1469 return wrapper;
1470 }
1471 /**
1472 * Return metadata for currently registered effects.
1473 *
1474 * @returns one {@link EffectMeta} tree per labeled live effect.
1475 */
1476 getEffects() {
1477 return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
1478 }
1479 _getState() {
1480 if (this.uid === null) return 4;
1481 if (this._error) return 3;
1482 if (this._runner.epoch !== INACTIVE) return 2;
1483 return 0;
1484 }
1485 _updateState(callback) {
1486 const oldState = this.state;
1487 this.state = callback() ?? this._getState();
1488 if (oldState === this.state) return;
1489 this.context.emit("internal/status", this, oldState);
1490 if (oldState !== 2 && this.state !== 2) return;
1491 for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
1492 const impl = this.ctx.reflect.store[key];
1493 if (impl.fiber !== this) continue;
1494 this.ctx.reflect.notify([impl.name]);
1495 }
1496 }
1497 _checkImpl(name) {
1498 const impl = this.ctx.reflect._getImpl(name, true);
1499 if (!impl) return delete this._store[name];
1500 try {
1501 if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name];
1502 } catch (error) {
1503 impl.fiber.ctx.logger.error(error);
1504 return delete this._store[name];
1505 }
1506 this._store[name] = impl;
1507 }
1508 _refresh() {
1509 let epoch = false;
1510 epoch = "";
1511 for (const name of Object.keys(this.inject)) {
1512 const impl = this._store[name];
1513 if (!impl) {
1514 epoch = INACTIVE;
1515 break;
1516 }
1517 epoch += ":" + impl.fiber.uid;
1518 }
1519 this._setEpoch(epoch);
1520 }
1521 _setEpoch(epoch) {
1522 const oldEpoch = this._runner.epoch;
1523 if (epoch === oldEpoch) return;
1524 this._runner.epoch = epoch;
1525 if (this.inertia) return;
1526 this._updateState(() => {
1527 if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
1528 this.inertia = this._reload();
1529 return 1;
1530 } else {
1531 this.inertia = this._unload();
1532 return 5;
1533 }
1534 });
1535 }
1536 _resolveConfig(config) {
1537 config = this.context.waterfall(this, "internal/config", config, () => config);
1538 return this.runtime ? resolveConfig(this.runtime, config) : config;
1539 }
1540 async _reload() {
1541 this.store = { ...this._store };
1542 const oldEpoch = this._runner.epoch;
1543 try {
1544 await Promise.resolve();
1545 if (this._runner.epoch === oldEpoch) {
1546 this.config = this._resolveConfig(this._config);
1547 await this._execute(this._runner);
1548 this._error = void 0;
1549 }
1550 } catch (reason) {
1551 this.ctx.logger.error(reason);
1552 this._error = reason;
1553 this._runner.epoch = INACTIVE;
1554 }
1555 this._updateState(() => {
1556 if (this._runner.epoch === oldEpoch) this.inertia = void 0;
1557 else {
1558 this.inertia = this._unload();
1559 return 5;
1560 }
1561 });
1562 }
1563 async _unload() {
1564 await Promise.all(this._disposables.clear().map(async (dispose) => {
1565 try {
1566 await composeError(async (info) => {
1567 await Promise.resolve();
1568 info.error = /* @__PURE__ */ new Error();
1569 await runDisposable(dispose);
1570 }, this._runner.getOuterStack);
1571 } catch (reason) {
1572 this.ctx.logger.error(reason);
1573 }
1574 }));
1575 this.store = void 0;
1576 this._updateState(() => {
1577 if (this._runner.epoch === INACTIVE) this.inertia = void 0;
1578 else {
1579 this.inertia = this._reload();
1580 return 1;
1581 }
1582 });
1583 }
1584 /**
1585 * Wait for current lifecycle work and rethrow startup errors.
1586 *
1587 * @returns this fiber, once it has settled into a stable state.
1588 * @throws the config-validation or plugin-startup error, if any.
1589 */
1590 async await() {
1591 while (this.inertia) await this.inertia;
1592 if (this._error) throw this._error;
1593 return this;
1594 }
1595 /**
1596 * Dispose and immediately reload this plugin with its current config.
1597 *
1598 * @returns a promise resolving once the reload settled.
1599 * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
1600 */
1601 async restart() {
1602 this.assertActive();
1603 this._setEpoch(INACTIVE);
1604 this._refresh();
1605 await this.await();
1606 }
1607 /**
1608 * Validate and apply new config, then restart the plugin.
1609 *
1610 * Runs the `internal/update` waterfall first, so update hooks (and HMR)
1611 * can veto or replace the restart.
1612 *
1613 * @param config — the new raw config; validated before anything restarts.
1614 * @param noSave — hint for persistence hooks not to write the change back.
1615 * @returns nothing; the restart runs behind the `internal/update` waterfall.
1616 * @throws {ValidationError} when the new config fails validation.
1617 */
1618 update(config, noSave = false) {
1619 this.assertActive();
1620 this._config = config;
1621 if (this.state !== 2) {
1622 this._error = void 0;
1623 this._setEpoch(INACTIVE);
1624 this._refresh();
1625 return;
1626 }
1627 config = this._resolveConfig(config);
1628 this.context.waterfall(this, "internal/update", config, noSave, () => {
1629 this.config = config;
1630 this._error = void 0;
1631 return this.restart();
1632 });
1633 }
1634 };
1635 (function(Inject2) {
1636 function resolve6(inject, result = /* @__PURE__ */ Object.create(null)) {
1637 if (!inject) return result;
1638 if (Array.isArray(inject)) for (const name of inject) result[name] = null;
1639 else if (Reflect.has(inject, symbols.checkProto)) {
1640 Object.assign(result, resolve6(Object.getPrototypeOf(inject)));
1641 for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
1642 } else for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
1643 return result;
1644 }
1645 Inject2.resolve = resolve6;
1646 })(Inject || (Inject = {}));
1647 RegistryService = class {
1648 ctx;
1649 _counter = 0;
1650 _internal = /* @__PURE__ */ new Map();
1651 constructor(ctx) {
1652 this.ctx = ctx;
1653 defineProperty(this, symbols.tracker, {
1654 property: "ctx",
1655 noShadow: true
1656 });
1657 }
1658 /** Allocate the next fiber uid (increments on every read). */
1659 get counter() {
1660 return ++this._counter;
1661 }
1662 /** Number of registered plugin runtimes. */
1663 get size() {
1664 return this._internal.size;
1665 }
1666 /**
1667 * Resolve a supported plugin shape to its executable callback.
1668 *
1669 * @param plugin — a function, class, or `{ apply }` object plugin.
1670 * @returns the callback identifying the plugin, or `undefined` if invalid.
1671 */
1672 resolve(plugin) {
1673 try {
1674 if (typeof plugin === "function") return plugin;
1675 if (isApplicable(plugin)) return plugin.apply;
1676 } catch {
1677 }
1678 }
1679 /**
1680 * Look up the runtime record for a plugin.
1681 *
1682 * @param plugin — any supported plugin shape.
1683 * @returns the runtime, or `undefined` when the plugin is not registered.
1684 */
1685 get(plugin) {
1686 const key = this.resolve(plugin);
1687 return key && this._internal.get(key);
1688 }
1689 /**
1690 * Check whether a plugin has a registered runtime.
1691 *
1692 * @param plugin — any supported plugin shape.
1693 * @returns `true` when at least one fiber of the plugin exists.
1694 */
1695 has(plugin) {
1696 const key = this.resolve(plugin);
1697 return !!key && this._internal.has(key);
1698 }
1699 /**
1700 * Dispose every running fiber for a plugin and remove its runtime record.
1701 *
1702 * @param plugin — any supported plugin shape.
1703 * @returns the removed runtime, or `undefined` when none was registered.
1704 */
1705 delete(plugin) {
1706 const key = this.resolve(plugin);
1707 const runtime = key && this._internal.get(key);
1708 if (!runtime) return;
1709 this._internal.delete(key);
1710 for (const fiber of runtime.fibers) fiber.dispose();
1711 return runtime;
1712 }
1713 /** Iterate the registered plugin callbacks. */
1714 keys() {
1715 return this._internal.keys();
1716 }
1717 /** Iterate the registered plugin runtimes. */
1718 values() {
1719 return this._internal.values();
1720 }
1721 /** Iterate `[callback, runtime]` pairs. */
1722 entries() {
1723 return this._internal.entries();
1724 }
1725 /**
1726 * Visit every registered runtime.
1727 *
1728 * @param callback — receives each runtime and its identifying callback.
1729 */
1730 forEach(callback) {
1731 return this._internal.forEach(callback);
1732 }
1733 /**
1734 * Start a callback once the requested dependencies are available.
1735 *
1736 * @param inject — required services, as an array or a name → config map.
1737 * @param callback — plugin body called with `(ctx, config)`.
1738 * @returns the fiber; awaiting it settles once loading finished.
1739 */
1740 inject(inject, callback) {
1741 return this.plugin({
1742 inject,
1743 apply: callback,
1744 name: callback.name
1745 });
1746 }
1747 /**
1748 * Start a plugin in the current context and return its fiber.
1749 *
1750 * Creates (or reuses) the plugin's runtime record, then starts a new fiber
1751 * under the current context. Throws if `plugin` is not a supported shape or
1752 * if the current fiber is already disposed.
1753 *
1754 * @param plugin — a function, class, or `{ apply }` object plugin.
1755 * @param config — the plugin config, validated against its `Config` schema.
1756 * @param getOuterStack — captures the caller stack for effect diagnostics.
1757 * @returns the fiber; awaiting it settles once loading finished.
1758 */
1759 plugin(plugin, config, getOuterStack = buildOuterStack()) {
1760 const callback = this.resolve(plugin);
1761 if (!callback) throw new Error('invalid plugin, expect function or object with an "apply" method, received ' + typeof plugin);
1762 this.ctx.fiber.assertActive();
1763 let runtime = this._internal.get(callback);
1764 if (!runtime) {
1765 let name = plugin.name;
1766 if (name === "apply") name = void 0;
1767 runtime = {
1768 name,
1769 callback,
1770 fibers: new DisposableList(),
1771 Config: plugin.Config
1772 };
1773 this._internal.set(callback, runtime);
1774 }
1775 const fiber = new Fiber(this.ctx, config, Inject.resolve(plugin.inject), runtime, getOuterStack);
1776 const wrapped = Object.create(fiber);
1777 wrapped.then = (onFulfilled, onRejected) => {
1778 return fiber.await().then(onFulfilled, onRejected);
1779 };
1780 return wrapped;
1781 }
1782 };
1783 Context = class Context2 {
1784 /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */
1785 static effect = symbols.effect;
1786 /** Symbol key for a context's listener filter, consulted on every event dispatch. */
1787 static filter = symbols.filter;
1788 /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */
1789 static isolate = symbols.isolate;
1790 /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */
1791 static intercept = symbols.intercept;
1792 /**
1793 * Returns true for Cordis context proxies and context prototypes.
1794 *
1795 * Works across realms and across multiple copies of cordis, because the
1796 * brand is keyed by a global symbol rather than by `instanceof`.
1797 *
1798 * @param value — the value to test.
1799 * @returns `true` if `value` is a Cordis context, narrowing its type.
1800 */
1801 static is(value) {
1802 return !!value?.[Context2.is];
1803 }
1804 static {
1805 Context2.is[Symbol.toPrimitive] = () => /* @__PURE__ */ Symbol.for("cordis.is");
1806 Context2.prototype[Context2.is] = true;
1807 }
1808 /** Create the root context and install the built-in services. */
1809 constructor() {
1810 this[symbols.isolate] = /* @__PURE__ */ Object.create(null);
1811 this[symbols.intercept] = /* @__PURE__ */ Object.create(null);
1812 const self = new Proxy(this, ReflectService.handler);
1813 this.root = self;
1814 this.baseUrl = void 0;
1815 this.fiber = new Fiber(self, {}, /* @__PURE__ */ Object.create(null), null, () => []);
1816 this.reflect = new ReflectService(self);
1817 this.registry = new RegistryService(self);
1818 this.events = new EventsService(self);
1819 this.logger = new LoggerService(self);
1820 this.fiber._disposables.clear();
1821 return self;
1822 }
1823 [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1824 return `Context <${this.fiber.name}>`;
1825 }
1826 /**
1827 * Create a child context with extra metadata on top of the current scope.
1828 *
1829 * The child prototypally inherits every property of this context; own
1830 * properties of `meta` shadow the inherited ones. The parent is not mutated.
1831 *
1832 * @param meta — own properties (including symbol keys) to define on the child.
1833 * @returns a child context inheriting from this one.
1834 */
1835 extend(meta = {}) {
1836 const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value;
1837 const self = Object.create(getTraceable(this, this));
1838 for (const prop of Reflect.ownKeys(meta)) Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta, prop));
1839 if (!shadow) return self;
1840 return Object.assign(Object.create(self), { [symbols.shadow]: shadow });
1841 }
1842 /**
1843 * Create a child context with an independent service scope for `name`.
1844 *
1845 * Below the returned context, reads and writes of the service `name`
1846 * resolve against the new label instead of the parent's, so a different
1847 * implementation can be provided without affecting the parent scope.
1848 * Passing the same `label` to two `isolate()` calls joins their scopes.
1849 *
1850 * @param name — the service name to isolate.
1851 * @param label — scope label to join; defaults to a fresh unique symbol.
1852 * @returns a child context whose `name` service resolves in the new scope.
1853 */
1854 isolate(name, label) {
1855 const shadow = Object.create(this[symbols.isolate]);
1856 shadow[name] = label ?? Symbol(name);
1857 return this.extend({ [symbols.isolate]: shadow });
1858 }
1859 intercept(name, config) {
1860 const intercept = Object.create(this[symbols.intercept]);
1861 intercept[name] = config;
1862 return this.extend({ [symbols.intercept]: intercept });
1863 }
1864 };
1865 Service = class Service2 {
1866 ctx;
1867 /** Symbol key of an instance method run after construction (class plugins). */
1868 static init = symbols.init;
1869 /** Symbol key of the availability predicate passed to `ctx.provide()`. */
1870 static check = symbols.check;
1871 /** Symbol key of the phantom intercept-config type parameter. */
1872 static config = symbols.config;
1873 /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
1874 static invoke = symbols.invoke;
1875 /** Symbol key of the helper deriving an extended service instance. */
1876 static extend = symbols.extend;
1877 /** Symbol key of the tracker metadata used for context tracing. */
1878 static tracker = symbols.tracker;
1879 /** Symbol key of the intercept-config resolution helper below. */
1880 static resolveConfig = symbols.resolveConfig;
1881 /** The service name this instance is registered under. */
1882 name;
1883 /**
1884 * Register this instance as `name` in the current context.
1885 *
1886 * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the
1887 * service is unregistered automatically when the owning fiber unloads.
1888 * Services with a `[Service.invoke]` body return a callable instance.
1889 *
1890 * @param ctx — the context to register in (stored as `this.ctx`).
1891 * @param name — the service name; defaults to the static `provide` field.
1892 */
1893 constructor(ctx, name) {
1894 this.ctx = ctx;
1895 name ??= this.constructor["provide"];
1896 let self = this;
1897 const tracker = {
1898 associate: name,
1899 property: "ctx"
1900 };
1901 if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
1902 self.ctx = ctx;
1903 self.name = name;
1904 defineProperty(self, symbols.tracker, tracker);
1905 self.ctx.reflect.provide(name, self, this[symbols.check]);
1906 return self;
1907 }
1908 [symbols.filter](ctx) {
1909 return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
1910 }
1911 [symbols.extend](props) {
1912 let self;
1913 if (this[Service2.invoke]) self = createCallable(this.name, this, this[symbols.tracker]);
1914 else self = Object.create(this);
1915 return Object.assign(self, props);
1916 }
1917 /**
1918 * Merge intercept config from ancestors with optional base and head values.
1919 *
1920 * Entries added closer to the root apply first; `base` is prepended and
1921 * `head` appended. Uses `Config.merge` when the service declares one,
1922 * otherwise a shallow `Object.assign`.
1923 *
1924 * @param base — lowest-precedence config merged before all intercepts.
1925 * @param head — highest-precedence config merged after all intercepts.
1926 * @returns the merged config.
1927 */
1928 [symbols.resolveConfig](base, head) {
1929 let intercept = this.ctx[Context.intercept];
1930 const configs = [];
1931 while (this.name in intercept) {
1932 if (Object.hasOwn(intercept, this.name)) configs.unshift(intercept[this.name]);
1933 intercept = Object.getPrototypeOf(intercept);
1934 }
1935 if (base) configs.unshift(base);
1936 if (head) configs.push(head);
1937 if (this["Config"]?.merge) return this["Config"].merge(...configs);
1938 else return Object.assign({}, ...configs);
1939 }
1940 static [Symbol.hasInstance](instance) {
1941 if (!instance) return false;
1942 let constructor = instance.constructor;
1943 while (constructor) {
1944 constructor = constructor.prototype?.constructor;
1945 if (constructor === this) return true;
1946 constructor &&= Object.getPrototypeOf(constructor);
1947 }
1948 return false;
1949 }
1950 };
1951 }
1952 });
1953
1954 // src/shims/owned.ts
1955 var init_owned = __esm({
1956 "src/shims/owned.ts"() {
1957 "use strict";
1958 }
1959 });
1960
1961 // src/shims/prompt.ts
1962 function normalizePromptSection(value) {
1963 if (typeof value !== "object" || value === null || Array.isArray(value)) {
1964 throw new TypeError("prompt section must be an object with id and text");
1965 }
1966 if (Object.keys(value).some((key) => key !== "id" && key !== "text" && key !== "interpolate")) {
1967 throw new TypeError("prompt section supports only id and text, plus optional model-cwd interpolation");
1968 }
1969 const { id, text: text2, interpolate: interpolate2 } = value;
1970 if (typeof id !== "string" || !SECTION_ID.test(id)) {
1971 throw new TypeError("prompt section id must be lower case, start with a letter, and use a-z, 0-9, _ or - (at most 64 characters)");
1972 }
1973 if (typeof text2 !== "string" || text2.trim().length === 0) {
1974 throw new TypeError(`prompt section "${id}" needs non-empty text`);
1975 }
1976 if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(text2)) {
1977 throw new TypeError(`prompt section "${id}" text contains control characters`);
1978 }
1979 if (Buffer.byteLength(text2, "utf8") > MAX_PROMPT_SECTION_BYTES) {
1980 throw new RangeError(`prompt section "${id}" exceeds ${MAX_PROMPT_SECTION_BYTES} UTF-8 bytes`);
1981 }
1982 if (interpolate2 !== void 0 && interpolate2 !== "model-cwd") throw new TypeError("prompt interpolation supports only model-cwd");
1983 if (interpolate2 !== void 0) validatePromptTemplate(text2);
1984 return Object.freeze({ id, text: text2, ...interpolate2 === void 0 ? {} : { interpolate: interpolate2 } });
1985 }
1986 function validatePromptTemplate(text2) {
1987 for (let open = text2.indexOf("{{"); open >= 0; ) {
1988 const group = /^\{\{([^{}]*)\}\}/u.exec(text2.slice(open));
1989 if (!group) {
1990 if (text2.indexOf("}}", open + 2) >= 0) throw new TypeError("malformed prompt variable reference");
1991 open = text2.indexOf("{{", open + 2);
1992 continue;
1993 }
1994 if (!/^[a-z][a-z0-9_]*$/u.test(group[1])) throw new TypeError("malformed prompt variable reference");
1995 if (group[1] !== "model" && group[1] !== "cwd") throw new TypeError(`unknown Core prompt variable "{{${group[1]}}}"; supported variables: model, cwd`);
1996 open = text2.indexOf("{{", open + group[0].length);
1997 }
1998 }
1999 var MAX_PROMPT_SECTION_BYTES, MAX_PROMPT_OWNER_BYTES, MAX_PROMPT_HOST_BYTES, SECTION_ID;
2000 var init_prompt = __esm({
2001 "src/shims/prompt.ts"() {
2002 "use strict";
2003 init_owned();
2004 MAX_PROMPT_SECTION_BYTES = 4 * 1024;
2005 MAX_PROMPT_OWNER_BYTES = 32 * 1024;
2006 MAX_PROMPT_HOST_BYTES = 128 * 1024;
2007 SECTION_ID = /^[a-z][a-z0-9_-]{0,63}$/u;
2008 }
2009 });
2010
2011 // src/dsh/fiber-state.ts
2012 var FiberState;
2013 var init_fiber_state = __esm({
2014 "src/dsh/fiber-state.ts"() {
2015 "use strict";
2016 FiberState = {
2017 PENDING: 0,
2018 LOADING: 1,
2019 ACTIVE: 2,
2020 FAILED: 3,
2021 DISPOSED: 4,
2022 UNLOADING: 5
2023 };
2024 }
2025 });
2026
2027 // src/dsh/upstream/loader/src/config/group.ts
2028 var EntryGroup, Group;
2029 var init_group = __esm({
2030 "src/dsh/upstream/loader/src/config/group.ts"() {
2031 "use strict";
2032 init_lib2();
2033 init_entry();
2034 EntryGroup = class {
2035 constructor(ctx, tree) {
2036 this.ctx = ctx;
2037 this.tree = tree;
2038 const entry = ctx.fiber.entry;
2039 if (entry) entry.subgroup = this;
2040 }
2041 ctx;
2042 tree;
2043 static key = /* @__PURE__ */ Symbol.for("cordis.group");
2044 data = [];
2045 get context() {
2046 return this.ctx;
2047 }
2048 async create(options) {
2049 const id = this.tree.ensureId(options);
2050 const entry = this.tree.store[id] ??= new Entry(this.ctx.loader);
2051 entry.parent = this;
2052 await entry.update(options, true, true);
2053 return entry.id;
2054 }
2055 unlink(options) {
2056 const config = this.data;
2057 const index = config.indexOf(options);
2058 if (index >= 0) config.splice(index, 1);
2059 }
2060 remove(id, isDispose = false) {
2061 const entry = this.tree.store[id];
2062 if (!entry) return;
2063 entry.fiber?.dispose();
2064 if (!isDispose) {
2065 this.unlink(entry.options);
2066 }
2067 delete this.tree.store[id];
2068 this.context.emit("loader/partial-dispose", entry, entry.options, false);
2069 }
2070 async update(config) {
2071 const oldConfig = this.data;
2072 this.data = config;
2073 const oldMap = Object.fromEntries(oldConfig.map((options) => [options.id, options]));
2074 const newMap = Object.fromEntries(config.map((options) => [options.id ?? /* @__PURE__ */ Symbol("anonymous"), options]));
2075 const ids = Reflect.ownKeys({ ...oldMap, ...newMap });
2076 await Promise.all(ids.map(async (id) => {
2077 if (newMap[id]) {
2078 await this.create(newMap[id]).catch((error) => {
2079 this.ctx.logger.error(error);
2080 });
2081 } else {
2082 this.remove(id);
2083 }
2084 }));
2085 }
2086 stop() {
2087 for (const options of this.data) {
2088 this.remove(options.id, true);
2089 }
2090 }
2091 };
2092 Group = class extends EntryGroup {
2093 constructor(ctx, config) {
2094 super(ctx, ctx.fiber.entry.parent.tree);
2095 this.ctx = ctx;
2096 this.config = config;
2097 ctx.on("internal/update", (config2) => {
2098 this.update(config2);
2099 });
2100 }
2101 ctx;
2102 config;
2103 static initial = [];
2104 static [EntryGroup.key] = true;
2105 async *[Service.init]() {
2106 yield () => this.stop();
2107 await this.update(this.config);
2108 }
2109 };
2110 }
2111 });
2112
2113 // src/dsh/upstream/loader/src/config/tree.ts
2114 var EntryTree;
2115 var init_tree = __esm({
2116 "src/dsh/upstream/loader/src/config/tree.ts"() {
2117 "use strict";
2118 init_lib2();
2119 init_lib();
2120 init_group();
2121 EntryTree = class _EntryTree {
2122 static sep = ":";
2123 ctx;
2124 enableLogs;
2125 root;
2126 store = /* @__PURE__ */ Object.create(null);
2127 constructor(ctx) {
2128 this.ctx = ctx.extend({ baseUrl: ctx.baseUrl });
2129 this.root = new EntryGroup(this.ctx, this);
2130 const entry = this.ctx.fiber.entry;
2131 if (entry) entry.subtree = this;
2132 }
2133 get context() {
2134 return this.ctx;
2135 }
2136 /** Iterate entries in this tree and any nested subtrees. */
2137 *entries() {
2138 for (const entry of Object.values(this.store)) {
2139 yield entry;
2140 if (!entry.subtree) continue;
2141 yield* entry.subtree.entries();
2142 }
2143 }
2144 /** Return pending import and lifecycle tasks owned by this tree. */
2145 getTasks() {
2146 return [...this.entries()].map((entry) => entry._initTask || entry.fiber?.inertia).filter(isNonNullable);
2147 }
2148 /** Wait until this tree has no pending import or lifecycle tasks. */
2149 async await() {
2150 while (true) {
2151 const tasks = this.getTasks();
2152 if (!tasks.length) return;
2153 await Promise.allSettled(tasks);
2154 }
2155 }
2156 ensureId(options) {
2157 if (!options.id) {
2158 do {
2159 options.id = Math.random().toString(16).slice(2, 10);
2160 } while (this.store[options.id]);
2161 }
2162 return options.id;
2163 }
2164 /** Resolve an entry by id, including nested ids separated by `EntryTree.sep`. */
2165 resolve(id) {
2166 const parts = id.split(_EntryTree.sep);
2167 let tree = this;
2168 const final = parts.pop();
2169 for (const part of parts) {
2170 tree = tree.store[part]?.subtree;
2171 if (!tree) throw new Error(`cannot resolve entry ${id}`);
2172 }
2173 const entry = tree.store[final];
2174 if (!entry) throw new Error(`cannot resolve entry ${id}`);
2175 return entry;
2176 }
2177 resolveGroup(id) {
2178 if (!id) return this.root;
2179 const entry = this.resolve(id);
2180 if (!entry.subgroup) throw new Error(`entry ${id} is not a group`);
2181 return entry.subgroup;
2182 }
2183 /** Create an entry in the root group or a nested group. */
2184 async create(options, parent = null, position = Infinity) {
2185 const group = this.resolveGroup(parent);
2186 group.data.splice(position, 0, options);
2187 group.tree.write();
2188 return group.create(options);
2189 }
2190 /** Stop and remove an entry from its parent group. */
2191 remove(id) {
2192 const entry = this.resolve(id);
2193 entry.parent.remove(id);
2194 entry.parent.tree.write();
2195 }
2196 /** Update an entry and optionally move it to another group. */
2197 async update(id, options, parent, position) {
2198 const entry = this.resolve(id);
2199 const source = entry.parent;
2200 if (parent !== void 0) {
2201 const target = this.resolveGroup(parent);
2202 source.unlink(entry.options);
2203 target.data.splice(position ?? Infinity, 0, entry.options);
2204 target.tree.write();
2205 entry.parent = target;
2206 }
2207 source.tree.write();
2208 return entry.update(options, false, true);
2209 }
2210 /** Import a plugin module from a specifier or `cordis:` builtin. */
2211 import(name, getOuterStack) {
2212 if (name.startsWith("cordis:")) {
2213 return this.ctx.loader.builtins[name.slice(7)];
2214 }
2215 return composeError(async (info) => {
2216 info.offset += 3;
2217 if (this.ctx.loader.internal) {
2218 return await this.ctx.loader.internal.import(name, this.ctx.baseUrl, {});
2219 } else if (name.startsWith(".")) {
2220 return await import(
2221 /* @vite-ignore */
2222 new URL(name, this.ctx.baseUrl).href
2223 );
2224 } else {
2225 return await import(
2226 /* @vite-ignore */
2227 name
2228 );
2229 }
2230 }, getOuterStack);
2231 }
2232 };
2233 }
2234 });
2235
2236 // src/dsh/upstream/loader/src/config/utils.ts
2237 function interpolate(ctx, value) {
2238 if (isJsExpr(value)) {
2239 return evaluate(ctx, value.__jsExpr);
2240 } else if (!value || typeof value !== "object") {
2241 return value;
2242 } else if (Array.isArray(value)) {
2243 return value.map((item) => interpolate(ctx, item));
2244 } else {
2245 return mapValues(value, (item) => interpolate(ctx, item));
2246 }
2247 }
2248 function isJsExpr(value) {
2249 return value instanceof Object && "__jsExpr" in value;
2250 }
2251 var evaluate;
2252 var init_utils = __esm({
2253 "src/dsh/upstream/loader/src/config/utils.ts"() {
2254 "use strict";
2255 init_lib();
2256 evaluate = new Function("ctx", "expr", `
2257 with (ctx) {
2258 return eval(expr)
2259 }
2260 `);
2261 }
2262 });
2263
2264 // src/dsh/upstream/loader/src/config/entry.ts
2265 function takeEntries(object, keys) {
2266 const indexed = object;
2267 const result = [];
2268 for (const key of keys) {
2269 if (!(key in object)) continue;
2270 result.push([key, indexed[key]]);
2271 delete indexed[key];
2272 }
2273 return result;
2274 }
2275 function sortKeys(object, prepend = ["id", "name"], append = ["config"]) {
2276 const part1 = takeEntries(object, prepend);
2277 const part2 = takeEntries(object, append);
2278 const rest = takeEntries(object, Object.keys(object)).sort(([a], [b]) => a.localeCompare(b));
2279 return Object.assign(object, Object.fromEntries([...part1, ...rest, ...part2]));
2280 }
2281 var Entry;
2282 var init_entry = __esm({
2283 "src/dsh/upstream/loader/src/config/entry.ts"() {
2284 "use strict";
2285 init_lib();
2286 init_tree();
2287 init_utils();
2288 Entry = class _Entry {
2289 constructor(loader2) {
2290 this.loader = loader2;
2291 this.ctx = loader2.ctx.extend({ [_Entry.key]: this });
2292 this.context.emit("loader/entry-init", this);
2293 }
2294 loader;
2295 static key = /* @__PURE__ */ Symbol.for("cordis.entry");
2296 ctx;
2297 fiber;
2298 parent;
2299 // safety: call `entry.update()` immediately after creating an entry
2300 options = {};
2301 subgroup;
2302 subtree;
2303 _initTask;
2304 get context() {
2305 return this.ctx;
2306 }
2307 get id() {
2308 let id = this.options.id;
2309 if (this.parent.tree.ctx.fiber.entry) {
2310 id = this.parent.tree.ctx.fiber.entry.id + EntryTree.sep + id;
2311 }
2312 return id;
2313 }
2314 /** True when this entry or any owning parent entry is disabled. */
2315 get disabled() {
2316 if (this.options.group) return false;
2317 let entry = this;
2318 do {
2319 if (this.disabledOf(entry.options)) return true;
2320 entry = entry.parent.ctx.fiber.entry;
2321 } while (entry);
2322 return false;
2323 }
2324 /**
2325 * Effective disabled state: a `!!js` expression evaluates against the loader
2326 * context. The raw node stays in the options, so write-back keeps the form.
2327 */
2328 disabledOf(options) {
2329 return isJsExpr(options.disabled) ? Boolean(this.evaluate(options.disabled.__jsExpr)) : Boolean(options.disabled);
2330 }
2331 evaluate(expr) {
2332 return evaluate(this.ctx, expr);
2333 }
2334 _patchContext(diff) {
2335 this.context.waterfall("loader/patch-context", this, () => {
2336 Object.setPrototypeOf(this.ctx, this.parent.ctx);
2337 if (this.fiber?.uid && (diff.includes("config") || this.options.group)) {
2338 this.fiber.update(this.options.config, true);
2339 }
2340 });
2341 }
2342 async refresh() {
2343 if (this.fiber) return;
2344 if (this.disabled) return;
2345 await this.init();
2346 }
2347 /** Merge new options, restart as needed, and persist through the parent tree. */
2348 async update(options, create = false, force = false) {
2349 const legacy = { ...this.options };
2350 if (create) {
2351 this.options = options;
2352 } else {
2353 for (const [key, value] of Object.entries(options)) {
2354 if (isNullable(value)) {
2355 delete this.options[key];
2356 } else {
2357 this.options[key] = value;
2358 }
2359 }
2360 }
2361 sortKeys(this.options);
2362 if (this.disabled) {
2363 this.fiber?.dispose();
2364 return;
2365 }
2366 if (this.fiber?.uid) {
2367 const diff = Object.keys({ ...this.options, ...legacy }).filter((key) => !deepEqual(
2368 this.options[key],
2369 legacy[key]
2370 ));
2371 if (!diff.length && !force) return;
2372 this.context.emit("loader/partial-dispose", this, legacy, true);
2373 this._patchContext(diff);
2374 } else {
2375 await this.init();
2376 }
2377 }
2378 getOuterStack = () => {
2379 let entry = this;
2380 const result = [];
2381 do {
2382 result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`);
2383 entry = entry.parent.ctx.fiber.entry;
2384 } while (entry);
2385 return result;
2386 };
2387 /** Import and start the configured plugin if it is not already running. */
2388 async init() {
2389 try {
2390 await (this._initTask ??= this._init());
2391 } finally {
2392 this._initTask = void 0;
2393 }
2394 const notify = () => {
2395 if (this.loader.getTasks().length) return;
2396 this.ctx.reflect.notify(["loader"]);
2397 };
2398 this.fiber?.await().then(notify, notify);
2399 }
2400 async _init() {
2401 let exports;
2402 try {
2403 exports = await this.parent.tree.import(this.options.name, this.getOuterStack);
2404 } catch (error) {
2405 this.ctx.logger.error(error);
2406 return;
2407 } finally {
2408 this._initTask = void 0;
2409 }
2410 const plugin = this.loader.unwrapExports(exports);
2411 this._patchContext([]);
2412 this.loader.showLog(this, "apply");
2413 this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack);
2414 }
2415 };
2416 }
2417 });
2418
2419 // src/dsh/upstream/loader/src/config/isolate.ts
2420 function swap(target, source) {
2421 for (const key of Reflect.ownKeys(target)) {
2422 Reflect.deleteProperty(target, key);
2423 }
2424 for (const key of Reflect.ownKeys(source || {})) {
2425 Reflect.defineProperty(target, key, Reflect.getOwnPropertyDescriptor(source, key));
2426 }
2427 }
2428 function isolate(ctx) {
2429 const realms = /* @__PURE__ */ Object.create(null);
2430 const delims = /* @__PURE__ */ Object.create(null);
2431 function access2(entry, name, create = false) {
2432 let realm;
2433 const label = entry.options.isolate?.[name];
2434 if (!label) return;
2435 if (label === true) {
2436 realm = entry.realm ??= new LocalRealm(entry);
2437 } else if (create) {
2438 realm = realms[label] ??= new GlobalRealm(label);
2439 } else {
2440 realm = realms[label];
2441 }
2442 return realm?.access(name, create);
2443 }
2444 ctx.on("loader/entry-init", (entry) => {
2445 entry.ctx[Context.intercept] = Object.create(entry.ctx[Context.intercept]);
2446 entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate]);
2447 });
2448 ctx.on("loader/patch-context", (entry, next) => {
2449 const newMap = Object.create(entry.parent.ctx[Context.isolate]);
2450 for (const name of Object.keys(entry.options.isolate ?? {})) {
2451 newMap[name] = access2(entry, name, true);
2452 }
2453 const diff = /* @__PURE__ */ Object.create(null);
2454 const oldMap = entry.ctx[Context.isolate];
2455 for (const name in { ...newMap, ...delims }) {
2456 if (newMap[name] === oldMap[name]) continue;
2457 const delim = delims[name] ??= /* @__PURE__ */ Symbol(`delim:${name}`);
2458 entry.ctx[delim] = /* @__PURE__ */ Symbol(`${name}#${entry.id}`);
2459 for (const symbol of [oldMap[name], newMap[name]]) {
2460 const impl = symbol && entry.ctx.reflect.store[symbol];
2461 if (!impl) continue;
2462 if (!impl.fiber) {
2463 entry.ctx.logger.warn(new Error(`expected service ${name} to be implemented`));
2464 continue;
2465 }
2466 diff[name] = [oldMap[name], newMap[name], entry.ctx[delim], impl.fiber.ctx[delim]];
2467 if (entry.ctx[delim] !== impl.fiber.ctx[delim]) break;
2468 }
2469 }
2470 Object.setPrototypeOf(entry.ctx[Context.isolate], entry.parent.ctx[Context.isolate]);
2471 Object.setPrototypeOf(entry.ctx[Context.intercept], entry.parent.ctx[Context.intercept]);
2472 swap(entry.ctx[Context.isolate], newMap);
2473 swap(entry.ctx[Context.intercept], entry.options.intercept);
2474 next();
2475 for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) {
2476 if (flag1 === flag2 && entry.ctx.reflect.store[symbol1] && !entry.ctx.reflect.store[symbol2]) {
2477 entry.ctx.reflect.store[symbol2] = entry.ctx.reflect.store[symbol1];
2478 delete entry.ctx.reflect.store[symbol1];
2479 }
2480 }
2481 ctx.reflect.notify(Object.keys(diff), (ctx2, name) => {
2482 const [symbol1, symbol2, flag1, flag2] = diff[name];
2483 const symbol3 = ctx2[Context.isolate][name];
2484 const flag3 = ctx2[delims[name]];
2485 return (symbol1 === symbol3 || symbol2 === symbol3) && flag1 === flag3 !== (flag1 === flag2);
2486 });
2487 for (const name in delims) {
2488 if (!Reflect.ownKeys(newMap).includes(name)) {
2489 delete entry.ctx[delims[name]];
2490 }
2491 }
2492 });
2493 ctx.on("loader/partial-dispose", (entry, legacy, active) => {
2494 for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
2495 if (label === true) continue;
2496 if (active && entry.options.isolate?.[name] === label) continue;
2497 const realm = realms[label];
2498 if (!realm) continue;
2499 for (const entry2 of ctx.loader.entries()) {
2500 if (entry2.options.isolate?.[name] === realm.label) return;
2501 }
2502 realm.delete(name);
2503 if (!realm.size) {
2504 delete realms[realm.label];
2505 }
2506 }
2507 });
2508 }
2509 var Realm, LocalRealm, GlobalRealm;
2510 var init_isolate = __esm({
2511 "src/dsh/upstream/loader/src/config/isolate.ts"() {
2512 "use strict";
2513 init_lib2();
2514 Realm = class {
2515 store = /* @__PURE__ */ Object.create(null);
2516 access(key, create = false) {
2517 if (create) {
2518 return this.store[key] ??= /* @__PURE__ */ Symbol(`${key}${this.suffix}`);
2519 } else {
2520 return this.store[key] ?? /* @__PURE__ */ Symbol(`${key}${this.suffix}`);
2521 }
2522 }
2523 delete(key) {
2524 delete this.store[key];
2525 }
2526 get size() {
2527 return Object.keys(this.store).length;
2528 }
2529 };
2530 LocalRealm = class extends Realm {
2531 constructor(entry) {
2532 super();
2533 this.entry = entry;
2534 }
2535 entry;
2536 get suffix() {
2537 return "#" + this.entry.options.id;
2538 }
2539 };
2540 GlobalRealm = class extends Realm {
2541 constructor(label) {
2542 super();
2543 this.label = label;
2544 }
2545 label;
2546 get suffix() {
2547 return "@" + this.label;
2548 }
2549 };
2550 }
2551 });
2552
2553 // src/dsh/upstream/loader/src/internal.ts
2554 import { createRequire } from "node:module";
2555 var ModuleLoader;
2556 var init_internal = __esm({
2557 "src/dsh/upstream/loader/src/internal.ts"() {
2558 "use strict";
2559 ((ModuleLoader2) => {
2560 let _cachedLoader;
2561 function requireInternal(id) {
2562 const require3 = createRequire(import.meta.url);
2563 if (process.execArgv.includes("--expose-internals")) {
2564 try {
2565 return require3(id);
2566 } catch {
2567 }
2568 }
2569 try {
2570 return require3("node-addon-require-builtin").requireBuiltin(id);
2571 } catch {
2572 }
2573 }
2574 function fromInternal() {
2575 if (_cachedLoader) return _cachedLoader;
2576 const [major] = process.versions.node.split(".").map(Number);
2577 if (major < 22) return;
2578 const raw = requireInternal("internal/modules/esm/loader")?.getOrInitializeCascadedLoader();
2579 if (!raw) return;
2580 const version2 = typeof raw.getOrCreateModuleJob === "function" ? "v2" : typeof raw.getModuleJobForImport === "function" ? "v1" : void 0;
2581 if (!version2) return;
2582 return _cachedLoader = Object.assign(raw, { version: version2 });
2583 }
2584 ModuleLoader2.fromInternal = fromInternal;
2585 })(ModuleLoader || (ModuleLoader = {}));
2586 }
2587 });
2588
2589 // src/dsh/upstream/loader/src/index.ts
2590 var Loader;
2591 var init_src = __esm({
2592 "src/dsh/upstream/loader/src/index.ts"() {
2593 "use strict";
2594 init_lib2();
2595 init_lib();
2596 init_entry();
2597 init_group();
2598 init_isolate();
2599 init_tree();
2600 init_utils();
2601 init_fiber_state();
2602 init_entry();
2603 init_group();
2604 init_isolate();
2605 init_tree();
2606 init_utils();
2607 init_internal();
2608 Loader = class extends EntryTree {
2609 constructor(ctx, config = {}) {
2610 super(ctx);
2611 this.config = config;
2612 if (config.baseUrl) {
2613 this.ctx.baseUrl = config.baseUrl;
2614 }
2615 const self = this;
2616 defineProperty(this, Service.tracker, {
2617 associate: "loader",
2618 property: "ctx",
2619 noShadow: true
2620 });
2621 ctx.reflect.provide("loader", this, this[Service.check]);
2622 ctx.on("internal/config", function(_config, next) {
2623 const config2 = next();
2624 if (!this.entry || this.parent.fiber?.entry === this.entry) return config2;
2625 const plugin = this.runtime?.callback;
2626 if (plugin?.[EntryGroup.key]) return config2;
2627 return interpolate(this.ctx, config2);
2628 }, { global: true });
2629 ctx.on("internal/update", function(config2, noSave, next) {
2630 if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next();
2631 const unparse = this.runtime?.Config?.simplify;
2632 this.entry.options.config = unparse ? unparse(config2) : config2;
2633 this.entry.parent.tree.write();
2634 return next();
2635 }, { global: true, prepend: true });
2636 ctx.on("internal/update", function(config2, _, next) {
2637 if (!this.entry || this.parent.fiber?.entry === this.entry) return next();
2638 self.showLog(this.entry, "reload");
2639 return next();
2640 }, { global: true });
2641 ctx.on("internal/plugin", (fiber) => {
2642 if (fiber.parent[Entry.key] && !fiber.entry) {
2643 fiber.entry = fiber.parent[Entry.key];
2644 Inject.resolve(fiber.entry.options.inject, fiber.inject);
2645 }
2646 if (fiber.uid) return;
2647 if (!fiber.entry) return;
2648 if (fiber.parent.fiber?.entry === fiber.entry) return;
2649 if (!ctx.registry.has(fiber.runtime.callback)) return;
2650 const treeOwner = fiber.entry.parent.tree.ctx.fiber;
2651 if (!treeOwner.uid || treeOwner.state === FiberState.UNLOADING) return;
2652 this.showLog(fiber.entry, "unload");
2653 if (fiber.entry.disabled) return;
2654 fiber.entry.options.disabled = true;
2655 fiber.entry.parent.tree.write();
2656 });
2657 ctx.plugin(isolate);
2658 }
2659 config;
2660 envData = process.env.CORDIS_SHARED ? JSON.parse(process.env.CORDIS_SHARED) : { startTime: Date.now() };
2661 name = "loader";
2662 // Codewhale host delta: native internals/addon probing is unavailable.
2663 // EntryTree retains upstream's documented native ESM fallback.
2664 internal = void 0;
2665 builtins = /* @__PURE__ */ Object.create(null);
2666 write() {
2667 }
2668 [Service.check]() {
2669 const config = Service.prototype[Service.resolveConfig].call(this);
2670 if (config.await && this.getTasks().length) return false;
2671 return true;
2672 }
2673 showLog(entry, type2) {
2674 if (entry.options.group || !entry.parent.tree.enableLogs) return;
2675 this.ctx.root.logger?.("loader").info("%s plugin %C", type2, entry.options.name);
2676 }
2677 /** Return the loader entry id that owns `fiber`, if any. */
2678 locate(fiber = this.ctx.fiber) {
2679 while (1) {
2680 if (fiber.entry) return fiber.entry.id;
2681 const next = fiber.parent.fiber;
2682 if (fiber === next) return;
2683 fiber = next;
2684 }
2685 }
2686 /** Hook for hosts that can restart the process on full-reload requests. */
2687 exit() {
2688 }
2689 /** Normalize ESM/CJS/default export shapes before applying a plugin. */
2690 unwrapExports(exports) {
2691 if (isNullable(exports)) return exports;
2692 exports = exports.default ?? exports;
2693 if (!exports.__esModule) return exports;
2694 return exports.default ?? exports;
2695 }
2696 };
2697 }
2698 });
2699
2700 // node_modules/js-yaml/dist/js-yaml.mjs
2701 function getDefaultExportFromCjs(x) {
2702 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
2703 }
2704 function requireCommon() {
2705 if (hasRequiredCommon) return common;
2706 hasRequiredCommon = 1;
2707 function isNothing(subject) {
2708 return typeof subject === "undefined" || subject === null;
2709 }
2710 function isObject2(subject) {
2711 return typeof subject === "object" && subject !== null;
2712 }
2713 function toArray(sequence) {
2714 if (Array.isArray(sequence)) return sequence;
2715 else if (isNothing(sequence)) return [];
2716 return [sequence];
2717 }
2718 function extend2(target, source) {
2719 if (source) {
2720 const sourceKeys = Object.keys(source);
2721 for (let index = 0, length = sourceKeys.length; index < length; index += 1) {
2722 const key = sourceKeys[index];
2723 target[key] = source[key];
2724 }
2725 }
2726 return target;
2727 }
2728 function repeat(string, count) {
2729 let result = "";
2730 for (let cycle = 0; cycle < count; cycle += 1) {
2731 result += string;
2732 }
2733 return result;
2734 }
2735 function isNegativeZero(number) {
2736 return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
2737 }
2738 common.isNothing = isNothing;
2739 common.isObject = isObject2;
2740 common.toArray = toArray;
2741 common.repeat = repeat;
2742 common.isNegativeZero = isNegativeZero;
2743 common.extend = extend2;
2744 return common;
2745 }
2746 function requireException() {
2747 if (hasRequiredException) return exception;
2748 hasRequiredException = 1;
2749 function formatError(exception2, compact) {
2750 let where = "";
2751 const message = exception2.reason || "(unknown reason)";
2752 if (!exception2.mark) return message;
2753 if (exception2.mark.name) {
2754 where += 'in "' + exception2.mark.name + '" ';
2755 }
2756 where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")";
2757 if (!compact && exception2.mark.snippet) {
2758 where += "\n\n" + exception2.mark.snippet;
2759 }
2760 return message + " " + where;
2761 }
2762 function YAMLException2(reason, mark) {
2763 Error.call(this);
2764 this.name = "YAMLException";
2765 this.reason = reason;
2766 this.mark = mark;
2767 this.message = formatError(this, false);
2768 if (Error.captureStackTrace) {
2769 Error.captureStackTrace(this, this.constructor);
2770 } else {
2771 this.stack = new Error().stack || "";
2772 }
2773 }
2774 YAMLException2.prototype = Object.create(Error.prototype);
2775 YAMLException2.prototype.constructor = YAMLException2;
2776 YAMLException2.prototype.toString = function toString2(compact) {
2777 return this.name + ": " + formatError(this, compact);
2778 };
2779 exception = YAMLException2;
2780 return exception;
2781 }
2782 function requireSnippet() {
2783 if (hasRequiredSnippet) return snippet;
2784 hasRequiredSnippet = 1;
2785 const common2 = requireCommon();
2786 function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
2787 let head = "";
2788 let tail = "";
2789 const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
2790 if (position - lineStart > maxHalfLength) {
2791 head = " ... ";
2792 lineStart = position - maxHalfLength + head.length;
2793 }
2794 if (lineEnd - position > maxHalfLength) {
2795 tail = " ...";
2796 lineEnd = position + maxHalfLength - tail.length;
2797 }
2798 return {
2799 str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail,
2800 pos: position - lineStart + head.length
2801 // relative position
2802 };
2803 }
2804 function padStart(string, max) {
2805 return common2.repeat(" ", max - string.length) + string;
2806 }
2807 function makeSnippet(mark, options) {
2808 options = Object.create(options || null);
2809 if (!mark.buffer) return null;
2810 if (!options.maxLength) options.maxLength = 79;
2811 if (typeof options.indent !== "number") options.indent = 1;
2812 if (typeof options.linesBefore !== "number") options.linesBefore = 3;
2813 if (typeof options.linesAfter !== "number") options.linesAfter = 2;
2814 const re = /\r?\n|\r|\0/g;
2815 const lineStarts = [0];
2816 const lineEnds = [];
2817 let match;
2818 let foundLineNo = -1;
2819 while (match = re.exec(mark.buffer)) {
2820 lineEnds.push(match.index);
2821 lineStarts.push(match.index + match[0].length);
2822 if (mark.position <= match.index && foundLineNo < 0) {
2823 foundLineNo = lineStarts.length - 2;
2824 }
2825 }
2826 if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
2827 let result = "";
2828 const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
2829 const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
2830 for (let i2 = 1; i2 <= options.linesBefore; i2++) {
2831 if (foundLineNo - i2 < 0) break;
2832 const line2 = getLine(
2833 mark.buffer,
2834 lineStarts[foundLineNo - i2],
2835 lineEnds[foundLineNo - i2],
2836 mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i2]),
2837 maxLineLength
2838 );
2839 result = common2.repeat(" ", options.indent) + padStart((mark.line - i2 + 1).toString(), lineNoLength) + " | " + line2.str + "\n" + result;
2840 }
2841 const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
2842 result += common2.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
2843 result += common2.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
2844 for (let i2 = 1; i2 <= options.linesAfter; i2++) {
2845 if (foundLineNo + i2 >= lineEnds.length) break;
2846 const line2 = getLine(
2847 mark.buffer,
2848 lineStarts[foundLineNo + i2],
2849 lineEnds[foundLineNo + i2],
2850 mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i2]),
2851 maxLineLength
2852 );
2853 result += common2.repeat(" ", options.indent) + padStart((mark.line + i2 + 1).toString(), lineNoLength) + " | " + line2.str + "\n";
2854 }
2855 return result.replace(/\n$/, "");
2856 }
2857 snippet = makeSnippet;
2858 return snippet;
2859 }
2860 function requireType() {
2861 if (hasRequiredType) return type;
2862 hasRequiredType = 1;
2863 const YAMLException2 = requireException();
2864 const TYPE_CONSTRUCTOR_OPTIONS = [
2865 "kind",
2866 "multi",
2867 "resolve",
2868 "construct",
2869 "instanceOf",
2870 "predicate",
2871 "represent",
2872 "representName",
2873 "defaultStyle",
2874 "styleAliases"
2875 ];
2876 const YAML_NODE_KINDS = [
2877 "scalar",
2878 "sequence",
2879 "mapping"
2880 ];
2881 function compileStyleAliases(map2) {
2882 const result = {};
2883 if (map2 !== null) {
2884 Object.keys(map2).forEach(function(style) {
2885 map2[style].forEach(function(alias) {
2886 result[String(alias)] = style;
2887 });
2888 });
2889 }
2890 return result;
2891 }
2892 function Type2(tag, options) {
2893 options = options || {};
2894 Object.keys(options).forEach(function(name) {
2895 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
2896 throw new YAMLException2('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
2897 }
2898 });
2899 this.options = options;
2900 this.tag = tag;
2901 this.kind = options["kind"] || null;
2902 this.resolve = options["resolve"] || function() {
2903 return true;
2904 };
2905 this.construct = options["construct"] || function(data2) {
2906 return data2;
2907 };
2908 this.instanceOf = options["instanceOf"] || null;
2909 this.predicate = options["predicate"] || null;
2910 this.represent = options["represent"] || null;
2911 this.representName = options["representName"] || null;
2912 this.defaultStyle = options["defaultStyle"] || null;
2913 this.multi = options["multi"] || false;
2914 this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
2915 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
2916 throw new YAMLException2('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
2917 }
2918 }
2919 type = Type2;
2920 return type;
2921 }
2922 function requireSchema() {
2923 if (hasRequiredSchema) return schema;
2924 hasRequiredSchema = 1;
2925 const YAMLException2 = requireException();
2926 const Type2 = requireType();
2927 function compileList(schema22, name) {
2928 const result = [];
2929 schema22[name].forEach(function(currentType) {
2930 let newIndex = result.length;
2931 result.forEach(function(previousType, previousIndex) {
2932 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
2933 newIndex = previousIndex;
2934 }
2935 });
2936 result[newIndex] = currentType;
2937 });
2938 return result;
2939 }
2940 function compileMap() {
2941 const result = {
2942 scalar: {},
2943 sequence: {},
2944 mapping: {},
2945 fallback: {},
2946 multi: {
2947 scalar: [],
2948 sequence: [],
2949 mapping: [],
2950 fallback: []
2951 }
2952 };
2953 function collectType(type2) {
2954 if (type2.multi) {
2955 result.multi[type2.kind].push(type2);
2956 result.multi["fallback"].push(type2);
2957 } else {
2958 result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
2959 }
2960 }
2961 for (let index = 0, length = arguments.length; index < length; index += 1) {
2962 arguments[index].forEach(collectType);
2963 }
2964 return result;
2965 }
2966 function Schema2(definition) {
2967 return this.extend(definition);
2968 }
2969 Schema2.prototype.extend = function extend2(definition) {
2970 let implicit = [];
2971 let explicit = [];
2972 if (definition instanceof Type2) {
2973 explicit.push(definition);
2974 } else if (Array.isArray(definition)) {
2975 explicit = explicit.concat(definition);
2976 } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
2977 if (definition.implicit) implicit = implicit.concat(definition.implicit);
2978 if (definition.explicit) explicit = explicit.concat(definition.explicit);
2979 } else {
2980 throw new YAMLException2("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
2981 }
2982 implicit.forEach(function(type2) {
2983 if (!(type2 instanceof Type2)) {
2984 throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
2985 }
2986 if (type2.loadKind && type2.loadKind !== "scalar") {
2987 throw new YAMLException2("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
2988 }
2989 if (type2.multi) {
2990 throw new YAMLException2("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
2991 }
2992 });
2993 explicit.forEach(function(type2) {
2994 if (!(type2 instanceof Type2)) {
2995 throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
2996 }
2997 });
2998 const result = Object.create(Schema2.prototype);
2999 result.implicit = (this.implicit || []).concat(implicit);
3000 result.explicit = (this.explicit || []).concat(explicit);
3001 result.compiledImplicit = compileList(result, "implicit");
3002 result.compiledExplicit = compileList(result, "explicit");
3003 result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
3004 return result;
3005 };
3006 schema = Schema2;
3007 return schema;
3008 }
3009 function requireStr() {
3010 if (hasRequiredStr) return str;
3011 hasRequiredStr = 1;
3012 const Type2 = requireType();
3013 str = new Type2("tag:yaml.org,2002:str", {
3014 kind: "scalar",
3015 construct: function(data2) {
3016 return data2 !== null ? data2 : "";
3017 }
3018 });
3019 return str;
3020 }
3021 function requireSeq() {
3022 if (hasRequiredSeq) return seq;
3023 hasRequiredSeq = 1;
3024 const Type2 = requireType();
3025 seq = new Type2("tag:yaml.org,2002:seq", {
3026 kind: "sequence",
3027 construct: function(data2) {
3028 return data2 !== null ? data2 : [];
3029 }
3030 });
3031 return seq;
3032 }
3033 function requireMap() {
3034 if (hasRequiredMap) return map;
3035 hasRequiredMap = 1;
3036 const Type2 = requireType();
3037 map = new Type2("tag:yaml.org,2002:map", {
3038 kind: "mapping",
3039 construct: function(data2) {
3040 return data2 !== null ? data2 : {};
3041 }
3042 });
3043 return map;
3044 }
3045 function requireFailsafe() {
3046 if (hasRequiredFailsafe) return failsafe;
3047 hasRequiredFailsafe = 1;
3048 const Schema2 = requireSchema();
3049 failsafe = new Schema2({
3050 explicit: [
3051 requireStr(),
3052 requireSeq(),
3053 requireMap()
3054 ]
3055 });
3056 return failsafe;
3057 }
3058 function require_null() {
3059 if (hasRequired_null) return _null;
3060 hasRequired_null = 1;
3061 const Type2 = requireType();
3062 function resolveYamlNull(data2) {
3063 if (data2 === null) return true;
3064 const max = data2.length;
3065 return max === 1 && data2 === "~" || max === 4 && (data2 === "null" || data2 === "Null" || data2 === "NULL");
3066 }
3067 function constructYamlNull() {
3068 return null;
3069 }
3070 function isNull(object) {
3071 return object === null;
3072 }
3073 _null = new Type2("tag:yaml.org,2002:null", {
3074 kind: "scalar",
3075 resolve: resolveYamlNull,
3076 construct: constructYamlNull,
3077 predicate: isNull,
3078 represent: {
3079 canonical: function() {
3080 return "~";
3081 },
3082 lowercase: function() {
3083 return "null";
3084 },
3085 uppercase: function() {
3086 return "NULL";
3087 },
3088 camelcase: function() {
3089 return "Null";
3090 },
3091 empty: function() {
3092 return "";
3093 }
3094 },
3095 defaultStyle: "lowercase"
3096 });
3097 return _null;
3098 }
3099 function requireBool() {
3100 if (hasRequiredBool) return bool;
3101 hasRequiredBool = 1;
3102 const Type2 = requireType();
3103 function resolveYamlBoolean(data2) {
3104 if (data2 === null) return false;
3105 const max = data2.length;
3106 return max === 4 && (data2 === "true" || data2 === "True" || data2 === "TRUE") || max === 5 && (data2 === "false" || data2 === "False" || data2 === "FALSE");
3107 }
3108 function constructYamlBoolean(data2) {
3109 return data2 === "true" || data2 === "True" || data2 === "TRUE";
3110 }
3111 function isBoolean(object) {
3112 return Object.prototype.toString.call(object) === "[object Boolean]";
3113 }
3114 bool = new Type2("tag:yaml.org,2002:bool", {
3115 kind: "scalar",
3116 resolve: resolveYamlBoolean,
3117 construct: constructYamlBoolean,
3118 predicate: isBoolean,
3119 represent: {
3120 lowercase: function(object) {
3121 return object ? "true" : "false";
3122 },
3123 uppercase: function(object) {
3124 return object ? "TRUE" : "FALSE";
3125 },
3126 camelcase: function(object) {
3127 return object ? "True" : "False";
3128 }
3129 },
3130 defaultStyle: "lowercase"
3131 });
3132 return bool;
3133 }
3134 function requireInt() {
3135 if (hasRequiredInt) return int;
3136 hasRequiredInt = 1;
3137 const common2 = requireCommon();
3138 const Type2 = requireType();
3139 function isHexCode(c) {
3140 return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
3141 }
3142 function isOctCode(c) {
3143 return c >= 48 && c <= 55;
3144 }
3145 function isDecCode(c) {
3146 return c >= 48 && c <= 57;
3147 }
3148 function resolveYamlInteger(data2) {
3149 if (data2 === null) return false;
3150 const max = data2.length;
3151 let index = 0;
3152 let hasDigits = false;
3153 if (!max) return false;
3154 let ch = data2[index];
3155 if (ch === "-" || ch === "+") {
3156 ch = data2[++index];
3157 }
3158 if (ch === "0") {
3159 if (index + 1 === max) return true;
3160 ch = data2[++index];
3161 if (ch === "b") {
3162 index++;
3163 for (; index < max; index++) {
3164 ch = data2[index];
3165 if (ch !== "0" && ch !== "1") return false;
3166 hasDigits = true;
3167 }
3168 return hasDigits && isFinite(parseYamlInteger(data2));
3169 }
3170 if (ch === "x") {
3171 index++;
3172 for (; index < max; index++) {
3173 if (!isHexCode(data2.charCodeAt(index))) return false;
3174 hasDigits = true;
3175 }
3176 return hasDigits && isFinite(parseYamlInteger(data2));
3177 }
3178 if (ch === "o") {
3179 index++;
3180 for (; index < max; index++) {
3181 if (!isOctCode(data2.charCodeAt(index))) return false;
3182 hasDigits = true;
3183 }
3184 return hasDigits && isFinite(parseYamlInteger(data2));
3185 }
3186 }
3187 for (; index < max; index++) {
3188 if (!isDecCode(data2.charCodeAt(index))) {
3189 return false;
3190 }
3191 hasDigits = true;
3192 }
3193 if (!hasDigits) return false;
3194 return isFinite(parseYamlInteger(data2));
3195 }
3196 function parseYamlInteger(data2) {
3197 let value = data2;
3198 let sign = 1;
3199 let ch = value[0];
3200 if (ch === "-" || ch === "+") {
3201 if (ch === "-") sign = -1;
3202 value = value.slice(1);
3203 ch = value[0];
3204 }
3205 if (value === "0") return 0;
3206 if (ch === "0") {
3207 if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
3208 if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
3209 if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
3210 }
3211 return sign * parseInt(value, 10);
3212 }
3213 function constructYamlInteger(data2) {
3214 return parseYamlInteger(data2);
3215 }
3216 function isInteger(object) {
3217 return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common2.isNegativeZero(object));
3218 }
3219 int = new Type2("tag:yaml.org,2002:int", {
3220 kind: "scalar",
3221 resolve: resolveYamlInteger,
3222 construct: constructYamlInteger,
3223 predicate: isInteger,
3224 represent: {
3225 binary: function(obj) {
3226 return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
3227 },
3228 octal: function(obj) {
3229 return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
3230 },
3231 decimal: function(obj) {
3232 return obj.toString(10);
3233 },
3234 hexadecimal: function(obj) {
3235 return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
3236 }
3237 },
3238 defaultStyle: "decimal",
3239 styleAliases: {
3240 binary: [2, "bin"],
3241 octal: [8, "oct"],
3242 decimal: [10, "dec"],
3243 hexadecimal: [16, "hex"]
3244 }
3245 });
3246 return int;
3247 }
3248 function requireFloat() {
3249 if (hasRequiredFloat) return float;
3250 hasRequiredFloat = 1;
3251 const common2 = requireCommon();
3252 const Type2 = requireType();
3253 const YAML_FLOAT_PATTERN = new RegExp(
3254 // 2.5e4, 2.5 and integers
3255 "^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
3256 );
3257 const YAML_FLOAT_SPECIAL_PATTERN = new RegExp(
3258 "^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
3259 );
3260 function resolveYamlFloat(data2) {
3261 if (data2 === null) return false;
3262 if (!YAML_FLOAT_PATTERN.test(data2)) {
3263 return false;
3264 }
3265 if (isFinite(parseFloat(data2, 10))) {
3266 return true;
3267 }
3268 return YAML_FLOAT_SPECIAL_PATTERN.test(data2);
3269 }
3270 function constructYamlFloat(data2) {
3271 let value = data2.toLowerCase();
3272 const sign = value[0] === "-" ? -1 : 1;
3273 if ("+-".indexOf(value[0]) >= 0) {
3274 value = value.slice(1);
3275 }
3276 if (value === ".inf") {
3277 return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
3278 } else if (value === ".nan") {
3279 return NaN;
3280 }
3281 return sign * parseFloat(value, 10);
3282 }
3283 const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
3284 function representYamlFloat(object, style) {
3285 if (isNaN(object)) {
3286 switch (style) {
3287 case "lowercase":
3288 return ".nan";
3289 case "uppercase":
3290 return ".NAN";
3291 case "camelcase":
3292 return ".NaN";
3293 }
3294 } else if (Number.POSITIVE_INFINITY === object) {
3295 switch (style) {
3296 case "lowercase":
3297 return ".inf";
3298 case "uppercase":
3299 return ".INF";
3300 case "camelcase":
3301 return ".Inf";
3302 }
3303 } else if (Number.NEGATIVE_INFINITY === object) {
3304 switch (style) {
3305 case "lowercase":
3306 return "-.inf";
3307 case "uppercase":
3308 return "-.INF";
3309 case "camelcase":
3310 return "-.Inf";
3311 }
3312 } else if (common2.isNegativeZero(object)) {
3313 return "-0.0";
3314 }
3315 const res = object.toString(10);
3316 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
3317 }
3318 function isFloat(object) {
3319 return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common2.isNegativeZero(object));
3320 }
3321 float = new Type2("tag:yaml.org,2002:float", {
3322 kind: "scalar",
3323 resolve: resolveYamlFloat,
3324 construct: constructYamlFloat,
3325 predicate: isFloat,
3326 represent: representYamlFloat,
3327 defaultStyle: "lowercase"
3328 });
3329 return float;
3330 }
3331 function requireJson() {
3332 if (hasRequiredJson) return json;
3333 hasRequiredJson = 1;
3334 json = requireFailsafe().extend({
3335 implicit: [
3336 require_null(),
3337 requireBool(),
3338 requireInt(),
3339 requireFloat()
3340 ]
3341 });
3342 return json;
3343 }
3344 function requireCore() {
3345 if (hasRequiredCore) return core;
3346 hasRequiredCore = 1;
3347 core = requireJson();
3348 return core;
3349 }
3350 function requireTimestamp() {
3351 if (hasRequiredTimestamp) return timestamp;
3352 hasRequiredTimestamp = 1;
3353 const Type2 = requireType();
3354 const YAML_DATE_REGEXP = new RegExp(
3355 "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
3356 );
3357 const YAML_TIMESTAMP_REGEXP = new RegExp(
3358 "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
3359 );
3360 function resolveYamlTimestamp(data2) {
3361 if (data2 === null) return false;
3362 if (YAML_DATE_REGEXP.exec(data2) !== null) return true;
3363 if (YAML_TIMESTAMP_REGEXP.exec(data2) !== null) return true;
3364 return false;
3365 }
3366 function constructYamlTimestamp(data2) {
3367 let fraction = 0;
3368 let delta = null;
3369 let match = YAML_DATE_REGEXP.exec(data2);
3370 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data2);
3371 if (match === null) throw new Error("Date resolve error");
3372 const year = +match[1];
3373 const month = +match[2] - 1;
3374 const day = +match[3];
3375 if (!match[4]) {
3376 return new Date(Date.UTC(year, month, day));
3377 }
3378 const hour = +match[4];
3379 const minute = +match[5];
3380 const second = +match[6];
3381 if (match[7]) {
3382 fraction = match[7].slice(0, 3);
3383 while (fraction.length < 3) {
3384 fraction += "0";
3385 }
3386 fraction = +fraction;
3387 }
3388 if (match[9]) {
3389 const tzHour = +match[10];
3390 const tzMinute = +(match[11] || 0);
3391 delta = (tzHour * 60 + tzMinute) * 6e4;
3392 if (match[9] === "-") delta = -delta;
3393 }
3394 const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
3395 if (delta) date.setTime(date.getTime() - delta);
3396 return date;
3397 }
3398 function representYamlTimestamp(object) {
3399 return object.toISOString();
3400 }
3401 timestamp = new Type2("tag:yaml.org,2002:timestamp", {
3402 kind: "scalar",
3403 resolve: resolveYamlTimestamp,
3404 construct: constructYamlTimestamp,
3405 instanceOf: Date,
3406 represent: representYamlTimestamp
3407 });
3408 return timestamp;
3409 }
3410 function requireMerge() {
3411 if (hasRequiredMerge) return merge;
3412 hasRequiredMerge = 1;
3413 const Type2 = requireType();
3414 function resolveYamlMerge(data2) {
3415 return data2 === "<<" || data2 === null;
3416 }
3417 merge = new Type2("tag:yaml.org,2002:merge", {
3418 kind: "scalar",
3419 resolve: resolveYamlMerge
3420 });
3421 return merge;
3422 }
3423 function requireBinary() {
3424 if (hasRequiredBinary) return binary;
3425 hasRequiredBinary = 1;
3426 const Type2 = requireType();
3427 const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
3428 function resolveYamlBinary(data2) {
3429 if (data2 === null) return false;
3430 let bitlen = 0;
3431 const max = data2.length;
3432 const map2 = BASE64_MAP;
3433 for (let idx = 0; idx < max; idx++) {
3434 const code = map2.indexOf(data2.charAt(idx));
3435 if (code > 64) continue;
3436 if (code < 0) return false;
3437 bitlen += 6;
3438 }
3439 return bitlen % 8 === 0;
3440 }
3441 function constructYamlBinary(data2) {
3442 const input = data2.replace(/[\r\n=]/g, "");
3443 const max = input.length;
3444 const map2 = BASE64_MAP;
3445 let bits = 0;
3446 const result = [];
3447 for (let idx = 0; idx < max; idx++) {
3448 if (idx % 4 === 0 && idx) {
3449 result.push(bits >> 16 & 255);
3450 result.push(bits >> 8 & 255);
3451 result.push(bits & 255);
3452 }
3453 bits = bits << 6 | map2.indexOf(input.charAt(idx));
3454 }
3455 const tailbits = max % 4 * 6;
3456 if (tailbits === 0) {
3457 result.push(bits >> 16 & 255);
3458 result.push(bits >> 8 & 255);
3459 result.push(bits & 255);
3460 } else if (tailbits === 18) {
3461 result.push(bits >> 10 & 255);
3462 result.push(bits >> 2 & 255);
3463 } else if (tailbits === 12) {
3464 result.push(bits >> 4 & 255);
3465 }
3466 return new Uint8Array(result);
3467 }
3468 function representYamlBinary(object) {
3469 let result = "";
3470 let bits = 0;
3471 const max = object.length;
3472 const map2 = BASE64_MAP;
3473 for (let idx = 0; idx < max; idx++) {
3474 if (idx % 3 === 0 && idx) {
3475 result += map2[bits >> 18 & 63];
3476 result += map2[bits >> 12 & 63];
3477 result += map2[bits >> 6 & 63];
3478 result += map2[bits & 63];
3479 }
3480 bits = (bits << 8) + object[idx];
3481 }
3482 const tail = max % 3;
3483 if (tail === 0) {
3484 result += map2[bits >> 18 & 63];
3485 result += map2[bits >> 12 & 63];
3486 result += map2[bits >> 6 & 63];
3487 result += map2[bits & 63];
3488 } else if (tail === 2) {
3489 result += map2[bits >> 10 & 63];
3490 result += map2[bits >> 4 & 63];
3491 result += map2[bits << 2 & 63];
3492 result += map2[64];
3493 } else if (tail === 1) {
3494 result += map2[bits >> 2 & 63];
3495 result += map2[bits << 4 & 63];
3496 result += map2[64];
3497 result += map2[64];
3498 }
3499 return result;
3500 }
3501 function isBinary(obj) {
3502 return Object.prototype.toString.call(obj) === "[object Uint8Array]";
3503 }
3504 binary = new Type2("tag:yaml.org,2002:binary", {
3505 kind: "scalar",
3506 resolve: resolveYamlBinary,
3507 construct: constructYamlBinary,
3508 predicate: isBinary,
3509 represent: representYamlBinary
3510 });
3511 return binary;
3512 }
3513 function requireOmap() {
3514 if (hasRequiredOmap) return omap;
3515 hasRequiredOmap = 1;
3516 const Type2 = requireType();
3517 const _hasOwnProperty = Object.prototype.hasOwnProperty;
3518 const _toString = Object.prototype.toString;
3519 function resolveYamlOmap(data2) {
3520 if (data2 === null) return true;
3521 const objectKeys = {};
3522 const object = data2;
3523 for (let index = 0, length = object.length; index < length; index += 1) {
3524 const pair = object[index];
3525 let pairHasKey = false;
3526 if (_toString.call(pair) !== "[object Object]") return false;
3527 let pairKey;
3528 for (pairKey in pair) {
3529 if (_hasOwnProperty.call(pair, pairKey)) {
3530 if (!pairHasKey) pairHasKey = true;
3531 else return false;
3532 }
3533 }
3534 if (!pairHasKey) return false;
3535 if (_hasOwnProperty.call(objectKeys, pairKey)) return false;
3536 Object.defineProperty(objectKeys, pairKey, { value: true });
3537 }
3538 return true;
3539 }
3540 function constructYamlOmap(data2) {
3541 return data2 !== null ? data2 : [];
3542 }
3543 omap = new Type2("tag:yaml.org,2002:omap", {
3544 kind: "sequence",
3545 resolve: resolveYamlOmap,
3546 construct: constructYamlOmap
3547 });
3548 return omap;
3549 }
3550 function requirePairs() {
3551 if (hasRequiredPairs) return pairs;
3552 hasRequiredPairs = 1;
3553 const Type2 = requireType();
3554 const _toString = Object.prototype.toString;
3555 function resolveYamlPairs(data2) {
3556 if (data2 === null) return true;
3557 const object = data2;
3558 const result = new Array(object.length);
3559 for (let index = 0, length = object.length; index < length; index += 1) {
3560 const pair = object[index];
3561 if (_toString.call(pair) !== "[object Object]") return false;
3562 const keys = Object.keys(pair);
3563 if (keys.length !== 1) return false;
3564 result[index] = [keys[0], pair[keys[0]]];
3565 }
3566 return true;
3567 }
3568 function constructYamlPairs(data2) {
3569 if (data2 === null) return [];
3570 const object = data2;
3571 const result = new Array(object.length);
3572 for (let index = 0, length = object.length; index < length; index += 1) {
3573 const pair = object[index];
3574 const keys = Object.keys(pair);
3575 result[index] = [keys[0], pair[keys[0]]];
3576 }
3577 return result;
3578 }
3579 pairs = new Type2("tag:yaml.org,2002:pairs", {
3580 kind: "sequence",
3581 resolve: resolveYamlPairs,
3582 construct: constructYamlPairs
3583 });
3584 return pairs;
3585 }
3586 function requireSet() {
3587 if (hasRequiredSet) return set;
3588 hasRequiredSet = 1;
3589 const Type2 = requireType();
3590 const _hasOwnProperty = Object.prototype.hasOwnProperty;
3591 function resolveYamlSet(data2) {
3592 if (data2 === null) return true;
3593 const object = data2;
3594 for (const key in object) {
3595 if (_hasOwnProperty.call(object, key)) {
3596 if (object[key] !== null) return false;
3597 }
3598 }
3599 return true;
3600 }
3601 function constructYamlSet(data2) {
3602 return data2 !== null ? data2 : {};
3603 }
3604 set = new Type2("tag:yaml.org,2002:set", {
3605 kind: "mapping",
3606 resolve: resolveYamlSet,
3607 construct: constructYamlSet
3608 });
3609 return set;
3610 }
3611 function require_default() {
3612 if (hasRequired_default) return _default;
3613 hasRequired_default = 1;
3614 _default = requireCore().extend({
3615 implicit: [
3616 requireTimestamp(),
3617 requireMerge()
3618 ],
3619 explicit: [
3620 requireBinary(),
3621 requireOmap(),
3622 requirePairs(),
3623 requireSet()
3624 ]
3625 });
3626 return _default;
3627 }
3628 function requireLoader() {
3629 if (hasRequiredLoader) return loader;
3630 hasRequiredLoader = 1;
3631 const common2 = requireCommon();
3632 const YAMLException2 = requireException();
3633 const makeSnippet = requireSnippet();
3634 const DEFAULT_SCHEMA2 = require_default();
3635 const _hasOwnProperty = Object.prototype.hasOwnProperty;
3636 const CONTEXT_FLOW_IN = 1;
3637 const CONTEXT_FLOW_OUT = 2;
3638 const CONTEXT_BLOCK_IN = 3;
3639 const CONTEXT_BLOCK_OUT = 4;
3640 const CHOMPING_CLIP = 1;
3641 const CHOMPING_STRIP = 2;
3642 const CHOMPING_KEEP = 3;
3643 const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
3644 const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
3645 const PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
3646 const PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
3647 const PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;
3648 function _class(obj) {
3649 return Object.prototype.toString.call(obj);
3650 }
3651 function isEol(c) {
3652 return c === 10 || c === 13;
3653 }
3654 function isWhiteSpace(c) {
3655 return c === 9 || c === 32;
3656 }
3657 function isWsOrEol(c) {
3658 return c === 9 || c === 32 || c === 10 || c === 13;
3659 }
3660 function isFlowIndicator(c) {
3661 return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
3662 }
3663 function fromHexCode(c) {
3664 if (c >= 48 && c <= 57) {
3665 return c - 48;
3666 }
3667 const lc = c | 32;
3668 if (lc >= 97 && lc <= 102) {
3669 return lc - 97 + 10;
3670 }
3671 return -1;
3672 }
3673 function escapedHexLen(c) {
3674 if (c === 120) {
3675 return 2;
3676 }
3677 if (c === 117) {
3678 return 4;
3679 }
3680 if (c === 85) {
3681 return 8;
3682 }
3683 return 0;
3684 }
3685 function fromDecimalCode(c) {
3686 if (c >= 48 && c <= 57) {
3687 return c - 48;
3688 }
3689 return -1;
3690 }
3691 function simpleEscapeSequence(c) {
3692 switch (c) {
3693 case 48:
3694 return "\0";
3695 case 97:
3696 return "\x07";
3697 case 98:
3698 return "\b";
3699 case 116:
3700 return " ";
3701 case 9:
3702 return " ";
3703 case 110:
3704 return "\n";
3705 case 118:
3706 return "\v";
3707 case 102:
3708 return "\f";
3709 case 114:
3710 return "\r";
3711 case 101:
3712 return "\x1B";
3713 case 32:
3714 return " ";
3715 case 34:
3716 return '"';
3717 case 47:
3718 return "/";
3719 case 92:
3720 return "\\";
3721 case 78:
3722 return "…";
3723 case 95:
3724 return " ";
3725 case 76:
3726 return "\u2028";
3727 case 80:
3728 return "\u2029";
3729 default:
3730 return "";
3731 }
3732 }
3733 function charFromCodepoint(c) {
3734 if (c <= 65535) {
3735 return String.fromCharCode(c);
3736 }
3737 return String.fromCharCode(
3738 (c - 65536 >> 10) + 55296,
3739 (c - 65536 & 1023) + 56320
3740 );
3741 }
3742 function setProperty(object, key, value) {
3743 if (key === "__proto__") {
3744 Object.defineProperty(object, key, {
3745 configurable: true,
3746 enumerable: true,
3747 writable: true,
3748 value
3749 });
3750 } else {
3751 object[key] = value;
3752 }
3753 }
3754 const simpleEscapeCheck = new Array(256);
3755 const simpleEscapeMap = new Array(256);
3756 for (let i2 = 0; i2 < 256; i2++) {
3757 simpleEscapeCheck[i2] = simpleEscapeSequence(i2) ? 1 : 0;
3758 simpleEscapeMap[i2] = simpleEscapeSequence(i2);
3759 }
3760 function State(input, options) {
3761 this.input = input;
3762 this.filename = options["filename"] || null;
3763 this.schema = options["schema"] || DEFAULT_SCHEMA2;
3764 this.onWarning = options["onWarning"] || null;
3765 this.legacy = options["legacy"] || false;
3766 this.json = options["json"] || false;
3767 this.listener = options["listener"] || null;
3768 this.maxDepth = typeof options["maxDepth"] === "number" ? options["maxDepth"] : 100;
3769 this.maxTotalMergeKeys = typeof options["maxTotalMergeKeys"] === "number" ? options["maxTotalMergeKeys"] : 1e4;
3770 this.implicitTypes = this.schema.compiledImplicit;
3771 this.typeMap = this.schema.compiledTypeMap;
3772 this.length = input.length;
3773 this.position = 0;
3774 this.line = 0;
3775 this.lineStart = 0;
3776 this.lineIndent = 0;
3777 this.depth = 0;
3778 this.totalMergeKeys = 0;
3779 this.firstTabInLine = -1;
3780 this.documents = [];
3781 this.anchorMapTransactions = [];
3782 }
3783 function generateError(state, message) {
3784 const mark = {
3785 name: state.filename,
3786 buffer: state.input.slice(0, -1),
3787 // omit trailing \0
3788 position: state.position,
3789 line: state.line,
3790 column: state.position - state.lineStart
3791 };
3792 mark.snippet = makeSnippet(mark);
3793 return new YAMLException2(message, mark);
3794 }
3795 function throwError(state, message) {
3796 throw generateError(state, message);
3797 }
3798 function throwWarning(state, message) {
3799 if (state.onWarning) {
3800 state.onWarning.call(null, generateError(state, message));
3801 }
3802 }
3803 function storeAnchor(state, name, value) {
3804 const transactions = state.anchorMapTransactions;
3805 if (transactions.length !== 0) {
3806 const transaction = transactions[transactions.length - 1];
3807 if (!_hasOwnProperty.call(transaction, name)) {
3808 transaction[name] = {
3809 existed: _hasOwnProperty.call(state.anchorMap, name),
3810 value: state.anchorMap[name]
3811 };
3812 }
3813 }
3814 state.anchorMap[name] = value;
3815 }
3816 function beginAnchorTransaction(state) {
3817 state.anchorMapTransactions.push(/* @__PURE__ */ Object.create(null));
3818 }
3819 function commitAnchorTransaction(state) {
3820 const transaction = state.anchorMapTransactions.pop();
3821 const transactions = state.anchorMapTransactions;
3822 if (transactions.length === 0) return;
3823 const parent = transactions[transactions.length - 1];
3824 const names = Object.keys(transaction);
3825 for (let index = 0, length = names.length; index < length; index += 1) {
3826 const name = names[index];
3827 if (!_hasOwnProperty.call(parent, name)) {
3828 parent[name] = transaction[name];
3829 }
3830 }
3831 }
3832 function rollbackAnchorTransaction(state) {
3833 const transaction = state.anchorMapTransactions.pop();
3834 const names = Object.keys(transaction);
3835 for (let index = names.length - 1; index >= 0; index -= 1) {
3836 const entry = transaction[names[index]];
3837 if (entry.existed) {
3838 state.anchorMap[names[index]] = entry.value;
3839 } else {
3840 delete state.anchorMap[names[index]];
3841 }
3842 }
3843 }
3844 function snapshotState(state) {
3845 return {
3846 position: state.position,
3847 line: state.line,
3848 lineStart: state.lineStart,
3849 lineIndent: state.lineIndent,
3850 firstTabInLine: state.firstTabInLine,
3851 tag: state.tag,
3852 anchor: state.anchor,
3853 kind: state.kind,
3854 result: state.result
3855 };
3856 }
3857 function restoreState(state, snapshot) {
3858 state.position = snapshot.position;
3859 state.line = snapshot.line;
3860 state.lineStart = snapshot.lineStart;
3861 state.lineIndent = snapshot.lineIndent;
3862 state.firstTabInLine = snapshot.firstTabInLine;
3863 state.tag = snapshot.tag;
3864 state.anchor = snapshot.anchor;
3865 state.kind = snapshot.kind;
3866 state.result = snapshot.result;
3867 }
3868 const directiveHandlers = {
3869 YAML: function handleYamlDirective(state, name, args) {
3870 if (state.version !== null) {
3871 throwError(state, "duplication of %YAML directive");
3872 }
3873 if (args.length !== 1) {
3874 throwError(state, "YAML directive accepts exactly one argument");
3875 }
3876 const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
3877 if (match === null) {
3878 throwError(state, "ill-formed argument of the YAML directive");
3879 }
3880 const major = parseInt(match[1], 10);
3881 const minor = parseInt(match[2], 10);
3882 if (major !== 1) {
3883 throwError(state, "unacceptable YAML version of the document");
3884 }
3885 state.version = args[0];
3886 state.checkLineBreaks = minor < 2;
3887 if (minor !== 1 && minor !== 2) {
3888 throwWarning(state, "unsupported YAML version of the document");
3889 }
3890 },
3891 TAG: function handleTagDirective(state, name, args) {
3892 let prefix;
3893 if (args.length !== 2) {
3894 throwError(state, "TAG directive accepts exactly two arguments");
3895 }
3896 const handle = args[0];
3897 prefix = args[1];
3898 if (!PATTERN_TAG_HANDLE.test(handle)) {
3899 throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
3900 }
3901 if (_hasOwnProperty.call(state.tagMap, handle)) {
3902 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
3903 }
3904 if (!PATTERN_TAG_URI.test(prefix)) {
3905 throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
3906 }
3907 try {
3908 prefix = decodeURIComponent(prefix);
3909 } catch (err) {
3910 throwError(state, "tag prefix is malformed: " + prefix);
3911 }
3912 state.tagMap[handle] = prefix;
3913 }
3914 };
3915 function captureSegment(state, start, end, checkJson) {
3916 if (start < end) {
3917 const _result = state.input.slice(start, end);
3918 if (checkJson) {
3919 for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {
3920 const _character = _result.charCodeAt(_position);
3921 if (!(_character === 9 || _character >= 32 && _character <= 1114111)) {
3922 throwError(state, "expected valid JSON character");
3923 }
3924 }
3925 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
3926 throwError(state, "the stream contains non-printable characters");
3927 }
3928 state.result += _result;
3929 }
3930 }
3931 function chargeMergeWork(state) {
3932 state.totalMergeKeys++;
3933 if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) {
3934 throwError(state, "merge keys exceeded maxTotalMergeKeys (" + state.maxTotalMergeKeys + ")");
3935 }
3936 }
3937 function mergeMappings(state, destination, source, overridableKeys) {
3938 if (!common2.isObject(source)) {
3939 throwError(state, "cannot merge mappings; the provided source object is unacceptable");
3940 }
3941 chargeMergeWork(state);
3942 const sourceKeys = Object.keys(source);
3943 for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
3944 const key = sourceKeys[index];
3945 chargeMergeWork(state);
3946 if (!_hasOwnProperty.call(destination, key)) {
3947 setProperty(destination, key, source[key]);
3948 overridableKeys[key] = true;
3949 }
3950 }
3951 }
3952 function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
3953 if (Array.isArray(keyNode)) {
3954 keyNode = Array.prototype.slice.call(keyNode);
3955 for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {
3956 if (Array.isArray(keyNode[index])) {
3957 throwError(state, "nested arrays are not supported inside keys");
3958 }
3959 if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
3960 keyNode[index] = "[object Object]";
3961 }
3962 }
3963 }
3964 if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
3965 keyNode = "[object Object]";
3966 }
3967 keyNode = String(keyNode);
3968 if (_result === null) {
3969 _result = {};
3970 }
3971 if (keyTag === "tag:yaml.org,2002:merge") {
3972 if (Array.isArray(valueNode)) {
3973 if (valueNode.length > 100) {
3974 throwError(state, "abnormal merge sequence size");
3975 }
3976 for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {
3977 mergeMappings(state, _result, valueNode[index], overridableKeys);
3978 }
3979 } else {
3980 mergeMappings(state, _result, valueNode, overridableKeys);
3981 }
3982 } else {
3983 if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
3984 state.line = startLine || state.line;
3985 state.lineStart = startLineStart || state.lineStart;
3986 state.position = startPos || state.position;
3987 throwError(state, "duplicated mapping key");
3988 }
3989 setProperty(_result, keyNode, valueNode);
3990 delete overridableKeys[keyNode];
3991 }
3992 return _result;
3993 }
3994 function readLineBreak(state) {
3995 const ch = state.input.charCodeAt(state.position);
3996 if (ch === 10) {
3997 state.position++;
3998 } else if (ch === 13) {
3999 state.position++;
4000 if (state.input.charCodeAt(state.position) === 10) {
4001 state.position++;
4002 }
4003 } else {
4004 throwError(state, "a line break is expected");
4005 }
4006 state.line += 1;
4007 state.lineStart = state.position;
4008 state.firstTabInLine = -1;
4009 }
4010 function skipSeparationSpace(state, allowComments, checkIndent) {
4011 let lineBreaks = 0;
4012 let ch = state.input.charCodeAt(state.position);
4013 while (ch !== 0) {
4014 while (isWhiteSpace(ch)) {
4015 if (ch === 9 && state.firstTabInLine === -1) {
4016 state.firstTabInLine = state.position;
4017 }
4018 ch = state.input.charCodeAt(++state.position);
4019 }
4020 if (allowComments && ch === 35) {
4021 do {
4022 ch = state.input.charCodeAt(++state.position);
4023 } while (ch !== 10 && ch !== 13 && ch !== 0);
4024 }
4025 if (isEol(ch)) {
4026 readLineBreak(state);
4027 ch = state.input.charCodeAt(state.position);
4028 lineBreaks++;
4029 state.lineIndent = 0;
4030 while (ch === 32) {
4031 state.lineIndent++;
4032 ch = state.input.charCodeAt(++state.position);
4033 }
4034 } else {
4035 break;
4036 }
4037 }
4038 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
4039 throwWarning(state, "deficient indentation");
4040 }
4041 return lineBreaks;
4042 }
4043 function testDocumentSeparator(state) {
4044 let _position = state.position;
4045 let ch = state.input.charCodeAt(_position);
4046 if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
4047 _position += 3;
4048 ch = state.input.charCodeAt(_position);
4049 if (ch === 0 || isWsOrEol(ch)) {
4050 return true;
4051 }
4052 }
4053 return false;
4054 }
4055 function writeFoldedLines(state, count) {
4056 if (count === 1) {
4057 state.result += " ";
4058 } else if (count > 1) {
4059 state.result += common2.repeat("\n", count - 1);
4060 }
4061 }
4062 function readPlainScalar(state, nodeIndent, withinFlowCollection) {
4063 let captureStart;
4064 let captureEnd;
4065 let hasPendingContent;
4066 let _line;
4067 let _lineStart;
4068 let _lineIndent;
4069 const _kind = state.kind;
4070 const _result = state.result;
4071 let ch = state.input.charCodeAt(state.position);
4072 if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
4073 return false;
4074 }
4075 if (ch === 63 || ch === 45) {
4076 const following = state.input.charCodeAt(state.position + 1);
4077 if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
4078 return false;
4079 }
4080 }
4081 state.kind = "scalar";
4082 state.result = "";
4083 captureStart = captureEnd = state.position;
4084 hasPendingContent = false;
4085 while (ch !== 0) {
4086 if (ch === 58) {
4087 const following = state.input.charCodeAt(state.position + 1);
4088 if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
4089 break;
4090 }
4091 } else if (ch === 35) {
4092 const preceding = state.input.charCodeAt(state.position - 1);
4093 if (isWsOrEol(preceding)) {
4094 break;
4095 }
4096 } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) {
4097 break;
4098 } else if (isEol(ch)) {
4099 _line = state.line;
4100 _lineStart = state.lineStart;
4101 _lineIndent = state.lineIndent;
4102 skipSeparationSpace(state, false, -1);
4103 if (state.lineIndent >= nodeIndent) {
4104 hasPendingContent = true;
4105 ch = state.input.charCodeAt(state.position);
4106 continue;
4107 } else {
4108 state.position = captureEnd;
4109 state.line = _line;
4110 state.lineStart = _lineStart;
4111 state.lineIndent = _lineIndent;
4112 break;
4113 }
4114 }
4115 if (hasPendingContent) {
4116 captureSegment(state, captureStart, captureEnd, false);
4117 writeFoldedLines(state, state.line - _line);
4118 captureStart = captureEnd = state.position;
4119 hasPendingContent = false;
4120 }
4121 if (!isWhiteSpace(ch)) {
4122 captureEnd = state.position + 1;
4123 }
4124 ch = state.input.charCodeAt(++state.position);
4125 }
4126 captureSegment(state, captureStart, captureEnd, false);
4127 if (state.result) {
4128 return true;
4129 }
4130 state.kind = _kind;
4131 state.result = _result;
4132 return false;
4133 }
4134 function readSingleQuotedScalar(state, nodeIndent) {
4135 let captureStart;
4136 let captureEnd;
4137 let ch = state.input.charCodeAt(state.position);
4138 if (ch !== 39) {
4139 return false;
4140 }
4141 state.kind = "scalar";
4142 state.result = "";
4143 state.position++;
4144 captureStart = captureEnd = state.position;
4145 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
4146 if (ch === 39) {
4147 captureSegment(state, captureStart, state.position, true);
4148 ch = state.input.charCodeAt(++state.position);
4149 if (ch === 39) {
4150 captureStart = state.position;
4151 state.position++;
4152 captureEnd = state.position;
4153 } else {
4154 return true;
4155 }
4156 } else if (isEol(ch)) {
4157 captureSegment(state, captureStart, captureEnd, true);
4158 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
4159 captureStart = captureEnd = state.position;
4160 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
4161 throwError(state, "unexpected end of the document within a single quoted scalar");
4162 } else {
4163 state.position++;
4164 if (!isWhiteSpace(ch)) {
4165 captureEnd = state.position;
4166 }
4167 }
4168 }
4169 throwError(state, "unexpected end of the stream within a single quoted scalar");
4170 }
4171 function readDoubleQuotedScalar(state, nodeIndent) {
4172 let captureStart;
4173 let captureEnd;
4174 let tmp;
4175 let ch = state.input.charCodeAt(state.position);
4176 if (ch !== 34) {
4177 return false;
4178 }
4179 state.kind = "scalar";
4180 state.result = "";
4181 state.position++;
4182 captureStart = captureEnd = state.position;
4183 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
4184 if (ch === 34) {
4185 captureSegment(state, captureStart, state.position, true);
4186 state.position++;
4187 return true;
4188 } else if (ch === 92) {
4189 captureSegment(state, captureStart, state.position, true);
4190 ch = state.input.charCodeAt(++state.position);
4191 if (isEol(ch)) {
4192 skipSeparationSpace(state, false, nodeIndent);
4193 } else if (ch < 256 && simpleEscapeCheck[ch]) {
4194 state.result += simpleEscapeMap[ch];
4195 state.position++;
4196 } else if ((tmp = escapedHexLen(ch)) > 0) {
4197 let hexLength = tmp;
4198 let hexResult = 0;
4199 for (; hexLength > 0; hexLength--) {
4200 ch = state.input.charCodeAt(++state.position);
4201 if ((tmp = fromHexCode(ch)) >= 0) {
4202 hexResult = (hexResult << 4) + tmp;
4203 } else {
4204 throwError(state, "expected hexadecimal character");
4205 }
4206 }
4207 state.result += charFromCodepoint(hexResult);
4208 state.position++;
4209 } else {
4210 throwError(state, "unknown escape sequence");
4211 }
4212 captureStart = captureEnd = state.position;
4213 } else if (isEol(ch)) {
4214 captureSegment(state, captureStart, captureEnd, true);
4215 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
4216 captureStart = captureEnd = state.position;
4217 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
4218 throwError(state, "unexpected end of the document within a double quoted scalar");
4219 } else {
4220 state.position++;
4221 if (!isWhiteSpace(ch)) {
4222 captureEnd = state.position;
4223 }
4224 }
4225 }
4226 throwError(state, "unexpected end of the stream within a double quoted scalar");
4227 }
4228 function readFlowCollection(state, nodeIndent) {
4229 let readNext = true;
4230 let _line;
4231 let _lineStart;
4232 let _pos;
4233 const _tag = state.tag;
4234 let _result;
4235 const _anchor = state.anchor;
4236 let terminator;
4237 let isPair;
4238 let isExplicitPair;
4239 let isMapping;
4240 const overridableKeys = /* @__PURE__ */ Object.create(null);
4241 let keyNode;
4242 let keyTag;
4243 let valueNode;
4244 let ch = state.input.charCodeAt(state.position);
4245 if (ch === 91) {
4246 terminator = 93;
4247 isMapping = false;
4248 _result = [];
4249 } else if (ch === 123) {
4250 terminator = 125;
4251 isMapping = true;
4252 _result = {};
4253 } else {
4254 return false;
4255 }
4256 if (state.anchor !== null) {
4257 storeAnchor(state, state.anchor, _result);
4258 }
4259 ch = state.input.charCodeAt(++state.position);
4260 while (ch !== 0) {
4261 skipSeparationSpace(state, true, nodeIndent);
4262 ch = state.input.charCodeAt(state.position);
4263 if (ch === terminator) {
4264 state.position++;
4265 state.tag = _tag;
4266 state.anchor = _anchor;
4267 state.kind = isMapping ? "mapping" : "sequence";
4268 state.result = _result;
4269 return true;
4270 } else if (!readNext) {
4271 throwError(state, "missed comma between flow collection entries");
4272 } else if (ch === 44) {
4273 throwError(state, "expected the node content, but found ','");
4274 }
4275 keyTag = keyNode = valueNode = null;
4276 isPair = isExplicitPair = false;
4277 if (ch === 63) {
4278 const following = state.input.charCodeAt(state.position + 1);
4279 if (isWsOrEol(following)) {
4280 isPair = isExplicitPair = true;
4281 state.position++;
4282 skipSeparationSpace(state, true, nodeIndent);
4283 }
4284 }
4285 _line = state.line;
4286 _lineStart = state.lineStart;
4287 _pos = state.position;
4288 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
4289 keyTag = state.tag;
4290 keyNode = state.result;
4291 skipSeparationSpace(state, true, nodeIndent);
4292 ch = state.input.charCodeAt(state.position);
4293 if ((isExplicitPair || state.line === _line) && ch === 58) {
4294 isPair = true;
4295 ch = state.input.charCodeAt(++state.position);
4296 skipSeparationSpace(state, true, nodeIndent);
4297 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
4298 valueNode = state.result;
4299 }
4300 if (isMapping) {
4301 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
4302 } else if (isPair) {
4303 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
4304 } else {
4305 _result.push(keyNode);
4306 }
4307 skipSeparationSpace(state, true, nodeIndent);
4308 ch = state.input.charCodeAt(state.position);
4309 if (ch === 44) {
4310 readNext = true;
4311 ch = state.input.charCodeAt(++state.position);
4312 } else {
4313 readNext = false;
4314 }
4315 }
4316 throwError(state, "unexpected end of the stream within a flow collection");
4317 }
4318 function readBlockScalar(state, nodeIndent) {
4319 let folding;
4320 let chomping = CHOMPING_CLIP;
4321 let didReadContent = false;
4322 let detectedIndent = false;
4323 let textIndent = nodeIndent;
4324 let emptyLines = 0;
4325 let atMoreIndented = false;
4326 let tmp;
4327 let ch = state.input.charCodeAt(state.position);
4328 if (ch === 124) {
4329 folding = false;
4330 } else if (ch === 62) {
4331 folding = true;
4332 } else {
4333 return false;
4334 }
4335 state.kind = "scalar";
4336 state.result = "";
4337 while (ch !== 0) {
4338 ch = state.input.charCodeAt(++state.position);
4339 if (ch === 43 || ch === 45) {
4340 if (CHOMPING_CLIP === chomping) {
4341 chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
4342 } else {
4343 throwError(state, "repeat of a chomping mode identifier");
4344 }
4345 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
4346 if (tmp === 0) {
4347 throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
4348 } else if (!detectedIndent) {
4349 textIndent = nodeIndent + tmp - 1;
4350 detectedIndent = true;
4351 } else {
4352 throwError(state, "repeat of an indentation width identifier");
4353 }
4354 } else {
4355 break;
4356 }
4357 }
4358 if (isWhiteSpace(ch)) {
4359 do {
4360 ch = state.input.charCodeAt(++state.position);
4361 } while (isWhiteSpace(ch));
4362 if (ch === 35) {
4363 do {
4364 ch = state.input.charCodeAt(++state.position);
4365 } while (!isEol(ch) && ch !== 0);
4366 }
4367 }
4368 while (ch !== 0) {
4369 readLineBreak(state);
4370 state.lineIndent = 0;
4371 ch = state.input.charCodeAt(state.position);
4372 while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
4373 state.lineIndent++;
4374 ch = state.input.charCodeAt(++state.position);
4375 }
4376 if (!detectedIndent && state.lineIndent > textIndent) {
4377 textIndent = state.lineIndent;
4378 }
4379 if (isEol(ch)) {
4380 emptyLines++;
4381 continue;
4382 }
4383 if (!detectedIndent && textIndent === 0) {
4384 throwError(state, "missing indentation for block scalar");
4385 }
4386 if (state.lineIndent < textIndent) {
4387 if (chomping === CHOMPING_KEEP) {
4388 state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
4389 } else if (chomping === CHOMPING_CLIP) {
4390 if (didReadContent) {
4391 state.result += "\n";
4392 }
4393 }
4394 break;
4395 }
4396 if (folding) {
4397 if (isWhiteSpace(ch)) {
4398 atMoreIndented = true;
4399 state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
4400 } else if (atMoreIndented) {
4401 atMoreIndented = false;
4402 state.result += common2.repeat("\n", emptyLines + 1);
4403 } else if (emptyLines === 0) {
4404 if (didReadContent) {
4405 state.result += " ";
4406 }
4407 } else {
4408 state.result += common2.repeat("\n", emptyLines);
4409 }
4410 } else {
4411 state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
4412 }
4413 didReadContent = true;
4414 detectedIndent = true;
4415 emptyLines = 0;
4416 const captureStart = state.position;
4417 while (!isEol(ch) && ch !== 0) {
4418 ch = state.input.charCodeAt(++state.position);
4419 }
4420 captureSegment(state, captureStart, state.position, false);
4421 }
4422 return true;
4423 }
4424 function readBlockSequence(state, nodeIndent) {
4425 const _tag = state.tag;
4426 const _anchor = state.anchor;
4427 const _result = [];
4428 let detected = false;
4429 if (state.firstTabInLine !== -1) return false;
4430 if (state.anchor !== null) {
4431 storeAnchor(state, state.anchor, _result);
4432 }
4433 let ch = state.input.charCodeAt(state.position);
4434 while (ch !== 0) {
4435 if (state.firstTabInLine !== -1) {
4436 state.position = state.firstTabInLine;
4437 throwError(state, "tab characters must not be used in indentation");
4438 }
4439 if (ch !== 45) {
4440 break;
4441 }
4442 const following = state.input.charCodeAt(state.position + 1);
4443 if (!isWsOrEol(following)) {
4444 break;
4445 }
4446 detected = true;
4447 state.position++;
4448 if (skipSeparationSpace(state, true, -1)) {
4449 if (state.lineIndent <= nodeIndent) {
4450 _result.push(null);
4451 ch = state.input.charCodeAt(state.position);
4452 continue;
4453 }
4454 }
4455 const _line = state.line;
4456 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
4457 _result.push(state.result);
4458 skipSeparationSpace(state, true, -1);
4459 ch = state.input.charCodeAt(state.position);
4460 if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
4461 throwError(state, "bad indentation of a sequence entry");
4462 } else if (state.lineIndent < nodeIndent) {
4463 break;
4464 }
4465 }
4466 if (detected) {
4467 state.tag = _tag;
4468 state.anchor = _anchor;
4469 state.kind = "sequence";
4470 state.result = _result;
4471 return true;
4472 }
4473 return false;
4474 }
4475 function readBlockMapping(state, nodeIndent, flowIndent) {
4476 let allowCompact;
4477 let _keyLine;
4478 let _keyLineStart;
4479 let _keyPos;
4480 const _tag = state.tag;
4481 const _anchor = state.anchor;
4482 const _result = {};
4483 const overridableKeys = /* @__PURE__ */ Object.create(null);
4484 let keyTag = null;
4485 let keyNode = null;
4486 let valueNode = null;
4487 let atExplicitKey = false;
4488 let detected = false;
4489 if (state.firstTabInLine !== -1) return false;
4490 if (state.anchor !== null) {
4491 storeAnchor(state, state.anchor, _result);
4492 }
4493 let ch = state.input.charCodeAt(state.position);
4494 while (ch !== 0) {
4495 if (!atExplicitKey && state.firstTabInLine !== -1) {
4496 state.position = state.firstTabInLine;
4497 throwError(state, "tab characters must not be used in indentation");
4498 }
4499 const following = state.input.charCodeAt(state.position + 1);
4500 const _line = state.line;
4501 if ((ch === 63 || ch === 58) && isWsOrEol(following)) {
4502 if (ch === 63) {
4503 if (atExplicitKey) {
4504 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
4505 keyTag = keyNode = valueNode = null;
4506 }
4507 detected = true;
4508 atExplicitKey = true;
4509 allowCompact = true;
4510 } else if (atExplicitKey) {
4511 atExplicitKey = false;
4512 allowCompact = true;
4513 } else {
4514 throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
4515 }
4516 state.position += 1;
4517 ch = following;
4518 } else {
4519 _keyLine = state.line;
4520 _keyLineStart = state.lineStart;
4521 _keyPos = state.position;
4522 if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
4523 break;
4524 }
4525 if (state.line === _line) {
4526 ch = state.input.charCodeAt(state.position);
4527 while (isWhiteSpace(ch)) {
4528 ch = state.input.charCodeAt(++state.position);
4529 }
4530 if (ch === 58) {
4531 ch = state.input.charCodeAt(++state.position);
4532 if (!isWsOrEol(ch)) {
4533 throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
4534 }
4535 if (atExplicitKey) {
4536 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
4537 keyTag = keyNode = valueNode = null;
4538 }
4539 detected = true;
4540 atExplicitKey = false;
4541 allowCompact = false;
4542 keyTag = state.tag;
4543 keyNode = state.result;
4544 } else if (detected) {
4545 throwError(state, "can not read an implicit mapping pair; a colon is missed");
4546 } else {
4547 state.tag = _tag;
4548 state.anchor = _anchor;
4549 return true;
4550 }
4551 } else if (detected) {
4552 throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
4553 } else {
4554 state.tag = _tag;
4555 state.anchor = _anchor;
4556 return true;
4557 }
4558 }
4559 if (state.line === _line || state.lineIndent > nodeIndent) {
4560 if (atExplicitKey) {
4561 _keyLine = state.line;
4562 _keyLineStart = state.lineStart;
4563 _keyPos = state.position;
4564 }
4565 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
4566 if (atExplicitKey) {
4567 keyNode = state.result;
4568 } else {
4569 valueNode = state.result;
4570 }
4571 }
4572 if (!atExplicitKey) {
4573 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
4574 keyTag = keyNode = valueNode = null;
4575 }
4576 skipSeparationSpace(state, true, -1);
4577 ch = state.input.charCodeAt(state.position);
4578 }
4579 if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
4580 throwError(state, "bad indentation of a mapping entry");
4581 } else if (state.lineIndent < nodeIndent) {
4582 break;
4583 }
4584 }
4585 if (atExplicitKey) {
4586 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
4587 }
4588 if (detected) {
4589 state.tag = _tag;
4590 state.anchor = _anchor;
4591 state.kind = "mapping";
4592 state.result = _result;
4593 }
4594 return detected;
4595 }
4596 function readTagProperty(state) {
4597 let isVerbatim = false;
4598 let isNamed = false;
4599 let tagHandle;
4600 let tagName;
4601 let ch = state.input.charCodeAt(state.position);
4602 if (ch !== 33) return false;
4603 if (state.tag !== null) {
4604 throwError(state, "duplication of a tag property");
4605 }
4606 ch = state.input.charCodeAt(++state.position);
4607 if (ch === 60) {
4608 isVerbatim = true;
4609 ch = state.input.charCodeAt(++state.position);
4610 } else if (ch === 33) {
4611 isNamed = true;
4612 tagHandle = "!!";
4613 ch = state.input.charCodeAt(++state.position);
4614 } else {
4615 tagHandle = "!";
4616 }
4617 let _position = state.position;
4618 if (isVerbatim) {
4619 do {
4620 ch = state.input.charCodeAt(++state.position);
4621 } while (ch !== 0 && ch !== 62);
4622 if (state.position < state.length) {
4623 tagName = state.input.slice(_position, state.position);
4624 ch = state.input.charCodeAt(++state.position);
4625 } else {
4626 throwError(state, "unexpected end of the stream within a verbatim tag");
4627 }
4628 } else {
4629 while (ch !== 0 && !isWsOrEol(ch)) {
4630 if (ch === 33) {
4631 if (!isNamed) {
4632 tagHandle = state.input.slice(_position - 1, state.position + 1);
4633 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
4634 throwError(state, "named tag handle cannot contain such characters");
4635 }
4636 isNamed = true;
4637 _position = state.position + 1;
4638 } else {
4639 throwError(state, "tag suffix cannot contain exclamation marks");
4640 }
4641 }
4642 ch = state.input.charCodeAt(++state.position);
4643 }
4644 tagName = state.input.slice(_position, state.position);
4645 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
4646 throwError(state, "tag suffix cannot contain flow indicator characters");
4647 }
4648 }
4649 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
4650 throwError(state, "tag name cannot contain such characters: " + tagName);
4651 }
4652 try {
4653 tagName = decodeURIComponent(tagName);
4654 } catch (err) {
4655 throwError(state, "tag name is malformed: " + tagName);
4656 }
4657 if (isVerbatim) {
4658 state.tag = tagName;
4659 } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
4660 state.tag = state.tagMap[tagHandle] + tagName;
4661 } else if (tagHandle === "!") {
4662 state.tag = "!" + tagName;
4663 } else if (tagHandle === "!!") {
4664 state.tag = "tag:yaml.org,2002:" + tagName;
4665 } else {
4666 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
4667 }
4668 return true;
4669 }
4670 function readAnchorProperty(state) {
4671 let ch = state.input.charCodeAt(state.position);
4672 if (ch !== 38) return false;
4673 if (state.anchor !== null) {
4674 throwError(state, "duplication of an anchor property");
4675 }
4676 ch = state.input.charCodeAt(++state.position);
4677 const _position = state.position;
4678 while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
4679 ch = state.input.charCodeAt(++state.position);
4680 }
4681 if (state.position === _position) {
4682 throwError(state, "name of an anchor node must contain at least one character");
4683 }
4684 state.anchor = state.input.slice(_position, state.position);
4685 return true;
4686 }
4687 function readAlias(state) {
4688 let ch = state.input.charCodeAt(state.position);
4689 if (ch !== 42) return false;
4690 ch = state.input.charCodeAt(++state.position);
4691 const _position = state.position;
4692 while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
4693 ch = state.input.charCodeAt(++state.position);
4694 }
4695 if (state.position === _position) {
4696 throwError(state, "name of an alias node must contain at least one character");
4697 }
4698 const alias = state.input.slice(_position, state.position);
4699 if (!_hasOwnProperty.call(state.anchorMap, alias)) {
4700 throwError(state, 'unidentified alias "' + alias + '"');
4701 }
4702 state.result = state.anchorMap[alias];
4703 skipSeparationSpace(state, true, -1);
4704 return true;
4705 }
4706 function tryReadBlockMappingFromProperty(state, propertyStart, nodeIndent, flowIndent) {
4707 const fallbackState = snapshotState(state);
4708 beginAnchorTransaction(state);
4709 restoreState(state, propertyStart);
4710 state.tag = null;
4711 state.anchor = null;
4712 state.kind = null;
4713 state.result = null;
4714 if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === "mapping") {
4715 commitAnchorTransaction(state);
4716 return true;
4717 }
4718 rollbackAnchorTransaction(state);
4719 restoreState(state, fallbackState);
4720 return false;
4721 }
4722 function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
4723 let allowBlockScalars;
4724 let allowBlockCollections;
4725 let indentStatus = 1;
4726 let atNewLine = false;
4727 let hasContent = false;
4728 let propertyStart = null;
4729 let type2;
4730 let flowIndent;
4731 let blockIndent;
4732 if (state.depth >= state.maxDepth) {
4733 throwError(state, "nesting exceeded maxDepth (" + state.maxDepth + ")");
4734 }
4735 state.depth += 1;
4736 if (state.listener !== null) {
4737 state.listener("open", state);
4738 }
4739 state.tag = null;
4740 state.anchor = null;
4741 state.kind = null;
4742 state.result = null;
4743 const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
4744 if (allowToSeek) {
4745 if (skipSeparationSpace(state, true, -1)) {
4746 atNewLine = true;
4747 if (state.lineIndent > parentIndent) {
4748 indentStatus = 1;
4749 } else if (state.lineIndent === parentIndent) {
4750 indentStatus = 0;
4751 } else if (state.lineIndent < parentIndent) {
4752 indentStatus = -1;
4753 }
4754 }
4755 }
4756 if (indentStatus === 1) {
4757 while (true) {
4758 const ch = state.input.charCodeAt(state.position);
4759 const propertyState = snapshotState(state);
4760 if (atNewLine && (ch === 33 && state.tag !== null || ch === 38 && state.anchor !== null)) {
4761 break;
4762 }
4763 if (!readTagProperty(state) && !readAnchorProperty(state)) {
4764 break;
4765 }
4766 if (propertyStart === null) {
4767 propertyStart = propertyState;
4768 }
4769 if (skipSeparationSpace(state, true, -1)) {
4770 atNewLine = true;
4771 allowBlockCollections = allowBlockStyles;
4772 if (state.lineIndent > parentIndent) {
4773 indentStatus = 1;
4774 } else if (state.lineIndent === parentIndent) {
4775 indentStatus = 0;
4776 } else if (state.lineIndent < parentIndent) {
4777 indentStatus = -1;
4778 }
4779 } else {
4780 allowBlockCollections = false;
4781 }
4782 }
4783 }
4784 if (allowBlockCollections) {
4785 allowBlockCollections = atNewLine || allowCompact;
4786 }
4787 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
4788 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
4789 flowIndent = parentIndent;
4790 } else {
4791 flowIndent = parentIndent + 1;
4792 }
4793 blockIndent = state.position - state.lineStart;
4794 if (indentStatus === 1) {
4795 if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
4796 hasContent = true;
4797 } else {
4798 const ch = state.input.charCodeAt(state.position);
4799 if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(
4800 state,
4801 propertyStart,
4802 propertyStart.position - propertyStart.lineStart,
4803 flowIndent
4804 )) {
4805 hasContent = true;
4806 } else if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
4807 hasContent = true;
4808 } else if (readAlias(state)) {
4809 hasContent = true;
4810 if (state.tag !== null || state.anchor !== null) {
4811 throwError(state, "alias node should not have any properties");
4812 }
4813 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
4814 hasContent = true;
4815 if (state.tag === null) {
4816 state.tag = "?";
4817 }
4818 }
4819 if (state.anchor !== null) {
4820 storeAnchor(state, state.anchor, state.result);
4821 }
4822 }
4823 } else if (indentStatus === 0) {
4824 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
4825 }
4826 }
4827 if (state.tag === null) {
4828 if (state.anchor !== null) {
4829 storeAnchor(state, state.anchor, state.result);
4830 }
4831 } else if (state.tag === "?") {
4832 if (state.result !== null && state.kind !== "scalar") {
4833 throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
4834 }
4835 for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
4836 type2 = state.implicitTypes[typeIndex];
4837 if (type2.resolve(state.result)) {
4838 state.result = type2.construct(state.result);
4839 state.tag = type2.tag;
4840 if (state.anchor !== null) {
4841 storeAnchor(state, state.anchor, state.result);
4842 }
4843 break;
4844 }
4845 }
4846 } else if (state.tag !== "!") {
4847 if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {
4848 type2 = state.typeMap[state.kind || "fallback"][state.tag];
4849 } else {
4850 type2 = null;
4851 const typeList = state.typeMap.multi[state.kind || "fallback"];
4852 for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
4853 if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
4854 type2 = typeList[typeIndex];
4855 break;
4856 }
4857 }
4858 }
4859 if (!type2) {
4860 throwError(state, "unknown tag !<" + state.tag + ">");
4861 }
4862 if (state.result !== null && type2.kind !== state.kind) {
4863 throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
4864 }
4865 if (!type2.resolve(state.result, state.tag)) {
4866 throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
4867 } else {
4868 state.result = type2.construct(state.result, state.tag);
4869 if (state.anchor !== null) {
4870 storeAnchor(state, state.anchor, state.result);
4871 }
4872 }
4873 }
4874 if (state.listener !== null) {
4875 state.listener("close", state);
4876 }
4877 state.depth -= 1;
4878 return state.tag !== null || state.anchor !== null || hasContent;
4879 }
4880 function readDocument(state) {
4881 const documentStart = state.position;
4882 let hasDirectives = false;
4883 let ch;
4884 state.version = null;
4885 state.checkLineBreaks = state.legacy;
4886 state.tagMap = /* @__PURE__ */ Object.create(null);
4887 state.anchorMap = /* @__PURE__ */ Object.create(null);
4888 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
4889 skipSeparationSpace(state, true, -1);
4890 ch = state.input.charCodeAt(state.position);
4891 if (state.lineIndent > 0 || ch !== 37) {
4892 break;
4893 }
4894 hasDirectives = true;
4895 ch = state.input.charCodeAt(++state.position);
4896 let _position = state.position;
4897 while (ch !== 0 && !isWsOrEol(ch)) {
4898 ch = state.input.charCodeAt(++state.position);
4899 }
4900 const directiveName = state.input.slice(_position, state.position);
4901 const directiveArgs = [];
4902 if (directiveName.length < 1) {
4903 throwError(state, "directive name must not be less than one character in length");
4904 }
4905 while (ch !== 0) {
4906 while (isWhiteSpace(ch)) {
4907 ch = state.input.charCodeAt(++state.position);
4908 }
4909 if (ch === 35) {
4910 do {
4911 ch = state.input.charCodeAt(++state.position);
4912 } while (ch !== 0 && !isEol(ch));
4913 break;
4914 }
4915 if (isEol(ch)) break;
4916 _position = state.position;
4917 while (ch !== 0 && !isWsOrEol(ch)) {
4918 ch = state.input.charCodeAt(++state.position);
4919 }
4920 directiveArgs.push(state.input.slice(_position, state.position));
4921 }
4922 if (ch !== 0) readLineBreak(state);
4923 if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
4924 directiveHandlers[directiveName](state, directiveName, directiveArgs);
4925 } else {
4926 throwWarning(state, 'unknown document directive "' + directiveName + '"');
4927 }
4928 }
4929 skipSeparationSpace(state, true, -1);
4930 if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
4931 state.position += 3;
4932 skipSeparationSpace(state, true, -1);
4933 } else if (hasDirectives) {
4934 throwError(state, "directives end mark is expected");
4935 }
4936 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
4937 skipSeparationSpace(state, true, -1);
4938 if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
4939 throwWarning(state, "non-ASCII line breaks are interpreted as content");
4940 }
4941 state.documents.push(state.result);
4942 if (state.position === state.lineStart && testDocumentSeparator(state)) {
4943 if (state.input.charCodeAt(state.position) === 46) {
4944 state.position += 3;
4945 skipSeparationSpace(state, true, -1);
4946 }
4947 return;
4948 }
4949 if (state.position < state.length - 1) {
4950 throwError(state, "end of the stream or a document separator is expected");
4951 }
4952 }
4953 function loadDocuments(input, options) {
4954 input = String(input);
4955 options = options || {};
4956 if (input.length !== 0) {
4957 if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
4958 input += "\n";
4959 }
4960 if (input.charCodeAt(0) === 65279) {
4961 input = input.slice(1);
4962 }
4963 }
4964 const state = new State(input, options);
4965 const nullpos = input.indexOf("\0");
4966 if (nullpos !== -1) {
4967 state.position = nullpos;
4968 throwError(state, "null byte is not allowed in input");
4969 }
4970 state.input += "\0";
4971 while (state.input.charCodeAt(state.position) === 32) {
4972 state.lineIndent += 1;
4973 state.position += 1;
4974 }
4975 while (state.position < state.length - 1) {
4976 readDocument(state);
4977 }
4978 return state.documents;
4979 }
4980 function loadAll2(input, iterator, options) {
4981 if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
4982 options = iterator;
4983 iterator = null;
4984 }
4985 const documents = loadDocuments(input, options);
4986 if (typeof iterator !== "function") {
4987 return documents;
4988 }
4989 for (let index = 0, length = documents.length; index < length; index += 1) {
4990 iterator(documents[index]);
4991 }
4992 }
4993 function load2(input, options) {
4994 const documents = loadDocuments(input, options);
4995 if (documents.length === 0) {
4996 return void 0;
4997 } else if (documents.length === 1) {
4998 return documents[0];
4999 }
5000 throw new YAMLException2("expected a single document in the stream, but found more");
5001 }
5002 loader.loadAll = loadAll2;
5003 loader.load = load2;
5004 return loader;
5005 }
5006 function requireDumper() {
5007 if (hasRequiredDumper) return dumper;
5008 hasRequiredDumper = 1;
5009 const common2 = requireCommon();
5010 const YAMLException2 = requireException();
5011 const DEFAULT_SCHEMA2 = require_default();
5012 const _toString = Object.prototype.toString;
5013 const _hasOwnProperty = Object.prototype.hasOwnProperty;
5014 const CHAR_BOM = 65279;
5015 const CHAR_TAB = 9;
5016 const CHAR_LINE_FEED = 10;
5017 const CHAR_CARRIAGE_RETURN = 13;
5018 const CHAR_SPACE = 32;
5019 const CHAR_EXCLAMATION = 33;
5020 const CHAR_DOUBLE_QUOTE = 34;
5021 const CHAR_SHARP = 35;
5022 const CHAR_PERCENT = 37;
5023 const CHAR_AMPERSAND = 38;
5024 const CHAR_SINGLE_QUOTE = 39;
5025 const CHAR_ASTERISK = 42;
5026 const CHAR_COMMA = 44;
5027 const CHAR_MINUS = 45;
5028 const CHAR_COLON = 58;
5029 const CHAR_EQUALS = 61;
5030 const CHAR_GREATER_THAN = 62;
5031 const CHAR_QUESTION = 63;
5032 const CHAR_COMMERCIAL_AT = 64;
5033 const CHAR_LEFT_SQUARE_BRACKET = 91;
5034 const CHAR_RIGHT_SQUARE_BRACKET = 93;
5035 const CHAR_GRAVE_ACCENT = 96;
5036 const CHAR_LEFT_CURLY_BRACKET = 123;
5037 const CHAR_VERTICAL_LINE = 124;
5038 const CHAR_RIGHT_CURLY_BRACKET = 125;
5039 const ESCAPE_SEQUENCES = {};
5040 ESCAPE_SEQUENCES[0] = "\\0";
5041 ESCAPE_SEQUENCES[7] = "\\a";
5042 ESCAPE_SEQUENCES[8] = "\\b";
5043 ESCAPE_SEQUENCES[9] = "\\t";
5044 ESCAPE_SEQUENCES[10] = "\\n";
5045 ESCAPE_SEQUENCES[11] = "\\v";
5046 ESCAPE_SEQUENCES[12] = "\\f";
5047 ESCAPE_SEQUENCES[13] = "\\r";
5048 ESCAPE_SEQUENCES[27] = "\\e";
5049 ESCAPE_SEQUENCES[34] = '\\"';
5050 ESCAPE_SEQUENCES[92] = "\\\\";
5051 ESCAPE_SEQUENCES[133] = "\\N";
5052 ESCAPE_SEQUENCES[160] = "\\_";
5053 ESCAPE_SEQUENCES[8232] = "\\L";
5054 ESCAPE_SEQUENCES[8233] = "\\P";
5055 const DEPRECATED_BOOLEANS_SYNTAX = [
5056 "y",
5057 "Y",
5058 "yes",
5059 "Yes",
5060 "YES",
5061 "on",
5062 "On",
5063 "ON",
5064 "n",
5065 "N",
5066 "no",
5067 "No",
5068 "NO",
5069 "off",
5070 "Off",
5071 "OFF"
5072 ];
5073 const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
5074 function compileStyleMap(schema22, map2) {
5075 if (map2 === null) return {};
5076 const result = {};
5077 const keys = Object.keys(map2);
5078 for (let index = 0, length = keys.length; index < length; index += 1) {
5079 let tag = keys[index];
5080 let style = String(map2[tag]);
5081 if (tag.slice(0, 2) === "!!") {
5082 tag = "tag:yaml.org,2002:" + tag.slice(2);
5083 }
5084 const type2 = schema22.compiledTypeMap["fallback"][tag];
5085 if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
5086 style = type2.styleAliases[style];
5087 }
5088 result[tag] = style;
5089 }
5090 return result;
5091 }
5092 function encodeHex(character) {
5093 let handle;
5094 let length;
5095 const string = character.toString(16).toUpperCase();
5096 if (character <= 255) {
5097 handle = "x";
5098 length = 2;
5099 } else if (character <= 65535) {
5100 handle = "u";
5101 length = 4;
5102 } else if (character <= 4294967295) {
5103 handle = "U";
5104 length = 8;
5105 } else {
5106 throw new YAMLException2("code point within a string may not be greater than 0xFFFFFFFF");
5107 }
5108 return "\\" + handle + common2.repeat("0", length - string.length) + string;
5109 }
5110 const QUOTING_TYPE_SINGLE = 1;
5111 const QUOTING_TYPE_DOUBLE = 2;
5112 function State(options) {
5113 this.schema = options["schema"] || DEFAULT_SCHEMA2;
5114 this.indent = Math.max(1, options["indent"] || 2);
5115 this.noArrayIndent = options["noArrayIndent"] || false;
5116 this.skipInvalid = options["skipInvalid"] || false;
5117 this.flowLevel = common2.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
5118 this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
5119 this.sortKeys = options["sortKeys"] || false;
5120 this.lineWidth = options["lineWidth"] || 80;
5121 this.noRefs = options["noRefs"] || false;
5122 this.noCompatMode = options["noCompatMode"] || false;
5123 this.condenseFlow = options["condenseFlow"] || false;
5124 this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
5125 this.forceQuotes = options["forceQuotes"] || false;
5126 this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
5127 this.implicitTypes = this.schema.compiledImplicit;
5128 this.explicitTypes = this.schema.compiledExplicit;
5129 this.tag = null;
5130 this.result = "";
5131 this.duplicates = [];
5132 this.usedDuplicates = null;
5133 }
5134 function indentString(string, spaces) {
5135 const ind = common2.repeat(" ", spaces);
5136 let position = 0;
5137 let result = "";
5138 const length = string.length;
5139 while (position < length) {
5140 let line;
5141 const next = string.indexOf("\n", position);
5142 if (next === -1) {
5143 line = string.slice(position);
5144 position = length;
5145 } else {
5146 line = string.slice(position, next + 1);
5147 position = next + 1;
5148 }
5149 if (line.length && line !== "\n") result += ind;
5150 result += line;
5151 }
5152 return result;
5153 }
5154 function generateNextLine(state, level) {
5155 return "\n" + common2.repeat(" ", state.indent * level);
5156 }
5157 function testImplicitResolving(state, str2) {
5158 for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {
5159 const type2 = state.implicitTypes[index];
5160 if (type2.resolve(str2)) {
5161 return true;
5162 }
5163 }
5164 return false;
5165 }
5166 function isWhitespace(c) {
5167 return c === CHAR_SPACE || c === CHAR_TAB;
5168 }
5169 function isPrintable(c) {
5170 return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
5171 }
5172 function isNsCharOrWhitespace(c) {
5173 return isPrintable(c) && c !== CHAR_BOM && // - b-char
5174 c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
5175 }
5176 function isPlainSafe(c, prev, inblock) {
5177 const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
5178 const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
5179 return (
5180 // ns-plain-safe
5181 (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && // - c-flow-indicator
5182 c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && // ns-plain-char
5183 c !== CHAR_SHARP && // false on '#'
5184 !(prev === CHAR_COLON && !cIsNsChar) || // false on ': '
5185 isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || // change to true on '[^ ]#'
5186 prev === CHAR_COLON && cIsNsChar
5187 );
5188 }
5189 function isPlainSafeFirst(c) {
5190 return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && // - s-white
5191 // - (c-indicator ::=
5192 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
5193 c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
5194 c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && // | “%” | “@” | “`”)
5195 c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
5196 }
5197 function isPlainSafeLast(c) {
5198 return !isWhitespace(c) && c !== CHAR_COLON;
5199 }
5200 function codePointAt(string, pos) {
5201 const first = string.charCodeAt(pos);
5202 let second;
5203 if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
5204 second = string.charCodeAt(pos + 1);
5205 if (second >= 56320 && second <= 57343) {
5206 return (first - 55296) * 1024 + second - 56320 + 65536;
5207 }
5208 }
5209 return first;
5210 }
5211 function needIndentIndicator(string) {
5212 const leadingSpaceRe = /^\n* /;
5213 return leadingSpaceRe.test(string);
5214 }
5215 const STYLE_PLAIN = 1;
5216 const STYLE_SINGLE = 2;
5217 const STYLE_LITERAL = 3;
5218 const STYLE_FOLDED = 4;
5219 const STYLE_DOUBLE = 5;
5220 function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
5221 let i2;
5222 let char = 0;
5223 let prevChar = null;
5224 let hasLineBreak = false;
5225 let hasFoldableLine = false;
5226 const shouldTrackWidth = lineWidth !== -1;
5227 let previousLineBreak = -1;
5228 let plain2 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
5229 if (singleLineOnly || forceQuotes) {
5230 for (i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
5231 char = codePointAt(string, i2);
5232 if (!isPrintable(char)) {
5233 return STYLE_DOUBLE;
5234 }
5235 plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
5236 prevChar = char;
5237 }
5238 } else {
5239 for (i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
5240 char = codePointAt(string, i2);
5241 if (char === CHAR_LINE_FEED) {
5242 hasLineBreak = true;
5243 if (shouldTrackWidth) {
5244 hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
5245 i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
5246 previousLineBreak = i2;
5247 }
5248 } else if (!isPrintable(char)) {
5249 return STYLE_DOUBLE;
5250 }
5251 plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
5252 prevChar = char;
5253 }
5254 hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
5255 }
5256 if (!hasLineBreak && !hasFoldableLine) {
5257 if (plain2 && !forceQuotes && !testAmbiguousType(string)) {
5258 return STYLE_PLAIN;
5259 }
5260 return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
5261 }
5262 if (indentPerLevel > 9 && needIndentIndicator(string)) {
5263 return STYLE_DOUBLE;
5264 }
5265 if (!forceQuotes) {
5266 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
5267 }
5268 return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
5269 }
5270 function writeScalar(state, string, level, iskey, inblock) {
5271 state.dump = (function() {
5272 if (string.length === 0) {
5273 return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
5274 }
5275 if (!state.noCompatMode) {
5276 if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
5277 return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
5278 }
5279 }
5280 const indent = state.indent * Math.max(1, level);
5281 const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
5282 const singleLineOnly = iskey || // No block styles in flow mode.
5283 state.flowLevel > -1 && level >= state.flowLevel;
5284 function testAmbiguity(string2) {
5285 return testImplicitResolving(state, string2);
5286 }
5287 switch (chooseScalarStyle(
5288 string,
5289 singleLineOnly,
5290 state.indent,
5291 lineWidth,
5292 testAmbiguity,
5293 state.quotingType,
5294 state.forceQuotes && !iskey,
5295 inblock
5296 )) {
5297 case STYLE_PLAIN:
5298 return string;
5299 case STYLE_SINGLE:
5300 return "'" + string.replace(/'/g, "''") + "'";
5301 case STYLE_LITERAL:
5302 return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
5303 case STYLE_FOLDED:
5304 return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
5305 case STYLE_DOUBLE:
5306 return '"' + escapeString(string) + '"';
5307 default:
5308 throw new YAMLException2("impossible error: invalid scalar style");
5309 }
5310 })();
5311 }
5312 function blockHeader(string, indentPerLevel) {
5313 const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
5314 const clip = string[string.length - 1] === "\n";
5315 const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
5316 const chomp = keep ? "+" : clip ? "" : "-";
5317 return indentIndicator + chomp + "\n";
5318 }
5319 function dropEndingNewline(string) {
5320 return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
5321 }
5322 function foldString(string, width) {
5323 const lineRe = /(\n+)([^\n]*)/g;
5324 let result = (function() {
5325 let nextLF = string.indexOf("\n");
5326 nextLF = nextLF !== -1 ? nextLF : string.length;
5327 lineRe.lastIndex = nextLF;
5328 return foldLine(string.slice(0, nextLF), width);
5329 })();
5330 let prevMoreIndented = string[0] === "\n" || string[0] === " ";
5331 let moreIndented;
5332 let match;
5333 while (match = lineRe.exec(string)) {
5334 const prefix = match[1];
5335 const line = match[2];
5336 moreIndented = line[0] === " ";
5337 result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
5338 prevMoreIndented = moreIndented;
5339 }
5340 return result;
5341 }
5342 function foldLine(line, width) {
5343 if (line === "" || line[0] === " ") return line;
5344 const breakRe = / [^ ]/g;
5345 let match;
5346 let start = 0;
5347 let end;
5348 let curr = 0;
5349 let next = 0;
5350 let result = "";
5351 while (match = breakRe.exec(line)) {
5352 next = match.index;
5353 if (next - start > width) {
5354 end = curr > start ? curr : next;
5355 result += "\n" + line.slice(start, end);
5356 start = end + 1;
5357 }
5358 curr = next;
5359 }
5360 result += "\n";
5361 if (line.length - start > width && curr > start) {
5362 result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
5363 } else {
5364 result += line.slice(start);
5365 }
5366 return result.slice(1);
5367 }
5368 function escapeString(string) {
5369 let result = "";
5370 let char = 0;
5371 for (let i2 = 0; i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
5372 char = codePointAt(string, i2);
5373 const escapeSeq = ESCAPE_SEQUENCES[char];
5374 if (!escapeSeq && isPrintable(char)) {
5375 result += string[i2];
5376 if (char >= 65536) result += string[i2 + 1];
5377 } else {
5378 result += escapeSeq || encodeHex(char);
5379 }
5380 }
5381 return result;
5382 }
5383 function writeFlowSequence(state, level, object) {
5384 let _result = "";
5385 const _tag = state.tag;
5386 for (let index = 0, length = object.length; index < length; index += 1) {
5387 let value = object[index];
5388 if (state.replacer) {
5389 value = state.replacer.call(object, String(index), value);
5390 }
5391 if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
5392 if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
5393 _result += state.dump;
5394 }
5395 }
5396 state.tag = _tag;
5397 state.dump = "[" + _result + "]";
5398 }
5399 function writeBlockSequence(state, level, object, compact) {
5400 let _result = "";
5401 const _tag = state.tag;
5402 for (let index = 0, length = object.length; index < length; index += 1) {
5403 let value = object[index];
5404 if (state.replacer) {
5405 value = state.replacer.call(object, String(index), value);
5406 }
5407 if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
5408 if (!compact || _result !== "") {
5409 _result += generateNextLine(state, level);
5410 }
5411 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5412 _result += "-";
5413 } else {
5414 _result += "- ";
5415 }
5416 _result += state.dump;
5417 }
5418 }
5419 state.tag = _tag;
5420 state.dump = _result || "[]";
5421 }
5422 function writeFlowMapping(state, level, object) {
5423 let _result = "";
5424 const _tag = state.tag;
5425 const objectKeyList = Object.keys(object);
5426 for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
5427 let pairBuffer = "";
5428 if (_result !== "") pairBuffer += ", ";
5429 if (state.condenseFlow) pairBuffer += '"';
5430 const objectKey = objectKeyList[index];
5431 let objectValue = object[objectKey];
5432 if (state.replacer) {
5433 objectValue = state.replacer.call(object, objectKey, objectValue);
5434 }
5435 if (!writeNode(state, level, objectKey, false, false)) {
5436 continue;
5437 }
5438 if (state.dump.length > 1024) pairBuffer += "? ";
5439 pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
5440 if (!writeNode(state, level, objectValue, false, false)) {
5441 continue;
5442 }
5443 pairBuffer += state.dump;
5444 _result += pairBuffer;
5445 }
5446 state.tag = _tag;
5447 state.dump = "{" + _result + "}";
5448 }
5449 function writeBlockMapping(state, level, object, compact) {
5450 let _result = "";
5451 const _tag = state.tag;
5452 const objectKeyList = Object.keys(object);
5453 if (state.sortKeys === true) {
5454 objectKeyList.sort();
5455 } else if (typeof state.sortKeys === "function") {
5456 objectKeyList.sort(state.sortKeys);
5457 } else if (state.sortKeys) {
5458 throw new YAMLException2("sortKeys must be a boolean or a function");
5459 }
5460 for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
5461 let pairBuffer = "";
5462 if (!compact || _result !== "") {
5463 pairBuffer += generateNextLine(state, level);
5464 }
5465 const objectKey = objectKeyList[index];
5466 let objectValue = object[objectKey];
5467 if (state.replacer) {
5468 objectValue = state.replacer.call(object, objectKey, objectValue);
5469 }
5470 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
5471 continue;
5472 }
5473 const explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
5474 if (explicitPair) {
5475 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5476 pairBuffer += "?";
5477 } else {
5478 pairBuffer += "? ";
5479 }
5480 }
5481 pairBuffer += state.dump;
5482 if (explicitPair) {
5483 pairBuffer += generateNextLine(state, level);
5484 }
5485 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
5486 continue;
5487 }
5488 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
5489 pairBuffer += ":";
5490 } else {
5491 pairBuffer += ": ";
5492 }
5493 pairBuffer += state.dump;
5494 _result += pairBuffer;
5495 }
5496 state.tag = _tag;
5497 state.dump = _result || "{}";
5498 }
5499 function detectType(state, object, explicit) {
5500 const typeList = explicit ? state.explicitTypes : state.implicitTypes;
5501 for (let index = 0, length = typeList.length; index < length; index += 1) {
5502 const type2 = typeList[index];
5503 if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
5504 if (explicit) {
5505 if (type2.multi && type2.representName) {
5506 state.tag = type2.representName(object);
5507 } else {
5508 state.tag = type2.tag;
5509 }
5510 } else {
5511 state.tag = "?";
5512 }
5513 if (type2.represent) {
5514 const style = state.styleMap[type2.tag] || type2.defaultStyle;
5515 let _result;
5516 if (_toString.call(type2.represent) === "[object Function]") {
5517 _result = type2.represent(object, style);
5518 } else if (_hasOwnProperty.call(type2.represent, style)) {
5519 _result = type2.represent[style](object, style);
5520 } else {
5521 throw new YAMLException2("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
5522 }
5523 state.dump = _result;
5524 }
5525 return true;
5526 }
5527 }
5528 return false;
5529 }
5530 function writeNode(state, level, object, block, compact, iskey, isblockseq) {
5531 state.tag = null;
5532 state.dump = object;
5533 if (!detectType(state, object, false)) {
5534 detectType(state, object, true);
5535 }
5536 const type2 = _toString.call(state.dump);
5537 const inblock = block;
5538 if (block) {
5539 block = state.flowLevel < 0 || state.flowLevel > level;
5540 }
5541 const objectOrArray = type2 === "[object Object]" || type2 === "[object Array]";
5542 let duplicateIndex;
5543 let duplicate;
5544 if (objectOrArray) {
5545 duplicateIndex = state.duplicates.indexOf(object);
5546 duplicate = duplicateIndex !== -1;
5547 }
5548 if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
5549 compact = false;
5550 }
5551 if (duplicate && state.usedDuplicates[duplicateIndex]) {
5552 state.dump = "*ref_" + duplicateIndex;
5553 } else {
5554 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
5555 state.usedDuplicates[duplicateIndex] = true;
5556 }
5557 if (type2 === "[object Object]") {
5558 if (block && Object.keys(state.dump).length !== 0) {
5559 writeBlockMapping(state, level, state.dump, compact);
5560 if (duplicate) {
5561 state.dump = "&ref_" + duplicateIndex + state.dump;
5562 }
5563 } else {
5564 writeFlowMapping(state, level, state.dump);
5565 if (duplicate) {
5566 state.dump = "&ref_" + duplicateIndex + " " + state.dump;
5567 }
5568 }
5569 } else if (type2 === "[object Array]") {
5570 if (block && state.dump.length !== 0) {
5571 if (state.noArrayIndent && !isblockseq && level > 0) {
5572 writeBlockSequence(state, level - 1, state.dump, compact);
5573 } else {
5574 writeBlockSequence(state, level, state.dump, compact);
5575 }
5576 if (duplicate) {
5577 state.dump = "&ref_" + duplicateIndex + state.dump;
5578 }
5579 } else {
5580 writeFlowSequence(state, level, state.dump);
5581 if (duplicate) {
5582 state.dump = "&ref_" + duplicateIndex + " " + state.dump;
5583 }
5584 }
5585 } else if (type2 === "[object String]") {
5586 if (state.tag !== "?") {
5587 writeScalar(state, state.dump, level, iskey, inblock);
5588 }
5589 } else if (type2 === "[object Undefined]") {
5590 return false;
5591 } else {
5592 if (state.skipInvalid) return false;
5593 throw new YAMLException2("unacceptable kind of an object to dump " + type2);
5594 }
5595 if (state.tag !== null && state.tag !== "?") {
5596 let tagStr = encodeURI(
5597 state.tag[0] === "!" ? state.tag.slice(1) : state.tag
5598 ).replace(/!/g, "%21");
5599 if (state.tag[0] === "!") {
5600 tagStr = "!" + tagStr;
5601 } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
5602 tagStr = "!!" + tagStr.slice(18);
5603 } else {
5604 tagStr = "!<" + tagStr + ">";
5605 }
5606 state.dump = tagStr + " " + state.dump;
5607 }
5608 }
5609 return true;
5610 }
5611 function getDuplicateReferences(object, state) {
5612 const objects = [];
5613 const duplicatesIndexes = [];
5614 inspectNode(object, objects, duplicatesIndexes);
5615 const length = duplicatesIndexes.length;
5616 for (let index = 0; index < length; index += 1) {
5617 state.duplicates.push(objects[duplicatesIndexes[index]]);
5618 }
5619 state.usedDuplicates = new Array(length);
5620 }
5621 function inspectNode(object, objects, duplicatesIndexes) {
5622 if (object !== null && typeof object === "object") {
5623 const index = objects.indexOf(object);
5624 if (index !== -1) {
5625 if (duplicatesIndexes.indexOf(index) === -1) {
5626 duplicatesIndexes.push(index);
5627 }
5628 } else {
5629 objects.push(object);
5630 if (Array.isArray(object)) {
5631 for (let i2 = 0, length = object.length; i2 < length; i2 += 1) {
5632 inspectNode(object[i2], objects, duplicatesIndexes);
5633 }
5634 } else {
5635 const objectKeyList = Object.keys(object);
5636 for (let i2 = 0, length = objectKeyList.length; i2 < length; i2 += 1) {
5637 inspectNode(object[objectKeyList[i2]], objects, duplicatesIndexes);
5638 }
5639 }
5640 }
5641 }
5642 }
5643 function dump2(input, options) {
5644 options = options || {};
5645 const state = new State(options);
5646 if (!state.noRefs) getDuplicateReferences(input, state);
5647 let value = input;
5648 if (state.replacer) {
5649 value = state.replacer.call({ "": value }, "", value);
5650 }
5651 if (writeNode(state, 0, value, true, true)) return state.dump + "\n";
5652 return "";
5653 }
5654 dumper.dump = dump2;
5655 return dumper;
5656 }
5657 function requireJsYaml() {
5658 if (hasRequiredJsYaml) return jsYaml;
5659 hasRequiredJsYaml = 1;
5660 const loader2 = requireLoader();
5661 const dumper2 = requireDumper();
5662 function renamed(from, to) {
5663 return function() {
5664 throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
5665 };
5666 }
5667 jsYaml.Type = requireType();
5668 jsYaml.Schema = requireSchema();
5669 jsYaml.FAILSAFE_SCHEMA = requireFailsafe();
5670 jsYaml.JSON_SCHEMA = requireJson();
5671 jsYaml.CORE_SCHEMA = requireCore();
5672 jsYaml.DEFAULT_SCHEMA = require_default();
5673 jsYaml.load = loader2.load;
5674 jsYaml.loadAll = loader2.loadAll;
5675 jsYaml.dump = dumper2.dump;
5676 jsYaml.YAMLException = requireException();
5677 jsYaml.types = {
5678 binary: requireBinary(),
5679 float: requireFloat(),
5680 map: requireMap(),
5681 null: require_null(),
5682 pairs: requirePairs(),
5683 set: requireSet(),
5684 timestamp: requireTimestamp(),
5685 bool: requireBool(),
5686 int: requireInt(),
5687 merge: requireMerge(),
5688 omap: requireOmap(),
5689 seq: requireSeq(),
5690 str: requireStr()
5691 };
5692 jsYaml.safeLoad = renamed("safeLoad", "load");
5693 jsYaml.safeLoadAll = renamed("safeLoadAll", "loadAll");
5694 jsYaml.safeDump = renamed("safeDump", "dump");
5695 return jsYaml;
5696 }
5697 var jsYaml, loader, common, hasRequiredCommon, exception, hasRequiredException, snippet, hasRequiredSnippet, type, hasRequiredType, schema, hasRequiredSchema, str, hasRequiredStr, seq, hasRequiredSeq, map, hasRequiredMap, failsafe, hasRequiredFailsafe, _null, hasRequired_null, bool, hasRequiredBool, int, hasRequiredInt, float, hasRequiredFloat, json, hasRequiredJson, core, hasRequiredCore, timestamp, hasRequiredTimestamp, merge, hasRequiredMerge, binary, hasRequiredBinary, omap, hasRequiredOmap, pairs, hasRequiredPairs, set, hasRequiredSet, _default, hasRequired_default, hasRequiredLoader, dumper, hasRequiredDumper, hasRequiredJsYaml, jsYamlExports, yaml, Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump;
5698 var init_js_yaml = __esm({
5699 "node_modules/js-yaml/dist/js-yaml.mjs"() {
5700 jsYaml = {};
5701 loader = {};
5702 common = {};
5703 dumper = {};
5704 jsYamlExports = requireJsYaml();
5705 yaml = /* @__PURE__ */ getDefaultExportFromCjs(jsYamlExports);
5706 ({
5707 Type,
5708 Schema,
5709 FAILSAFE_SCHEMA,
5710 JSON_SCHEMA,
5711 CORE_SCHEMA,
5712 DEFAULT_SCHEMA,
5713 load,
5714 loadAll,
5715 dump,
5716 YAMLException,
5717 types,
5718 safeLoad,
5719 safeLoadAll,
5720 safeDump
5721 } = yaml);
5722 }
5723 });
5724
5725 // src/dsh/upstream/include/src/index.ts
5726 import { extname } from "node:path";
5727 import { access, constants, readFile, rename, writeFile } from "node:fs/promises";
5728 import { setTimeout as delay } from "node:timers/promises";
5729 import { fileURLToPath, pathToFileURL } from "node:url";
5730 function retryableWriteError(error) {
5731 const code = error?.code;
5732 return code === "EACCES" || code === "EBUSY" || code === "EPERM";
5733 }
5734 function applyEntryPatches(data2, patches, warn) {
5735 if (!patches?.length) return [...data2];
5736 data2 = structuredClone(data2);
5737 const entryMap = /* @__PURE__ */ new Map();
5738 const buildMap = (entries) => {
5739 for (const entry of entries) {
5740 if (entry.id) entryMap.set(entry.id, entry);
5741 if (entry.group && Array.isArray(entry.config)) {
5742 buildMap(entry.config);
5743 }
5744 }
5745 };
5746 buildMap(data2);
5747 for (const patch of patches) {
5748 const { id, insert, name, ...overrides } = patch;
5749 if (insert) {
5750 if (id) {
5751 const target2 = entryMap.get(id);
5752 if (!target2) {
5753 warn("patch insert: entry %C not found", id);
5754 continue;
5755 }
5756 if (!target2.group) {
5757 warn("patch insert: entry %C is not a group", id);
5758 continue;
5759 }
5760 if (!Array.isArray(target2.config)) target2.config = [];
5761 target2.config.push(...insert);
5762 } else {
5763 data2.push(...insert);
5764 }
5765 buildMap(insert);
5766 continue;
5767 }
5768 if (!id) {
5769 warn("patch: id is required for non-insert patches");
5770 continue;
5771 }
5772 const target = entryMap.get(id);
5773 if (!target) {
5774 warn("patch: entry %C not found", id);
5775 continue;
5776 }
5777 if (name && name !== target.name) {
5778 warn("patch: name mismatch for %C (expected %C, got %C), skipping", id, target.name, name);
5779 continue;
5780 }
5781 for (const [key, value] of Object.entries(overrides)) {
5782 if (key === "id") continue;
5783 target[key] = value;
5784 }
5785 }
5786 return data2;
5787 }
5788 var JsExpr, entryListSchema, schema2, writable, supported, WRITE_RETRY_LIMIT, WRITE_RETRY_DELAY_MS, Include;
5789 var init_src2 = __esm({
5790 "src/dsh/upstream/include/src/index.ts"() {
5791 "use strict";
5792 init_src();
5793 init_lib2();
5794 init_js_yaml();
5795 JsExpr = new Type("tag:yaml.org,2002:js", {
5796 kind: "scalar",
5797 resolve: (data2) => typeof data2 === "string",
5798 construct: (data2) => ({ __jsExpr: data2 }),
5799 predicate: isJsExpr,
5800 represent: (data2) => data2.__jsExpr
5801 });
5802 entryListSchema = JSON_SCHEMA.extend(JsExpr);
5803 schema2 = entryListSchema;
5804 writable = {
5805 ".json": "application/json",
5806 ".yaml": "application/yaml",
5807 ".yml": "application/yaml"
5808 };
5809 supported = new Set(Object.keys(writable));
5810 WRITE_RETRY_LIMIT = 10;
5811 WRITE_RETRY_DELAY_MS = 50;
5812 Include = class extends EntryTree {
5813 constructor(ctx, config) {
5814 super(ctx);
5815 this.config = config;
5816 this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false;
5817 this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl));
5818 const ext = extname(this.filename);
5819 if (!supported.has(ext)) {
5820 throw new Error(`extension "${ext}" not supported`);
5821 }
5822 this.type = writable[ext];
5823 this.readonly = !this.type;
5824 this.ctx.baseUrl = new URL(".", pathToFileURL(this.filename)).href;
5825 ctx.on("internal/update", (config2, _, next) => {
5826 if (config2.path !== this.config.path) return next();
5827 this.config = config2;
5828 this.root.update(this.applyPatches(this.data, config2.patches)).catch((error) => {
5829 this.ctx.logger.warn("config update at %C failed", this.filename);
5830 this.ctx.logger.warn(error);
5831 });
5832 });
5833 }
5834 config;
5835 static inject = ["loader"];
5836 // Tree-carrier marker (the Group plugin declares the same): this config is
5837 // entry and patch lists, so the Loader's `internal/config` interpolation
5838 // keeps it literal — a `!!js` expression inside a nested row's config
5839 // belongs to that row's fiber, resolving lazily in the row's own context.
5840 // Include's own fields (`path`, `enableLogs`) therefore stay literal too.
5841 static [EntryGroup.key] = true;
5842 filename;
5843 type;
5844 readonly;
5845 content;
5846 data;
5847 writeTask;
5848 pendingWrite;
5849 writeQueue = Promise.resolve();
5850 async checkAccess() {
5851 if (!this.type) return;
5852 try {
5853 await access(this.filename, constants.W_OK);
5854 } catch {
5855 this.readonly = true;
5856 }
5857 }
5858 async read(forced = false) {
5859 const content = await readFile(this.filename, "utf8");
5860 if (!forced && this.content === content) return false;
5861 let data2;
5862 if (this.type === "application/yaml") {
5863 data2 = load(content, { schema: entryListSchema });
5864 } else if (this.type === "application/json") {
5865 data2 = JSON.parse(content);
5866 } else {
5867 const module = await import(
5868 /* @vite-ignore */
5869 this.filename
5870 );
5871 data2 = module.default || module;
5872 }
5873 if (!Array.isArray(data2)) {
5874 throw new TypeError(`config file must be a top-level array of entries: ${this.filename}`);
5875 }
5876 this.content = content;
5877 this.data = data2;
5878 await this.checkAccess();
5879 return true;
5880 }
5881 applyPatches(data2, patches = this.config.patches) {
5882 return applyEntryPatches(data2, patches, (message, ...args) => {
5883 this.ctx.root.logger?.("loader").warn(message, ...args);
5884 });
5885 }
5886 async *[Service.init]() {
5887 try {
5888 await this.read();
5889 } catch (error) {
5890 if (error?.code !== "ENOENT") throw error;
5891 if (this.config.initial) {
5892 await this._writeFile(this.config.initial);
5893 await this.read(true);
5894 } else {
5895 throw new Error(`config file not found: ${this.filename}`);
5896 }
5897 }
5898 yield () => this.stop();
5899 await this.root.update(this.applyPatches(this.data));
5900 }
5901 async stop() {
5902 try {
5903 await this.flushWrite();
5904 } finally {
5905 this.root.stop();
5906 await this.flushWrite();
5907 }
5908 }
5909 /**
5910 * Re-read the file and refresh child entries when content changed. An
5911 * unreadable or unparsable file logs a warning and keeps the last good
5912 * tree: a hot-reload of a live app must never take the process down.
5913 */
5914 async refresh() {
5915 try {
5916 if (!await this.read()) return;
5917 await this.root.update(this.applyPatches(this.data));
5918 } catch (error) {
5919 this.ctx.logger.warn("config reload at %C failed; keeping the running tree", this.filename);
5920 this.ctx.logger.warn(error);
5921 }
5922 }
5923 async _writeFile(config) {
5924 if (this.readonly) {
5925 throw new Error(`cannot overwrite readonly config`);
5926 }
5927 if (this.type === "application/yaml") {
5928 this.content = dump(config, { schema: schema2 });
5929 } else if (this.type === "application/json") {
5930 this.content = JSON.stringify(config, null, 2);
5931 }
5932 await writeFile(this.filename + ".tmp", this.content);
5933 for (let retry = 0; ; retry++) {
5934 try {
5935 await rename(this.filename + ".tmp", this.filename);
5936 return;
5937 } catch (error) {
5938 if (!retryableWriteError(error) || retry >= WRITE_RETRY_LIMIT) throw error;
5939 await delay((retry + 1) * WRITE_RETRY_DELAY_MS);
5940 }
5941 }
5942 }
5943 writeFile(config) {
5944 clearTimeout(this.writeTask);
5945 this.pendingWrite = config;
5946 this.writeTask = setTimeout(() => {
5947 void this.flushWrite();
5948 }, 0);
5949 }
5950 flushWrite() {
5951 clearTimeout(this.writeTask);
5952 this.writeTask = void 0;
5953 const config = this.pendingWrite;
5954 this.pendingWrite = void 0;
5955 if (config === void 0) return this.writeQueue;
5956 const run = this.writeQueue.then(
5957 () => this._writeFile(config),
5958 () => this._writeFile(config)
5959 );
5960 this.writeQueue = run;
5961 void run.catch((error) => {
5962 this.ctx.root.logger?.("loader").warn("failed to write config file %C", this.filename);
5963 this.ctx.root.logger?.("loader").warn(error);
5964 });
5965 return run;
5966 }
5967 /** Schedule a write of the current root entry data. */
5968 write() {
5969 this.context.emit("loader/config-update");
5970 return this.writeFile(this.root.data);
5971 }
5972 };
5973 }
5974 });
5975
5976 // src/json.ts
5977 function isJson(value, depth = 0) {
5978 if (depth > 64) return false;
5979 if (value === null) return true;
5980 switch (typeof value) {
5981 case "boolean":
5982 case "string":
5983 return true;
5984 case "number":
5985 return Number.isFinite(value);
5986 case "object": {
5987 const array = Array.isArray(value);
5988 if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
5989 const keys = Reflect.ownKeys(value);
5990 if (array && keys.length !== value.length + 1) return false;
5991 for (const key of keys) {
5992 if (array && key === "length") continue;
5993 if (typeof key !== "string") return false;
5994 if (array && (!/^(0|[1-9]\d*)$/u.test(key) || Number(key) >= value.length)) return false;
5995 const descriptor = Object.getOwnPropertyDescriptor(value, key);
5996 if (!descriptor.enumerable || !("value" in descriptor) || !isJson(descriptor.value, depth + 1)) return false;
5997 }
5998 return true;
5999 }
6000 default:
6001 return false;
6002 }
6003 }
6004 var init_json = __esm({
6005 "src/json.ts"() {
6006 "use strict";
6007 }
6008 });
6009
6010 // src/shims/mcp.ts
6011 function normalizeMcp(value) {
6012 if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((k) => k !== "serverName" && k !== "server")) throw new TypeError("MCP needs serverName and server");
6013 const { serverName, server } = value;
6014 if (typeof serverName !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/.test(serverName) || !server || Array.isArray(server) || typeof server !== "object" || !isJson(server)) throw new TypeError("MCP definition must be bounded plain JSON");
6015 for (const key of ["headers", "env"]) if (server[key] !== void 0 && (!server[key] || typeof server[key] !== "object" || Array.isArray(server[key]) || Object.keys(server[key]).length)) throw new TypeError("MCP credentials remain under Rust authentication authority");
6016 if (typeof server.url === "string") {
6017 const url = new URL(server.url);
6018 if (url.username || url.password || url.search || url.hash) throw new TypeError("MCP endpoint credentials and query data remain under Rust authority");
6019 }
6020 if (Buffer.byteLength(JSON.stringify(server)) > 64 * 1024) throw new RangeError("MCP definition exceeds 64 KiB");
6021 return Object.freeze({ serverName, server: structuredClone(server) });
6022 }
6023 var init_mcp = __esm({
6024 "src/shims/mcp.ts"() {
6025 "use strict";
6026 init_json();
6027 init_owned();
6028 }
6029 });
6030
6031 // src/dsh/mcp.ts
6032 function reviewedMcpModule() {
6033 return {
6034 name: "codewhale-reviewed-mcp",
6035 inject: ["mcp"],
6036 apply(ctx, config) {
6037 if (!config || Array.isArray(config) || Object.keys(config).some((k) => !["transport", "serverName", "command", "args", "env", "cwd", "url", "headers", "toolCallTimeoutMs", "failOnStartupError"].includes(k))) throw new Error("MCP row uses unsupported configuration; Core owns reconnect and instruction bounds");
6038 if (typeof config.serverName !== "string") throw new Error("MCP serverName must be literal");
6039 const options = {};
6040 if (config.toolCallTimeoutMs !== void 0) {
6041 const timeout = config.toolCallTimeoutMs;
6042 if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1e3 || timeout > 864e5 || timeout % 1e3 !== 0) throw new Error("MCP timeout must be whole seconds within Core bounds");
6043 options.execute_timeout = timeout / 1e3;
6044 }
6045 if (config.failOnStartupError === true) throw new Error("failOnStartupError requires explicit Core MCP connection qualification before activation");
6046 if (config.failOnStartupError !== void 0 && config.failOnStartupError !== false) throw new Error("MCP startup gate must be a boolean");
6047 let server;
6048 if (config.transport === "stdio") {
6049 const cwd = config.cwd ?? "";
6050 if (typeof cwd !== "string" || cwd !== "" && cwd !== "." && (!cwd || /[\\:\u0000-\u001f]/u.test(cwd) || cwd.split("/").some((p) => !p || p === "." || p === ".."))) throw new Error("MCP cwd must be a reviewed bundle-relative directory");
6051 server = { type: "stdio", command: config.command, args: config.args ?? [], env: config.env ?? {}, cwd: cwd === "" || cwd === "." ? "source" : `source/${cwd}` };
6052 } else if (config.transport === "streamable-http" || config.transport === "sse") server = { type: config.transport, url: config.url, headers: config.headers ?? {} };
6053 else throw new Error("MCP transport must be stdio, streamable-http or sse");
6054 if (Object.keys(options).length) server.extensions = { "net.codewhale": options };
6055 ctx.mcp.registerServer(normalizeMcp({ serverName: config.serverName, server }));
6056 }
6057 };
6058 }
6059 var init_mcp2 = __esm({
6060 "src/dsh/mcp.ts"() {
6061 "use strict";
6062 init_mcp();
6063 }
6064 });
6065
6066 // src/shims/skills.ts
6067 function normalizeSkillRoot(value) {
6068 if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).some((key) => key !== "path")) throw new TypeError("skill root supports only path");
6069 const { path } = value;
6070 if (typeof path !== "string" || !path || Buffer.byteLength(path, "utf8") > 512 || /[\\:\u0000-\u001f\u007f-\u009f]/u.test(path) || path.split("/").some((part) => !part || part === "." || part === "..")) {
6071 throw new TypeError("skill root path must be a bounded bundle-relative path with normal slash-separated components");
6072 }
6073 return Object.freeze({ path });
6074 }
6075 var init_skills = __esm({
6076 "src/shims/skills.ts"() {
6077 "use strict";
6078 init_owned();
6079 }
6080 });
6081
6082 // src/dsh/skill-filesystem.ts
6083 function reviewedSkillModule() {
6084 return { name: "codewhale-reviewed-skills", inject: ["skills"], apply(ctx, config) {
6085 if (!config || Array.isArray(config) || Object.keys(config).some((k) => !["providerName", "includeDefaultRoots", "customSkillDirs", "watch"].includes(k))) throw new Error("filesystem row requires reviewed roots; ambient roots and watcher controls are unsupported");
6086 if (config.includeDefaultRoots !== false || config.watch !== false) throw new Error("filesystem row must explicitly disable default roots and watchers");
6087 if (config.providerName !== void 0 && (typeof config.providerName !== "string" || !config.providerName || config.providerName.length > 64)) throw new Error("skill providerName must be bounded");
6088 if (!Array.isArray(config.customSkillDirs) || !config.customSkillDirs.length || config.customSkillDirs.length > 8) throw new Error("filesystem row needs 1–8 reviewed roots");
6089 const roots = config.customSkillDirs.map((path) => normalizeSkillRoot({ path }));
6090 const seen = /* @__PURE__ */ new Set();
6091 for (const { path } of roots) {
6092 if (seen.has(path)) throw new Error("duplicate filesystem root");
6093 seen.add(path);
6094 }
6095 for (const { path } of roots) ctx.skills.registerRoot({ path: `source/${path}` });
6096 } };
6097 }
6098 var init_skill_filesystem = __esm({
6099 "src/dsh/skill-filesystem.ts"() {
6100 "use strict";
6101 init_skills();
6102 }
6103 });
6104
6105 // src/dsh/canonical-path.ts
6106 import { realpathSync } from "node:fs";
6107 import { posix, win32 } from "node:path";
6108 function canonicalPath(path, platform = process.platform) {
6109 if (platform !== "win32") return realpathSync(path);
6110 try {
6111 return stripVerbatim(realpathSync.native(path), platform);
6112 } catch (error) {
6113 const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
6114 if (code === "EPERM" || code === "EACCES") {
6115 return stripVerbatim(win32.normalize(path), platform);
6116 }
6117 throw error;
6118 }
6119 }
6120 function stripVerbatim(path, platform = process.platform) {
6121 if (platform !== "win32") return path;
6122 if (/^[\\/]{2}\?[\\/]UNC[\\/]/i.test(path)) return `\\\\${path.slice(8)}`;
6123 if (/^[\\/]{2}\?[\\/]/.test(path)) return path.slice(4);
6124 return path;
6125 }
6126 function pathKey(path, platform = process.platform) {
6127 if (platform !== "win32") return posix.normalize(path);
6128 return win32.normalize(stripVerbatim(path, platform)).toLowerCase();
6129 }
6130 function samePath(a, b, platform = process.platform) {
6131 return pathKey(a, platform) === pathKey(b, platform);
6132 }
6133 function insideKey(root, target, platform = process.platform) {
6134 const path = platform === "win32" ? win32 : posix;
6135 const inside = path.relative(stripVerbatim(root, platform), stripVerbatim(target, platform));
6136 if (inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) return void 0;
6137 return platform === "win32" ? inside.split(win32.sep).join("/") : inside;
6138 }
6139 function isUnlinkedInside(root, key, target, platform = process.platform) {
6140 let canonicalRoot, canonicalTarget;
6141 try {
6142 canonicalRoot = canonicalPath(root, platform);
6143 canonicalTarget = canonicalPath(target, platform);
6144 } catch {
6145 return false;
6146 }
6147 return unlinkedKeyMatches(canonicalRoot, key, canonicalTarget, platform);
6148 }
6149 function unlinkedKeyMatches(canonicalRoot, key, canonicalTarget, platform = process.platform) {
6150 if (!key || key.split("/").some((part) => !part || part === "." || part === "..")) return false;
6151 const path = platform === "win32" ? win32 : posix;
6152 return samePath(path.join(stripVerbatim(canonicalRoot, platform), ...key.split("/")), canonicalTarget, platform);
6153 }
6154 var init_canonical_path = __esm({
6155 "src/dsh/canonical-path.ts"() {
6156 "use strict";
6157 }
6158 });
6159
6160 // src/dsh/upstream/hooks/hook-protocol/src/matcher.ts
6161 function isMatchAll(matcher) {
6162 return matcher === void 0 || matcher === "" || matcher === "*";
6163 }
6164 function compileRegex(pattern) {
6165 try {
6166 return new RegExp(pattern);
6167 } catch (_syntaxError) {
6168 return void 0;
6169 }
6170 }
6171 function matcherDiagnostic(matcher, mode) {
6172 if (isMatchAll(matcher)) return void 0;
6173 const pattern = matcher;
6174 if (mode === "claude-code" && CLAUDE_LITERAL.test(pattern)) return void 0;
6175 return compileRegex(pattern) === void 0 ? `invalid ${mode} regex matcher ${JSON.stringify(pattern)}` : void 0;
6176 }
6177 var CLAUDE_LITERAL;
6178 var init_matcher = __esm({
6179 "src/dsh/upstream/hooks/hook-protocol/src/matcher.ts"() {
6180 "use strict";
6181 CLAUDE_LITERAL = /^[A-Za-z0-9_|]+$/;
6182 }
6183 });
6184
6185 // src/dsh/upstream/hooks/hooks-claude-code/src/config.ts
6186 function asObject(value) {
6187 return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
6188 }
6189 function substituteCommand(command, vars) {
6190 let out = command;
6191 if (vars.pluginRoot !== void 0) out = out.split("${CLAUDE_PLUGIN_ROOT}").join(vars.pluginRoot);
6192 if (vars.projectDir !== void 0) out = out.split("${CLAUDE_PROJECT_DIR}").join(vars.projectDir);
6193 return out;
6194 }
6195 function parseClaudeCodeConfig(raw, vars = {}) {
6196 const config = {};
6197 const skipped = [];
6198 const root = asObject(raw);
6199 const hooksMap = root ? asObject(root.hooks) ?? root : void 0;
6200 if (!hooksMap) return { config, skipped };
6201 for (const event of CLAUDE_EVENTS) {
6202 const rawGroups = hooksMap[event];
6203 if (!Array.isArray(rawGroups)) continue;
6204 const groups = [];
6205 for (const rawGroup of rawGroups) {
6206 const group = asObject(rawGroup);
6207 if (!group || !Array.isArray(group.hooks)) continue;
6208 const commands = [];
6209 for (const rawHook of group.hooks) {
6210 const hook = asObject(rawHook);
6211 if (!hook) continue;
6212 const type2 = typeof hook.type === "string" ? hook.type : "command";
6213 if (type2 !== "command") {
6214 skipped.push({ event, type: type2 });
6215 continue;
6216 }
6217 if (typeof hook.command !== "string") continue;
6218 commands.push({
6219 command: substituteCommand(hook.command, vars),
6220 ...typeof hook.timeout === "number" ? { timeoutSec: hook.timeout } : {}
6221 });
6222 }
6223 if (commands.length === 0) continue;
6224 const matcher = event === "UserPromptSubmit" || event === "Stop" ? void 0 : typeof group.matcher === "string" ? group.matcher : void 0;
6225 const diagnostic = matcherDiagnostic(matcher, "claude-code");
6226 if (diagnostic !== void 0) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`);
6227 groups.push({
6228 ...matcher !== void 0 ? { matcher } : {},
6229 hooks: commands
6230 });
6231 }
6232 if (groups.length > 0) config[event] = groups;
6233 }
6234 return { config, skipped };
6235 }
6236 var CLAUDE_EVENTS;
6237 var init_config = __esm({
6238 "src/dsh/upstream/hooks/hooks-claude-code/src/config.ts"() {
6239 "use strict";
6240 init_matcher();
6241 CLAUDE_EVENTS = [
6242 "SessionStart",
6243 "UserPromptSubmit",
6244 "PreToolUse",
6245 "PostToolUse",
6246 "Stop",
6247 "SubagentStart",
6248 "SubagentStop"
6249 ];
6250 }
6251 });
6252
6253 // src/dsh/upstream/hooks/hooks-codex/src/config.ts
6254 function asObject2(value) {
6255 return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
6256 }
6257 function parseCodexConfig(raw) {
6258 const config = {};
6259 const skipped = [];
6260 const root = asObject2(raw);
6261 const hooksMap = root ? asObject2(root.hooks) ?? root : void 0;
6262 if (!hooksMap) return { config, skipped };
6263 for (const event of CODEX_EVENTS) {
6264 const rawGroups = hooksMap[event];
6265 if (!Array.isArray(rawGroups)) continue;
6266 const groups = [];
6267 for (const rawGroup of rawGroups) {
6268 const group = asObject2(rawGroup);
6269 if (!group || !Array.isArray(group.hooks)) continue;
6270 const commands = [];
6271 for (const rawHook of group.hooks) {
6272 const hook = asObject2(rawHook);
6273 if (!hook) continue;
6274 const type2 = typeof hook.type === "string" ? hook.type : "command";
6275 if (type2 !== "command") {
6276 skipped.push({ event, reason: `unsupported "${type2}" hook` });
6277 continue;
6278 }
6279 if (hook.async === true) {
6280 skipped.push({ event, reason: "async hook" });
6281 continue;
6282 }
6283 if (typeof hook.command !== "string") continue;
6284 const timeout = typeof hook.timeout === "number" ? hook.timeout : typeof hook.timeoutSec === "number" ? hook.timeoutSec : void 0;
6285 commands.push({ command: hook.command, ...timeout !== void 0 ? { timeoutSec: timeout } : {} });
6286 }
6287 if (commands.length === 0) continue;
6288 const matcher = event === "UserPromptSubmit" || event === "Stop" ? void 0 : typeof group.matcher === "string" ? group.matcher : void 0;
6289 const diagnostic = matcherDiagnostic(matcher, "codex");
6290 if (diagnostic !== void 0) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`);
6291 groups.push({ ...matcher !== void 0 ? { matcher } : {}, hooks: commands });
6292 }
6293 if (groups.length > 0) config[event] = groups;
6294 }
6295 return { config, skipped };
6296 }
6297 var CODEX_EVENTS;
6298 var init_config2 = __esm({
6299 "src/dsh/upstream/hooks/hooks-codex/src/config.ts"() {
6300 "use strict";
6301 init_matcher();
6302 CODEX_EVENTS = ["PreToolUse", "PostToolUse", "SessionStart", "UserPromptSubmit", "Stop"];
6303 }
6304 });
6305
6306 // src/dsh/shell-hooks.ts
6307 import { createHash } from "node:crypto";
6308 import { readFileSync, lstatSync } from "node:fs";
6309 import { resolve, relative, isAbsolute, sep } from "node:path";
6310 function reviewedHookModule(dialect, root, files) {
6311 return { name: `hooks-${dialect}`, inject: ["shellHooks"], apply(ctx, config) {
6312 if (!config || typeof config.configPath !== "string") throw new Error("hook bridge needs its reviewed configPath");
6313 const path = resolve(root, config.configPath);
6314 const inside = relative(root, path).split(sep).join("/");
6315 if (!inside || inside.startsWith("../") || isAbsolute(inside) || !files[inside] || !isUnlinkedInside(root, inside, path) || !lstatSync(path).isFile()) throw new Error("hook config is absent from the reviewed regular-file closure");
6316 const bytes = readFileSync(path);
6317 if (bytes.length > 1024 * 1024 || createHash("sha256").update(bytes).digest("hex") !== files[inside]) throw new Error("hook config changed after review or exceeds 1 MiB");
6318 if (config.projectDir !== void 0) throw new Error("explicit projectDir is unsupported; each process uses its current core workspace");
6319 if (config.pluginRoot !== void 0 && config.pluginRoot !== "." && config.pluginRoot !== root) throw new Error("pluginRoot must be this reviewed bundle root");
6320 const raw = JSON.parse(bytes.toString("utf8"));
6321 const parsed = dialect === "claude-code" ? parseClaudeCodeConfig(raw, { pluginRoot: root }) : parseCodexConfig(raw);
6322 if (parsed.skipped.length) throw new Error("hook config contains unsupported non-command or asynchronous hooks");
6323 let count = 0;
6324 for (const [point, groups] of Object.entries(parsed.config)) {
6325 if (point === "Stop") ctx.logger.warn("Stop runs at the core TurnEnd observer; forced continuation is unsupported");
6326 for (const group of groups) for (const hook of group.hooks) {
6327 if (++count > 128) throw new Error("hook bridge exceeds 128 commands");
6328 const seconds = hook.timeoutSec ?? (config.defaultTimeoutMs ?? 6e5) / 1e3;
6329 if (!Number.isSafeInteger(seconds) || seconds < 1 || seconds > 86400) throw new Error("hook timeout must be 1–86400 whole seconds");
6330 ctx.shellHooks.register({ dialect, point, ...group.matcher === void 0 ? {} : { matcher: group.matcher }, hook: { event: EVENTS[point], command: hook.command, timeout_secs: seconds, background: false, continue_on_error: false, name: `${dialect}:${point}:${count}` } });
6331 }
6332 }
6333 if (count === 0) throw new Error("reviewed hook config has no supported command hooks");
6334 } };
6335 }
6336 var EVENTS;
6337 var init_shell_hooks = __esm({
6338 "src/dsh/shell-hooks.ts"() {
6339 "use strict";
6340 init_canonical_path();
6341 init_canonical_path();
6342 init_config();
6343 init_config2();
6344 EVENTS = { SessionStart: "session_start", UserPromptSubmit: "message_submit", PreToolUse: "tool_call_before", PostToolUse: "tool_call_after", Stop: "turn_end", SubagentStart: "subagent_spawn", SubagentStop: "subagent_complete" };
6345 }
6346 });
6347
6348 // src/runtime.ts
6349 import * as nodeModule from "node:module";
6350 var require2, RUNTIME;
6351 var init_runtime = __esm({
6352 "src/runtime.ts"() {
6353 "use strict";
6354 require2 = nodeModule.createRequire(import.meta.url);
6355 RUNTIME = typeof process.versions.bun === "string" ? { name: "bun", version: process.versions.bun } : { name: "node", version: process.versions.node };
6356 }
6357 });
6358
6359 // node_modules/acorn/dist/acorn.mjs
6360 function isInAstralSet(code, set2) {
6361 var pos = 65536;
6362 for (var i2 = 0; i2 < set2.length; i2 += 2) {
6363 pos += set2[i2];
6364 if (pos > code) {
6365 return false;
6366 }
6367 pos += set2[i2 + 1];
6368 if (pos >= code) {
6369 return true;
6370 }
6371 }
6372 return false;
6373 }
6374 function isIdentifierStart(code, astral) {
6375 if (code < 65) {
6376 return code === 36;
6377 }
6378 if (code < 91) {
6379 return true;
6380 }
6381 if (code < 97) {
6382 return code === 95;
6383 }
6384 if (code < 123) {
6385 return true;
6386 }
6387 if (code <= 65535) {
6388 return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
6389 }
6390 if (astral === false) {
6391 return false;
6392 }
6393 return isInAstralSet(code, astralIdentifierStartCodes);
6394 }
6395 function isIdentifierChar(code, astral) {
6396 if (code < 48) {
6397 return code === 36;
6398 }
6399 if (code < 58) {
6400 return true;
6401 }
6402 if (code < 65) {
6403 return false;
6404 }
6405 if (code < 91) {
6406 return true;
6407 }
6408 if (code < 97) {
6409 return code === 95;
6410 }
6411 if (code < 123) {
6412 return true;
6413 }
6414 if (code <= 65535) {
6415 return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
6416 }
6417 if (astral === false) {
6418 return false;
6419 }
6420 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
6421 }
6422 function binop(name, prec) {
6423 return new TokenType(name, { beforeExpr: true, binop: prec });
6424 }
6425 function kw(name, options) {
6426 if (options === void 0) options = {};
6427 options.keyword = name;
6428 return keywords[name] = new TokenType(name, options);
6429 }
6430 function isNewLine(code) {
6431 return code === 10 || code === 13 || code === 8232 || code === 8233;
6432 }
6433 function nextLineBreak(code, from, end) {
6434 if (end === void 0) end = code.length;
6435 for (var i2 = from; i2 < end; i2++) {
6436 var next = code.charCodeAt(i2);
6437 if (isNewLine(next)) {
6438 return i2 < end - 1 && next === 13 && code.charCodeAt(i2 + 1) === 10 ? i2 + 2 : i2 + 1;
6439 }
6440 }
6441 return -1;
6442 }
6443 function wordsRegexp(words) {
6444 return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
6445 }
6446 function codePointToString(code) {
6447 if (code <= 65535) {
6448 return String.fromCharCode(code);
6449 }
6450 code -= 65536;
6451 return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
6452 }
6453 function getLineInfo(input, offset2) {
6454 for (var line = 1, cur = 0; ; ) {
6455 var nextBreak = nextLineBreak(input, cur, offset2);
6456 if (nextBreak < 0) {
6457 return new Position(line, offset2 - cur);
6458 }
6459 ++line;
6460 cur = nextBreak;
6461 }
6462 }
6463 function getOptions(opts) {
6464 var options = {};
6465 for (var opt in defaultOptions) {
6466 options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt];
6467 }
6468 if (options.ecmaVersion === "latest") {
6469 options.ecmaVersion = 1e8;
6470 } else if (options.ecmaVersion == null) {
6471 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
6472 warnedAboutEcmaVersion = true;
6473 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
6474 }
6475 options.ecmaVersion = 11;
6476 } else if (options.ecmaVersion >= 2015) {
6477 options.ecmaVersion -= 2009;
6478 }
6479 if (options.allowReserved == null) {
6480 options.allowReserved = options.ecmaVersion < 5;
6481 }
6482 if (!opts || opts.allowHashBang == null) {
6483 options.allowHashBang = options.ecmaVersion >= 14;
6484 }
6485 if (isArray(options.onToken)) {
6486 var tokens = options.onToken;
6487 options.onToken = function(token) {
6488 return tokens.push(token);
6489 };
6490 }
6491 if (isArray(options.onComment)) {
6492 options.onComment = pushComment(options, options.onComment);
6493 }
6494 if (options.sourceType === "commonjs" && options.allowAwaitOutsideFunction) {
6495 throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");
6496 }
6497 return options;
6498 }
6499 function pushComment(options, array) {
6500 return function(block, text2, start, end, startLoc, endLoc) {
6501 var comment = {
6502 type: block ? "Block" : "Line",
6503 value: text2,
6504 start,
6505 end
6506 };
6507 if (options.locations) {
6508 comment.loc = new SourceLocation(this, startLoc, endLoc);
6509 }
6510 if (options.ranges) {
6511 comment.range = [start, end];
6512 }
6513 array.push(comment);
6514 };
6515 }
6516 function functionFlags(async, generator) {
6517 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
6518 }
6519 function isPrivateNameConflicted(privateNameMap, element) {
6520 var name = element.key.name;
6521 var curr = privateNameMap[name];
6522 var next = "true";
6523 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
6524 next = (element.static ? "s" : "i") + element.kind;
6525 }
6526 if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
6527 privateNameMap[name] = "true";
6528 return false;
6529 } else if (!curr) {
6530 privateNameMap[name] = next;
6531 return false;
6532 } else {
6533 return true;
6534 }
6535 }
6536 function checkKeyName(node, name) {
6537 var computed = node.computed;
6538 var key = node.key;
6539 return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
6540 }
6541 function isLocalVariableAccess(node) {
6542 return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression);
6543 }
6544 function isPrivateFieldAccess(node) {
6545 return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression);
6546 }
6547 function finishNodeAt(node, type2, pos, loc) {
6548 node.type = type2;
6549 node.end = pos;
6550 if (this.options.locations) {
6551 node.loc.end = loc;
6552 }
6553 if (this.options.ranges) {
6554 node.range[1] = pos;
6555 }
6556 return node;
6557 }
6558 function buildUnicodeData(ecmaVersion2) {
6559 var d = data[ecmaVersion2] = {
6560 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion2] + " " + unicodeGeneralCategoryValues),
6561 binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion2]),
6562 nonBinary: {
6563 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
6564 Script: wordsRegexp(unicodeScriptValues[ecmaVersion2])
6565 }
6566 };
6567 d.nonBinary.Script_Extensions = d.nonBinary.Script;
6568 d.nonBinary.gc = d.nonBinary.General_Category;
6569 d.nonBinary.sc = d.nonBinary.Script;
6570 d.nonBinary.scx = d.nonBinary.Script_Extensions;
6571 }
6572 function hasProp(obj) {
6573 for (var _ in obj) {
6574 return true;
6575 }
6576 return false;
6577 }
6578 function isRegularExpressionModifier(ch) {
6579 return ch === 105 || ch === 109 || ch === 115;
6580 }
6581 function isSyntaxCharacter(ch) {
6582 return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
6583 }
6584 function isRegExpIdentifierStart(ch) {
6585 return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
6586 }
6587 function isRegExpIdentifierPart(ch) {
6588 return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
6589 }
6590 function isControlLetter(ch) {
6591 return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
6592 }
6593 function isValidUnicode(ch) {
6594 return ch >= 0 && ch <= 1114111;
6595 }
6596 function isCharacterClassEscape(ch) {
6597 return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
6598 }
6599 function isUnicodePropertyNameCharacter(ch) {
6600 return isControlLetter(ch) || ch === 95;
6601 }
6602 function isUnicodePropertyValueCharacter(ch) {
6603 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
6604 }
6605 function isClassSetReservedDoublePunctuatorCharacter(ch) {
6606 return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;
6607 }
6608 function isClassSetSyntaxCharacter(ch) {
6609 return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;
6610 }
6611 function isClassSetReservedPunctuator(ch) {
6612 return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;
6613 }
6614 function isDecimalDigit(ch) {
6615 return ch >= 48 && ch <= 57;
6616 }
6617 function isHexDigit(ch) {
6618 return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
6619 }
6620 function hexToInt(ch) {
6621 if (ch >= 65 && ch <= 70) {
6622 return 10 + (ch - 65);
6623 }
6624 if (ch >= 97 && ch <= 102) {
6625 return 10 + (ch - 97);
6626 }
6627 return ch - 48;
6628 }
6629 function isOctalDigit(ch) {
6630 return ch >= 48 && ch <= 55;
6631 }
6632 function stringToNumber(str2, isLegacyOctalNumericLiteral) {
6633 if (isLegacyOctalNumericLiteral) {
6634 return parseInt(str2, 8);
6635 }
6636 return parseFloat(str2.replace(/_/g, ""));
6637 }
6638 function stringToBigInt(str2) {
6639 if (typeof BigInt !== "function") {
6640 return null;
6641 }
6642 return BigInt(str2.replace(/_/g, ""));
6643 }
6644 var astralIdentifierCodes, astralIdentifierStartCodes, nonASCIIidentifierChars, nonASCIIidentifierStartChars, reservedWords, ecma5AndLessKeywords, keywords$1, keywordRelationalOperator, nonASCIIidentifierStart, nonASCIIidentifier, TokenType, beforeExpr, startsExpr, keywords, types$1, lineBreak, lineBreakG, nonASCIIwhitespace, skipWhiteSpace, ref, hasOwnProperty, toString, hasOwn, isArray, regexpCache, loneSurrogate, Position, SourceLocation, defaultOptions, warnedAboutEcmaVersion, SCOPE_TOP, SCOPE_FUNCTION, SCOPE_ASYNC, SCOPE_GENERATOR, SCOPE_ARROW, SCOPE_SIMPLE_CATCH, SCOPE_SUPER, SCOPE_DIRECT_SUPER, SCOPE_CLASS_STATIC_BLOCK, SCOPE_CLASS_FIELD_INIT, SCOPE_SWITCH, SCOPE_VAR, BIND_NONE, BIND_VAR, BIND_LEXICAL, BIND_FUNCTION, BIND_SIMPLE_CATCH, BIND_OUTSIDE, Parser, prototypeAccessors, pp$9, literal, DestructuringErrors, pp$8, loopLabel, switchLabel, empty$1, FUNC_STATEMENT, FUNC_HANGING_STATEMENT, FUNC_NULLABLE_ID, pp$7, TokContext, types2, pp$6, pp$5, empty, pp$4, pp$3, Scope, Node, pp$2, scriptValuesAddedInUnicode, ecma9BinaryProperties, ecma10BinaryProperties, ecma11BinaryProperties, ecma12BinaryProperties, ecma13BinaryProperties, ecma14BinaryProperties, unicodeBinaryProperties, ecma14BinaryPropertiesOfStrings, unicodeBinaryPropertiesOfStrings, unicodeGeneralCategoryValues, ecma9ScriptValues, ecma10ScriptValues, ecma11ScriptValues, ecma12ScriptValues, ecma13ScriptValues, ecma14ScriptValues, unicodeScriptValues, data, ecmaVersion, i, list, pp$1, BranchID, RegExpValidationState, CharSetNone, CharSetOk, CharSetString, Token, pp, INVALID_TEMPLATE_ESCAPE_ERROR, version;
6645 var init_acorn = __esm({
6646 "node_modules/acorn/dist/acorn.mjs"() {
6647 astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
6648 astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
6649 nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-᫝᫠-᫫ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・";
6650 nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-࢏ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚ౜ౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ೜-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ƛ꟱-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";
6651 reservedWords = {
6652 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
6653 5: "class enum extends super const export import",
6654 6: "enum",
6655 strict: "implements interface let package private protected public static yield",
6656 strictBind: "eval arguments"
6657 };
6658 ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
6659 keywords$1 = {
6660 5: ecma5AndLessKeywords,
6661 "5module": ecma5AndLessKeywords + " export import",
6662 6: ecma5AndLessKeywords + " const class extends export import super"
6663 };
6664 keywordRelationalOperator = /^in(stanceof)?$/;
6665 nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
6666 nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
6667 TokenType = function TokenType2(label, conf) {
6668 if (conf === void 0) conf = {};
6669 this.label = label;
6670 this.keyword = conf.keyword;
6671 this.beforeExpr = !!conf.beforeExpr;
6672 this.startsExpr = !!conf.startsExpr;
6673 this.isLoop = !!conf.isLoop;
6674 this.isAssign = !!conf.isAssign;
6675 this.prefix = !!conf.prefix;
6676 this.postfix = !!conf.postfix;
6677 this.binop = conf.binop || null;
6678 this.updateContext = null;
6679 };
6680 beforeExpr = { beforeExpr: true };
6681 startsExpr = { startsExpr: true };
6682 keywords = {};
6683 types$1 = {
6684 num: new TokenType("num", startsExpr),
6685 regexp: new TokenType("regexp", startsExpr),
6686 string: new TokenType("string", startsExpr),
6687 name: new TokenType("name", startsExpr),
6688 privateId: new TokenType("privateId", startsExpr),
6689 eof: new TokenType("eof"),
6690 // Punctuation token types.
6691 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
6692 bracketR: new TokenType("]"),
6693 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
6694 braceR: new TokenType("}"),
6695 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
6696 parenR: new TokenType(")"),
6697 comma: new TokenType(",", beforeExpr),
6698 semi: new TokenType(";", beforeExpr),
6699 colon: new TokenType(":", beforeExpr),
6700 dot: new TokenType("."),
6701 question: new TokenType("?", beforeExpr),
6702 questionDot: new TokenType("?."),
6703 arrow: new TokenType("=>", beforeExpr),
6704 template: new TokenType("template"),
6705 invalidTemplate: new TokenType("invalidTemplate"),
6706 ellipsis: new TokenType("...", beforeExpr),
6707 backQuote: new TokenType("`", startsExpr),
6708 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
6709 // Operators. These carry several kinds of properties to help the
6710 // parser use them properly (the presence of these properties is
6711 // what categorizes them as operators).
6712 //
6713 // `binop`, when present, specifies that this operator is a binary
6714 // operator, and will refer to its precedence.
6715 //
6716 // `prefix` and `postfix` mark the operator as a prefix or postfix
6717 // unary operator.
6718 //
6719 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
6720 // binary operators with a very low precedence, that should result
6721 // in AssignmentExpression nodes.
6722 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
6723 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
6724 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
6725 prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
6726 logicalOR: binop("||", 1),
6727 logicalAND: binop("&&", 2),
6728 bitwiseOR: binop("|", 3),
6729 bitwiseXOR: binop("^", 4),
6730 bitwiseAND: binop("&", 5),
6731 equality: binop("==/!=/===/!==", 6),
6732 relational: binop("</>/<=/>=", 7),
6733 bitShift: binop("<</>>/>>>", 8),
6734 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
6735 modulo: binop("%", 10),
6736 star: binop("*", 10),
6737 slash: binop("/", 10),
6738 starstar: new TokenType("**", { beforeExpr: true }),
6739 coalesce: binop("??", 1),
6740 // Keyword token types.
6741 _break: kw("break"),
6742 _case: kw("case", beforeExpr),
6743 _catch: kw("catch"),
6744 _continue: kw("continue"),
6745 _debugger: kw("debugger"),
6746 _default: kw("default", beforeExpr),
6747 _do: kw("do", { isLoop: true, beforeExpr: true }),
6748 _else: kw("else", beforeExpr),
6749 _finally: kw("finally"),
6750 _for: kw("for", { isLoop: true }),
6751 _function: kw("function", startsExpr),
6752 _if: kw("if"),
6753 _return: kw("return", beforeExpr),
6754 _switch: kw("switch"),
6755 _throw: kw("throw", beforeExpr),
6756 _try: kw("try"),
6757 _var: kw("var"),
6758 _const: kw("const"),
6759 _while: kw("while", { isLoop: true }),
6760 _with: kw("with"),
6761 _new: kw("new", { beforeExpr: true, startsExpr: true }),
6762 _this: kw("this", startsExpr),
6763 _super: kw("super", startsExpr),
6764 _class: kw("class", startsExpr),
6765 _extends: kw("extends", beforeExpr),
6766 _export: kw("export"),
6767 _import: kw("import", startsExpr),
6768 _null: kw("null", startsExpr),
6769 _true: kw("true", startsExpr),
6770 _false: kw("false", startsExpr),
6771 _in: kw("in", { beforeExpr: true, binop: 7 }),
6772 _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
6773 _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
6774 _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
6775 _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
6776 };
6777 lineBreak = /\r\n?|\n|\u2028|\u2029/;
6778 lineBreakG = new RegExp(lineBreak.source, "g");
6779 nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
6780 skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
6781 ref = Object.prototype;
6782 hasOwnProperty = ref.hasOwnProperty;
6783 toString = ref.toString;
6784 hasOwn = Object.hasOwn || (function(obj, propName) {
6785 return hasOwnProperty.call(obj, propName);
6786 });
6787 isArray = Array.isArray || (function(obj) {
6788 return toString.call(obj) === "[object Array]";
6789 });
6790 regexpCache = /* @__PURE__ */ Object.create(null);
6791 loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
6792 Position = function Position2(line, col) {
6793 this.line = line;
6794 this.column = col;
6795 };
6796 Position.prototype.offset = function offset(n) {
6797 return new Position(this.line, this.column + n);
6798 };
6799 SourceLocation = function SourceLocation2(p, start, end) {
6800 this.start = start;
6801 this.end = end;
6802 if (p.sourceFile !== null) {
6803 this.source = p.sourceFile;
6804 }
6805 };
6806 defaultOptions = {
6807 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
6808 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
6809 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
6810 // (the latest version the library supports). This influences
6811 // support for strict mode, the set of reserved words, and support
6812 // for new syntax features.
6813 ecmaVersion: null,
6814 // `sourceType` indicates the mode the code should be parsed in.
6815 // Can be either `"script"`, `"module"` or `"commonjs"`. This influences global
6816 // strict mode and parsing of `import` and `export` declarations.
6817 sourceType: "script",
6818 // When set to true, enable strict parsing mode even if `sourceType`
6819 // is `"script"`.
6820 strict: false,
6821 // `onInsertedSemicolon` can be a callback that will be called when
6822 // a semicolon is automatically inserted. It will be passed the
6823 // position of the inserted semicolon as an offset, and if
6824 // `locations` is enabled, it is given the location as a `{line,
6825 // column}` object as second argument.
6826 onInsertedSemicolon: null,
6827 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
6828 // trailing commas.
6829 onTrailingComma: null,
6830 // By default, reserved words are only enforced if ecmaVersion >= 5.
6831 // Set `allowReserved` to a boolean value to explicitly turn this on
6832 // an off. When this option has the value "never", reserved words
6833 // and keywords can also not be used as property names.
6834 allowReserved: null,
6835 // When enabled, a return at the top level is not considered an
6836 // error.
6837 allowReturnOutsideFunction: false,
6838 // When enabled, import/export statements are not constrained to
6839 // appearing at the top of the program, and an import.meta expression
6840 // in a script isn't considered an error.
6841 allowImportExportEverywhere: false,
6842 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
6843 // When enabled, await identifiers are allowed to appear at the top-level scope,
6844 // but they are still not allowed in non-async functions.
6845 allowAwaitOutsideFunction: null,
6846 // When enabled, super identifiers are not constrained to
6847 // appearing in methods and do not raise an error when they appear elsewhere.
6848 allowSuperOutsideMethod: null,
6849 // When enabled, hashbang directive in the beginning of file is
6850 // allowed and treated as a line comment. Enabled by default when
6851 // `ecmaVersion` >= 2023.
6852 allowHashBang: false,
6853 // By default, the parser will verify that private properties are
6854 // only used in places where they are valid and have been declared.
6855 // Set this to false to turn such checks off.
6856 checkPrivateFields: true,
6857 // When `locations` is on, `loc` properties holding objects with
6858 // `start` and `end` properties in `{line, column}` form (with
6859 // line being 1-based and column 0-based) will be attached to the
6860 // nodes.
6861 locations: false,
6862 // Pass an optional `{line, column}` object to use for the start of
6863 // the parse. This is mostly useful when using `parseExpressionAt`
6864 // with `locations: true`, to prevent the parser from having to
6865 // determine the line position at the start position.
6866 startLocation: null,
6867 // A function can be passed as `onToken` option, which will
6868 // cause Acorn to call that function with object in the same
6869 // format as tokens returned from `tokenizer().getToken()`. Note
6870 // that you are not allowed to call the parser from the
6871 // callback—that will corrupt its internal state.
6872 onToken: null,
6873 // A function can be passed as `onComment` option, which will
6874 // cause Acorn to call that function with `(block, text, start,
6875 // end)` parameters whenever a comment is skipped. `block` is a
6876 // boolean indicating whether this is a block (`/* */`) comment,
6877 // `text` is the content of the comment, and `start` and `end` are
6878 // character offsets that denote the start and end of the comment.
6879 // When the `locations` option is on, two more parameters are
6880 // passed, the full `{line, column}` locations of the start and
6881 // end of the comments. Note that you are not allowed to call the
6882 // parser from the callback—that will corrupt its internal state.
6883 // When this option has an array as value, objects representing the
6884 // comments are pushed to it.
6885 onComment: null,
6886 // Nodes have their start and end characters offsets recorded in
6887 // `start` and `end` properties (directly on the node, rather than
6888 // the `loc` object, which holds line/column data. To also add a
6889 // [semi-standardized][range] `range` property holding a `[start,
6890 // end]` array with the same numbers, set the `ranges` option to
6891 // `true`.
6892 //
6893 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
6894 ranges: false,
6895 // It is possible to parse multiple files into a single AST by
6896 // passing the tree produced by parsing the first file as
6897 // `program` option in subsequent parses. This will add the
6898 // toplevel forms of the parsed file to the `Program` (top) node
6899 // of an existing parse tree.
6900 program: null,
6901 // When `locations` is on, you can pass this to record the source
6902 // file in every node's `loc` object.
6903 sourceFile: null,
6904 // This value, if given, is stored in every node, whether
6905 // `locations` is on or off.
6906 directSourceFile: null,
6907 // When enabled, parenthesized expressions are represented by
6908 // (non-standard) ParenthesizedExpression nodes
6909 preserveParens: false
6910 };
6911 warnedAboutEcmaVersion = false;
6912 SCOPE_TOP = 1;
6913 SCOPE_FUNCTION = 2;
6914 SCOPE_ASYNC = 4;
6915 SCOPE_GENERATOR = 8;
6916 SCOPE_ARROW = 16;
6917 SCOPE_SIMPLE_CATCH = 32;
6918 SCOPE_SUPER = 64;
6919 SCOPE_DIRECT_SUPER = 128;
6920 SCOPE_CLASS_STATIC_BLOCK = 256;
6921 SCOPE_CLASS_FIELD_INIT = 512;
6922 SCOPE_SWITCH = 1024;
6923 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
6924 BIND_NONE = 0;
6925 BIND_VAR = 1;
6926 BIND_LEXICAL = 2;
6927 BIND_FUNCTION = 3;
6928 BIND_SIMPLE_CATCH = 4;
6929 BIND_OUTSIDE = 5;
6930 Parser = function Parser2(options, input, startPos) {
6931 this.options = options = getOptions(options);
6932 this.sourceFile = options.sourceFile;
6933 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
6934 var reserved = "";
6935 if (options.allowReserved !== true) {
6936 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
6937 if (options.sourceType === "module") {
6938 reserved += " await";
6939 }
6940 }
6941 this.reservedWords = wordsRegexp(reserved);
6942 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
6943 this.reservedWordsStrict = wordsRegexp(reservedStrict);
6944 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
6945 this.input = String(input);
6946 this.containsEsc = false;
6947 this.pos = startPos || 0;
6948 this.curLine = 1;
6949 if (options.startLocation) {
6950 this.lineStart = this.pos - options.startLocation.column;
6951 this.curLine = options.startLocation.line;
6952 } else if (startPos) {
6953 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
6954 if (this.options.locations) {
6955 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
6956 }
6957 } else {
6958 this.lineStart = 0;
6959 }
6960 this.type = types$1.eof;
6961 this.value = null;
6962 this.start = this.end = this.pos;
6963 this.startLoc = this.endLoc = this.curPosition();
6964 this.lastTokEndLoc = this.lastTokStartLoc = null;
6965 this.lastTokStart = this.lastTokEnd = this.pos;
6966 this.context = this.initialContext();
6967 this.exprAllowed = true;
6968 this.inModule = options.sourceType === "module";
6969 this.strict = this.inModule || options.strict === true || this.strictDirective(this.pos);
6970 this.potentialArrowAt = -1;
6971 this.potentialArrowInForAwait = false;
6972 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
6973 this.labels = [];
6974 this.undefinedExports = /* @__PURE__ */ Object.create(null);
6975 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
6976 this.skipLineComment(2);
6977 }
6978 this.scopeStack = [];
6979 this.enterScope(
6980 this.options.sourceType === "commonjs" ? SCOPE_FUNCTION : SCOPE_TOP
6981 );
6982 this.regexpState = null;
6983 this.privateNameStack = [];
6984 };
6985 prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowReturn: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, allowUsing: { configurable: true }, inClassStaticBlock: { configurable: true } };
6986 Parser.prototype.parse = function parse() {
6987 var this$1$1 = this;
6988 var node = this.options.program || this.startNode();
6989 this.nextToken();
6990 return this.catchStackOverflow(function() {
6991 return this$1$1.parseTopLevel(node);
6992 });
6993 };
6994 prototypeAccessors.inFunction.get = function() {
6995 return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
6996 };
6997 prototypeAccessors.inGenerator.get = function() {
6998 return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
6999 };
7000 prototypeAccessors.inAsync.get = function() {
7001 return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
7002 };
7003 prototypeAccessors.canAwait.get = function() {
7004 for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {
7005 var ref2 = this.scopeStack[i2];
7006 var flags = ref2.flags;
7007 if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) {
7008 return false;
7009 }
7010 if (flags & SCOPE_FUNCTION) {
7011 return (flags & SCOPE_ASYNC) > 0;
7012 }
7013 }
7014 return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;
7015 };
7016 prototypeAccessors.allowReturn.get = function() {
7017 if (this.inFunction) {
7018 return true;
7019 }
7020 if (this.options.allowReturnOutsideFunction && this.currentVarScope().flags & SCOPE_TOP) {
7021 return true;
7022 }
7023 return false;
7024 };
7025 prototypeAccessors.allowSuper.get = function() {
7026 var ref2 = this.currentThisScope();
7027 var flags = ref2.flags;
7028 return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod;
7029 };
7030 prototypeAccessors.allowDirectSuper.get = function() {
7031 return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
7032 };
7033 prototypeAccessors.treatFunctionsAsVar.get = function() {
7034 return this.treatFunctionsAsVarInScope(this.currentScope());
7035 };
7036 prototypeAccessors.allowNewDotTarget.get = function() {
7037 for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {
7038 var ref2 = this.scopeStack[i2];
7039 var flags = ref2.flags;
7040 if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || flags & SCOPE_FUNCTION && !(flags & SCOPE_ARROW)) {
7041 return true;
7042 }
7043 }
7044 return false;
7045 };
7046 prototypeAccessors.allowUsing.get = function() {
7047 var ref2 = this.currentScope();
7048 var flags = ref2.flags;
7049 if (flags & SCOPE_SWITCH) {
7050 return false;
7051 }
7052 if (!this.inModule && flags & SCOPE_TOP) {
7053 return false;
7054 }
7055 return true;
7056 };
7057 prototypeAccessors.inClassStaticBlock.get = function() {
7058 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;
7059 };
7060 Parser.extend = function extend() {
7061 var plugins = [], len = arguments.length;
7062 while (len--) plugins[len] = arguments[len];
7063 var cls = this;
7064 for (var i2 = 0; i2 < plugins.length; i2++) {
7065 cls = plugins[i2](cls);
7066 }
7067 return cls;
7068 };
7069 Parser.parse = function parse2(input, options) {
7070 return new this(options, input).parse();
7071 };
7072 Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {
7073 var parser = new this(options, input, pos);
7074 parser.nextToken();
7075 return parser.parseExpression();
7076 };
7077 Parser.tokenizer = function tokenizer(input, options) {
7078 return new this(options, input);
7079 };
7080 Object.defineProperties(Parser.prototype, prototypeAccessors);
7081 pp$9 = Parser.prototype;
7082 literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
7083 pp$9.strictDirective = function(start) {
7084 if (this.options.ecmaVersion < 5) {
7085 return false;
7086 }
7087 for (; ; ) {
7088 skipWhiteSpace.lastIndex = start;
7089 start += skipWhiteSpace.exec(this.input)[0].length;
7090 var match = literal.exec(this.input.slice(start));
7091 if (!match) {
7092 return false;
7093 }
7094 if ((match[1] || match[2]) === "use strict") {
7095 skipWhiteSpace.lastIndex = start + match[0].length;
7096 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
7097 var next = this.input.charAt(end);
7098 return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
7099 }
7100 start += match[0].length;
7101 skipWhiteSpace.lastIndex = start;
7102 start += skipWhiteSpace.exec(this.input)[0].length;
7103 if (this.input[start] === ";") {
7104 start++;
7105 }
7106 }
7107 };
7108 pp$9.eat = function(type2) {
7109 if (this.type === type2) {
7110 this.next();
7111 return true;
7112 } else {
7113 return false;
7114 }
7115 };
7116 pp$9.isContextual = function(name) {
7117 return this.type === types$1.name && this.value === name && !this.containsEsc;
7118 };
7119 pp$9.eatContextual = function(name) {
7120 if (!this.isContextual(name)) {
7121 return false;
7122 }
7123 this.next();
7124 return true;
7125 };
7126 pp$9.catchStackOverflow = function(f) {
7127 try {
7128 return f();
7129 } catch (e) {
7130 if (e instanceof Error && (/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message) || /\btoo much recursion\b/i.test(e.message))) {
7131 this.raise(this.start, "Not enough stack space to parse input");
7132 } else {
7133 throw e;
7134 }
7135 }
7136 };
7137 pp$9.expectContextual = function(name) {
7138 if (!this.eatContextual(name)) {
7139 this.unexpected();
7140 }
7141 };
7142 pp$9.canInsertSemicolon = function() {
7143 return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
7144 };
7145 pp$9.insertSemicolon = function() {
7146 if (this.canInsertSemicolon()) {
7147 if (this.options.onInsertedSemicolon) {
7148 this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
7149 }
7150 return true;
7151 }
7152 };
7153 pp$9.semicolon = function() {
7154 if (!this.eat(types$1.semi) && !this.insertSemicolon()) {
7155 this.unexpected();
7156 }
7157 };
7158 pp$9.afterTrailingComma = function(tokType, notNext) {
7159 if (this.type === tokType) {
7160 if (this.options.onTrailingComma) {
7161 this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
7162 }
7163 if (!notNext) {
7164 this.next();
7165 }
7166 return true;
7167 }
7168 };
7169 pp$9.expect = function(type2) {
7170 this.eat(type2) || this.unexpected();
7171 };
7172 pp$9.unexpected = function(pos) {
7173 this.raise(pos != null ? pos : this.start, "Unexpected token");
7174 };
7175 DestructuringErrors = function DestructuringErrors2() {
7176 this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
7177 };
7178 pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
7179 if (!refDestructuringErrors) {
7180 return;
7181 }
7182 if (refDestructuringErrors.trailingComma > -1) {
7183 this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
7184 }
7185 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
7186 if (parens > -1) {
7187 this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");
7188 }
7189 };
7190 pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
7191 if (!refDestructuringErrors) {
7192 return false;
7193 }
7194 var shorthandAssign = refDestructuringErrors.shorthandAssign;
7195 var doubleProto = refDestructuringErrors.doubleProto;
7196 if (!andThrow) {
7197 return shorthandAssign >= 0 || doubleProto >= 0;
7198 }
7199 if (shorthandAssign >= 0) {
7200 this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
7201 }
7202 if (doubleProto >= 0) {
7203 this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
7204 }
7205 };
7206 pp$9.checkYieldAwaitInDefaultParams = function() {
7207 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
7208 this.raise(this.yieldPos, "Yield expression cannot be a default value");
7209 }
7210 if (this.awaitPos) {
7211 this.raise(this.awaitPos, "Await expression cannot be a default value");
7212 }
7213 };
7214 pp$9.isSimpleAssignTarget = function(expr) {
7215 if (expr.type === "ParenthesizedExpression") {
7216 return this.isSimpleAssignTarget(expr.expression);
7217 }
7218 return expr.type === "Identifier" || expr.type === "MemberExpression";
7219 };
7220 pp$8 = Parser.prototype;
7221 pp$8.parseTopLevel = function(node) {
7222 var exports$1 = /* @__PURE__ */ Object.create(null);
7223 if (!node.body) {
7224 node.body = [];
7225 }
7226 while (this.type !== types$1.eof) {
7227 var stmt = this.parseStatement(null, true, exports$1);
7228 node.body.push(stmt);
7229 }
7230 if (this.inModule) {
7231 for (var i2 = 0, list2 = Object.keys(this.undefinedExports); i2 < list2.length; i2 += 1) {
7232 var name = list2[i2];
7233 this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
7234 }
7235 }
7236 this.adaptDirectivePrologue(node.body);
7237 this.next();
7238 node.sourceType = this.options.sourceType === "commonjs" ? "script" : this.options.sourceType;
7239 return this.finishNode(node, "Program");
7240 };
7241 loopLabel = { kind: "loop" };
7242 switchLabel = { kind: "switch" };
7243 pp$8.isLet = function(context) {
7244 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
7245 return false;
7246 }
7247 skipWhiteSpace.lastIndex = this.pos;
7248 var skip = skipWhiteSpace.exec(this.input);
7249 var next = this.pos + skip[0].length, nextCh = this.fullCharCodeAt(next);
7250 if (nextCh === 91 || nextCh === 92) {
7251 return true;
7252 }
7253 if (context) {
7254 return false;
7255 }
7256 if (nextCh === 123) {
7257 return true;
7258 }
7259 if (isIdentifierStart(nextCh)) {
7260 var start = next;
7261 do {
7262 next += nextCh <= 65535 ? 1 : 2;
7263 } while (isIdentifierChar(nextCh = this.fullCharCodeAt(next)));
7264 if (nextCh === 92) {
7265 return true;
7266 }
7267 var ident = this.input.slice(start, next);
7268 if (!keywordRelationalOperator.test(ident)) {
7269 return true;
7270 }
7271 }
7272 return false;
7273 };
7274 pp$8.isAsyncFunction = function() {
7275 if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
7276 return false;
7277 }
7278 skipWhiteSpace.lastIndex = this.pos;
7279 var skip = skipWhiteSpace.exec(this.input);
7280 var next = this.pos + skip[0].length, after;
7281 return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.fullCharCodeAt(next + 8)) || after === 92));
7282 };
7283 pp$8.isUsingKeyword = function(isAwaitUsing, isFor) {
7284 if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) {
7285 return false;
7286 }
7287 skipWhiteSpace.lastIndex = this.pos;
7288 var skip = skipWhiteSpace.exec(this.input);
7289 var next = this.pos + skip[0].length;
7290 if (lineBreak.test(this.input.slice(this.pos, next))) {
7291 return false;
7292 }
7293 if (isAwaitUsing) {
7294 var usingEndPos = next + 5, after;
7295 if (this.input.slice(next, usingEndPos) !== "using" || usingEndPos === this.input.length || isIdentifierChar(after = this.fullCharCodeAt(usingEndPos)) || after === 92) {
7296 return false;
7297 }
7298 skipWhiteSpace.lastIndex = usingEndPos;
7299 var skipAfterUsing = skipWhiteSpace.exec(this.input);
7300 next = usingEndPos + skipAfterUsing[0].length;
7301 if (skipAfterUsing && lineBreak.test(this.input.slice(usingEndPos, next))) {
7302 return false;
7303 }
7304 }
7305 var ch = this.fullCharCodeAt(next);
7306 if (!isIdentifierStart(ch) && ch !== 92) {
7307 return false;
7308 }
7309 var idStart = next;
7310 do {
7311 next += ch <= 65535 ? 1 : 2;
7312 } while (isIdentifierChar(ch = this.fullCharCodeAt(next)));
7313 if (ch === 92) {
7314 return true;
7315 }
7316 var id = this.input.slice(idStart, next);
7317 if (keywordRelationalOperator.test(id)) {
7318 return false;
7319 }
7320 if (isFor && !isAwaitUsing && id === "of") {
7321 skipWhiteSpace.lastIndex = next;
7322 var skipAfterOf = skipWhiteSpace.exec(this.input);
7323 next = next + skipAfterOf[0].length;
7324 if (this.input.charCodeAt(next) !== 61 || // Check for ==, === and => operators
7325 (ch = this.input.charCodeAt(next + 1)) === 61 || ch === 62) {
7326 return false;
7327 }
7328 }
7329 return true;
7330 };
7331 pp$8.isAwaitUsing = function(isFor) {
7332 return this.isUsingKeyword(true, isFor);
7333 };
7334 pp$8.isUsing = function(isFor) {
7335 return this.isUsingKeyword(false, isFor);
7336 };
7337 pp$8.parseStatement = function(context, topLevel, exports$1) {
7338 var starttype = this.type, node = this.startNode(), kind;
7339 if (this.isLet(context)) {
7340 starttype = types$1._var;
7341 kind = "let";
7342 }
7343 switch (starttype) {
7344 case types$1._break:
7345 case types$1._continue:
7346 return this.parseBreakContinueStatement(node, starttype.keyword);
7347 case types$1._debugger:
7348 return this.parseDebuggerStatement(node);
7349 case types$1._do:
7350 return this.parseDoStatement(node);
7351 case types$1._for:
7352 return this.parseForStatement(node);
7353 case types$1._function:
7354 if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
7355 this.unexpected();
7356 }
7357 return this.parseFunctionStatement(node, false, !context);
7358 case types$1._class:
7359 if (context) {
7360 this.unexpected();
7361 }
7362 return this.parseClass(node, true);
7363 case types$1._if:
7364 return this.parseIfStatement(node);
7365 case types$1._return:
7366 return this.parseReturnStatement(node);
7367 case types$1._switch:
7368 return this.parseSwitchStatement(node);
7369 case types$1._throw:
7370 return this.parseThrowStatement(node);
7371 case types$1._try:
7372 return this.parseTryStatement(node);
7373 case types$1._const:
7374 case types$1._var:
7375 kind = kind || this.value;
7376 if (context && kind !== "var") {
7377 this.unexpected();
7378 }
7379 return this.parseVarStatement(node, kind);
7380 case types$1._while:
7381 return this.parseWhileStatement(node);
7382 case types$1._with:
7383 return this.parseWithStatement(node);
7384 case types$1.braceL:
7385 return this.parseBlock(true, node);
7386 case types$1.semi:
7387 return this.parseEmptyStatement(node);
7388 case types$1._export:
7389 case types$1._import:
7390 if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
7391 skipWhiteSpace.lastIndex = this.pos;
7392 var skip = skipWhiteSpace.exec(this.input);
7393 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
7394 if (nextCh === 40 || nextCh === 46) {
7395 return this.parseExpressionStatement(node, this.parseExpression());
7396 }
7397 }
7398 if (!this.options.allowImportExportEverywhere) {
7399 if (!topLevel) {
7400 this.raise(this.start, "'import' and 'export' may only appear at the top level");
7401 }
7402 if (!this.inModule) {
7403 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
7404 }
7405 }
7406 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports$1);
7407 // If the statement does not start with a statement keyword or a
7408 // brace, it's an ExpressionStatement or LabeledStatement. We
7409 // simply start parsing an expression, and afterwards, if the
7410 // next token is a colon and the expression was a simple
7411 // Identifier node, we switch to interpreting it as a label.
7412 default:
7413 if (this.isAsyncFunction()) {
7414 if (context) {
7415 this.unexpected();
7416 }
7417 this.next();
7418 return this.parseFunctionStatement(node, true, !context);
7419 }
7420 var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null;
7421 if (usingKind) {
7422 if (!this.allowUsing) {
7423 this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement");
7424 }
7425 if (context) {
7426 this.raise(this.start, "Using declaration is not allowed in single-statement positions");
7427 }
7428 if (usingKind === "await using") {
7429 if (!this.canAwait) {
7430 this.raise(this.start, "Await using cannot appear outside of async function");
7431 }
7432 this.next();
7433 }
7434 this.next();
7435 this.parseVar(node, false, usingKind);
7436 this.semicolon();
7437 return this.finishNode(node, "VariableDeclaration");
7438 }
7439 var maybeName = this.value, expr = this.parseExpression();
7440 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) {
7441 return this.parseLabeledStatement(node, maybeName, expr, context);
7442 } else {
7443 return this.parseExpressionStatement(node, expr);
7444 }
7445 }
7446 };
7447 pp$8.parseBreakContinueStatement = function(node, keyword) {
7448 var isBreak = keyword === "break";
7449 this.next();
7450 if (this.eat(types$1.semi) || this.insertSemicolon()) {
7451 node.label = null;
7452 } else if (this.type !== types$1.name) {
7453 this.unexpected();
7454 } else {
7455 node.label = this.parseIdent();
7456 this.semicolon();
7457 }
7458 var i2 = 0;
7459 for (; i2 < this.labels.length; ++i2) {
7460 var lab = this.labels[i2];
7461 if (node.label == null || lab.name === node.label.name) {
7462 if (lab.kind != null && (isBreak || lab.kind === "loop")) {
7463 break;
7464 }
7465 if (node.label && isBreak) {
7466 break;
7467 }
7468 }
7469 }
7470 if (i2 === this.labels.length) {
7471 this.raise(node.start, "Unsyntactic " + keyword);
7472 }
7473 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
7474 };
7475 pp$8.parseDebuggerStatement = function(node) {
7476 this.next();
7477 this.semicolon();
7478 return this.finishNode(node, "DebuggerStatement");
7479 };
7480 pp$8.parseDoStatement = function(node) {
7481 this.next();
7482 this.labels.push(loopLabel);
7483 node.body = this.parseStatement("do");
7484 this.labels.pop();
7485 this.expect(types$1._while);
7486 node.test = this.parseParenExpression();
7487 if (this.options.ecmaVersion >= 6) {
7488 this.eat(types$1.semi);
7489 } else {
7490 this.semicolon();
7491 }
7492 return this.finishNode(node, "DoWhileStatement");
7493 };
7494 pp$8.parseForStatement = function(node) {
7495 this.next();
7496 var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
7497 this.labels.push(loopLabel);
7498 this.enterScope(0);
7499 this.expect(types$1.parenL);
7500 if (this.type === types$1.semi) {
7501 if (awaitAt > -1) {
7502 this.unexpected(awaitAt);
7503 }
7504 return this.parseFor(node, null);
7505 }
7506 var isLet = this.isLet();
7507 if (this.type === types$1._var || this.type === types$1._const || isLet) {
7508 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
7509 this.next();
7510 this.parseVar(init$1, true, kind);
7511 this.finishNode(init$1, "VariableDeclaration");
7512 return this.parseForAfterInit(node, init$1, awaitAt);
7513 }
7514 var startsWithLet = this.isContextual("let"), isForOf = false;
7515 var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null;
7516 if (usingKind) {
7517 var init$2 = this.startNode();
7518 this.next();
7519 if (usingKind === "await using") {
7520 if (!this.canAwait) {
7521 this.raise(this.start, "Await using cannot appear outside of async function");
7522 }
7523 this.next();
7524 }
7525 this.parseVar(init$2, true, usingKind);
7526 this.finishNode(init$2, "VariableDeclaration");
7527 return this.parseForAfterInit(node, init$2, awaitAt);
7528 }
7529 var containsEsc = this.containsEsc;
7530 var refDestructuringErrors = new DestructuringErrors();
7531 var initPos = this.start;
7532 var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);
7533 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
7534 if (awaitAt > -1) {
7535 if (this.type === types$1._in) {
7536 this.unexpected(awaitAt);
7537 }
7538 node.await = true;
7539 } else if (isForOf && this.options.ecmaVersion >= 8) {
7540 if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") {
7541 this.unexpected();
7542 } else if (this.options.ecmaVersion >= 9) {
7543 node.await = false;
7544 }
7545 }
7546 if (startsWithLet && isForOf) {
7547 this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.");
7548 }
7549 this.toAssignable(init, false, refDestructuringErrors);
7550 this.checkLValPattern(init);
7551 return this.parseForIn(node, init);
7552 } else {
7553 this.checkExpressionErrors(refDestructuringErrors, true);
7554 }
7555 if (awaitAt > -1) {
7556 this.unexpected(awaitAt);
7557 }
7558 return this.parseFor(node, init);
7559 };
7560 pp$8.parseForAfterInit = function(node, init, awaitAt) {
7561 if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init.declarations.length === 1) {
7562 if (this.type === types$1._in) {
7563 if ((init.kind === "using" || init.kind === "await using") && !init.declarations[0].init) {
7564 this.raise(this.start, "Using declaration is not allowed in for-in loops");
7565 }
7566 if (this.options.ecmaVersion >= 9 && awaitAt > -1) {
7567 this.unexpected(awaitAt);
7568 }
7569 } else if (this.options.ecmaVersion >= 9) {
7570 node.await = awaitAt > -1;
7571 }
7572 return this.parseForIn(node, init);
7573 }
7574 if (awaitAt > -1) {
7575 this.unexpected(awaitAt);
7576 }
7577 return this.parseFor(node, init);
7578 };
7579 pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
7580 this.next();
7581 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync);
7582 };
7583 pp$8.parseIfStatement = function(node) {
7584 this.next();
7585 node.test = this.parseParenExpression();
7586 node.consequent = this.parseStatement("if");
7587 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
7588 return this.finishNode(node, "IfStatement");
7589 };
7590 pp$8.parseReturnStatement = function(node) {
7591 if (!this.allowReturn) {
7592 this.raise(this.start, "'return' outside of function");
7593 }
7594 this.next();
7595 if (this.eat(types$1.semi) || this.insertSemicolon()) {
7596 node.argument = null;
7597 } else {
7598 node.argument = this.parseExpression();
7599 this.semicolon();
7600 }
7601 return this.finishNode(node, "ReturnStatement");
7602 };
7603 pp$8.parseSwitchStatement = function(node) {
7604 this.next();
7605 node.discriminant = this.parseParenExpression();
7606 node.cases = [];
7607 this.expect(types$1.braceL);
7608 this.labels.push(switchLabel);
7609 this.enterScope(SCOPE_SWITCH);
7610 var cur;
7611 for (var sawDefault = false; this.type !== types$1.braceR; ) {
7612 if (this.type === types$1._case || this.type === types$1._default) {
7613 var isCase = this.type === types$1._case;
7614 if (cur) {
7615 this.finishNode(cur, "SwitchCase");
7616 }
7617 node.cases.push(cur = this.startNode());
7618 cur.consequent = [];
7619 this.next();
7620 if (isCase) {
7621 cur.test = this.parseExpression();
7622 } else {
7623 if (sawDefault) {
7624 this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
7625 }
7626 sawDefault = true;
7627 cur.test = null;
7628 }
7629 this.expect(types$1.colon);
7630 } else {
7631 if (!cur) {
7632 this.unexpected();
7633 }
7634 cur.consequent.push(this.parseStatement(null));
7635 }
7636 }
7637 this.exitScope();
7638 if (cur) {
7639 this.finishNode(cur, "SwitchCase");
7640 }
7641 this.next();
7642 this.labels.pop();
7643 return this.finishNode(node, "SwitchStatement");
7644 };
7645 pp$8.parseThrowStatement = function(node) {
7646 this.next();
7647 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
7648 this.raise(this.lastTokEnd, "Illegal newline after throw");
7649 }
7650 node.argument = this.parseExpression();
7651 this.semicolon();
7652 return this.finishNode(node, "ThrowStatement");
7653 };
7654 empty$1 = [];
7655 pp$8.parseCatchClauseParam = function() {
7656 var param = this.parseBindingAtom();
7657 var simple = param.type === "Identifier";
7658 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
7659 this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
7660 this.expect(types$1.parenR);
7661 return param;
7662 };
7663 pp$8.parseTryStatement = function(node) {
7664 this.next();
7665 node.block = this.parseBlock();
7666 node.handler = null;
7667 if (this.type === types$1._catch) {
7668 var clause = this.startNode();
7669 this.next();
7670 if (this.eat(types$1.parenL)) {
7671 clause.param = this.parseCatchClauseParam();
7672 } else {
7673 if (this.options.ecmaVersion < 10) {
7674 this.unexpected();
7675 }
7676 clause.param = null;
7677 this.enterScope(0);
7678 }
7679 clause.body = this.parseBlock(false);
7680 this.exitScope();
7681 node.handler = this.finishNode(clause, "CatchClause");
7682 }
7683 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
7684 if (!node.handler && !node.finalizer) {
7685 this.raise(node.start, "Missing catch or finally clause");
7686 }
7687 return this.finishNode(node, "TryStatement");
7688 };
7689 pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
7690 this.next();
7691 this.parseVar(node, false, kind, allowMissingInitializer);
7692 this.semicolon();
7693 return this.finishNode(node, "VariableDeclaration");
7694 };
7695 pp$8.parseWhileStatement = function(node) {
7696 this.next();
7697 node.test = this.parseParenExpression();
7698 this.labels.push(loopLabel);
7699 node.body = this.parseStatement("while");
7700 this.labels.pop();
7701 return this.finishNode(node, "WhileStatement");
7702 };
7703 pp$8.parseWithStatement = function(node) {
7704 if (this.strict) {
7705 this.raise(this.start, "'with' in strict mode");
7706 }
7707 this.next();
7708 node.object = this.parseParenExpression();
7709 node.body = this.parseStatement("with");
7710 return this.finishNode(node, "WithStatement");
7711 };
7712 pp$8.parseEmptyStatement = function(node) {
7713 this.next();
7714 return this.finishNode(node, "EmptyStatement");
7715 };
7716 pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
7717 for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
7718 var label = list2[i$1];
7719 if (label.name === maybeName) {
7720 this.raise(expr.start, "Label '" + maybeName + "' is already declared");
7721 }
7722 }
7723 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
7724 for (var i2 = this.labels.length - 1; i2 >= 0; i2--) {
7725 var label$1 = this.labels[i2];
7726 if (label$1.statementStart === node.start) {
7727 label$1.statementStart = this.start;
7728 label$1.kind = kind;
7729 } else {
7730 break;
7731 }
7732 }
7733 this.labels.push({ name: maybeName, kind, statementStart: this.start });
7734 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
7735 this.labels.pop();
7736 node.label = expr;
7737 return this.finishNode(node, "LabeledStatement");
7738 };
7739 pp$8.parseExpressionStatement = function(node, expr) {
7740 node.expression = expr;
7741 this.semicolon();
7742 return this.finishNode(node, "ExpressionStatement");
7743 };
7744 pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
7745 if (createNewLexicalScope === void 0) createNewLexicalScope = true;
7746 if (node === void 0) node = this.startNode();
7747 node.body = [];
7748 this.expect(types$1.braceL);
7749 if (createNewLexicalScope) {
7750 this.enterScope(0);
7751 }
7752 while (this.type !== types$1.braceR) {
7753 var stmt = this.parseStatement(null);
7754 node.body.push(stmt);
7755 }
7756 if (exitStrict) {
7757 this.strict = false;
7758 }
7759 this.next();
7760 if (createNewLexicalScope) {
7761 this.exitScope();
7762 }
7763 return this.finishNode(node, "BlockStatement");
7764 };
7765 pp$8.parseFor = function(node, init) {
7766 node.init = init;
7767 this.expect(types$1.semi);
7768 node.test = this.type === types$1.semi ? null : this.parseExpression();
7769 this.expect(types$1.semi);
7770 node.update = this.type === types$1.parenR ? null : this.parseExpression();
7771 this.expect(types$1.parenR);
7772 node.body = this.parseStatement("for");
7773 this.exitScope();
7774 this.labels.pop();
7775 return this.finishNode(node, "ForStatement");
7776 };
7777 pp$8.parseForIn = function(node, init) {
7778 var isForIn = this.type === types$1._in;
7779 this.next();
7780 if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
7781 this.raise(
7782 init.start,
7783 (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer"
7784 );
7785 }
7786 node.left = init;
7787 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
7788 this.expect(types$1.parenR);
7789 node.body = this.parseStatement("for");
7790 this.exitScope();
7791 this.labels.pop();
7792 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
7793 };
7794 pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
7795 node.declarations = [];
7796 node.kind = kind;
7797 for (; ; ) {
7798 var decl = this.startNode();
7799 this.parseVarId(decl, kind);
7800 if (this.eat(types$1.eq)) {
7801 decl.init = this.parseMaybeAssign(isFor);
7802 } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
7803 this.unexpected();
7804 } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual("of")) {
7805 this.raise(this.lastTokEnd, "Missing initializer in " + kind + " declaration");
7806 } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
7807 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
7808 } else {
7809 decl.init = null;
7810 }
7811 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
7812 if (!this.eat(types$1.comma)) {
7813 break;
7814 }
7815 }
7816 return node;
7817 };
7818 pp$8.parseVarId = function(decl, kind) {
7819 decl.id = kind === "using" || kind === "await using" ? this.parseIdent() : this.parseBindingAtom();
7820 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
7821 };
7822 FUNC_STATEMENT = 1;
7823 FUNC_HANGING_STATEMENT = 2;
7824 FUNC_NULLABLE_ID = 4;
7825 pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
7826 this.initFunction(node);
7827 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
7828 if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) {
7829 this.unexpected();
7830 }
7831 node.generator = this.eat(types$1.star);
7832 }
7833 if (this.options.ecmaVersion >= 8) {
7834 node.async = !!isAsync;
7835 }
7836 if (statement & FUNC_STATEMENT) {
7837 node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent();
7838 if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {
7839 this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
7840 }
7841 }
7842 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
7843 this.yieldPos = 0;
7844 this.awaitPos = 0;
7845 this.awaitIdentPos = 0;
7846 this.enterScope(functionFlags(node.async, node.generator));
7847 if (!(statement & FUNC_STATEMENT)) {
7848 node.id = this.type === types$1.name ? this.parseIdent() : null;
7849 }
7850 this.parseFunctionParams(node);
7851 this.parseFunctionBody(node, allowExpressionBody, false, forInit);
7852 this.yieldPos = oldYieldPos;
7853 this.awaitPos = oldAwaitPos;
7854 this.awaitIdentPos = oldAwaitIdentPos;
7855 return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
7856 };
7857 pp$8.parseFunctionParams = function(node) {
7858 this.expect(types$1.parenL);
7859 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
7860 this.checkYieldAwaitInDefaultParams();
7861 };
7862 pp$8.parseClass = function(node, isStatement) {
7863 this.next();
7864 var oldStrict = this.strict;
7865 this.strict = true;
7866 this.parseClassId(node, isStatement);
7867 this.parseClassSuper(node);
7868 var privateNameMap = this.enterClassBody();
7869 var classBody = this.startNode();
7870 var hadConstructor = false;
7871 classBody.body = [];
7872 this.expect(types$1.braceL);
7873 while (this.type !== types$1.braceR) {
7874 var element = this.parseClassElement(node.superClass !== null);
7875 if (element) {
7876 classBody.body.push(element);
7877 if (element.type === "MethodDefinition" && element.kind === "constructor") {
7878 if (hadConstructor) {
7879 this.raiseRecoverable(element.start, "Duplicate constructor in the same class");
7880 }
7881 hadConstructor = true;
7882 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
7883 this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
7884 }
7885 }
7886 }
7887 this.strict = oldStrict;
7888 this.next();
7889 node.body = this.finishNode(classBody, "ClassBody");
7890 this.exitClassBody();
7891 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
7892 };
7893 pp$8.parseClassElement = function(constructorAllowsSuper) {
7894 if (this.eat(types$1.semi)) {
7895 return null;
7896 }
7897 var ecmaVersion2 = this.options.ecmaVersion;
7898 var node = this.startNode();
7899 var keyName = "";
7900 var isGenerator = false;
7901 var isAsync = false;
7902 var kind = "method";
7903 var isStatic = false;
7904 if (this.eatContextual("static")) {
7905 if (ecmaVersion2 >= 13 && this.eat(types$1.braceL)) {
7906 this.parseClassStaticBlock(node);
7907 return node;
7908 }
7909 if (this.isClassElementNameStart() || this.type === types$1.star) {
7910 isStatic = true;
7911 } else {
7912 keyName = "static";
7913 }
7914 }
7915 node.static = isStatic;
7916 if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) {
7917 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
7918 isAsync = true;
7919 } else {
7920 keyName = "async";
7921 }
7922 }
7923 if (!keyName && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {
7924 isGenerator = true;
7925 }
7926 if (!keyName && !isAsync && !isGenerator) {
7927 var lastValue = this.value;
7928 if (this.eatContextual("get") || this.eatContextual("set")) {
7929 if (this.isClassElementNameStart()) {
7930 kind = lastValue;
7931 } else {
7932 keyName = lastValue;
7933 }
7934 }
7935 }
7936 if (keyName) {
7937 node.computed = false;
7938 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
7939 node.key.name = keyName;
7940 this.finishNode(node.key, "Identifier");
7941 } else {
7942 this.parseClassElementName(node);
7943 }
7944 if (ecmaVersion2 < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
7945 var isConstructor2 = !node.static && checkKeyName(node, "constructor");
7946 var allowsDirectSuper = isConstructor2 && constructorAllowsSuper;
7947 if (isConstructor2 && kind !== "method") {
7948 this.raise(node.key.start, "Constructor can't have get/set modifier");
7949 }
7950 node.kind = isConstructor2 ? "constructor" : kind;
7951 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
7952 } else {
7953 this.parseClassField(node);
7954 }
7955 return node;
7956 };
7957 pp$8.isClassElementNameStart = function() {
7958 return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword;
7959 };
7960 pp$8.parseClassElementName = function(element) {
7961 if (this.type === types$1.privateId) {
7962 if (this.value === "constructor") {
7963 this.raise(this.start, "Classes can't have an element named '#constructor'");
7964 }
7965 element.computed = false;
7966 element.key = this.parsePrivateIdent();
7967 } else {
7968 this.parsePropertyName(element);
7969 }
7970 };
7971 pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
7972 var key = method.key;
7973 if (method.kind === "constructor") {
7974 if (isGenerator) {
7975 this.raise(key.start, "Constructor can't be a generator");
7976 }
7977 if (isAsync) {
7978 this.raise(key.start, "Constructor can't be an async method");
7979 }
7980 } else if (method.static && checkKeyName(method, "prototype")) {
7981 this.raise(key.start, "Classes may not have a static property named prototype");
7982 }
7983 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
7984 if (method.kind === "get" && value.params.length !== 0) {
7985 this.raiseRecoverable(value.start, "getter should have no params");
7986 }
7987 if (method.kind === "set" && value.params.length !== 1) {
7988 this.raiseRecoverable(value.start, "setter should have exactly one param");
7989 }
7990 if (method.kind === "set" && value.params[0].type === "RestElement") {
7991 this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
7992 }
7993 return this.finishNode(method, "MethodDefinition");
7994 };
7995 pp$8.parseClassField = function(field) {
7996 if (checkKeyName(field, "constructor")) {
7997 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
7998 } else if (field.static && checkKeyName(field, "prototype")) {
7999 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
8000 }
8001 if (this.eat(types$1.eq)) {
8002 this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER);
8003 field.value = this.parseMaybeAssign();
8004 this.exitScope();
8005 } else {
8006 field.value = null;
8007 }
8008 this.semicolon();
8009 return this.finishNode(field, "PropertyDefinition");
8010 };
8011 pp$8.parseClassStaticBlock = function(node) {
8012 node.body = [];
8013 var oldLabels = this.labels;
8014 this.labels = [];
8015 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
8016 while (this.type !== types$1.braceR) {
8017 var stmt = this.parseStatement(null);
8018 node.body.push(stmt);
8019 }
8020 this.next();
8021 this.exitScope();
8022 this.labels = oldLabels;
8023 return this.finishNode(node, "StaticBlock");
8024 };
8025 pp$8.parseClassId = function(node, isStatement) {
8026 if (this.type === types$1.name) {
8027 node.id = this.parseIdent();
8028 if (isStatement) {
8029 this.checkLValSimple(node.id, BIND_LEXICAL, false);
8030 }
8031 } else {
8032 if (isStatement === true) {
8033 this.unexpected();
8034 }
8035 node.id = null;
8036 }
8037 };
8038 pp$8.parseClassSuper = function(node) {
8039 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
8040 };
8041 pp$8.enterClassBody = function() {
8042 var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };
8043 this.privateNameStack.push(element);
8044 return element.declared;
8045 };
8046 pp$8.exitClassBody = function() {
8047 var ref2 = this.privateNameStack.pop();
8048 var declared = ref2.declared;
8049 var used = ref2.used;
8050 if (!this.options.checkPrivateFields) {
8051 return;
8052 }
8053 var len = this.privateNameStack.length;
8054 var parent = len === 0 ? null : this.privateNameStack[len - 1];
8055 for (var i2 = 0; i2 < used.length; ++i2) {
8056 var id = used[i2];
8057 if (!hasOwn(declared, id.name)) {
8058 if (parent) {
8059 parent.used.push(id);
8060 } else {
8061 this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
8062 }
8063 }
8064 }
8065 };
8066 pp$8.parseExportAllDeclaration = function(node, exports$1) {
8067 if (this.options.ecmaVersion >= 11) {
8068 if (this.eatContextual("as")) {
8069 node.exported = this.parseModuleExportName();
8070 this.checkExport(exports$1, node.exported, this.lastTokStart);
8071 } else {
8072 node.exported = null;
8073 }
8074 }
8075 this.expectContextual("from");
8076 if (this.type !== types$1.string) {
8077 this.unexpected();
8078 }
8079 node.source = this.parseExprAtom();
8080 if (this.options.ecmaVersion >= 16) {
8081 node.attributes = this.parseWithClause();
8082 }
8083 this.semicolon();
8084 return this.finishNode(node, "ExportAllDeclaration");
8085 };
8086 pp$8.parseExport = function(node, exports$1) {
8087 this.next();
8088 if (this.eat(types$1.star)) {
8089 return this.parseExportAllDeclaration(node, exports$1);
8090 }
8091 if (this.eat(types$1._default)) {
8092 this.checkExport(exports$1, "default", this.lastTokStart);
8093 node.declaration = this.parseExportDefaultDeclaration();
8094 return this.finishNode(node, "ExportDefaultDeclaration");
8095 }
8096 if (this.shouldParseExportStatement()) {
8097 node.declaration = this.parseExportDeclaration(node);
8098 if (node.declaration.type === "VariableDeclaration") {
8099 this.checkVariableExport(exports$1, node.declaration.declarations);
8100 } else {
8101 this.checkExport(exports$1, node.declaration.id, node.declaration.id.start);
8102 }
8103 node.specifiers = [];
8104 node.source = null;
8105 if (this.options.ecmaVersion >= 16) {
8106 node.attributes = [];
8107 }
8108 } else {
8109 node.declaration = null;
8110 node.specifiers = this.parseExportSpecifiers(exports$1);
8111 if (this.eatContextual("from")) {
8112 if (this.type !== types$1.string) {
8113 this.unexpected();
8114 }
8115 node.source = this.parseExprAtom();
8116 if (this.options.ecmaVersion >= 16) {
8117 node.attributes = this.parseWithClause();
8118 }
8119 } else {
8120 for (var i2 = 0, list2 = node.specifiers; i2 < list2.length; i2 += 1) {
8121 var spec = list2[i2];
8122 this.checkUnreserved(spec.local);
8123 this.checkLocalExport(spec.local);
8124 if (spec.local.type === "Literal") {
8125 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
8126 }
8127 }
8128 node.source = null;
8129 if (this.options.ecmaVersion >= 16) {
8130 node.attributes = [];
8131 }
8132 }
8133 this.semicolon();
8134 }
8135 return this.finishNode(node, "ExportNamedDeclaration");
8136 };
8137 pp$8.parseExportDeclaration = function(node) {
8138 return this.parseStatement(null);
8139 };
8140 pp$8.parseExportDefaultDeclaration = function() {
8141 var isAsync;
8142 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
8143 var fNode = this.startNode();
8144 this.next();
8145 if (isAsync) {
8146 this.next();
8147 }
8148 return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
8149 } else if (this.type === types$1._class) {
8150 var cNode = this.startNode();
8151 return this.parseClass(cNode, "nullableID");
8152 } else {
8153 var declaration = this.parseMaybeAssign();
8154 this.semicolon();
8155 return declaration;
8156 }
8157 };
8158 pp$8.checkExport = function(exports$1, name, pos) {
8159 if (!exports$1) {
8160 return;
8161 }
8162 if (typeof name !== "string") {
8163 name = name.type === "Identifier" ? name.name : name.value;
8164 }
8165 if (hasOwn(exports$1, name)) {
8166 this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
8167 }
8168 exports$1[name] = true;
8169 };
8170 pp$8.checkPatternExport = function(exports$1, pat) {
8171 var type2 = pat.type;
8172 if (type2 === "Identifier") {
8173 this.checkExport(exports$1, pat, pat.start);
8174 } else if (type2 === "ObjectPattern") {
8175 for (var i2 = 0, list2 = pat.properties; i2 < list2.length; i2 += 1) {
8176 var prop = list2[i2];
8177 this.checkPatternExport(exports$1, prop);
8178 }
8179 } else if (type2 === "ArrayPattern") {
8180 for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
8181 var elt = list$1[i$1];
8182 if (elt) {
8183 this.checkPatternExport(exports$1, elt);
8184 }
8185 }
8186 } else if (type2 === "Property") {
8187 this.checkPatternExport(exports$1, pat.value);
8188 } else if (type2 === "AssignmentPattern") {
8189 this.checkPatternExport(exports$1, pat.left);
8190 } else if (type2 === "RestElement") {
8191 this.checkPatternExport(exports$1, pat.argument);
8192 }
8193 };
8194 pp$8.checkVariableExport = function(exports$1, decls) {
8195 if (!exports$1) {
8196 return;
8197 }
8198 for (var i2 = 0, list2 = decls; i2 < list2.length; i2 += 1) {
8199 var decl = list2[i2];
8200 this.checkPatternExport(exports$1, decl.id);
8201 }
8202 };
8203 pp$8.shouldParseExportStatement = function() {
8204 return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
8205 };
8206 pp$8.parseExportSpecifier = function(exports$1) {
8207 var node = this.startNode();
8208 node.local = this.parseModuleExportName();
8209 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
8210 this.checkExport(
8211 exports$1,
8212 node.exported,
8213 node.exported.start
8214 );
8215 return this.finishNode(node, "ExportSpecifier");
8216 };
8217 pp$8.parseExportSpecifiers = function(exports$1) {
8218 var nodes = [], first = true;
8219 this.expect(types$1.braceL);
8220 while (!this.eat(types$1.braceR)) {
8221 if (!first) {
8222 this.expect(types$1.comma);
8223 if (this.afterTrailingComma(types$1.braceR)) {
8224 break;
8225 }
8226 } else {
8227 first = false;
8228 }
8229 nodes.push(this.parseExportSpecifier(exports$1));
8230 }
8231 return nodes;
8232 };
8233 pp$8.parseImport = function(node) {
8234 this.next();
8235 if (this.type === types$1.string) {
8236 node.specifiers = empty$1;
8237 node.source = this.parseExprAtom();
8238 } else {
8239 node.specifiers = this.parseImportSpecifiers();
8240 this.expectContextual("from");
8241 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
8242 }
8243 if (this.options.ecmaVersion >= 16) {
8244 node.attributes = this.parseWithClause();
8245 }
8246 this.semicolon();
8247 return this.finishNode(node, "ImportDeclaration");
8248 };
8249 pp$8.parseImportSpecifier = function() {
8250 var node = this.startNode();
8251 node.imported = this.parseModuleExportName();
8252 if (this.eatContextual("as")) {
8253 node.local = this.parseIdent();
8254 } else {
8255 this.checkUnreserved(node.imported);
8256 node.local = node.imported;
8257 }
8258 this.checkLValSimple(node.local, BIND_LEXICAL);
8259 return this.finishNode(node, "ImportSpecifier");
8260 };
8261 pp$8.parseImportDefaultSpecifier = function() {
8262 var node = this.startNode();
8263 node.local = this.parseIdent();
8264 this.checkLValSimple(node.local, BIND_LEXICAL);
8265 return this.finishNode(node, "ImportDefaultSpecifier");
8266 };
8267 pp$8.parseImportNamespaceSpecifier = function() {
8268 var node = this.startNode();
8269 this.next();
8270 this.expectContextual("as");
8271 node.local = this.parseIdent();
8272 this.checkLValSimple(node.local, BIND_LEXICAL);
8273 return this.finishNode(node, "ImportNamespaceSpecifier");
8274 };
8275 pp$8.parseImportSpecifiers = function() {
8276 var nodes = [], first = true;
8277 if (this.type === types$1.name) {
8278 nodes.push(this.parseImportDefaultSpecifier());
8279 if (!this.eat(types$1.comma)) {
8280 return nodes;
8281 }
8282 }
8283 if (this.type === types$1.star) {
8284 nodes.push(this.parseImportNamespaceSpecifier());
8285 return nodes;
8286 }
8287 this.expect(types$1.braceL);
8288 while (!this.eat(types$1.braceR)) {
8289 if (!first) {
8290 this.expect(types$1.comma);
8291 if (this.afterTrailingComma(types$1.braceR)) {
8292 break;
8293 }
8294 } else {
8295 first = false;
8296 }
8297 nodes.push(this.parseImportSpecifier());
8298 }
8299 return nodes;
8300 };
8301 pp$8.parseWithClause = function() {
8302 var nodes = [];
8303 if (!this.eat(types$1._with)) {
8304 return nodes;
8305 }
8306 this.expect(types$1.braceL);
8307 var attributeKeys = {};
8308 var first = true;
8309 while (!this.eat(types$1.braceR)) {
8310 if (!first) {
8311 this.expect(types$1.comma);
8312 if (this.afterTrailingComma(types$1.braceR)) {
8313 break;
8314 }
8315 } else {
8316 first = false;
8317 }
8318 var attr = this.parseImportAttribute();
8319 var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
8320 if (hasOwn(attributeKeys, keyName)) {
8321 this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
8322 }
8323 attributeKeys[keyName] = true;
8324 nodes.push(attr);
8325 }
8326 return nodes;
8327 };
8328 pp$8.parseImportAttribute = function() {
8329 var node = this.startNode();
8330 node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
8331 this.expect(types$1.colon);
8332 if (this.type !== types$1.string) {
8333 this.unexpected();
8334 }
8335 node.value = this.parseExprAtom();
8336 return this.finishNode(node, "ImportAttribute");
8337 };
8338 pp$8.parseModuleExportName = function() {
8339 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
8340 var stringLiteral = this.parseLiteral(this.value);
8341 if (loneSurrogate.test(stringLiteral.value)) {
8342 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
8343 }
8344 return stringLiteral;
8345 }
8346 return this.parseIdent(true);
8347 };
8348 pp$8.adaptDirectivePrologue = function(statements) {
8349 for (var i2 = 0; i2 < statements.length && this.isDirectiveCandidate(statements[i2]); ++i2) {
8350 statements[i2].directive = statements[i2].expression.raw.slice(1, -1);
8351 }
8352 };
8353 pp$8.isDirectiveCandidate = function(statement) {
8354 return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings.
8355 (this.input[statement.start] === '"' || this.input[statement.start] === "'");
8356 };
8357 pp$7 = Parser.prototype;
8358 pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
8359 if (this.options.ecmaVersion >= 6 && node) {
8360 switch (node.type) {
8361 case "Identifier":
8362 if (this.inAsync && node.name === "await") {
8363 this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
8364 }
8365 break;
8366 case "ObjectPattern":
8367 case "ArrayPattern":
8368 case "AssignmentPattern":
8369 case "RestElement":
8370 break;
8371 case "ObjectExpression":
8372 node.type = "ObjectPattern";
8373 if (refDestructuringErrors) {
8374 this.checkPatternErrors(refDestructuringErrors, true);
8375 }
8376 for (var i2 = 0, list2 = node.properties; i2 < list2.length; i2 += 1) {
8377 var prop = list2[i2];
8378 this.toAssignable(prop, isBinding);
8379 if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
8380 this.raise(prop.argument.start, "Unexpected token");
8381 }
8382 }
8383 break;
8384 case "Property":
8385 if (node.kind !== "init") {
8386 this.raise(node.key.start, "Object pattern can't contain getter or setter");
8387 }
8388 this.toAssignable(node.value, isBinding);
8389 break;
8390 case "ArrayExpression":
8391 node.type = "ArrayPattern";
8392 if (refDestructuringErrors) {
8393 this.checkPatternErrors(refDestructuringErrors, true);
8394 }
8395 this.toAssignableList(node.elements, isBinding);
8396 break;
8397 case "SpreadElement":
8398 node.type = "RestElement";
8399 this.toAssignable(node.argument, isBinding);
8400 if (node.argument.type === "AssignmentPattern") {
8401 this.raise(node.argument.start, "Rest elements cannot have a default value");
8402 }
8403 break;
8404 case "AssignmentExpression":
8405 if (node.operator !== "=") {
8406 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
8407 }
8408 node.type = "AssignmentPattern";
8409 delete node.operator;
8410 this.toAssignable(node.left, isBinding);
8411 break;
8412 case "ParenthesizedExpression":
8413 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
8414 break;
8415 case "ChainExpression":
8416 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
8417 break;
8418 case "MemberExpression":
8419 if (!isBinding) {
8420 break;
8421 }
8422 default:
8423 this.raise(node.start, "Assigning to rvalue");
8424 }
8425 } else if (refDestructuringErrors) {
8426 this.checkPatternErrors(refDestructuringErrors, true);
8427 }
8428 return node;
8429 };
8430 pp$7.toAssignableList = function(exprList, isBinding) {
8431 var end = exprList.length;
8432 for (var i2 = 0; i2 < end; i2++) {
8433 var elt = exprList[i2];
8434 if (elt) {
8435 this.toAssignable(elt, isBinding);
8436 }
8437 }
8438 if (end) {
8439 var last = exprList[end - 1];
8440 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
8441 this.unexpected(last.argument.start);
8442 }
8443 }
8444 return exprList;
8445 };
8446 pp$7.parseSpread = function(refDestructuringErrors) {
8447 var node = this.startNode();
8448 this.next();
8449 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
8450 return this.finishNode(node, "SpreadElement");
8451 };
8452 pp$7.parseRestBinding = function() {
8453 var node = this.startNode();
8454 this.next();
8455 if (this.options.ecmaVersion === 6 && this.type !== types$1.name) {
8456 this.unexpected();
8457 }
8458 node.argument = this.parseBindingAtom();
8459 return this.finishNode(node, "RestElement");
8460 };
8461 pp$7.parseBindingAtom = function() {
8462 if (this.options.ecmaVersion >= 6) {
8463 switch (this.type) {
8464 case types$1.bracketL:
8465 var node = this.startNode();
8466 this.next();
8467 node.elements = this.parseBindingList(types$1.bracketR, true, true);
8468 return this.finishNode(node, "ArrayPattern");
8469 case types$1.braceL:
8470 return this.parseObj(true);
8471 }
8472 }
8473 return this.parseIdent();
8474 };
8475 pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
8476 var elts = [], first = true;
8477 while (!this.eat(close)) {
8478 if (first) {
8479 first = false;
8480 } else {
8481 this.expect(types$1.comma);
8482 }
8483 if (allowEmpty && this.type === types$1.comma) {
8484 elts.push(null);
8485 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
8486 break;
8487 } else if (this.type === types$1.ellipsis) {
8488 var rest = this.parseRestBinding();
8489 this.parseBindingListItem(rest);
8490 elts.push(rest);
8491 if (this.type === types$1.comma) {
8492 this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
8493 }
8494 this.expect(close);
8495 break;
8496 } else {
8497 elts.push(this.parseAssignableListItem(allowModifiers));
8498 }
8499 }
8500 return elts;
8501 };
8502 pp$7.parseAssignableListItem = function(allowModifiers) {
8503 var elem = this.parseMaybeDefault(this.start, this.startLoc);
8504 this.parseBindingListItem(elem);
8505 return elem;
8506 };
8507 pp$7.parseBindingListItem = function(param) {
8508 return param;
8509 };
8510 pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
8511 left = left || this.parseBindingAtom();
8512 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) {
8513 return left;
8514 }
8515 var node = this.startNodeAt(startPos, startLoc);
8516 node.left = left;
8517 node.right = this.parseMaybeAssign();
8518 return this.finishNode(node, "AssignmentPattern");
8519 };
8520 pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
8521 if (bindingType === void 0) bindingType = BIND_NONE;
8522 var isBind = bindingType !== BIND_NONE;
8523 switch (expr.type) {
8524 case "Identifier":
8525 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
8526 this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
8527 }
8528 if (isBind) {
8529 if (bindingType === BIND_LEXICAL && expr.name === "let") {
8530 this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
8531 }
8532 if (checkClashes) {
8533 if (hasOwn(checkClashes, expr.name)) {
8534 this.raiseRecoverable(expr.start, "Argument name clash");
8535 }
8536 checkClashes[expr.name] = true;
8537 }
8538 if (bindingType !== BIND_OUTSIDE) {
8539 this.declareName(expr.name, bindingType, expr.start);
8540 }
8541 }
8542 break;
8543 case "ChainExpression":
8544 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
8545 break;
8546 case "MemberExpression":
8547 if (isBind) {
8548 this.raiseRecoverable(expr.start, "Binding member expression");
8549 }
8550 break;
8551 case "ParenthesizedExpression":
8552 if (isBind) {
8553 this.raiseRecoverable(expr.start, "Binding parenthesized expression");
8554 }
8555 return this.checkLValSimple(expr.expression, bindingType, checkClashes);
8556 default:
8557 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
8558 }
8559 };
8560 pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
8561 if (bindingType === void 0) bindingType = BIND_NONE;
8562 switch (expr.type) {
8563 case "ObjectPattern":
8564 for (var i2 = 0, list2 = expr.properties; i2 < list2.length; i2 += 1) {
8565 var prop = list2[i2];
8566 this.checkLValInnerPattern(prop, bindingType, checkClashes);
8567 }
8568 break;
8569 case "ArrayPattern":
8570 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
8571 var elem = list$1[i$1];
8572 if (elem) {
8573 this.checkLValInnerPattern(elem, bindingType, checkClashes);
8574 }
8575 }
8576 break;
8577 default:
8578 this.checkLValSimple(expr, bindingType, checkClashes);
8579 }
8580 };
8581 pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
8582 if (bindingType === void 0) bindingType = BIND_NONE;
8583 switch (expr.type) {
8584 case "Property":
8585 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
8586 break;
8587 case "AssignmentPattern":
8588 this.checkLValPattern(expr.left, bindingType, checkClashes);
8589 break;
8590 case "RestElement":
8591 this.checkLValPattern(expr.argument, bindingType, checkClashes);
8592 break;
8593 default:
8594 this.checkLValPattern(expr, bindingType, checkClashes);
8595 }
8596 };
8597 TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) {
8598 this.token = token;
8599 this.isExpr = !!isExpr;
8600 this.preserveSpace = !!preserveSpace;
8601 this.override = override;
8602 this.generator = !!generator;
8603 };
8604 types2 = {
8605 b_stat: new TokContext("{", false),
8606 b_expr: new TokContext("{", true),
8607 b_tmpl: new TokContext("${", false),
8608 p_stat: new TokContext("(", false),
8609 p_expr: new TokContext("(", true),
8610 q_tmpl: new TokContext("`", true, true, function(p) {
8611 return p.tryReadTemplateToken();
8612 }),
8613 f_stat: new TokContext("function", false),
8614 f_expr: new TokContext("function", true),
8615 f_expr_gen: new TokContext("function", true, false, null, true),
8616 f_gen: new TokContext("function", false, false, null, true)
8617 };
8618 pp$6 = Parser.prototype;
8619 pp$6.initialContext = function() {
8620 return [types2.b_stat];
8621 };
8622 pp$6.curContext = function() {
8623 return this.context[this.context.length - 1];
8624 };
8625 pp$6.braceIsBlock = function(prevType) {
8626 var parent = this.curContext();
8627 if (parent === types2.f_expr || parent === types2.f_stat) {
8628 return true;
8629 }
8630 if (prevType === types$1.colon && (parent === types2.b_stat || parent === types2.b_expr)) {
8631 return !parent.isExpr;
8632 }
8633 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) {
8634 return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
8635 }
8636 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) {
8637 return true;
8638 }
8639 if (prevType === types$1.braceL) {
8640 return parent === types2.b_stat;
8641 }
8642 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) {
8643 return false;
8644 }
8645 return !this.exprAllowed;
8646 };
8647 pp$6.inGeneratorContext = function() {
8648 for (var i2 = this.context.length - 1; i2 >= 1; i2--) {
8649 var context = this.context[i2];
8650 if (context.token === "function") {
8651 return context.generator;
8652 }
8653 }
8654 return false;
8655 };
8656 pp$6.updateContext = function(prevType) {
8657 var update, type2 = this.type;
8658 if (type2.keyword && prevType === types$1.dot) {
8659 this.exprAllowed = false;
8660 } else if (update = type2.updateContext) {
8661 update.call(this, prevType);
8662 } else {
8663 this.exprAllowed = type2.beforeExpr;
8664 }
8665 };
8666 pp$6.overrideContext = function(tokenCtx) {
8667 if (this.curContext() !== tokenCtx) {
8668 this.context[this.context.length - 1] = tokenCtx;
8669 }
8670 };
8671 types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
8672 if (this.context.length === 1) {
8673 this.exprAllowed = true;
8674 return;
8675 }
8676 var out = this.context.pop();
8677 if (out === types2.b_stat && this.curContext().token === "function") {
8678 out = this.context.pop();
8679 }
8680 this.exprAllowed = !out.isExpr;
8681 };
8682 types$1.braceL.updateContext = function(prevType) {
8683 this.context.push(this.braceIsBlock(prevType) ? types2.b_stat : types2.b_expr);
8684 this.exprAllowed = true;
8685 };
8686 types$1.dollarBraceL.updateContext = function() {
8687 this.context.push(types2.b_tmpl);
8688 this.exprAllowed = true;
8689 };
8690 types$1.parenL.updateContext = function(prevType) {
8691 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
8692 this.context.push(statementParens ? types2.p_stat : types2.p_expr);
8693 this.exprAllowed = true;
8694 };
8695 types$1.incDec.updateContext = function() {
8696 };
8697 types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
8698 if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types2.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types2.b_stat)) {
8699 this.context.push(types2.f_expr);
8700 } else {
8701 this.context.push(types2.f_stat);
8702 }
8703 this.exprAllowed = false;
8704 };
8705 types$1.colon.updateContext = function() {
8706 if (this.curContext().token === "function") {
8707 this.context.pop();
8708 }
8709 this.exprAllowed = true;
8710 };
8711 types$1.backQuote.updateContext = function() {
8712 if (this.curContext() === types2.q_tmpl) {
8713 this.context.pop();
8714 } else {
8715 this.context.push(types2.q_tmpl);
8716 }
8717 this.exprAllowed = false;
8718 };
8719 types$1.star.updateContext = function(prevType) {
8720 if (prevType === types$1._function) {
8721 var index = this.context.length - 1;
8722 if (this.context[index] === types2.f_expr) {
8723 this.context[index] = types2.f_expr_gen;
8724 } else {
8725 this.context[index] = types2.f_gen;
8726 }
8727 }
8728 this.exprAllowed = true;
8729 };
8730 types$1.name.updateContext = function(prevType) {
8731 var allowed = false;
8732 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
8733 if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
8734 allowed = true;
8735 }
8736 }
8737 this.exprAllowed = allowed;
8738 };
8739 pp$5 = Parser.prototype;
8740 pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
8741 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
8742 return;
8743 }
8744 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
8745 return;
8746 }
8747 var key = prop.key;
8748 var name;
8749 switch (key.type) {
8750 case "Identifier":
8751 name = key.name;
8752 break;
8753 case "Literal":
8754 name = String(key.value);
8755 break;
8756 default:
8757 return;
8758 }
8759 var kind = prop.kind;
8760 if (this.options.ecmaVersion >= 6) {
8761 if (name === "__proto__" && kind === "init") {
8762 if (propHash.proto) {
8763 if (refDestructuringErrors) {
8764 if (refDestructuringErrors.doubleProto < 0) {
8765 refDestructuringErrors.doubleProto = key.start;
8766 }
8767 } else {
8768 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
8769 }
8770 }
8771 propHash.proto = true;
8772 }
8773 return;
8774 }
8775 name = "$" + name;
8776 var other = propHash[name];
8777 if (other) {
8778 var redefinition;
8779 if (kind === "init") {
8780 redefinition = this.strict && other.init || other.get || other.set;
8781 } else {
8782 redefinition = other.init || other[kind];
8783 }
8784 if (redefinition) {
8785 this.raiseRecoverable(key.start, "Redefinition of property");
8786 }
8787 } else {
8788 other = propHash[name] = {
8789 init: false,
8790 get: false,
8791 set: false
8792 };
8793 }
8794 other[kind] = true;
8795 };
8796 pp$5.parseExpression = function(forInit, refDestructuringErrors) {
8797 var this$1$1 = this;
8798 return this.catchStackOverflow(function() {
8799 var startPos = this$1$1.start, startLoc = this$1$1.startLoc;
8800 var expr = this$1$1.parseMaybeAssign(forInit, refDestructuringErrors);
8801 if (this$1$1.type === types$1.comma) {
8802 var node = this$1$1.startNodeAt(startPos, startLoc);
8803 node.expressions = [expr];
8804 while (this$1$1.eat(types$1.comma)) {
8805 node.expressions.push(this$1$1.parseMaybeAssign(forInit, refDestructuringErrors));
8806 }
8807 return this$1$1.finishNode(node, "SequenceExpression");
8808 }
8809 return expr;
8810 });
8811 };
8812 pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
8813 if (this.isContextual("yield")) {
8814 if (this.inGenerator) {
8815 return this.parseYield(forInit);
8816 } else {
8817 this.exprAllowed = false;
8818 }
8819 }
8820 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
8821 if (refDestructuringErrors) {
8822 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
8823 oldTrailingComma = refDestructuringErrors.trailingComma;
8824 oldDoubleProto = refDestructuringErrors.doubleProto;
8825 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
8826 } else {
8827 refDestructuringErrors = new DestructuringErrors();
8828 ownDestructuringErrors = true;
8829 }
8830 var startPos = this.start, startLoc = this.startLoc;
8831 if (this.type === types$1.parenL || this.type === types$1.name) {
8832 this.potentialArrowAt = this.start;
8833 this.potentialArrowInForAwait = forInit === "await";
8834 }
8835 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
8836 if (afterLeftParse) {
8837 left = afterLeftParse.call(this, left, startPos, startLoc);
8838 }
8839 if (this.type.isAssign) {
8840 var node = this.startNodeAt(startPos, startLoc);
8841 node.operator = this.value;
8842 if (this.type === types$1.eq) {
8843 left = this.toAssignable(left, false, refDestructuringErrors);
8844 }
8845 if (!ownDestructuringErrors) {
8846 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
8847 }
8848 if (refDestructuringErrors.shorthandAssign >= left.start) {
8849 refDestructuringErrors.shorthandAssign = -1;
8850 }
8851 if (this.type === types$1.eq) {
8852 this.checkLValPattern(left);
8853 } else {
8854 this.checkLValSimple(left);
8855 }
8856 node.left = left;
8857 this.next();
8858 node.right = this.parseMaybeAssign(forInit);
8859 if (oldDoubleProto > -1) {
8860 refDestructuringErrors.doubleProto = oldDoubleProto;
8861 }
8862 return this.finishNode(node, "AssignmentExpression");
8863 } else {
8864 if (ownDestructuringErrors) {
8865 this.checkExpressionErrors(refDestructuringErrors, true);
8866 }
8867 }
8868 if (oldParenAssign > -1) {
8869 refDestructuringErrors.parenthesizedAssign = oldParenAssign;
8870 }
8871 if (oldTrailingComma > -1) {
8872 refDestructuringErrors.trailingComma = oldTrailingComma;
8873 }
8874 return left;
8875 };
8876 pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
8877 var startPos = this.start, startLoc = this.startLoc;
8878 var expr = this.parseExprOps(forInit, refDestructuringErrors);
8879 if (this.checkExpressionErrors(refDestructuringErrors)) {
8880 return expr;
8881 }
8882 if (!(expr.type === "ArrowFunctionExpression" && expr.start === startPos) && this.eat(types$1.question)) {
8883 var node = this.startNodeAt(startPos, startLoc);
8884 node.test = expr;
8885 node.consequent = this.parseMaybeAssign();
8886 this.expect(types$1.colon);
8887 node.alternate = this.parseMaybeAssign(forInit);
8888 return this.finishNode(node, "ConditionalExpression");
8889 }
8890 return expr;
8891 };
8892 pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
8893 var startPos = this.start, startLoc = this.startLoc;
8894 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
8895 if (this.checkExpressionErrors(refDestructuringErrors)) {
8896 return expr;
8897 }
8898 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
8899 };
8900 pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
8901 var prec = this.type.binop;
8902 if (prec != null && (!forInit || this.type !== types$1._in)) {
8903 if (prec > minPrec) {
8904 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
8905 var coalesce = this.type === types$1.coalesce;
8906 if (coalesce) {
8907 prec = types$1.logicalAND.binop;
8908 }
8909 var op = this.value;
8910 this.next();
8911 var startPos = this.start, startLoc = this.startLoc;
8912 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
8913 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
8914 if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) {
8915 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
8916 }
8917 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);
8918 }
8919 }
8920 return left;
8921 };
8922 pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
8923 if (right.type === "PrivateIdentifier") {
8924 this.raise(right.start, "Private identifier can only be left side of binary expression");
8925 }
8926 var node = this.startNodeAt(startPos, startLoc);
8927 node.left = left;
8928 node.operator = op;
8929 node.right = right;
8930 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
8931 };
8932 pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
8933 var startPos = this.start, startLoc = this.startLoc, expr;
8934 if (this.isContextual("await") && this.canAwait) {
8935 expr = this.parseAwait(forInit);
8936 sawUnary = true;
8937 } else if (this.type.prefix) {
8938 var node = this.startNode(), update = this.type === types$1.incDec;
8939 node.operator = this.value;
8940 node.prefix = true;
8941 this.next();
8942 node.argument = this.parseMaybeUnary(null, true, update, forInit);
8943 this.checkExpressionErrors(refDestructuringErrors, true);
8944 if (update) {
8945 this.checkLValSimple(node.argument);
8946 } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) {
8947 this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
8948 } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) {
8949 this.raiseRecoverable(node.start, "Private fields can not be deleted");
8950 } else {
8951 sawUnary = true;
8952 }
8953 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
8954 } else if (!sawUnary && this.type === types$1.privateId) {
8955 if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) {
8956 this.unexpected();
8957 }
8958 expr = this.parsePrivateIdent();
8959 if (this.type !== types$1._in) {
8960 this.unexpected();
8961 }
8962 } else {
8963 expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
8964 if (this.checkExpressionErrors(refDestructuringErrors)) {
8965 return expr;
8966 }
8967 while (this.type.postfix && !this.canInsertSemicolon()) {
8968 var node$1 = this.startNodeAt(startPos, startLoc);
8969 node$1.operator = this.value;
8970 node$1.prefix = false;
8971 node$1.argument = expr;
8972 this.checkLValSimple(expr);
8973 this.next();
8974 expr = this.finishNode(node$1, "UpdateExpression");
8975 }
8976 }
8977 if (!incDec && !(expr.type === "ArrowFunctionExpression" && expr.start === startPos) && this.eat(types$1.starstar)) {
8978 if (sawUnary) {
8979 this.unexpected(this.lastTokStart);
8980 } else {
8981 return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);
8982 }
8983 } else {
8984 return expr;
8985 }
8986 };
8987 pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
8988 var startPos = this.start, startLoc = this.startLoc;
8989 var expr = this.parseExprAtom(refDestructuringErrors, forInit);
8990 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
8991 return expr;
8992 }
8993 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
8994 if (refDestructuringErrors && result.type === "MemberExpression") {
8995 if (refDestructuringErrors.parenthesizedAssign >= result.start) {
8996 refDestructuringErrors.parenthesizedAssign = -1;
8997 }
8998 if (refDestructuringErrors.parenthesizedBind >= result.start) {
8999 refDestructuringErrors.parenthesizedBind = -1;
9000 }
9001 if (refDestructuringErrors.trailingComma >= result.start) {
9002 refDestructuringErrors.trailingComma = -1;
9003 }
9004 }
9005 return result;
9006 };
9007 pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
9008 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;
9009 var optionalChained = false;
9010 while (true) {
9011 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
9012 if (element.optional) {
9013 optionalChained = true;
9014 }
9015 if (element === base || element.type === "ArrowFunctionExpression") {
9016 if (optionalChained) {
9017 var chainNode = this.startNodeAt(startPos, startLoc);
9018 chainNode.expression = element;
9019 element = this.finishNode(chainNode, "ChainExpression");
9020 }
9021 return element;
9022 }
9023 base = element;
9024 }
9025 };
9026 pp$5.shouldParseAsyncArrow = function() {
9027 return !this.canInsertSemicolon() && this.eat(types$1.arrow);
9028 };
9029 pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
9030 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);
9031 };
9032 pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
9033 var optionalSupported = this.options.ecmaVersion >= 11;
9034 var optional = optionalSupported && this.eat(types$1.questionDot);
9035 if (noCalls && optional) {
9036 this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
9037 }
9038 var computed = this.eat(types$1.bracketL);
9039 if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) {
9040 var node = this.startNodeAt(startPos, startLoc);
9041 node.object = base;
9042 if (computed) {
9043 node.property = this.parseExpression();
9044 this.expect(types$1.bracketR);
9045 } else if (this.type === types$1.privateId && base.type !== "Super") {
9046 node.property = this.parsePrivateIdent();
9047 } else {
9048 node.property = this.parseIdent(this.options.allowReserved !== "never");
9049 }
9050 node.computed = !!computed;
9051 if (optionalSupported) {
9052 node.optional = optional;
9053 }
9054 base = this.finishNode(node, "MemberExpression");
9055 } else if (!noCalls && this.eat(types$1.parenL)) {
9056 var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
9057 this.yieldPos = 0;
9058 this.awaitPos = 0;
9059 this.awaitIdentPos = 0;
9060 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
9061 if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
9062 this.checkPatternErrors(refDestructuringErrors, false);
9063 this.checkYieldAwaitInDefaultParams();
9064 if (this.awaitIdentPos > 0) {
9065 this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
9066 }
9067 this.yieldPos = oldYieldPos;
9068 this.awaitPos = oldAwaitPos;
9069 this.awaitIdentPos = oldAwaitIdentPos;
9070 return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);
9071 }
9072 this.checkExpressionErrors(refDestructuringErrors, true);
9073 this.yieldPos = oldYieldPos || this.yieldPos;
9074 this.awaitPos = oldAwaitPos || this.awaitPos;
9075 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
9076 var node$1 = this.startNodeAt(startPos, startLoc);
9077 node$1.callee = base;
9078 node$1.arguments = exprList;
9079 if (optionalSupported) {
9080 node$1.optional = optional;
9081 }
9082 base = this.finishNode(node$1, "CallExpression");
9083 } else if (this.type === types$1.backQuote) {
9084 if (optional || optionalChained) {
9085 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
9086 }
9087 var node$2 = this.startNodeAt(startPos, startLoc);
9088 node$2.tag = base;
9089 node$2.quasi = this.parseTemplate({ isTagged: true });
9090 base = this.finishNode(node$2, "TaggedTemplateExpression");
9091 }
9092 return base;
9093 };
9094 pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
9095 if (this.type === types$1.slash) {
9096 this.readRegexp();
9097 }
9098 var node, canBeArrow = this.potentialArrowAt === this.start;
9099 switch (this.type) {
9100 case types$1._super:
9101 if (!this.allowSuper) {
9102 this.raise(this.start, "'super' keyword outside a method");
9103 }
9104 node = this.startNode();
9105 this.next();
9106 if (this.type === types$1.parenL && !this.allowDirectSuper) {
9107 this.raise(node.start, "super() call outside constructor of a subclass");
9108 }
9109 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) {
9110 this.unexpected();
9111 }
9112 return this.finishNode(node, "Super");
9113 case types$1._this:
9114 node = this.startNode();
9115 this.next();
9116 return this.finishNode(node, "ThisExpression");
9117 case types$1.name:
9118 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
9119 var id = this.parseIdent(false);
9120 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
9121 this.overrideContext(types2.f_expr);
9122 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);
9123 }
9124 if (canBeArrow && !this.canInsertSemicolon()) {
9125 if (this.eat(types$1.arrow)) {
9126 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit);
9127 }
9128 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
9129 id = this.parseIdent(false);
9130 if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) {
9131 this.unexpected();
9132 }
9133 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit);
9134 }
9135 }
9136 return id;
9137 case types$1.regexp:
9138 var value = this.value;
9139 node = this.parseLiteral(value.value);
9140 node.regex = { pattern: value.pattern, flags: value.flags };
9141 return node;
9142 case types$1.num:
9143 case types$1.string:
9144 return this.parseLiteral(this.value);
9145 case types$1._null:
9146 case types$1._true:
9147 case types$1._false:
9148 node = this.startNode();
9149 node.value = this.type === types$1._null ? null : this.type === types$1._true;
9150 node.raw = this.type.keyword;
9151 this.next();
9152 return this.finishNode(node, "Literal");
9153 case types$1.parenL:
9154 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
9155 if (refDestructuringErrors) {
9156 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
9157 refDestructuringErrors.parenthesizedAssign = start;
9158 }
9159 if (refDestructuringErrors.parenthesizedBind < 0) {
9160 refDestructuringErrors.parenthesizedBind = start;
9161 }
9162 }
9163 return expr;
9164 case types$1.bracketL:
9165 node = this.startNode();
9166 this.next();
9167 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
9168 return this.finishNode(node, "ArrayExpression");
9169 case types$1.braceL:
9170 this.overrideContext(types2.b_expr);
9171 return this.parseObj(false, refDestructuringErrors);
9172 case types$1._function:
9173 node = this.startNode();
9174 this.next();
9175 return this.parseFunction(node, 0);
9176 case types$1._class:
9177 return this.parseClass(this.startNode(), false);
9178 case types$1._new:
9179 return this.parseNew();
9180 case types$1.backQuote:
9181 return this.parseTemplate();
9182 case types$1._import:
9183 if (this.options.ecmaVersion >= 11) {
9184 return this.parseExprImport(forNew);
9185 } else {
9186 return this.unexpected();
9187 }
9188 default:
9189 return this.parseExprAtomDefault();
9190 }
9191 };
9192 pp$5.parseExprAtomDefault = function() {
9193 this.unexpected();
9194 };
9195 pp$5.parseExprImport = function(forNew) {
9196 var node = this.startNode();
9197 if (this.containsEsc) {
9198 this.raiseRecoverable(this.start, "Escape sequence in keyword import");
9199 }
9200 this.next();
9201 if (this.type === types$1.parenL && !forNew) {
9202 return this.parseDynamicImport(node);
9203 } else if (this.type === types$1.dot) {
9204 var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
9205 meta.name = "import";
9206 node.meta = this.finishNode(meta, "Identifier");
9207 return this.parseImportMeta(node);
9208 } else {
9209 this.unexpected();
9210 }
9211 };
9212 pp$5.parseDynamicImport = function(node) {
9213 this.next();
9214 node.source = this.parseMaybeAssign();
9215 if (this.options.ecmaVersion >= 16) {
9216 if (!this.eat(types$1.parenR)) {
9217 this.expect(types$1.comma);
9218 if (!this.afterTrailingComma(types$1.parenR)) {
9219 node.options = this.parseMaybeAssign();
9220 if (!this.eat(types$1.parenR)) {
9221 this.expect(types$1.comma);
9222 if (!this.afterTrailingComma(types$1.parenR)) {
9223 this.unexpected();
9224 }
9225 }
9226 } else {
9227 node.options = null;
9228 }
9229 } else {
9230 node.options = null;
9231 }
9232 } else {
9233 if (!this.eat(types$1.parenR)) {
9234 var errorPos = this.start;
9235 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
9236 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
9237 } else {
9238 this.unexpected(errorPos);
9239 }
9240 }
9241 }
9242 return this.finishNode(node, "ImportExpression");
9243 };
9244 pp$5.parseImportMeta = function(node) {
9245 this.next();
9246 var containsEsc = this.containsEsc;
9247 node.property = this.parseIdent(true);
9248 if (node.property.name !== "meta") {
9249 this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
9250 }
9251 if (containsEsc) {
9252 this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
9253 }
9254 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
9255 this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
9256 }
9257 return this.finishNode(node, "MetaProperty");
9258 };
9259 pp$5.parseLiteral = function(value) {
9260 var node = this.startNode();
9261 node.value = value;
9262 node.raw = this.input.slice(this.start, this.end);
9263 if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
9264 node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, "");
9265 }
9266 this.next();
9267 return this.finishNode(node, "Literal");
9268 };
9269 pp$5.parseParenExpression = function() {
9270 this.expect(types$1.parenL);
9271 var val = this.parseExpression();
9272 this.expect(types$1.parenR);
9273 return val;
9274 };
9275 pp$5.shouldParseArrow = function(exprList) {
9276 return !this.canInsertSemicolon();
9277 };
9278 pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
9279 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
9280 if (this.options.ecmaVersion >= 6) {
9281 this.next();
9282 var innerStartPos = this.start, innerStartLoc = this.startLoc;
9283 var exprList = [], first = true, lastIsComma = false;
9284 var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
9285 this.yieldPos = 0;
9286 this.awaitPos = 0;
9287 while (this.type !== types$1.parenR) {
9288 first ? first = false : this.expect(types$1.comma);
9289 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
9290 lastIsComma = true;
9291 break;
9292 } else if (this.type === types$1.ellipsis) {
9293 spreadStart = this.start;
9294 exprList.push(this.parseParenItem(this.parseRestBinding()));
9295 if (this.type === types$1.comma) {
9296 this.raiseRecoverable(
9297 this.start,
9298 "Comma is not permitted after the rest element"
9299 );
9300 }
9301 break;
9302 } else {
9303 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
9304 }
9305 }
9306 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
9307 this.expect(types$1.parenR);
9308 if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
9309 this.checkPatternErrors(refDestructuringErrors, false);
9310 this.checkYieldAwaitInDefaultParams();
9311 this.yieldPos = oldYieldPos;
9312 this.awaitPos = oldAwaitPos;
9313 return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
9314 }
9315 if (!exprList.length || lastIsComma) {
9316 this.unexpected(this.lastTokStart);
9317 }
9318 if (spreadStart) {
9319 this.unexpected(spreadStart);
9320 }
9321 this.checkExpressionErrors(refDestructuringErrors, true);
9322 this.yieldPos = oldYieldPos || this.yieldPos;
9323 this.awaitPos = oldAwaitPos || this.awaitPos;
9324 if (exprList.length > 1) {
9325 val = this.startNodeAt(innerStartPos, innerStartLoc);
9326 val.expressions = exprList;
9327 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
9328 } else {
9329 val = exprList[0];
9330 }
9331 } else {
9332 val = this.parseParenExpression();
9333 }
9334 if (this.options.preserveParens) {
9335 var par = this.startNodeAt(startPos, startLoc);
9336 par.expression = val;
9337 return this.finishNode(par, "ParenthesizedExpression");
9338 } else {
9339 return val;
9340 }
9341 };
9342 pp$5.parseParenItem = function(item) {
9343 return item;
9344 };
9345 pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
9346 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);
9347 };
9348 empty = [];
9349 pp$5.parseNew = function() {
9350 if (this.containsEsc) {
9351 this.raiseRecoverable(this.start, "Escape sequence in keyword new");
9352 }
9353 var node = this.startNode();
9354 this.next();
9355 if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) {
9356 var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
9357 meta.name = "new";
9358 node.meta = this.finishNode(meta, "Identifier");
9359 this.next();
9360 var containsEsc = this.containsEsc;
9361 node.property = this.parseIdent(true);
9362 if (node.property.name !== "target") {
9363 this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
9364 }
9365 if (containsEsc) {
9366 this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
9367 }
9368 if (!this.allowNewDotTarget) {
9369 this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block");
9370 }
9371 return this.finishNode(node, "MetaProperty");
9372 }
9373 var startPos = this.start, startLoc = this.startLoc;
9374 node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
9375 if (node.callee.type === "Super") {
9376 this.raiseRecoverable(startPos, "Invalid use of 'super'");
9377 }
9378 if (this.eat(types$1.parenL)) {
9379 node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false);
9380 } else {
9381 node.arguments = empty;
9382 }
9383 return this.finishNode(node, "NewExpression");
9384 };
9385 pp$5.parseTemplateElement = function(ref2) {
9386 var isTagged = ref2.isTagged;
9387 var elem = this.startNode();
9388 if (this.type === types$1.invalidTemplate) {
9389 if (!isTagged) {
9390 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
9391 }
9392 elem.value = {
9393 raw: this.value.replace(/\r\n?/g, "\n"),
9394 cooked: null
9395 };
9396 } else {
9397 elem.value = {
9398 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
9399 cooked: this.value
9400 };
9401 }
9402 this.next();
9403 elem.tail = this.type === types$1.backQuote;
9404 return this.finishNode(elem, "TemplateElement");
9405 };
9406 pp$5.parseTemplate = function(ref2) {
9407 if (ref2 === void 0) ref2 = {};
9408 var isTagged = ref2.isTagged;
9409 if (isTagged === void 0) isTagged = false;
9410 var node = this.startNode();
9411 this.next();
9412 node.expressions = [];
9413 var curElt = this.parseTemplateElement({ isTagged });
9414 node.quasis = [curElt];
9415 while (!curElt.tail) {
9416 if (this.type === types$1.eof) {
9417 this.raise(this.pos, "Unterminated template literal");
9418 }
9419 this.expect(types$1.dollarBraceL);
9420 node.expressions.push(this.parseExpression());
9421 this.expect(types$1.braceR);
9422 node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
9423 }
9424 this.next();
9425 return this.finishNode(node, "TemplateLiteral");
9426 };
9427 pp$5.isAsyncProp = function(prop) {
9428 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
9429 };
9430 pp$5.parseObj = function(isPattern, refDestructuringErrors) {
9431 var node = this.startNode(), first = true, propHash = {};
9432 node.properties = [];
9433 this.next();
9434 while (!this.eat(types$1.braceR)) {
9435 if (!first) {
9436 this.expect(types$1.comma);
9437 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) {
9438 break;
9439 }
9440 } else {
9441 first = false;
9442 }
9443 var prop = this.parseProperty(isPattern, refDestructuringErrors);
9444 if (!isPattern) {
9445 this.checkPropClash(prop, propHash, refDestructuringErrors);
9446 }
9447 node.properties.push(prop);
9448 }
9449 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
9450 };
9451 pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
9452 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
9453 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
9454 if (isPattern) {
9455 prop.argument = this.parseIdent(false);
9456 if (this.type === types$1.comma) {
9457 this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
9458 }
9459 return this.finishNode(prop, "RestElement");
9460 }
9461 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
9462 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
9463 refDestructuringErrors.trailingComma = this.start;
9464 }
9465 return this.finishNode(prop, "SpreadElement");
9466 }
9467 if (this.options.ecmaVersion >= 6) {
9468 prop.method = false;
9469 prop.shorthand = false;
9470 if (isPattern || refDestructuringErrors) {
9471 startPos = this.start;
9472 startLoc = this.startLoc;
9473 }
9474 if (!isPattern) {
9475 isGenerator = this.eat(types$1.star);
9476 }
9477 }
9478 var containsEsc = this.containsEsc;
9479 this.parsePropertyName(prop);
9480 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
9481 isAsync = true;
9482 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
9483 this.parsePropertyName(prop);
9484 } else {
9485 isAsync = false;
9486 }
9487 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
9488 return this.finishNode(prop, "Property");
9489 };
9490 pp$5.parseGetterSetter = function(prop) {
9491 var kind = prop.key.name;
9492 this.parsePropertyName(prop);
9493 prop.value = this.parseMethod(false);
9494 prop.kind = kind;
9495 var paramCount = prop.kind === "get" ? 0 : 1;
9496 if (prop.value.params.length !== paramCount) {
9497 var start = prop.value.start;
9498 if (prop.kind === "get") {
9499 this.raiseRecoverable(start, "getter should have no params");
9500 } else {
9501 this.raiseRecoverable(start, "setter should have exactly one param");
9502 }
9503 } else {
9504 if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
9505 this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
9506 }
9507 }
9508 };
9509 pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
9510 if ((isGenerator || isAsync) && this.type === types$1.colon) {
9511 this.unexpected();
9512 }
9513 if (this.eat(types$1.colon)) {
9514 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
9515 prop.kind = "init";
9516 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
9517 if (isPattern) {
9518 this.unexpected();
9519 }
9520 prop.method = true;
9521 prop.value = this.parseMethod(isGenerator, isAsync);
9522 prop.kind = "init";
9523 } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
9524 if (isGenerator || isAsync) {
9525 this.unexpected();
9526 }
9527 this.parseGetterSetter(prop);
9528 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
9529 if (isGenerator || isAsync) {
9530 this.unexpected();
9531 }
9532 this.checkUnreserved(prop.key);
9533 if (prop.key.name === "await" && !this.awaitIdentPos) {
9534 this.awaitIdentPos = startPos;
9535 }
9536 if (isPattern) {
9537 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
9538 } else if (this.type === types$1.eq && refDestructuringErrors) {
9539 if (refDestructuringErrors.shorthandAssign < 0) {
9540 refDestructuringErrors.shorthandAssign = this.start;
9541 }
9542 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
9543 } else {
9544 prop.value = this.copyNode(prop.key);
9545 }
9546 prop.kind = "init";
9547 prop.shorthand = true;
9548 } else {
9549 this.unexpected();
9550 }
9551 };
9552 pp$5.parsePropertyName = function(prop) {
9553 if (this.options.ecmaVersion >= 6) {
9554 if (this.eat(types$1.bracketL)) {
9555 prop.computed = true;
9556 prop.key = this.parseMaybeAssign();
9557 this.expect(types$1.bracketR);
9558 return prop.key;
9559 } else {
9560 prop.computed = false;
9561 }
9562 }
9563 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
9564 };
9565 pp$5.initFunction = function(node) {
9566 node.id = null;
9567 if (this.options.ecmaVersion >= 6) {
9568 node.generator = node.expression = false;
9569 }
9570 if (this.options.ecmaVersion >= 8) {
9571 node.async = false;
9572 }
9573 };
9574 pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
9575 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
9576 this.initFunction(node);
9577 if (this.options.ecmaVersion >= 6) {
9578 node.generator = isGenerator;
9579 }
9580 if (this.options.ecmaVersion >= 8) {
9581 node.async = !!isAsync;
9582 }
9583 this.yieldPos = 0;
9584 this.awaitPos = 0;
9585 this.awaitIdentPos = 0;
9586 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
9587 this.expect(types$1.parenL);
9588 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
9589 this.checkYieldAwaitInDefaultParams();
9590 this.parseFunctionBody(node, false, true, false);
9591 this.yieldPos = oldYieldPos;
9592 this.awaitPos = oldAwaitPos;
9593 this.awaitIdentPos = oldAwaitIdentPos;
9594 return this.finishNode(node, "FunctionExpression");
9595 };
9596 pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
9597 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
9598 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
9599 this.initFunction(node);
9600 if (this.options.ecmaVersion >= 8) {
9601 node.async = !!isAsync;
9602 }
9603 this.yieldPos = 0;
9604 this.awaitPos = 0;
9605 this.awaitIdentPos = 0;
9606 node.params = this.toAssignableList(params, true);
9607 this.parseFunctionBody(node, true, false, forInit);
9608 this.yieldPos = oldYieldPos;
9609 this.awaitPos = oldAwaitPos;
9610 this.awaitIdentPos = oldAwaitIdentPos;
9611 return this.finishNode(node, "ArrowFunctionExpression");
9612 };
9613 pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
9614 var isExpression = isArrowFunction && this.type !== types$1.braceL;
9615 var oldStrict = this.strict, useStrict = false;
9616 if (isExpression) {
9617 node.body = this.parseMaybeAssign(forInit);
9618 node.expression = true;
9619 this.checkParams(node, false);
9620 } else {
9621 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
9622 if (!oldStrict || nonSimple) {
9623 useStrict = this.strictDirective(this.end);
9624 if (useStrict && nonSimple) {
9625 this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
9626 }
9627 }
9628 var oldLabels = this.labels;
9629 this.labels = [];
9630 if (useStrict) {
9631 this.strict = true;
9632 }
9633 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
9634 if (this.strict && node.id) {
9635 this.checkLValSimple(node.id, BIND_OUTSIDE);
9636 }
9637 node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
9638 node.expression = false;
9639 this.adaptDirectivePrologue(node.body.body);
9640 this.labels = oldLabels;
9641 }
9642 this.exitScope();
9643 };
9644 pp$5.isSimpleParamList = function(params) {
9645 for (var i2 = 0, list2 = params; i2 < list2.length; i2 += 1) {
9646 var param = list2[i2];
9647 if (param.type !== "Identifier") {
9648 return false;
9649 }
9650 }
9651 return true;
9652 };
9653 pp$5.checkParams = function(node, allowDuplicates) {
9654 var nameHash = /* @__PURE__ */ Object.create(null);
9655 for (var i2 = 0, list2 = node.params; i2 < list2.length; i2 += 1) {
9656 var param = list2[i2];
9657 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
9658 }
9659 };
9660 pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
9661 var elts = [], first = true;
9662 while (!this.eat(close)) {
9663 if (!first) {
9664 this.expect(types$1.comma);
9665 if (allowTrailingComma && this.afterTrailingComma(close)) {
9666 break;
9667 }
9668 } else {
9669 first = false;
9670 }
9671 var elt = void 0;
9672 if (allowEmpty && this.type === types$1.comma) {
9673 elt = null;
9674 } else if (this.type === types$1.ellipsis) {
9675 elt = this.parseSpread(refDestructuringErrors);
9676 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) {
9677 refDestructuringErrors.trailingComma = this.start;
9678 }
9679 } else {
9680 elt = this.parseMaybeAssign(false, refDestructuringErrors);
9681 }
9682 elts.push(elt);
9683 }
9684 return elts;
9685 };
9686 pp$5.checkUnreserved = function(ref2) {
9687 var start = ref2.start;
9688 var end = ref2.end;
9689 var name = ref2.name;
9690 if (this.inGenerator && name === "yield") {
9691 this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
9692 }
9693 if (this.inAsync && name === "await") {
9694 this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
9695 }
9696 if (!(this.currentThisScope().flags & SCOPE_VAR) && name === "arguments") {
9697 this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
9698 }
9699 if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {
9700 this.raise(start, "Cannot use " + name + " in class static initialization block");
9701 }
9702 if (this.keywords.test(name)) {
9703 this.raise(start, "Unexpected keyword '" + name + "'");
9704 }
9705 if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
9706 return;
9707 }
9708 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
9709 if (re.test(name)) {
9710 if (!this.inAsync && name === "await") {
9711 this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
9712 }
9713 this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
9714 }
9715 };
9716 pp$5.parseIdent = function(liberal) {
9717 var node = this.parseIdentNode();
9718 this.next(!!liberal);
9719 this.finishNode(node, "Identifier");
9720 if (!liberal) {
9721 this.checkUnreserved(node);
9722 if (node.name === "await" && !this.awaitIdentPos) {
9723 this.awaitIdentPos = node.start;
9724 }
9725 }
9726 return node;
9727 };
9728 pp$5.parseIdentNode = function() {
9729 var node = this.startNode();
9730 if (this.type === types$1.name) {
9731 node.name = this.value;
9732 } else if (this.type.keyword) {
9733 node.name = this.type.keyword;
9734 if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
9735 this.context.pop();
9736 }
9737 this.type = types$1.name;
9738 } else {
9739 this.unexpected();
9740 }
9741 return node;
9742 };
9743 pp$5.parsePrivateIdent = function() {
9744 var node = this.startNode();
9745 if (this.type === types$1.privateId) {
9746 node.name = this.value;
9747 } else {
9748 this.unexpected();
9749 }
9750 this.next();
9751 this.finishNode(node, "PrivateIdentifier");
9752 if (this.options.checkPrivateFields) {
9753 if (this.privateNameStack.length === 0) {
9754 this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
9755 } else {
9756 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
9757 }
9758 }
9759 return node;
9760 };
9761 pp$5.parseYield = function(forInit) {
9762 if (!this.yieldPos) {
9763 this.yieldPos = this.start;
9764 }
9765 var node = this.startNode();
9766 this.next();
9767 if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) {
9768 node.delegate = false;
9769 node.argument = null;
9770 } else {
9771 node.delegate = this.eat(types$1.star);
9772 node.argument = this.parseMaybeAssign(forInit);
9773 }
9774 return this.finishNode(node, "YieldExpression");
9775 };
9776 pp$5.parseAwait = function(forInit) {
9777 if (!this.awaitPos) {
9778 this.awaitPos = this.start;
9779 }
9780 var node = this.startNode();
9781 this.next();
9782 node.argument = this.parseMaybeUnary(null, true, false, forInit);
9783 return this.finishNode(node, "AwaitExpression");
9784 };
9785 pp$4 = Parser.prototype;
9786 pp$4.raise = function(pos, message) {
9787 var loc = getLineInfo(this.input, pos);
9788 message += " (" + loc.line + ":" + loc.column + ")";
9789 if (this.sourceFile) {
9790 message += " in " + this.sourceFile;
9791 }
9792 var err = new SyntaxError(message);
9793 err.pos = pos;
9794 err.loc = loc;
9795 err.raisedAt = this.pos;
9796 throw err;
9797 };
9798 pp$4.raiseRecoverable = pp$4.raise;
9799 pp$4.curPosition = function() {
9800 if (this.options.locations) {
9801 return new Position(this.curLine, this.pos - this.lineStart);
9802 }
9803 };
9804 pp$3 = Parser.prototype;
9805 Scope = function Scope2(flags) {
9806 this.flags = flags;
9807 this.var = [];
9808 this.lexical = [];
9809 this.functions = [];
9810 };
9811 pp$3.enterScope = function(flags) {
9812 this.scopeStack.push(new Scope(flags));
9813 };
9814 pp$3.exitScope = function() {
9815 this.scopeStack.pop();
9816 };
9817 pp$3.treatFunctionsAsVarInScope = function(scope) {
9818 return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
9819 };
9820 pp$3.declareName = function(name, bindingType, pos) {
9821 var redeclared = false;
9822 if (bindingType === BIND_LEXICAL) {
9823 var scope = this.currentScope();
9824 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
9825 scope.lexical.push(name);
9826 if (this.inModule && scope.flags & SCOPE_TOP) {
9827 delete this.undefinedExports[name];
9828 }
9829 } else if (bindingType === BIND_SIMPLE_CATCH) {
9830 var scope$1 = this.currentScope();
9831 scope$1.lexical.push(name);
9832 } else if (bindingType === BIND_FUNCTION) {
9833 var scope$2 = this.currentScope();
9834 if (this.treatFunctionsAsVar) {
9835 redeclared = scope$2.lexical.indexOf(name) > -1;
9836 } else {
9837 redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
9838 }
9839 scope$2.functions.push(name);
9840 } else {
9841 for (var i2 = this.scopeStack.length - 1; i2 >= 0; --i2) {
9842 var scope$3 = this.scopeStack[i2];
9843 if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
9844 redeclared = true;
9845 break;
9846 }
9847 scope$3.var.push(name);
9848 if (this.inModule && scope$3.flags & SCOPE_TOP) {
9849 delete this.undefinedExports[name];
9850 }
9851 if (scope$3.flags & SCOPE_VAR) {
9852 break;
9853 }
9854 }
9855 }
9856 if (redeclared) {
9857 this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
9858 }
9859 };
9860 pp$3.checkLocalExport = function(id) {
9861 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
9862 this.undefinedExports[id.name] = id;
9863 }
9864 };
9865 pp$3.currentScope = function() {
9866 return this.scopeStack[this.scopeStack.length - 1];
9867 };
9868 pp$3.currentVarScope = function() {
9869 for (var i2 = this.scopeStack.length - 1; ; i2--) {
9870 var scope = this.scopeStack[i2];
9871 if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) {
9872 return scope;
9873 }
9874 }
9875 };
9876 pp$3.currentThisScope = function() {
9877 for (var i2 = this.scopeStack.length - 1; ; i2--) {
9878 var scope = this.scopeStack[i2];
9879 if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && !(scope.flags & SCOPE_ARROW)) {
9880 return scope;
9881 }
9882 }
9883 };
9884 Node = function Node2(parser, pos, loc) {
9885 this.type = "";
9886 this.start = pos;
9887 this.end = 0;
9888 if (parser.options.locations) {
9889 this.loc = new SourceLocation(parser, loc);
9890 }
9891 if (parser.options.directSourceFile) {
9892 this.sourceFile = parser.options.directSourceFile;
9893 }
9894 if (parser.options.ranges) {
9895 this.range = [pos, 0];
9896 }
9897 };
9898 pp$2 = Parser.prototype;
9899 pp$2.startNode = function() {
9900 return new Node(this, this.start, this.startLoc);
9901 };
9902 pp$2.startNodeAt = function(pos, loc) {
9903 return new Node(this, pos, loc);
9904 };
9905 pp$2.finishNode = function(node, type2) {
9906 return finishNodeAt.call(this, node, type2, this.lastTokEnd, this.lastTokEndLoc);
9907 };
9908 pp$2.finishNodeAt = function(node, type2, pos, loc) {
9909 return finishNodeAt.call(this, node, type2, pos, loc);
9910 };
9911 pp$2.copyNode = function(node) {
9912 var newNode = new Node(this, node.start, this.startLoc);
9913 for (var prop in node) {
9914 newNode[prop] = node[prop];
9915 }
9916 return newNode;
9917 };
9918 scriptValuesAddedInUnicode = "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz";
9919 ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
9920 ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
9921 ecma11BinaryProperties = ecma10BinaryProperties;
9922 ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
9923 ecma13BinaryProperties = ecma12BinaryProperties;
9924 ecma14BinaryProperties = ecma13BinaryProperties;
9925 unicodeBinaryProperties = {
9926 9: ecma9BinaryProperties,
9927 10: ecma10BinaryProperties,
9928 11: ecma11BinaryProperties,
9929 12: ecma12BinaryProperties,
9930 13: ecma13BinaryProperties,
9931 14: ecma14BinaryProperties
9932 };
9933 ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
9934 unicodeBinaryPropertiesOfStrings = {
9935 9: "",
9936 10: "",
9937 11: "",
9938 12: "",
9939 13: "",
9940 14: ecma14BinaryPropertiesOfStrings
9941 };
9942 unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
9943 ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
9944 ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
9945 ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
9946 ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
9947 ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
9948 ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;
9949 unicodeScriptValues = {
9950 9: ecma9ScriptValues,
9951 10: ecma10ScriptValues,
9952 11: ecma11ScriptValues,
9953 12: ecma12ScriptValues,
9954 13: ecma13ScriptValues,
9955 14: ecma14ScriptValues
9956 };
9957 data = {};
9958 for (i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
9959 ecmaVersion = list[i];
9960 buildUnicodeData(ecmaVersion);
9961 }
9962 pp$1 = Parser.prototype;
9963 BranchID = function BranchID2(parent, base) {
9964 this.parent = parent;
9965 this.base = base || this;
9966 };
9967 BranchID.prototype.separatedFrom = function separatedFrom(alt) {
9968 for (var self = this; self; self = self.parent) {
9969 for (var other = alt; other; other = other.parent) {
9970 if (self.base === other.base && self !== other) {
9971 return true;
9972 }
9973 }
9974 }
9975 return false;
9976 };
9977 BranchID.prototype.sibling = function sibling() {
9978 return new BranchID(this.parent, this.base);
9979 };
9980 RegExpValidationState = function RegExpValidationState2(parser) {
9981 this.parser = parser;
9982 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
9983 this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
9984 this.source = "";
9985 this.flags = "";
9986 this.start = 0;
9987 this.switchU = false;
9988 this.switchV = false;
9989 this.switchN = false;
9990 this.pos = 0;
9991 this.lastIntValue = 0;
9992 this.lastStringValue = "";
9993 this.lastAssertionIsQuantifiable = false;
9994 this.numCapturingParens = 0;
9995 this.maxBackReference = 0;
9996 this.groupNames = /* @__PURE__ */ Object.create(null);
9997 this.backReferenceNames = [];
9998 this.branchID = null;
9999 };
10000 RegExpValidationState.prototype.reset = function reset(start, pattern, flags) {
10001 var unicodeSets = flags.indexOf("v") !== -1;
10002 var unicode = flags.indexOf("u") !== -1;
10003 this.start = start | 0;
10004 this.source = pattern + "";
10005 this.flags = flags;
10006 if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
10007 this.switchU = true;
10008 this.switchV = true;
10009 this.switchN = true;
10010 } else {
10011 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
10012 this.switchV = false;
10013 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
10014 }
10015 };
10016 RegExpValidationState.prototype.raise = function raise(message) {
10017 this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
10018 };
10019 RegExpValidationState.prototype.at = function at(i2, forceU) {
10020 if (forceU === void 0) forceU = false;
10021 var s = this.source;
10022 var l = s.length;
10023 if (i2 >= l) {
10024 return -1;
10025 }
10026 var c = s.charCodeAt(i2);
10027 if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l) {
10028 return c;
10029 }
10030 var next = s.charCodeAt(i2 + 1);
10031 return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
10032 };
10033 RegExpValidationState.prototype.nextIndex = function nextIndex(i2, forceU) {
10034 if (forceU === void 0) forceU = false;
10035 var s = this.source;
10036 var l = s.length;
10037 if (i2 >= l) {
10038 return l;
10039 }
10040 var c = s.charCodeAt(i2), next;
10041 if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l || (next = s.charCodeAt(i2 + 1)) < 56320 || next > 57343) {
10042 return i2 + 1;
10043 }
10044 return i2 + 2;
10045 };
10046 RegExpValidationState.prototype.current = function current(forceU) {
10047 if (forceU === void 0) forceU = false;
10048 return this.at(this.pos, forceU);
10049 };
10050 RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
10051 if (forceU === void 0) forceU = false;
10052 return this.at(this.nextIndex(this.pos, forceU), forceU);
10053 };
10054 RegExpValidationState.prototype.advance = function advance(forceU) {
10055 if (forceU === void 0) forceU = false;
10056 this.pos = this.nextIndex(this.pos, forceU);
10057 };
10058 RegExpValidationState.prototype.eat = function eat(ch, forceU) {
10059 if (forceU === void 0) forceU = false;
10060 if (this.current(forceU) === ch) {
10061 this.advance(forceU);
10062 return true;
10063 }
10064 return false;
10065 };
10066 RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {
10067 if (forceU === void 0) forceU = false;
10068 var pos = this.pos;
10069 for (var i2 = 0, list2 = chs; i2 < list2.length; i2 += 1) {
10070 var ch = list2[i2];
10071 var current2 = this.at(pos, forceU);
10072 if (current2 === -1 || current2 !== ch) {
10073 return false;
10074 }
10075 pos = this.nextIndex(pos, forceU);
10076 }
10077 this.pos = pos;
10078 return true;
10079 };
10080 pp$1.validateRegExpFlags = function(state) {
10081 var validFlags = state.validFlags;
10082 var flags = state.flags;
10083 var u = false;
10084 var v = false;
10085 for (var i2 = 0; i2 < flags.length; i2++) {
10086 var flag = flags.charAt(i2);
10087 if (validFlags.indexOf(flag) === -1) {
10088 this.raise(state.start, "Invalid regular expression flag");
10089 }
10090 if (flags.indexOf(flag, i2 + 1) > -1) {
10091 this.raise(state.start, "Duplicate regular expression flag");
10092 }
10093 if (flag === "u") {
10094 u = true;
10095 }
10096 if (flag === "v") {
10097 v = true;
10098 }
10099 }
10100 if (this.options.ecmaVersion >= 15 && u && v) {
10101 this.raise(state.start, "Invalid regular expression flag");
10102 }
10103 };
10104 pp$1.validateRegExpPattern = function(state) {
10105 this.regexp_pattern(state);
10106 if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {
10107 state.switchN = true;
10108 this.regexp_pattern(state);
10109 }
10110 };
10111 pp$1.regexp_pattern = function(state) {
10112 state.pos = 0;
10113 state.lastIntValue = 0;
10114 state.lastStringValue = "";
10115 state.lastAssertionIsQuantifiable = false;
10116 state.numCapturingParens = 0;
10117 state.maxBackReference = 0;
10118 state.groupNames = /* @__PURE__ */ Object.create(null);
10119 state.backReferenceNames.length = 0;
10120 state.branchID = null;
10121 this.regexp_disjunction(state);
10122 if (state.pos !== state.source.length) {
10123 if (state.eat(
10124 41
10125 /* ) */
10126 )) {
10127 state.raise("Unmatched ')'");
10128 }
10129 if (state.eat(
10130 93
10131 /* ] */
10132 ) || state.eat(
10133 125
10134 /* } */
10135 )) {
10136 state.raise("Lone quantifier brackets");
10137 }
10138 }
10139 if (state.maxBackReference > state.numCapturingParens) {
10140 state.raise("Invalid escape");
10141 }
10142 for (var i2 = 0, list2 = state.backReferenceNames; i2 < list2.length; i2 += 1) {
10143 var name = list2[i2];
10144 if (!state.groupNames[name]) {
10145 state.raise("Invalid named capture referenced");
10146 }
10147 }
10148 };
10149 pp$1.regexp_disjunction = function(state) {
10150 var trackDisjunction = this.options.ecmaVersion >= 16;
10151 if (trackDisjunction) {
10152 state.branchID = new BranchID(state.branchID, null);
10153 }
10154 this.regexp_alternative(state);
10155 while (state.eat(
10156 124
10157 /* | */
10158 )) {
10159 if (trackDisjunction) {
10160 state.branchID = state.branchID.sibling();
10161 }
10162 this.regexp_alternative(state);
10163 }
10164 if (trackDisjunction) {
10165 state.branchID = state.branchID.parent;
10166 }
10167 if (this.regexp_eatQuantifier(state, true)) {
10168 state.raise("Nothing to repeat");
10169 }
10170 if (state.eat(
10171 123
10172 /* { */
10173 )) {
10174 state.raise("Lone quantifier brackets");
10175 }
10176 };
10177 pp$1.regexp_alternative = function(state) {
10178 while (state.pos < state.source.length && this.regexp_eatTerm(state)) {
10179 }
10180 };
10181 pp$1.regexp_eatTerm = function(state) {
10182 if (this.regexp_eatAssertion(state)) {
10183 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
10184 if (state.switchU) {
10185 state.raise("Invalid quantifier");
10186 }
10187 }
10188 return true;
10189 }
10190 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
10191 this.regexp_eatQuantifier(state);
10192 return true;
10193 }
10194 return false;
10195 };
10196 pp$1.regexp_eatAssertion = function(state) {
10197 var start = state.pos;
10198 state.lastAssertionIsQuantifiable = false;
10199 if (state.eat(
10200 94
10201 /* ^ */
10202 ) || state.eat(
10203 36
10204 /* $ */
10205 )) {
10206 return true;
10207 }
10208 if (state.eat(
10209 92
10210 /* \ */
10211 )) {
10212 if (state.eat(
10213 66
10214 /* B */
10215 ) || state.eat(
10216 98
10217 /* b */
10218 )) {
10219 return true;
10220 }
10221 state.pos = start;
10222 }
10223 if (state.eat(
10224 40
10225 /* ( */
10226 ) && state.eat(
10227 63
10228 /* ? */
10229 )) {
10230 var lookbehind = false;
10231 if (this.options.ecmaVersion >= 9) {
10232 lookbehind = state.eat(
10233 60
10234 /* < */
10235 );
10236 }
10237 if (state.eat(
10238 61
10239 /* = */
10240 ) || state.eat(
10241 33
10242 /* ! */
10243 )) {
10244 this.regexp_disjunction(state);
10245 if (!state.eat(
10246 41
10247 /* ) */
10248 )) {
10249 state.raise("Unterminated group");
10250 }
10251 state.lastAssertionIsQuantifiable = !lookbehind;
10252 return true;
10253 }
10254 }
10255 state.pos = start;
10256 return false;
10257 };
10258 pp$1.regexp_eatQuantifier = function(state, noError) {
10259 if (noError === void 0) noError = false;
10260 if (this.regexp_eatQuantifierPrefix(state, noError)) {
10261 state.eat(
10262 63
10263 /* ? */
10264 );
10265 return true;
10266 }
10267 return false;
10268 };
10269 pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
10270 return state.eat(
10271 42
10272 /* * */
10273 ) || state.eat(
10274 43
10275 /* + */
10276 ) || state.eat(
10277 63
10278 /* ? */
10279 ) || this.regexp_eatBracedQuantifier(state, noError);
10280 };
10281 pp$1.regexp_eatBracedQuantifier = function(state, noError) {
10282 var start = state.pos;
10283 if (state.eat(
10284 123
10285 /* { */
10286 )) {
10287 var min = 0, max = -1;
10288 if (this.regexp_eatDecimalDigits(state)) {
10289 min = state.lastIntValue;
10290 if (state.eat(
10291 44
10292 /* , */
10293 ) && this.regexp_eatDecimalDigits(state)) {
10294 max = state.lastIntValue;
10295 }
10296 if (state.eat(
10297 125
10298 /* } */
10299 )) {
10300 if (max !== -1 && max < min && !noError) {
10301 state.raise("numbers out of order in {} quantifier");
10302 }
10303 return true;
10304 }
10305 }
10306 if (state.switchU && !noError) {
10307 state.raise("Incomplete quantifier");
10308 }
10309 state.pos = start;
10310 }
10311 return false;
10312 };
10313 pp$1.regexp_eatAtom = function(state) {
10314 return this.regexp_eatPatternCharacters(state) || state.eat(
10315 46
10316 /* . */
10317 ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
10318 };
10319 pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
10320 var start = state.pos;
10321 if (state.eat(
10322 92
10323 /* \ */
10324 )) {
10325 if (this.regexp_eatAtomEscape(state)) {
10326 return true;
10327 }
10328 state.pos = start;
10329 }
10330 return false;
10331 };
10332 pp$1.regexp_eatUncapturingGroup = function(state) {
10333 var start = state.pos;
10334 if (state.eat(
10335 40
10336 /* ( */
10337 )) {
10338 if (state.eat(
10339 63
10340 /* ? */
10341 )) {
10342 if (this.options.ecmaVersion >= 16) {
10343 var addModifiers = this.regexp_eatModifiers(state);
10344 var hasHyphen = state.eat(
10345 45
10346 /* - */
10347 );
10348 if (addModifiers || hasHyphen) {
10349 for (var i2 = 0; i2 < addModifiers.length; i2++) {
10350 var modifier = addModifiers.charAt(i2);
10351 if (addModifiers.indexOf(modifier, i2 + 1) > -1) {
10352 state.raise("Duplicate regular expression modifiers");
10353 }
10354 }
10355 if (hasHyphen) {
10356 var removeModifiers = this.regexp_eatModifiers(state);
10357 if (!addModifiers && !removeModifiers && state.current() === 58) {
10358 state.raise("Invalid regular expression modifiers");
10359 }
10360 for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {
10361 var modifier$1 = removeModifiers.charAt(i$1);
10362 if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) {
10363 state.raise("Duplicate regular expression modifiers");
10364 }
10365 }
10366 }
10367 }
10368 }
10369 if (state.eat(
10370 58
10371 /* : */
10372 )) {
10373 this.regexp_disjunction(state);
10374 if (state.eat(
10375 41
10376 /* ) */
10377 )) {
10378 return true;
10379 }
10380 state.raise("Unterminated group");
10381 }
10382 }
10383 state.pos = start;
10384 }
10385 return false;
10386 };
10387 pp$1.regexp_eatCapturingGroup = function(state) {
10388 if (state.eat(
10389 40
10390 /* ( */
10391 )) {
10392 if (this.options.ecmaVersion >= 9) {
10393 this.regexp_groupSpecifier(state);
10394 } else if (state.current() === 63) {
10395 state.raise("Invalid group");
10396 }
10397 this.regexp_disjunction(state);
10398 if (state.eat(
10399 41
10400 /* ) */
10401 )) {
10402 state.numCapturingParens += 1;
10403 return true;
10404 }
10405 state.raise("Unterminated group");
10406 }
10407 return false;
10408 };
10409 pp$1.regexp_eatModifiers = function(state) {
10410 var modifiers = "";
10411 var ch = 0;
10412 while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {
10413 modifiers += codePointToString(ch);
10414 state.advance();
10415 }
10416 return modifiers;
10417 };
10418 pp$1.regexp_eatExtendedAtom = function(state) {
10419 return state.eat(
10420 46
10421 /* . */
10422 ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
10423 };
10424 pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
10425 if (this.regexp_eatBracedQuantifier(state, true)) {
10426 state.raise("Nothing to repeat");
10427 }
10428 return false;
10429 };
10430 pp$1.regexp_eatSyntaxCharacter = function(state) {
10431 var ch = state.current();
10432 if (isSyntaxCharacter(ch)) {
10433 state.lastIntValue = ch;
10434 state.advance();
10435 return true;
10436 }
10437 return false;
10438 };
10439 pp$1.regexp_eatPatternCharacters = function(state) {
10440 var start = state.pos;
10441 var ch = 0;
10442 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
10443 state.advance();
10444 }
10445 return state.pos !== start;
10446 };
10447 pp$1.regexp_eatExtendedPatternCharacter = function(state) {
10448 var ch = state.current();
10449 if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
10450 state.advance();
10451 return true;
10452 }
10453 return false;
10454 };
10455 pp$1.regexp_groupSpecifier = function(state) {
10456 if (state.eat(
10457 63
10458 /* ? */
10459 )) {
10460 if (!this.regexp_eatGroupName(state)) {
10461 state.raise("Invalid group");
10462 }
10463 var trackDisjunction = this.options.ecmaVersion >= 16;
10464 var known = state.groupNames[state.lastStringValue];
10465 if (known) {
10466 if (trackDisjunction) {
10467 for (var i2 = 0, list2 = known; i2 < list2.length; i2 += 1) {
10468 var altID = list2[i2];
10469 if (!altID.separatedFrom(state.branchID)) {
10470 state.raise("Duplicate capture group name");
10471 }
10472 }
10473 } else {
10474 state.raise("Duplicate capture group name");
10475 }
10476 }
10477 if (trackDisjunction) {
10478 (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);
10479 } else {
10480 state.groupNames[state.lastStringValue] = true;
10481 }
10482 }
10483 };
10484 pp$1.regexp_eatGroupName = function(state) {
10485 state.lastStringValue = "";
10486 if (state.eat(
10487 60
10488 /* < */
10489 )) {
10490 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(
10491 62
10492 /* > */
10493 )) {
10494 return true;
10495 }
10496 state.raise("Invalid capture group name");
10497 }
10498 return false;
10499 };
10500 pp$1.regexp_eatRegExpIdentifierName = function(state) {
10501 state.lastStringValue = "";
10502 if (this.regexp_eatRegExpIdentifierStart(state)) {
10503 state.lastStringValue += codePointToString(state.lastIntValue);
10504 while (this.regexp_eatRegExpIdentifierPart(state)) {
10505 state.lastStringValue += codePointToString(state.lastIntValue);
10506 }
10507 return true;
10508 }
10509 return false;
10510 };
10511 pp$1.regexp_eatRegExpIdentifierStart = function(state) {
10512 var start = state.pos;
10513 var forceU = this.options.ecmaVersion >= 11;
10514 var ch = state.current(forceU);
10515 state.advance(forceU);
10516 if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
10517 ch = state.lastIntValue;
10518 }
10519 if (isRegExpIdentifierStart(ch)) {
10520 state.lastIntValue = ch;
10521 return true;
10522 }
10523 state.pos = start;
10524 return false;
10525 };
10526 pp$1.regexp_eatRegExpIdentifierPart = function(state) {
10527 var start = state.pos;
10528 var forceU = this.options.ecmaVersion >= 11;
10529 var ch = state.current(forceU);
10530 state.advance(forceU);
10531 if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
10532 ch = state.lastIntValue;
10533 }
10534 if (isRegExpIdentifierPart(ch)) {
10535 state.lastIntValue = ch;
10536 return true;
10537 }
10538 state.pos = start;
10539 return false;
10540 };
10541 pp$1.regexp_eatAtomEscape = function(state) {
10542 if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
10543 return true;
10544 }
10545 if (state.switchU) {
10546 if (state.current() === 99) {
10547 state.raise("Invalid unicode escape");
10548 }
10549 state.raise("Invalid escape");
10550 }
10551 return false;
10552 };
10553 pp$1.regexp_eatBackReference = function(state) {
10554 var start = state.pos;
10555 if (this.regexp_eatDecimalEscape(state)) {
10556 var n = state.lastIntValue;
10557 if (state.switchU) {
10558 if (n > state.maxBackReference) {
10559 state.maxBackReference = n;
10560 }
10561 return true;
10562 }
10563 if (n <= state.numCapturingParens) {
10564 return true;
10565 }
10566 state.pos = start;
10567 }
10568 return false;
10569 };
10570 pp$1.regexp_eatKGroupName = function(state) {
10571 if (state.eat(
10572 107
10573 /* k */
10574 )) {
10575 if (this.regexp_eatGroupName(state)) {
10576 state.backReferenceNames.push(state.lastStringValue);
10577 return true;
10578 }
10579 state.raise("Invalid named reference");
10580 }
10581 return false;
10582 };
10583 pp$1.regexp_eatCharacterEscape = function(state) {
10584 return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
10585 };
10586 pp$1.regexp_eatCControlLetter = function(state) {
10587 var start = state.pos;
10588 if (state.eat(
10589 99
10590 /* c */
10591 )) {
10592 if (this.regexp_eatControlLetter(state)) {
10593 return true;
10594 }
10595 state.pos = start;
10596 }
10597 return false;
10598 };
10599 pp$1.regexp_eatZero = function(state) {
10600 if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {
10601 state.lastIntValue = 0;
10602 state.advance();
10603 return true;
10604 }
10605 return false;
10606 };
10607 pp$1.regexp_eatControlEscape = function(state) {
10608 var ch = state.current();
10609 if (ch === 116) {
10610 state.lastIntValue = 9;
10611 state.advance();
10612 return true;
10613 }
10614 if (ch === 110) {
10615 state.lastIntValue = 10;
10616 state.advance();
10617 return true;
10618 }
10619 if (ch === 118) {
10620 state.lastIntValue = 11;
10621 state.advance();
10622 return true;
10623 }
10624 if (ch === 102) {
10625 state.lastIntValue = 12;
10626 state.advance();
10627 return true;
10628 }
10629 if (ch === 114) {
10630 state.lastIntValue = 13;
10631 state.advance();
10632 return true;
10633 }
10634 return false;
10635 };
10636 pp$1.regexp_eatControlLetter = function(state) {
10637 var ch = state.current();
10638 if (isControlLetter(ch)) {
10639 state.lastIntValue = ch % 32;
10640 state.advance();
10641 return true;
10642 }
10643 return false;
10644 };
10645 pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
10646 if (forceU === void 0) forceU = false;
10647 var start = state.pos;
10648 var switchU = forceU || state.switchU;
10649 if (state.eat(
10650 117
10651 /* u */
10652 )) {
10653 if (this.regexp_eatFixedHexDigits(state, 4)) {
10654 var lead = state.lastIntValue;
10655 if (switchU && lead >= 55296 && lead <= 56319) {
10656 var leadSurrogateEnd = state.pos;
10657 if (state.eat(
10658 92
10659 /* \ */
10660 ) && state.eat(
10661 117
10662 /* u */
10663 ) && this.regexp_eatFixedHexDigits(state, 4)) {
10664 var trail = state.lastIntValue;
10665 if (trail >= 56320 && trail <= 57343) {
10666 state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
10667 return true;
10668 }
10669 }
10670 state.pos = leadSurrogateEnd;
10671 state.lastIntValue = lead;
10672 }
10673 return true;
10674 }
10675 if (switchU && state.eat(
10676 123
10677 /* { */
10678 ) && this.regexp_eatHexDigits(state) && state.eat(
10679 125
10680 /* } */
10681 ) && isValidUnicode(state.lastIntValue)) {
10682 return true;
10683 }
10684 if (switchU) {
10685 state.raise("Invalid unicode escape");
10686 }
10687 state.pos = start;
10688 }
10689 return false;
10690 };
10691 pp$1.regexp_eatIdentityEscape = function(state) {
10692 if (state.switchU) {
10693 if (this.regexp_eatSyntaxCharacter(state)) {
10694 return true;
10695 }
10696 if (state.eat(
10697 47
10698 /* / */
10699 )) {
10700 state.lastIntValue = 47;
10701 return true;
10702 }
10703 return false;
10704 }
10705 var ch = state.current();
10706 if (ch !== 99 && (!state.switchN || ch !== 107)) {
10707 state.lastIntValue = ch;
10708 state.advance();
10709 return true;
10710 }
10711 return false;
10712 };
10713 pp$1.regexp_eatDecimalEscape = function(state) {
10714 state.lastIntValue = 0;
10715 var ch = state.current();
10716 if (ch >= 49 && ch <= 57) {
10717 do {
10718 state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
10719 state.advance();
10720 } while ((ch = state.current()) >= 48 && ch <= 57);
10721 return true;
10722 }
10723 return false;
10724 };
10725 CharSetNone = 0;
10726 CharSetOk = 1;
10727 CharSetString = 2;
10728 pp$1.regexp_eatCharacterClassEscape = function(state) {
10729 var ch = state.current();
10730 if (isCharacterClassEscape(ch)) {
10731 state.lastIntValue = -1;
10732 state.advance();
10733 return CharSetOk;
10734 }
10735 var negate = false;
10736 if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {
10737 state.lastIntValue = -1;
10738 state.advance();
10739 var result;
10740 if (state.eat(
10741 123
10742 /* { */
10743 ) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(
10744 125
10745 /* } */
10746 )) {
10747 if (negate && result === CharSetString) {
10748 state.raise("Invalid property name");
10749 }
10750 return result;
10751 }
10752 state.raise("Invalid property name");
10753 }
10754 return CharSetNone;
10755 };
10756 pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
10757 var start = state.pos;
10758 if (this.regexp_eatUnicodePropertyName(state) && state.eat(
10759 61
10760 /* = */
10761 )) {
10762 var name = state.lastStringValue;
10763 if (this.regexp_eatUnicodePropertyValue(state)) {
10764 var value = state.lastStringValue;
10765 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
10766 return CharSetOk;
10767 }
10768 }
10769 state.pos = start;
10770 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
10771 var nameOrValue = state.lastStringValue;
10772 return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
10773 }
10774 return CharSetNone;
10775 };
10776 pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
10777 if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
10778 state.raise("Invalid property name");
10779 }
10780 if (!state.unicodeProperties.nonBinary[name].test(value)) {
10781 state.raise("Invalid property value");
10782 }
10783 };
10784 pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
10785 if (state.unicodeProperties.binary.test(nameOrValue)) {
10786 return CharSetOk;
10787 }
10788 if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) {
10789 return CharSetString;
10790 }
10791 state.raise("Invalid property name");
10792 };
10793 pp$1.regexp_eatUnicodePropertyName = function(state) {
10794 var ch = 0;
10795 state.lastStringValue = "";
10796 while (isUnicodePropertyNameCharacter(ch = state.current())) {
10797 state.lastStringValue += codePointToString(ch);
10798 state.advance();
10799 }
10800 return state.lastStringValue !== "";
10801 };
10802 pp$1.regexp_eatUnicodePropertyValue = function(state) {
10803 var ch = 0;
10804 state.lastStringValue = "";
10805 while (isUnicodePropertyValueCharacter(ch = state.current())) {
10806 state.lastStringValue += codePointToString(ch);
10807 state.advance();
10808 }
10809 return state.lastStringValue !== "";
10810 };
10811 pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
10812 return this.regexp_eatUnicodePropertyValue(state);
10813 };
10814 pp$1.regexp_eatCharacterClass = function(state) {
10815 if (state.eat(
10816 91
10817 /* [ */
10818 )) {
10819 var negate = state.eat(
10820 94
10821 /* ^ */
10822 );
10823 var result = this.regexp_classContents(state);
10824 if (!state.eat(
10825 93
10826 /* ] */
10827 )) {
10828 state.raise("Unterminated character class");
10829 }
10830 if (negate && result === CharSetString) {
10831 state.raise("Negated character class may contain strings");
10832 }
10833 return true;
10834 }
10835 return false;
10836 };
10837 pp$1.regexp_classContents = function(state) {
10838 if (state.current() === 93) {
10839 return CharSetOk;
10840 }
10841 if (state.switchV) {
10842 return this.regexp_classSetExpression(state);
10843 }
10844 this.regexp_nonEmptyClassRanges(state);
10845 return CharSetOk;
10846 };
10847 pp$1.regexp_nonEmptyClassRanges = function(state) {
10848 while (this.regexp_eatClassAtom(state)) {
10849 var left = state.lastIntValue;
10850 if (state.eat(
10851 45
10852 /* - */
10853 ) && this.regexp_eatClassAtom(state)) {
10854 var right = state.lastIntValue;
10855 if (state.switchU && (left === -1 || right === -1)) {
10856 state.raise("Invalid character class");
10857 }
10858 if (left !== -1 && right !== -1 && left > right) {
10859 state.raise("Range out of order in character class");
10860 }
10861 }
10862 }
10863 };
10864 pp$1.regexp_eatClassAtom = function(state) {
10865 var start = state.pos;
10866 if (state.eat(
10867 92
10868 /* \ */
10869 )) {
10870 if (this.regexp_eatClassEscape(state)) {
10871 return true;
10872 }
10873 if (state.switchU) {
10874 var ch$1 = state.current();
10875 if (ch$1 === 99 || isOctalDigit(ch$1)) {
10876 state.raise("Invalid class escape");
10877 }
10878 state.raise("Invalid escape");
10879 }
10880 state.pos = start;
10881 }
10882 var ch = state.current();
10883 if (ch !== 93) {
10884 state.lastIntValue = ch;
10885 state.advance();
10886 return true;
10887 }
10888 return false;
10889 };
10890 pp$1.regexp_eatClassEscape = function(state) {
10891 var start = state.pos;
10892 if (state.eat(
10893 98
10894 /* b */
10895 )) {
10896 state.lastIntValue = 8;
10897 return true;
10898 }
10899 if (state.switchU && state.eat(
10900 45
10901 /* - */
10902 )) {
10903 state.lastIntValue = 45;
10904 return true;
10905 }
10906 if (!state.switchU && state.eat(
10907 99
10908 /* c */
10909 )) {
10910 if (this.regexp_eatClassControlLetter(state)) {
10911 return true;
10912 }
10913 state.pos = start;
10914 }
10915 return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
10916 };
10917 pp$1.regexp_classSetExpression = function(state) {
10918 var result = CharSetOk, subResult;
10919 if (this.regexp_eatClassSetRange(state)) ;
10920 else if (subResult = this.regexp_eatClassSetOperand(state)) {
10921 if (subResult === CharSetString) {
10922 result = CharSetString;
10923 }
10924 var start = state.pos;
10925 while (state.eatChars(
10926 [38, 38]
10927 /* && */
10928 )) {
10929 if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) {
10930 if (subResult !== CharSetString) {
10931 result = CharSetOk;
10932 }
10933 continue;
10934 }
10935 state.raise("Invalid character in character class");
10936 }
10937 if (start !== state.pos) {
10938 return result;
10939 }
10940 while (state.eatChars(
10941 [45, 45]
10942 /* -- */
10943 )) {
10944 if (this.regexp_eatClassSetOperand(state)) {
10945 continue;
10946 }
10947 state.raise("Invalid character in character class");
10948 }
10949 if (start !== state.pos) {
10950 return result;
10951 }
10952 } else {
10953 state.raise("Invalid character in character class");
10954 }
10955 for (; ; ) {
10956 if (this.regexp_eatClassSetRange(state)) {
10957 continue;
10958 }
10959 subResult = this.regexp_eatClassSetOperand(state);
10960 if (!subResult) {
10961 return result;
10962 }
10963 if (subResult === CharSetString) {
10964 result = CharSetString;
10965 }
10966 }
10967 };
10968 pp$1.regexp_eatClassSetRange = function(state) {
10969 var start = state.pos;
10970 if (this.regexp_eatClassSetCharacter(state)) {
10971 var left = state.lastIntValue;
10972 if (state.eat(
10973 45
10974 /* - */
10975 ) && this.regexp_eatClassSetCharacter(state)) {
10976 var right = state.lastIntValue;
10977 if (left !== -1 && right !== -1 && left > right) {
10978 state.raise("Range out of order in character class");
10979 }
10980 return true;
10981 }
10982 state.pos = start;
10983 }
10984 return false;
10985 };
10986 pp$1.regexp_eatClassSetOperand = function(state) {
10987 if (this.regexp_eatClassSetCharacter(state)) {
10988 return CharSetOk;
10989 }
10990 return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state);
10991 };
10992 pp$1.regexp_eatNestedClass = function(state) {
10993 var start = state.pos;
10994 if (state.eat(
10995 91
10996 /* [ */
10997 )) {
10998 var negate = state.eat(
10999 94
11000 /* ^ */
11001 );
11002 var result = this.regexp_classContents(state);
11003 if (state.eat(
11004 93
11005 /* ] */
11006 )) {
11007 if (negate && result === CharSetString) {
11008 state.raise("Negated character class may contain strings");
11009 }
11010 return result;
11011 }
11012 state.pos = start;
11013 }
11014 if (state.eat(
11015 92
11016 /* \ */
11017 )) {
11018 var result$1 = this.regexp_eatCharacterClassEscape(state);
11019 if (result$1) {
11020 return result$1;
11021 }
11022 state.pos = start;
11023 }
11024 return null;
11025 };
11026 pp$1.regexp_eatClassStringDisjunction = function(state) {
11027 var start = state.pos;
11028 if (state.eatChars(
11029 [92, 113]
11030 /* \q */
11031 )) {
11032 if (state.eat(
11033 123
11034 /* { */
11035 )) {
11036 var result = this.regexp_classStringDisjunctionContents(state);
11037 if (state.eat(
11038 125
11039 /* } */
11040 )) {
11041 return result;
11042 }
11043 } else {
11044 state.raise("Invalid escape");
11045 }
11046 state.pos = start;
11047 }
11048 return null;
11049 };
11050 pp$1.regexp_classStringDisjunctionContents = function(state) {
11051 var result = this.regexp_classString(state);
11052 while (state.eat(
11053 124
11054 /* | */
11055 )) {
11056 if (this.regexp_classString(state) === CharSetString) {
11057 result = CharSetString;
11058 }
11059 }
11060 return result;
11061 };
11062 pp$1.regexp_classString = function(state) {
11063 var count = 0;
11064 while (this.regexp_eatClassSetCharacter(state)) {
11065 count++;
11066 }
11067 return count === 1 ? CharSetOk : CharSetString;
11068 };
11069 pp$1.regexp_eatClassSetCharacter = function(state) {
11070 var start = state.pos;
11071 if (state.eat(
11072 92
11073 /* \ */
11074 )) {
11075 if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) {
11076 return true;
11077 }
11078 if (state.eat(
11079 98
11080 /* b */
11081 )) {
11082 state.lastIntValue = 8;
11083 return true;
11084 }
11085 state.pos = start;
11086 return false;
11087 }
11088 var ch = state.current();
11089 if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) {
11090 return false;
11091 }
11092 if (isClassSetSyntaxCharacter(ch)) {
11093 return false;
11094 }
11095 state.advance();
11096 state.lastIntValue = ch;
11097 return true;
11098 };
11099 pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
11100 var ch = state.current();
11101 if (isClassSetReservedPunctuator(ch)) {
11102 state.lastIntValue = ch;
11103 state.advance();
11104 return true;
11105 }
11106 return false;
11107 };
11108 pp$1.regexp_eatClassControlLetter = function(state) {
11109 var ch = state.current();
11110 if (isDecimalDigit(ch) || ch === 95) {
11111 state.lastIntValue = ch % 32;
11112 state.advance();
11113 return true;
11114 }
11115 return false;
11116 };
11117 pp$1.regexp_eatHexEscapeSequence = function(state) {
11118 var start = state.pos;
11119 if (state.eat(
11120 120
11121 /* x */
11122 )) {
11123 if (this.regexp_eatFixedHexDigits(state, 2)) {
11124 return true;
11125 }
11126 if (state.switchU) {
11127 state.raise("Invalid escape");
11128 }
11129 state.pos = start;
11130 }
11131 return false;
11132 };
11133 pp$1.regexp_eatDecimalDigits = function(state) {
11134 var start = state.pos;
11135 var ch = 0;
11136 state.lastIntValue = 0;
11137 while (isDecimalDigit(ch = state.current())) {
11138 state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
11139 state.advance();
11140 }
11141 return state.pos !== start;
11142 };
11143 pp$1.regexp_eatHexDigits = function(state) {
11144 var start = state.pos;
11145 var ch = 0;
11146 state.lastIntValue = 0;
11147 while (isHexDigit(ch = state.current())) {
11148 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
11149 state.advance();
11150 }
11151 return state.pos !== start;
11152 };
11153 pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
11154 if (this.regexp_eatOctalDigit(state)) {
11155 var n1 = state.lastIntValue;
11156 if (this.regexp_eatOctalDigit(state)) {
11157 var n2 = state.lastIntValue;
11158 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
11159 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
11160 } else {
11161 state.lastIntValue = n1 * 8 + n2;
11162 }
11163 } else {
11164 state.lastIntValue = n1;
11165 }
11166 return true;
11167 }
11168 return false;
11169 };
11170 pp$1.regexp_eatOctalDigit = function(state) {
11171 var ch = state.current();
11172 if (isOctalDigit(ch)) {
11173 state.lastIntValue = ch - 48;
11174 state.advance();
11175 return true;
11176 }
11177 state.lastIntValue = 0;
11178 return false;
11179 };
11180 pp$1.regexp_eatFixedHexDigits = function(state, length) {
11181 var start = state.pos;
11182 state.lastIntValue = 0;
11183 for (var i2 = 0; i2 < length; ++i2) {
11184 var ch = state.current();
11185 if (!isHexDigit(ch)) {
11186 state.pos = start;
11187 return false;
11188 }
11189 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
11190 state.advance();
11191 }
11192 return true;
11193 };
11194 Token = function Token2(p) {
11195 this.type = p.type;
11196 this.value = p.value;
11197 this.start = p.start;
11198 this.end = p.end;
11199 if (p.options.locations) {
11200 this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
11201 }
11202 if (p.options.ranges) {
11203 this.range = [p.start, p.end];
11204 }
11205 };
11206 pp = Parser.prototype;
11207 pp.next = function(ignoreEscapeSequenceInKeyword) {
11208 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
11209 this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
11210 }
11211 if (this.options.onToken) {
11212 this.options.onToken(new Token(this));
11213 }
11214 this.lastTokEnd = this.end;
11215 this.lastTokStart = this.start;
11216 this.lastTokEndLoc = this.endLoc;
11217 this.lastTokStartLoc = this.startLoc;
11218 this.nextToken();
11219 };
11220 pp.getToken = function() {
11221 this.next();
11222 return new Token(this);
11223 };
11224 if (typeof Symbol !== "undefined") {
11225 pp[Symbol.iterator] = function() {
11226 var this$1$1 = this;
11227 return {
11228 next: function() {
11229 var token = this$1$1.getToken();
11230 return {
11231 done: token.type === types$1.eof,
11232 value: token
11233 };
11234 }
11235 };
11236 };
11237 }
11238 pp.nextToken = function() {
11239 var curContext = this.curContext();
11240 if (!curContext || !curContext.preserveSpace) {
11241 this.skipSpace();
11242 }
11243 this.start = this.pos;
11244 if (this.options.locations) {
11245 this.startLoc = this.curPosition();
11246 }
11247 if (this.pos >= this.input.length) {
11248 return this.finishToken(types$1.eof);
11249 }
11250 if (curContext.override) {
11251 return curContext.override(this);
11252 } else {
11253 this.readToken(this.fullCharCodeAtPos());
11254 }
11255 };
11256 pp.readToken = function(code) {
11257 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) {
11258 return this.readWord();
11259 }
11260 return this.getTokenFromCode(code);
11261 };
11262 pp.fullCharCodeAt = function(pos) {
11263 var code = this.input.charCodeAt(pos);
11264 if (code <= 55295 || code >= 56320) {
11265 return code;
11266 }
11267 var next = this.input.charCodeAt(pos + 1);
11268 return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888;
11269 };
11270 pp.fullCharCodeAtPos = function() {
11271 return this.fullCharCodeAt(this.pos);
11272 };
11273 pp.skipBlockComment = function() {
11274 var startLoc = this.options.onComment && this.curPosition();
11275 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
11276 if (end === -1) {
11277 this.raise(this.pos - 2, "Unterminated comment");
11278 }
11279 this.pos = end + 2;
11280 if (this.options.locations) {
11281 for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) {
11282 ++this.curLine;
11283 pos = this.lineStart = nextBreak;
11284 }
11285 }
11286 if (this.options.onComment) {
11287 this.options.onComment(
11288 true,
11289 this.input.slice(start + 2, end),
11290 start,
11291 this.pos,
11292 startLoc,
11293 this.curPosition()
11294 );
11295 }
11296 };
11297 pp.skipLineComment = function(startSkip) {
11298 var start = this.pos;
11299 var startLoc = this.options.onComment && this.curPosition();
11300 var ch = this.input.charCodeAt(this.pos += startSkip);
11301 while (this.pos < this.input.length && !isNewLine(ch)) {
11302 ch = this.input.charCodeAt(++this.pos);
11303 }
11304 if (this.options.onComment) {
11305 this.options.onComment(
11306 false,
11307 this.input.slice(start + startSkip, this.pos),
11308 start,
11309 this.pos,
11310 startLoc,
11311 this.curPosition()
11312 );
11313 }
11314 };
11315 pp.skipSpace = function() {
11316 loop: while (this.pos < this.input.length) {
11317 var ch = this.input.charCodeAt(this.pos);
11318 switch (ch) {
11319 case 32:
11320 case 160:
11321 ++this.pos;
11322 break;
11323 case 13:
11324 if (this.input.charCodeAt(this.pos + 1) === 10) {
11325 ++this.pos;
11326 }
11327 case 10:
11328 case 8232:
11329 case 8233:
11330 ++this.pos;
11331 if (this.options.locations) {
11332 ++this.curLine;
11333 this.lineStart = this.pos;
11334 }
11335 break;
11336 case 47:
11337 switch (this.input.charCodeAt(this.pos + 1)) {
11338 case 42:
11339 this.skipBlockComment();
11340 break;
11341 case 47:
11342 this.skipLineComment(2);
11343 break;
11344 default:
11345 break loop;
11346 }
11347 break;
11348 default:
11349 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
11350 ++this.pos;
11351 } else {
11352 break loop;
11353 }
11354 }
11355 }
11356 };
11357 pp.finishToken = function(type2, val) {
11358 this.end = this.pos;
11359 if (this.options.locations) {
11360 this.endLoc = this.curPosition();
11361 }
11362 var prevType = this.type;
11363 this.type = type2;
11364 this.value = val;
11365 this.updateContext(prevType);
11366 };
11367 pp.readToken_dot = function() {
11368 var next = this.input.charCodeAt(this.pos + 1);
11369 if (next >= 48 && next <= 57) {
11370 return this.readNumber(true);
11371 }
11372 var next2 = this.input.charCodeAt(this.pos + 2);
11373 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
11374 this.pos += 3;
11375 return this.finishToken(types$1.ellipsis);
11376 } else {
11377 ++this.pos;
11378 return this.finishToken(types$1.dot);
11379 }
11380 };
11381 pp.readToken_slash = function() {
11382 var next = this.input.charCodeAt(this.pos + 1);
11383 if (this.exprAllowed) {
11384 ++this.pos;
11385 return this.readRegexp();
11386 }
11387 if (next === 61) {
11388 return this.finishOp(types$1.assign, 2);
11389 }
11390 return this.finishOp(types$1.slash, 1);
11391 };
11392 pp.readToken_mult_modulo_exp = function(code) {
11393 var next = this.input.charCodeAt(this.pos + 1);
11394 var size = 1;
11395 var tokentype = code === 42 ? types$1.star : types$1.modulo;
11396 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
11397 ++size;
11398 tokentype = types$1.starstar;
11399 next = this.input.charCodeAt(this.pos + 2);
11400 }
11401 if (next === 61) {
11402 return this.finishOp(types$1.assign, size + 1);
11403 }
11404 return this.finishOp(tokentype, size);
11405 };
11406 pp.readToken_pipe_amp = function(code) {
11407 var next = this.input.charCodeAt(this.pos + 1);
11408 if (next === code) {
11409 if (this.options.ecmaVersion >= 12) {
11410 var next2 = this.input.charCodeAt(this.pos + 2);
11411 if (next2 === 61) {
11412 return this.finishOp(types$1.assign, 3);
11413 }
11414 }
11415 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2);
11416 }
11417 if (next === 61) {
11418 return this.finishOp(types$1.assign, 2);
11419 }
11420 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1);
11421 };
11422 pp.readToken_caret = function() {
11423 var next = this.input.charCodeAt(this.pos + 1);
11424 if (next === 61) {
11425 return this.finishOp(types$1.assign, 2);
11426 }
11427 return this.finishOp(types$1.bitwiseXOR, 1);
11428 };
11429 pp.readToken_plus_min = function(code) {
11430 var next = this.input.charCodeAt(this.pos + 1);
11431 if (next === code) {
11432 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
11433 this.skipLineComment(3);
11434 this.skipSpace();
11435 return this.nextToken();
11436 }
11437 return this.finishOp(types$1.incDec, 2);
11438 }
11439 if (next === 61) {
11440 return this.finishOp(types$1.assign, 2);
11441 }
11442 return this.finishOp(types$1.plusMin, 1);
11443 };
11444 pp.readToken_lt_gt = function(code) {
11445 var next = this.input.charCodeAt(this.pos + 1);
11446 var size = 1;
11447 if (next === code) {
11448 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
11449 if (this.input.charCodeAt(this.pos + size) === 61) {
11450 return this.finishOp(types$1.assign, size + 1);
11451 }
11452 return this.finishOp(types$1.bitShift, size);
11453 }
11454 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
11455 this.skipLineComment(4);
11456 this.skipSpace();
11457 return this.nextToken();
11458 }
11459 if (next === 61) {
11460 size = 2;
11461 }
11462 return this.finishOp(types$1.relational, size);
11463 };
11464 pp.readToken_eq_excl = function(code) {
11465 var next = this.input.charCodeAt(this.pos + 1);
11466 if (next === 61) {
11467 return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
11468 }
11469 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
11470 this.pos += 2;
11471 return this.finishToken(types$1.arrow);
11472 }
11473 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1);
11474 };
11475 pp.readToken_question = function() {
11476 var ecmaVersion2 = this.options.ecmaVersion;
11477 if (ecmaVersion2 >= 11) {
11478 var next = this.input.charCodeAt(this.pos + 1);
11479 if (next === 46) {
11480 var next2 = this.input.charCodeAt(this.pos + 2);
11481 if (next2 < 48 || next2 > 57) {
11482 return this.finishOp(types$1.questionDot, 2);
11483 }
11484 }
11485 if (next === 63) {
11486 if (ecmaVersion2 >= 12) {
11487 var next2$1 = this.input.charCodeAt(this.pos + 2);
11488 if (next2$1 === 61) {
11489 return this.finishOp(types$1.assign, 3);
11490 }
11491 }
11492 return this.finishOp(types$1.coalesce, 2);
11493 }
11494 }
11495 return this.finishOp(types$1.question, 1);
11496 };
11497 pp.readToken_numberSign = function() {
11498 var ecmaVersion2 = this.options.ecmaVersion;
11499 var code = 35;
11500 if (ecmaVersion2 >= 13) {
11501 ++this.pos;
11502 code = this.fullCharCodeAtPos();
11503 if (isIdentifierStart(code, true) || code === 92) {
11504 return this.finishToken(types$1.privateId, this.readWord1());
11505 }
11506 }
11507 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
11508 };
11509 pp.getTokenFromCode = function(code) {
11510 switch (code) {
11511 // The interpretation of a dot depends on whether it is followed
11512 // by a digit or another two dots.
11513 case 46:
11514 return this.readToken_dot();
11515 // Punctuation tokens.
11516 case 40:
11517 ++this.pos;
11518 return this.finishToken(types$1.parenL);
11519 case 41:
11520 ++this.pos;
11521 return this.finishToken(types$1.parenR);
11522 case 59:
11523 ++this.pos;
11524 return this.finishToken(types$1.semi);
11525 case 44:
11526 ++this.pos;
11527 return this.finishToken(types$1.comma);
11528 case 91:
11529 ++this.pos;
11530 return this.finishToken(types$1.bracketL);
11531 case 93:
11532 ++this.pos;
11533 return this.finishToken(types$1.bracketR);
11534 case 123:
11535 ++this.pos;
11536 return this.finishToken(types$1.braceL);
11537 case 125:
11538 ++this.pos;
11539 return this.finishToken(types$1.braceR);
11540 case 58:
11541 ++this.pos;
11542 return this.finishToken(types$1.colon);
11543 case 96:
11544 if (this.options.ecmaVersion < 6) {
11545 break;
11546 }
11547 ++this.pos;
11548 return this.finishToken(types$1.backQuote);
11549 case 48:
11550 var next = this.input.charCodeAt(this.pos + 1);
11551 if (next === 120 || next === 88) {
11552 return this.readRadixNumber(16);
11553 }
11554 if (this.options.ecmaVersion >= 6) {
11555 if (next === 111 || next === 79) {
11556 return this.readRadixNumber(8);
11557 }
11558 if (next === 98 || next === 66) {
11559 return this.readRadixNumber(2);
11560 }
11561 }
11562 // Anything else beginning with a digit is an integer, octal
11563 // number, or float.
11564 case 49:
11565 case 50:
11566 case 51:
11567 case 52:
11568 case 53:
11569 case 54:
11570 case 55:
11571 case 56:
11572 case 57:
11573 return this.readNumber(false);
11574 // Quotes produce strings.
11575 case 34:
11576 case 39:
11577 return this.readString(code);
11578 // Operators are parsed inline in tiny state machines. '=' (61) is
11579 // often referred to. `finishOp` simply skips the amount of
11580 // characters it is given as second argument, and returns a token
11581 // of the type given by its first argument.
11582 case 47:
11583 return this.readToken_slash();
11584 case 37:
11585 case 42:
11586 return this.readToken_mult_modulo_exp(code);
11587 case 124:
11588 case 38:
11589 return this.readToken_pipe_amp(code);
11590 case 94:
11591 return this.readToken_caret();
11592 case 43:
11593 case 45:
11594 return this.readToken_plus_min(code);
11595 case 60:
11596 case 62:
11597 return this.readToken_lt_gt(code);
11598 case 61:
11599 case 33:
11600 return this.readToken_eq_excl(code);
11601 case 63:
11602 return this.readToken_question();
11603 case 126:
11604 return this.finishOp(types$1.prefix, 1);
11605 case 35:
11606 return this.readToken_numberSign();
11607 }
11608 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
11609 };
11610 pp.finishOp = function(type2, size) {
11611 var str2 = this.input.slice(this.pos, this.pos + size);
11612 this.pos += size;
11613 return this.finishToken(type2, str2);
11614 };
11615 pp.readRegexp = function() {
11616 var escaped, inClass, start = this.pos;
11617 for (; ; ) {
11618 if (this.pos >= this.input.length) {
11619 this.raise(start, "Unterminated regular expression");
11620 }
11621 var ch = this.input.charAt(this.pos);
11622 if (lineBreak.test(ch)) {
11623 this.raise(start, "Unterminated regular expression");
11624 }
11625 if (!escaped) {
11626 if (ch === "[") {
11627 inClass = true;
11628 } else if (ch === "]" && inClass) {
11629 inClass = false;
11630 } else if (ch === "/" && !inClass) {
11631 break;
11632 }
11633 escaped = ch === "\\";
11634 } else {
11635 escaped = false;
11636 }
11637 ++this.pos;
11638 }
11639 var pattern = this.input.slice(start, this.pos);
11640 ++this.pos;
11641 var flagsStart = this.pos;
11642 var flags = this.readWord1();
11643 if (this.containsEsc) {
11644 this.unexpected(flagsStart);
11645 }
11646 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
11647 state.reset(start, pattern, flags);
11648 this.validateRegExpFlags(state);
11649 this.validateRegExpPattern(state);
11650 var value = null;
11651 try {
11652 value = new RegExp(pattern, flags);
11653 } catch (e) {
11654 }
11655 return this.finishToken(types$1.regexp, { pattern, flags, value });
11656 };
11657 pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
11658 var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
11659 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
11660 var start = this.pos, total = 0, lastCode = 0;
11661 for (var i2 = 0, e = len == null ? Infinity : len; i2 < e; ++i2, ++this.pos) {
11662 var code = this.input.charCodeAt(this.pos), val = void 0;
11663 if (allowSeparators && code === 95) {
11664 if (isLegacyOctalNumericLiteral) {
11665 this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
11666 }
11667 if (lastCode === 95) {
11668 this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
11669 }
11670 if (i2 === 0) {
11671 this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
11672 }
11673 lastCode = code;
11674 continue;
11675 }
11676 if (code >= 97) {
11677 val = code - 97 + 10;
11678 } else if (code >= 65) {
11679 val = code - 65 + 10;
11680 } else if (code >= 48 && code <= 57) {
11681 val = code - 48;
11682 } else {
11683 val = Infinity;
11684 }
11685 if (val >= radix) {
11686 break;
11687 }
11688 lastCode = code;
11689 total = total * radix + val;
11690 }
11691 if (allowSeparators && lastCode === 95) {
11692 this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
11693 }
11694 if (this.pos === start || len != null && this.pos - start !== len) {
11695 return null;
11696 }
11697 return total;
11698 };
11699 pp.readRadixNumber = function(radix) {
11700 var start = this.pos;
11701 this.pos += 2;
11702 var val = this.readInt(radix);
11703 if (val == null) {
11704 this.raise(this.start + 2, "Expected number in radix " + radix);
11705 }
11706 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
11707 val = stringToBigInt(this.input.slice(start, this.pos));
11708 ++this.pos;
11709 } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
11710 this.raise(this.pos, "Identifier directly after number");
11711 }
11712 return this.finishToken(types$1.num, val);
11713 };
11714 pp.readNumber = function(startsWithDot) {
11715 var start = this.pos;
11716 if (!startsWithDot && this.readInt(10, void 0, true) === null) {
11717 this.raise(start, "Invalid number");
11718 }
11719 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
11720 if (octal && this.strict) {
11721 this.raise(start, "Invalid number");
11722 }
11723 var next = this.input.charCodeAt(this.pos);
11724 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
11725 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
11726 ++this.pos;
11727 if (isIdentifierStart(this.fullCharCodeAtPos())) {
11728 this.raise(this.pos, "Identifier directly after number");
11729 }
11730 return this.finishToken(types$1.num, val$1);
11731 }
11732 if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
11733 octal = false;
11734 }
11735 if (next === 46 && !octal) {
11736 ++this.pos;
11737 this.readInt(10);
11738 next = this.input.charCodeAt(this.pos);
11739 }
11740 if ((next === 69 || next === 101) && !octal) {
11741 next = this.input.charCodeAt(++this.pos);
11742 if (next === 43 || next === 45) {
11743 ++this.pos;
11744 }
11745 if (this.readInt(10) === null) {
11746 this.raise(start, "Invalid number");
11747 }
11748 }
11749 if (isIdentifierStart(this.fullCharCodeAtPos())) {
11750 this.raise(this.pos, "Identifier directly after number");
11751 }
11752 var val = stringToNumber(this.input.slice(start, this.pos), octal);
11753 return this.finishToken(types$1.num, val);
11754 };
11755 pp.readCodePoint = function() {
11756 var ch = this.input.charCodeAt(this.pos), code;
11757 if (ch === 123) {
11758 if (this.options.ecmaVersion < 6) {
11759 this.unexpected();
11760 }
11761 var codePos = ++this.pos;
11762 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
11763 ++this.pos;
11764 if (code > 1114111) {
11765 this.invalidStringToken(codePos, "Code point out of bounds");
11766 }
11767 } else {
11768 code = this.readHexChar(4);
11769 }
11770 return code;
11771 };
11772 pp.readString = function(quote) {
11773 var out = "", chunkStart = ++this.pos;
11774 for (; ; ) {
11775 if (this.pos >= this.input.length) {
11776 this.raise(this.start, "Unterminated string constant");
11777 }
11778 var ch = this.input.charCodeAt(this.pos);
11779 if (ch === quote) {
11780 break;
11781 }
11782 if (ch === 92) {
11783 out += this.input.slice(chunkStart, this.pos);
11784 out += this.readEscapedChar(false);
11785 chunkStart = this.pos;
11786 } else if (ch === 8232 || ch === 8233) {
11787 if (this.options.ecmaVersion < 10) {
11788 this.raise(this.start, "Unterminated string constant");
11789 }
11790 ++this.pos;
11791 if (this.options.locations) {
11792 this.curLine++;
11793 this.lineStart = this.pos;
11794 }
11795 } else {
11796 if (isNewLine(ch)) {
11797 this.raise(this.start, "Unterminated string constant");
11798 }
11799 ++this.pos;
11800 }
11801 }
11802 out += this.input.slice(chunkStart, this.pos++);
11803 return this.finishToken(types$1.string, out);
11804 };
11805 INVALID_TEMPLATE_ESCAPE_ERROR = {};
11806 pp.tryReadTemplateToken = function() {
11807 this.inTemplateElement = true;
11808 try {
11809 this.readTmplToken();
11810 } catch (err) {
11811 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
11812 this.readInvalidTemplateToken();
11813 } else {
11814 throw err;
11815 }
11816 }
11817 this.inTemplateElement = false;
11818 };
11819 pp.invalidStringToken = function(position, message) {
11820 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
11821 throw INVALID_TEMPLATE_ESCAPE_ERROR;
11822 } else {
11823 this.raise(position, message);
11824 }
11825 };
11826 pp.readTmplToken = function() {
11827 var out = "", chunkStart = this.pos;
11828 for (; ; ) {
11829 if (this.pos >= this.input.length) {
11830 this.raise(this.start, "Unterminated template");
11831 }
11832 var ch = this.input.charCodeAt(this.pos);
11833 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
11834 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
11835 if (ch === 36) {
11836 this.pos += 2;
11837 return this.finishToken(types$1.dollarBraceL);
11838 } else {
11839 ++this.pos;
11840 return this.finishToken(types$1.backQuote);
11841 }
11842 }
11843 out += this.input.slice(chunkStart, this.pos);
11844 return this.finishToken(types$1.template, out);
11845 }
11846 if (ch === 92) {
11847 out += this.input.slice(chunkStart, this.pos);
11848 out += this.readEscapedChar(true);
11849 chunkStart = this.pos;
11850 } else if (isNewLine(ch)) {
11851 out += this.input.slice(chunkStart, this.pos);
11852 ++this.pos;
11853 switch (ch) {
11854 case 13:
11855 if (this.input.charCodeAt(this.pos) === 10) {
11856 ++this.pos;
11857 }
11858 case 10:
11859 out += "\n";
11860 break;
11861 default:
11862 out += String.fromCharCode(ch);
11863 break;
11864 }
11865 if (this.options.locations) {
11866 ++this.curLine;
11867 this.lineStart = this.pos;
11868 }
11869 chunkStart = this.pos;
11870 } else {
11871 ++this.pos;
11872 }
11873 }
11874 };
11875 pp.readInvalidTemplateToken = function() {
11876 for (; this.pos < this.input.length; this.pos++) {
11877 switch (this.input[this.pos]) {
11878 case "\\":
11879 ++this.pos;
11880 break;
11881 case "$":
11882 if (this.input[this.pos + 1] !== "{") {
11883 break;
11884 }
11885 // fall through
11886 case "`":
11887 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos));
11888 case "\r":
11889 if (this.input[this.pos + 1] === "\n") {
11890 ++this.pos;
11891 }
11892 // fall through
11893 case "\n":
11894 case "\u2028":
11895 case "\u2029":
11896 ++this.curLine;
11897 this.lineStart = this.pos + 1;
11898 break;
11899 }
11900 }
11901 this.raise(this.start, "Unterminated template");
11902 };
11903 pp.readEscapedChar = function(inTemplate) {
11904 var ch = this.input.charCodeAt(++this.pos);
11905 ++this.pos;
11906 switch (ch) {
11907 case 110:
11908 return "\n";
11909 // 'n' -> '\n'
11910 case 114:
11911 return "\r";
11912 // 'r' -> '\r'
11913 case 120:
11914 return String.fromCharCode(this.readHexChar(2));
11915 // 'x'
11916 case 117:
11917 return codePointToString(this.readCodePoint());
11918 // 'u'
11919 case 116:
11920 return " ";
11921 // 't' -> '\t'
11922 case 98:
11923 return "\b";
11924 // 'b' -> '\b'
11925 case 118:
11926 return "\v";
11927 // 'v' -> '\u000b'
11928 case 102:
11929 return "\f";
11930 // 'f' -> '\f'
11931 case 13:
11932 if (this.input.charCodeAt(this.pos) === 10) {
11933 ++this.pos;
11934 }
11935 // '\r\n'
11936 case 10:
11937 if (this.options.locations) {
11938 this.lineStart = this.pos;
11939 ++this.curLine;
11940 }
11941 return "";
11942 case 56:
11943 case 57:
11944 if (this.strict) {
11945 this.invalidStringToken(
11946 this.pos - 1,
11947 "Invalid escape sequence"
11948 );
11949 }
11950 if (inTemplate) {
11951 var codePos = this.pos - 1;
11952 this.invalidStringToken(
11953 codePos,
11954 "Invalid escape sequence in template string"
11955 );
11956 }
11957 default:
11958 if (ch >= 48 && ch <= 55) {
11959 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
11960 var octal = parseInt(octalStr, 8);
11961 if (octal > 255) {
11962 octalStr = octalStr.slice(0, -1);
11963 octal = parseInt(octalStr, 8);
11964 }
11965 this.pos += octalStr.length - 1;
11966 ch = this.input.charCodeAt(this.pos);
11967 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
11968 this.invalidStringToken(
11969 this.pos - 1 - octalStr.length,
11970 inTemplate ? "Octal literal in template string" : "Octal literal in strict mode"
11971 );
11972 }
11973 return String.fromCharCode(octal);
11974 }
11975 if (isNewLine(ch)) {
11976 if (this.options.locations) {
11977 this.lineStart = this.pos;
11978 ++this.curLine;
11979 }
11980 return "";
11981 }
11982 return String.fromCharCode(ch);
11983 }
11984 };
11985 pp.readHexChar = function(len) {
11986 var codePos = this.pos;
11987 var n = this.readInt(16, len);
11988 if (n === null) {
11989 this.invalidStringToken(codePos, "Bad character escape sequence");
11990 }
11991 return n;
11992 };
11993 pp.readWord1 = function() {
11994 this.containsEsc = false;
11995 var word = "", first = true, chunkStart = this.pos;
11996 var astral = this.options.ecmaVersion >= 6;
11997 while (this.pos < this.input.length) {
11998 var ch = this.fullCharCodeAtPos();
11999 if (isIdentifierChar(ch, astral)) {
12000 this.pos += ch <= 65535 ? 1 : 2;
12001 } else if (ch === 92) {
12002 this.containsEsc = true;
12003 word += this.input.slice(chunkStart, this.pos);
12004 var escStart = this.pos;
12005 if (this.input.charCodeAt(++this.pos) !== 117) {
12006 this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
12007 }
12008 ++this.pos;
12009 var esc = this.readCodePoint();
12010 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
12011 this.invalidStringToken(escStart, "Invalid Unicode escape");
12012 }
12013 word += codePointToString(esc);
12014 chunkStart = this.pos;
12015 } else {
12016 break;
12017 }
12018 first = false;
12019 }
12020 return word + this.input.slice(chunkStart, this.pos);
12021 };
12022 pp.readWord = function() {
12023 var word = this.readWord1();
12024 var type2 = types$1.name;
12025 if (this.keywords.test(word)) {
12026 type2 = keywords[word];
12027 }
12028 return this.finishToken(type2, word);
12029 };
12030 version = "8.18.0";
12031 Parser.acorn = {
12032 Parser,
12033 version,
12034 defaultOptions,
12035 Position,
12036 SourceLocation,
12037 getLineInfo,
12038 Node,
12039 TokenType,
12040 tokTypes: types$1,
12041 keywordTypes: keywords,
12042 TokContext,
12043 tokContexts: types2,
12044 isIdentifierChar,
12045 isIdentifierStart,
12046 Token,
12047 isNewLine,
12048 lineBreak,
12049 lineBreakG,
12050 nonASCIIwhitespace
12051 };
12052 }
12053 });
12054
12055 // src/dsh/bun-closure.ts
12056 var init_bun_closure = __esm({
12057 "src/dsh/bun-closure.ts"() {
12058 "use strict";
12059 init_acorn();
12060 }
12061 });
12062
12063 // src/dsh/resolve-hooks.ts
12064 import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "node:url";
12065 import { resolve as resolve2, isAbsolute as isAbsolute2, dirname } from "node:path";
12066 function keyIn(closure, path) {
12067 const canonical = insideKey(closure.canonicalRoot, path);
12068 if (canonical !== void 0) return canonical;
12069 for (const root of closure.rawRoots) {
12070 const raw = insideKey(root, path);
12071 if (raw !== void 0) return raw;
12072 }
12073 }
12074 function admitReviewedClosure(baseUrl, files) {
12075 const rawRoot = resolve2(fileURLToPath2(baseUrl));
12076 const canonicalRoot = canonicalPath(rawRoot);
12077 const id = pathKey(canonicalRoot);
12078 const accepted = /* @__PURE__ */ Object.create(null);
12079 const keys = Object.keys(files);
12080 if (keys.length > 4096) throw new Error("reviewed composition closure exceeds its file limit");
12081 for (const key of keys) {
12082 if (!key || key.split("/").some((part) => !part || part === "." || part === "..") || key.includes("\\") || key.includes(":") || isAbsolute2(key) || !/^[a-f0-9]{64}$/.test(files[key])) throw new Error("invalid reviewed composition closure file");
12083 accepted[key] = files[key];
12084 }
12085 const existing = reviewedClosures.get(id);
12086 if (existing) {
12087 if (Object.keys(existing.files).length !== keys.length || keys.some((key) => existing.files[key] !== accepted[key])) throw new Error("the same composition root carries different file receipts");
12088 existing.refs++;
12089 existing.rawRoots.add(rawRoot);
12090 } else reviewedClosures.set(id, { files: Object.freeze(accepted), refs: 1, canonicalRoot, rawRoots: /* @__PURE__ */ new Set([rawRoot]) });
12091 let disposed = false;
12092 return () => {
12093 if (disposed) return;
12094 disposed = true;
12095 const current2 = reviewedClosures.get(id);
12096 if (current2 && --current2.refs === 0) reviewedClosures.delete(id);
12097 };
12098 }
12099 async function importReviewedModule(baseUrl, path) {
12100 const rawRoot = resolve2(fileURLToPath2(baseUrl));
12101 const id = pathKey(canonicalPath(rawRoot));
12102 const receipt = reviewedClosures.get(id);
12103 if (!receipt) throw new Error("composition module closure is no longer admitted");
12104 const entry = resolve2(rawRoot, path);
12105 const admitted = closureAt(pathToFileURL2(entry).href);
12106 if (!admitted || admitted.root !== id || !(admitted.path in receipt.files)) throw new Error("composition module is absent from reviewed closure");
12107 return import(pathToFileURL2(entry).href);
12108 }
12109 function closureAt(url) {
12110 if (!url?.startsWith("file:")) return;
12111 const path = resolve2(fileURLToPath2(url));
12112 for (const [root, receipt] of reviewedClosures) {
12113 const inside = keyIn(receipt, path);
12114 if (inside !== void 0) return { root, receipt, path: inside };
12115 }
12116 }
12117 var reviewedClosures;
12118 var init_resolve_hooks = __esm({
12119 "src/dsh/resolve-hooks.ts"() {
12120 "use strict";
12121 init_canonical_path();
12122 init_runtime();
12123 init_bun_closure();
12124 reviewedClosures = /* @__PURE__ */ new Map();
12125 }
12126 });
12127
12128 // src/dsh/composition.ts
12129 var composition_exports = {};
12130 __export(composition_exports, {
12131 ReviewedLoader: () => ReviewedLoader,
12132 compositionRowProblem: () => compositionRowProblem,
12133 hasReviewedRowBridge: () => hasReviewedRowBridge,
12134 installCompositionLoader: () => installCompositionLoader,
12135 mountReviewedComposition: () => mountReviewedComposition,
12136 mountReviewedPreset: () => mountReviewedPreset,
12137 parsePresetComposition: () => parsePresetComposition,
12138 reviewComposition: () => reviewComposition
12139 });
12140 import { createHash as createHash2 } from "node:crypto";
12141 import { readFile as readFile2 } from "node:fs/promises";
12142 import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
12143 import { fileURLToPath as fileURLToPath3 } from "node:url";
12144 function digest(bytes) {
12145 return createHash2("sha256").update(bytes).digest("hex");
12146 }
12147 function plainRelative(path) {
12148 return typeof path === "string" && path.length > 0 && path.length <= 4096 && !isAbsolute3(path) && !path.startsWith("/") && !/[\\:\u0000-\u001f\u007f]/u.test(path) && path.split("/").every((part) => part !== "" && part !== "." && part !== "..");
12149 }
12150 function boundData(root) {
12151 let nodes = 0;
12152 let bytes = 0;
12153 const ancestors = /* @__PURE__ */ new Set();
12154 function visit(value, depth) {
12155 if (++nodes > MAX_DATA_NODES || depth > MAX_DEPTH) throw new Error("composition data exceeds its resource limit");
12156 if (typeof value === "string") bytes += Buffer.byteLength(value);
12157 if (bytes > MAX_DATA_BYTES) throw new Error("composition expanded text exceeds 4 MiB");
12158 if (value === null || typeof value !== "object") return;
12159 if (ancestors.has(value)) throw new Error("cyclic configuration data is unsupported");
12160 ancestors.add(value);
12161 if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
12162 throw new Error("composition configuration must be plain data");
12163 }
12164 for (const [key, child] of Object.entries(value)) {
12165 bytes += Buffer.byteLength(key);
12166 visit(child, depth + 1);
12167 }
12168 ancestors.delete(value);
12169 }
12170 visit(root, 0);
12171 }
12172 function assignmentSafe(value) {
12173 if (Object.hasOwn(value, "__proto__")) throw new Error("prototype-mutating entry field is unsupported");
12174 }
12175 function checkRows(rows, depth = 0, count = { value: 0 }) {
12176 if (depth > MAX_DEPTH) throw new Error("composition entry nesting exceeds 32 levels");
12177 for (const row of rows) {
12178 if (++count.value > MAX_ROWS) throw new Error("composition exceeds 1024 entry rows");
12179 if (row === null || typeof row !== "object" || Array.isArray(row)) throw new Error("entry row must be an object");
12180 assignmentSafe(row);
12181 if (row.id !== void 0 && (typeof row.id !== "string" || row.id.length > 512)) throw new Error("entry id must be a bounded string");
12182 if (!(row.group === true && row.name === void 0) && (typeof row.name !== "string" || row.name.length === 0 || row.name.length > 4096)) throw new Error("entry name must be a bounded string");
12183 if ((row.group || row.name === "cordis:group" || row.name === "@deepseek-ai/cordis-plugin-group") && Array.isArray(row.config)) checkRows(row.config, depth + 1, count);
12184 }
12185 }
12186 function parsePresetComposition(source) {
12187 if (Buffer.byteLength(source) > MAX_SOURCE_BYTES) throw new Error("preset source exceeds its limit");
12188 const rows = load(source, { schema: entryListSchema });
12189 boundData(rows);
12190 if (!Array.isArray(rows)) throw new Error("preset composition must be an entry list");
12191 checkRows(rows);
12192 return rows;
12193 }
12194 function reviewComposition(spec) {
12195 if (!spec || spec.version !== 1 || !Array.isArray(spec.layers) || spec.layers.length === 0 || spec.layers.length > MAX_LAYERS) {
12196 throw new Error("composition needs 1–64 reviewed layers");
12197 }
12198 let sourceBytes = 0;
12199 const patches = [];
12200 const locations = [];
12201 const layers = [];
12202 for (const layer of spec.layers) {
12203 if (!layer || !plainRelative(layer.path) || typeof layer.source !== "string" || typeof layer.sha256 !== "string" || !SHA256.test(layer.sha256)) throw new Error("invalid reviewed layer");
12204 sourceBytes += Buffer.byteLength(layer.source);
12205 if (sourceBytes > MAX_SOURCE_BYTES || digest(layer.source) !== layer.sha256) throw new Error("layer source changed or exceeds 1 MiB");
12206 let parsed;
12207 try {
12208 parsed = load(layer.source, { schema: entryListSchema });
12209 } catch {
12210 throw new Error("invalid DSH patch data");
12211 }
12212 if (!Array.isArray(parsed)) throw new Error("DSH patch layer must be a list");
12213 boundData(parsed);
12214 for (const patch of parsed) {
12215 if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new Error("patch must be an object");
12216 assignmentSafe(patch);
12217 if (patch.insert !== void 0 && patch.insert !== null) {
12218 if (!Array.isArray(patch.insert)) throw new Error("patch insert must be a list");
12219 checkRows(patch.insert);
12220 }
12221 }
12222 patches.push(...parsed);
12223 locations.push(...parsed.map((_, i2) => ({ layer: layer.path, patch: i2 + 1 })));
12224 layers.push({ path: layer.path, sha256: layer.sha256 });
12225 }
12226 boundData(patches);
12227 const warnings = [];
12228 const skipped = [];
12229 let entries = [];
12230 for (const [i2, patch] of patches.entries()) {
12231 entries = applyEntryPatches(entries, [patch], (message, ...args) => {
12232 let index = 0;
12233 const reason = message.replace(/%C/g, () => JSON.stringify(args[index++]));
12234 warnings.push(reason);
12235 skipped.push({ ...typeof patch.id === "string" ? { row: patch.id } : {}, ...typeof patch.name === "string" ? { package: patch.name } : {}, reason, ...locations[i2] });
12236 });
12237 }
12238 boundData(entries);
12239 checkRows(entries);
12240 return { version: 1, entries, warnings, skipped, layers };
12241 }
12242 function hasReviewedRowBridge(name) {
12243 return name === "@deepseek-ai/dsh-mcp-client" || name === "@deepseek-ai/dsh-skill-filesystem" || name === "@deepseek-ai/dsh-hooks-claude-code" || name === "@deepseek-ai/dsh-hooks-codex" || name === PERSONA;
12244 }
12245 function compositionRowProblem(name) {
12246 return UNSUPPORTED_ROWS.get(name);
12247 }
12248 function installCompositionLoader(root) {
12249 if (loaders.has(root)) return;
12250 const ctx = root.isolate("loader");
12251 const fiber = ctx.plugin(ReviewedLoader, {});
12252 loaders.set(root, { ctx, fiber });
12253 }
12254 function validateInventory(group) {
12255 for (const row of group.data) {
12256 const entry = group.tree.store[row.id];
12257 if (!entry || entry.parent !== group || entry.options !== row) {
12258 throw new Error(`composition row ${JSON.stringify(row.id ?? row.name)} was not created`);
12259 }
12260 if (entry.disabled) continue;
12261 if (entry.subgroup) validateInventory(entry.subgroup);
12262 if (entry.subtree) validateInventory(entry.subtree.root);
12263 }
12264 }
12265 async function mountReviewedComposition(ctx, baseUrl, spec) {
12266 const review = reviewComposition(spec);
12267 function groups(rows) {
12268 for (const row of rows) {
12269 if (row.group === true && row.name === void 0) row.name = "cordis:group";
12270 if (row.group === true && Array.isArray(row.config)) groups(row.config);
12271 }
12272 }
12273 groups(review.entries);
12274 const installed = loaders.get(ctx.root);
12275 if (!installed) throw new Error("composition loader was not installed by this host");
12276 await installed.fiber.await();
12277 const loaderCtx = ctx.extend({
12278 baseUrl,
12279 [Context.isolate]: Object.assign(Object.create(ctx[Context.isolate]), {
12280 loader: installed.ctx[Context.isolate].loader
12281 })
12282 });
12283 const config = { baseUrl, spec, review, releaseClosure: admitReviewedClosure(baseUrl, spec.files) };
12284 const carrier = loaderCtx.plugin(ReviewedCarrier, config);
12285 let disposed = false;
12286 const dispose = async () => {
12287 if (disposed) return;
12288 disposed = true;
12289 try {
12290 await mountedTrees.get(config)?.dispose();
12291 await carrier.dispose();
12292 } finally {
12293 config.releaseClosure();
12294 }
12295 };
12296 ctx.effect(() => dispose, "reviewed DSH composition teardown");
12297 try {
12298 await carrier.await();
12299 const mount = mountedTrees.get(config);
12300 if (!mount || carrier.state !== FiberState.ACTIVE) throw new Error("reviewed composition carrier did not activate");
12301 return { tree: mount.tree, dispose };
12302 } catch (error) {
12303 await dispose().catch(() => void 0);
12304 throw error;
12305 }
12306 }
12307 function leakedServices(ctx, mount) {
12308 const rootIsolate = ctx.root[Context.isolate];
12309 const leaked = [];
12310 for (const key of Object.getOwnPropertySymbols(ctx.reflect.store)) {
12311 const impl = ctx.reflect.store[key];
12312 if (impl === void 0) continue;
12313 let current2 = impl.fiber;
12314 while (current2 !== mount && current2.parent.fiber !== current2) current2 = current2.parent.fiber;
12315 if (current2 === mount && rootIsolate[impl.name] === key) leaked.push(impl.name);
12316 }
12317 return leaked.sort((left, right) => left.localeCompare(right));
12318 }
12319 async function mountReviewedPreset(ctx, baseUrl, spec, catalog, selected) {
12320 if (!selected) throw new Error("agent-presets: explicit selection is required when no default is configured");
12321 const entries = structuredClone(reviewComposition(spec).entries);
12322 let found = 0;
12323 function prepare(rows) {
12324 for (const row of rows) {
12325 if (row.group === true || row.name === "cordis:group" || row.name === "@deepseek-ai/cordis-plugin-group") {
12326 prepare(row.config);
12327 } else if (row.name === AGENT_PRESETS) {
12328 found++;
12329 row.isolate = { ...row.isolate, agentPresets: true };
12330 row.config = { codewhale_reviewed: { catalog, selected, base_url: baseUrl } };
12331 }
12332 }
12333 }
12334 prepare(entries);
12335 if (found !== 1) throw new Error("exactly one raw roster row is required for a selected preset");
12336 const source = JSON.stringify([{ insert: entries }]);
12337 const top = await mountReviewedComposition(ctx, baseUrl, { ...spec, layers: [{ path: "selected-preset.json", sha256: digest(source), source }] });
12338 try {
12339 const entry = [...top.tree.entries()].find((entry2) => entry2.options.name === AGENT_PRESETS && !entry2.disabled);
12340 const roster = entry?.ctx.get("agentPresets");
12341 if (!roster) throw new Error("selected raw roster did not become active");
12342 await roster.mountSelected();
12343 return top;
12344 } catch (error) {
12345 await top.dispose();
12346 throw error;
12347 }
12348 }
12349 var MAX_LAYERS, MAX_SOURCE_BYTES, MAX_DATA_BYTES, MAX_DATA_NODES, MAX_ROWS, MAX_DEPTH, SHA256, UNSUPPORTED_ROWS, ReviewedGroup, ReviewedLoader, loaders, ReviewedTree, mountedTrees, ReviewedCarrier;
12350 var init_composition = __esm({
12351 "src/dsh/composition.ts"() {
12352 "use strict";
12353 init_lib2();
12354 init_fiber_state();
12355 init_src();
12356 init_src2();
12357 init_js_yaml();
12358 init_mcp2();
12359 init_skill_filesystem();
12360 init_shell_hooks();
12361 init_resolve_hooks();
12362 init_persona();
12363 init_agent_presets();
12364 MAX_LAYERS = 64;
12365 MAX_SOURCE_BYTES = 1024 * 1024;
12366 MAX_DATA_BYTES = 4 * 1024 * 1024;
12367 MAX_DATA_NODES = 1e5;
12368 MAX_ROWS = 1024;
12369 MAX_DEPTH = 32;
12370 SHA256 = /^[a-f0-9]{64}$/;
12371 UNSUPPORTED_ROWS = /* @__PURE__ */ new Map();
12372 ReviewedGroup = class extends Group {
12373 static inject = ["loader"];
12374 };
12375 ReviewedLoader = class extends Loader {
12376 constructor(ctx, config) {
12377 super(ctx, config);
12378 this.builtins.group = ReviewedGroup;
12379 }
12380 };
12381 loaders = /* @__PURE__ */ new WeakMap();
12382 ReviewedTree = class extends EntryTree {
12383 base;
12384 modules;
12385 spec;
12386 constructor(ctx, base, spec) {
12387 super(ctx);
12388 this.base = base;
12389 this.spec = spec;
12390 const modules = /* @__PURE__ */ new Map();
12391 if (!Array.isArray(spec.modules) || spec.modules.length > MAX_ROWS || !spec.files || Object.keys(spec.files).length > 4096) throw new Error("invalid reviewed module closure");
12392 for (const module of spec.modules) {
12393 if (!module || typeof module.name !== "string" || module.name.length === 0 || module.name.length > 4096 || modules.has(module.name) || !plainRelative(module.path) || !SHA256.test(module.sha256) || spec.files[module.path] !== module.sha256) throw new Error("module map differs from reviewed closure");
12394 modules.set(module.name, module);
12395 }
12396 this.modules = modules;
12397 }
12398 /** A reviewed composition is input; teardown and self-disposal never rewrite it. */
12399 write() {
12400 }
12401 import(name) {
12402 if (name === PERSONA) return reviewedPersonaModule;
12403 if (name === AGENT_PRESETS) return defineReviewedAgentPresets(mountReviewedComposition);
12404 if (name === "cordis:group" || name === "@deepseek-ai/cordis-plugin-group") return ReviewedGroup;
12405 if (name === "@deepseek-ai/dsh-mcp-client") return reviewedMcpModule();
12406 if (name === "@deepseek-ai/dsh-skill-filesystem") return reviewedSkillModule();
12407 if (name === "@deepseek-ai/dsh-hooks-claude-code") return reviewedHookModule("claude-code", fileURLToPath3(this.base), this.spec.files);
12408 if (name === "@deepseek-ai/dsh-hooks-codex") return reviewedHookModule("codex", fileURLToPath3(this.base), this.spec.files);
12409 if (UNSUPPORTED_ROWS.has(name)) throw new Error(`${name}: ${UNSUPPORTED_ROWS.get(name)}`);
12410 const module = this.modules.get(name);
12411 if (!module) throw new Error(`row requires ${JSON.stringify(name)}, absent from the reviewed module closure`);
12412 return this.importReviewed(module);
12413 }
12414 async importReviewed(module) {
12415 const root = fileURLToPath3(this.base);
12416 const path = resolve3(root, module.path);
12417 const inside = relative2(root, path);
12418 if (inside.startsWith(`..${sep2}`) || inside === ".." || isAbsolute3(inside)) throw new Error("module escapes reviewed bundle");
12419 if (this.spec.files[module.path] !== module.sha256 || digest(await readFile2(path)) !== module.sha256) throw new Error("module changed after review");
12420 return importReviewedModule(this.base, module.path);
12421 }
12422 };
12423 mountedTrees = /* @__PURE__ */ new WeakMap();
12424 ReviewedCarrier = class {
12425 constructor(ctx, config) {
12426 this.ctx = ctx;
12427 this.config = config;
12428 this.tree = new ReviewedTree(ctx, config.baseUrl, config.spec);
12429 mountedTrees.set(config, { tree: this.tree, dispose: () => this.dispose() });
12430 }
12431 ctx;
12432 config;
12433 static inject = ["loader"];
12434 tree;
12435 disposed = false;
12436 async dispose() {
12437 if (this.disposed) return;
12438 this.disposed = true;
12439 const fibers = [...new Set([...this.tree.entries()].map((entry) => entry.fiber).filter((fiber) => fiber !== void 0))].reverse();
12440 const pending = this.tree.getTasks();
12441 let stopError;
12442 try {
12443 this.tree.root.stop();
12444 } catch (error) {
12445 stopError = error;
12446 }
12447 const outcomes = await Promise.allSettled([
12448 ...pending,
12449 ...fibers.map((fiber) => Promise.resolve().then(() => fiber.dispose()))
12450 ]);
12451 try {
12452 await this.tree.await();
12453 if (stopError !== void 0) throw stopError;
12454 const failed = outcomes.find((outcome) => outcome.status === "rejected");
12455 if (failed) throw failed.reason;
12456 } finally {
12457 this.config.releaseClosure();
12458 }
12459 }
12460 async *[Service.init]() {
12461 yield () => this.dispose();
12462 await this.tree.root.update(this.config.review.entries);
12463 await this.tree.await();
12464 validateInventory(this.tree.root);
12465 for (const entry of this.tree.entries()) {
12466 if (entry.disabled) continue;
12467 if (!entry.fiber || entry.fiber.uid === null) throw new Error(`composition row ${JSON.stringify(entry.options.id ?? entry.options.name)} failed activation`);
12468 await entry.fiber.await();
12469 const missing = Object.keys(entry.fiber.inject).filter((name) => entry.fiber.ctx.get(name) === void 0);
12470 if (missing.length || entry.fiber.state !== FiberState.ACTIVE) throw new Error(`composition row ${JSON.stringify(entry.options.id ?? entry.options.name)} is not active`);
12471 }
12472 const leaked = leakedServices(this.ctx, this.ctx.fiber);
12473 if (leaked.length) throw new Error(`composition published shared-root services: ${leaked.join(", ")}`);
12474 }
12475 };
12476 }
12477 });
12478
12479 // src/protocol.generated.ts
12480 var MAGIC_ASCII;
12481 var init_protocol_generated = __esm({
12482 "src/protocol.generated.ts"() {
12483 "use strict";
12484 MAGIC_ASCII = "CWX1";
12485 }
12486 });
12487
12488 // src/protocol.ts
12489 var MAGIC;
12490 var init_protocol = __esm({
12491 "src/protocol.ts"() {
12492 "use strict";
12493 init_protocol_generated();
12494 init_protocol_generated();
12495 MAGIC = Buffer.from(MAGIC_ASCII, "ascii");
12496 }
12497 });
12498
12499 // src/rpc.ts
12500 var init_rpc = __esm({
12501 "src/rpc.ts"() {
12502 "use strict";
12503 init_protocol();
12504 }
12505 });
12506
12507 // src/shims/core.ts
12508 var init_core = __esm({
12509 "src/shims/core.ts"() {
12510 "use strict";
12511 init_protocol();
12512 init_json();
12513 init_rpc();
12514 }
12515 });
12516
12517 // src/shims/shell-hooks.ts
12518 var init_shell_hooks2 = __esm({
12519 "src/shims/shell-hooks.ts"() {
12520 "use strict";
12521 }
12522 });
12523
12524 // src/shims/hooks.ts
12525 var init_hooks = __esm({
12526 "src/shims/hooks.ts"() {
12527 "use strict";
12528 init_json();
12529 }
12530 });
12531
12532 // src/shims/storage.ts
12533 var STORAGE_LIMITS, MAX_RECORD_BYTES;
12534 var init_storage = __esm({
12535 "src/shims/storage.ts"() {
12536 "use strict";
12537 init_json();
12538 STORAGE_LIMITS = Object.freeze({ keyBytes: 128, valueBytes: 128 * 1024, totalBytes: 4 * 1024 * 1024, keys: 1024 });
12539 MAX_RECORD_BYTES = STORAGE_LIMITS.valueBytes + STORAGE_LIMITS.keyBytes * 6 + 128;
12540 }
12541 });
12542
12543 // src/tier.ts
12544 var init_tier = __esm({
12545 "src/tier.ts"() {
12546 "use strict";
12547 }
12548 });
12549
12550 // src/shims/commands.ts
12551 var NO_ATTACHMENTS;
12552 var init_commands = __esm({
12553 "src/shims/commands.ts"() {
12554 "use strict";
12555 NO_ATTACHMENTS = Object.freeze([]);
12556 }
12557 });
12558
12559 // src/root.ts
12560 import { AsyncLocalStorage } from "node:async_hooks";
12561 var ownerStorage;
12562 var init_root = __esm({
12563 "src/root.ts"() {
12564 "use strict";
12565 init_composition();
12566 init_protocol();
12567 init_rpc();
12568 init_resolve_hooks();
12569 init_json();
12570 init_core();
12571 init_owned();
12572 init_shell_hooks2();
12573 init_hooks();
12574 init_prompt();
12575 init_storage();
12576 init_mcp();
12577 init_skills();
12578 init_tier();
12579 init_commands();
12580 ownerStorage = new AsyncLocalStorage();
12581 }
12582 });
12583
12584 // src/dsh/persona.ts
12585 function normalizePersonaConfig(value) {
12586 if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("persona config must be plain data");
12587 const config = value;
12588 if (Object.keys(config).some((key) => !["prefix", "suffix", "complete", "includeRuntimeContext"].includes(key))) throw new TypeError("persona config has an unsupported field");
12589 if (config.complete !== void 0 && config.complete !== false) throw new TypeError("persona replacement belongs to the Core prompt and cannot be imported");
12590 if (config.includeRuntimeContext !== void 0 && config.includeRuntimeContext !== true) throw new TypeError("persona runtime-context suppression belongs to the Core prompt and cannot be imported");
12591 if (typeof config.prefix !== "string" || config.suffix !== void 0 && typeof config.suffix !== "string") throw new TypeError("persona prefix and suffix must be text");
12592 const result = { prefix: config.prefix, suffix: config.suffix ?? "" };
12593 for (const [position, text2] of Object.entries(result)) {
12594 if (Buffer.byteLength(text2, "utf8") > MAX_PROMPT_SECTION_BYTES) throw new RangeError("persona text exceeds 4096 UTF-8 bytes");
12595 if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(text2)) throw new TypeError("persona text contains control characters");
12596 validatePromptTemplate(text2);
12597 if (text2.trim().length > 0) normalizePromptSection({ id: `persona-${position}`, text: text2, interpolate: "model-cwd" });
12598 }
12599 return Object.freeze(result);
12600 }
12601 var PERSONA, reviewedPersonaModule;
12602 var init_persona = __esm({
12603 "src/dsh/persona.ts"() {
12604 "use strict";
12605 init_prompt();
12606 init_root();
12607 PERSONA = "@deepseek-ai/dsh-persona";
12608 reviewedPersonaModule = Object.freeze({
12609 name: "persona",
12610 inject: ["prompt"],
12611 apply(ctx, value) {
12612 if (!ownerStorage.getStore()?.scope) throw new Error("persona requires an exact Core-selected entry scope");
12613 const config = normalizePersonaConfig(value);
12614 for (const [position, text2] of Object.entries(config)) {
12615 if (text2.trim().length > 0) ctx.prompt.registerSection({ id: `persona-${position}`, text: text2, interpolate: "model-cwd" });
12616 }
12617 }
12618 });
12619 }
12620 });
12621
12622 // src/dsh/upstream/agent-presets/metadata.ts
12623 import { join } from "node:path";
12624 function text(value) {
12625 if (typeof value !== "string") return void 0;
12626 const trimmed = value.trim();
12627 return trimmed === "" ? void 0 : trimmed;
12628 }
12629 async function readPresetMetadata(directory, readFile3) {
12630 let raw;
12631 try {
12632 raw = await readFile3(join(directory, METADATA_FILE), "utf8");
12633 } catch {
12634 return {};
12635 }
12636 let parsed;
12637 try {
12638 parsed = yaml.load(raw);
12639 } catch {
12640 return {};
12641 }
12642 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
12643 const record = parsed;
12644 const name = text(record.name);
12645 const description = text(record.description);
12646 const order = typeof record.order === "number" && Number.isFinite(record.order) ? record.order : void 0;
12647 return {
12648 ...name === void 0 ? {} : { name },
12649 ...description === void 0 ? {} : { description },
12650 ...order === void 0 ? {} : { order }
12651 };
12652 }
12653 var METADATA_FILE;
12654 var init_metadata = __esm({
12655 "src/dsh/upstream/agent-presets/metadata.ts"() {
12656 "use strict";
12657 init_js_yaml();
12658 METADATA_FILE = "preset.yml";
12659 }
12660 });
12661
12662 // src/dsh/upstream/agent-presets/preset.ts
12663 var PRESET_ID;
12664 var init_preset = __esm({
12665 "src/dsh/upstream/agent-presets/preset.ts"() {
12666 "use strict";
12667 PRESET_ID = /^[a-z0-9][a-z0-9-]*$/;
12668 }
12669 });
12670
12671 // src/dsh/upstream/agent-presets/specifier.ts
12672 import { isAbsolute as isAbsolute4 } from "node:path";
12673 import { pathToFileURL as pathToFileURL3 } from "node:url";
12674 function classifyRowSpecifier(name) {
12675 if (name.startsWith("cordis:")) return { kind: "builtin", specifier: name };
12676 if (name.startsWith(".")) return { kind: "preset", specifier: name };
12677 if (name.startsWith("file:")) return { kind: "file", specifier: name };
12678 if (isAbsolute4(name)) return { kind: "file", specifier: pathToFileURL3(name).href };
12679 return { kind: "package", specifier: name };
12680 }
12681 var init_specifier = __esm({
12682 "src/dsh/upstream/agent-presets/specifier.ts"() {
12683 "use strict";
12684 }
12685 });
12686
12687 // src/dsh/upstream/agent-presets/discovery.ts
12688 import { isBuiltin as isBuiltin2 } from "node:module";
12689 import { join as join2, resolve as resolve4 } from "node:path";
12690 import { fileURLToPath as fileURLToPath4, pathToFileURL as pathToFileURL4 } from "node:url";
12691 function entryListProblem(rows, at2 = "") {
12692 if (!Array.isArray(rows)) {
12693 return at2 === "" ? "the composition must be a top-level list of plugin rows" : `group ${at2} must hold a list of plugin rows`;
12694 }
12695 for (const [index, row] of rows.entries()) {
12696 const label = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
12697 if (typeof row !== "object" || row === null || Array.isArray(row)) {
12698 return `${label} is not a plugin row (expected a map with a "name")`;
12699 }
12700 const { name, group, config } = row;
12701 if (typeof name !== "string" || name === "") {
12702 return `${label} names no plugin (a "name" string is required)`;
12703 }
12704 if (group === true) {
12705 const nested = entryListProblem(config, label);
12706 if (nested !== void 0) return nested;
12707 }
12708 }
12709 return void 0;
12710 }
12711 async function rowResolves(row, presetBase, harnessBase, resolves, io) {
12712 if (row.kind === "builtin") return true;
12713 if (row.kind === "package") return isBuiltin2(row.specifier) || resolves(row.specifier, harnessBase);
12714 const url = row.kind === "file" ? new URL(row.specifier) : new URL(row.specifier, presetBase);
12715 return await isFile(fileURLToPath4(url), io);
12716 }
12717 async function unresolvableRows(rows, presetBase, harnessBase, resolves, io, at2 = "") {
12718 const found = [];
12719 for (const [index, entry] of rows.entries()) {
12720 const row = entry;
12721 if (Boolean(row.disabled)) continue;
12722 const positional = at2 === "" ? `row ${String(index + 1)}` : `${at2} row ${String(index + 1)}`;
12723 if (row.group === true) {
12724 found.push(...await unresolvableRows(row.config, presetBase, harnessBase, resolves, io, positional));
12725 continue;
12726 }
12727 if (await rowResolves(classifyRowSpecifier(row.name), presetBase, harnessBase, resolves, io)) continue;
12728 const label = typeof row.id === "string" && row.id !== "" ? `row "${row.id}"` : positional;
12729 found.push({ label, name: row.name });
12730 }
12731 return found;
12732 }
12733 async function compositionProblem(path, harnessBase, resolves, io) {
12734 let content;
12735 try {
12736 content = await io.readFile(path, "utf8");
12737 } catch {
12738 return `the composition file ${COMPOSITION_FILE} cannot be read`;
12739 }
12740 let rows;
12741 try {
12742 rows = load(content, { schema: entryListSchema });
12743 } catch (error) {
12744 const full = error instanceof Error ? error.message : String(error);
12745 return `the composition is not valid YAML: ${full.replace(/\n[\s\S]*$/, "")}`;
12746 }
12747 const shape = entryListProblem(rows);
12748 if (shape !== void 0) return shape;
12749 const presetBase = new URL(".", pathToFileURL4(path)).href;
12750 let unresolvable;
12751 try {
12752 unresolvable = await unresolvableRows(rows, presetBase, harnessBase, resolves, io);
12753 } catch (error) {
12754 const full = error instanceof Error ? error.message : String(error);
12755 return `the composition's plugins cannot be checked: ${full.replace(/\n[\s\S]*$/, "")}`;
12756 }
12757 const [first] = unresolvable;
12758 if (first === void 0) return void 0;
12759 if (unresolvable.length === 1) {
12760 return `${first.label} names a plugin that cannot be resolved: ${first.name}`;
12761 }
12762 return `${String(unresolvable.length)} rows name plugins that cannot be resolved:
12763 ` + unresolvable.map((row) => `- ${row.label}: ${row.name}`).join("\n");
12764 }
12765 async function isFile(path, io) {
12766 try {
12767 return (await io.stat(path)).isFile();
12768 } catch {
12769 return false;
12770 }
12771 }
12772 async function scanRoot(root, harnessBase, resolves, io) {
12773 const dir = resolve4(root.path);
12774 let children;
12775 try {
12776 children = await io.readdir(dir, { withFileTypes: true });
12777 } catch (error) {
12778 if (error.code === "ENOENT") return [];
12779 throw new Error(`agent-presets: cannot read preset root ${dir}: ${String(error)}`, { cause: error });
12780 }
12781 const found = [];
12782 for (const child of children) {
12783 if (!child.isDirectory() || !PRESET_ID.test(child.name)) continue;
12784 const directory = join2(dir, child.name);
12785 const path = join2(directory, COMPOSITION_FILE);
12786 const broken = await isFile(path, io) ? await compositionProblem(path, harnessBase, resolves, io) : `the composition file ${COMPOSITION_FILE} is missing — the directory still occupies the id; delete it or restore the file`;
12787 const metadata = await readPresetMetadata(directory, io.readFile);
12788 found.push({
12789 id: child.name,
12790 trust: root.trust,
12791 path,
12792 ...metadata,
12793 ...broken === void 0 ? {} : { broken }
12794 });
12795 }
12796 return found.sort((left, right) => {
12797 const leftOrder = left.order ?? Number.POSITIVE_INFINITY;
12798 const rightOrder = right.order ?? Number.POSITIVE_INFINITY;
12799 const byOrder = leftOrder === rightOrder ? 0 : leftOrder - rightOrder;
12800 return byOrder === 0 ? left.id.localeCompare(right.id) : byOrder;
12801 });
12802 }
12803 async function discoverPresets(roots, harnessBase, resolves, io) {
12804 const byId = /* @__PURE__ */ new Map();
12805 for (const root of roots) {
12806 for (const preset of await scanRoot(root, harnessBase, resolves, io)) {
12807 if (byId.has(preset.id)) continue;
12808 byId.set(preset.id, preset);
12809 }
12810 }
12811 return [...byId.values()];
12812 }
12813 var COMPOSITION_FILE, SHIPPED_PRESET_ROOT;
12814 var init_discovery = __esm({
12815 "src/dsh/upstream/agent-presets/discovery.ts"() {
12816 "use strict";
12817 init_js_yaml();
12818 init_src2();
12819 init_metadata();
12820 init_preset();
12821 init_specifier();
12822 COMPOSITION_FILE = "agent.cordis.yml";
12823 SHIPPED_PRESET_ROOT = fileURLToPath4(new URL("../presets/", import.meta.url));
12824 }
12825 });
12826
12827 // src/dsh/upstream/agent-presets/composition-inventory.ts
12828 function disabledContribution(value, evaluateExpression) {
12829 if (isJsExpr(value)) {
12830 try {
12831 return Boolean(evaluateExpression(value.__jsExpr));
12832 } catch {
12833 return "conditional";
12834 }
12835 }
12836 return Boolean(value);
12837 }
12838 function combineDisabled(outer, own) {
12839 if (outer === true || own === true) return true;
12840 if (outer === "conditional" || own === "conditional") return "conditional";
12841 return false;
12842 }
12843 function flattenRows(rows, outerDisabled, evaluateExpression, found) {
12844 for (const value of rows) {
12845 const row = value;
12846 const disabled = combineDisabled(outerDisabled, disabledContribution(row.disabled, evaluateExpression));
12847 if (row.group === true) {
12848 flattenRows(row.config, disabled, evaluateExpression, found);
12849 continue;
12850 }
12851 found.push({
12852 entryId: typeof row.id === "string" && row.id !== "" ? row.id : null,
12853 moduleName: row.name,
12854 enabled: disabled === true ? false : disabled === "conditional" ? "conditional" : true,
12855 ...isJsExpr(row.disabled) ? { condition: row.disabled.__jsExpr } : {}
12856 });
12857 }
12858 }
12859 async function fileComposition(path, evaluateExpression, readFile3) {
12860 let rows;
12861 try {
12862 rows = load(await readFile3(path, "utf8"), { schema: entryListSchema });
12863 } catch (error) {
12864 return { broken: error instanceof Error ? error.message : String(error) };
12865 }
12866 const problem = entryListProblem(rows);
12867 if (problem !== void 0) return { broken: problem };
12868 const found = [];
12869 flattenRows(rows, false, evaluateExpression, found);
12870 return { rows: found };
12871 }
12872 function mountedCompositionRows(tree) {
12873 const found = [];
12874 for (const entry of tree.entries()) {
12875 if (entry.options.group) continue;
12876 found.push({
12877 entryId: entry.id,
12878 moduleName: entry.options.name,
12879 enabled: !entry.disabled,
12880 ...isJsExpr(entry.options.disabled) ? { condition: entry.options.disabled.__jsExpr } : {},
12881 ...entry.fiber === void 0 ? {} : { fiberState: entry.fiber.state }
12882 });
12883 }
12884 return found;
12885 }
12886 var init_composition_inventory = __esm({
12887 "src/dsh/upstream/agent-presets/composition-inventory.ts"() {
12888 "use strict";
12889 init_js_yaml();
12890 init_src();
12891 init_src2();
12892 init_discovery();
12893 }
12894 });
12895
12896 // src/dsh/agent-presets.ts
12897 import { createHash as createHash3 } from "node:crypto";
12898 import { resolve as resolve5, relative as relative3, dirname as dirname3, sep as sep3 } from "node:path";
12899 import { fileURLToPath as fileURLToPath5, pathToFileURL as pathToFileURL5 } from "node:url";
12900 function plain(path) {
12901 return typeof path === "string" && path.length > 0 && path.length <= 4096 && !/[\\:\u0000-\u001f\u007f]/u.test(path) && !path.startsWith("/") && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
12902 }
12903 function fail(message) {
12904 throw new Error(`agent-presets: ${message}`);
12905 }
12906 function containedPackageModule(name, documents, files) {
12907 if (!name || /[\\:\u0000-\u0020\u007f]/u.test(name)) return;
12908 const parts = name.split("/");
12909 const n = name.startsWith("@") ? 2 : 1;
12910 if (parts.length < n || parts.some((p) => !p || p === "." || p === "..")) return;
12911 const pkg = parts.slice(0, n).join("/");
12912 const packageRoot = `node_modules/${pkg}`;
12913 const source = documents.get(`${packageRoot}/package.json`);
12914 if (source === void 0) return;
12915 let data2;
12916 try {
12917 data2 = JSON.parse(source);
12918 } catch {
12919 return;
12920 }
12921 if (data2.name !== pkg || data2.type !== "module") return;
12922 const subpath = parts.length === n ? "." : `./${parts.slice(n).join("/")}`;
12923 const refused = /* @__PURE__ */ Symbol("unsupported package target");
12924 function target(value) {
12925 if (typeof value === "string") return value;
12926 if (!value || Array.isArray(value) || typeof value !== "object") return refused;
12927 for (const [condition, child] of Object.entries(value)) {
12928 if (["node", "import", "default"].includes(condition)) {
12929 const picked = target(child);
12930 if (picked !== void 0) return picked;
12931 }
12932 }
12933 }
12934 let entry;
12935 if (data2.exports !== void 0) {
12936 const value = data2.exports;
12937 entry = value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).some((k) => k.startsWith(".")) ? target(value[subpath]) : subpath === "." ? target(value) : void 0;
12938 } else if (subpath === ".") entry = typeof data2.main === "string" ? data2.main : "./index.js";
12939 else entry = subpath;
12940 if (typeof entry !== "string" || !entry.startsWith("./") || !plain(entry.slice(2))) return;
12941 const path = `${packageRoot}/${entry.slice(2)}`;
12942 if (!/\.(mjs|js|mts)$/.test(path) || !SHA.test(files[path] ?? "")) return;
12943 return { name, path, sha256: files[path] };
12944 }
12945 async function reviewAgentPresets(input) {
12946 const { composition } = input;
12947 const files = composition.files;
12948 if (!files || Object.keys(files).length > 4096 || !Array.isArray(input.directories) || input.directories.length > 4096) fail("invalid source inventory");
12949 const base = resolve5("codewhale-reviewed-agent-presets");
12950 const baseUrl = pathToFileURL5(`${base}${sep3}`).href;
12951 function key(path) {
12952 const inside = relative3(base, path).split(sep3).join("/");
12953 if (!plain(inside)) fail("path escapes the admitted source root");
12954 return inside;
12955 }
12956 const documents = /* @__PURE__ */ new Map();
12957 let bytes = 0;
12958 for (const doc of input.documents) {
12959 if (!plain(doc.path) || !SHA.test(doc.sha256) || files[doc.path] !== doc.sha256 || hash(doc.source) !== doc.sha256 || documents.has(doc.path)) fail("document changed or is outside the source receipt");
12960 bytes += Buffer.byteLength(doc.source);
12961 if (Buffer.byteLength(doc.source) > 1024 * 1024 || bytes > 4 * 1024 * 1024) fail("documents exceed their bound");
12962 documents.set(doc.path, doc.source);
12963 }
12964 const directories = new Set(input.directories);
12965 for (const path of directories) if (!plain(path)) fail("invalid source directory");
12966 for (const path of Object.keys(files)) if (!plain(path) || !SHA.test(files[path])) fail("invalid source file receipt");
12967 const invalid = /* @__PURE__ */ new Set();
12968 const parsed = /* @__PURE__ */ new Map();
12969 const io = {
12970 async readFile(path) {
12971 const relative4 = key(path);
12972 if (invalid.has(relative4)) throw new Error("composition exceeds its data/shape bound");
12973 const text2 = documents.get(relative4);
12974 if (text2 === void 0) throw new Error("document not admitted");
12975 return text2;
12976 },
12977 async stat(path) {
12978 return { isFile: () => Object.hasOwn(files, key(path)) };
12979 },
12980 async readdir(path) {
12981 const prefix = `${key(path)}/`;
12982 if (!directories.has(prefix.slice(0, -1))) {
12983 const e = new Error("missing root");
12984 Object.assign(e, { code: "ENOENT" });
12985 throw e;
12986 }
12987 return [...directories].filter((p) => p.startsWith(prefix) && !p.slice(prefix.length).includes("/")).map((p) => ({ name: p.slice(prefix.length), isDirectory: () => true }));
12988 }
12989 };
12990 const { reviewComposition: reviewComposition2, parsePresetComposition: parsePresetComposition2, compositionRowProblem: compositionRowProblem2, hasReviewedRowBridge: hasReviewedRowBridge2 } = await Promise.resolve().then(() => (init_composition(), composition_exports));
12991 for (const [path, source] of documents) {
12992 if (!path.endsWith("/agent.cordis.yml")) continue;
12993 try {
12994 parsed.set(path, parsePresetComposition2(source));
12995 } catch {
12996 invalid.add(path);
12997 }
12998 }
12999 const top = reviewComposition2(composition);
13000 const rosterRows = [];
13001 function visit(rows2) {
13002 for (const row of rows2) {
13003 if (row.group === true || row.name === "cordis:group" || row.name === "@deepseek-ai/cordis-plugin-group") visit(row.config ?? []);
13004 else if (row.name === AGENT_PRESETS) rosterRows.push(row);
13005 }
13006 }
13007 visit(top.entries);
13008 if (rosterRows.length !== 1) fail("exactly one raw roster row is required");
13009 const config = rosterRows[0].config ?? {};
13010 if (!config || Array.isArray(config) || typeof config !== "object" || Object.keys(config).some((k) => !["default", "roots", "includeShippedRoot", "includeUserRoot"].includes(k))) fail("roster configuration must be literal upstream fields");
13011 for (const k of ["includeShippedRoot", "includeUserRoot"]) if (config[k] !== void 0 && typeof config[k] !== "boolean") fail("root gates must be literal booleans");
13012 if (config.default !== void 0 && (typeof config.default !== "string" || !PRESET_ID.test(config.default) || config.default.length > 64)) fail("invalid default id");
13013 const roots = [];
13014 if (config.includeShippedRoot !== false) {
13015 const candidates = [...documents.entries()].filter(([p, text2]) => {
13016 if (p !== "package.json" && !p.endsWith("/package.json")) return false;
13017 try {
13018 return JSON.parse(text2).name === AGENT_PRESETS;
13019 } catch {
13020 return false;
13021 }
13022 });
13023 if (candidates.length !== 1) fail("shipped root requires exactly one admitted agent-presets package");
13024 const folder = dirname3(candidates[0][0]).split(sep3).join("/");
13025 const root = folder === "." ? "presets" : `${folder}/presets`;
13026 if (!directories.has(root)) fail("shipped preset root was not admitted");
13027 roots.push({ path: resolve5(base, root), trust: "system" });
13028 }
13029 if (config.roots !== void 0 && !Array.isArray(config.roots)) fail("roots must be a literal list");
13030 for (const root of config.roots ?? []) {
13031 if (!root || Object.keys(root).some((k) => !["path", "trust"].includes(k)) || !plain(root.path) || !["system", "user"].includes(root.trust)) fail("configured roots must stay inside the admitted package");
13032 if (!directories.has(root.path)) fail("configured preset root was not admitted");
13033 roots.push({ path: resolve5(base, root.path), trust: root.trust });
13034 }
13035 if (config.includeUserRoot !== false) {
13036 if (!directories.has(".agent-presets")) fail("user root requires an admitted .agent-presets tree; ambient home discovery is refused");
13037 roots.push({ path: resolve5(base, ".agent-presets"), trust: "user" });
13038 }
13039 if (roots.length > 64) fail("too many roots");
13040 const declared = new Map(composition.modules.map((m) => [m.name, m]));
13041 if (declared.size !== composition.modules.length) fail("duplicate module name receipt");
13042 const found = await discoverPresets(roots, baseUrl, (name) => hasReviewedRowBridge2(name) || declared.has(name) || containedPackageModule(name, documents, files) !== void 0, io);
13043 if (found.length > MAX_PRESETS) fail("too many presets");
13044 const prepared = [];
13045 const rows = [];
13046 const inventory = /* @__PURE__ */ Object.create(null);
13047 for (const preset of found) {
13048 let resolveRows2 = function(children) {
13049 for (const row of children) {
13050 if (Boolean(row.disabled) && !isJsExpr(row.disabled)) continue;
13051 if (row.group === true || row.name === "cordis:group" || row.name === "@deepseek-ai/cordis-plugin-group") {
13052 resolveRows2(row.config ?? []);
13053 continue;
13054 }
13055 const specifier = classifyRowSpecifier(row.name);
13056 if (row.name === PERSONA) normalizePersonaConfig(row.config);
13057 if (specifier.kind === "builtin" || hasReviewedRowBridge2(row.name)) continue;
13058 if (row.name === AGENT_PRESETS) fail("nested roster cannot create a second selection authority");
13059 const problem = compositionRowProblem2(row.name);
13060 if (problem) fail(problem);
13061 let receipt;
13062 if (specifier.kind === "package") receipt = declared.get(row.name) ?? containedPackageModule(row.name, documents, files);
13063 else {
13064 const url = specifier.kind === "file" ? new URL(specifier.specifier) : new URL(specifier.specifier, pathToFileURL5(preset.path).href);
13065 const path2 = key(fileURLToPath5(url));
13066 if (files[path2] !== void 0) receipt = { name: row.name, path: path2, sha256: files[path2] };
13067 }
13068 if (!receipt || files[receipt.path] !== receipt.sha256) {
13069 if (isJsExpr(row.disabled)) continue;
13070 fail("row module has no exact admitted receipt");
13071 }
13072 modules.set(row.name, receipt);
13073 }
13074 };
13075 var resolveRows = resolveRows2;
13076 if (preset.id.length > 64 || (preset.name?.length ?? 0) > 1024 || (preset.description?.length ?? 0) > 4096) fail("preset metadata exceeds its bound");
13077 const metadata = {
13078 id: preset.id,
13079 trust: preset.trust,
13080 is_default: preset.id === config.default,
13081 ...preset.name === void 0 ? {} : { name: preset.name },
13082 ...preset.description === void 0 ? {} : { description: preset.description },
13083 ...preset.order === void 0 ? {} : { order: preset.order },
13084 ...preset.broken === void 0 ? {} : { broken: preset.broken }
13085 };
13086 rows.push(metadata);
13087 const path = key(preset.path);
13088 inventory[preset.id] = { path, ...preset.broken !== void 0 ? { broken: preset.broken } : await fileComposition(preset.path, () => {
13089 throw new Error("conditional until mounted");
13090 }, io.readFile) };
13091 if (preset.broken !== void 0) continue;
13092 const source = await io.readFile(preset.path, "utf8");
13093 const entries = parsed.get(key(preset.path));
13094 const modules = /* @__PURE__ */ new Map();
13095 try {
13096 resolveRows2(entries);
13097 } catch (error) {
13098 metadata.broken = error instanceof Error ? error.message : "preset preparation refused";
13099 continue;
13100 }
13101 const layer = JSON.stringify([{ insert: entries }]);
13102 const spec = { version: 1, layers: [{ path: key(preset.path), sha256: hash(layer), source: layer }], modules: [...modules.values()], files };
13103 reviewComposition2(spec);
13104 prepared.push({ metadata, composition: spec, source });
13105 }
13106 if (config.default !== void 0 && !prepared.some((p) => p.metadata.id === config.default)) fail("default preset is missing or broken");
13107 if (!prepared.length) fail("no admitted usable preset");
13108 if (Buffer.byteLength(JSON.stringify(inventory)) > 4 * 1024 * 1024) fail("composition inventory exceeds its bound");
13109 return { catalog: { version: 1, ...config.default === void 0 ? {} : { default: config.default }, mode_selection_enabled: true, presets: rows, inventory }, presets: prepared };
13110 }
13111 function defineReviewedAgentPresets(mount) {
13112 return class ReviewedAgentPresets extends Service {
13113 static inject = ["loader"];
13114 snapshot;
13115 selfCtx;
13116 constructor(ctx, config) {
13117 super(ctx, "agentPresets");
13118 this.selfCtx = ctx;
13119 const snapshot = config?.codewhale_reviewed;
13120 if (!snapshot || snapshot.catalog?.version !== 1 || !snapshot.catalog.presets.some((p) => p.id === snapshot.selected?.metadata.id && !p.broken)) fail("raw roster needs an installer-minted preset receipt");
13121 this.snapshot = structuredClone(snapshot);
13122 }
13123 mounting;
13124 mounted;
13125 mountSelected() {
13126 return this.mounting ??= mount(this.selfCtx, this.snapshot.base_url, this.snapshot.selected.composition).then((result) => this.mounted = result);
13127 }
13128 async list() {
13129 return this.snapshot.catalog.presets.map((row) => ({ ...structuredClone(row), path: fileURLToPath5(new URL(this.snapshot.catalog.inventory[row.id].path, this.snapshot.base_url)) }));
13130 }
13131 async remoteExportList() {
13132 return { presets: this.snapshot.catalog.presets.map(({ is_default, entry, ...row }) => ({ ...structuredClone(row), isDefault: is_default })), authorable: false, defaultId: this.defaultId, modeSelectionEnabled: this.snapshot.catalog.mode_selection_enabled };
13133 }
13134 get defaultId() {
13135 return this.snapshot.catalog.default;
13136 }
13137 get authorable() {
13138 return false;
13139 }
13140 async resolve(id = this.defaultId) {
13141 const row = (await this.list()).find((p) => p.id === id);
13142 if (!row) fail("preset not found");
13143 return row;
13144 }
13145 composedPreset() {
13146 return this.snapshot.selected.metadata.id;
13147 }
13148 async compositionInventory() {
13149 return this.snapshot.catalog.presets.map((row) => {
13150 const identity = { id: row.id, trust: row.trust, ...row.name === void 0 ? {} : { name: row.name }, isDefault: row.id === this.defaultId };
13151 if (row.id === this.composedPreset() && this.mounted) return { ...identity, rows: mountedCompositionRows(this.mounted.tree) };
13152 const read = this.snapshot.catalog.inventory[row.id];
13153 if (row.broken || "broken" in read) return { ...identity, broken: row.broken ?? ("broken" in read ? read.broken : void 0), rows: [] };
13154 return { ...identity, rows: structuredClone(read.rows) };
13155 });
13156 }
13157 async readDocument(id) {
13158 if (id !== this.composedPreset()) fail("read another preset through Core file authority");
13159 return { agentPreset: id, trust: this.snapshot.selected.metadata.trust, content: this.snapshot.selected.source };
13160 }
13161 select() {
13162 fail("select through Core AgentProfile/native preset selection before a turn");
13163 }
13164 recompose() {
13165 fail("Core owns the captured agent selection and blank-session check");
13166 }
13167 copy() {
13168 fail("copy through Core file/install/review/reload authority");
13169 }
13170 remove() {
13171 fail("delete through Core file/install/review/reload authority");
13172 }
13173 };
13174 }
13175 var AGENT_PRESETS, MAX_PRESETS, hash, SHA;
13176 var init_agent_presets = __esm({
13177 "src/dsh/agent-presets.ts"() {
13178 init_persona();
13179 init_lib2();
13180 init_discovery();
13181 init_preset();
13182 init_specifier();
13183 init_composition_inventory();
13184 init_src();
13185 AGENT_PRESETS = "@deepseek-ai/dsh-agent-presets";
13186 MAX_PRESETS = 64;
13187 hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
13188 SHA = /^[a-f0-9]{64}$/;
13189 }
13190 });
13191 init_agent_presets();
13192 export {
13193 AGENT_PRESETS,
13194 containedPackageModule,
13195 defineReviewedAgentPresets,
13196 reviewAgentPresets
13197 };
13198
13198 lines Plain Text