@midscene/cli 1.8.7 → 1.8.8-beta-20260601092605.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/es/index.mjs CHANGED
@@ -1,26 +1,29 @@
1
1
  /*! For license information please see index.mjs.LICENSE.txt */
2
- import node_path, { basename, dirname, extname, join, posix, relative as external_node_path_relative, resolve as external_node_path_resolve, win32 } from "node:path";
2
+ import { basename as external_node_path_basename, dirname as external_node_path_dirname, extname as external_node_path_extname, join as external_node_path_join, posix, relative as external_node_path_relative, resolve as external_node_path_resolve, sep as external_node_path_sep, win32 } from "node:path";
3
3
  import { createReportCliCommands } from "@midscene/core";
4
4
  import { runToolsCLI } from "@midscene/shared/cli";
5
- import { ScriptPlayer, interpolateEnvVars, parseYamlScript } from "@midscene/core/yaml";
6
- import { getMidsceneRunSubDir } from "@midscene/shared/common";
7
- import { buildChromeArgs, defaultViewportHeight, defaultViewportWidth, puppeteerAgentForTarget } from "@midscene/web/puppeteer-agent-launcher";
8
- import lodash_merge from "lodash.merge";
9
- import puppeteer from "puppeteer";
10
- import { createServer } from "http-server";
11
- import node_assert from "node:assert";
12
- import { createAgent, getReportFileName } from "@midscene/core/agent";
13
- import { processCacheConfig } from "@midscene/core/utils";
14
5
  import { getDebug } from "@midscene/shared/logger";
15
- import { AgentOverChromeBridge } from "@midscene/web/bridge-mode";
16
- import { stripVTControlCharacters } from "node:util";
17
- import node_process, { cwd as external_node_process_cwd } from "node:process";
18
- import { fileURLToPath } from "node:url";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { channel, tracingChannel } from "node:diagnostics_channel";
19
8
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
20
9
  import { EventEmitter } from "node:events";
21
10
  import node_stream from "node:stream";
22
11
  import { StringDecoder } from "node:string_decoder";
23
12
  import { fileURLToPath as external_url_fileURLToPath } from "url";
13
+ import { cwd as external_node_process_cwd } from "node:process";
14
+ import { interpolateEnvVars } from "@midscene/core/yaml";
15
+ import lodash_merge from "lodash.merge";
16
+ import { getMidsceneRunSubDir } from "@midscene/shared/common";
17
+ import { createRequire } from "node:module";
18
+ import "@rstest/core";
19
+ import "@midscene/web/puppeteer-agent-launcher";
20
+ import "puppeteer";
21
+ import "http-server";
22
+ import "node:assert";
23
+ import "@midscene/core/agent";
24
+ import "@midscene/core/utils";
25
+ import "@midscene/web/bridge-mode";
26
+ import "node:util";
24
27
  import * as __rspack_external_assert from "assert";
25
28
  import * as __rspack_external_crypto from "crypto";
26
29
  import * as __rspack_external_fs from "fs";
@@ -290,199 +293,6 @@ var __webpack_modules__ = {
290
293
  get: assembleStyles
291
294
  });
292
295
  },
293
- "../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js" (module) {
294
- module.exports = balanced;
295
- function balanced(a, b, str) {
296
- if (a instanceof RegExp) a = maybeMatch(a, str);
297
- if (b instanceof RegExp) b = maybeMatch(b, str);
298
- var r = range(a, b, str);
299
- return r && {
300
- start: r[0],
301
- end: r[1],
302
- pre: str.slice(0, r[0]),
303
- body: str.slice(r[0] + a.length, r[1]),
304
- post: str.slice(r[1] + b.length)
305
- };
306
- }
307
- function maybeMatch(reg, str) {
308
- var m = str.match(reg);
309
- return m ? m[0] : null;
310
- }
311
- balanced.range = range;
312
- function range(a, b, str) {
313
- var begs, beg, left, right, result;
314
- var ai = str.indexOf(a);
315
- var bi = str.indexOf(b, ai + 1);
316
- var i = ai;
317
- if (ai >= 0 && bi > 0) {
318
- if (a === b) return [
319
- ai,
320
- bi
321
- ];
322
- begs = [];
323
- left = str.length;
324
- while(i >= 0 && !result){
325
- if (i == ai) {
326
- begs.push(i);
327
- ai = str.indexOf(a, i + 1);
328
- } else if (1 == begs.length) result = [
329
- begs.pop(),
330
- bi
331
- ];
332
- else {
333
- beg = begs.pop();
334
- if (beg < left) {
335
- left = beg;
336
- right = bi;
337
- }
338
- bi = str.indexOf(b, i + 1);
339
- }
340
- i = ai < bi && ai >= 0 ? ai : bi;
341
- }
342
- if (begs.length) result = [
343
- left,
344
- right
345
- ];
346
- }
347
- return result;
348
- }
349
- },
350
- "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js" (module, __unused_rspack_exports, __webpack_require__) {
351
- var balanced = __webpack_require__("../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js");
352
- module.exports = expandTop;
353
- var escSlash = '\0SLASH' + Math.random() + '\0';
354
- var escOpen = '\0OPEN' + Math.random() + '\0';
355
- var escClose = '\0CLOSE' + Math.random() + '\0';
356
- var escComma = '\0COMMA' + Math.random() + '\0';
357
- var escPeriod = '\0PERIOD' + Math.random() + '\0';
358
- function numeric(str) {
359
- return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
360
- }
361
- function escapeBraces(str) {
362
- return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
363
- }
364
- function unescapeBraces(str) {
365
- return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
366
- }
367
- function parseCommaParts(str) {
368
- if (!str) return [
369
- ''
370
- ];
371
- var parts = [];
372
- var m = balanced('{', '}', str);
373
- if (!m) return str.split(',');
374
- var pre = m.pre;
375
- var body = m.body;
376
- var post = m.post;
377
- var p = pre.split(',');
378
- p[p.length - 1] += '{' + body + '}';
379
- var postParts = parseCommaParts(post);
380
- if (post.length) {
381
- p[p.length - 1] += postParts.shift();
382
- p.push.apply(p, postParts);
383
- }
384
- parts.push.apply(parts, p);
385
- return parts;
386
- }
387
- function expandTop(str) {
388
- if (!str) return [];
389
- if ('{}' === str.substr(0, 2)) str = '\\{\\}' + str.substr(2);
390
- return expand(escapeBraces(str), true).map(unescapeBraces);
391
- }
392
- function embrace(str) {
393
- return '{' + str + '}';
394
- }
395
- function isPadded(el) {
396
- return /^-?0\d/.test(el);
397
- }
398
- function lte(i, y) {
399
- return i <= y;
400
- }
401
- function gte(i, y) {
402
- return i >= y;
403
- }
404
- function expand(str, isTop) {
405
- var expansions = [];
406
- var m = balanced('{', '}', str);
407
- if (!m) return [
408
- str
409
- ];
410
- var pre = m.pre;
411
- var post = m.post.length ? expand(m.post, false) : [
412
- ''
413
- ];
414
- if (/\$$/.test(m.pre)) for(var k = 0; k < post.length; k++){
415
- var expansion = pre + '{' + m.body + '}' + post[k];
416
- expansions.push(expansion);
417
- }
418
- else {
419
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
420
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
421
- var isSequence = isNumericSequence || isAlphaSequence;
422
- var isOptions = m.body.indexOf(',') >= 0;
423
- if (!isSequence && !isOptions) {
424
- if (m.post.match(/,.*\}/)) {
425
- str = m.pre + '{' + m.body + escClose + m.post;
426
- return expand(str);
427
- }
428
- return [
429
- str
430
- ];
431
- }
432
- var n;
433
- if (isSequence) n = m.body.split(/\.\./);
434
- else {
435
- n = parseCommaParts(m.body);
436
- if (1 === n.length) {
437
- n = expand(n[0], false).map(embrace);
438
- if (1 === n.length) return post.map(function(p) {
439
- return m.pre + n[0] + p;
440
- });
441
- }
442
- }
443
- var N;
444
- if (isSequence) {
445
- var x = numeric(n[0]);
446
- var y = numeric(n[1]);
447
- var width = Math.max(n[0].length, n[1].length);
448
- var incr = 3 == n.length ? Math.abs(numeric(n[2])) : 1;
449
- var test = lte;
450
- var reverse = y < x;
451
- if (reverse) {
452
- incr *= -1;
453
- test = gte;
454
- }
455
- var pad = n.some(isPadded);
456
- N = [];
457
- for(var i = x; test(i, y); i += incr){
458
- var c;
459
- if (isAlphaSequence) {
460
- c = String.fromCharCode(i);
461
- if ('\\' === c) c = '';
462
- } else {
463
- c = String(i);
464
- if (pad) {
465
- var need = width - c.length;
466
- if (need > 0) {
467
- var z = new Array(need + 1).join('0');
468
- c = i < 0 ? '-' + z + c.slice(1) : z + c;
469
- }
470
- }
471
- }
472
- N.push(c);
473
- }
474
- } else {
475
- N = [];
476
- for(var j = 0; j < n.length; j++)N.push.apply(N, expand(n[j], false));
477
- }
478
- for(var j = 0; j < N.length; j++)for(var k = 0; k < post.length; k++){
479
- var expansion = pre + N[j] + post[k];
480
- if (!isTop || isSequence || expansion) expansions.push(expansion);
481
- }
482
- }
483
- return expansions;
484
- }
485
- },
486
296
  "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js" (module, __unused_rspack_exports, __webpack_require__) {
487
297
  const ansiStyles = __webpack_require__("../../node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js");
488
298
  const { stdout: stdoutColor, stderr: stderrColor } = __webpack_require__("../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js");
@@ -3024,1127 +2834,202 @@ var __webpack_modules__ = {
3024
2834
  "./src/index.ts" (__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
3025
2835
  var main = __webpack_require__("../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js");
3026
2836
  var main_default = /*#__PURE__*/ __webpack_require__.n(main);
3027
- var package_namespaceObject = {
3028
- rE: "1.8.7"
3029
- };
3030
- class Node {
3031
- value;
3032
- next;
3033
- constructor(value){
3034
- this.value = value;
3035
- }
3036
- }
3037
- class Queue {
3038
- #head;
3039
- #tail;
3040
- #size;
3041
- constructor(){
3042
- this.clear();
3043
- }
3044
- enqueue(value) {
3045
- const node = new Node(value);
3046
- if (this.#head) {
3047
- this.#tail.next = node;
3048
- this.#tail = node;
3049
- } else {
3050
- this.#head = node;
3051
- this.#tail = node;
3052
- }
3053
- this.#size++;
3054
- }
3055
- dequeue() {
3056
- const current = this.#head;
3057
- if (!current) return;
3058
- this.#head = this.#head.next;
3059
- this.#size--;
3060
- return current.value;
3061
- }
3062
- peek() {
3063
- if (!this.#head) return;
3064
- return this.#head.value;
3065
- }
3066
- clear() {
3067
- this.#head = void 0;
3068
- this.#tail = void 0;
3069
- this.#size = 0;
3070
- }
3071
- get size() {
3072
- return this.#size;
3073
- }
3074
- *[Symbol.iterator]() {
3075
- let current = this.#head;
3076
- while(current){
3077
- yield current.value;
3078
- current = current.next;
3079
- }
3080
- }
3081
- *drain() {
3082
- while(this.#head)yield this.dequeue();
3083
- }
3084
- }
3085
- function pLimit(concurrency) {
3086
- validateConcurrency(concurrency);
3087
- const queue = new Queue();
3088
- let activeCount = 0;
3089
- const resumeNext = ()=>{
3090
- if (activeCount < concurrency && queue.size > 0) {
3091
- queue.dequeue()();
3092
- activeCount++;
3093
- }
3094
- };
3095
- const next = ()=>{
3096
- activeCount--;
3097
- resumeNext();
3098
- };
3099
- const run = async (function_, resolve, arguments_)=>{
3100
- const result = (async ()=>function_(...arguments_))();
3101
- resolve(result);
3102
- try {
3103
- await result;
3104
- } catch {}
3105
- next();
3106
- };
3107
- const enqueue = (function_, resolve, arguments_)=>{
3108
- new Promise((internalResolve)=>{
3109
- queue.enqueue(internalResolve);
3110
- }).then(run.bind(void 0, function_, resolve, arguments_));
3111
- (async ()=>{
3112
- await Promise.resolve();
3113
- if (activeCount < concurrency) resumeNext();
3114
- })();
2837
+ var package_namespaceObject = JSON.parse('{"rE":"1.8.8-beta-20260601092605.0"}');
2838
+ const balanced = (a, b, str)=>{
2839
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
2840
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
2841
+ const r = null !== ma && null != mb && range(ma, mb, str);
2842
+ return r && {
2843
+ start: r[0],
2844
+ end: r[1],
2845
+ pre: str.slice(0, r[0]),
2846
+ body: str.slice(r[0] + ma.length, r[1]),
2847
+ post: str.slice(r[1] + mb.length)
3115
2848
  };
3116
- const generator = (function_, ...arguments_)=>new Promise((resolve)=>{
3117
- enqueue(function_, resolve, arguments_);
3118
- });
3119
- Object.defineProperties(generator, {
3120
- activeCount: {
3121
- get: ()=>activeCount
3122
- },
3123
- pendingCount: {
3124
- get: ()=>queue.size
3125
- },
3126
- clearQueue: {
3127
- value () {
3128
- queue.clear();
3129
- }
3130
- },
3131
- concurrency: {
3132
- get: ()=>concurrency,
3133
- set (newConcurrency) {
3134
- validateConcurrency(newConcurrency);
3135
- concurrency = newConcurrency;
3136
- queueMicrotask(()=>{
3137
- while(activeCount < concurrency && queue.size > 0)resumeNext();
3138
- });
2849
+ };
2850
+ const maybeMatch = (reg, str)=>{
2851
+ const m = str.match(reg);
2852
+ return m ? m[0] : null;
2853
+ };
2854
+ const range = (a, b, str)=>{
2855
+ let begs, beg, left, right, result;
2856
+ let ai = str.indexOf(a);
2857
+ let bi = str.indexOf(b, ai + 1);
2858
+ let i = ai;
2859
+ if (ai >= 0 && bi > 0) {
2860
+ if (a === b) return [
2861
+ ai,
2862
+ bi
2863
+ ];
2864
+ begs = [];
2865
+ left = str.length;
2866
+ while(i >= 0 && !result){
2867
+ if (i === ai) {
2868
+ begs.push(i);
2869
+ ai = str.indexOf(a, i + 1);
2870
+ } else if (1 === begs.length) {
2871
+ const r = begs.pop();
2872
+ if (void 0 !== r) result = [
2873
+ r,
2874
+ bi
2875
+ ];
2876
+ } else {
2877
+ beg = begs.pop();
2878
+ if (void 0 !== beg && beg < left) {
2879
+ left = beg;
2880
+ right = bi;
2881
+ }
2882
+ bi = str.indexOf(b, i + 1);
3139
2883
  }
2884
+ i = ai < bi && ai >= 0 ? ai : bi;
3140
2885
  }
3141
- });
3142
- return generator;
3143
- }
3144
- function validateConcurrency(concurrency) {
3145
- if (!((Number.isInteger(concurrency) || concurrency === 1 / 0) && concurrency > 0)) throw new TypeError('Expected `concurrency` to be a number from 1 and up');
2886
+ if (begs.length && void 0 !== right) result = [
2887
+ left,
2888
+ right
2889
+ ];
2890
+ }
2891
+ return result;
2892
+ };
2893
+ const escSlash = '\0SLASH' + Math.random() + '\0';
2894
+ const escOpen = '\0OPEN' + Math.random() + '\0';
2895
+ const escClose = '\0CLOSE' + Math.random() + '\0';
2896
+ const escComma = '\0COMMA' + Math.random() + '\0';
2897
+ const escPeriod = '\0PERIOD' + Math.random() + '\0';
2898
+ const escSlashPattern = new RegExp(escSlash, 'g');
2899
+ const escOpenPattern = new RegExp(escOpen, 'g');
2900
+ const escClosePattern = new RegExp(escClose, 'g');
2901
+ const escCommaPattern = new RegExp(escComma, 'g');
2902
+ const escPeriodPattern = new RegExp(escPeriod, 'g');
2903
+ const slashPattern = /\\\\/g;
2904
+ const openPattern = /\\{/g;
2905
+ const closePattern = /\\}/g;
2906
+ const commaPattern = /\\,/g;
2907
+ const periodPattern = /\\\./g;
2908
+ const EXPANSION_MAX = 100000;
2909
+ function numeric(str) {
2910
+ return isNaN(str) ? str.charCodeAt(0) : parseInt(str, 10);
3146
2911
  }
3147
- const debug = getDebug('create-yaml-player');
3148
- const launchServer = async (dir)=>new Promise((resolve)=>{
3149
- const server = createServer({
3150
- root: dir
3151
- });
3152
- server.listen(0, '127.0.0.1', ()=>{
3153
- resolve(server);
3154
- });
3155
- });
3156
- function resolveReportFileName(yamlReportFileName, cliTestId, yamlTestId, fileName) {
3157
- const baseName = yamlReportFileName ?? cliTestId ?? yamlTestId ?? fileName;
3158
- return getReportFileName(baseName);
2912
+ function escapeBraces(str) {
2913
+ return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
3159
2914
  }
3160
- function buildAgentOptions(yamlAgent, reportFileName, fileName) {
3161
- return {
3162
- ...yamlAgent || {},
3163
- cache: processCacheConfig(yamlAgent?.cache, fileName),
3164
- reportFileName
3165
- };
2915
+ function unescapeBraces(str) {
2916
+ return str.replace(escSlashPattern, '\\').replace(escOpenPattern, '{').replace(escClosePattern, '}').replace(escCommaPattern, ',').replace(escPeriodPattern, '.');
3166
2917
  }
3167
- async function createYamlPlayer(file, script, options) {
3168
- const yamlScript = script || parseYamlScript((0, __rspack_external_node_fs_5ea92f0c.readFileSync)(file, 'utf-8'), file);
3169
- const clonedYamlScript = structuredClone(yamlScript);
3170
- const fileName = basename(file, extname(file));
3171
- const preference = {
3172
- headed: options?.headed,
3173
- keepWindow: options?.keepWindow,
3174
- reportFileName: resolveReportFileName(clonedYamlScript.agent?.reportFileName, options?.testId, clonedYamlScript.agent?.testId, fileName)
3175
- };
3176
- const player = new ScriptPlayer(clonedYamlScript, async ()=>{
3177
- const freeFn = [];
3178
- const webTarget = clonedYamlScript.web || clonedYamlScript.target;
3179
- const targetCount = [
3180
- void 0 !== webTarget,
3181
- void 0 !== clonedYamlScript.android,
3182
- void 0 !== clonedYamlScript.ios,
3183
- void 0 !== clonedYamlScript.computer,
3184
- void 0 !== clonedYamlScript.interface
3185
- ].filter(Boolean).length;
3186
- if (targetCount > 1) {
3187
- const specifiedTargets = [
3188
- void 0 !== webTarget ? 'web' : null,
3189
- void 0 !== clonedYamlScript.android ? 'android' : null,
3190
- void 0 !== clonedYamlScript.ios ? 'ios' : null,
3191
- void 0 !== clonedYamlScript.computer ? 'computer' : null,
3192
- void 0 !== clonedYamlScript.interface ? 'interface' : null
3193
- ].filter(Boolean);
3194
- throw new Error(`Only one target type can be specified, but found multiple: ${specifiedTargets.join(', ')}. Please specify only one of: web, android, ios, computer, or interface.`);
3195
- }
3196
- if (void 0 !== webTarget) {
3197
- if (void 0 !== clonedYamlScript.target) console.warn("target is deprecated, please use web instead. See https://midscenejs.com/automate-with-scripts-in-yaml for more information. Sorry for the inconvenience.");
3198
- let localServer;
3199
- let urlToVisit;
3200
- if (webTarget.serve) {
3201
- node_assert('string' == typeof webTarget.url, 'url is required in serve mode');
3202
- localServer = await launchServer(webTarget.serve);
3203
- const serverAddress = localServer.server.address();
3204
- freeFn.push({
3205
- name: 'local_server',
3206
- fn: ()=>localServer?.server.close()
3207
- });
3208
- urlToVisit = webTarget.url.startsWith('/') ? `http://${serverAddress?.address}:${serverAddress?.port}${webTarget.url}` : `http://${serverAddress?.address}:${serverAddress?.port}/${webTarget.url}`;
3209
- webTarget.url = urlToVisit;
3210
- }
3211
- if (webTarget.cdpEndpoint && webTarget.bridgeMode) throw new Error('cdpEndpoint and bridgeMode are mutually exclusive. Please specify only one.');
3212
- if (webTarget.cdpEndpoint) {
3213
- const cdpBrowser = options?.browser ?? await puppeteer.connect({
3214
- browserWSEndpoint: webTarget.cdpEndpoint,
3215
- defaultViewport: null
3216
- });
3217
- if (webTarget.chromeArgs) console.warn('chromeArgs are not supported in CDP mode (browser is already running). They will be ignored.');
3218
- const { agent, freeFn: newFreeFn } = await puppeteerAgentForTarget(webTarget, {
3219
- ...preference,
3220
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3221
- }, cdpBrowser, options?.page);
3222
- const cleanFreeFn = newFreeFn.filter((f)=>'puppeteer_browser' !== f.name);
3223
- if (!options?.browser) cleanFreeFn.push({
3224
- name: 'cdp_browser_disconnect',
3225
- fn: ()=>cdpBrowser.disconnect()
3226
- });
3227
- freeFn.push(...cleanFreeFn);
3228
- return {
3229
- agent,
3230
- freeFn
3231
- };
3232
- }
3233
- if (!webTarget.bridgeMode) {
3234
- const { agent, freeFn: newFreeFn } = await puppeteerAgentForTarget(webTarget, {
3235
- ...preference,
3236
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3237
- }, options?.browser, options?.page);
3238
- freeFn.push(...newFreeFn);
3239
- return {
3240
- agent,
3241
- freeFn
3242
- };
3243
- }
3244
- node_assert('newTabWithUrl' === webTarget.bridgeMode || 'currentTab' === webTarget.bridgeMode, `bridgeMode config value must be either "newTabWithUrl" or "currentTab", but got ${webTarget.bridgeMode}`);
3245
- if (webTarget.userAgent || null != webTarget.viewportWidth || null != webTarget.viewportHeight || null != webTarget.deviceScaleFactor || webTarget.waitForNetworkIdle || webTarget.cookie || webTarget.chromeArgs) console.warn('puppeteer options (userAgent, viewportWidth, viewportHeight, deviceScaleFactor, waitForNetworkIdle, cookie, chromeArgs) are not supported in bridge mode. They will be ignored.');
3246
- const agent = new AgentOverChromeBridge({
3247
- closeNewTabsAfterDisconnect: webTarget.closeNewTabsAfterDisconnect,
3248
- closeConflictServer: true,
3249
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3250
- });
3251
- if ('newTabWithUrl' === webTarget.bridgeMode) await agent.connectNewTabWithUrl(webTarget.url);
3252
- else {
3253
- if (webTarget.url) console.warn('url will be ignored in bridge mode with "currentTab"');
3254
- await agent.connectCurrentTab();
3255
- }
3256
- freeFn.push({
3257
- name: 'destroy_agent_over_chrome_bridge',
3258
- fn: ()=>agent.destroy()
3259
- });
3260
- return {
3261
- agent,
3262
- freeFn
3263
- };
3264
- }
3265
- if (void 0 !== clonedYamlScript.android) {
3266
- const androidTarget = clonedYamlScript.android;
3267
- const { agentFromAdbDevice } = await import("@midscene/android");
3268
- const agent = await agentFromAdbDevice(androidTarget?.deviceId, {
3269
- ...androidTarget,
3270
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3271
- });
3272
- if (androidTarget?.launch) await agent.launch(androidTarget.launch);
3273
- freeFn.push({
3274
- name: 'destroy_android_agent',
3275
- fn: ()=>agent.destroy()
3276
- });
3277
- return {
3278
- agent,
3279
- freeFn
3280
- };
3281
- }
3282
- if (void 0 !== clonedYamlScript.ios) {
3283
- const iosTarget = clonedYamlScript.ios;
3284
- const { agentFromWebDriverAgent } = await import("@midscene/ios");
3285
- const agent = await agentFromWebDriverAgent({
3286
- ...iosTarget,
3287
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3288
- });
3289
- if (iosTarget?.launch) await agent.launch(iosTarget.launch);
3290
- freeFn.push({
3291
- name: 'destroy_ios_agent',
3292
- fn: ()=>agent.destroy()
3293
- });
3294
- return {
3295
- agent,
3296
- freeFn
3297
- };
3298
- }
3299
- if (void 0 !== clonedYamlScript.computer) {
3300
- const computerTarget = clonedYamlScript.computer;
3301
- const { agentForComputer } = await import("@midscene/computer");
3302
- const agent = await agentForComputer({
3303
- ...computerTarget,
3304
- ...buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName)
3305
- });
3306
- freeFn.push({
3307
- name: 'destroy_computer_agent',
3308
- fn: ()=>agent.destroy()
3309
- });
3310
- return {
3311
- agent,
3312
- freeFn
3313
- };
3314
- }
3315
- if (void 0 !== clonedYamlScript.interface) {
3316
- const interfaceTarget = clonedYamlScript.interface;
3317
- const moduleSpecifier = interfaceTarget.module;
3318
- let finalModuleSpecifier;
3319
- if (moduleSpecifier.startsWith('./') || moduleSpecifier.startsWith('../') || node_path.isAbsolute(moduleSpecifier)) {
3320
- const resolvedPath = join(process.cwd(), moduleSpecifier);
3321
- finalModuleSpecifier = resolvedPath;
3322
- } else finalModuleSpecifier = moduleSpecifier;
3323
- debug('importing module config', interfaceTarget.module, 'with export config', interfaceTarget.export, 'final module specifier', finalModuleSpecifier);
3324
- const importedModule = await import(finalModuleSpecifier);
3325
- const DeviceClass = interfaceTarget.export ? importedModule[interfaceTarget.export] : importedModule.default || importedModule;
3326
- debug('DeviceClass', DeviceClass, 'with param', interfaceTarget.param);
3327
- const device = new DeviceClass(interfaceTarget.param || {});
3328
- debug('creating agent from device', device);
3329
- const agent = createAgent(device, buildAgentOptions(clonedYamlScript.agent, preference.reportFileName, fileName));
3330
- freeFn.push({
3331
- name: 'destroy_general_interface_agent',
3332
- fn: ()=>{
3333
- agent.destroy();
3334
- }
3335
- });
3336
- return {
3337
- agent,
3338
- freeFn
3339
- };
3340
- }
3341
- throw new Error('No valid interface configuration found in the yaml script, should be either "web", "android", "ios", "computer", or "interface"');
3342
- }, void 0, file);
3343
- return player;
3344
- }
3345
- var chalk_source = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js");
3346
- var source_default = /*#__PURE__*/ __webpack_require__.n(chalk_source);
3347
- const isTTY = process.env.MIDSCENE_CLI_LOG_ON_NON_TTY ? false : process.stdout.isTTY;
3348
- const printer_indent = ' ';
3349
- const spinnerInterval = 80;
3350
- const spinnerFrames = [
3351
- '◰',
3352
- '◳',
3353
- '◲',
3354
- '◱'
3355
- ];
3356
- const currentSpinningFrame = ()=>spinnerFrames[Math.floor(Date.now() / spinnerInterval) % spinnerFrames.length];
3357
- function indicatorForStatus(status) {
3358
- if ('init' === status) return source_default().gray('◌');
3359
- if ('running' === status) return source_default().yellowBright(currentSpinningFrame());
3360
- if ('done' === status) return source_default().green('✔︎');
3361
- if ('error' === status) return source_default().red('✘');
3362
- }
3363
- const contextInfo = (context)=>{
3364
- const filePath = context.file;
3365
- const filePathToShow = external_node_path_relative(process.cwd(), filePath);
3366
- const fileNameToPrint = `${source_default().gray(`${filePathToShow}`)}`;
3367
- const fileStatusText = indicatorForStatus(context.player.status);
3368
- const contextActionText = void 0 === context.player.currentTaskIndex && 'running' === context.player.status ? source_default().gray('(navigating)') : '';
3369
- const errorText = context.player.errorInSetup ? `\n${printer_indent}${source_default().red('error:')} ${context.player.errorInSetup?.message}\n${printer_indent}${printer_indent}${context.player.errorInSetup?.stack}` : '';
3370
- const outputFile = context.player.output;
3371
- const outputText = outputFile && Object.keys(context.player.result || {}).length > 0 ? `\n${printer_indent}${source_default().gray(`output: ${outputFile}`)}` : '';
3372
- const reportFile = context.player.reportFile;
3373
- const reportText = reportFile ? `\n${printer_indent}${source_default().gray(`report: ${reportFile}`)}` : '';
3374
- const agentStatusTip = context.player.agentStatusTip;
3375
- const agentStatusText = agentStatusTip ? `\n${printer_indent}${source_default().gray(`agent status: ${agentStatusTip}`)}` : '';
3376
- const mergedText = `${fileStatusText} ${fileNameToPrint} ${contextActionText}${outputText}${reportText}${errorText}${agentStatusText}`.trim();
3377
- return {
3378
- fileNameToPrint,
3379
- fileStatusText,
3380
- contextActionText,
3381
- outputText,
3382
- reportText,
3383
- mergedText
3384
- };
3385
- };
3386
- const singleTaskInfo = (task)=>{
3387
- let stepText = '';
3388
- if ('init' === task.status) stepText = '';
3389
- else if ('running' === task.status || 'error' === task.status) if (void 0 === task.currentStep) stepText = source_default().gray('(navigating)');
3390
- else if ('number' == typeof task.currentStep) {
3391
- const actionText = '';
3392
- stepText = source_default().gray(`(task ${task.currentStep + 1}/${task.totalSteps}${actionText})`.trim());
3393
- } else stepText = source_default().gray('(unknown task)');
3394
- const errorText = 'error' === task.status ? `\n${printer_indent}${source_default().gray('error:')}\n${printer_indent}${printer_indent}${task.error?.message}` : '';
3395
- const statusText = indicatorForStatus(task.status);
3396
- const mergedLine = `${statusText} ${task.name} ${stepText}${errorText}`;
3397
- return {
3398
- nameText: task.name,
3399
- stepText,
3400
- errorText,
3401
- itemStatusText: statusText,
3402
- mergedLine
3403
- };
3404
- };
3405
- function paddingLines(lines) {
3406
- return lines.map((line)=>`${printer_indent}${line}`);
3407
- }
3408
- const contextTaskListSummary = (taskStatusArray, context)=>{
3409
- const prefixLines = [];
3410
- const currentLine = [];
3411
- const suffixText = [];
3412
- const { mergedText: fileInfo } = contextInfo(context);
3413
- if (!context.player.errorInSetup) for (const task of taskStatusArray){
3414
- const { mergedLine } = singleTaskInfo(task);
3415
- if ('init' === context.player.status) suffixText.push(mergedLine);
3416
- else if ('running' === context.player.status) currentLine.push(mergedLine);
3417
- else if ('done' === context.player.status) prefixLines.push(mergedLine);
3418
- else if ('error' === context.player.status) prefixLines.push(mergedLine);
3419
- }
3420
- const lines = [
3421
- fileInfo
2918
+ function parseCommaParts(str) {
2919
+ if (!str) return [
2920
+ ''
3422
2921
  ];
3423
- if (prefixLines.length > 0) lines.push(...paddingLines(prefixLines));
3424
- if (currentLine.length > 0) lines.push(...paddingLines(currentLine));
3425
- if (suffixText.length > 0) lines.push(...paddingLines(suffixText));
3426
- return lines.join('\n');
3427
- };
3428
- const copyProperty = (to, from, property, ignoreNonConfigurable)=>{
3429
- if ('length' === property || 'prototype' === property) return;
3430
- if ('arguments' === property || 'caller' === property) return;
3431
- const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
3432
- const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
3433
- if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) return;
3434
- Object.defineProperty(to, property, fromDescriptor);
3435
- };
3436
- const canCopyProperty = function(toDescriptor, fromDescriptor) {
3437
- return void 0 === toDescriptor || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
3438
- };
3439
- const changePrototype = (to, from)=>{
3440
- const fromPrototype = Object.getPrototypeOf(from);
3441
- if (fromPrototype === Object.getPrototypeOf(to)) return;
3442
- Object.setPrototypeOf(to, fromPrototype);
3443
- };
3444
- const wrappedToString = (withName, fromBody)=>`/* Wrapped ${withName}*/\n${fromBody}`;
3445
- const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
3446
- const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
3447
- const changeToString = (to, from, name)=>{
3448
- const withName = '' === name ? '' : `with ${name.trim()}() `;
3449
- const newToString = wrappedToString.bind(null, withName, from.toString());
3450
- Object.defineProperty(newToString, 'name', toStringName);
3451
- const { writable, enumerable, configurable } = toStringDescriptor;
3452
- Object.defineProperty(to, 'toString', {
3453
- value: newToString,
3454
- writable,
3455
- enumerable,
3456
- configurable
3457
- });
3458
- };
3459
- function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
3460
- const { name } = to;
3461
- for (const property of Reflect.ownKeys(from))copyProperty(to, from, property, ignoreNonConfigurable);
3462
- changePrototype(to, from);
3463
- changeToString(to, from, name);
3464
- return to;
3465
- }
3466
- const calledFunctions = new WeakMap();
3467
- const onetime_onetime = (function_, options = {})=>{
3468
- if ('function' != typeof function_) throw new TypeError('Expected a function');
3469
- let returnValue;
3470
- let callCount = 0;
3471
- const functionName = function_.displayName || function_.name || '<anonymous>';
3472
- const onetime = function(...arguments_) {
3473
- calledFunctions.set(onetime, ++callCount);
3474
- if (1 === callCount) {
3475
- returnValue = function_.apply(this, arguments_);
3476
- function_ = void 0;
3477
- } else if (true === options.throw) throw new Error(`Function \`${functionName}\` can only be called once`);
3478
- return returnValue;
3479
- };
3480
- mimicFunction(onetime, function_);
3481
- calledFunctions.set(onetime, callCount);
3482
- return onetime;
3483
- };
3484
- onetime_onetime.callCount = (function_)=>{
3485
- if (!calledFunctions.has(function_)) throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
3486
- return calledFunctions.get(function_);
3487
- };
3488
- const node_modules_onetime = onetime_onetime;
3489
- const signals = [];
3490
- signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
3491
- if ('win32' !== process.platform) signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT');
3492
- if ('linux' === process.platform) signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
3493
- const processOk = (process1)=>!!process1 && 'object' == typeof process1 && 'function' == typeof process1.removeListener && 'function' == typeof process1.emit && 'function' == typeof process1.reallyExit && 'function' == typeof process1.listeners && 'function' == typeof process1.kill && 'number' == typeof process1.pid && 'function' == typeof process1.on;
3494
- const kExitEmitter = Symbol.for('signal-exit emitter');
3495
- const global = globalThis;
3496
- const ObjectDefineProperty = Object.defineProperty.bind(Object);
3497
- class Emitter {
3498
- emitted = {
3499
- afterExit: false,
3500
- exit: false
3501
- };
3502
- listeners = {
3503
- afterExit: [],
3504
- exit: []
3505
- };
3506
- count = 0;
3507
- id = Math.random();
3508
- constructor(){
3509
- if (global[kExitEmitter]) return global[kExitEmitter];
3510
- ObjectDefineProperty(global, kExitEmitter, {
3511
- value: this,
3512
- writable: false,
3513
- enumerable: false,
3514
- configurable: false
3515
- });
3516
- }
3517
- on(ev, fn) {
3518
- this.listeners[ev].push(fn);
3519
- }
3520
- removeListener(ev, fn) {
3521
- const list = this.listeners[ev];
3522
- const i = list.indexOf(fn);
3523
- if (-1 === i) return;
3524
- if (0 === i && 1 === list.length) list.length = 0;
3525
- else list.splice(i, 1);
3526
- }
3527
- emit(ev, code, signal) {
3528
- if (this.emitted[ev]) return false;
3529
- this.emitted[ev] = true;
3530
- let ret = false;
3531
- for (const fn of this.listeners[ev])ret = true === fn(code, signal) || ret;
3532
- if ('exit' === ev) ret = this.emit('afterExit', code, signal) || ret;
3533
- return ret;
2922
+ const parts = [];
2923
+ const m = balanced('{', '}', str);
2924
+ if (!m) return str.split(',');
2925
+ const { pre, body, post } = m;
2926
+ const p = pre.split(',');
2927
+ p[p.length - 1] += '{' + body + '}';
2928
+ const postParts = parseCommaParts(post);
2929
+ if (post.length) {
2930
+ p[p.length - 1] += postParts.shift();
2931
+ p.push.apply(p, postParts);
3534
2932
  }
2933
+ parts.push.apply(parts, p);
2934
+ return parts;
3535
2935
  }
3536
- class SignalExitBase {
3537
- }
3538
- const signalExitWrap = (handler)=>({
3539
- onExit (cb, opts) {
3540
- return handler.onExit(cb, opts);
3541
- },
3542
- load () {
3543
- return handler.load();
3544
- },
3545
- unload () {
3546
- return handler.unload();
3547
- }
3548
- });
3549
- class SignalExitFallback extends SignalExitBase {
3550
- onExit() {
3551
- return ()=>{};
3552
- }
3553
- load() {}
3554
- unload() {}
3555
- }
3556
- class SignalExit extends SignalExitBase {
3557
- #hupSig = 'win32' === mjs_process.platform ? 'SIGINT' : 'SIGHUP';
3558
- #emitter = new Emitter();
3559
- #process;
3560
- #originalProcessEmit;
3561
- #originalProcessReallyExit;
3562
- #sigListeners = {};
3563
- #loaded = false;
3564
- constructor(process1){
3565
- super();
3566
- this.#process = process1;
3567
- this.#sigListeners = {};
3568
- for (const sig of signals)this.#sigListeners[sig] = ()=>{
3569
- const listeners = this.#process.listeners(sig);
3570
- let { count } = this.#emitter;
3571
- const p = process1;
3572
- if ('object' == typeof p.__signal_exit_emitter__ && 'number' == typeof p.__signal_exit_emitter__.count) count += p.__signal_exit_emitter__.count;
3573
- if (listeners.length === count) {
3574
- this.unload();
3575
- const ret = this.#emitter.emit('exit', null, sig);
3576
- const s = 'SIGHUP' === sig ? this.#hupSig : sig;
3577
- if (!ret) process1.kill(process1.pid, s);
3578
- }
3579
- };
3580
- this.#originalProcessReallyExit = process1.reallyExit;
3581
- this.#originalProcessEmit = process1.emit;
3582
- }
3583
- onExit(cb, opts) {
3584
- if (!processOk(this.#process)) return ()=>{};
3585
- if (false === this.#loaded) this.load();
3586
- const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
3587
- this.#emitter.on(ev, cb);
3588
- return ()=>{
3589
- this.#emitter.removeListener(ev, cb);
3590
- if (0 === this.#emitter.listeners['exit'].length && 0 === this.#emitter.listeners['afterExit'].length) this.unload();
3591
- };
3592
- }
3593
- load() {
3594
- if (this.#loaded) return;
3595
- this.#loaded = true;
3596
- this.#emitter.count += 1;
3597
- for (const sig of signals)try {
3598
- const fn = this.#sigListeners[sig];
3599
- if (fn) this.#process.on(sig, fn);
3600
- } catch (_) {}
3601
- this.#process.emit = (ev, ...a)=>this.#processEmit(ev, ...a);
3602
- this.#process.reallyExit = (code)=>this.#processReallyExit(code);
3603
- }
3604
- unload() {
3605
- if (!this.#loaded) return;
3606
- this.#loaded = false;
3607
- signals.forEach((sig)=>{
3608
- const listener = this.#sigListeners[sig];
3609
- if (!listener) throw new Error('Listener not defined for signal: ' + sig);
3610
- try {
3611
- this.#process.removeListener(sig, listener);
3612
- } catch (_) {}
3613
- });
3614
- this.#process.emit = this.#originalProcessEmit;
3615
- this.#process.reallyExit = this.#originalProcessReallyExit;
3616
- this.#emitter.count -= 1;
3617
- }
3618
- #processReallyExit(code) {
3619
- if (!processOk(this.#process)) return 0;
3620
- this.#process.exitCode = code || 0;
3621
- this.#emitter.emit('exit', this.#process.exitCode, null);
3622
- return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
3623
- }
3624
- #processEmit(ev, ...args) {
3625
- const og = this.#originalProcessEmit;
3626
- if (!('exit' === ev && processOk(this.#process))) return og.call(this.#process, ev, ...args);
3627
- {
3628
- if ('number' == typeof args[0]) this.#process.exitCode = args[0];
3629
- const ret = og.call(this.#process, ev, ...args);
3630
- this.#emitter.emit('exit', this.#process.exitCode, null);
3631
- return ret;
3632
- }
3633
- }
2936
+ function expand(str, options = {}) {
2937
+ if (!str) return [];
2938
+ const { max = EXPANSION_MAX } = options;
2939
+ if ('{}' === str.slice(0, 2)) str = '\\{\\}' + str.slice(2);
2940
+ return expand_(escapeBraces(str), max, true).map(unescapeBraces);
3634
2941
  }
3635
- const mjs_process = globalThis.process;
3636
- const { onExit, load, unload } = signalExitWrap(processOk(mjs_process) ? new SignalExit(mjs_process) : new SignalExitFallback());
3637
- const terminal = node_process.stderr.isTTY ? node_process.stderr : node_process.stdout.isTTY ? node_process.stdout : void 0;
3638
- const restoreCursor = terminal ? node_modules_onetime(()=>{
3639
- onExit(()=>{
3640
- terminal.write('\u001B[?25h');
3641
- }, {
3642
- alwaysLast: true
3643
- });
3644
- }) : ()=>{};
3645
- const restore_cursor = restoreCursor;
3646
- function _define_property(obj, key, value) {
3647
- if (key in obj) Object.defineProperty(obj, key, {
3648
- value: value,
3649
- enumerable: true,
3650
- configurable: true,
3651
- writable: true
3652
- });
3653
- else obj[key] = value;
3654
- return obj;
2942
+ function embrace(str) {
2943
+ return '{' + str + '}';
3655
2944
  }
3656
- const DEFAULT_RENDER_INTERVAL = 160;
3657
- const ESC = '\x1B[';
3658
- const CLEAR_LINE = `${ESC}K`;
3659
- const MOVE_CURSOR_ONE_ROW_UP = `${ESC}1A`;
3660
- const HIDE_CURSOR = `${ESC}?25l`;
3661
- const SHOW_CURSOR = `${ESC}?25h`;
3662
- const SYNC_START = `${ESC}?2026h`;
3663
- const SYNC_END = `${ESC}?2026l`;
3664
- class TTYWindowRenderer {
3665
- start() {
3666
- this.finished = false;
3667
- this.renderInterval = setInterval(()=>this.flushBuffer(), this.options.interval);
3668
- }
3669
- stop() {
3670
- this.flushBuffer();
3671
- this.write(SHOW_CURSOR, 'output');
3672
- this.cleanups.splice(0).map((fn)=>fn());
3673
- clearInterval(this.renderInterval);
3674
- }
3675
- finish() {
3676
- this.finished = true;
3677
- this.flushBuffer();
3678
- clearInterval(this.renderInterval);
3679
- }
3680
- flushBuffer() {
3681
- if (0 === this.buffer.length) return this.render();
3682
- let current;
3683
- for (const next of this.buffer.splice(0)){
3684
- if (!current) {
3685
- current = next;
3686
- continue;
3687
- }
3688
- if (current.type !== next.type) {
3689
- this.render(current.message, current.type);
3690
- current = next;
3691
- continue;
3692
- }
3693
- current.message += next.message;
3694
- }
3695
- if (current) this.render(current?.message, current?.type);
3696
- }
3697
- render(message, type = 'output') {
3698
- if (this.finished) {
3699
- this.clearWindow();
3700
- return this.write(message || '', type);
3701
- }
3702
- const windowContent = this.options.getWindow();
3703
- const rowCount = getRenderedRowCount(windowContent, this.options.outputStream);
3704
- let padding = this.windowHeight - rowCount;
3705
- if (padding > 0 && message) padding -= getRenderedRowCount([
3706
- message
3707
- ], this.options.outputStream);
3708
- this.write(SYNC_START);
3709
- this.clearWindow();
3710
- if (message) this.write(message, type);
3711
- if (padding > 0) this.write('\n'.repeat(padding));
3712
- this.write(windowContent.join('\n'));
3713
- this.write(SYNC_END);
3714
- this.windowHeight = rowCount + Math.max(0, padding);
3715
- }
3716
- clearWindow() {
3717
- if (0 === this.windowHeight) return;
3718
- this.write(CLEAR_LINE);
3719
- for(let i = 1; i < this.windowHeight; i++)this.write(`${MOVE_CURSOR_ONE_ROW_UP}${CLEAR_LINE}`);
3720
- this.windowHeight = 0;
3721
- }
3722
- interceptStream(stream, type) {
3723
- const original = stream.write;
3724
- stream.write = (chunk, _, callback)=>{
3725
- if (chunk) if (this.finished) this.write(chunk.toString(), type);
3726
- else this.buffer.push({
3727
- type,
3728
- message: chunk.toString()
3729
- });
3730
- callback?.();
3731
- };
3732
- return function() {
3733
- stream.write = original;
3734
- };
3735
- }
3736
- write(message, type = 'output') {
3737
- this.streams[type](message);
3738
- }
3739
- constructor(options){
3740
- _define_property(this, "options", void 0);
3741
- _define_property(this, "streams", void 0);
3742
- _define_property(this, "buffer", []);
3743
- _define_property(this, "renderInterval", void 0);
3744
- _define_property(this, "windowHeight", 0);
3745
- _define_property(this, "finished", false);
3746
- _define_property(this, "cleanups", []);
3747
- this.options = {
3748
- interval: DEFAULT_RENDER_INTERVAL,
3749
- ...options
3750
- };
3751
- this.streams = {
3752
- output: options.outputStream.write.bind(options.outputStream),
3753
- error: options.errorStream.write.bind(options.errorStream)
3754
- };
3755
- this.cleanups.push(this.interceptStream(process.stdout, 'output'), this.interceptStream(process.stderr, 'error'));
3756
- restore_cursor();
3757
- this.write(HIDE_CURSOR, 'output');
3758
- this.start();
3759
- }
2945
+ function isPadded(el) {
2946
+ return /^-?0\d/.test(el);
3760
2947
  }
3761
- function getRenderedRowCount(contents, stream) {
3762
- let count = 0;
3763
- const columns = 'columns' in stream ? stream.columns : 80;
3764
- for (const content of contents){
3765
- const rows = content.split('\n');
3766
- for (const row of rows){
3767
- const text = stripVTControlCharacters(row);
3768
- count += Math.max(1, Math.ceil(text.length / columns));
3769
- }
3770
- }
3771
- return count;
2948
+ function lte(i, y) {
2949
+ return i <= y;
3772
2950
  }
3773
- function batch_runner_define_property(obj, key, value) {
3774
- if (key in obj) Object.defineProperty(obj, key, {
3775
- value: value,
3776
- enumerable: true,
3777
- configurable: true,
3778
- writable: true
3779
- });
3780
- else obj[key] = value;
3781
- return obj;
2951
+ function gte(i, y) {
2952
+ return i >= y;
3782
2953
  }
3783
- class BatchRunner {
3784
- async run() {
3785
- const { keepWindow, headed } = this.config;
3786
- this.printExecutionPlan();
3787
- const fileContextList = [];
3788
- let browser = null;
3789
- let sharedPage = null;
3790
- try {
3791
- for (const file of this.config.files){
3792
- const fileConfig = await this.loadFileConfig(file);
3793
- const context = await this.createFileContext(file, fileConfig, {
3794
- headed,
3795
- keepWindow
3796
- });
3797
- fileContextList.push(context);
3798
- }
3799
- const needsBrowser = fileContextList.some((ctx)=>Object.keys(ctx.executionConfig.web || ctx.executionConfig.target || {}).length > 0);
3800
- if (needsBrowser && this.config.shareBrowserContext) {
3801
- const globalWebConfig = this.config.globalConfig?.web;
3802
- if (globalWebConfig?.cdpEndpoint) browser = await puppeteer.connect({
3803
- browserWSEndpoint: globalWebConfig.cdpEndpoint,
3804
- defaultViewport: null
3805
- });
3806
- else {
3807
- const width = globalWebConfig?.viewportWidth ?? defaultViewportWidth;
3808
- const height = globalWebConfig?.viewportHeight ?? defaultViewportHeight;
3809
- const args = buildChromeArgs({
3810
- userAgent: globalWebConfig?.userAgent,
3811
- windowSize: headed ? {
3812
- width,
3813
- height
3814
- } : void 0,
3815
- chromeArgs: globalWebConfig?.chromeArgs
3816
- });
3817
- browser = await puppeteer.launch({
3818
- headless: !headed,
3819
- defaultViewport: headed ? null : {
3820
- width,
3821
- height
3822
- },
3823
- args,
3824
- acceptInsecureCerts: globalWebConfig?.acceptInsecureCerts
3825
- });
3826
- }
3827
- sharedPage = await browser.newPage();
3828
- for (const context of fileContextList){
3829
- context.options.browser = browser;
3830
- context.options.page = sharedPage;
3831
- }
3832
- }
3833
- const { executedResults, notExecutedContexts } = await this.executeFiles(fileContextList);
3834
- this.results = await this.processResults(executedResults, notExecutedContexts);
3835
- } finally{
3836
- if (browser && !this.config.keepWindow) {
3837
- const isCdp = !!this.config.globalConfig?.web?.cdpEndpoint;
3838
- if (isCdp) browser.disconnect();
3839
- else await browser.close();
3840
- }
3841
- await this.generateOutputIndex();
3842
- }
3843
- return this.results;
3844
- }
3845
- async createFileContext(file, fileConfig, options) {
3846
- const { globalConfig } = this.config;
3847
- const clonedFileConfig = JSON.parse(JSON.stringify(fileConfig));
3848
- if (clonedFileConfig.target) {
3849
- clonedFileConfig.web = {
3850
- ...clonedFileConfig.target,
3851
- ...clonedFileConfig.web
3852
- };
3853
- delete clonedFileConfig.target;
3854
- }
3855
- if (globalConfig?.target) {
3856
- globalConfig.web = {
3857
- ...globalConfig.target,
3858
- ...globalConfig.web
3859
- };
3860
- delete globalConfig.target;
3861
- }
3862
- const executionConfig = lodash_merge(clonedFileConfig, globalConfig);
3863
- return {
3864
- file,
3865
- executionConfig,
3866
- options
3867
- };
2954
+ function expand_(str, max, isTop) {
2955
+ const expansions = [];
2956
+ const m = balanced('{', '}', str);
2957
+ if (!m) return [
2958
+ str
2959
+ ];
2960
+ const pre = m.pre;
2961
+ const post = m.post.length ? expand_(m.post, max, false) : [
2962
+ ''
2963
+ ];
2964
+ if (/\$$/.test(m.pre)) for(let k = 0; k < post.length && k < max; k++){
2965
+ const expansion = pre + '{' + m.body + '}' + post[k];
2966
+ expansions.push(expansion);
3868
2967
  }
3869
- async executeFiles(fileContextList) {
3870
- const executedResults = [];
3871
- const notExecutedContexts = [];
3872
- const allFileContexts = [];
3873
- for (const context of fileContextList){
3874
- const player = await createYamlPlayer(context.file, context.executionConfig, context.options);
3875
- allFileContexts.push({
3876
- file: context.file,
3877
- player
3878
- });
3879
- }
3880
- let ttyRenderer;
3881
- if (isTTY) {
3882
- const summaryContents = ()=>{
3883
- const summary = [
3884
- ''
3885
- ];
3886
- for (const context of allFileContexts)summary.push(contextTaskListSummary(context.player.taskStatusList, context));
3887
- summary.push('');
3888
- return summary;
3889
- };
3890
- ttyRenderer = new TTYWindowRenderer({
3891
- outputStream: process.stdout,
3892
- errorStream: process.stderr,
3893
- getWindow: summaryContents,
3894
- interval: spinnerInterval
3895
- });
3896
- ttyRenderer.start();
3897
- }
3898
- try {
3899
- const executeFile = async (context)=>{
3900
- const allFileContext = allFileContexts.find((c)=>c.file === context.file);
3901
- if (!allFileContext) throw new Error(`Player not found for file: ${context.file}`);
3902
- if (!isTTY) {
3903
- const { mergedText } = contextInfo(allFileContext);
3904
- console.log(mergedText);
3905
- }
3906
- if (context.outputPath) allFileContext.player.output = context.outputPath;
3907
- const startTime = Date.now();
3908
- await allFileContext.player.run();
3909
- const endTime = Date.now();
3910
- const duration = endTime - startTime;
3911
- const executedContext = {
3912
- file: context.file,
3913
- player: allFileContext.player,
3914
- duration
3915
- };
3916
- if (!isTTY) console.log(contextTaskListSummary(allFileContext.player.taskStatusList, executedContext));
3917
- return executedContext;
3918
- };
3919
- await this.executeConcurrently(fileContextList, executeFile, executedResults, notExecutedContexts);
3920
- if (!isTTY) {
3921
- console.log('\n📋 Execution Results:');
3922
- for (const context of executedResults)console.log(contextTaskListSummary(context.player.taskStatusList, context));
2968
+ else {
2969
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
2970
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
2971
+ const isSequence = isNumericSequence || isAlphaSequence;
2972
+ const isOptions = m.body.indexOf(',') >= 0;
2973
+ if (!isSequence && !isOptions) {
2974
+ if (m.post.match(/,(?!,).*\}/)) {
2975
+ str = m.pre + '{' + m.body + escClose + m.post;
2976
+ return expand_(str, max, true);
3923
2977
  }
3924
- } finally{
3925
- if (ttyRenderer) ttyRenderer.stop();
2978
+ return [
2979
+ str
2980
+ ];
3926
2981
  }
3927
- return {
3928
- executedResults,
3929
- notExecutedContexts
3930
- };
3931
- }
3932
- async executeConcurrently(fileContextList, executeFile, executedResults, notExecutedContexts) {
3933
- const limit = pLimit(this.config.concurrent);
3934
- if (this.config.continueOnError) {
3935
- const tasks = fileContextList.map((context)=>limit(async ()=>{
3936
- const executedContext = await executeFile(context);
3937
- executedResults.push(executedContext);
3938
- }));
3939
- await Promise.allSettled(tasks);
3940
- } else {
3941
- let shouldStop = false;
3942
- const stopLock = {
3943
- value: false
3944
- };
3945
- const tasks = fileContextList.map((context)=>limit(async ()=>{
3946
- if (stopLock.value) return void notExecutedContexts.push({
3947
- file: context.file,
3948
- player: null
3949
- });
3950
- const executedContext = await executeFile(context);
3951
- executedResults.push(executedContext);
3952
- if ('error' === executedContext.player.status && !stopLock.value) {
3953
- stopLock.value = true;
3954
- shouldStop = true;
2982
+ let n;
2983
+ if (isSequence) n = m.body.split(/\.\./);
2984
+ else {
2985
+ n = parseCommaParts(m.body);
2986
+ if (1 === n.length && void 0 !== n[0]) {
2987
+ n = expand_(n[0], max, false).map(embrace);
2988
+ if (1 === n.length) return post.map((p)=>m.pre + n[0] + p);
2989
+ }
2990
+ }
2991
+ let N;
2992
+ if (isSequence && void 0 !== n[0] && void 0 !== n[1]) {
2993
+ const x = numeric(n[0]);
2994
+ const y = numeric(n[1]);
2995
+ const width = Math.max(n[0].length, n[1].length);
2996
+ let incr = 3 === n.length && void 0 !== n[2] ? Math.max(Math.abs(numeric(n[2])), 1) : 1;
2997
+ let test = lte;
2998
+ const reverse = y < x;
2999
+ if (reverse) {
3000
+ incr *= -1;
3001
+ test = gte;
3002
+ }
3003
+ const pad = n.some(isPadded);
3004
+ N = [];
3005
+ for(let i = x; test(i, y); i += incr){
3006
+ let c;
3007
+ if (isAlphaSequence) {
3008
+ c = String.fromCharCode(i);
3009
+ if ('\\' === c) c = '';
3010
+ } else {
3011
+ c = String(i);
3012
+ if (pad) {
3013
+ const need = width - c.length;
3014
+ if (need > 0) {
3015
+ const z = new Array(need + 1).join('0');
3016
+ c = i < 0 ? '-' + z + c.slice(1) : z + c;
3017
+ }
3955
3018
  }
3956
- }));
3957
- await Promise.allSettled(tasks);
3958
- if (shouldStop) {
3959
- for (const context of fileContextList)if (!executedResults.some((r)=>r.file === context.file) && !notExecutedContexts.some((ctx)=>ctx.file === context.file)) notExecutedContexts.push({
3960
- file: context.file,
3961
- player: null
3962
- });
3019
+ }
3020
+ N.push(c);
3963
3021
  }
3022
+ } else {
3023
+ N = [];
3024
+ for(let j = 0; j < n.length; j++)N.push.apply(N, expand_(n[j], max, false));
3964
3025
  }
3965
- }
3966
- async processResults(executedContexts, notExecutedContexts) {
3967
- const results = [];
3968
- for (const context of executedContexts){
3969
- const { file, player, duration } = context;
3970
- const hasFailedTasks = player.taskStatusList?.some((task)=>'error' === task.status) ?? false;
3971
- const hasPlayerError = 'error' === player.status;
3972
- let success;
3973
- let resultType;
3974
- if (hasPlayerError) {
3975
- success = false;
3976
- resultType = 'failed';
3977
- } else if (hasFailedTasks) {
3978
- success = false;
3979
- resultType = 'partialFailed';
3980
- } else {
3981
- success = true;
3982
- resultType = 'success';
3983
- }
3984
- let reportFile;
3985
- if (player.reportFile) reportFile = player.reportFile;
3986
- let outputPath = player.output || void 0;
3987
- if (outputPath && !(0, __rspack_external_node_fs_5ea92f0c.existsSync)(outputPath)) outputPath = void 0;
3988
- let errorMessage;
3989
- if (player.errorInSetup?.message) errorMessage = player.errorInSetup.message;
3990
- else if (hasPlayerError || hasFailedTasks) {
3991
- const taskErrors = player.taskStatusList?.filter((task)=>'error' === task.status && task.error?.message).map((task)=>task.error.message);
3992
- errorMessage = taskErrors && taskErrors.length > 0 ? taskErrors.join('; ') : hasPlayerError ? 'Execution failed' : 'Some tasks failed';
3993
- }
3994
- results.push({
3995
- file,
3996
- success,
3997
- executed: true,
3998
- output: outputPath,
3999
- report: reportFile,
4000
- duration,
4001
- resultType,
4002
- error: errorMessage
4003
- });
4004
- }
4005
- for (const context of notExecutedContexts)results.push({
4006
- file: context.file,
4007
- success: false,
4008
- executed: false,
4009
- output: void 0,
4010
- report: void 0,
4011
- duration: 0,
4012
- resultType: 'notExecuted',
4013
- error: 'Not executed (previous task failed)'
4014
- });
4015
- return results;
4016
- }
4017
- async loadFileConfig(file) {
4018
- const content = (0, __rspack_external_node_fs_5ea92f0c.readFileSync)(file, 'utf8');
4019
- return parseYamlScript(content, file);
4020
- }
4021
- getSummaryAbsolutePath() {
4022
- return external_node_path_resolve(getMidsceneRunSubDir('output'), this.config.summary);
4023
- }
4024
- printExecutionPlan() {
4025
- console.log(' Scripts:');
4026
- for (const file of this.config.files)console.log(` - ${file}`);
4027
- console.log('📋 Execution plan');
4028
- console.log(` Concurrency: ${this.config.concurrent}`);
4029
- console.log(` Keep window: ${this.config.keepWindow}`);
4030
- console.log(` Headed: ${this.config.headed}`);
4031
- console.log(` Continue on error: ${this.config.continueOnError}`);
4032
- console.log(` Share browser context: ${this.config.shareBrowserContext ?? false}`);
4033
- console.log(` Summary output: ${this.config.summary}`);
4034
- }
4035
- async generateOutputIndex() {
4036
- const indexPath = external_node_path_resolve(getMidsceneRunSubDir('output'), this.config.summary);
4037
- const outputDir = dirname(indexPath);
4038
- try {
4039
- (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(outputDir, {
4040
- recursive: true
4041
- });
4042
- const indexData = {
4043
- summary: {
4044
- total: this.results.length,
4045
- successful: this.results.filter((r)=>'success' === r.resultType).length,
4046
- failed: this.results.filter((r)=>'failed' === r.resultType).length,
4047
- partialFailed: this.results.filter((r)=>'partialFailed' === r.resultType).length,
4048
- notExecuted: this.results.filter((r)=>'notExecuted' === r.resultType).length,
4049
- totalDuration: this.results.reduce((sum, r)=>sum + (r.duration || 0), 0),
4050
- generatedAt: new Date().toLocaleString()
4051
- },
4052
- results: this.results.map((result)=>({
4053
- script: external_node_path_relative(outputDir, result.file),
4054
- success: result.success,
4055
- resultType: result.resultType,
4056
- output: result.output ? (()=>{
4057
- const relativePath = external_node_path_relative(outputDir, result.output);
4058
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
4059
- })() : void 0,
4060
- report: result.report ? external_node_path_relative(outputDir, result.report) : void 0,
4061
- error: result.error,
4062
- duration: result.duration
4063
- }))
4064
- };
4065
- (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(indexPath, JSON.stringify(indexData, null, 2));
4066
- console.log('Execution finished:');
4067
- } catch (error) {
4068
- console.error('Failed to generate output index:', error);
4069
- }
4070
- }
4071
- getExecutionSummary() {
4072
- const successful = this.results.filter((r)=>'success' === r.resultType).length;
4073
- const failed = this.results.filter((r)=>'failed' === r.resultType).length;
4074
- const partialFailed = this.results.filter((r)=>'partialFailed' === r.resultType).length;
4075
- const notExecuted = this.results.filter((r)=>'notExecuted' === r.resultType).length;
4076
- return {
4077
- total: this.results.length,
4078
- successful,
4079
- failed,
4080
- partialFailed,
4081
- notExecuted,
4082
- totalDuration: this.results.reduce((sum, r)=>sum + (r.duration || 0), 0)
4083
- };
4084
- }
4085
- getFailedFiles() {
4086
- return this.results.filter((r)=>'failed' === r.resultType).map((r)=>r.file);
4087
- }
4088
- getPartialFailedFiles() {
4089
- return this.results.filter((r)=>'partialFailed' === r.resultType).map((r)=>r.file);
4090
- }
4091
- getNotExecutedFiles() {
4092
- return this.results.filter((r)=>'notExecuted' === r.resultType).map((r)=>r.file);
4093
- }
4094
- getSuccessfulFiles() {
4095
- return this.results.filter((r)=>'success' === r.resultType).map((r)=>r.file);
4096
- }
4097
- getResults() {
4098
- return [
4099
- ...this.results
4100
- ];
4101
- }
4102
- printExecutionSummary() {
4103
- const summary = this.getExecutionSummary();
4104
- const success = 0 === summary.failed && 0 === summary.partialFailed && 0 === summary.notExecuted;
4105
- console.log('\n📊 Execution Summary:');
4106
- console.log(` Total files: ${summary.total}`);
4107
- console.log(` Successful: ${summary.successful}`);
4108
- console.log(` Failed: ${summary.failed}`);
4109
- console.log(` Partial failed: ${summary.partialFailed}`);
4110
- console.log(` Not executed: ${summary.notExecuted}`);
4111
- console.log(` Duration: ${(summary.totalDuration / 1000).toFixed(2)}s`);
4112
- console.log(` Summary: ${this.getSummaryAbsolutePath()}`);
4113
- if (summary.successful > 0) {
4114
- console.log('\n✅ Successful files:');
4115
- this.getSuccessfulFiles().forEach((file)=>{
4116
- console.log(` ${file}`);
4117
- });
4118
- }
4119
- if (summary.failed > 0) {
4120
- console.log('\n❌ Failed files');
4121
- this.getFailedFiles().forEach((file)=>{
4122
- console.log(` ${file}`);
4123
- });
4124
- }
4125
- if (summary.partialFailed > 0) {
4126
- console.log('\n⚠️ Partial failed files (some tasks failed with continueOnError)');
4127
- this.getPartialFailedFiles().forEach((file)=>{
4128
- console.log(` ${file}`);
4129
- });
4130
- }
4131
- if (summary.notExecuted > 0) {
4132
- console.log('\n⏸️ Not executed files');
4133
- this.getNotExecutedFiles().forEach((file)=>{
4134
- console.log(` ${file}`);
4135
- });
3026
+ for(let j = 0; j < N.length; j++)for(let k = 0; k < post.length && expansions.length < max; k++){
3027
+ const expansion = pre + N[j] + post[k];
3028
+ if (!isTop || isSequence || expansion) expansions.push(expansion);
4136
3029
  }
4137
- if (success) console.log('\n🎉 All files executed successfully!');
4138
- else console.log('\n⚠️ Some files failed or were not executed.');
4139
- return success;
4140
- }
4141
- constructor(config){
4142
- batch_runner_define_property(this, "config", void 0);
4143
- batch_runner_define_property(this, "results", []);
4144
- this.config = config;
4145
3030
  }
3031
+ return expansions;
4146
3032
  }
4147
- var brace_expansion = __webpack_require__("../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js");
4148
3033
  const MAX_PATTERN_LENGTH = 65536;
4149
3034
  const assertValidPattern = (pattern)=>{
4150
3035
  if ('string' != typeof pattern) throw new TypeError('invalid pattern');
@@ -4310,7 +3195,11 @@ var __webpack_modules__ = {
4310
3195
  true
4311
3196
  ];
4312
3197
  };
4313
- const unescape_unescape = (s, { windowsPathsNoEscape = false } = {})=>windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, '$1') : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
3198
+ const unescape_unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {})=>{
3199
+ if (magicalBraces) return windowsPathsNoEscape ? s.replace(/\[([^/\\])\]/g, '$1') : s.replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2').replace(/\\([^/])/g, '$1');
3200
+ return windowsPathsNoEscape ? s.replace(/\[([^/\\{}])\]/g, '$1') : s.replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2').replace(/\\([^/{}])/g, '$1');
3201
+ };
3202
+ var ast_a;
4314
3203
  const types = new Set([
4315
3204
  '!',
4316
3205
  '?',
@@ -4318,7 +3207,169 @@ var __webpack_modules__ = {
4318
3207
  '*',
4319
3208
  '@'
4320
3209
  ]);
4321
- const isExtglobType = (c)=>types.has(c);
3210
+ const isExtglobType = (c)=>types.has(c);
3211
+ const isExtglobAST = (c)=>isExtglobType(c.type);
3212
+ const adoptionMap = new Map([
3213
+ [
3214
+ '!',
3215
+ [
3216
+ '@'
3217
+ ]
3218
+ ],
3219
+ [
3220
+ '?',
3221
+ [
3222
+ '?',
3223
+ '@'
3224
+ ]
3225
+ ],
3226
+ [
3227
+ '@',
3228
+ [
3229
+ '@'
3230
+ ]
3231
+ ],
3232
+ [
3233
+ '*',
3234
+ [
3235
+ '*',
3236
+ '+',
3237
+ '?',
3238
+ '@'
3239
+ ]
3240
+ ],
3241
+ [
3242
+ '+',
3243
+ [
3244
+ '+',
3245
+ '@'
3246
+ ]
3247
+ ]
3248
+ ]);
3249
+ const adoptionWithSpaceMap = new Map([
3250
+ [
3251
+ '!',
3252
+ [
3253
+ '?'
3254
+ ]
3255
+ ],
3256
+ [
3257
+ '@',
3258
+ [
3259
+ '?'
3260
+ ]
3261
+ ],
3262
+ [
3263
+ '+',
3264
+ [
3265
+ '?',
3266
+ '*'
3267
+ ]
3268
+ ]
3269
+ ]);
3270
+ const adoptionAnyMap = new Map([
3271
+ [
3272
+ '!',
3273
+ [
3274
+ '?',
3275
+ '@'
3276
+ ]
3277
+ ],
3278
+ [
3279
+ '?',
3280
+ [
3281
+ '?',
3282
+ '@'
3283
+ ]
3284
+ ],
3285
+ [
3286
+ '@',
3287
+ [
3288
+ '?',
3289
+ '@'
3290
+ ]
3291
+ ],
3292
+ [
3293
+ '*',
3294
+ [
3295
+ '*',
3296
+ '+',
3297
+ '?',
3298
+ '@'
3299
+ ]
3300
+ ],
3301
+ [
3302
+ '+',
3303
+ [
3304
+ '+',
3305
+ '@',
3306
+ '?',
3307
+ '*'
3308
+ ]
3309
+ ]
3310
+ ]);
3311
+ const usurpMap = new Map([
3312
+ [
3313
+ '!',
3314
+ new Map([
3315
+ [
3316
+ '!',
3317
+ '@'
3318
+ ]
3319
+ ])
3320
+ ],
3321
+ [
3322
+ '?',
3323
+ new Map([
3324
+ [
3325
+ '*',
3326
+ '*'
3327
+ ],
3328
+ [
3329
+ '+',
3330
+ '*'
3331
+ ]
3332
+ ])
3333
+ ],
3334
+ [
3335
+ '@',
3336
+ new Map([
3337
+ [
3338
+ '!',
3339
+ '!'
3340
+ ],
3341
+ [
3342
+ '?',
3343
+ '?'
3344
+ ],
3345
+ [
3346
+ '@',
3347
+ '@'
3348
+ ],
3349
+ [
3350
+ '*',
3351
+ '*'
3352
+ ],
3353
+ [
3354
+ '+',
3355
+ '+'
3356
+ ]
3357
+ ])
3358
+ ],
3359
+ [
3360
+ '+',
3361
+ new Map([
3362
+ [
3363
+ '?',
3364
+ '*'
3365
+ ],
3366
+ [
3367
+ '*',
3368
+ '*'
3369
+ ]
3370
+ ])
3371
+ ]
3372
+ ]);
4322
3373
  const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
4323
3374
  const startNoDot = '(?!\\.)';
4324
3375
  const addPatternStart = new Set([
@@ -4334,6 +3385,7 @@ var __webpack_modules__ = {
4334
3385
  const qmark = '[^/]';
4335
3386
  const star = qmark + '*?';
4336
3387
  const starNoEmpty = qmark + '+?';
3388
+ let ID = 0;
4337
3389
  class ast_AST {
4338
3390
  type;
4339
3391
  #root;
@@ -4347,6 +3399,22 @@ var __webpack_modules__ = {
4347
3399
  #options;
4348
3400
  #toString;
4349
3401
  #emptyExt = false;
3402
+ id = ++ID;
3403
+ get depth() {
3404
+ return (this.#parent?.depth ?? -1) + 1;
3405
+ }
3406
+ [Symbol.for('nodejs.util.inspect.custom')]() {
3407
+ return {
3408
+ '@@type': 'AST',
3409
+ id: this.id,
3410
+ type: this.type,
3411
+ root: this.#root.id,
3412
+ parent: this.#parent?.id,
3413
+ depth: this.depth,
3414
+ partsLength: this.#parts.length,
3415
+ parts: this.#parts
3416
+ };
3417
+ }
4350
3418
  constructor(type, parent, options = {}){
4351
3419
  this.type = type;
4352
3420
  if (type) this.#hasMagic = true;
@@ -4365,9 +3433,7 @@ var __webpack_modules__ = {
4365
3433
  return this.#hasMagic;
4366
3434
  }
4367
3435
  toString() {
4368
- if (void 0 !== this.#toString) return this.#toString;
4369
- if (!this.type) return this.#toString = this.#parts.map((p)=>String(p)).join('');
4370
- return this.#toString = this.type + '(' + this.#parts.map((p)=>String(p)).join('|') + ')';
3436
+ return void 0 !== this.#toString ? this.#toString : this.type ? this.#toString = this.type + '(' + this.#parts.map((p)=>String(p)).join('|') + ')' : this.#toString = this.#parts.map((p)=>String(p)).join('');
4371
3437
  }
4372
3438
  #fillNegs() {
4373
3439
  if (this !== this.#root) throw new Error('should only call on root');
@@ -4392,7 +3458,7 @@ var __webpack_modules__ = {
4392
3458
  }
4393
3459
  push(...parts) {
4394
3460
  for (const p of parts)if ('' !== p) {
4395
- if ('string' != typeof p && !(p instanceof ast_AST && p.#parent === this)) throw new Error('invalid part: ' + p);
3461
+ if ('string' != typeof p && !(p instanceof ast_a && p.#parent === this)) throw new Error('invalid part: ' + p);
4396
3462
  this.#parts.push(p);
4397
3463
  }
4398
3464
  }
@@ -4412,7 +3478,7 @@ var __webpack_modules__ = {
4412
3478
  const p = this.#parent;
4413
3479
  for(let i = 0; i < this.#parentIndex; i++){
4414
3480
  const pp = p.#parts[i];
4415
- if (!(pp instanceof ast_AST && '!' === pp.type)) return false;
3481
+ if (!(pp instanceof ast_a && '!' === pp.type)) return false;
4416
3482
  }
4417
3483
  return true;
4418
3484
  }
@@ -4429,11 +3495,12 @@ var __webpack_modules__ = {
4429
3495
  else this.push(part.clone(this));
4430
3496
  }
4431
3497
  clone(parent) {
4432
- const c = new ast_AST(this.type, parent);
3498
+ const c = new ast_a(this.type, parent);
4433
3499
  for (const p of this.#parts)c.copyIn(p);
4434
3500
  return c;
4435
3501
  }
4436
- static #parseAST(str, ast, pos, opt) {
3502
+ static #parseAST(str, ast, pos, opt, extDepth) {
3503
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
4437
3504
  let escaping = false;
4438
3505
  let inBrace = false;
4439
3506
  let braceStart = -1;
@@ -4462,11 +3529,12 @@ var __webpack_modules__ = {
4462
3529
  acc += c;
4463
3530
  continue;
4464
3531
  }
4465
- if (!opt.noext && isExtglobType(c) && '(' === str.charAt(i)) {
3532
+ const doRecurse = !opt.noext && isExtglobType(c) && '(' === str.charAt(i) && extDepth <= maxDepth;
3533
+ if (doRecurse) {
4466
3534
  ast.push(acc);
4467
3535
  acc = '';
4468
- const ext = new ast_AST(c, ast);
4469
- i = ast_AST.#parseAST(str, ext, i, opt);
3536
+ const ext = new ast_a(c, ast);
3537
+ i = ast_a.#parseAST(str, ext, i, opt, extDepth + 1);
4470
3538
  ast.push(ext);
4471
3539
  continue;
4472
3540
  }
@@ -4476,7 +3544,7 @@ var __webpack_modules__ = {
4476
3544
  return i;
4477
3545
  }
4478
3546
  let i = pos + 1;
4479
- let part = new ast_AST(null, ast);
3547
+ let part = new ast_a(null, ast);
4480
3548
  const parts = [];
4481
3549
  let acc = '';
4482
3550
  while(i < str.length){
@@ -4500,19 +3568,21 @@ var __webpack_modules__ = {
4500
3568
  acc += c;
4501
3569
  continue;
4502
3570
  }
4503
- if (isExtglobType(c) && '(' === str.charAt(i)) {
3571
+ const doRecurse = !opt.noext && isExtglobType(c) && '(' === str.charAt(i) && (extDepth <= maxDepth || ast && ast.#canAdoptType(c));
3572
+ if (doRecurse) {
3573
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
4504
3574
  part.push(acc);
4505
3575
  acc = '';
4506
- const ext = new ast_AST(c, part);
3576
+ const ext = new ast_a(c, part);
4507
3577
  part.push(ext);
4508
- i = ast_AST.#parseAST(str, ext, i, opt);
3578
+ i = ast_a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
4509
3579
  continue;
4510
3580
  }
4511
3581
  if ('|' === c) {
4512
3582
  part.push(acc);
4513
3583
  acc = '';
4514
3584
  parts.push(part);
4515
- part = new ast_AST(null, ast);
3585
+ part = new ast_a(null, ast);
4516
3586
  continue;
4517
3587
  }
4518
3588
  if (')' === c) {
@@ -4531,9 +3601,55 @@ var __webpack_modules__ = {
4531
3601
  ];
4532
3602
  return i;
4533
3603
  }
3604
+ #canAdoptWithSpace(child) {
3605
+ return this.#canAdopt(child, adoptionWithSpaceMap);
3606
+ }
3607
+ #canAdopt(child, map = adoptionMap) {
3608
+ if (!child || 'object' != typeof child || null !== child.type || 1 !== child.#parts.length || null === this.type) return false;
3609
+ const gc = child.#parts[0];
3610
+ if (!gc || 'object' != typeof gc || null === gc.type) return false;
3611
+ return this.#canAdoptType(gc.type, map);
3612
+ }
3613
+ #canAdoptType(c, map = adoptionAnyMap) {
3614
+ return !!map.get(this.type)?.includes(c);
3615
+ }
3616
+ #adoptWithSpace(child, index) {
3617
+ const gc = child.#parts[0];
3618
+ const blank = new ast_a(null, gc, this.options);
3619
+ blank.#parts.push('');
3620
+ gc.push(blank);
3621
+ this.#adopt(child, index);
3622
+ }
3623
+ #adopt(child, index) {
3624
+ const gc = child.#parts[0];
3625
+ this.#parts.splice(index, 1, ...gc.#parts);
3626
+ for (const p of gc.#parts)if ('object' == typeof p) p.#parent = this;
3627
+ this.#toString = void 0;
3628
+ }
3629
+ #canUsurpType(c) {
3630
+ const m = usurpMap.get(this.type);
3631
+ return !!m?.has(c);
3632
+ }
3633
+ #canUsurp(child) {
3634
+ if (!child || 'object' != typeof child || null !== child.type || 1 !== child.#parts.length || null === this.type || 1 !== this.#parts.length) return false;
3635
+ const gc = child.#parts[0];
3636
+ if (!gc || 'object' != typeof gc || null === gc.type) return false;
3637
+ return this.#canUsurpType(gc.type);
3638
+ }
3639
+ #usurp(child) {
3640
+ const m = usurpMap.get(this.type);
3641
+ const gc = child.#parts[0];
3642
+ const nt = m?.get(gc.type);
3643
+ if (!nt) return false;
3644
+ this.#parts = gc.#parts;
3645
+ for (const p of this.#parts)if ('object' == typeof p) p.#parent = this;
3646
+ this.type = nt;
3647
+ this.#toString = void 0;
3648
+ this.#emptyExt = false;
3649
+ }
4534
3650
  static fromGlob(pattern, options = {}) {
4535
- const ast = new ast_AST(null, void 0, options);
4536
- ast_AST.#parseAST(pattern, ast, 0, options);
3651
+ const ast = new ast_a(null, void 0, options);
3652
+ ast_a.#parseAST(pattern, ast, 0, options, 0);
4537
3653
  return ast;
4538
3654
  }
4539
3655
  toMMPattern() {
@@ -4553,11 +3669,14 @@ var __webpack_modules__ = {
4553
3669
  }
4554
3670
  toRegExpSource(allowDot) {
4555
3671
  const dot = allowDot ?? !!this.#options.dot;
4556
- if (this.#root === this) this.#fillNegs();
4557
- if (!this.type) {
4558
- const noEmpty = this.isStart() && this.isEnd();
3672
+ if (this.#root === this) {
3673
+ this.#flatten();
3674
+ this.#fillNegs();
3675
+ }
3676
+ if (!isExtglobAST(this)) {
3677
+ const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s)=>'string' != typeof s);
4559
3678
  const src = this.#parts.map((p)=>{
4560
- const [re, _, hasMagic, uflag] = 'string' == typeof p ? ast_AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
3679
+ const [re, _, hasMagic, uflag] = 'string' == typeof p ? ast_a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
4561
3680
  this.#hasMagic = this.#hasMagic || hasMagic;
4562
3681
  this.#uflag = this.#uflag || uflag;
4563
3682
  return re;
@@ -4589,11 +3708,12 @@ var __webpack_modules__ = {
4589
3708
  let body = this.#partsToRegExp(dot);
4590
3709
  if (this.isStart() && this.isEnd() && !body && '!' !== this.type) {
4591
3710
  const s = this.toString();
4592
- this.#parts = [
3711
+ const me = this;
3712
+ me.#parts = [
4593
3713
  s
4594
3714
  ];
4595
- this.type = null;
4596
- this.#hasMagic = void 0;
3715
+ me.type = null;
3716
+ me.#hasMagic = void 0;
4597
3717
  return [
4598
3718
  s,
4599
3719
  unescape_unescape(this.toString()),
@@ -4617,6 +3737,32 @@ var __webpack_modules__ = {
4617
3737
  this.#uflag
4618
3738
  ];
4619
3739
  }
3740
+ #flatten() {
3741
+ if (isExtglobAST(this)) {
3742
+ let iterations = 0;
3743
+ let done = false;
3744
+ do {
3745
+ done = true;
3746
+ for(let i = 0; i < this.#parts.length; i++){
3747
+ const c = this.#parts[i];
3748
+ if ('object' == typeof c) {
3749
+ c.#flatten();
3750
+ if (this.#canAdopt(c)) {
3751
+ done = false;
3752
+ this.#adopt(c, i);
3753
+ } else if (this.#canAdoptWithSpace(c)) {
3754
+ done = false;
3755
+ this.#adoptWithSpace(c, i);
3756
+ } else if (this.#canUsurp(c)) {
3757
+ done = false;
3758
+ this.#usurp(c);
3759
+ }
3760
+ }
3761
+ }
3762
+ }while (!done && ++iterations < 10);
3763
+ } else for (const p of this.#parts)if ('object' == typeof p) p.#flatten();
3764
+ this.#toString = void 0;
3765
+ }
4620
3766
  #partsToRegExp(dot) {
4621
3767
  return this.#parts.map((p)=>{
4622
3768
  if ('string' == typeof p) throw new Error('string type in extglob ast??');
@@ -4629,6 +3775,7 @@ var __webpack_modules__ = {
4629
3775
  let escaping = false;
4630
3776
  let re = '';
4631
3777
  let uflag = false;
3778
+ let inStar = false;
4632
3779
  for(let i = 0; i < glob.length; i++){
4633
3780
  const c = glob.charAt(i);
4634
3781
  if (escaping) {
@@ -4636,6 +3783,14 @@ var __webpack_modules__ = {
4636
3783
  re += (reSpecials.has(c) ? '\\' : '') + c;
4637
3784
  continue;
4638
3785
  }
3786
+ if ('*' === c) {
3787
+ if (inStar) continue;
3788
+ inStar = true;
3789
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
3790
+ hasMagic = true;
3791
+ continue;
3792
+ }
3793
+ inStar = false;
4639
3794
  if ('\\' === c) {
4640
3795
  if (i === glob.length - 1) re += '\\\\';
4641
3796
  else escaping = true;
@@ -4651,12 +3806,6 @@ var __webpack_modules__ = {
4651
3806
  continue;
4652
3807
  }
4653
3808
  }
4654
- if ('*' === c) {
4655
- if (noEmpty && '*' === glob) re += starNoEmpty;
4656
- else re += star;
4657
- hasMagic = true;
4658
- continue;
4659
- }
4660
3809
  if ('?' === c) {
4661
3810
  re += qmark;
4662
3811
  hasMagic = true;
@@ -4672,13 +3821,17 @@ var __webpack_modules__ = {
4672
3821
  ];
4673
3822
  }
4674
3823
  }
4675
- const escape_escape = (s, { windowsPathsNoEscape = false } = {})=>windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&');
3824
+ ast_a = ast_AST;
3825
+ const escape_escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {})=>{
3826
+ if (magicalBraces) return windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, '[$&]') : s.replace(/[?*()[\]\\{}]/g, '\\$&');
3827
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&');
3828
+ };
4676
3829
  const minimatch = (p, pattern, options = {})=>{
4677
3830
  assertValidPattern(pattern);
4678
3831
  if (!options.nocomment && '#' === pattern.charAt(0)) return false;
4679
3832
  return new esm_Minimatch(pattern, options).match(p);
4680
3833
  };
4681
- const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
3834
+ const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
4682
3835
  const starDotExtTest = (ext)=>(f)=>!f.startsWith('.') && f.endsWith(ext);
4683
3836
  const starDotExtTestDot = (ext)=>(f)=>f.endsWith(ext);
4684
3837
  const starDotExtTestNocase = (ext)=>{
@@ -4697,7 +3850,7 @@ var __webpack_modules__ = {
4697
3850
  const starRE = /^\*+$/;
4698
3851
  const starTest = (f)=>0 !== f.length && !f.startsWith('.');
4699
3852
  const starTestDot = (f)=>0 !== f.length && '.' !== f && '..' !== f;
4700
- const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
3853
+ const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
4701
3854
  const qmarksTestNocase = ([$0, ext = ''])=>{
4702
3855
  const noext = qmarksTestNoExt([
4703
3856
  $0
@@ -4792,7 +3945,9 @@ var __webpack_modules__ = {
4792
3945
  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) return [
4793
3946
  pattern
4794
3947
  ];
4795
- return brace_expansion(pattern);
3948
+ return expand(pattern, {
3949
+ max: options.braceExpandMax
3950
+ });
4796
3951
  };
4797
3952
  minimatch.braceExpand = braceExpand;
4798
3953
  const makeRe = (pattern, options = {})=>new esm_Minimatch(pattern, options).makeRe();
@@ -4823,15 +3978,18 @@ var __webpack_modules__ = {
4823
3978
  isWindows;
4824
3979
  platform;
4825
3980
  windowsNoMagicRoot;
3981
+ maxGlobstarRecursion;
4826
3982
  regexp;
4827
3983
  constructor(pattern, options = {}){
4828
3984
  assertValidPattern(pattern);
4829
3985
  options = options || {};
4830
3986
  this.options = options;
3987
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
4831
3988
  this.pattern = pattern;
4832
3989
  this.platform = options.platform || defaultPlatform;
4833
3990
  this.isWindows = 'win32' === this.platform;
4834
- this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || false === options.allowWindowsEscape;
3991
+ const awe = "allowWindowsEscape";
3992
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || false === options[awe];
4835
3993
  if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, '/');
4836
3994
  this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
4837
3995
  this.regexp = null;
@@ -4898,7 +4056,7 @@ var __webpack_modules__ = {
4898
4056
  }
4899
4057
  preprocess(globParts) {
4900
4058
  if (this.options.noglobstar) {
4901
- for(let i = 0; i < globParts.length; i++)for(let j = 0; j < globParts[i].length; j++)if ('**' === globParts[i][j]) globParts[i][j] = '*';
4059
+ for (const partset of globParts)for(let j = 0; j < partset.length; j++)if ('**' === partset[j]) partset[j] = '*';
4902
4060
  }
4903
4061
  const { optimizationLevel = 1 } = this.options;
4904
4062
  if (optimizationLevel >= 2) {
@@ -4961,7 +4119,7 @@ var __webpack_modules__ = {
4961
4119
  let dd = 0;
4962
4120
  while(-1 !== (dd = parts.indexOf('..', dd + 1))){
4963
4121
  const p = parts[dd - 1];
4964
- if (p && '.' !== p && '..' !== p && '**' !== p) {
4122
+ if (p && '.' !== p && '..' !== p && '**' !== p && !(this.isWindows && /^[a-z]:$/i.test(p))) {
4965
4123
  didSomething = true;
4966
4124
  parts.splice(dd - 1, 2);
4967
4125
  dd -= 2;
@@ -5083,7 +4241,8 @@ var __webpack_modules__ = {
5083
4241
  this.negate = negate;
5084
4242
  }
5085
4243
  matchOne(file, pattern, partial = false) {
5086
- const options = this.options;
4244
+ let fileStartIndex = 0;
4245
+ let patternStartIndex = 0;
5087
4246
  if (this.isWindows) {
5088
4247
  const fileDrive = 'string' == typeof file[0] && /^[a-z]:$/i.test(file[0]);
5089
4248
  const fileUNC = !fileDrive && '' === file[0] && '' === file[1] && '?' === file[2] && /^[a-z]:$/i.test(file[3]);
@@ -5098,57 +4257,116 @@ var __webpack_modules__ = {
5098
4257
  ];
5099
4258
  if (fd.toLowerCase() === pd.toLowerCase()) {
5100
4259
  pattern[pdi] = fd;
5101
- if (pdi > fdi) pattern = pattern.slice(pdi);
5102
- else if (fdi > pdi) file = file.slice(fdi);
4260
+ patternStartIndex = pdi;
4261
+ fileStartIndex = fdi;
5103
4262
  }
5104
4263
  }
5105
4264
  }
5106
4265
  const { optimizationLevel = 1 } = this.options;
5107
4266
  if (optimizationLevel >= 2) file = this.levelTwoFileOptimize(file);
5108
- this.debug('matchOne', this, {
5109
- file,
5110
- pattern
5111
- });
5112
- this.debug('matchOne', file.length, pattern.length);
5113
- for(var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++){
4267
+ if (pattern.includes(GLOBSTAR)) return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
4268
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
4269
+ }
4270
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
4271
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
4272
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
4273
+ const [head, body, tail] = partial ? [
4274
+ pattern.slice(patternIndex, firstgs),
4275
+ pattern.slice(firstgs + 1),
4276
+ []
4277
+ ] : [
4278
+ pattern.slice(patternIndex, firstgs),
4279
+ pattern.slice(firstgs + 1, lastgs),
4280
+ pattern.slice(lastgs + 1)
4281
+ ];
4282
+ if (head.length) {
4283
+ const fileHead = file.slice(fileIndex, fileIndex + head.length);
4284
+ if (!this.#matchOne(fileHead, head, partial, 0, 0)) return false;
4285
+ fileIndex += head.length;
4286
+ patternIndex += head.length;
4287
+ }
4288
+ let fileTailMatch = 0;
4289
+ if (tail.length) {
4290
+ if (tail.length + fileIndex > file.length) return false;
4291
+ let tailStart = file.length - tail.length;
4292
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) fileTailMatch = tail.length;
4293
+ else {
4294
+ if ('' !== file[file.length - 1] || fileIndex + tail.length === file.length) return false;
4295
+ tailStart--;
4296
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) return false;
4297
+ fileTailMatch = tail.length + 1;
4298
+ }
4299
+ }
4300
+ if (!body.length) {
4301
+ let sawSome = !!fileTailMatch;
4302
+ for(let i = fileIndex; i < file.length - fileTailMatch; i++){
4303
+ const f = String(file[i]);
4304
+ sawSome = true;
4305
+ if ('.' === f || '..' === f || !this.options.dot && f.startsWith('.')) return false;
4306
+ }
4307
+ return partial || sawSome;
4308
+ }
4309
+ const bodySegments = [
4310
+ [
4311
+ [],
4312
+ 0
4313
+ ]
4314
+ ];
4315
+ let currentBody = bodySegments[0];
4316
+ let nonGsParts = 0;
4317
+ const nonGsPartsSums = [
4318
+ 0
4319
+ ];
4320
+ for (const b of body)if (b === GLOBSTAR) {
4321
+ nonGsPartsSums.push(nonGsParts);
4322
+ currentBody = [
4323
+ [],
4324
+ 0
4325
+ ];
4326
+ bodySegments.push(currentBody);
4327
+ } else {
4328
+ currentBody[0].push(b);
4329
+ nonGsParts++;
4330
+ }
4331
+ let i = bodySegments.length - 1;
4332
+ const fileLength = file.length - fileTailMatch;
4333
+ for (const b of bodySegments)b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
4334
+ return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
4335
+ }
4336
+ #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
4337
+ const bs = bodySegments[bodyIndex];
4338
+ if (!bs) {
4339
+ for(let i = fileIndex; i < file.length; i++){
4340
+ sawTail = true;
4341
+ const f = file[i];
4342
+ if ('.' === f || '..' === f || !this.options.dot && f.startsWith('.')) return false;
4343
+ }
4344
+ return sawTail;
4345
+ }
4346
+ const [body, after] = bs;
4347
+ while(fileIndex <= after){
4348
+ const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
4349
+ if (m && globStarDepth < this.maxGlobstarRecursion) {
4350
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
4351
+ if (false !== sub) return sub;
4352
+ }
4353
+ const f = file[fileIndex];
4354
+ if ('.' === f || '..' === f || !this.options.dot && f.startsWith('.')) return false;
4355
+ fileIndex++;
4356
+ }
4357
+ return partial || null;
4358
+ }
4359
+ #matchOne(file, pattern, partial, fileIndex, patternIndex) {
4360
+ let fi;
4361
+ let pi;
4362
+ let pl;
4363
+ let fl;
4364
+ for(fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++){
5114
4365
  this.debug('matchOne loop');
5115
- var p = pattern[pi];
5116
- var f = file[fi];
4366
+ let p = pattern[pi];
4367
+ let f = file[fi];
5117
4368
  this.debug(pattern, p, f);
5118
- if (false === p) return false;
5119
- if (p === GLOBSTAR) {
5120
- this.debug('GLOBSTAR', [
5121
- pattern,
5122
- p,
5123
- f
5124
- ]);
5125
- var fr = fi;
5126
- var pr = pi + 1;
5127
- if (pr === pl) {
5128
- this.debug('** at the end');
5129
- for(; fi < fl; fi++)if ('.' === file[fi] || '..' === file[fi] || !options.dot && '.' === file[fi].charAt(0)) return false;
5130
- return true;
5131
- }
5132
- while(fr < fl){
5133
- var swallowee = file[fr];
5134
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
5135
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
5136
- this.debug('globstar found match!', fr, fl, swallowee);
5137
- return true;
5138
- }
5139
- if ('.' === swallowee || '..' === swallowee || !options.dot && '.' === swallowee.charAt(0)) {
5140
- this.debug('dot detected!', file, fr, pattern, pr);
5141
- break;
5142
- }
5143
- this.debug('globstar swallow a segment, and continue');
5144
- fr++;
5145
- }
5146
- if (partial) {
5147
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
5148
- if (fr === fl) return true;
5149
- }
5150
- return false;
5151
- }
4369
+ if (false === p || p === GLOBSTAR) return false;
5152
4370
  let hit;
5153
4371
  if ('string' == typeof p) {
5154
4372
  hit = f === p;
@@ -5208,13 +4426,19 @@ var __webpack_modules__ = {
5208
4426
  if (p !== GLOBSTAR || prev === GLOBSTAR) return;
5209
4427
  if (void 0 === prev) if (void 0 !== next && next !== GLOBSTAR) pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
5210
4428
  else pp[i] = twoStar;
5211
- else if (void 0 === next) pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
4429
+ else if (void 0 === next) pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
5212
4430
  else if (next !== GLOBSTAR) {
5213
4431
  pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
5214
4432
  pp[i + 1] = GLOBSTAR;
5215
4433
  }
5216
4434
  });
5217
- return pp.filter((p)=>p !== GLOBSTAR).join('/');
4435
+ const filtered = pp.filter((p)=>p !== GLOBSTAR);
4436
+ if (this.partial && filtered.length >= 1) {
4437
+ const prefixes = [];
4438
+ for(let i = 1; i <= filtered.length; i++)prefixes.push(filtered.slice(0, i).join('/'));
4439
+ return '(?:' + prefixes.join('|') + ')';
4440
+ }
4441
+ return filtered.join('/');
5218
4442
  }).join('|');
5219
4443
  const [open, close] = set.length > 1 ? [
5220
4444
  '(?:',
@@ -5224,19 +4448,20 @@ var __webpack_modules__ = {
5224
4448
  ''
5225
4449
  ];
5226
4450
  re = '^' + open + re + close + '$';
4451
+ if (this.partial) re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
5227
4452
  if (this.negate) re = '^(?!' + re + ').+$';
5228
4453
  try {
5229
4454
  this.regexp = new RegExp(re, [
5230
4455
  ...flags
5231
4456
  ].join(''));
5232
- } catch (ex) {
4457
+ } catch {
5233
4458
  this.regexp = false;
5234
4459
  }
5235
4460
  return this.regexp;
5236
4461
  }
5237
4462
  slashSplit(p) {
5238
4463
  if (this.preserveMultipleSlashes) return p.split('/');
5239
- if (this.isWindows && /^\/\/[^\/]+/.test(p)) return [
4464
+ if (this.isWindows && /^\/\/[^/]+/.test(p)) return [
5240
4465
  '',
5241
4466
  ...p.split(/\/+/)
5242
4467
  ];
@@ -5255,8 +4480,7 @@ var __webpack_modules__ = {
5255
4480
  this.debug(this.pattern, 'set', set);
5256
4481
  let filename = ff[ff.length - 1];
5257
4482
  if (!filename) for(let i = ff.length - 2; !filename && i >= 0; i--)filename = ff[i];
5258
- for(let i = 0; i < set.length; i++){
5259
- const pattern = set[i];
4483
+ for (const pattern of set){
5260
4484
  let file = ff;
5261
4485
  if (options.matchBase && 1 === pattern.length) file = [
5262
4486
  filename
@@ -5278,85 +4502,46 @@ var __webpack_modules__ = {
5278
4502
  minimatch.Minimatch = esm_Minimatch;
5279
4503
  minimatch.escape = escape_escape;
5280
4504
  minimatch.unescape = unescape_unescape;
5281
- const perf = 'object' == typeof performance && performance && 'function' == typeof performance.now ? performance : Date;
5282
- const warned = new Set();
5283
- const PROCESS = 'object' == typeof process && process ? process : {};
5284
- const emitWarning = (msg, type, code, fn)=>{
5285
- 'function' == typeof PROCESS.emitWarning ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
5286
- };
5287
- let AC = globalThis.AbortController;
5288
- let AS = globalThis.AbortSignal;
5289
- if (void 0 === AC) {
5290
- AS = class {
5291
- onabort;
5292
- _onabort = [];
5293
- reason;
5294
- aborted = false;
5295
- addEventListener(_, fn) {
5296
- this._onabort.push(fn);
5297
- }
5298
- };
5299
- AC = class {
5300
- constructor(){
5301
- warnACPolyfill();
5302
- }
5303
- signal = new AS();
5304
- abort(reason) {
5305
- if (this.signal.aborted) return;
5306
- this.signal.reason = reason;
5307
- this.signal.aborted = true;
5308
- for (const fn of this.signal._onabort)fn(reason);
5309
- this.signal.onabort?.(reason);
5310
- }
5311
- };
5312
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
5313
- const warnACPolyfill = ()=>{
5314
- if (!printACPolyfillWarning) return;
5315
- printACPolyfillWarning = false;
5316
- emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
5317
- };
5318
- }
5319
- const shouldWarn = (code)=>!warned.has(code);
5320
- Symbol('type');
5321
- const isPosInt = (n)=>n && n === Math.floor(n) && n > 0 && isFinite(n);
5322
- const getUintArray = (max)=>isPosInt(max) ? max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null : null;
5323
- class ZeroArray extends Array {
5324
- constructor(size){
5325
- super(size);
5326
- this.fill(0);
5327
- }
5328
- }
5329
- class Stack {
4505
+ var S = channel("lru-cache:metrics"), W = tracingChannel("lru-cache");
4506
+ var D = ()=>S.hasSubscribers || W.hasSubscribers, G = "object" == typeof performance && performance && "function" == typeof performance.now ? performance : Date, M = new Set, C = "object" == typeof process && process ? process : {}, P = (u, e1, t1, i)=>{
4507
+ "function" == typeof C.emitWarning ? C.emitWarning(u, e1, t1, i) : console.error(`[${t1}] ${e1}: ${u}`);
4508
+ }, H = (u)=>!M.has(u), F = (Symbol("type"), (u)=>!!u && u === Math.floor(u) && u > 0 && isFinite(u)), U = (u)=>F(u) ? u <= Math.pow(2, 8) ? Uint8Array : u <= Math.pow(2, 16) ? Uint16Array : u <= Math.pow(2, 32) ? Uint32Array : u <= Number.MAX_SAFE_INTEGER ? O : null : null, O = class extends Array {
4509
+ constructor(e1){
4510
+ super(e1), this.fill(0);
4511
+ }
4512
+ }, R = class u {
5330
4513
  heap;
5331
4514
  length;
5332
- static #constructing = false;
5333
- static create(max) {
5334
- const HeapCls = getUintArray(max);
5335
- if (!HeapCls) return [];
5336
- Stack.#constructing = true;
5337
- const s = new Stack(max, HeapCls);
5338
- Stack.#constructing = false;
5339
- return s;
5340
- }
5341
- constructor(max, HeapCls){
5342
- if (!Stack.#constructing) throw new TypeError('instantiate Stack using Stack.create(n)');
5343
- this.heap = new HeapCls(max);
5344
- this.length = 0;
5345
- }
5346
- push(n) {
5347
- this.heap[this.length++] = n;
4515
+ static #o = !1;
4516
+ static create(e1) {
4517
+ let t1 = U(e1);
4518
+ if (!t1) return [];
4519
+ u.#o = !0;
4520
+ let i = new u(e1, t1);
4521
+ return u.#o = !1, i;
4522
+ }
4523
+ constructor(e1, t1){
4524
+ if (!u.#o) throw new TypeError("instantiate Stack using Stack.create(n)");
4525
+ this.heap = new t1(e1), this.length = 0;
4526
+ }
4527
+ push(e1) {
4528
+ this.heap[this.length++] = e1;
5348
4529
  }
5349
4530
  pop() {
5350
4531
  return this.heap[--this.length];
5351
4532
  }
5352
- }
5353
- class LRUCache {
5354
- #max;
5355
- #maxSize;
5356
- #dispose;
5357
- #disposeAfter;
5358
- #fetchMethod;
5359
- #memoMethod;
4533
+ }, L = class u {
4534
+ #o;
4535
+ #u;
4536
+ #w;
4537
+ #D;
4538
+ #S;
4539
+ #M;
4540
+ #U;
4541
+ #m;
4542
+ get perf() {
4543
+ return this.#m;
4544
+ }
5360
4545
  ttl;
5361
4546
  ttlResolution;
5362
4547
  ttlAutopurge;
@@ -5372,823 +4557,613 @@ var __webpack_modules__ = {
5372
4557
  allowStaleOnFetchAbort;
5373
4558
  allowStaleOnFetchRejection;
5374
4559
  ignoreFetchAbort;
5375
- #size;
5376
- #calculatedSize;
5377
- #keyMap;
5378
- #keyList;
5379
- #valList;
5380
- #next;
5381
- #prev;
5382
- #head;
5383
- #tail;
5384
- #free;
5385
- #disposed;
5386
- #sizes;
5387
- #starts;
5388
- #ttls;
5389
- #hasDispose;
5390
- #hasFetchMethod;
5391
- #hasDisposeAfter;
5392
- static unsafeExposeInternals(c) {
4560
+ #n;
4561
+ #b;
4562
+ #s;
4563
+ #i;
4564
+ #t;
4565
+ #a;
4566
+ #c;
4567
+ #l;
4568
+ #h;
4569
+ #y;
4570
+ #r;
4571
+ #_;
4572
+ #F;
4573
+ #d;
4574
+ #g;
4575
+ #T;
4576
+ #W;
4577
+ #f;
4578
+ #j;
4579
+ static unsafeExposeInternals(e1) {
5393
4580
  return {
5394
- starts: c.#starts,
5395
- ttls: c.#ttls,
5396
- sizes: c.#sizes,
5397
- keyMap: c.#keyMap,
5398
- keyList: c.#keyList,
5399
- valList: c.#valList,
5400
- next: c.#next,
5401
- prev: c.#prev,
4581
+ starts: e1.#F,
4582
+ ttls: e1.#d,
4583
+ autopurgeTimers: e1.#g,
4584
+ sizes: e1.#_,
4585
+ keyMap: e1.#s,
4586
+ keyList: e1.#i,
4587
+ valList: e1.#t,
4588
+ next: e1.#a,
4589
+ prev: e1.#c,
5402
4590
  get head () {
5403
- return c.#head;
4591
+ return e1.#l;
5404
4592
  },
5405
4593
  get tail () {
5406
- return c.#tail;
4594
+ return e1.#h;
5407
4595
  },
5408
- free: c.#free,
5409
- isBackgroundFetch: (p)=>c.#isBackgroundFetch(p),
5410
- backgroundFetch: (k, index, options, context)=>c.#backgroundFetch(k, index, options, context),
5411
- moveToTail: (index)=>c.#moveToTail(index),
5412
- indexes: (options)=>c.#indexes(options),
5413
- rindexes: (options)=>c.#rindexes(options),
5414
- isStale: (index)=>c.#isStale(index)
4596
+ free: e1.#y,
4597
+ isBackgroundFetch: (t1)=>e1.#e(t1),
4598
+ backgroundFetch: (t1, i, s, n)=>e1.#P(t1, i, s, n),
4599
+ moveToTail: (t1)=>e1.#L(t1),
4600
+ indexes: (t1)=>e1.#A(t1),
4601
+ rindexes: (t1)=>e1.#z(t1),
4602
+ isStale: (t1)=>e1.#p(t1)
5415
4603
  };
5416
4604
  }
5417
4605
  get max() {
5418
- return this.#max;
4606
+ return this.#o;
5419
4607
  }
5420
4608
  get maxSize() {
5421
- return this.#maxSize;
4609
+ return this.#u;
5422
4610
  }
5423
4611
  get calculatedSize() {
5424
- return this.#calculatedSize;
4612
+ return this.#b;
5425
4613
  }
5426
4614
  get size() {
5427
- return this.#size;
4615
+ return this.#n;
5428
4616
  }
5429
4617
  get fetchMethod() {
5430
- return this.#fetchMethod;
4618
+ return this.#M;
5431
4619
  }
5432
4620
  get memoMethod() {
5433
- return this.#memoMethod;
4621
+ return this.#U;
5434
4622
  }
5435
4623
  get dispose() {
5436
- return this.#dispose;
4624
+ return this.#w;
5437
4625
  }
5438
- get disposeAfter() {
5439
- return this.#disposeAfter;
4626
+ get onInsert() {
4627
+ return this.#D;
5440
4628
  }
5441
- constructor(options){
5442
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
5443
- if (0 !== max && !isPosInt(max)) throw new TypeError('max option must be a nonnegative integer');
5444
- const UintArray = max ? getUintArray(max) : Array;
5445
- if (!UintArray) throw new Error('invalid max value: ' + max);
5446
- this.#max = max;
5447
- this.#maxSize = maxSize;
5448
- this.maxEntrySize = maxEntrySize || this.#maxSize;
5449
- this.sizeCalculation = sizeCalculation;
5450
- if (this.sizeCalculation) {
5451
- if (!this.#maxSize && !this.maxEntrySize) throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
5452
- if ('function' != typeof this.sizeCalculation) throw new TypeError('sizeCalculation set to non-function');
5453
- }
5454
- if (void 0 !== memoMethod && 'function' != typeof memoMethod) throw new TypeError('memoMethod must be a function if defined');
5455
- this.#memoMethod = memoMethod;
5456
- if (void 0 !== fetchMethod && 'function' != typeof fetchMethod) throw new TypeError('fetchMethod must be a function if specified');
5457
- this.#fetchMethod = fetchMethod;
5458
- this.#hasFetchMethod = !!fetchMethod;
5459
- this.#keyMap = new Map();
5460
- this.#keyList = new Array(max).fill(void 0);
5461
- this.#valList = new Array(max).fill(void 0);
5462
- this.#next = new UintArray(max);
5463
- this.#prev = new UintArray(max);
5464
- this.#head = 0;
5465
- this.#tail = 0;
5466
- this.#free = Stack.create(max);
5467
- this.#size = 0;
5468
- this.#calculatedSize = 0;
5469
- if ('function' == typeof dispose) this.#dispose = dispose;
5470
- if ('function' == typeof disposeAfter) {
5471
- this.#disposeAfter = disposeAfter;
5472
- this.#disposed = [];
5473
- } else {
5474
- this.#disposeAfter = void 0;
5475
- this.#disposed = void 0;
5476
- }
5477
- this.#hasDispose = !!this.#dispose;
5478
- this.#hasDisposeAfter = !!this.#disposeAfter;
5479
- this.noDisposeOnSet = !!noDisposeOnSet;
5480
- this.noUpdateTTL = !!noUpdateTTL;
5481
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
5482
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
5483
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
5484
- this.ignoreFetchAbort = !!ignoreFetchAbort;
5485
- if (0 !== this.maxEntrySize) {
5486
- if (0 !== this.#maxSize) {
5487
- if (!isPosInt(this.#maxSize)) throw new TypeError('maxSize must be a positive integer if specified');
5488
- }
5489
- if (!isPosInt(this.maxEntrySize)) throw new TypeError('maxEntrySize must be a positive integer if specified');
5490
- this.#initializeSizeTracking();
5491
- }
5492
- this.allowStale = !!allowStale;
5493
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
5494
- this.updateAgeOnGet = !!updateAgeOnGet;
5495
- this.updateAgeOnHas = !!updateAgeOnHas;
5496
- this.ttlResolution = isPosInt(ttlResolution) || 0 === ttlResolution ? ttlResolution : 1;
5497
- this.ttlAutopurge = !!ttlAutopurge;
5498
- this.ttl = ttl || 0;
5499
- if (this.ttl) {
5500
- if (!isPosInt(this.ttl)) throw new TypeError('ttl must be a positive integer if specified');
5501
- this.#initializeTTLTracking();
5502
- }
5503
- if (0 === this.#max && 0 === this.ttl && 0 === this.#maxSize) throw new TypeError('At least one of max, maxSize, or ttl is required');
5504
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
5505
- const code = 'LRU_CACHE_UNBOUNDED';
5506
- if (shouldWarn(code)) {
5507
- warned.add(code);
5508
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
5509
- emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
5510
- }
5511
- }
5512
- }
5513
- getRemainingTTL(key) {
5514
- return this.#keyMap.has(key) ? 1 / 0 : 0;
5515
- }
5516
- #initializeTTLTracking() {
5517
- const ttls = new ZeroArray(this.#max);
5518
- const starts = new ZeroArray(this.#max);
5519
- this.#ttls = ttls;
5520
- this.#starts = starts;
5521
- this.#setItemTTL = (index, ttl, start = perf.now())=>{
5522
- starts[index] = 0 !== ttl ? start : 0;
5523
- ttls[index] = ttl;
5524
- if (0 !== ttl && this.ttlAutopurge) {
5525
- const t1 = setTimeout(()=>{
5526
- if (this.#isStale(index)) this.#delete(this.#keyList[index], 'expire');
5527
- }, ttl + 1);
5528
- if (t1.unref) t1.unref();
5529
- }
5530
- };
5531
- this.#updateItemAge = (index)=>{
5532
- starts[index] = 0 !== ttls[index] ? perf.now() : 0;
4629
+ get disposeAfter() {
4630
+ return this.#S;
4631
+ }
4632
+ constructor(e1){
4633
+ let { max: t1 = 0, ttl: i, ttlResolution: s = 1, ttlAutopurge: n, updateAgeOnGet: o, updateAgeOnHas: r, allowStale: h, dispose: l, onInsert: c, disposeAfter: f, noDisposeOnSet: g, noUpdateTTL: p, maxSize: T = 0, maxEntrySize: w = 0, sizeCalculation: y, fetchMethod: a, memoMethod: m, noDeleteOnFetchRejection: _, noDeleteOnStaleGet: b, allowStaleOnFetchRejection: d, allowStaleOnFetchAbort: A, ignoreFetchAbort: z, perf: x } = e1;
4634
+ if (void 0 !== x && "function" != typeof x?.now) throw new TypeError("perf option must have a now() method if specified");
4635
+ if (this.#m = x ?? G, 0 !== t1 && !F(t1)) throw new TypeError("max option must be a nonnegative integer");
4636
+ let v = t1 ? U(t1) : Array;
4637
+ if (!v) throw new Error("invalid max value: " + t1);
4638
+ if (this.#o = t1, this.#u = T, this.maxEntrySize = w || this.#u, this.sizeCalculation = y, this.sizeCalculation) {
4639
+ if (!this.#u && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
4640
+ if ("function" != typeof this.sizeCalculation) throw new TypeError("sizeCalculation set to non-function");
4641
+ }
4642
+ if (void 0 !== m && "function" != typeof m) throw new TypeError("memoMethod must be a function if defined");
4643
+ if (this.#U = m, void 0 !== a && "function" != typeof a) throw new TypeError("fetchMethod must be a function if specified");
4644
+ if (this.#M = a, this.#W = !!a, this.#s = new Map, this.#i = Array.from({
4645
+ length: t1
4646
+ }).fill(void 0), this.#t = Array.from({
4647
+ length: t1
4648
+ }).fill(void 0), this.#a = new v(t1), this.#c = new v(t1), this.#l = 0, this.#h = 0, this.#y = R.create(t1), this.#n = 0, this.#b = 0, "function" == typeof l && (this.#w = l), "function" == typeof c && (this.#D = c), "function" == typeof f ? (this.#S = f, this.#r = []) : (this.#S = void 0, this.#r = void 0), this.#T = !!this.#w, this.#j = !!this.#D, this.#f = !!this.#S, this.noDisposeOnSet = !!g, this.noUpdateTTL = !!p, this.noDeleteOnFetchRejection = !!_, this.allowStaleOnFetchRejection = !!d, this.allowStaleOnFetchAbort = !!A, this.ignoreFetchAbort = !!z, 0 !== this.maxEntrySize) {
4649
+ if (0 !== this.#u && !F(this.#u)) throw new TypeError("maxSize must be a positive integer if specified");
4650
+ if (!F(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified");
4651
+ this.#X();
4652
+ }
4653
+ if (this.allowStale = !!h, this.noDeleteOnStaleGet = !!b, this.updateAgeOnGet = !!o, this.updateAgeOnHas = !!r, this.ttlResolution = F(s) || 0 === s ? s : 1, this.ttlAutopurge = !!n, this.ttl = i || 0, this.ttl) {
4654
+ if (!F(this.ttl)) throw new TypeError("ttl must be a positive integer if specified");
4655
+ this.#H();
4656
+ }
4657
+ if (0 === this.#o && 0 === this.ttl && 0 === this.#u) throw new TypeError("At least one of max, maxSize, or ttl is required");
4658
+ if (!this.ttlAutopurge && !this.#o && !this.#u) {
4659
+ let E = "LRU_CACHE_UNBOUNDED";
4660
+ H(E) && (M.add(E), P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", E, u));
4661
+ }
4662
+ }
4663
+ getRemainingTTL(e1) {
4664
+ return this.#s.has(e1) ? 1 / 0 : 0;
4665
+ }
4666
+ #H() {
4667
+ let e1 = new O(this.#o), t1 = new O(this.#o);
4668
+ this.#d = e1, this.#F = t1;
4669
+ let i = this.ttlAutopurge ? Array.from({
4670
+ length: this.#o
4671
+ }) : void 0;
4672
+ this.#g = i, this.#N = (r, h, l = this.#m.now())=>{
4673
+ t1[r] = 0 !== h ? l : 0, e1[r] = h, s(r, h);
4674
+ }, this.#x = (r)=>{
4675
+ t1[r] = 0 !== e1[r] ? this.#m.now() : 0, s(r, e1[r]);
5533
4676
  };
5534
- this.#statusTTL = (status, index)=>{
5535
- if (ttls[index]) {
5536
- const ttl = ttls[index];
5537
- const start = starts[index];
5538
- if (!ttl || !start) return;
5539
- status.ttl = ttl;
5540
- status.start = start;
5541
- status.now = cachedNow || getNow();
5542
- const age = status.now - start;
5543
- status.remainingTTL = ttl - age;
4677
+ let s = this.ttlAutopurge ? (r, h)=>{
4678
+ if (i?.[r] && (clearTimeout(i[r]), i[r] = void 0), h && 0 !== h && i) {
4679
+ let l = setTimeout(()=>{
4680
+ this.#p(r) && this.#v(this.#i[r], "expire");
4681
+ }, h + 1);
4682
+ l.unref && l.unref(), i[r] = l;
4683
+ }
4684
+ } : ()=>{};
4685
+ this.#E = (r, h)=>{
4686
+ if (e1[h]) {
4687
+ let l = e1[h], c = t1[h];
4688
+ if (!l || !c) return;
4689
+ r.ttl = l, r.start = c, r.now = n || o();
4690
+ let f = r.now - c;
4691
+ r.remainingTTL = l - f;
5544
4692
  }
5545
4693
  };
5546
- let cachedNow = 0;
5547
- const getNow = ()=>{
5548
- const n = perf.now();
4694
+ let n = 0, o = ()=>{
4695
+ let r = this.#m.now();
5549
4696
  if (this.ttlResolution > 0) {
5550
- cachedNow = n;
5551
- const t1 = setTimeout(()=>cachedNow = 0, this.ttlResolution);
5552
- if (t1.unref) t1.unref();
4697
+ n = r;
4698
+ let h = setTimeout(()=>n = 0, this.ttlResolution);
4699
+ h.unref && h.unref();
5553
4700
  }
5554
- return n;
5555
- };
5556
- this.getRemainingTTL = (key)=>{
5557
- const index = this.#keyMap.get(key);
5558
- if (void 0 === index) return 0;
5559
- const ttl = ttls[index];
5560
- const start = starts[index];
5561
- if (!ttl || !start) return 1 / 0;
5562
- const age = (cachedNow || getNow()) - start;
5563
- return ttl - age;
4701
+ return r;
5564
4702
  };
5565
- this.#isStale = (index)=>{
5566
- const s = starts[index];
5567
- const t1 = ttls[index];
5568
- return !!t1 && !!s && (cachedNow || getNow()) - s > t1;
4703
+ this.getRemainingTTL = (r)=>{
4704
+ let h = this.#s.get(r);
4705
+ if (void 0 === h) return 0;
4706
+ let l = e1[h], c = t1[h];
4707
+ if (!l || !c) return 1 / 0;
4708
+ let f = (n || o()) - c;
4709
+ return l - f;
4710
+ }, this.#p = (r)=>{
4711
+ let h = t1[r], l = e1[r];
4712
+ return !!l && !!h && (n || o()) - h > l;
5569
4713
  };
5570
4714
  }
5571
- #updateItemAge = ()=>{};
5572
- #statusTTL = ()=>{};
5573
- #setItemTTL = ()=>{};
5574
- #isStale = ()=>false;
5575
- #initializeSizeTracking() {
5576
- const sizes = new ZeroArray(this.#max);
5577
- this.#calculatedSize = 0;
5578
- this.#sizes = sizes;
5579
- this.#removeItemSize = (index)=>{
5580
- this.#calculatedSize -= sizes[index];
5581
- sizes[index] = 0;
5582
- };
5583
- this.#requireSize = (k, v, size, sizeCalculation)=>{
5584
- if (this.#isBackgroundFetch(v)) return 0;
5585
- if (!isPosInt(size)) if (sizeCalculation) {
5586
- if ('function' != typeof sizeCalculation) throw new TypeError('sizeCalculation must be a function');
5587
- size = sizeCalculation(v, k);
5588
- if (!isPosInt(size)) throw new TypeError('sizeCalculation return invalid (expect positive integer)');
4715
+ #x = ()=>{};
4716
+ #E = ()=>{};
4717
+ #N = ()=>{};
4718
+ #p = ()=>!1;
4719
+ #X() {
4720
+ let e1 = new O(this.#o);
4721
+ this.#b = 0, this.#_ = e1, this.#R = (t1)=>{
4722
+ this.#b -= e1[t1], e1[t1] = 0;
4723
+ }, this.#k = (t1, i, s, n)=>{
4724
+ if (this.#e(i)) return 0;
4725
+ if (!F(s)) if (n) {
4726
+ if ("function" != typeof n) throw new TypeError("sizeCalculation must be a function");
4727
+ if (s = n(i, t1), !F(s)) throw new TypeError("sizeCalculation return invalid (expect positive integer)");
5589
4728
  } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
5590
- return size;
5591
- };
5592
- this.#addItemSize = (index, size, status)=>{
5593
- sizes[index] = size;
5594
- if (this.#maxSize) {
5595
- const maxSize = this.#maxSize - sizes[index];
5596
- while(this.#calculatedSize > maxSize)this.#evict(true);
5597
- }
5598
- this.#calculatedSize += sizes[index];
5599
- if (status) {
5600
- status.entrySize = size;
5601
- status.totalCalculatedSize = this.#calculatedSize;
4729
+ return s;
4730
+ }, this.#I = (t1, i, s)=>{
4731
+ if (e1[t1] = i, this.#u) {
4732
+ let n = this.#u - e1[t1];
4733
+ for(; this.#b > n;)this.#G(!0);
5602
4734
  }
4735
+ this.#b += e1[t1], s && (s.entrySize = i, s.totalCalculatedSize = this.#b);
5603
4736
  };
5604
4737
  }
5605
- #removeItemSize = (_i)=>{};
5606
- #addItemSize = (_i, _s, _st)=>{};
5607
- #requireSize = (_k, _v, size, sizeCalculation)=>{
5608
- if (size || sizeCalculation) throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
4738
+ #R = (e1)=>{};
4739
+ #I = (e1, t1, i)=>{};
4740
+ #k = (e1, t1, i, s)=>{
4741
+ if (i || s) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
5609
4742
  return 0;
5610
4743
  };
5611
- *#indexes({ allowStale = this.allowStale } = {}) {
5612
- if (this.#size) for(let i = this.#tail; true;){
5613
- if (!this.#isValidIndex(i)) break;
5614
- if (allowStale || !this.#isStale(i)) yield i;
5615
- if (i === this.#head) break;
5616
- i = this.#prev[i];
5617
- }
4744
+ *#A({ allowStale: e1 = this.allowStale } = {}) {
4745
+ if (this.#n) for(let t1 = this.#h; this.#V(t1) && ((e1 || !this.#p(t1)) && (yield t1), t1 !== this.#l);)t1 = this.#c[t1];
5618
4746
  }
5619
- *#rindexes({ allowStale = this.allowStale } = {}) {
5620
- if (this.#size) for(let i = this.#head; true;){
5621
- if (!this.#isValidIndex(i)) break;
5622
- if (allowStale || !this.#isStale(i)) yield i;
5623
- if (i === this.#tail) break;
5624
- i = this.#next[i];
5625
- }
4747
+ *#z({ allowStale: e1 = this.allowStale } = {}) {
4748
+ if (this.#n) for(let t1 = this.#l; this.#V(t1) && ((e1 || !this.#p(t1)) && (yield t1), t1 !== this.#h);)t1 = this.#a[t1];
5626
4749
  }
5627
- #isValidIndex(index) {
5628
- return void 0 !== index && this.#keyMap.get(this.#keyList[index]) === index;
4750
+ #V(e1) {
4751
+ return void 0 !== e1 && this.#s.get(this.#i[e1]) === e1;
5629
4752
  }
5630
4753
  *entries() {
5631
- for (const i of this.#indexes())if (void 0 !== this.#valList[i] && void 0 !== this.#keyList[i] && !this.#isBackgroundFetch(this.#valList[i])) yield [
5632
- this.#keyList[i],
5633
- this.#valList[i]
5634
- ];
4754
+ for (let e1 of this.#A())void 0 === this.#t[e1] || void 0 === this.#i[e1] || this.#e(this.#t[e1]) || (yield [
4755
+ this.#i[e1],
4756
+ this.#t[e1]
4757
+ ]);
5635
4758
  }
5636
4759
  *rentries() {
5637
- for (const i of this.#rindexes())if (void 0 !== this.#valList[i] && void 0 !== this.#keyList[i] && !this.#isBackgroundFetch(this.#valList[i])) yield [
5638
- this.#keyList[i],
5639
- this.#valList[i]
5640
- ];
4760
+ for (let e1 of this.#z())void 0 === this.#t[e1] || void 0 === this.#i[e1] || this.#e(this.#t[e1]) || (yield [
4761
+ this.#i[e1],
4762
+ this.#t[e1]
4763
+ ]);
5641
4764
  }
5642
4765
  *keys() {
5643
- for (const i of this.#indexes()){
5644
- const k = this.#keyList[i];
5645
- if (void 0 !== k && !this.#isBackgroundFetch(this.#valList[i])) yield k;
4766
+ for (let e1 of this.#A()){
4767
+ let t1 = this.#i[e1];
4768
+ void 0 === t1 || this.#e(this.#t[e1]) || (yield t1);
5646
4769
  }
5647
4770
  }
5648
4771
  *rkeys() {
5649
- for (const i of this.#rindexes()){
5650
- const k = this.#keyList[i];
5651
- if (void 0 !== k && !this.#isBackgroundFetch(this.#valList[i])) yield k;
4772
+ for (let e1 of this.#z()){
4773
+ let t1 = this.#i[e1];
4774
+ void 0 === t1 || this.#e(this.#t[e1]) || (yield t1);
5652
4775
  }
5653
4776
  }
5654
4777
  *values() {
5655
- for (const i of this.#indexes()){
5656
- const v = this.#valList[i];
5657
- if (void 0 !== v && !this.#isBackgroundFetch(this.#valList[i])) yield this.#valList[i];
5658
- }
4778
+ for (let e1 of this.#A())void 0 === this.#t[e1] || this.#e(this.#t[e1]) || (yield this.#t[e1]);
5659
4779
  }
5660
4780
  *rvalues() {
5661
- for (const i of this.#rindexes()){
5662
- const v = this.#valList[i];
5663
- if (void 0 !== v && !this.#isBackgroundFetch(this.#valList[i])) yield this.#valList[i];
5664
- }
4781
+ for (let e1 of this.#z())void 0 === this.#t[e1] || this.#e(this.#t[e1]) || (yield this.#t[e1]);
5665
4782
  }
5666
4783
  [Symbol.iterator]() {
5667
4784
  return this.entries();
5668
4785
  }
5669
- [Symbol.toStringTag] = 'LRUCache';
5670
- find(fn, getOptions = {}) {
5671
- for (const i of this.#indexes()){
5672
- const v = this.#valList[i];
5673
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5674
- if (void 0 !== value) {
5675
- if (fn(value, this.#keyList[i], this)) return this.get(this.#keyList[i], getOptions);
5676
- }
4786
+ [Symbol.toStringTag] = "LRUCache";
4787
+ find(e1, t1 = {}) {
4788
+ for (let i of this.#A()){
4789
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
4790
+ if (void 0 !== n && e1(n, this.#i[i], this)) return this.#C(this.#i[i], t1);
5677
4791
  }
5678
4792
  }
5679
- forEach(fn, thisp = this) {
5680
- for (const i of this.#indexes()){
5681
- const v = this.#valList[i];
5682
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5683
- if (void 0 !== value) fn.call(thisp, value, this.#keyList[i], this);
4793
+ forEach(e1, t1 = this) {
4794
+ for (let i of this.#A()){
4795
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
4796
+ void 0 !== n && e1.call(t1, n, this.#i[i], this);
5684
4797
  }
5685
4798
  }
5686
- rforEach(fn, thisp = this) {
5687
- for (const i of this.#rindexes()){
5688
- const v = this.#valList[i];
5689
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5690
- if (void 0 !== value) fn.call(thisp, value, this.#keyList[i], this);
4799
+ rforEach(e1, t1 = this) {
4800
+ for (let i of this.#z()){
4801
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
4802
+ void 0 !== n && e1.call(t1, n, this.#i[i], this);
5691
4803
  }
5692
4804
  }
5693
4805
  purgeStale() {
5694
- let deleted = false;
5695
- for (const i of this.#rindexes({
5696
- allowStale: true
5697
- }))if (this.#isStale(i)) {
5698
- this.#delete(this.#keyList[i], 'expire');
5699
- deleted = true;
5700
- }
5701
- return deleted;
5702
- }
5703
- info(key) {
5704
- const i = this.#keyMap.get(key);
5705
- if (void 0 === i) return;
5706
- const v = this.#valList[i];
5707
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5708
- if (void 0 === value) return;
5709
- const entry = {
5710
- value
4806
+ let e1 = !1;
4807
+ for (let t1 of this.#z({
4808
+ allowStale: !0
4809
+ }))this.#p(t1) && (this.#v(this.#i[t1], "expire"), e1 = !0);
4810
+ return e1;
4811
+ }
4812
+ info(e1) {
4813
+ let t1 = this.#s.get(e1);
4814
+ if (void 0 === t1) return;
4815
+ let i = this.#t[t1], s = this.#e(i) ? i.__staleWhileFetching : i;
4816
+ if (void 0 === s) return;
4817
+ let n = {
4818
+ value: s
5711
4819
  };
5712
- if (this.#ttls && this.#starts) {
5713
- const ttl = this.#ttls[i];
5714
- const start = this.#starts[i];
5715
- if (ttl && start) {
5716
- const remain = ttl - (perf.now() - start);
5717
- entry.ttl = remain;
5718
- entry.start = Date.now();
4820
+ if (this.#d && this.#F) {
4821
+ let o = this.#d[t1], r = this.#F[t1];
4822
+ if (o && r) {
4823
+ let h = o - (this.#m.now() - r);
4824
+ n.ttl = h, n.start = Date.now();
5719
4825
  }
5720
4826
  }
5721
- if (this.#sizes) entry.size = this.#sizes[i];
5722
- return entry;
4827
+ return this.#_ && (n.size = this.#_[t1]), n;
5723
4828
  }
5724
4829
  dump() {
5725
- const arr = [];
5726
- for (const i of this.#indexes({
5727
- allowStale: true
4830
+ let e1 = [];
4831
+ for (let t1 of this.#A({
4832
+ allowStale: !0
5728
4833
  })){
5729
- const key = this.#keyList[i];
5730
- const v = this.#valList[i];
5731
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5732
- if (void 0 === value || void 0 === key) continue;
5733
- const entry = {
5734
- value
4834
+ let i = this.#i[t1], s = this.#t[t1], n = this.#e(s) ? s.__staleWhileFetching : s;
4835
+ if (void 0 === n || void 0 === i) continue;
4836
+ let o = {
4837
+ value: n
5735
4838
  };
5736
- if (this.#ttls && this.#starts) {
5737
- entry.ttl = this.#ttls[i];
5738
- const age = perf.now() - this.#starts[i];
5739
- entry.start = Math.floor(Date.now() - age);
5740
- }
5741
- if (this.#sizes) entry.size = this.#sizes[i];
5742
- arr.unshift([
5743
- key,
5744
- entry
4839
+ if (this.#d && this.#F) {
4840
+ o.ttl = this.#d[t1];
4841
+ let r = this.#m.now() - this.#F[t1];
4842
+ o.start = Math.floor(Date.now() - r);
4843
+ }
4844
+ this.#_ && (o.size = this.#_[t1]), e1.unshift([
4845
+ i,
4846
+ o
5745
4847
  ]);
5746
4848
  }
5747
- return arr;
4849
+ return e1;
5748
4850
  }
5749
- load(arr) {
4851
+ load(e1) {
5750
4852
  this.clear();
5751
- for (const [key, entry] of arr){
5752
- if (entry.start) {
5753
- const age = Date.now() - entry.start;
5754
- entry.start = perf.now() - age;
5755
- }
5756
- this.set(key, entry.value, entry);
5757
- }
5758
- }
5759
- set(k, v, setOptions = {}) {
5760
- if (void 0 === v) {
5761
- this.delete(k);
5762
- return this;
5763
- }
5764
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
5765
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
5766
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
5767
- if (this.maxEntrySize && size > this.maxEntrySize) {
5768
- if (status) {
5769
- status.set = 'miss';
5770
- status.maxEntrySizeExceeded = true;
5771
- }
5772
- this.#delete(k, 'set');
5773
- return this;
5774
- }
5775
- let index = 0 === this.#size ? void 0 : this.#keyMap.get(k);
5776
- if (void 0 === index) {
5777
- index = 0 === this.#size ? this.#tail : 0 !== this.#free.length ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
5778
- this.#keyList[index] = k;
5779
- this.#valList[index] = v;
5780
- this.#keyMap.set(k, index);
5781
- this.#next[this.#tail] = index;
5782
- this.#prev[index] = this.#tail;
5783
- this.#tail = index;
5784
- this.#size++;
5785
- this.#addItemSize(index, size, status);
5786
- if (status) status.set = 'add';
5787
- noUpdateTTL = false;
5788
- } else {
5789
- this.#moveToTail(index);
5790
- const oldVal = this.#valList[index];
5791
- if (v !== oldVal) {
5792
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
5793
- oldVal.__abortController.abort(new Error('replaced'));
5794
- const { __staleWhileFetching: s } = oldVal;
5795
- if (void 0 !== s && !noDisposeOnSet) {
5796
- if (this.#hasDispose) this.#dispose?.(s, k, 'set');
5797
- if (this.#hasDisposeAfter) this.#disposed?.push([
5798
- s,
5799
- k,
5800
- 'set'
5801
- ]);
5802
- }
5803
- } else if (!noDisposeOnSet) {
5804
- if (this.#hasDispose) this.#dispose?.(oldVal, k, 'set');
5805
- if (this.#hasDisposeAfter) this.#disposed?.push([
5806
- oldVal,
5807
- k,
5808
- 'set'
5809
- ]);
5810
- }
5811
- this.#removeItemSize(index);
5812
- this.#addItemSize(index, size, status);
5813
- this.#valList[index] = v;
5814
- if (status) {
5815
- status.set = 'replace';
5816
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
5817
- if (void 0 !== oldValue) status.oldValue = oldValue;
4853
+ for (let [t1, i] of e1){
4854
+ if (i.start) {
4855
+ let s = Date.now() - i.start;
4856
+ i.start = this.#m.now() - s;
4857
+ }
4858
+ this.#O(t1, i.value, i);
4859
+ }
4860
+ }
4861
+ set(e1, t1, i = {}) {
4862
+ let { status: s = S.hasSubscribers ? {} : void 0 } = i;
4863
+ i.status = s, s && (s.op = "set", s.key = e1, void 0 !== t1 && (s.value = t1));
4864
+ let n = this.#O(e1, t1, i);
4865
+ return s && S.hasSubscribers && S.publish(s), n;
4866
+ }
4867
+ #O(e1, t1, i = {}) {
4868
+ let { ttl: s = this.ttl, start: n, noDisposeOnSet: o = this.noDisposeOnSet, sizeCalculation: r = this.sizeCalculation, status: h } = i;
4869
+ if (void 0 === t1) return h && (h.set = "deleted"), this.delete(e1), this;
4870
+ let { noUpdateTTL: l = this.noUpdateTTL } = i;
4871
+ h && !this.#e(t1) && (h.value = t1);
4872
+ let c = this.#k(e1, t1, i.size || 0, r, h);
4873
+ if (this.maxEntrySize && c > this.maxEntrySize) return this.#v(e1, "set"), h && (h.set = "miss", h.maxEntrySizeExceeded = !0), this;
4874
+ let f = 0 === this.#n ? void 0 : this.#s.get(e1);
4875
+ if (void 0 === f) f = 0 === this.#n ? this.#h : 0 !== this.#y.length ? this.#y.pop() : this.#n === this.#o ? this.#G(!1) : this.#n, this.#i[f] = e1, this.#t[f] = t1, this.#s.set(e1, f), this.#a[this.#h] = f, this.#c[f] = this.#h, this.#h = f, this.#n++, this.#I(f, c, h), h && (h.set = "add"), l = !1, this.#j && this.#D?.(t1, e1, "add");
4876
+ else {
4877
+ this.#L(f);
4878
+ let g = this.#t[f];
4879
+ if (t1 !== g) {
4880
+ if (this.#W && this.#e(g)) {
4881
+ g.__abortController.abort(new Error("replaced"));
4882
+ let { __staleWhileFetching: p } = g;
4883
+ void 0 !== p && !o && (this.#T && this.#w?.(p, e1, "set"), this.#f && this.#r?.push([
4884
+ p,
4885
+ e1,
4886
+ "set"
4887
+ ]));
4888
+ } else o || (this.#T && this.#w?.(g, e1, "set"), this.#f && this.#r?.push([
4889
+ g,
4890
+ e1,
4891
+ "set"
4892
+ ]));
4893
+ if (this.#R(f), this.#I(f, c, h), this.#t[f] = t1, h) {
4894
+ h.set = "replace";
4895
+ let p = g && this.#e(g) ? g.__staleWhileFetching : g;
4896
+ void 0 !== p && (h.oldValue = p);
5818
4897
  }
5819
- } else if (status) status.set = 'update';
4898
+ } else h && (h.set = "update");
4899
+ this.#j && this.onInsert?.(t1, e1, t1 === g ? "update" : "replace");
5820
4900
  }
5821
- if (0 !== ttl && !this.#ttls) this.#initializeTTLTracking();
5822
- if (this.#ttls) {
5823
- if (!noUpdateTTL) this.#setItemTTL(index, ttl, start);
5824
- if (status) this.#statusTTL(status, index);
5825
- }
5826
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
5827
- const dt = this.#disposed;
5828
- let task;
5829
- while(task = dt?.shift())this.#disposeAfter?.(...task);
4901
+ if (0 === s || this.#d || this.#H(), this.#d && (l || this.#N(f, s, n), h && this.#E(h, f)), !o && this.#f && this.#r) {
4902
+ let g = this.#r, p;
4903
+ for(; p = g?.shift();)this.#S?.(...p);
5830
4904
  }
5831
4905
  return this;
5832
4906
  }
5833
4907
  pop() {
5834
4908
  try {
5835
- while(this.#size){
5836
- const val = this.#valList[this.#head];
5837
- this.#evict(true);
5838
- if (this.#isBackgroundFetch(val)) {
5839
- if (val.__staleWhileFetching) return val.__staleWhileFetching;
5840
- } else if (void 0 !== val) return val;
4909
+ for(; this.#n;){
4910
+ let e1 = this.#t[this.#l];
4911
+ if (this.#G(!0), this.#e(e1)) {
4912
+ if (e1.__staleWhileFetching) return e1.__staleWhileFetching;
4913
+ } else if (void 0 !== e1) return e1;
5841
4914
  }
5842
4915
  } finally{
5843
- if (this.#hasDisposeAfter && this.#disposed) {
5844
- const dt = this.#disposed;
5845
- let task;
5846
- while(task = dt?.shift())this.#disposeAfter?.(...task);
4916
+ if (this.#f && this.#r) {
4917
+ let e1 = this.#r, t1;
4918
+ for(; t1 = e1?.shift();)this.#S?.(...t1);
5847
4919
  }
5848
4920
  }
5849
4921
  }
5850
- #evict(free) {
5851
- const head = this.#head;
5852
- const k = this.#keyList[head];
5853
- const v = this.#valList[head];
5854
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) v.__abortController.abort(new Error('evicted'));
5855
- else if (this.#hasDispose || this.#hasDisposeAfter) {
5856
- if (this.#hasDispose) this.#dispose?.(v, k, 'evict');
5857
- if (this.#hasDisposeAfter) this.#disposed?.push([
5858
- v,
5859
- k,
5860
- 'evict'
5861
- ]);
4922
+ #G(e1) {
4923
+ let t1 = this.#l, i = this.#i[t1], s = this.#t[t1];
4924
+ return this.#W && this.#e(s) ? s.__abortController.abort(new Error("evicted")) : (this.#T || this.#f) && (this.#T && this.#w?.(s, i, "evict"), this.#f && this.#r?.push([
4925
+ s,
4926
+ i,
4927
+ "evict"
4928
+ ])), this.#R(t1), this.#g?.[t1] && (clearTimeout(this.#g[t1]), this.#g[t1] = void 0), e1 && (this.#i[t1] = void 0, this.#t[t1] = void 0, this.#y.push(t1)), 1 === this.#n ? (this.#l = this.#h = 0, this.#y.length = 0) : this.#l = this.#a[t1], this.#s.delete(i), this.#n--, t1;
4929
+ }
4930
+ has(e1, t1 = {}) {
4931
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t1;
4932
+ t1.status = i, i && (i.op = "has", i.key = e1);
4933
+ let s = this.#Y(e1, t1);
4934
+ return S.hasSubscribers && S.publish(i), s;
4935
+ }
4936
+ #Y(e1, t1 = {}) {
4937
+ let { updateAgeOnHas: i = this.updateAgeOnHas, status: s } = t1, n = this.#s.get(e1);
4938
+ if (void 0 !== n) {
4939
+ let o = this.#t[n];
4940
+ if (this.#e(o) && void 0 === o.__staleWhileFetching) return !1;
4941
+ if (!this.#p(n)) return i && this.#x(n), s && (s.has = "hit", this.#E(s, n)), !0;
4942
+ s && (s.has = "stale", this.#E(s, n));
4943
+ } else s && (s.has = "miss");
4944
+ return !1;
4945
+ }
4946
+ peek(e1, t1 = {}) {
4947
+ let { status: i = D() ? {} : void 0 } = t1;
4948
+ i && (i.op = "peek", i.key = e1), t1.status = i;
4949
+ let s = this.#J(e1, t1);
4950
+ return S.hasSubscribers && S.publish(i), s;
4951
+ }
4952
+ #J(e1, t1) {
4953
+ let { status: i, allowStale: s = this.allowStale } = t1, n = this.#s.get(e1);
4954
+ if (void 0 === n || !s && this.#p(n)) {
4955
+ i && (i.peek = void 0 === n ? "miss" : "stale");
4956
+ return;
5862
4957
  }
5863
- this.#removeItemSize(head);
5864
- if (free) {
5865
- this.#keyList[head] = void 0;
5866
- this.#valList[head] = void 0;
5867
- this.#free.push(head);
5868
- }
5869
- if (1 === this.#size) {
5870
- this.#head = this.#tail = 0;
5871
- this.#free.length = 0;
5872
- } else this.#head = this.#next[head];
5873
- this.#keyMap.delete(k);
5874
- this.#size--;
5875
- return head;
5876
- }
5877
- has(k, hasOptions = {}) {
5878
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
5879
- const index = this.#keyMap.get(k);
5880
- if (void 0 !== index) {
5881
- const v = this.#valList[index];
5882
- if (this.#isBackgroundFetch(v) && void 0 === v.__staleWhileFetching) return false;
5883
- if (this.#isStale(index)) {
5884
- if (status) {
5885
- status.has = 'stale';
5886
- this.#statusTTL(status, index);
5887
- }
5888
- } else {
5889
- if (updateAgeOnHas) this.#updateItemAge(index);
5890
- if (status) {
5891
- status.has = 'hit';
5892
- this.#statusTTL(status, index);
5893
- }
5894
- return true;
5895
- }
5896
- } else if (status) status.has = 'miss';
5897
- return false;
4958
+ let o = this.#t[n], r = this.#e(o) ? o.__staleWhileFetching : o;
4959
+ return i && (void 0 !== r ? (i.peek = "hit", i.value = r) : i.peek = "miss"), r;
5898
4960
  }
5899
- peek(k, peekOptions = {}) {
5900
- const { allowStale = this.allowStale } = peekOptions;
5901
- const index = this.#keyMap.get(k);
5902
- if (void 0 === index || !allowStale && this.#isStale(index)) return;
5903
- const v = this.#valList[index];
5904
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
5905
- }
5906
- #backgroundFetch(k, index, options, context) {
5907
- const v = void 0 === index ? void 0 : this.#valList[index];
5908
- if (this.#isBackgroundFetch(v)) return v;
5909
- const ac = new AC();
5910
- const { signal } = options;
5911
- signal?.addEventListener('abort', ()=>ac.abort(signal.reason), {
5912
- signal: ac.signal
4961
+ #P(e1, t1, i, s) {
4962
+ let n = void 0 === t1 ? void 0 : this.#t[t1];
4963
+ if (this.#e(n)) return n;
4964
+ let o = new AbortController, { signal: r } = i;
4965
+ r?.addEventListener("abort", ()=>o.abort(r.reason), {
4966
+ signal: o.signal
5913
4967
  });
5914
- const fetchOpts = {
5915
- signal: ac.signal,
5916
- options,
5917
- context
5918
- };
5919
- const cb = (v, updateCache = false)=>{
5920
- const { aborted } = ac.signal;
5921
- const ignoreAbort = options.ignoreFetchAbort && void 0 !== v;
5922
- if (options.status) if (aborted && !updateCache) {
5923
- options.status.fetchAborted = true;
5924
- options.status.fetchError = ac.signal.reason;
5925
- if (ignoreAbort) options.status.fetchAbortIgnored = true;
5926
- } else options.status.fetchResolved = true;
5927
- if (aborted && !ignoreAbort && !updateCache) return fetchFail(ac.signal.reason);
5928
- const bf = p;
5929
- if (this.#valList[index] === p) if (void 0 === v) if (bf.__staleWhileFetching) this.#valList[index] = bf.__staleWhileFetching;
5930
- else this.#delete(k, 'fetch');
5931
- else {
5932
- if (options.status) options.status.fetchUpdated = true;
5933
- this.set(k, v, fetchOpts.options);
5934
- }
5935
- return v;
5936
- };
5937
- const eb = (er)=>{
5938
- if (options.status) {
5939
- options.status.fetchRejected = true;
5940
- options.status.fetchError = er;
5941
- }
5942
- return fetchFail(er);
5943
- };
5944
- const fetchFail = (er)=>{
5945
- const { aborted } = ac.signal;
5946
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
5947
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
5948
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
5949
- const bf = p;
5950
- if (this.#valList[index] === p) {
5951
- const del = !noDelete || void 0 === bf.__staleWhileFetching;
5952
- if (del) this.#delete(k, 'fetch');
5953
- else if (!allowStaleAborted) this.#valList[index] = bf.__staleWhileFetching;
5954
- }
5955
- if (allowStale) {
5956
- if (options.status && void 0 !== bf.__staleWhileFetching) options.status.returnedStale = true;
5957
- return bf.__staleWhileFetching;
5958
- }
5959
- if (bf.__returned === bf) throw er;
5960
- };
5961
- const pcall = (res, rej)=>{
5962
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
5963
- if (fmp && fmp instanceof Promise) fmp.then((v)=>res(void 0 === v ? void 0 : v), rej);
5964
- ac.signal.addEventListener('abort', ()=>{
5965
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
5966
- res(void 0);
5967
- if (options.allowStaleOnFetchAbort) res = (v)=>cb(v, true);
5968
- }
4968
+ let h = {
4969
+ signal: o.signal,
4970
+ options: i,
4971
+ context: s
4972
+ }, l = (w, y = !1)=>{
4973
+ let { aborted: a } = o.signal, m = i.ignoreFetchAbort && void 0 !== w, _ = i.ignoreFetchAbort || !!(i.allowStaleOnFetchAbort && void 0 !== w);
4974
+ if (i.status && (a && !y ? (i.status.fetchAborted = !0, i.status.fetchError = o.signal.reason, m && (i.status.fetchAbortIgnored = !0)) : i.status.fetchResolved = !0), a && !m && !y) return f(o.signal.reason, _);
4975
+ let b = p, d = this.#t[t1];
4976
+ return (d === p || void 0 === d && m && y) && (void 0 === w ? void 0 !== b.__staleWhileFetching ? this.#t[t1] = b.__staleWhileFetching : this.#v(e1, "fetch") : (i.status && (i.status.fetchUpdated = !0), this.#O(e1, w, h.options))), w;
4977
+ }, c = (w)=>(i.status && (i.status.fetchRejected = !0, i.status.fetchError = w), f(w, !1)), f = (w, y)=>{
4978
+ let { aborted: a } = o.signal, m = a && i.allowStaleOnFetchAbort, _ = m || i.allowStaleOnFetchRejection, b = _ || i.noDeleteOnFetchRejection, d = p;
4979
+ if (this.#t[t1] === p && (b && (y || void 0 !== d.__staleWhileFetching) ? m || (this.#t[t1] = d.__staleWhileFetching) : this.#v(e1, "fetch")), _) return i.status && void 0 !== d.__staleWhileFetching && (i.status.returnedStale = !0), d.__staleWhileFetching;
4980
+ if (d.__returned === d) throw w;
4981
+ }, g = (w, y)=>{
4982
+ let a = this.#M?.(e1, n, h);
4983
+ a && a instanceof Promise && a.then((m)=>w(void 0 === m ? void 0 : m), y), o.signal.addEventListener("abort", ()=>{
4984
+ (!i.ignoreFetchAbort || i.allowStaleOnFetchAbort) && (w(void 0), i.allowStaleOnFetchAbort && (w = (m)=>l(m, !0)));
5969
4985
  });
5970
4986
  };
5971
- if (options.status) options.status.fetchDispatched = true;
5972
- const p = new Promise(pcall).then(cb, eb);
5973
- const bf = Object.assign(p, {
5974
- __abortController: ac,
5975
- __staleWhileFetching: v,
4987
+ i.status && (i.status.fetchDispatched = !0);
4988
+ let p = new Promise(g).then(l, c), T = Object.assign(p, {
4989
+ __abortController: o,
4990
+ __staleWhileFetching: n,
5976
4991
  __returned: void 0
5977
4992
  });
5978
- if (void 0 === index) {
5979
- this.set(k, bf, {
5980
- ...fetchOpts.options,
5981
- status: void 0
5982
- });
5983
- index = this.#keyMap.get(k);
5984
- } else this.#valList[index] = bf;
5985
- return bf;
5986
- }
5987
- #isBackgroundFetch(p) {
5988
- if (!this.#hasFetchMethod) return false;
5989
- const b = p;
5990
- return !!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && b.__abortController instanceof AC;
5991
- }
5992
- async fetch(k, fetchOptions = {}) {
5993
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal } = fetchOptions;
5994
- if (!this.#hasFetchMethod) {
5995
- if (status) status.fetch = 'get';
5996
- return this.get(k, {
5997
- allowStale,
5998
- updateAgeOnGet,
5999
- noDeleteOnStaleGet,
6000
- status
6001
- });
6002
- }
6003
- const options = {
6004
- allowStale,
6005
- updateAgeOnGet,
6006
- noDeleteOnStaleGet,
6007
- ttl,
6008
- noDisposeOnSet,
6009
- size,
6010
- sizeCalculation,
6011
- noUpdateTTL,
6012
- noDeleteOnFetchRejection,
6013
- allowStaleOnFetchRejection,
6014
- allowStaleOnFetchAbort,
6015
- ignoreFetchAbort,
6016
- status,
6017
- signal
6018
- };
6019
- let index = this.#keyMap.get(k);
6020
- if (void 0 === index) {
6021
- if (status) status.fetch = 'miss';
6022
- const p = this.#backgroundFetch(k, index, options, context);
6023
- return p.__returned = p;
4993
+ return void 0 === t1 ? (this.#O(e1, T, {
4994
+ ...h.options,
4995
+ status: void 0
4996
+ }), t1 = this.#s.get(e1)) : this.#t[t1] = T, T;
4997
+ }
4998
+ #e(e1) {
4999
+ if (!this.#W) return !1;
5000
+ let t1 = e1;
5001
+ return !!t1 && t1 instanceof Promise && t1.hasOwnProperty("__staleWhileFetching") && t1.__abortController instanceof AbortController;
5002
+ }
5003
+ fetch(e1, t1 = {}) {
5004
+ let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t1;
5005
+ t1.status = s, s && t1.context && (s.context = t1.context);
5006
+ let n = this.#B(e1, t1);
5007
+ return s && D() && i && (s.trace = !0, W.tracePromise(()=>n, s).catch(()=>{})), n;
5008
+ }
5009
+ async #B(e1, t1 = {}) {
5010
+ let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, ttl: o = this.ttl, noDisposeOnSet: r = this.noDisposeOnSet, size: h = 0, sizeCalculation: l = this.sizeCalculation, noUpdateTTL: c = this.noUpdateTTL, noDeleteOnFetchRejection: f = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: g = this.allowStaleOnFetchRejection, ignoreFetchAbort: p = this.ignoreFetchAbort, allowStaleOnFetchAbort: T = this.allowStaleOnFetchAbort, context: w, forceRefresh: y = !1, status: a, signal: m } = t1;
5011
+ if (a && (a.op = "fetch", a.key = e1, y && (a.forceRefresh = !0)), !this.#W) return a && (a.fetch = "get"), this.#C(e1, {
5012
+ allowStale: i,
5013
+ updateAgeOnGet: s,
5014
+ noDeleteOnStaleGet: n,
5015
+ status: a
5016
+ });
5017
+ let _ = {
5018
+ allowStale: i,
5019
+ updateAgeOnGet: s,
5020
+ noDeleteOnStaleGet: n,
5021
+ ttl: o,
5022
+ noDisposeOnSet: r,
5023
+ size: h,
5024
+ sizeCalculation: l,
5025
+ noUpdateTTL: c,
5026
+ noDeleteOnFetchRejection: f,
5027
+ allowStaleOnFetchRejection: g,
5028
+ allowStaleOnFetchAbort: T,
5029
+ ignoreFetchAbort: p,
5030
+ status: a,
5031
+ signal: m
5032
+ }, b = this.#s.get(e1);
5033
+ if (void 0 === b) {
5034
+ a && (a.fetch = "miss");
5035
+ let d = this.#P(e1, b, _, w);
5036
+ return d.__returned = d;
6024
5037
  }
6025
5038
  {
6026
- const v = this.#valList[index];
6027
- if (this.#isBackgroundFetch(v)) {
6028
- const stale = allowStale && void 0 !== v.__staleWhileFetching;
6029
- if (status) {
6030
- status.fetch = 'inflight';
6031
- if (stale) status.returnedStale = true;
6032
- }
6033
- return stale ? v.__staleWhileFetching : v.__returned = v;
6034
- }
6035
- const isStale = this.#isStale(index);
6036
- if (!forceRefresh && !isStale) {
6037
- if (status) status.fetch = 'hit';
6038
- this.#moveToTail(index);
6039
- if (updateAgeOnGet) this.#updateItemAge(index);
6040
- if (status) this.#statusTTL(status, index);
6041
- return v;
6042
- }
6043
- const p = this.#backgroundFetch(k, index, options, context);
6044
- const hasStale = void 0 !== p.__staleWhileFetching;
6045
- const staleVal = hasStale && allowStale;
6046
- if (status) {
6047
- status.fetch = isStale ? 'stale' : 'refresh';
6048
- if (staleVal && isStale) status.returnedStale = true;
6049
- }
6050
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
6051
- }
6052
- }
6053
- async forceFetch(k, fetchOptions = {}) {
6054
- const v = await this.fetch(k, fetchOptions);
6055
- if (void 0 === v) throw new Error('fetch() returned undefined');
6056
- return v;
6057
- }
6058
- memo(k, memoOptions = {}) {
6059
- const memoMethod = this.#memoMethod;
6060
- if (!memoMethod) throw new Error('no memoMethod provided to constructor');
6061
- const { context, forceRefresh, ...options } = memoOptions;
6062
- const v = this.get(k, options);
6063
- if (!forceRefresh && void 0 !== v) return v;
6064
- const vv = memoMethod(k, v, {
6065
- options,
6066
- context
5039
+ let d = this.#t[b];
5040
+ if (this.#e(d)) {
5041
+ let E = i && void 0 !== d.__staleWhileFetching;
5042
+ return a && (a.fetch = "inflight", E && (a.returnedStale = !0)), E ? d.__staleWhileFetching : d.__returned = d;
5043
+ }
5044
+ let A = this.#p(b);
5045
+ if (!y && !A) return a && (a.fetch = "hit"), this.#L(b), s && this.#x(b), a && this.#E(a, b), d;
5046
+ let z = this.#P(e1, b, _, w), v = void 0 !== z.__staleWhileFetching && i;
5047
+ return a && (a.fetch = A ? "stale" : "refresh", v && A && (a.returnedStale = !0)), v ? z.__staleWhileFetching : z.__returned = z;
5048
+ }
5049
+ }
5050
+ forceFetch(e1, t1 = {}) {
5051
+ let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t1;
5052
+ t1.status = s, s && t1.context && (s.context = t1.context);
5053
+ let n = this.#K(e1, t1);
5054
+ return s && D() && i && (s.trace = !0, W.tracePromise(()=>n, s).catch(()=>{})), n;
5055
+ }
5056
+ async #K(e1, t1 = {}) {
5057
+ let i = await this.#B(e1, t1);
5058
+ if (void 0 === i) throw new Error("fetch() returned undefined");
5059
+ return i;
5060
+ }
5061
+ memo(e1, t1 = {}) {
5062
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t1;
5063
+ t1.status = i, i && (i.op = "memo", i.key = e1, t1.context && (i.context = t1.context));
5064
+ let s = this.#Q(e1, t1);
5065
+ return i && (i.value = s), S.hasSubscribers && S.publish(i), s;
5066
+ }
5067
+ #Q(e1, t1 = {}) {
5068
+ let i = this.#U;
5069
+ if (!i) throw new Error("no memoMethod provided to constructor");
5070
+ let { context: s, status: n, forceRefresh: o, ...r } = t1;
5071
+ n && o && (n.forceRefresh = !0);
5072
+ let h = this.#C(e1, r), l = o || void 0 === h;
5073
+ if (n && (n.memo = l ? "miss" : "hit", l || (n.value = h)), !l) return h;
5074
+ let c = i(e1, h, {
5075
+ options: r,
5076
+ context: s
6067
5077
  });
6068
- this.set(k, vv, options);
6069
- return vv;
6070
- }
6071
- get(k, getOptions = {}) {
6072
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
6073
- const index = this.#keyMap.get(k);
6074
- if (void 0 !== index) {
6075
- const value = this.#valList[index];
6076
- const fetching = this.#isBackgroundFetch(value);
6077
- if (status) this.#statusTTL(status, index);
6078
- if (this.#isStale(index)) {
6079
- if (status) status.get = 'stale';
6080
- if (fetching) {
6081
- if (status && allowStale && void 0 !== value.__staleWhileFetching) status.returnedStale = true;
6082
- return allowStale ? value.__staleWhileFetching : void 0;
6083
- }
6084
- if (!noDeleteOnStaleGet) this.#delete(k, 'expire');
6085
- if (status && allowStale) status.returnedStale = true;
6086
- return allowStale ? value : void 0;
6087
- }
6088
- if (status) status.get = 'hit';
6089
- if (fetching) return value.__staleWhileFetching;
6090
- this.#moveToTail(index);
6091
- if (updateAgeOnGet) this.#updateItemAge(index);
6092
- return value;
5078
+ return n && (n.value = c), this.#O(e1, c, r), c;
5079
+ }
5080
+ get(e1, t1 = {}) {
5081
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t1;
5082
+ t1.status = i, i && (i.op = "get", i.key = e1);
5083
+ let s = this.#C(e1, t1);
5084
+ return i && (void 0 !== s && (i.value = s), S.hasSubscribers && S.publish(i)), s;
5085
+ }
5086
+ #C(e1, t1 = {}) {
5087
+ let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, status: o } = t1, r = this.#s.get(e1);
5088
+ if (void 0 === r) {
5089
+ o && (o.get = "miss");
5090
+ return;
6093
5091
  }
6094
- if (status) status.get = 'miss';
5092
+ let h = this.#t[r], l = this.#e(h);
5093
+ return o && this.#E(o, r), this.#p(r) ? l ? (o && (o.get = "stale-fetching"), i && void 0 !== h.__staleWhileFetching ? (o && (o.returnedStale = !0), h.__staleWhileFetching) : void 0) : (n || this.#v(e1, "expire"), o && (o.get = "stale"), i ? (o && (o.returnedStale = !0), h) : void 0) : (o && (o.get = l ? "fetching" : "hit"), this.#L(r), s && this.#x(r), l ? h.__staleWhileFetching : h);
6095
5094
  }
6096
- #connect(p, n) {
6097
- this.#prev[n] = p;
6098
- this.#next[p] = n;
5095
+ #$(e1, t1) {
5096
+ this.#c[t1] = e1, this.#a[e1] = t1;
6099
5097
  }
6100
- #moveToTail(index) {
6101
- if (index !== this.#tail) {
6102
- if (index === this.#head) this.#head = this.#next[index];
6103
- else this.#connect(this.#prev[index], this.#next[index]);
6104
- this.#connect(this.#tail, index);
6105
- this.#tail = index;
6106
- }
5098
+ #L(e1) {
5099
+ e1 !== this.#h && (e1 === this.#l ? this.#l = this.#a[e1] : this.#$(this.#c[e1], this.#a[e1]), this.#$(this.#h, e1), this.#h = e1);
6107
5100
  }
6108
- delete(k) {
6109
- return this.#delete(k, 'delete');
5101
+ delete(e1) {
5102
+ return this.#v(e1, "delete");
6110
5103
  }
6111
- #delete(k, reason) {
6112
- let deleted = false;
6113
- if (0 !== this.#size) {
6114
- const index = this.#keyMap.get(k);
6115
- if (void 0 !== index) {
6116
- deleted = true;
6117
- if (1 === this.#size) this.#clear(reason);
5104
+ #v(e1, t1) {
5105
+ S.hasSubscribers && S.publish({
5106
+ op: "delete",
5107
+ delete: t1,
5108
+ key: e1
5109
+ });
5110
+ let i = !1;
5111
+ if (0 !== this.#n) {
5112
+ let s = this.#s.get(e1);
5113
+ if (void 0 !== s) if (this.#g?.[s] && (clearTimeout(this.#g?.[s]), this.#g[s] = void 0), i = !0, 1 === this.#n) this.#q(t1);
5114
+ else {
5115
+ this.#R(s);
5116
+ let n = this.#t[s];
5117
+ if (this.#e(n) ? n.__abortController.abort(new Error("deleted")) : (this.#T || this.#f) && (this.#T && this.#w?.(n, e1, t1), this.#f && this.#r?.push([
5118
+ n,
5119
+ e1,
5120
+ t1
5121
+ ])), this.#s.delete(e1), this.#i[s] = void 0, this.#t[s] = void 0, s === this.#h) this.#h = this.#c[s];
5122
+ else if (s === this.#l) this.#l = this.#a[s];
6118
5123
  else {
6119
- this.#removeItemSize(index);
6120
- const v = this.#valList[index];
6121
- if (this.#isBackgroundFetch(v)) v.__abortController.abort(new Error('deleted'));
6122
- else if (this.#hasDispose || this.#hasDisposeAfter) {
6123
- if (this.#hasDispose) this.#dispose?.(v, k, reason);
6124
- if (this.#hasDisposeAfter) this.#disposed?.push([
6125
- v,
6126
- k,
6127
- reason
6128
- ]);
6129
- }
6130
- this.#keyMap.delete(k);
6131
- this.#keyList[index] = void 0;
6132
- this.#valList[index] = void 0;
6133
- if (index === this.#tail) this.#tail = this.#prev[index];
6134
- else if (index === this.#head) this.#head = this.#next[index];
6135
- else {
6136
- const pi = this.#prev[index];
6137
- this.#next[pi] = this.#next[index];
6138
- const ni = this.#next[index];
6139
- this.#prev[ni] = this.#prev[index];
6140
- }
6141
- this.#size--;
6142
- this.#free.push(index);
5124
+ let o = this.#c[s];
5125
+ this.#a[o] = this.#a[s];
5126
+ let r = this.#a[s];
5127
+ this.#c[r] = this.#c[s];
6143
5128
  }
5129
+ this.#n--, this.#y.push(s);
6144
5130
  }
6145
5131
  }
6146
- if (this.#hasDisposeAfter && this.#disposed?.length) {
6147
- const dt = this.#disposed;
6148
- let task;
6149
- while(task = dt?.shift())this.#disposeAfter?.(...task);
5132
+ if (this.#f && this.#r?.length) {
5133
+ let s = this.#r, n;
5134
+ for(; n = s?.shift();)this.#S?.(...n);
6150
5135
  }
6151
- return deleted;
5136
+ return i;
6152
5137
  }
6153
5138
  clear() {
6154
- return this.#clear('delete');
5139
+ return this.#q("delete");
6155
5140
  }
6156
- #clear(reason) {
6157
- for (const index of this.#rindexes({
6158
- allowStale: true
5141
+ #q(e1) {
5142
+ for (let t1 of this.#z({
5143
+ allowStale: !0
6159
5144
  })){
6160
- const v = this.#valList[index];
6161
- if (this.#isBackgroundFetch(v)) v.__abortController.abort(new Error('deleted'));
5145
+ let i = this.#t[t1];
5146
+ if (this.#e(i)) i.__abortController.abort(new Error("deleted"));
6162
5147
  else {
6163
- const k = this.#keyList[index];
6164
- if (this.#hasDispose) this.#dispose?.(v, k, reason);
6165
- if (this.#hasDisposeAfter) this.#disposed?.push([
6166
- v,
6167
- k,
6168
- reason
5148
+ let s = this.#i[t1];
5149
+ this.#T && this.#w?.(i, s, e1), this.#f && this.#r?.push([
5150
+ i,
5151
+ s,
5152
+ e1
6169
5153
  ]);
6170
5154
  }
6171
5155
  }
6172
- this.#keyMap.clear();
6173
- this.#valList.fill(void 0);
6174
- this.#keyList.fill(void 0);
6175
- if (this.#ttls && this.#starts) {
6176
- this.#ttls.fill(0);
6177
- this.#starts.fill(0);
5156
+ if (this.#s.clear(), this.#t.fill(void 0), this.#i.fill(void 0), this.#d && this.#F) {
5157
+ this.#d.fill(0), this.#F.fill(0);
5158
+ for (let t1 of this.#g ?? [])void 0 !== t1 && clearTimeout(t1);
5159
+ this.#g?.fill(void 0);
6178
5160
  }
6179
- if (this.#sizes) this.#sizes.fill(0);
6180
- this.#head = 0;
6181
- this.#tail = 0;
6182
- this.#free.length = 0;
6183
- this.#calculatedSize = 0;
6184
- this.#size = 0;
6185
- if (this.#hasDisposeAfter && this.#disposed) {
6186
- const dt = this.#disposed;
6187
- let task;
6188
- while(task = dt?.shift())this.#disposeAfter?.(...task);
5161
+ if (this.#_ && this.#_.fill(0), this.#l = 0, this.#h = 0, this.#y.length = 0, this.#b = 0, this.#n = 0, this.#f && this.#r) {
5162
+ let t1 = this.#r, i;
5163
+ for(; i = t1?.shift();)this.#S?.(...i);
6189
5164
  }
6190
5165
  }
6191
- }
5166
+ };
6192
5167
  var external_fs_ = __webpack_require__("fs");
6193
5168
  const proc = 'object' == typeof process && process ? process : {
6194
5169
  stdout: null,
@@ -6261,7 +5236,7 @@ var __webpack_modules__ = {
6261
5236
  }
6262
5237
  constructor(src, dest, opts){
6263
5238
  super(src, dest, opts);
6264
- this.proxyErrors = (er)=>dest.emit('error', er);
5239
+ this.proxyErrors = (er)=>this.dest.emit('error', er);
6265
5240
  src.on('error', this.proxyErrors);
6266
5241
  }
6267
5242
  }
@@ -6713,7 +5688,8 @@ var __webpack_modules__ = {
6713
5688
  return: stop,
6714
5689
  [Symbol.asyncIterator] () {
6715
5690
  return this;
6716
- }
5691
+ },
5692
+ [Symbol.asyncDispose]: async ()=>{}
6717
5693
  };
6718
5694
  }
6719
5695
  [Symbol.iterator]() {
@@ -6747,7 +5723,8 @@ var __webpack_modules__ = {
6747
5723
  return: stop,
6748
5724
  [Symbol.iterator] () {
6749
5725
  return this;
6750
- }
5726
+ },
5727
+ [Symbol.dispose]: ()=>{}
6751
5728
  };
6752
5729
  }
6753
5730
  destroy(er) {
@@ -6814,7 +5791,9 @@ var __webpack_modules__ = {
6814
5791
  const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
6815
5792
  const TYPEMASK = 1023;
6816
5793
  const entToType = (s)=>s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
6817
- const normalizeCache = new Map();
5794
+ const normalizeCache = new L({
5795
+ max: 4096
5796
+ });
6818
5797
  const normalize = (s)=>{
6819
5798
  const c = normalizeCache.get(s);
6820
5799
  if (c) return c;
@@ -6822,7 +5801,9 @@ var __webpack_modules__ = {
6822
5801
  normalizeCache.set(s, n);
6823
5802
  return n;
6824
5803
  };
6825
- const normalizeNocaseCache = new Map();
5804
+ const normalizeNocaseCache = new L({
5805
+ max: 4096
5806
+ });
6826
5807
  const normalizeNocase = (s)=>{
6827
5808
  const c = normalizeNocaseCache.get(s);
6828
5809
  if (c) return c;
@@ -6830,14 +5811,14 @@ var __webpack_modules__ = {
6830
5811
  normalizeNocaseCache.set(s, n);
6831
5812
  return n;
6832
5813
  };
6833
- class ResolveCache extends LRUCache {
5814
+ class ResolveCache extends L {
6834
5815
  constructor(){
6835
5816
  super({
6836
5817
  max: 256
6837
5818
  });
6838
5819
  }
6839
5820
  }
6840
- class ChildrenCache extends LRUCache {
5821
+ class ChildrenCache extends L {
6841
5822
  constructor(maxSize = 16384){
6842
5823
  super({
6843
5824
  maxSize,
@@ -9549,7 +8530,7 @@ var __webpack_modules__ = {
9549
8530
  yargsParser.looksLikeNumber = looksLikeNumber;
9550
8531
  var external_assert_ = __webpack_require__("assert");
9551
8532
  new RegExp("\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", 'g');
9552
- const platform_shims_node = {
8533
+ const node = {
9553
8534
  fs: {
9554
8535
  readFileSync: external_fs_.readFileSync,
9555
8536
  writeFile: external_fs_.writeFile
@@ -9699,7 +8680,7 @@ var __webpack_modules__ = {
9699
8680
  locale: y18n.locale
9700
8681
  };
9701
8682
  }
9702
- const y18n_y18n = (opts)=>lib_y18n(opts, platform_shims_node);
8683
+ const y18n_y18n = (opts)=>lib_y18n(opts, node);
9703
8684
  const node_modules_y18n = y18n_y18n;
9704
8685
  let esm_dirname;
9705
8686
  try {
@@ -10283,7 +9264,7 @@ var __webpack_modules__ = {
10283
9264
  function resolveYamlMerge(data) {
10284
9265
  return '<<' === data || null === data;
10285
9266
  }
10286
- var merge = new js_yaml_type('tag:yaml.org,2002:merge', {
9267
+ var js_yaml_merge = new js_yaml_type('tag:yaml.org,2002:merge', {
10287
9268
  kind: 'scalar',
10288
9269
  resolve: resolveYamlMerge
10289
9270
  });
@@ -10442,7 +9423,7 @@ var __webpack_modules__ = {
10442
9423
  var _default = core.extend({
10443
9424
  implicit: [
10444
9425
  js_yaml_timestamp,
10445
- merge
9426
+ js_yaml_merge
10446
9427
  ],
10447
9428
  explicit: [
10448
9429
  binary,
@@ -11790,7 +10771,7 @@ var __webpack_modules__ = {
11790
10771
  throw new Error('Function yaml.' + from + " is removed in js-yaml 4. Use yaml." + to + ' instead, which is now safe by default.');
11791
10772
  };
11792
10773
  }
11793
- var js_yaml_load = loader.load;
10774
+ var load = loader.load;
11794
10775
  loader.loadAll;
11795
10776
  dumper.dump;
11796
10777
  renamed('safeLoad', 'load');
@@ -11818,19 +10799,19 @@ var __webpack_modules__ = {
11818
10799
  return allFiles;
11819
10800
  }
11820
10801
  async function parseConfigYaml(configYamlPath) {
11821
- const basePath = dirname(external_node_path_resolve(configYamlPath));
10802
+ const basePath = external_node_path_dirname(external_node_path_resolve(configYamlPath));
11822
10803
  const configContent = (0, __rspack_external_node_fs_5ea92f0c.readFileSync)(configYamlPath, 'utf8');
11823
10804
  const interpolatedContent = interpolateEnvVars(configContent);
11824
10805
  let configYaml;
11825
10806
  try {
11826
- configYaml = js_yaml_load(interpolatedContent);
10807
+ configYaml = load(interpolatedContent);
11827
10808
  } catch (error) {
11828
10809
  throw new Error(`Failed to parse config YAML: ${error}`);
11829
10810
  }
11830
10811
  if (!configYaml?.files || !Array.isArray(configYaml?.files)) throw new Error('Config YAML must contain a "files" array');
11831
10812
  const files = await expandFilePatterns(configYaml?.files, basePath);
11832
10813
  if (0 === files.length) throw new Error('No YAML files found matching the patterns in "files"');
11833
- const configFileName = basename(configYamlPath, extname(configYamlPath));
10814
+ const configFileName = external_node_path_basename(configYamlPath, external_node_path_extname(configYamlPath));
11834
10815
  const timestamp = Date.now();
11835
10816
  const defaultSummary = `${configFileName}-${timestamp}.json`;
11836
10817
  const config = {
@@ -11867,7 +10848,7 @@ var __webpack_modules__ = {
11867
10848
  const finalHeaded = keepWindow || headed;
11868
10849
  let files = parsedConfig.files;
11869
10850
  if (options?.files && options.files.length > 0) {
11870
- const basePath = dirname(external_node_path_resolve(configYamlPath));
10851
+ const basePath = external_node_path_dirname(external_node_path_resolve(configYamlPath));
11871
10852
  files = await expandFilePatterns(options.files, basePath);
11872
10853
  }
11873
10854
  return {
@@ -11907,7 +10888,7 @@ var __webpack_modules__ = {
11907
10888
  }
11908
10889
  };
11909
10890
  }
11910
- const cli_utils_debug = getDebug('midscene:cli');
10891
+ const debug = getDebug('midscene:cli');
11911
10892
  function kebabToCamel(str) {
11912
10893
  return str.replace(/-([a-z])/g, (_, letter)=>letter.toUpperCase());
11913
10894
  }
@@ -11966,7 +10947,7 @@ Usage:
11966
10947
  type: 'boolean',
11967
10948
  description: `Turn on logging to help debug why certain keys or values are not being set as you expect, default is ${config_factory_defaultConfig.dotenvDebug}`
11968
10949
  }
11969
- }).version('version', 'Show version number', "1.8.7").help().epilogue(`For complete list of configuration options, please visit:
10950
+ }).version('version', 'Show version number', "1.8.8-beta-20260601092605.0").help().epilogue(`For complete list of configuration options, please visit:
11970
10951
  • Web options: https://midscenejs.com/automate-with-scripts-in-yaml#the-web-part
11971
10952
  • Android options: https://midscenejs.com/automate-with-scripts-in-yaml#the-android-part
11972
10953
  • iOS options: https://midscenejs.com/automate-with-scripts-in-yaml#the-ios-part
@@ -11976,7 +10957,7 @@ Examples:
11976
10957
  $0 script.yaml --android.device-id emulator-5554 --android.ime-strategy yadb-for-non-ascii
11977
10958
  $0 script.yaml --ios.wda-port 8100 --ios.auto-dismiss-keyboard`).wrap(yargs().terminalWidth());
11978
10959
  const argv = await args.argv;
11979
- cli_utils_debug('argv', argv);
10960
+ debug('argv', argv);
11980
10961
  const transformedArgv = {
11981
10962
  ...argv
11982
10963
  };
@@ -12000,7 +10981,7 @@ Examples:
12000
10981
  };
12001
10982
  };
12002
10983
  async function matchYamlFiles(fileGlob, options) {
12003
- if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(fileGlob) && (0, __rspack_external_node_fs_5ea92f0c.statSync)(fileGlob).isDirectory()) fileGlob = join(fileGlob, '**/*.{yml,yaml}');
10984
+ if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(fileGlob) && (0, __rspack_external_node_fs_5ea92f0c.statSync)(fileGlob).isDirectory()) fileGlob = external_node_path_join(fileGlob, '**/*.{yml,yaml}');
12004
10985
  const { cwd } = options || {};
12005
10986
  const ignore = [
12006
10987
  '**/node_modules/**'
@@ -12014,6 +10995,341 @@ Examples:
12014
10995
  });
12015
10996
  return files.filter((file)=>file.endsWith('.yml') || file.endsWith('.yaml')).sort();
12016
10997
  }
10998
+ const notExecutedError = 'Not executed (previous task failed)';
10999
+ function execution_summary_createNotExecutedYamlResult(file) {
11000
+ return {
11001
+ file,
11002
+ success: false,
11003
+ executed: false,
11004
+ output: void 0,
11005
+ report: void 0,
11006
+ duration: 0,
11007
+ resultType: 'notExecuted',
11008
+ error: notExecutedError
11009
+ };
11010
+ }
11011
+ function getExecutionSummary(results) {
11012
+ return {
11013
+ total: results.length,
11014
+ successful: getResultsByType(results, 'success').length,
11015
+ failed: getResultsByType(results, 'failed').length,
11016
+ partialFailed: getResultsByType(results, 'partialFailed').length,
11017
+ notExecuted: getResultsByType(results, 'notExecuted').length,
11018
+ totalDuration: results.reduce((sum, r)=>sum + (r.duration || 0), 0)
11019
+ };
11020
+ }
11021
+ function getResultsByType(results, resultType) {
11022
+ return results.filter((result)=>result.resultType === resultType);
11023
+ }
11024
+ function getSummaryAbsolutePath(summary) {
11025
+ return external_node_path_resolve(getMidsceneRunSubDir('output'), summary);
11026
+ }
11027
+ function execution_summary_writeExecutionSummaryFile(summary, results) {
11028
+ const indexPath = getSummaryAbsolutePath(summary);
11029
+ const outputDir = external_node_path_dirname(indexPath);
11030
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(outputDir, {
11031
+ recursive: true
11032
+ });
11033
+ const executionSummary = getExecutionSummary(results);
11034
+ const indexData = {
11035
+ summary: {
11036
+ ...executionSummary,
11037
+ generatedAt: new Date().toLocaleString()
11038
+ },
11039
+ results: results.map((result)=>({
11040
+ script: external_node_path_relative(outputDir, result.file),
11041
+ success: result.success,
11042
+ resultType: result.resultType,
11043
+ output: result.output ? (()=>{
11044
+ const relativePath = external_node_path_relative(outputDir, result.output);
11045
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
11046
+ })() : void 0,
11047
+ report: result.report ? external_node_path_relative(outputDir, result.report) : void 0,
11048
+ error: result.error,
11049
+ duration: result.duration
11050
+ }))
11051
+ };
11052
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(indexPath, JSON.stringify(indexData, null, 2));
11053
+ return indexPath;
11054
+ }
11055
+ function execution_summary_printExecutionPlan(config) {
11056
+ console.log(' Scripts:');
11057
+ for (const file of config.files)console.log(` - ${file}`);
11058
+ console.log('📋 Execution plan');
11059
+ console.log(` Concurrency: ${config.concurrent}`);
11060
+ console.log(` Keep window: ${config.keepWindow}`);
11061
+ console.log(` Headed: ${config.headed}`);
11062
+ console.log(` Continue on error: ${config.continueOnError}`);
11063
+ console.log(` Share browser context: ${config.shareBrowserContext ?? false}`);
11064
+ console.log(` Summary output: ${config.summary}`);
11065
+ }
11066
+ function execution_summary_printExecutionFinished() {
11067
+ console.log('Execution finished:');
11068
+ }
11069
+ function printExecutionSummary(results, summaryPath) {
11070
+ const summary = getExecutionSummary(results);
11071
+ const successfulFiles = getResultsByType(results, 'success');
11072
+ const failedFiles = getResultsByType(results, 'failed');
11073
+ const partialFailedFiles = getResultsByType(results, 'partialFailed');
11074
+ const notExecutedFiles = getResultsByType(results, 'notExecuted');
11075
+ const success = 0 === summary.failed && 0 === summary.partialFailed && 0 === summary.notExecuted;
11076
+ console.log('\n📊 Execution Summary:');
11077
+ console.log(` Total files: ${summary.total}`);
11078
+ console.log(` Successful: ${summary.successful}`);
11079
+ console.log(` Failed: ${summary.failed}`);
11080
+ console.log(` Partial failed: ${summary.partialFailed}`);
11081
+ console.log(` Not executed: ${summary.notExecuted}`);
11082
+ console.log(` Duration: ${(summary.totalDuration / 1000).toFixed(2)}s`);
11083
+ console.log(` Summary: ${summaryPath}`);
11084
+ if (successfulFiles.length > 0) {
11085
+ console.log('\n✅ Successful files:');
11086
+ successfulFiles.forEach((result)=>{
11087
+ console.log(` ${result.file}`);
11088
+ });
11089
+ }
11090
+ if (failedFiles.length > 0) {
11091
+ console.log('\n❌ Failed files');
11092
+ failedFiles.forEach((result)=>{
11093
+ console.log(` ${result.file}`);
11094
+ if (result.error) console.log(` Error: ${result.error}`);
11095
+ });
11096
+ }
11097
+ if (partialFailedFiles.length > 0) {
11098
+ console.log('\n⚠️ Partial failed files (some tasks failed with continueOnError)');
11099
+ partialFailedFiles.forEach((result)=>{
11100
+ console.log(` ${result.file}`);
11101
+ if (result.error) console.log(` Error: ${result.error}`);
11102
+ });
11103
+ }
11104
+ if (notExecutedFiles.length > 0) {
11105
+ console.log('\n⏸️ Not executed files');
11106
+ notExecutedFiles.forEach((result)=>{
11107
+ console.log(` ${result.file}`);
11108
+ });
11109
+ }
11110
+ if (success) console.log('\n🎉 All files executed successfully!');
11111
+ else console.log('\n⚠️ Some files failed or were not executed.');
11112
+ return success;
11113
+ }
11114
+ const DEFAULT_YAML_TEST_TIMEOUT = 0;
11115
+ const toPosixPath = (value)=>value.split(external_node_path_sep).join('/');
11116
+ const toImportLiteral = (value)=>JSON.stringify(toPosixPath(value));
11117
+ const toVirtualModuleId = (fileStem)=>`virtual:midscene-yaml/${fileStem}.test.ts`;
11118
+ const safeFileStem = (file, index)=>{
11119
+ const base = external_node_path_basename(file, external_node_path_extname(file)).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
11120
+ return `${String(index + 1).padStart(3, '0')}-${base || 'case'}`;
11121
+ };
11122
+ const resolveTestName = (projectDir, yamlFile)=>{
11123
+ const relativePath = external_node_path_relative(projectDir, yamlFile);
11124
+ return toPosixPath(relativePath.startsWith('..') ? yamlFile : relativePath);
11125
+ };
11126
+ const createGeneratedTestContent = (options)=>{
11127
+ const testOptions = {
11128
+ testName: options.testName,
11129
+ yamlFile: options.yamlFile,
11130
+ resultFile: options.resultFile,
11131
+ ...options.caseOptions ? {
11132
+ caseOptions: options.caseOptions
11133
+ } : {},
11134
+ ...options.webRuntimeOptions ? {
11135
+ webRuntimeOptions: options.webRuntimeOptions
11136
+ } : {}
11137
+ };
11138
+ return `import { defineYamlCaseTest } from ${toImportLiteral(options.frameworkImport)};
11139
+
11140
+ defineYamlCaseTest(${JSON.stringify(testOptions, null, 2)});
11141
+ `;
11142
+ };
11143
+ const createGeneratedBatchTestContent = (options)=>{
11144
+ const testOptions = {
11145
+ testName: options.testName,
11146
+ config: options.config,
11147
+ resultFiles: options.resultFiles
11148
+ };
11149
+ return `import { defineYamlBatchTest } from ${toImportLiteral(options.frameworkImport)};
11150
+
11151
+ defineYamlBatchTest(${JSON.stringify(testOptions, null, 2)});
11152
+ `;
11153
+ };
11154
+ const resolveDefaultFrameworkImport = ()=>{
11155
+ const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : '';
11156
+ const candidates = [
11157
+ entry ? external_node_path_join(external_node_path_dirname(entry), 'framework', 'index.js') : '',
11158
+ entry ? external_node_path_join(external_node_path_dirname(entry), '..', 'dist', 'lib', 'framework', 'index.js') : ''
11159
+ ].filter(Boolean);
11160
+ const matched = candidates.find((candidate)=>(0, __rspack_external_node_fs_5ea92f0c.existsSync)(candidate));
11161
+ return matched || '@midscene/cli/dist/lib/framework/index.js';
11162
+ };
11163
+ function createRstestYamlProject(options) {
11164
+ const projectDir = external_node_path_resolve(options.projectDir || process.cwd());
11165
+ const outputDir = options.outputDir || external_node_path_join(getMidsceneRunSubDir('tmp'), `rstest-yaml-${Date.now()}`);
11166
+ const resultDir = options.resultDir || external_node_path_join(outputDir, 'results');
11167
+ const frameworkImport = options.frameworkImport || resolveDefaultFrameworkImport();
11168
+ const testTimeout = options.testTimeout ?? DEFAULT_YAML_TEST_TIMEOUT;
11169
+ (0, __rspack_external_node_fs_5ea92f0c.rmSync)(outputDir, {
11170
+ recursive: true,
11171
+ force: true
11172
+ });
11173
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(resultDir, {
11174
+ recursive: true
11175
+ });
11176
+ const virtualModules = {};
11177
+ const cases = options.files.map((file, index)=>{
11178
+ const yamlFile = external_node_path_resolve(file);
11179
+ const testName = resolveTestName(projectDir, yamlFile);
11180
+ const fileStem = safeFileStem(yamlFile, index);
11181
+ const resultFile = external_node_path_join(resultDir, `${fileStem}.json`);
11182
+ const testModule = toVirtualModuleId(fileStem);
11183
+ virtualModules[testModule] = createGeneratedTestContent({
11184
+ frameworkImport,
11185
+ yamlFile,
11186
+ resultFile,
11187
+ testName,
11188
+ caseOptions: options.caseOptions?.[yamlFile],
11189
+ webRuntimeOptions: options.webRuntimeOptions?.[yamlFile]
11190
+ });
11191
+ return {
11192
+ yamlFile,
11193
+ testModule,
11194
+ resultFile,
11195
+ testName
11196
+ };
11197
+ });
11198
+ if (options.batchConfig) {
11199
+ const batchModule = 'virtual:midscene-yaml/batch.test.ts';
11200
+ const resultFiles = Object.fromEntries(cases.map((item)=>[
11201
+ item.yamlFile,
11202
+ item.resultFile
11203
+ ]));
11204
+ return {
11205
+ projectDir,
11206
+ outputDir,
11207
+ resultDir,
11208
+ include: [
11209
+ batchModule
11210
+ ],
11211
+ virtualModules: {
11212
+ [batchModule]: createGeneratedBatchTestContent({
11213
+ frameworkImport,
11214
+ testName: 'midscene yaml batch',
11215
+ config: options.batchConfig,
11216
+ resultFiles
11217
+ })
11218
+ },
11219
+ cases,
11220
+ maxConcurrency: 1,
11221
+ testTimeout,
11222
+ bail: options.bail
11223
+ };
11224
+ }
11225
+ return {
11226
+ projectDir,
11227
+ outputDir,
11228
+ resultDir,
11229
+ include: cases.map((item)=>item.testModule),
11230
+ virtualModules,
11231
+ cases,
11232
+ maxConcurrency: options.maxConcurrency,
11233
+ testTimeout,
11234
+ bail: options.bail
11235
+ };
11236
+ }
11237
+ const requireFromCliEntry = ()=>{
11238
+ const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : external_node_path_join(process.cwd(), 'midscene-cli.js');
11239
+ return createRequire(entry);
11240
+ };
11241
+ const resolvePackageFromRstestCore = (packageName)=>{
11242
+ const require1 = requireFromCliEntry();
11243
+ const rstestPackageJsonPath = require1.resolve('@rstest/core/package.json');
11244
+ return createRequire(rstestPackageJsonPath).resolve(packageName);
11245
+ };
11246
+ const formatRunError = (error)=>error.stack || `${error.name}: ${error.message}`;
11247
+ async function runRstestYamlProject(options) {
11248
+ const [{ runRstest }, { rspack }] = await Promise.all([
11249
+ import("@rstest/core/api"),
11250
+ import(pathToFileURL(resolvePackageFromRstestCore('@rsbuild/core')).href)
11251
+ ]);
11252
+ const { project } = options;
11253
+ const maxConcurrency = void 0 !== project.maxConcurrency ? Math.max(1, project.maxConcurrency) : void 0;
11254
+ const inlineConfig = {
11255
+ root: project.projectDir,
11256
+ include: project.include,
11257
+ testEnvironment: 'node',
11258
+ testTimeout: project.testTimeout,
11259
+ ...void 0 !== maxConcurrency ? {
11260
+ maxConcurrency
11261
+ } : {},
11262
+ ...void 0 !== maxConcurrency ? {
11263
+ pool: {
11264
+ maxWorkers: maxConcurrency,
11265
+ minWorkers: maxConcurrency
11266
+ }
11267
+ } : {},
11268
+ ...void 0 !== project.bail ? {
11269
+ bail: project.bail
11270
+ } : {},
11271
+ reporters: [],
11272
+ tools: {
11273
+ rspack: (_config, { appendPlugins })=>{
11274
+ appendPlugins(new rspack.experiments.VirtualModulesPlugin(project.virtualModules));
11275
+ }
11276
+ }
11277
+ };
11278
+ const result = await runRstest({
11279
+ cwd: options.cwd || project.projectDir,
11280
+ inlineConfig
11281
+ });
11282
+ if (!result.ok && 'pipe' !== options.stdio && result.unhandledErrors.length) console.error(result.unhandledErrors.map((error)=>formatRunError(error)).join('\n'));
11283
+ return result.ok ? 0 : 1;
11284
+ }
11285
+ const createCaseOptions = (config)=>{
11286
+ const caseOptions = {};
11287
+ for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
11288
+ globalConfig: config.globalConfig
11289
+ };
11290
+ return caseOptions;
11291
+ };
11292
+ const createWebRuntimeOptions = (config, runtimeOptions)=>{
11293
+ const caseOptions = {};
11294
+ for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
11295
+ headed: runtimeOptions.headed ?? config.headed,
11296
+ keepWindow: runtimeOptions.keepWindow ?? config.keepWindow
11297
+ };
11298
+ return caseOptions;
11299
+ };
11300
+ const readProjectResults = (project)=>project.cases.map((item)=>{
11301
+ if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(item.resultFile)) return JSON.parse((0, __rspack_external_node_fs_5ea92f0c.readFileSync)(item.resultFile, 'utf8'));
11302
+ return execution_summary_createNotExecutedYamlResult(item.yamlFile);
11303
+ });
11304
+ async function runFrameworkTestConfig(config, commandOptions = {}) {
11305
+ execution_summary_printExecutionPlan(config);
11306
+ const projectDir = external_node_path_resolve(commandOptions.projectDir || process.cwd());
11307
+ const project = createRstestYamlProject({
11308
+ files: config.files,
11309
+ projectDir,
11310
+ outputDir: commandOptions.outputDir,
11311
+ frameworkImport: commandOptions.frameworkImport,
11312
+ caseOptions: createCaseOptions(config),
11313
+ webRuntimeOptions: createWebRuntimeOptions(config, commandOptions),
11314
+ maxConcurrency: commandOptions.concurrent ?? config.concurrent,
11315
+ bail: config.continueOnError ? 0 : 1,
11316
+ batchConfig: config.shareBrowserContext ? config : void 0
11317
+ });
11318
+ const runner = commandOptions.rstestRunner || runRstestYamlProject;
11319
+ const exitCode = await runner({
11320
+ project,
11321
+ cwd: projectDir,
11322
+ stdio: commandOptions.stdio
11323
+ });
11324
+ const results = readProjectResults(project);
11325
+ const summaryPath = execution_summary_writeExecutionSummaryFile(config.summary, results);
11326
+ execution_summary_printExecutionFinished();
11327
+ const success = printExecutionSummary(results, summaryPath);
11328
+ return success ? exitCode : 1;
11329
+ }
11330
+ getDebug('create-yaml-player');
11331
+ __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js");
11332
+ process.env.MIDSCENE_CLI_LOG_ON_NON_TTY || process.stdout.isTTY;
12017
11333
  Promise.resolve((async ()=>{
12018
11334
  const rawArgs = process.argv.slice(2);
12019
11335
  const [firstArg] = rawArgs;
@@ -12072,7 +11388,7 @@ Examples:
12072
11388
  console.error('Could not create a valid configuration.');
12073
11389
  process.exit(1);
12074
11390
  }
12075
- const dotEnvConfigFile = join(process.cwd(), '.env');
11391
+ const dotEnvConfigFile = external_node_path_join(process.cwd(), '.env');
12076
11392
  if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(dotEnvConfigFile)) {
12077
11393
  console.log(` Env file: ${dotEnvConfigFile}`);
12078
11394
  main_default().config({
@@ -12081,16 +11397,11 @@ Examples:
12081
11397
  override: config.dotenvOverride
12082
11398
  });
12083
11399
  }
12084
- const executor = new BatchRunner(config);
12085
- await executor.run();
12086
- const success = executor.printExecutionSummary();
11400
+ const exitCode = await runFrameworkTestConfig(config);
12087
11401
  if (config.keepWindow) setInterval(()=>{
12088
11402
  console.log('browser is still running, use ctrl+c to stop it');
12089
11403
  }, 5000);
12090
- else {
12091
- if (!success) process.exit(1);
12092
- process.exit(0);
12093
- }
11404
+ else process.exit(exitCode);
12094
11405
  })().catch((e1)=>{
12095
11406
  console.error(e1);
12096
11407
  process.exit(1);