storybook-addon-designbook 0.7.0 → 0.9.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/cli.js CHANGED
@@ -4,6 +4,7 @@ import { readFileSync, existsSync, readdirSync, mkdirSync, appendFileSync, renam
4
4
  import { resolve, dirname, basename, parse, join, extname as extname$1, delimiter, relative, win32, posix } from 'path';
5
5
  import { load, dump } from 'js-yaml';
6
6
  import jsonata6 from 'jsonata';
7
+ import { channel, tracingChannel } from 'diagnostics_channel';
7
8
  import { EventEmitter } from 'events';
8
9
  import Stream from 'stream';
9
10
  import { StringDecoder } from 'string_decoder';
@@ -11,11 +12,11 @@ import { fileURLToPath } from 'url';
11
12
  import { realpath, readlink, readdir, lstat, readFile, mkdir, writeFile } from 'fs/promises';
12
13
  import { unescape, escape, Minimatch, GLOBSTAR } from 'minimatch';
13
14
  import { homedir } from 'os';
14
- import { spawn, execSync } from 'child_process';
15
+ import { execSync, spawn } from 'child_process';
15
16
  import * as http from 'http';
16
17
  import { createHash, randomBytes } from 'crypto';
17
18
  import { Command } from 'commander';
18
- import vm from 'vm';
19
+ import 'vm';
19
20
  import fm from 'front-matter';
20
21
  import { performance as performance$1 } from 'perf_hooks';
21
22
 
@@ -247,1436 +248,589 @@ var init_entity_mapping = __esm({
247
248
  init_data_pool();
248
249
  }
249
250
  });
250
-
251
- // ../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js
252
- var defaultPerf, warned, PROCESS, emitWarning, AC, AS, shouldWarn, isPosInt, getUintArray, ZeroArray, Stack, LRUCache;
253
- var init_esm = __esm({
254
- "../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"() {
255
- defaultPerf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
256
- warned = /* @__PURE__ */ new Set();
257
- PROCESS = typeof process === "object" && !!process ? process : {};
258
- emitWarning = (msg, type, code, fn) => {
259
- typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
251
+ var S, W, C, D, U, L, P, H, F, j, O, R, M;
252
+ var init_index_min = __esm({
253
+ "../../node_modules/.pnpm/lru-cache@11.3.6/node_modules/lru-cache/dist/esm/node/index.min.js"() {
254
+ S = channel("lru-cache:metrics");
255
+ W = tracingChannel("lru-cache");
256
+ C = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date;
257
+ D = () => S.hasSubscribers || W.hasSubscribers;
258
+ U = /* @__PURE__ */ new Set();
259
+ L = typeof process == "object" && process ? process : {};
260
+ P = (u3, e, t, i) => {
261
+ typeof L.emitWarning == "function" ? L.emitWarning(u3, e, t, i) : console.error(`[${t}] ${e}: ${u3}`);
260
262
  };
261
- AC = globalThis.AbortController;
262
- AS = globalThis.AbortSignal;
263
- if (typeof AC === "undefined") {
264
- AS = class AbortSignal {
265
- onabort;
266
- _onabort = [];
267
- reason;
268
- aborted = false;
269
- addEventListener(_, fn) {
270
- this._onabort.push(fn);
271
- }
272
- };
273
- AC = class AbortController {
274
- constructor() {
275
- warnACPolyfill();
276
- }
277
- signal = new AS();
278
- abort(reason) {
279
- if (this.signal.aborted)
280
- return;
281
- this.signal.reason = reason;
282
- this.signal.aborted = true;
283
- for (const fn of this.signal._onabort) {
284
- fn(reason);
285
- }
286
- this.signal.onabort?.(reason);
287
- }
288
- };
289
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
290
- const warnACPolyfill = () => {
291
- if (!printACPolyfillWarning)
292
- return;
293
- printACPolyfillWarning = false;
294
- 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);
295
- };
296
- }
297
- shouldWarn = (code) => !warned.has(code);
298
- isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
299
- getUintArray = (max) => !isPosInt(max) ? null : 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;
300
- ZeroArray = class extends Array {
301
- constructor(size) {
302
- super(size);
303
- this.fill(0);
263
+ H = (u3) => !U.has(u3);
264
+ F = (u3) => !!u3 && u3 === Math.floor(u3) && u3 > 0 && isFinite(u3);
265
+ j = (u3) => F(u3) ? u3 <= Math.pow(2, 8) ? Uint8Array : u3 <= Math.pow(2, 16) ? Uint16Array : u3 <= Math.pow(2, 32) ? Uint32Array : u3 <= Number.MAX_SAFE_INTEGER ? O : null : null;
266
+ O = class extends Array {
267
+ constructor(e) {
268
+ super(e), this.fill(0);
304
269
  }
305
270
  };
306
- Stack = class _Stack {
271
+ R = class u {
307
272
  heap;
308
273
  length;
309
- // private constructor
310
- static #constructing = false;
311
- static create(max) {
312
- const HeapCls = getUintArray(max);
313
- if (!HeapCls)
314
- return [];
315
- _Stack.#constructing = true;
316
- const s = new _Stack(max, HeapCls);
317
- _Stack.#constructing = false;
318
- return s;
274
+ static #o = false;
275
+ static create(e) {
276
+ let t = j(e);
277
+ if (!t) return [];
278
+ u.#o = true;
279
+ let i = new u(e, t);
280
+ return u.#o = false, i;
319
281
  }
320
- constructor(max, HeapCls) {
321
- if (!_Stack.#constructing) {
322
- throw new TypeError("instantiate Stack using Stack.create(n)");
323
- }
324
- this.heap = new HeapCls(max);
325
- this.length = 0;
282
+ constructor(e, t) {
283
+ if (!u.#o) throw new TypeError("instantiate Stack using Stack.create(n)");
284
+ this.heap = new t(e), this.length = 0;
326
285
  }
327
- push(n) {
328
- this.heap[this.length++] = n;
286
+ push(e) {
287
+ this.heap[this.length++] = e;
329
288
  }
330
289
  pop() {
331
290
  return this.heap[--this.length];
332
291
  }
333
292
  };
334
- LRUCache = class _LRUCache {
335
- // options that cannot be changed without disaster
336
- #max;
337
- #maxSize;
338
- #dispose;
339
- #onInsert;
340
- #disposeAfter;
341
- #fetchMethod;
342
- #memoMethod;
343
- #perf;
344
- /**
345
- * {@link LRUCache.OptionsBase.perf}
346
- */
293
+ M = class u2 {
294
+ #o;
295
+ #u;
296
+ #w;
297
+ #x;
298
+ #S;
299
+ #M;
300
+ #U;
301
+ #m;
347
302
  get perf() {
348
- return this.#perf;
303
+ return this.#m;
349
304
  }
350
- /**
351
- * {@link LRUCache.OptionsBase.ttl}
352
- */
353
305
  ttl;
354
- /**
355
- * {@link LRUCache.OptionsBase.ttlResolution}
356
- */
357
306
  ttlResolution;
358
- /**
359
- * {@link LRUCache.OptionsBase.ttlAutopurge}
360
- */
361
307
  ttlAutopurge;
362
- /**
363
- * {@link LRUCache.OptionsBase.updateAgeOnGet}
364
- */
365
308
  updateAgeOnGet;
366
- /**
367
- * {@link LRUCache.OptionsBase.updateAgeOnHas}
368
- */
369
309
  updateAgeOnHas;
370
- /**
371
- * {@link LRUCache.OptionsBase.allowStale}
372
- */
373
310
  allowStale;
374
- /**
375
- * {@link LRUCache.OptionsBase.noDisposeOnSet}
376
- */
377
311
  noDisposeOnSet;
378
- /**
379
- * {@link LRUCache.OptionsBase.noUpdateTTL}
380
- */
381
312
  noUpdateTTL;
382
- /**
383
- * {@link LRUCache.OptionsBase.maxEntrySize}
384
- */
385
313
  maxEntrySize;
386
- /**
387
- * {@link LRUCache.OptionsBase.sizeCalculation}
388
- */
389
314
  sizeCalculation;
390
- /**
391
- * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
392
- */
393
315
  noDeleteOnFetchRejection;
394
- /**
395
- * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
396
- */
397
316
  noDeleteOnStaleGet;
398
- /**
399
- * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
400
- */
401
317
  allowStaleOnFetchAbort;
402
- /**
403
- * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
404
- */
405
318
  allowStaleOnFetchRejection;
406
- /**
407
- * {@link LRUCache.OptionsBase.ignoreFetchAbort}
408
- */
409
319
  ignoreFetchAbort;
410
- // computed properties
411
- #size;
412
- #calculatedSize;
413
- #keyMap;
414
- #keyList;
415
- #valList;
416
- #next;
417
- #prev;
418
- #head;
419
- #tail;
420
- #free;
421
- #disposed;
422
- #sizes;
423
- #starts;
424
- #ttls;
425
- #autopurgeTimers;
426
- #hasDispose;
427
- #hasFetchMethod;
428
- #hasDisposeAfter;
429
- #hasOnInsert;
430
- /**
431
- * Do not call this method unless you need to inspect the
432
- * inner workings of the cache. If anything returned by this
433
- * object is modified in any way, strange breakage may occur.
434
- *
435
- * These fields are private for a reason!
436
- *
437
- * @internal
438
- */
439
- static unsafeExposeInternals(c) {
440
- return {
441
- // properties
442
- starts: c.#starts,
443
- ttls: c.#ttls,
444
- autopurgeTimers: c.#autopurgeTimers,
445
- sizes: c.#sizes,
446
- keyMap: c.#keyMap,
447
- keyList: c.#keyList,
448
- valList: c.#valList,
449
- next: c.#next,
450
- prev: c.#prev,
451
- get head() {
452
- return c.#head;
453
- },
454
- get tail() {
455
- return c.#tail;
456
- },
457
- free: c.#free,
458
- // methods
459
- isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
460
- backgroundFetch: (k, index, options, context2) => c.#backgroundFetch(k, index, options, context2),
461
- moveToTail: (index) => c.#moveToTail(index),
462
- indexes: (options) => c.#indexes(options),
463
- rindexes: (options) => c.#rindexes(options),
464
- isStale: (index) => c.#isStale(index)
465
- };
320
+ #n;
321
+ #b;
322
+ #s;
323
+ #i;
324
+ #t;
325
+ #a;
326
+ #c;
327
+ #l;
328
+ #h;
329
+ #y;
330
+ #r;
331
+ #_;
332
+ #F;
333
+ #d;
334
+ #g;
335
+ #T;
336
+ #W;
337
+ #f;
338
+ #j;
339
+ static unsafeExposeInternals(e) {
340
+ return { starts: e.#F, ttls: e.#d, autopurgeTimers: e.#g, sizes: e.#_, keyMap: e.#s, keyList: e.#i, valList: e.#t, next: e.#a, prev: e.#c, get head() {
341
+ return e.#l;
342
+ }, get tail() {
343
+ return e.#h;
344
+ }, free: e.#y, isBackgroundFetch: (t) => e.#e(t), backgroundFetch: (t, i, s, n) => e.#P(t, i, s, n), moveToTail: (t) => e.#L(t), indexes: (t) => e.#A(t), rindexes: (t) => e.#z(t), isStale: (t) => e.#p(t) };
466
345
  }
467
- // Protected read-only members
468
- /**
469
- * {@link LRUCache.OptionsBase.max} (read-only)
470
- */
471
346
  get max() {
472
- return this.#max;
347
+ return this.#o;
473
348
  }
474
- /**
475
- * {@link LRUCache.OptionsBase.maxSize} (read-only)
476
- */
477
349
  get maxSize() {
478
- return this.#maxSize;
350
+ return this.#u;
479
351
  }
480
- /**
481
- * The total computed size of items in the cache (read-only)
482
- */
483
352
  get calculatedSize() {
484
- return this.#calculatedSize;
353
+ return this.#b;
485
354
  }
486
- /**
487
- * The number of items stored in the cache (read-only)
488
- */
489
355
  get size() {
490
- return this.#size;
356
+ return this.#n;
491
357
  }
492
- /**
493
- * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
494
- */
495
358
  get fetchMethod() {
496
- return this.#fetchMethod;
359
+ return this.#M;
497
360
  }
498
361
  get memoMethod() {
499
- return this.#memoMethod;
362
+ return this.#U;
500
363
  }
501
- /**
502
- * {@link LRUCache.OptionsBase.dispose} (read-only)
503
- */
504
364
  get dispose() {
505
- return this.#dispose;
365
+ return this.#w;
506
366
  }
507
- /**
508
- * {@link LRUCache.OptionsBase.onInsert} (read-only)
509
- */
510
367
  get onInsert() {
511
- return this.#onInsert;
368
+ return this.#x;
512
369
  }
513
- /**
514
- * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
515
- */
516
370
  get disposeAfter() {
517
- return this.#disposeAfter;
518
- }
519
- constructor(options) {
520
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, perf } = options;
521
- if (perf !== void 0) {
522
- if (typeof perf?.now !== "function") {
523
- throw new TypeError("perf option must have a now() method if specified");
524
- }
525
- }
526
- this.#perf = perf ?? defaultPerf;
527
- if (max !== 0 && !isPosInt(max)) {
528
- throw new TypeError("max option must be a nonnegative integer");
529
- }
530
- const UintArray = max ? getUintArray(max) : Array;
531
- if (!UintArray) {
532
- throw new Error("invalid max value: " + max);
533
- }
534
- this.#max = max;
535
- this.#maxSize = maxSize;
536
- this.maxEntrySize = maxEntrySize || this.#maxSize;
537
- this.sizeCalculation = sizeCalculation;
538
- if (this.sizeCalculation) {
539
- if (!this.#maxSize && !this.maxEntrySize) {
540
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
541
- }
542
- if (typeof this.sizeCalculation !== "function") {
543
- throw new TypeError("sizeCalculation set to non-function");
544
- }
545
- }
546
- if (memoMethod !== void 0 && typeof memoMethod !== "function") {
547
- throw new TypeError("memoMethod must be a function if defined");
548
- }
549
- this.#memoMethod = memoMethod;
550
- if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
551
- throw new TypeError("fetchMethod must be a function if specified");
552
- }
553
- this.#fetchMethod = fetchMethod;
554
- this.#hasFetchMethod = !!fetchMethod;
555
- this.#keyMap = /* @__PURE__ */ new Map();
556
- this.#keyList = new Array(max).fill(void 0);
557
- this.#valList = new Array(max).fill(void 0);
558
- this.#next = new UintArray(max);
559
- this.#prev = new UintArray(max);
560
- this.#head = 0;
561
- this.#tail = 0;
562
- this.#free = Stack.create(max);
563
- this.#size = 0;
564
- this.#calculatedSize = 0;
565
- if (typeof dispose === "function") {
566
- this.#dispose = dispose;
567
- }
568
- if (typeof onInsert === "function") {
569
- this.#onInsert = onInsert;
570
- }
571
- if (typeof disposeAfter === "function") {
572
- this.#disposeAfter = disposeAfter;
573
- this.#disposed = [];
574
- } else {
575
- this.#disposeAfter = void 0;
576
- this.#disposed = void 0;
577
- }
578
- this.#hasDispose = !!this.#dispose;
579
- this.#hasOnInsert = !!this.#onInsert;
580
- this.#hasDisposeAfter = !!this.#disposeAfter;
581
- this.noDisposeOnSet = !!noDisposeOnSet;
582
- this.noUpdateTTL = !!noUpdateTTL;
583
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
584
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
585
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
586
- this.ignoreFetchAbort = !!ignoreFetchAbort;
587
- if (this.maxEntrySize !== 0) {
588
- if (this.#maxSize !== 0) {
589
- if (!isPosInt(this.#maxSize)) {
590
- throw new TypeError("maxSize must be a positive integer if specified");
591
- }
592
- }
593
- if (!isPosInt(this.maxEntrySize)) {
594
- throw new TypeError("maxEntrySize must be a positive integer if specified");
595
- }
596
- this.#initializeSizeTracking();
597
- }
598
- this.allowStale = !!allowStale;
599
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
600
- this.updateAgeOnGet = !!updateAgeOnGet;
601
- this.updateAgeOnHas = !!updateAgeOnHas;
602
- this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
603
- this.ttlAutopurge = !!ttlAutopurge;
604
- this.ttl = ttl || 0;
605
- if (this.ttl) {
606
- if (!isPosInt(this.ttl)) {
607
- throw new TypeError("ttl must be a positive integer if specified");
608
- }
609
- this.#initializeTTLTracking();
610
- }
611
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
612
- throw new TypeError("At least one of max, maxSize, or ttl is required");
613
- }
614
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
615
- const code = "LRU_CACHE_UNBOUNDED";
616
- if (shouldWarn(code)) {
617
- warned.add(code);
618
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
619
- emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
620
- }
621
- }
622
- }
623
- /**
624
- * Return the number of ms left in the item's TTL. If item is not in cache,
625
- * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
626
- */
627
- getRemainingTTL(key) {
628
- return this.#keyMap.has(key) ? Infinity : 0;
629
- }
630
- #initializeTTLTracking() {
631
- const ttls = new ZeroArray(this.#max);
632
- const starts = new ZeroArray(this.#max);
633
- this.#ttls = ttls;
634
- this.#starts = starts;
635
- const purgeTimers = this.ttlAutopurge ? new Array(this.#max) : void 0;
636
- this.#autopurgeTimers = purgeTimers;
637
- this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
638
- starts[index] = ttl !== 0 ? start : 0;
639
- ttls[index] = ttl;
640
- if (purgeTimers?.[index]) {
641
- clearTimeout(purgeTimers[index]);
642
- purgeTimers[index] = void 0;
643
- }
644
- if (ttl !== 0 && purgeTimers) {
645
- const t = setTimeout(() => {
646
- if (this.#isStale(index)) {
647
- this.#delete(this.#keyList[index], "expire");
648
- }
649
- }, ttl + 1);
650
- if (t.unref) {
651
- t.unref();
652
- }
653
- purgeTimers[index] = t;
654
- }
371
+ return this.#S;
372
+ }
373
+ constructor(e) {
374
+ let { max: t = 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 } = e;
375
+ if (x !== void 0 && typeof x?.now != "function") throw new TypeError("perf option must have a now() method if specified");
376
+ if (this.#m = x ?? C, t !== 0 && !F(t)) throw new TypeError("max option must be a nonnegative integer");
377
+ let v = t ? j(t) : Array;
378
+ if (!v) throw new Error("invalid max value: " + t);
379
+ if (this.#o = t, this.#u = T, this.maxEntrySize = w || this.#u, this.sizeCalculation = y, this.sizeCalculation) {
380
+ if (!this.#u && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
381
+ if (typeof this.sizeCalculation != "function") throw new TypeError("sizeCalculation set to non-function");
382
+ }
383
+ if (m !== void 0 && typeof m != "function") throw new TypeError("memoMethod must be a function if defined");
384
+ if (this.#U = m, a !== void 0 && typeof a != "function") throw new TypeError("fetchMethod must be a function if specified");
385
+ if (this.#M = a, this.#W = !!a, this.#s = /* @__PURE__ */ new Map(), this.#i = Array.from({ length: t }).fill(void 0), this.#t = Array.from({ length: t }).fill(void 0), this.#a = new v(t), this.#c = new v(t), this.#l = 0, this.#h = 0, this.#y = R.create(t), this.#n = 0, this.#b = 0, typeof l == "function" && (this.#w = l), typeof c == "function" && (this.#x = c), typeof f == "function" ? (this.#S = f, this.#r = []) : (this.#S = void 0, this.#r = void 0), this.#T = !!this.#w, this.#j = !!this.#x, this.#f = !!this.#S, this.noDisposeOnSet = !!g, this.noUpdateTTL = !!p, this.noDeleteOnFetchRejection = !!_, this.allowStaleOnFetchRejection = !!d, this.allowStaleOnFetchAbort = !!A, this.ignoreFetchAbort = !!z, this.maxEntrySize !== 0) {
386
+ if (this.#u !== 0 && !F(this.#u)) throw new TypeError("maxSize must be a positive integer if specified");
387
+ if (!F(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified");
388
+ this.#X();
389
+ }
390
+ if (this.allowStale = !!h, this.noDeleteOnStaleGet = !!b, this.updateAgeOnGet = !!o, this.updateAgeOnHas = !!r, this.ttlResolution = F(s) || s === 0 ? s : 1, this.ttlAutopurge = !!n, this.ttl = i || 0, this.ttl) {
391
+ if (!F(this.ttl)) throw new TypeError("ttl must be a positive integer if specified");
392
+ this.#H();
393
+ }
394
+ if (this.#o === 0 && this.ttl === 0 && this.#u === 0) throw new TypeError("At least one of max, maxSize, or ttl is required");
395
+ if (!this.ttlAutopurge && !this.#o && !this.#u) {
396
+ let E = "LRU_CACHE_UNBOUNDED";
397
+ H(E) && (U.add(E), P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", E, u2));
398
+ }
399
+ }
400
+ getRemainingTTL(e) {
401
+ return this.#s.has(e) ? 1 / 0 : 0;
402
+ }
403
+ #H() {
404
+ let e = new O(this.#o), t = new O(this.#o);
405
+ this.#d = e, this.#F = t;
406
+ let i = this.ttlAutopurge ? Array.from({ length: this.#o }) : void 0;
407
+ this.#g = i, this.#N = (r, h, l = this.#m.now()) => {
408
+ t[r] = h !== 0 ? l : 0, e[r] = h, s(r, h);
409
+ }, this.#D = (r) => {
410
+ t[r] = e[r] !== 0 ? this.#m.now() : 0, s(r, e[r]);
655
411
  };
656
- this.#updateItemAge = (index) => {
657
- starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0;
412
+ let s = this.ttlAutopurge ? (r, h) => {
413
+ if (i?.[r] && (clearTimeout(i[r]), i[r] = void 0), h && h !== 0 && i) {
414
+ let l = setTimeout(() => {
415
+ this.#p(r) && this.#v(this.#i[r], "expire");
416
+ }, h + 1);
417
+ l.unref && l.unref(), i[r] = l;
418
+ }
419
+ } : () => {
658
420
  };
659
- this.#statusTTL = (status, index) => {
660
- if (ttls[index]) {
661
- const ttl = ttls[index];
662
- const start = starts[index];
663
- if (!ttl || !start)
664
- return;
665
- status.ttl = ttl;
666
- status.start = start;
667
- status.now = cachedNow || getNow();
668
- const age = status.now - start;
669
- status.remainingTTL = ttl - age;
421
+ this.#E = (r, h) => {
422
+ if (e[h]) {
423
+ let l = e[h], c = t[h];
424
+ if (!l || !c) return;
425
+ r.ttl = l, r.start = c, r.now = n || o();
426
+ let f = r.now - c;
427
+ r.remainingTTL = l - f;
670
428
  }
671
429
  };
672
- let cachedNow = 0;
673
- const getNow = () => {
674
- const n = this.#perf.now();
430
+ let n = 0, o = () => {
431
+ let r = this.#m.now();
675
432
  if (this.ttlResolution > 0) {
676
- cachedNow = n;
677
- const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
678
- if (t.unref) {
679
- t.unref();
680
- }
681
- }
682
- return n;
683
- };
684
- this.getRemainingTTL = (key) => {
685
- const index = this.#keyMap.get(key);
686
- if (index === void 0) {
687
- return 0;
688
- }
689
- const ttl = ttls[index];
690
- const start = starts[index];
691
- if (!ttl || !start) {
692
- return Infinity;
433
+ n = r;
434
+ let h = setTimeout(() => n = 0, this.ttlResolution);
435
+ h.unref && h.unref();
693
436
  }
694
- const age = (cachedNow || getNow()) - start;
695
- return ttl - age;
437
+ return r;
696
438
  };
697
- this.#isStale = (index) => {
698
- const s = starts[index];
699
- const t = ttls[index];
700
- return !!t && !!s && (cachedNow || getNow()) - s > t;
439
+ this.getRemainingTTL = (r) => {
440
+ let h = this.#s.get(r);
441
+ if (h === void 0) return 0;
442
+ let l = e[h], c = t[h];
443
+ if (!l || !c) return 1 / 0;
444
+ let f = (n || o()) - c;
445
+ return l - f;
446
+ }, this.#p = (r) => {
447
+ let h = t[r], l = e[r];
448
+ return !!l && !!h && (n || o()) - h > l;
701
449
  };
702
450
  }
703
- // conditionally set private methods related to TTL
704
- #updateItemAge = () => {
451
+ #D = () => {
705
452
  };
706
- #statusTTL = () => {
453
+ #E = () => {
707
454
  };
708
- #setItemTTL = () => {
455
+ #N = () => {
709
456
  };
710
- /* c8 ignore stop */
711
- #isStale = () => false;
712
- #initializeSizeTracking() {
713
- const sizes = new ZeroArray(this.#max);
714
- this.#calculatedSize = 0;
715
- this.#sizes = sizes;
716
- this.#removeItemSize = (index) => {
717
- this.#calculatedSize -= sizes[index];
718
- sizes[index] = 0;
719
- };
720
- this.#requireSize = (k, v, size, sizeCalculation) => {
721
- if (this.#isBackgroundFetch(v)) {
722
- return 0;
723
- }
724
- if (!isPosInt(size)) {
725
- if (sizeCalculation) {
726
- if (typeof sizeCalculation !== "function") {
727
- throw new TypeError("sizeCalculation must be a function");
728
- }
729
- size = sizeCalculation(v, k);
730
- if (!isPosInt(size)) {
731
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
732
- }
733
- } else {
734
- throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
735
- }
736
- }
737
- return size;
738
- };
739
- this.#addItemSize = (index, size, status) => {
740
- sizes[index] = size;
741
- if (this.#maxSize) {
742
- const maxSize = this.#maxSize - sizes[index];
743
- while (this.#calculatedSize > maxSize) {
744
- this.#evict(true);
745
- }
746
- }
747
- this.#calculatedSize += sizes[index];
748
- if (status) {
749
- status.entrySize = size;
750
- status.totalCalculatedSize = this.#calculatedSize;
751
- }
457
+ #p = () => false;
458
+ #X() {
459
+ let e = new O(this.#o);
460
+ this.#b = 0, this.#_ = e, this.#R = (t) => {
461
+ this.#b -= e[t], e[t] = 0;
462
+ }, this.#k = (t, i, s, n) => {
463
+ if (this.#e(i)) return 0;
464
+ if (!F(s)) if (n) {
465
+ if (typeof n != "function") throw new TypeError("sizeCalculation must be a function");
466
+ if (s = n(i, t), !F(s)) throw new TypeError("sizeCalculation return invalid (expect positive integer)");
467
+ } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
468
+ return s;
469
+ }, this.#I = (t, i, s) => {
470
+ if (e[t] = i, this.#u) {
471
+ let n = this.#u - e[t];
472
+ for (; this.#b > n; ) this.#G(true);
473
+ }
474
+ this.#b += e[t], s && (s.entrySize = i, s.totalCalculatedSize = this.#b);
752
475
  };
753
476
  }
754
- #removeItemSize = (_i) => {
477
+ #R = (e) => {
755
478
  };
756
- #addItemSize = (_i, _s, _st) => {
479
+ #I = (e, t, i) => {
757
480
  };
758
- #requireSize = (_k, _v, size, sizeCalculation) => {
759
- if (size || sizeCalculation) {
760
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
761
- }
481
+ #k = (e, t, i, s) => {
482
+ if (i || s) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
762
483
  return 0;
763
484
  };
764
- *#indexes({ allowStale = this.allowStale } = {}) {
765
- if (this.#size) {
766
- for (let i = this.#tail; true; ) {
767
- if (!this.#isValidIndex(i)) {
768
- break;
769
- }
770
- if (allowStale || !this.#isStale(i)) {
771
- yield i;
772
- }
773
- if (i === this.#head) {
774
- break;
775
- } else {
776
- i = this.#prev[i];
777
- }
778
- }
779
- }
485
+ *#A({ allowStale: e = this.allowStale } = {}) {
486
+ if (this.#n) for (let t = this.#h; this.#V(t) && ((e || !this.#p(t)) && (yield t), t !== this.#l); ) t = this.#c[t];
780
487
  }
781
- *#rindexes({ allowStale = this.allowStale } = {}) {
782
- if (this.#size) {
783
- for (let i = this.#head; true; ) {
784
- if (!this.#isValidIndex(i)) {
785
- break;
786
- }
787
- if (allowStale || !this.#isStale(i)) {
788
- yield i;
789
- }
790
- if (i === this.#tail) {
791
- break;
792
- } else {
793
- i = this.#next[i];
794
- }
795
- }
796
- }
488
+ *#z({ allowStale: e = this.allowStale } = {}) {
489
+ if (this.#n) for (let t = this.#l; this.#V(t) && ((e || !this.#p(t)) && (yield t), t !== this.#h); ) t = this.#a[t];
797
490
  }
798
- #isValidIndex(index) {
799
- return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
491
+ #V(e) {
492
+ return e !== void 0 && this.#s.get(this.#i[e]) === e;
800
493
  }
801
- /**
802
- * Return a generator yielding `[key, value]` pairs,
803
- * in order from most recently used to least recently used.
804
- */
805
494
  *entries() {
806
- for (const i of this.#indexes()) {
807
- if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
808
- yield [this.#keyList[i], this.#valList[i]];
809
- }
810
- }
495
+ for (let e of this.#A()) this.#t[e] !== void 0 && this.#i[e] !== void 0 && !this.#e(this.#t[e]) && (yield [this.#i[e], this.#t[e]]);
811
496
  }
812
- /**
813
- * Inverse order version of {@link LRUCache.entries}
814
- *
815
- * Return a generator yielding `[key, value]` pairs,
816
- * in order from least recently used to most recently used.
817
- */
818
497
  *rentries() {
819
- for (const i of this.#rindexes()) {
820
- if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
821
- yield [this.#keyList[i], this.#valList[i]];
822
- }
823
- }
498
+ for (let e of this.#z()) this.#t[e] !== void 0 && this.#i[e] !== void 0 && !this.#e(this.#t[e]) && (yield [this.#i[e], this.#t[e]]);
824
499
  }
825
- /**
826
- * Return a generator yielding the keys in the cache,
827
- * in order from most recently used to least recently used.
828
- */
829
500
  *keys() {
830
- for (const i of this.#indexes()) {
831
- const k = this.#keyList[i];
832
- if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
833
- yield k;
834
- }
501
+ for (let e of this.#A()) {
502
+ let t = this.#i[e];
503
+ t !== void 0 && !this.#e(this.#t[e]) && (yield t);
835
504
  }
836
505
  }
837
- /**
838
- * Inverse order version of {@link LRUCache.keys}
839
- *
840
- * Return a generator yielding the keys in the cache,
841
- * in order from least recently used to most recently used.
842
- */
843
506
  *rkeys() {
844
- for (const i of this.#rindexes()) {
845
- const k = this.#keyList[i];
846
- if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
847
- yield k;
848
- }
507
+ for (let e of this.#z()) {
508
+ let t = this.#i[e];
509
+ t !== void 0 && !this.#e(this.#t[e]) && (yield t);
849
510
  }
850
511
  }
851
- /**
852
- * Return a generator yielding the values in the cache,
853
- * in order from most recently used to least recently used.
854
- */
855
512
  *values() {
856
- for (const i of this.#indexes()) {
857
- const v = this.#valList[i];
858
- if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
859
- yield this.#valList[i];
860
- }
861
- }
513
+ for (let e of this.#A()) this.#t[e] !== void 0 && !this.#e(this.#t[e]) && (yield this.#t[e]);
862
514
  }
863
- /**
864
- * Inverse order version of {@link LRUCache.values}
865
- *
866
- * Return a generator yielding the values in the cache,
867
- * in order from least recently used to most recently used.
868
- */
869
515
  *rvalues() {
870
- for (const i of this.#rindexes()) {
871
- const v = this.#valList[i];
872
- if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
873
- yield this.#valList[i];
874
- }
875
- }
516
+ for (let e of this.#z()) this.#t[e] !== void 0 && !this.#e(this.#t[e]) && (yield this.#t[e]);
876
517
  }
877
- /**
878
- * Iterating over the cache itself yields the same results as
879
- * {@link LRUCache.entries}
880
- */
881
518
  [Symbol.iterator]() {
882
519
  return this.entries();
883
520
  }
884
- /**
885
- * A String value that is used in the creation of the default string
886
- * description of an object. Called by the built-in method
887
- * `Object.prototype.toString`.
888
- */
889
521
  [Symbol.toStringTag] = "LRUCache";
890
- /**
891
- * Find a value for which the supplied fn method returns a truthy value,
892
- * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
893
- */
894
- find(fn, getOptions = {}) {
895
- for (const i of this.#indexes()) {
896
- const v = this.#valList[i];
897
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
898
- if (value === void 0)
899
- continue;
900
- if (fn(value, this.#keyList[i], this)) {
901
- return this.get(this.#keyList[i], getOptions);
902
- }
522
+ find(e, t = {}) {
523
+ for (let i of this.#A()) {
524
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
525
+ if (n !== void 0 && e(n, this.#i[i], this)) return this.#C(this.#i[i], t);
903
526
  }
904
527
  }
905
- /**
906
- * Call the supplied function on each item in the cache, in order from most
907
- * recently used to least recently used.
908
- *
909
- * `fn` is called as `fn(value, key, cache)`.
910
- *
911
- * If `thisp` is provided, function will be called in the `this`-context of
912
- * the provided object, or the cache if no `thisp` object is provided.
913
- *
914
- * Does not update age or recenty of use, or iterate over stale values.
915
- */
916
- forEach(fn, thisp = this) {
917
- for (const i of this.#indexes()) {
918
- const v = this.#valList[i];
919
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
920
- if (value === void 0)
921
- continue;
922
- fn.call(thisp, value, this.#keyList[i], this);
528
+ forEach(e, t = this) {
529
+ for (let i of this.#A()) {
530
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
531
+ n !== void 0 && e.call(t, n, this.#i[i], this);
923
532
  }
924
533
  }
925
- /**
926
- * The same as {@link LRUCache.forEach} but items are iterated over in
927
- * reverse order. (ie, less recently used items are iterated over first.)
928
- */
929
- rforEach(fn, thisp = this) {
930
- for (const i of this.#rindexes()) {
931
- const v = this.#valList[i];
932
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
933
- if (value === void 0)
934
- continue;
935
- fn.call(thisp, value, this.#keyList[i], this);
534
+ rforEach(e, t = this) {
535
+ for (let i of this.#z()) {
536
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
537
+ n !== void 0 && e.call(t, n, this.#i[i], this);
936
538
  }
937
539
  }
938
- /**
939
- * Delete any stale entries. Returns true if anything was removed,
940
- * false otherwise.
941
- */
942
540
  purgeStale() {
943
- let deleted = false;
944
- for (const i of this.#rindexes({ allowStale: true })) {
945
- if (this.#isStale(i)) {
946
- this.#delete(this.#keyList[i], "expire");
947
- deleted = true;
948
- }
949
- }
950
- return deleted;
541
+ let e = false;
542
+ for (let t of this.#z({ allowStale: true })) this.#p(t) && (this.#v(this.#i[t], "expire"), e = true);
543
+ return e;
951
544
  }
952
- /**
953
- * Get the extended info about a given entry, to get its value, size, and
954
- * TTL info simultaneously. Returns `undefined` if the key is not present.
955
- *
956
- * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
957
- * serialization, the `start` value is always the current timestamp, and the
958
- * `ttl` is a calculated remaining time to live (negative if expired).
959
- *
960
- * Always returns stale values, if their info is found in the cache, so be
961
- * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
962
- * if relevant.
963
- */
964
- info(key) {
965
- const i = this.#keyMap.get(key);
966
- if (i === void 0)
967
- return void 0;
968
- const v = this.#valList[i];
969
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
970
- if (value === void 0)
971
- return void 0;
972
- const entry = { value };
973
- if (this.#ttls && this.#starts) {
974
- const ttl = this.#ttls[i];
975
- const start = this.#starts[i];
976
- if (ttl && start) {
977
- const remain = ttl - (this.#perf.now() - start);
978
- entry.ttl = remain;
979
- entry.start = Date.now();
545
+ info(e) {
546
+ let t = this.#s.get(e);
547
+ if (t === void 0) return;
548
+ let i = this.#t[t], s = this.#e(i) ? i.__staleWhileFetching : i;
549
+ if (s === void 0) return;
550
+ let n = { value: s };
551
+ if (this.#d && this.#F) {
552
+ let o = this.#d[t], r = this.#F[t];
553
+ if (o && r) {
554
+ let h = o - (this.#m.now() - r);
555
+ n.ttl = h, n.start = Date.now();
980
556
  }
981
557
  }
982
- if (this.#sizes) {
983
- entry.size = this.#sizes[i];
984
- }
985
- return entry;
558
+ return this.#_ && (n.size = this.#_[t]), n;
986
559
  }
987
- /**
988
- * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
989
- * passed to {@link LRUCache#load}.
990
- *
991
- * The `start` fields are calculated relative to a portable `Date.now()`
992
- * timestamp, even if `performance.now()` is available.
993
- *
994
- * Stale entries are always included in the `dump`, even if
995
- * {@link LRUCache.OptionsBase.allowStale} is false.
996
- *
997
- * Note: this returns an actual array, not a generator, so it can be more
998
- * easily passed around.
999
- */
1000
560
  dump() {
1001
- const arr = [];
1002
- for (const i of this.#indexes({ allowStale: true })) {
1003
- const key = this.#keyList[i];
1004
- const v = this.#valList[i];
1005
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
1006
- if (value === void 0 || key === void 0)
1007
- continue;
1008
- const entry = { value };
1009
- if (this.#ttls && this.#starts) {
1010
- entry.ttl = this.#ttls[i];
1011
- const age = this.#perf.now() - this.#starts[i];
1012
- entry.start = Math.floor(Date.now() - age);
561
+ let e = [];
562
+ for (let t of this.#A({ allowStale: true })) {
563
+ let i = this.#i[t], s = this.#t[t], n = this.#e(s) ? s.__staleWhileFetching : s;
564
+ if (n === void 0 || i === void 0) continue;
565
+ let o = { value: n };
566
+ if (this.#d && this.#F) {
567
+ o.ttl = this.#d[t];
568
+ let r = this.#m.now() - this.#F[t];
569
+ o.start = Math.floor(Date.now() - r);
1013
570
  }
1014
- if (this.#sizes) {
1015
- entry.size = this.#sizes[i];
1016
- }
1017
- arr.unshift([key, entry]);
571
+ this.#_ && (o.size = this.#_[t]), e.unshift([i, o]);
1018
572
  }
1019
- return arr;
573
+ return e;
1020
574
  }
1021
- /**
1022
- * Reset the cache and load in the items in entries in the order listed.
1023
- *
1024
- * The shape of the resulting cache may be different if the same options are
1025
- * not used in both caches.
1026
- *
1027
- * The `start` fields are assumed to be calculated relative to a portable
1028
- * `Date.now()` timestamp, even if `performance.now()` is available.
1029
- */
1030
- load(arr) {
575
+ load(e) {
1031
576
  this.clear();
1032
- for (const [key, entry] of arr) {
1033
- if (entry.start) {
1034
- const age = Date.now() - entry.start;
1035
- entry.start = this.#perf.now() - age;
1036
- }
1037
- this.set(key, entry.value, entry);
1038
- }
1039
- }
1040
- /**
1041
- * Add a value to the cache.
1042
- *
1043
- * Note: if `undefined` is specified as a value, this is an alias for
1044
- * {@link LRUCache#delete}
1045
- *
1046
- * Fields on the {@link LRUCache.SetOptions} options param will override
1047
- * their corresponding values in the constructor options for the scope
1048
- * of this single `set()` operation.
1049
- *
1050
- * If `start` is provided, then that will set the effective start
1051
- * time for the TTL calculation. Note that this must be a previous
1052
- * value of `performance.now()` if supported, or a previous value of
1053
- * `Date.now()` if not.
1054
- *
1055
- * Options object may also include `size`, which will prevent
1056
- * calling the `sizeCalculation` function and just use the specified
1057
- * number if it is a positive integer, and `noDisposeOnSet` which
1058
- * will prevent calling a `dispose` function in the case of
1059
- * overwrites.
1060
- *
1061
- * If the `size` (or return value of `sizeCalculation`) for a given
1062
- * entry is greater than `maxEntrySize`, then the item will not be
1063
- * added to the cache.
1064
- *
1065
- * Will update the recency of the entry.
1066
- *
1067
- * If the value is `undefined`, then this is an alias for
1068
- * `cache.delete(key)`. `undefined` is never stored in the cache.
1069
- */
1070
- set(k, v, setOptions = {}) {
1071
- if (v === void 0) {
1072
- this.delete(k);
1073
- return this;
1074
- }
1075
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
1076
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
1077
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
1078
- if (this.maxEntrySize && size > this.maxEntrySize) {
1079
- if (status) {
1080
- status.set = "miss";
1081
- status.maxEntrySizeExceeded = true;
1082
- }
1083
- this.#delete(k, "set");
1084
- return this;
1085
- }
1086
- let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
1087
- if (index === void 0) {
1088
- index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
1089
- this.#keyList[index] = k;
1090
- this.#valList[index] = v;
1091
- this.#keyMap.set(k, index);
1092
- this.#next[this.#tail] = index;
1093
- this.#prev[index] = this.#tail;
1094
- this.#tail = index;
1095
- this.#size++;
1096
- this.#addItemSize(index, size, status);
1097
- if (status)
1098
- status.set = "add";
1099
- noUpdateTTL = false;
1100
- if (this.#hasOnInsert) {
1101
- this.#onInsert?.(v, k, "add");
1102
- }
1103
- } else {
1104
- this.#moveToTail(index);
1105
- const oldVal = this.#valList[index];
1106
- if (v !== oldVal) {
1107
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
1108
- oldVal.__abortController.abort(new Error("replaced"));
1109
- const { __staleWhileFetching: s } = oldVal;
1110
- if (s !== void 0 && !noDisposeOnSet) {
1111
- if (this.#hasDispose) {
1112
- this.#dispose?.(s, k, "set");
1113
- }
1114
- if (this.#hasDisposeAfter) {
1115
- this.#disposed?.push([s, k, "set"]);
1116
- }
1117
- }
1118
- } else if (!noDisposeOnSet) {
1119
- if (this.#hasDispose) {
1120
- this.#dispose?.(oldVal, k, "set");
1121
- }
1122
- if (this.#hasDisposeAfter) {
1123
- this.#disposed?.push([oldVal, k, "set"]);
1124
- }
1125
- }
1126
- this.#removeItemSize(index);
1127
- this.#addItemSize(index, size, status);
1128
- this.#valList[index] = v;
1129
- if (status) {
1130
- status.set = "replace";
1131
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
1132
- if (oldValue !== void 0)
1133
- status.oldValue = oldValue;
577
+ for (let [t, i] of e) {
578
+ if (i.start) {
579
+ let s = Date.now() - i.start;
580
+ i.start = this.#m.now() - s;
581
+ }
582
+ this.#O(t, i.value, i);
583
+ }
584
+ }
585
+ set(e, t, i = {}) {
586
+ let { status: s = S.hasSubscribers ? {} : void 0 } = i;
587
+ i.status = s, s && (s.op = "set", s.key = e, t !== void 0 && (s.value = t));
588
+ let n = this.#O(e, t, i);
589
+ return s && S.hasSubscribers && S.publish(s), n;
590
+ }
591
+ #O(e, t, i = {}) {
592
+ let { ttl: s = this.ttl, start: n, noDisposeOnSet: o = this.noDisposeOnSet, sizeCalculation: r = this.sizeCalculation, status: h } = i;
593
+ if (t === void 0) return h && (h.set = "deleted"), this.delete(e), this;
594
+ let { noUpdateTTL: l = this.noUpdateTTL } = i;
595
+ h && !this.#e(t) && (h.value = t);
596
+ let c = this.#k(e, t, i.size || 0, r, h);
597
+ if (this.maxEntrySize && c > this.maxEntrySize) return this.#v(e, "set"), h && (h.set = "miss", h.maxEntrySizeExceeded = true), this;
598
+ let f = this.#n === 0 ? void 0 : this.#s.get(e);
599
+ if (f === void 0) f = this.#n === 0 ? this.#h : this.#y.length !== 0 ? this.#y.pop() : this.#n === this.#o ? this.#G(false) : this.#n, this.#i[f] = e, this.#t[f] = t, this.#s.set(e, 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 = false, this.#j && this.#x?.(t, e, "add");
600
+ else {
601
+ this.#L(f);
602
+ let g = this.#t[f];
603
+ if (t !== g) {
604
+ if (this.#W && this.#e(g)) {
605
+ g.__abortController.abort(new Error("replaced"));
606
+ let { __staleWhileFetching: p } = g;
607
+ p !== void 0 && !o && (this.#T && this.#w?.(p, e, "set"), this.#f && this.#r?.push([p, e, "set"]));
608
+ } else o || (this.#T && this.#w?.(g, e, "set"), this.#f && this.#r?.push([g, e, "set"]));
609
+ if (this.#R(f), this.#I(f, c, h), this.#t[f] = t, h) {
610
+ h.set = "replace";
611
+ let p = g && this.#e(g) ? g.__staleWhileFetching : g;
612
+ p !== void 0 && (h.oldValue = p);
1134
613
  }
1135
- } else if (status) {
1136
- status.set = "update";
1137
- }
1138
- if (this.#hasOnInsert) {
1139
- this.onInsert?.(v, k, v === oldVal ? "update" : "replace");
1140
- }
1141
- }
1142
- if (ttl !== 0 && !this.#ttls) {
1143
- this.#initializeTTLTracking();
614
+ } else h && (h.set = "update");
615
+ this.#j && this.onInsert?.(t, e, t === g ? "update" : "replace");
1144
616
  }
1145
- if (this.#ttls) {
1146
- if (!noUpdateTTL) {
1147
- this.#setItemTTL(index, ttl, start);
1148
- }
1149
- if (status)
1150
- this.#statusTTL(status, index);
1151
- }
1152
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
1153
- const dt = this.#disposed;
1154
- let task;
1155
- while (task = dt?.shift()) {
1156
- this.#disposeAfter?.(...task);
1157
- }
617
+ if (s !== 0 && !this.#d && this.#H(), this.#d && (l || this.#N(f, s, n), h && this.#E(h, f)), !o && this.#f && this.#r) {
618
+ let g = this.#r, p;
619
+ for (; p = g?.shift(); ) this.#S?.(...p);
1158
620
  }
1159
621
  return this;
1160
622
  }
1161
- /**
1162
- * Evict the least recently used item, returning its value or
1163
- * `undefined` if cache is empty.
1164
- */
1165
623
  pop() {
1166
624
  try {
1167
- while (this.#size) {
1168
- const val = this.#valList[this.#head];
1169
- this.#evict(true);
1170
- if (this.#isBackgroundFetch(val)) {
1171
- if (val.__staleWhileFetching) {
1172
- return val.__staleWhileFetching;
1173
- }
1174
- } else if (val !== void 0) {
1175
- return val;
1176
- }
625
+ for (; this.#n; ) {
626
+ let e = this.#t[this.#l];
627
+ if (this.#G(true), this.#e(e)) {
628
+ if (e.__staleWhileFetching) return e.__staleWhileFetching;
629
+ } else if (e !== void 0) return e;
1177
630
  }
1178
631
  } finally {
1179
- if (this.#hasDisposeAfter && this.#disposed) {
1180
- const dt = this.#disposed;
1181
- let task;
1182
- while (task = dt?.shift()) {
1183
- this.#disposeAfter?.(...task);
1184
- }
1185
- }
1186
- }
1187
- }
1188
- #evict(free) {
1189
- const head = this.#head;
1190
- const k = this.#keyList[head];
1191
- const v = this.#valList[head];
1192
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
1193
- v.__abortController.abort(new Error("evicted"));
1194
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
1195
- if (this.#hasDispose) {
1196
- this.#dispose?.(v, k, "evict");
1197
- }
1198
- if (this.#hasDisposeAfter) {
1199
- this.#disposed?.push([v, k, "evict"]);
1200
- }
1201
- }
1202
- this.#removeItemSize(head);
1203
- if (this.#autopurgeTimers?.[head]) {
1204
- clearTimeout(this.#autopurgeTimers[head]);
1205
- this.#autopurgeTimers[head] = void 0;
1206
- }
1207
- if (free) {
1208
- this.#keyList[head] = void 0;
1209
- this.#valList[head] = void 0;
1210
- this.#free.push(head);
1211
- }
1212
- if (this.#size === 1) {
1213
- this.#head = this.#tail = 0;
1214
- this.#free.length = 0;
1215
- } else {
1216
- this.#head = this.#next[head];
1217
- }
1218
- this.#keyMap.delete(k);
1219
- this.#size--;
1220
- return head;
1221
- }
1222
- /**
1223
- * Check if a key is in the cache, without updating the recency of use.
1224
- * Will return false if the item is stale, even though it is technically
1225
- * in the cache.
1226
- *
1227
- * Check if a key is in the cache, without updating the recency of
1228
- * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
1229
- * to `true` in either the options or the constructor.
1230
- *
1231
- * Will return `false` if the item is stale, even though it is technically in
1232
- * the cache. The difference can be determined (if it matters) by using a
1233
- * `status` argument, and inspecting the `has` field.
1234
- *
1235
- * Will not update item age unless
1236
- * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
1237
- */
1238
- has(k, hasOptions = {}) {
1239
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
1240
- const index = this.#keyMap.get(k);
1241
- if (index !== void 0) {
1242
- const v = this.#valList[index];
1243
- if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
1244
- return false;
1245
- }
1246
- if (!this.#isStale(index)) {
1247
- if (updateAgeOnHas) {
1248
- this.#updateItemAge(index);
1249
- }
1250
- if (status) {
1251
- status.has = "hit";
1252
- this.#statusTTL(status, index);
1253
- }
1254
- return true;
1255
- } else if (status) {
1256
- status.has = "stale";
1257
- this.#statusTTL(status, index);
1258
- }
1259
- } else if (status) {
1260
- status.has = "miss";
1261
- }
632
+ if (this.#f && this.#r) {
633
+ let e = this.#r, t;
634
+ for (; t = e?.shift(); ) this.#S?.(...t);
635
+ }
636
+ }
637
+ }
638
+ #G(e) {
639
+ let t = this.#l, i = this.#i[t], s = this.#t[t];
640
+ 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([s, i, "evict"])), this.#R(t), this.#g?.[t] && (clearTimeout(this.#g[t]), this.#g[t] = void 0), e && (this.#i[t] = void 0, this.#t[t] = void 0, this.#y.push(t)), this.#n === 1 ? (this.#l = this.#h = 0, this.#y.length = 0) : this.#l = this.#a[t], this.#s.delete(i), this.#n--, t;
641
+ }
642
+ has(e, t = {}) {
643
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t;
644
+ t.status = i, i && (i.op = "has", i.key = e);
645
+ let s = this.#Y(e, t);
646
+ return S.hasSubscribers && S.publish(i), s;
647
+ }
648
+ #Y(e, t = {}) {
649
+ let { updateAgeOnHas: i = this.updateAgeOnHas, status: s } = t, n = this.#s.get(e);
650
+ if (n !== void 0) {
651
+ let o = this.#t[n];
652
+ if (this.#e(o) && o.__staleWhileFetching === void 0) return false;
653
+ if (this.#p(n)) s && (s.has = "stale", this.#E(s, n));
654
+ else return i && this.#D(n), s && (s.has = "hit", this.#E(s, n)), true;
655
+ } else s && (s.has = "miss");
1262
656
  return false;
1263
657
  }
1264
- /**
1265
- * Like {@link LRUCache#get} but doesn't update recency or delete stale
1266
- * items.
1267
- *
1268
- * Returns `undefined` if the item is stale, unless
1269
- * {@link LRUCache.OptionsBase.allowStale} is set.
1270
- */
1271
- peek(k, peekOptions = {}) {
1272
- const { allowStale = this.allowStale } = peekOptions;
1273
- const index = this.#keyMap.get(k);
1274
- if (index === void 0 || !allowStale && this.#isStale(index)) {
1275
- return;
1276
- }
1277
- const v = this.#valList[index];
1278
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
658
+ peek(e, t = {}) {
659
+ let { status: i = D() ? {} : void 0 } = t;
660
+ i && (i.op = "peek", i.key = e), t.status = i;
661
+ let s = this.#J(e, t);
662
+ return S.hasSubscribers && S.publish(i), s;
1279
663
  }
1280
- #backgroundFetch(k, index, options, context2) {
1281
- const v = index === void 0 ? void 0 : this.#valList[index];
1282
- if (this.#isBackgroundFetch(v)) {
1283
- return v;
664
+ #J(e, t) {
665
+ let { status: i, allowStale: s = this.allowStale } = t, n = this.#s.get(e);
666
+ if (n === void 0 || !s && this.#p(n)) {
667
+ i && (i.peek = n === void 0 ? "miss" : "stale");
668
+ return;
1284
669
  }
1285
- const ac = new AC();
1286
- const { signal } = options;
1287
- signal?.addEventListener("abort", () => ac.abort(signal.reason), {
1288
- signal: ac.signal
1289
- });
1290
- const fetchOpts = {
1291
- signal: ac.signal,
1292
- options,
1293
- context: context2
1294
- };
1295
- const cb = (v2, updateCache = false) => {
1296
- const { aborted } = ac.signal;
1297
- const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
1298
- const proceed = options.ignoreFetchAbort || !!(options.allowStaleOnFetchAbort && v2 !== void 0);
1299
- if (options.status) {
1300
- if (aborted && !updateCache) {
1301
- options.status.fetchAborted = true;
1302
- options.status.fetchError = ac.signal.reason;
1303
- if (ignoreAbort)
1304
- options.status.fetchAbortIgnored = true;
1305
- } else {
1306
- options.status.fetchResolved = true;
1307
- }
1308
- }
1309
- if (aborted && !ignoreAbort && !updateCache) {
1310
- return fetchFail(ac.signal.reason, proceed);
1311
- }
1312
- const bf2 = p;
1313
- const vl = this.#valList[index];
1314
- if (vl === p || ignoreAbort && updateCache && vl === void 0) {
1315
- if (v2 === void 0) {
1316
- if (bf2.__staleWhileFetching !== void 0) {
1317
- this.#valList[index] = bf2.__staleWhileFetching;
1318
- } else {
1319
- this.#delete(k, "fetch");
1320
- }
1321
- } else {
1322
- if (options.status)
1323
- options.status.fetchUpdated = true;
1324
- this.set(k, v2, fetchOpts.options);
1325
- }
1326
- }
1327
- return v2;
1328
- };
1329
- const eb = (er) => {
1330
- if (options.status) {
1331
- options.status.fetchRejected = true;
1332
- options.status.fetchError = er;
1333
- }
1334
- return fetchFail(er, false);
1335
- };
1336
- const fetchFail = (er, proceed) => {
1337
- const { aborted } = ac.signal;
1338
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
1339
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
1340
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
1341
- const bf2 = p;
1342
- if (this.#valList[index] === p) {
1343
- const del = !noDelete || !proceed && bf2.__staleWhileFetching === void 0;
1344
- if (del) {
1345
- this.#delete(k, "fetch");
1346
- } else if (!allowStaleAborted) {
1347
- this.#valList[index] = bf2.__staleWhileFetching;
1348
- }
1349
- }
1350
- if (allowStale) {
1351
- if (options.status && bf2.__staleWhileFetching !== void 0) {
1352
- options.status.returnedStale = true;
1353
- }
1354
- return bf2.__staleWhileFetching;
1355
- } else if (bf2.__returned === bf2) {
1356
- throw er;
1357
- }
1358
- };
1359
- const pcall = (res, rej) => {
1360
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
1361
- if (fmp && fmp instanceof Promise) {
1362
- fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
1363
- }
1364
- ac.signal.addEventListener("abort", () => {
1365
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
1366
- res(void 0);
1367
- if (options.allowStaleOnFetchAbort) {
1368
- res = (v2) => cb(v2, true);
1369
- }
1370
- }
670
+ let o = this.#t[n], r = this.#e(o) ? o.__staleWhileFetching : o;
671
+ return i && (r !== void 0 ? (i.peek = "hit", i.value = r) : i.peek = "miss"), r;
672
+ }
673
+ #P(e, t, i, s) {
674
+ let n = t === void 0 ? void 0 : this.#t[t];
675
+ if (this.#e(n)) return n;
676
+ let o = new AbortController(), { signal: r } = i;
677
+ r?.addEventListener("abort", () => o.abort(r.reason), { signal: o.signal });
678
+ let h = { signal: o.signal, options: i, context: s }, l = (w, y = false) => {
679
+ let { aborted: a } = o.signal, m = i.ignoreFetchAbort && w !== void 0, _ = i.ignoreFetchAbort || !!(i.allowStaleOnFetchAbort && w !== void 0);
680
+ if (i.status && (a && !y ? (i.status.fetchAborted = true, i.status.fetchError = o.signal.reason, m && (i.status.fetchAbortIgnored = true)) : i.status.fetchResolved = true), a && !m && !y) return f(o.signal.reason, _);
681
+ let b = p, d = this.#t[t];
682
+ return (d === p || d === void 0 && m && y) && (w === void 0 ? b.__staleWhileFetching !== void 0 ? this.#t[t] = b.__staleWhileFetching : this.#v(e, "fetch") : (i.status && (i.status.fetchUpdated = true), this.#O(e, w, h.options))), w;
683
+ }, c = (w) => (i.status && (i.status.fetchRejected = true, i.status.fetchError = w), f(w, false)), f = (w, y) => {
684
+ let { aborted: a } = o.signal, m = a && i.allowStaleOnFetchAbort, _ = m || i.allowStaleOnFetchRejection, b = _ || i.noDeleteOnFetchRejection, d = p;
685
+ if (this.#t[t] === p && (!b || !y && d.__staleWhileFetching === void 0 ? this.#v(e, "fetch") : m || (this.#t[t] = d.__staleWhileFetching)), _) return i.status && d.__staleWhileFetching !== void 0 && (i.status.returnedStale = true), d.__staleWhileFetching;
686
+ if (d.__returned === d) throw w;
687
+ }, g = (w, y) => {
688
+ let a = this.#M?.(e, n, h);
689
+ a && a instanceof Promise && a.then((m) => w(m === void 0 ? void 0 : m), y), o.signal.addEventListener("abort", () => {
690
+ (!i.ignoreFetchAbort || i.allowStaleOnFetchAbort) && (w(void 0), i.allowStaleOnFetchAbort && (w = (m) => l(m, true)));
1371
691
  });
1372
692
  };
1373
- if (options.status)
1374
- options.status.fetchDispatched = true;
1375
- const p = new Promise(pcall).then(cb, eb);
1376
- const bf = Object.assign(p, {
1377
- __abortController: ac,
1378
- __staleWhileFetching: v,
1379
- __returned: void 0
1380
- });
1381
- if (index === void 0) {
1382
- this.set(k, bf, { ...fetchOpts.options, status: void 0 });
1383
- index = this.#keyMap.get(k);
693
+ i.status && (i.status.fetchDispatched = true);
694
+ let p = new Promise(g).then(l, c), T = Object.assign(p, { __abortController: o, __staleWhileFetching: n, __returned: void 0 });
695
+ return t === void 0 ? (this.#O(e, T, { ...h.options, status: void 0 }), t = this.#s.get(e)) : this.#t[t] = T, T;
696
+ }
697
+ #e(e) {
698
+ if (!this.#W) return false;
699
+ let t = e;
700
+ return !!t && t instanceof Promise && t.hasOwnProperty("__staleWhileFetching") && t.__abortController instanceof AbortController;
701
+ }
702
+ fetch(e, t = {}) {
703
+ let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t;
704
+ t.status = s, s && t.context && (s.context = t.context);
705
+ let n = this.#B(e, t);
706
+ return s && i && (s.trace = true, W.tracePromise(() => n, s).catch(() => {
707
+ })), n;
708
+ }
709
+ async #B(e, t = {}) {
710
+ 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 = false, status: a, signal: m } = t;
711
+ if (a && (a.op = "fetch", a.key = e, y && (a.forceRefresh = true)), !this.#W) return a && (a.fetch = "get"), this.#C(e, { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, status: a });
712
+ let _ = { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, ttl: o, noDisposeOnSet: r, size: h, sizeCalculation: l, noUpdateTTL: c, noDeleteOnFetchRejection: f, allowStaleOnFetchRejection: g, allowStaleOnFetchAbort: T, ignoreFetchAbort: p, status: a, signal: m }, b = this.#s.get(e);
713
+ if (b === void 0) {
714
+ a && (a.fetch = "miss");
715
+ let d = this.#P(e, b, _, w);
716
+ return d.__returned = d;
1384
717
  } else {
1385
- this.#valList[index] = bf;
1386
- }
1387
- return bf;
1388
- }
1389
- #isBackgroundFetch(p) {
1390
- if (!this.#hasFetchMethod)
1391
- return false;
1392
- const b = p;
1393
- return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
1394
- }
1395
- async fetch(k, fetchOptions = {}) {
1396
- const {
1397
- // get options
1398
- allowStale = this.allowStale,
1399
- updateAgeOnGet = this.updateAgeOnGet,
1400
- noDeleteOnStaleGet = this.noDeleteOnStaleGet,
1401
- // set options
1402
- ttl = this.ttl,
1403
- noDisposeOnSet = this.noDisposeOnSet,
1404
- size = 0,
1405
- sizeCalculation = this.sizeCalculation,
1406
- noUpdateTTL = this.noUpdateTTL,
1407
- // fetch exclusive options
1408
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
1409
- allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
1410
- ignoreFetchAbort = this.ignoreFetchAbort,
1411
- allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
1412
- context: context2,
1413
- forceRefresh = false,
1414
- status,
1415
- signal
1416
- } = fetchOptions;
1417
- if (!this.#hasFetchMethod) {
1418
- if (status)
1419
- status.fetch = "get";
1420
- return this.get(k, {
1421
- allowStale,
1422
- updateAgeOnGet,
1423
- noDeleteOnStaleGet,
1424
- status
1425
- });
718
+ let d = this.#t[b];
719
+ if (this.#e(d)) {
720
+ let E = i && d.__staleWhileFetching !== void 0;
721
+ return a && (a.fetch = "inflight", E && (a.returnedStale = true)), E ? d.__staleWhileFetching : d.__returned = d;
722
+ }
723
+ let A = this.#p(b);
724
+ if (!y && !A) return a && (a.fetch = "hit"), this.#L(b), s && this.#D(b), a && this.#E(a, b), d;
725
+ let z = this.#P(e, b, _, w), v = z.__staleWhileFetching !== void 0 && i;
726
+ return a && (a.fetch = A ? "stale" : "refresh", v && A && (a.returnedStale = true)), v ? z.__staleWhileFetching : z.__returned = z;
727
+ }
728
+ }
729
+ forceFetch(e, t = {}) {
730
+ let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t;
731
+ t.status = s, s && t.context && (s.context = t.context);
732
+ let n = this.#K(e, t);
733
+ return s && i && (s.trace = true, W.tracePromise(() => n, s).catch(() => {
734
+ })), n;
735
+ }
736
+ async #K(e, t = {}) {
737
+ let i = await this.#B(e, t);
738
+ if (i === void 0) throw new Error("fetch() returned undefined");
739
+ return i;
740
+ }
741
+ memo(e, t = {}) {
742
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t;
743
+ t.status = i, i && (i.op = "memo", i.key = e, t.context && (i.context = t.context));
744
+ let s = this.#Q(e, t);
745
+ return i && (i.value = s), S.hasSubscribers && S.publish(i), s;
746
+ }
747
+ #Q(e, t = {}) {
748
+ let i = this.#U;
749
+ if (!i) throw new Error("no memoMethod provided to constructor");
750
+ let { context: s, status: n, forceRefresh: o, ...r } = t;
751
+ n && o && (n.forceRefresh = true);
752
+ let h = this.#C(e, r), l = o || h === void 0;
753
+ if (n && (n.memo = l ? "miss" : "hit", l || (n.value = h)), !l) return h;
754
+ let c = i(e, h, { options: r, context: s });
755
+ return n && (n.value = c), this.#O(e, c, r), c;
756
+ }
757
+ get(e, t = {}) {
758
+ let { status: i = S.hasSubscribers ? {} : void 0 } = t;
759
+ t.status = i, i && (i.op = "get", i.key = e);
760
+ let s = this.#C(e, t);
761
+ return i && (s !== void 0 && (i.value = s), S.hasSubscribers && S.publish(i)), s;
762
+ }
763
+ #C(e, t = {}) {
764
+ let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, status: o } = t, r = this.#s.get(e);
765
+ if (r === void 0) {
766
+ o && (o.get = "miss");
767
+ return;
1426
768
  }
1427
- const options = {
1428
- allowStale,
1429
- updateAgeOnGet,
1430
- noDeleteOnStaleGet,
1431
- ttl,
1432
- noDisposeOnSet,
1433
- size,
1434
- sizeCalculation,
1435
- noUpdateTTL,
1436
- noDeleteOnFetchRejection,
1437
- allowStaleOnFetchRejection,
1438
- allowStaleOnFetchAbort,
1439
- ignoreFetchAbort,
1440
- status,
1441
- signal
1442
- };
1443
- let index = this.#keyMap.get(k);
1444
- if (index === void 0) {
1445
- if (status)
1446
- status.fetch = "miss";
1447
- const p = this.#backgroundFetch(k, index, options, context2);
1448
- return p.__returned = p;
1449
- } else {
1450
- const v = this.#valList[index];
1451
- if (this.#isBackgroundFetch(v)) {
1452
- const stale = allowStale && v.__staleWhileFetching !== void 0;
1453
- if (status) {
1454
- status.fetch = "inflight";
1455
- if (stale)
1456
- status.returnedStale = true;
1457
- }
1458
- return stale ? v.__staleWhileFetching : v.__returned = v;
1459
- }
1460
- const isStale = this.#isStale(index);
1461
- if (!forceRefresh && !isStale) {
1462
- if (status)
1463
- status.fetch = "hit";
1464
- this.#moveToTail(index);
1465
- if (updateAgeOnGet) {
1466
- this.#updateItemAge(index);
1467
- }
1468
- if (status)
1469
- this.#statusTTL(status, index);
1470
- return v;
1471
- }
1472
- const p = this.#backgroundFetch(k, index, options, context2);
1473
- const hasStale = p.__staleWhileFetching !== void 0;
1474
- const staleVal = hasStale && allowStale;
1475
- if (status) {
1476
- status.fetch = isStale ? "stale" : "refresh";
1477
- if (staleVal && isStale)
1478
- status.returnedStale = true;
1479
- }
1480
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
1481
- }
1482
- }
1483
- async forceFetch(k, fetchOptions = {}) {
1484
- const v = await this.fetch(k, fetchOptions);
1485
- if (v === void 0)
1486
- throw new Error("fetch() returned undefined");
1487
- return v;
1488
- }
1489
- memo(k, memoOptions = {}) {
1490
- const memoMethod = this.#memoMethod;
1491
- if (!memoMethod) {
1492
- throw new Error("no memoMethod provided to constructor");
1493
- }
1494
- const { context: context2, forceRefresh, ...options } = memoOptions;
1495
- const v = this.get(k, options);
1496
- if (!forceRefresh && v !== void 0)
1497
- return v;
1498
- const vv = memoMethod(k, v, {
1499
- options,
1500
- context: context2
1501
- });
1502
- this.set(k, vv, options);
1503
- return vv;
769
+ let h = this.#t[r], l = this.#e(h);
770
+ return o && this.#E(o, r), this.#p(r) ? l ? (o && (o.get = "stale-fetching"), i && h.__staleWhileFetching !== void 0 ? (o && (o.returnedStale = true), h.__staleWhileFetching) : void 0) : (n || this.#v(e, "expire"), o && (o.get = "stale"), i ? (o && (o.returnedStale = true), h) : void 0) : (o && (o.get = l ? "fetching" : "hit"), this.#L(r), s && this.#D(r), l ? h.__staleWhileFetching : h);
1504
771
  }
1505
- /**
1506
- * Return a value from the cache. Will update the recency of the cache
1507
- * entry found.
1508
- *
1509
- * If the key is not found, get() will return `undefined`.
1510
- */
1511
- get(k, getOptions = {}) {
1512
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
1513
- const index = this.#keyMap.get(k);
1514
- if (index !== void 0) {
1515
- const value = this.#valList[index];
1516
- const fetching = this.#isBackgroundFetch(value);
1517
- if (status)
1518
- this.#statusTTL(status, index);
1519
- if (this.#isStale(index)) {
1520
- if (status)
1521
- status.get = "stale";
1522
- if (!fetching) {
1523
- if (!noDeleteOnStaleGet) {
1524
- this.#delete(k, "expire");
1525
- }
1526
- if (status && allowStale)
1527
- status.returnedStale = true;
1528
- return allowStale ? value : void 0;
1529
- } else {
1530
- if (status && allowStale && value.__staleWhileFetching !== void 0) {
1531
- status.returnedStale = true;
1532
- }
1533
- return allowStale ? value.__staleWhileFetching : void 0;
1534
- }
1535
- } else {
1536
- if (status)
1537
- status.get = "hit";
1538
- if (fetching) {
1539
- return value.__staleWhileFetching;
1540
- }
1541
- this.#moveToTail(index);
1542
- if (updateAgeOnGet) {
1543
- this.#updateItemAge(index);
1544
- }
1545
- return value;
1546
- }
1547
- } else if (status) {
1548
- status.get = "miss";
1549
- }
772
+ #$(e, t) {
773
+ this.#c[t] = e, this.#a[e] = t;
1550
774
  }
1551
- #connect(p, n) {
1552
- this.#prev[n] = p;
1553
- this.#next[p] = n;
775
+ #L(e) {
776
+ e !== this.#h && (e === this.#l ? this.#l = this.#a[e] : this.#$(this.#c[e], this.#a[e]), this.#$(this.#h, e), this.#h = e);
1554
777
  }
1555
- #moveToTail(index) {
1556
- if (index !== this.#tail) {
1557
- if (index === this.#head) {
1558
- this.#head = this.#next[index];
1559
- } else {
1560
- this.#connect(this.#prev[index], this.#next[index]);
1561
- }
1562
- this.#connect(this.#tail, index);
1563
- this.#tail = index;
1564
- }
778
+ delete(e) {
779
+ return this.#v(e, "delete");
1565
780
  }
1566
- /**
1567
- * Deletes a key out of the cache.
1568
- *
1569
- * Returns true if the key was deleted, false otherwise.
1570
- */
1571
- delete(k) {
1572
- return this.#delete(k, "delete");
1573
- }
1574
- #delete(k, reason) {
1575
- let deleted = false;
1576
- if (this.#size !== 0) {
1577
- const index = this.#keyMap.get(k);
1578
- if (index !== void 0) {
1579
- if (this.#autopurgeTimers?.[index]) {
1580
- clearTimeout(this.#autopurgeTimers?.[index]);
1581
- this.#autopurgeTimers[index] = void 0;
1582
- }
1583
- deleted = true;
1584
- if (this.#size === 1) {
1585
- this.#clear(reason);
1586
- } else {
1587
- this.#removeItemSize(index);
1588
- const v = this.#valList[index];
1589
- if (this.#isBackgroundFetch(v)) {
1590
- v.__abortController.abort(new Error("deleted"));
1591
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
1592
- if (this.#hasDispose) {
1593
- this.#dispose?.(v, k, reason);
1594
- }
1595
- if (this.#hasDisposeAfter) {
1596
- this.#disposed?.push([v, k, reason]);
1597
- }
1598
- }
1599
- this.#keyMap.delete(k);
1600
- this.#keyList[index] = void 0;
1601
- this.#valList[index] = void 0;
1602
- if (index === this.#tail) {
1603
- this.#tail = this.#prev[index];
1604
- } else if (index === this.#head) {
1605
- this.#head = this.#next[index];
1606
- } else {
1607
- const pi = this.#prev[index];
1608
- this.#next[pi] = this.#next[index];
1609
- const ni = this.#next[index];
1610
- this.#prev[ni] = this.#prev[index];
1611
- }
1612
- this.#size--;
1613
- this.#free.push(index);
781
+ #v(e, t) {
782
+ S.hasSubscribers && S.publish({ op: "delete", delete: t, key: e });
783
+ let i = false;
784
+ if (this.#n !== 0) {
785
+ let s = this.#s.get(e);
786
+ if (s !== void 0) if (this.#g?.[s] && (clearTimeout(this.#g?.[s]), this.#g[s] = void 0), i = true, this.#n === 1) this.#q(t);
787
+ else {
788
+ this.#R(s);
789
+ let n = this.#t[s];
790
+ if (this.#e(n) ? n.__abortController.abort(new Error("deleted")) : (this.#T || this.#f) && (this.#T && this.#w?.(n, e, t), this.#f && this.#r?.push([n, e, t])), this.#s.delete(e), this.#i[s] = void 0, this.#t[s] = void 0, s === this.#h) this.#h = this.#c[s];
791
+ else if (s === this.#l) this.#l = this.#a[s];
792
+ else {
793
+ let o = this.#c[s];
794
+ this.#a[o] = this.#a[s];
795
+ let r = this.#a[s];
796
+ this.#c[r] = this.#c[s];
1614
797
  }
798
+ this.#n--, this.#y.push(s);
1615
799
  }
1616
800
  }
1617
- if (this.#hasDisposeAfter && this.#disposed?.length) {
1618
- const dt = this.#disposed;
1619
- let task;
1620
- while (task = dt?.shift()) {
1621
- this.#disposeAfter?.(...task);
1622
- }
801
+ if (this.#f && this.#r?.length) {
802
+ let s = this.#r, n;
803
+ for (; n = s?.shift(); ) this.#S?.(...n);
1623
804
  }
1624
- return deleted;
805
+ return i;
1625
806
  }
1626
- /**
1627
- * Clear the cache entirely, throwing away all values.
1628
- */
1629
807
  clear() {
1630
- return this.#clear("delete");
808
+ return this.#q("delete");
1631
809
  }
1632
- #clear(reason) {
1633
- for (const index of this.#rindexes({ allowStale: true })) {
1634
- const v = this.#valList[index];
1635
- if (this.#isBackgroundFetch(v)) {
1636
- v.__abortController.abort(new Error("deleted"));
1637
- } else {
1638
- const k = this.#keyList[index];
1639
- if (this.#hasDispose) {
1640
- this.#dispose?.(v, k, reason);
1641
- }
1642
- if (this.#hasDisposeAfter) {
1643
- this.#disposed?.push([v, k, reason]);
1644
- }
810
+ #q(e) {
811
+ for (let t of this.#z({ allowStale: true })) {
812
+ let i = this.#t[t];
813
+ if (this.#e(i)) i.__abortController.abort(new Error("deleted"));
814
+ else {
815
+ let s = this.#i[t];
816
+ this.#T && this.#w?.(i, s, e), this.#f && this.#r?.push([i, s, e]);
1645
817
  }
1646
818
  }
1647
- this.#keyMap.clear();
1648
- this.#valList.fill(void 0);
1649
- this.#keyList.fill(void 0);
1650
- if (this.#ttls && this.#starts) {
1651
- this.#ttls.fill(0);
1652
- this.#starts.fill(0);
1653
- for (const t of this.#autopurgeTimers ?? []) {
1654
- if (t !== void 0)
1655
- clearTimeout(t);
1656
- }
1657
- this.#autopurgeTimers?.fill(void 0);
1658
- }
1659
- if (this.#sizes) {
1660
- this.#sizes.fill(0);
1661
- }
1662
- this.#head = 0;
1663
- this.#tail = 0;
1664
- this.#free.length = 0;
1665
- this.#calculatedSize = 0;
1666
- this.#size = 0;
1667
- if (this.#hasDisposeAfter && this.#disposed) {
1668
- const dt = this.#disposed;
1669
- let task;
1670
- while (task = dt?.shift()) {
1671
- this.#disposeAfter?.(...task);
1672
- }
819
+ if (this.#s.clear(), this.#t.fill(void 0), this.#i.fill(void 0), this.#d && this.#F) {
820
+ this.#d.fill(0), this.#F.fill(0);
821
+ for (let t of this.#g ?? []) t !== void 0 && clearTimeout(t);
822
+ this.#g?.fill(void 0);
823
+ }
824
+ 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) {
825
+ let t = this.#r, i;
826
+ for (; i = t?.shift(); ) this.#S?.(...i);
1673
827
  }
1674
828
  }
1675
829
  };
1676
830
  }
1677
831
  });
1678
832
  var proc, isStream, isReadable, isWritable, EOF, MAYBE_EMIT_END, EMITTED_END, EMITTING_END, EMITTED_ERROR, CLOSED, READ, FLUSH, FLUSHCHUNK, ENCODING, DECODER, FLOWING, PAUSED, RESUME, BUFFER, PIPES, BUFFERLENGTH, BUFFERPUSH, BUFFERSHIFT, OBJECTMODE, DESTROYED, ERROR, EMITDATA, EMITEND, EMITEND2, ASYNC, ABORT, ABORTED, SIGNAL, DATALISTENERS, DISCARDED, defer, nodefer, isEndish, isArrayBufferLike, isArrayBufferView, Pipe, PipeProxyErrors, isObjectModeOptions, isEncodingOptions, Minipass;
1679
- var init_esm2 = __esm({
833
+ var init_esm = __esm({
1680
834
  "../../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/dist/esm/index.js"() {
1681
835
  proc = typeof process === "object" && process ? process : {
1682
836
  stdout: null,
@@ -2403,10 +1557,10 @@ var init_esm2 = __esm({
2403
1557
  * Return a void Promise that resolves once the stream ends.
2404
1558
  */
2405
1559
  async promise() {
2406
- return new Promise((resolve20, reject) => {
1560
+ return new Promise((resolve21, reject) => {
2407
1561
  this.on(DESTROYED, () => reject(new Error("stream destroyed")));
2408
1562
  this.on("error", (er) => reject(er));
2409
- this.on("end", () => resolve20());
1563
+ this.on("end", () => resolve21());
2410
1564
  });
2411
1565
  }
2412
1566
  /**
@@ -2430,7 +1584,7 @@ var init_esm2 = __esm({
2430
1584
  return Promise.resolve({ done: false, value: res });
2431
1585
  if (this[EOF])
2432
1586
  return stop();
2433
- let resolve20;
1587
+ let resolve21;
2434
1588
  let reject;
2435
1589
  const onerr = (er) => {
2436
1590
  this.off("data", ondata);
@@ -2444,19 +1598,19 @@ var init_esm2 = __esm({
2444
1598
  this.off("end", onend);
2445
1599
  this.off(DESTROYED, ondestroy);
2446
1600
  this.pause();
2447
- resolve20({ value, done: !!this[EOF] });
1601
+ resolve21({ value, done: !!this[EOF] });
2448
1602
  };
2449
1603
  const onend = () => {
2450
1604
  this.off("error", onerr);
2451
1605
  this.off("data", ondata);
2452
1606
  this.off(DESTROYED, ondestroy);
2453
1607
  stop();
2454
- resolve20({ done: true, value: void 0 });
1608
+ resolve21({ done: true, value: void 0 });
2455
1609
  };
2456
1610
  const ondestroy = () => onerr(new Error("stream destroyed"));
2457
1611
  return new Promise((res2, rej) => {
2458
1612
  reject = rej;
2459
- resolve20 = res2;
1613
+ resolve21 = res2;
2460
1614
  this.once(DESTROYED, ondestroy);
2461
1615
  this.once("error", onerr);
2462
1616
  this.once("end", onend);
@@ -2554,10 +1708,10 @@ var init_esm2 = __esm({
2554
1708
  }
2555
1709
  });
2556
1710
  var realpathSync, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, PathScurry;
2557
- var init_esm3 = __esm({
1711
+ var init_esm2 = __esm({
2558
1712
  "../../node_modules/.pnpm/path-scurry@2.0.1/node_modules/path-scurry/dist/esm/index.js"() {
1713
+ init_index_min();
2559
1714
  init_esm();
2560
- init_esm2();
2561
1715
  realpathSync = realpathSync$1.native;
2562
1716
  defaultFS = {
2563
1717
  lstatSync,
@@ -2602,7 +1756,7 @@ var init_esm3 = __esm({
2602
1756
  ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
2603
1757
  TYPEMASK = 1023;
2604
1758
  entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
2605
- normalizeCache = new LRUCache({ max: 2 ** 12 });
1759
+ normalizeCache = new M({ max: 2 ** 12 });
2606
1760
  normalize = (s) => {
2607
1761
  const c = normalizeCache.get(s);
2608
1762
  if (c)
@@ -2611,7 +1765,7 @@ var init_esm3 = __esm({
2611
1765
  normalizeCache.set(s, n);
2612
1766
  return n;
2613
1767
  };
2614
- normalizeNocaseCache = new LRUCache({ max: 2 ** 12 });
1768
+ normalizeNocaseCache = new M({ max: 2 ** 12 });
2615
1769
  normalizeNocase = (s) => {
2616
1770
  const c = normalizeNocaseCache.get(s);
2617
1771
  if (c)
@@ -2620,12 +1774,12 @@ var init_esm3 = __esm({
2620
1774
  normalizeNocaseCache.set(s, n);
2621
1775
  return n;
2622
1776
  };
2623
- ResolveCache = class extends LRUCache {
1777
+ ResolveCache = class extends M {
2624
1778
  constructor() {
2625
1779
  super({ max: 256 });
2626
1780
  }
2627
1781
  };
2628
- ChildrenCache = class extends LRUCache {
1782
+ ChildrenCache = class extends M {
2629
1783
  constructor(maxSize = 16 * 1024) {
2630
1784
  super({
2631
1785
  maxSize,
@@ -3433,9 +2587,9 @@ var init_esm3 = __esm({
3433
2587
  if (this.#asyncReaddirInFlight) {
3434
2588
  await this.#asyncReaddirInFlight;
3435
2589
  } else {
3436
- let resolve20 = () => {
2590
+ let resolve21 = () => {
3437
2591
  };
3438
- this.#asyncReaddirInFlight = new Promise((res) => resolve20 = res);
2592
+ this.#asyncReaddirInFlight = new Promise((res) => resolve21 = res);
3439
2593
  try {
3440
2594
  for (const e of await this.#fs.promises.readdir(fullpath, {
3441
2595
  withFileTypes: true
@@ -3448,7 +2602,7 @@ var init_esm3 = __esm({
3448
2602
  children.provisional = 0;
3449
2603
  }
3450
2604
  this.#asyncReaddirInFlight = void 0;
3451
- resolve20();
2605
+ resolve21();
3452
2606
  }
3453
2607
  return children.slice(0, children.provisional);
3454
2608
  }
@@ -4774,7 +3928,7 @@ var init_processor = __esm({
4774
3928
  var makeIgnore, GlobUtil, GlobWalker, GlobStream;
4775
3929
  var init_walker = __esm({
4776
3930
  "../../node_modules/.pnpm/glob@11.1.0/node_modules/glob/dist/esm/walker.js"() {
4777
- init_esm2();
3931
+ init_esm();
4778
3932
  init_ignore();
4779
3933
  init_processor();
4780
3934
  makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
@@ -5107,7 +4261,7 @@ var init_walker = __esm({
5107
4261
  var defaultPlatform2, Glob;
5108
4262
  var init_glob = __esm({
5109
4263
  "../../node_modules/.pnpm/glob@11.1.0/node_modules/glob/dist/esm/glob.js"() {
5110
- init_esm3();
4264
+ init_esm2();
5111
4265
  init_pattern();
5112
4266
  init_walker();
5113
4267
  defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
@@ -5344,7 +4498,7 @@ function globIterate(pattern, options = {}) {
5344
4498
  return new Glob(pattern, options).iterate();
5345
4499
  }
5346
4500
  var streamSync, stream, iterateSync, iterate, sync, glob;
5347
- var init_esm4 = __esm({
4501
+ var init_esm3 = __esm({
5348
4502
  "../../node_modules/.pnpm/glob@11.1.0/node_modules/glob/dist/esm/index.js"() {
5349
4503
  init_glob();
5350
4504
  init_has_magic();
@@ -5382,21 +4536,21 @@ var init_esm4 = __esm({
5382
4536
  }
5383
4537
  });
5384
4538
  function findFreePort() {
5385
- return new Promise((resolve20, reject) => {
4539
+ return new Promise((resolve21, reject) => {
5386
4540
  const server = http.createServer();
5387
4541
  server.listen(0, "127.0.0.1", () => {
5388
4542
  const addr = server.address();
5389
4543
  const port = typeof addr === "object" && addr ? addr.port : null;
5390
4544
  server.close((err) => {
5391
4545
  if (err || port === null) reject(err ?? new Error("Could not determine port"));
5392
- else resolve20(port);
4546
+ else resolve21(port);
5393
4547
  });
5394
4548
  });
5395
4549
  server.on("error", reject);
5396
4550
  });
5397
4551
  }
5398
4552
  function fetchJson(url2) {
5399
- return new Promise((resolve20, reject) => {
4553
+ return new Promise((resolve21, reject) => {
5400
4554
  http.get(url2, (res) => {
5401
4555
  if (res.statusCode !== 200) {
5402
4556
  res.resume();
@@ -5409,7 +4563,7 @@ function fetchJson(url2) {
5409
4563
  });
5410
4564
  res.on("end", () => {
5411
4565
  try {
5412
- resolve20(JSON.parse(body));
4566
+ resolve21(JSON.parse(body));
5413
4567
  } catch {
5414
4568
  reject(new Error("Invalid JSON"));
5415
4569
  }
@@ -5808,47 +4962,6 @@ var init_scene_metadata = __esm({
5808
4962
  "src/renderer/scene-metadata.ts"() {
5809
4963
  }
5810
4964
  });
5811
- function normalizeUrl(url2) {
5812
- return url2.toLowerCase().replace(/\/+$/, "");
5813
- }
5814
- function hashReferenceUrl(url2) {
5815
- const normalized = normalizeUrl(url2);
5816
- return createHash("sha256").update(normalized).digest("hex").slice(0, 12);
5817
- }
5818
- var referenceFolderResolver;
5819
- var init_reference_folder = __esm({
5820
- "src/resolvers/reference-folder.ts"() {
5821
- referenceFolderResolver = {
5822
- name: "reference_folder",
5823
- resolve(_input, config, context2) {
5824
- const fromParam = config.from;
5825
- if (!fromParam) {
5826
- return {
5827
- resolved: false,
5828
- input: "",
5829
- error: 'Missing "from" field in resolver config'
5830
- };
5831
- }
5832
- const url2 = context2.params[fromParam];
5833
- if (typeof url2 !== "string" || url2 === "") {
5834
- return {
5835
- resolved: false,
5836
- input: "",
5837
- error: `Parameter "${fromParam}" is missing or empty`
5838
- };
5839
- }
5840
- const hash = hashReferenceUrl(url2);
5841
- const folder = resolve(context2.config.data, "references", hash);
5842
- mkdirSync(folder, { recursive: true });
5843
- return {
5844
- resolved: true,
5845
- value: folder,
5846
- input: url2
5847
- };
5848
- }
5849
- };
5850
- }
5851
- });
5852
4965
  function sanitize(str) {
5853
4966
  return str.toLowerCase().replace(/[ '–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/gi, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
5854
4967
  }
@@ -5894,14 +5007,12 @@ function resolveScene(dist, sceneRef) {
5894
5007
  var StoryMeta;
5895
5008
  var init_story_entity = __esm({
5896
5009
  "src/story-entity.ts"() {
5897
- init_esm4();
5010
+ init_esm3();
5898
5011
  init_scene_metadata();
5899
- init_reference_folder();
5900
5012
  StoryMeta = class _StoryMeta {
5901
5013
  storyId;
5902
5014
  section;
5903
5015
  storyDir;
5904
- reference;
5905
5016
  _meta;
5906
5017
  _metaPath;
5907
5018
  constructor(storyId, section, storyDir, meta, metaPath) {
@@ -5910,12 +5021,6 @@ var init_story_entity = __esm({
5910
5021
  this.storyDir = storyDir;
5911
5022
  this._meta = meta;
5912
5023
  this._metaPath = metaPath;
5913
- this.reference = {
5914
- url: meta.reference?.source?.url,
5915
- origin: meta.reference?.source?.origin,
5916
- screenId: meta.reference?.source?.screenId,
5917
- hasMarkup: meta.reference?.source?.hasMarkup
5918
- };
5919
5024
  }
5920
5025
  get data() {
5921
5026
  return this._meta;
@@ -5977,27 +5082,13 @@ var init_story_entity = __esm({
5977
5082
  mkdirSync(storyDir, { recursive: true });
5978
5083
  const metaPath = resolve(storyDir, "meta.yml");
5979
5084
  const section = _StoryMeta._deriveSection(storyId);
5980
- const tmpStory = new _StoryMeta(storyId, section, storyDir, {}, metaPath);
5981
- const breakpoints2 = tmpStory._getBreakpoints(config);
5982
- const regions = tmpStory._deriveRegions(config);
5983
5085
  const meta = {};
5984
- if (breakpoints2.length > 0) {
5985
- meta.reference = { breakpoints: {} };
5986
- for (const bp2 of breakpoints2) {
5987
- const regionMap = {};
5988
- for (const region of regions) {
5989
- regionMap[region.name] = { selector: region.selector };
5990
- }
5991
- meta.reference.breakpoints[bp2] = { threshold: 3, regions: regionMap };
5992
- }
5993
- }
5994
5086
  writeFileSync(metaPath, dump(meta, { lineWidth: -1 }), "utf-8");
5995
5087
  return new _StoryMeta(storyId, section, storyDir, meta, metaPath);
5996
5088
  }
5997
5089
  /**
5998
5090
  * Create or load a story by scene reference. Creates the story directory if
5999
- * missing, optionally seeds meta.yml with provided data, then fills in
6000
- * breakpoints/regions from design tokens.
5091
+ * missing, optionally seeds meta.yml with provided data.
6001
5092
  */
6002
5093
  static createByScene(config, sceneRef, metaSeed) {
6003
5094
  const { scenes, allScenes } = resolveScene(config.data, sceneRef);
@@ -6012,31 +5103,11 @@ var init_story_entity = __esm({
6012
5103
  const content = readFileSync(metaPath, "utf-8");
6013
5104
  meta = load(content) ?? {};
6014
5105
  }
6015
- if (metaSeed?.reference) {
6016
- if (!meta.reference) meta.reference = {};
6017
- if (metaSeed.reference.source) {
6018
- meta.reference.source = { ...meta.reference.source, ...metaSeed.reference.source };
6019
- }
6020
- if (metaSeed.reference.breakpoints) {
6021
- meta.reference.breakpoints = { ...meta.reference.breakpoints, ...metaSeed.reference.breakpoints };
6022
- }
5106
+ if (metaSeed?.reference !== void 0) {
5107
+ meta.reference = metaSeed.reference;
6023
5108
  }
6024
- if (!meta.reference?.breakpoints || Object.keys(meta.reference.breakpoints).length === 0) {
6025
- const section = _StoryMeta._deriveSection(storyId);
6026
- const tmpStory = new _StoryMeta(storyId, section, storyDir, meta, metaPath);
6027
- const breakpoints2 = tmpStory._getBreakpoints(config);
6028
- const regions = tmpStory._deriveRegions(config);
6029
- if (breakpoints2.length > 0) {
6030
- if (!meta.reference) meta.reference = {};
6031
- meta.reference.breakpoints = {};
6032
- for (const bp2 of breakpoints2) {
6033
- const regionMap = {};
6034
- for (const region of regions) {
6035
- regionMap[region.name] = { selector: region.selector };
6036
- }
6037
- meta.reference.breakpoints[bp2] = { threshold: 3, regions: regionMap };
6038
- }
6039
- }
5109
+ if (metaSeed?.elements !== void 0) {
5110
+ meta.elements = metaSeed.elements;
6040
5111
  }
6041
5112
  writeFileSync(metaPath, dump(meta, { lineWidth: -1 }), "utf-8");
6042
5113
  return _StoryMeta.load(config, storyId);
@@ -6045,26 +5116,19 @@ var init_story_entity = __esm({
6045
5116
  // Serialization
6046
5117
  // -------------------------------------------------------------------------
6047
5118
  toJSON() {
6048
- const breakpoints2 = {};
6049
- const bpData = this._meta.reference?.breakpoints ?? {};
6050
- for (const [bp2, cfg] of Object.entries(bpData)) {
6051
- const regions = {};
6052
- for (const [id, region] of Object.entries(cfg.regions ?? {})) {
6053
- regions[id] = {
6054
- selector: region.selector ?? "",
6055
- reference_selector: region.reference_selector ?? ""
6056
- };
6057
- }
6058
- breakpoints2[bp2] = { threshold: cfg.threshold ?? null, regions };
6059
- }
6060
- const referenceDir = this.reference.url ? `references/${hashReferenceUrl(this.reference.url)}` : null;
5119
+ const reference = this._meta.reference ?? null;
5120
+ const referenceDir = reference ? `references/${reference}` : null;
5121
+ const elements = (this._meta.elements ?? []).map((e) => ({
5122
+ id: e.id,
5123
+ selector: e.selector ?? ""
5124
+ }));
6061
5125
  return {
6062
5126
  storyId: this.storyId,
6063
5127
  section: this.section,
6064
5128
  storyDir: this.storyDir,
6065
- reference: this.reference,
5129
+ reference,
6066
5130
  referenceDir,
6067
- breakpoints: breakpoints2
5131
+ elements
6068
5132
  };
6069
5133
  }
6070
5134
  // -------------------------------------------------------------------------
@@ -6089,18 +5153,6 @@ var init_story_entity = __esm({
6089
5153
  const idx = storyId.indexOf("--");
6090
5154
  return idx > 0 ? storyId.substring(0, idx) : storyId;
6091
5155
  }
6092
- _getBreakpoints(config) {
6093
- const tokensPath = resolve(config.data, "design-system", "design-tokens.yml");
6094
- if (!existsSync(tokensPath)) return [];
6095
- const content = readFileSync(tokensPath, "utf-8");
6096
- const tokens = load(content);
6097
- const bpObj = tokens.breakpoints ?? tokens.semantic?.breakpoints;
6098
- if (!bpObj) return [];
6099
- return Object.keys(bpObj).filter((k) => !k.startsWith("$"));
6100
- }
6101
- _deriveRegions(_config) {
6102
- return [{ name: "full", selector: "" }];
6103
- }
6104
5156
  };
6105
5157
  }
6106
5158
  });
@@ -6290,34 +5342,54 @@ var init_story_url = __esm({
6290
5342
  };
6291
5343
  }
6292
5344
  });
6293
- function breakpointsFromMeta(context2, config) {
6294
- const fromParam = typeof config.from === "string" ? config.from : void 0;
6295
- if (!fromParam) return null;
6296
- const storyId = context2.params[fromParam];
6297
- if (typeof storyId !== "string" || storyId === "") return null;
6298
- const story = StoryMeta.loadOrCreate(context2.config, storyId);
6299
- const meta = story.data;
6300
- const bps = meta.reference?.breakpoints;
6301
- if (!bps) return null;
6302
- const keys = Object.keys(bps).filter((k) => !k.startsWith("$"));
6303
- return keys.length > 0 ? keys : null;
5345
+ function normalizeUrl(url2) {
5346
+ return url2.toLowerCase().replace(/\/+$/, "");
6304
5347
  }
5348
+ function hashReferenceUrl(url2) {
5349
+ const normalized = normalizeUrl(url2);
5350
+ return createHash("sha256").update(normalized).digest("hex").slice(0, 12);
5351
+ }
5352
+ var referenceFolderResolver;
5353
+ var init_reference_folder = __esm({
5354
+ "src/resolvers/reference-folder.ts"() {
5355
+ referenceFolderResolver = {
5356
+ name: "reference_folder",
5357
+ resolve(_input, config, context2) {
5358
+ const fromParam = config.from;
5359
+ if (!fromParam) {
5360
+ return {
5361
+ resolved: false,
5362
+ input: "",
5363
+ error: 'Missing "from" field in resolver config'
5364
+ };
5365
+ }
5366
+ const url2 = context2.params[fromParam];
5367
+ if (typeof url2 !== "string" || url2 === "") {
5368
+ return {
5369
+ resolved: false,
5370
+ input: "",
5371
+ error: `Parameter "${fromParam}" is missing or empty`
5372
+ };
5373
+ }
5374
+ const hash = hashReferenceUrl(url2);
5375
+ const folder = resolve(context2.config.data, "references", hash);
5376
+ mkdirSync(folder, { recursive: true });
5377
+ return {
5378
+ resolved: true,
5379
+ value: folder,
5380
+ input: url2
5381
+ };
5382
+ }
5383
+ };
5384
+ }
5385
+ });
6305
5386
  var TOKENS_PATH, breakpointsResolver;
6306
5387
  var init_breakpoints = __esm({
6307
5388
  "src/resolvers/breakpoints.ts"() {
6308
- init_story_entity();
6309
5389
  TOKENS_PATH = "design-system/design-tokens.yml";
6310
5390
  breakpointsResolver = {
6311
5391
  name: "breakpoints",
6312
- resolve(_input, config, context2) {
6313
- const metaBreakpoints = breakpointsFromMeta(context2, config);
6314
- if (metaBreakpoints) {
6315
- return {
6316
- resolved: true,
6317
- value: metaBreakpoints.join(","),
6318
- input: ""
6319
- };
6320
- }
5392
+ resolve(_input, _config, context2) {
6321
5393
  const tokensFile = join(context2.config.data, TOKENS_PATH);
6322
5394
  if (!existsSync(tokensFile)) {
6323
5395
  return {
@@ -7013,8 +6085,8 @@ function pickRegionLabel(params) {
7013
6085
  if (segments[0] === "design-system") {
7014
6086
  return "shell";
7015
6087
  }
7016
- const basename5 = segments[segments.length - 1] ?? "";
7017
- return basename5.replace(/(\.[^./]+)+$/, "");
6088
+ const basename6 = segments[segments.length - 1] ?? "";
6089
+ return basename6.replace(/(\.[^./]+)+$/, "");
7018
6090
  }
7019
6091
  return "";
7020
6092
  }
@@ -7187,6 +6259,32 @@ var init_region_properties = __esm({
7187
6259
  };
7188
6260
  }
7189
6261
  });
6262
+ function resolveConfigSyncDir({ docroot, syncRelative }) {
6263
+ if (syncRelative !== null) {
6264
+ return resolve(docroot, syncRelative);
6265
+ }
6266
+ return resolve(docroot, "sites", "default", "files", "config_default", "sync");
6267
+ }
6268
+ var configSyncDirResolver;
6269
+ var init_config_sync_dir = __esm({
6270
+ "src/resolvers/config-sync-dir.ts"() {
6271
+ configSyncDirResolver = {
6272
+ name: "config_sync_dir",
6273
+ resolve(input, config) {
6274
+ if (input.startsWith("/")) {
6275
+ return { resolved: true, value: input, input };
6276
+ }
6277
+ const docroot = typeof config.docroot === "string" ? config.docroot : input;
6278
+ if (!docroot) {
6279
+ return { resolved: false, input: "", error: "config_sync_dir: docroot is required" };
6280
+ }
6281
+ const syncRelative = typeof config.syncRelative === "string" && config.syncRelative !== "" ? config.syncRelative : null;
6282
+ const value = resolveConfigSyncDir({ docroot, syncRelative });
6283
+ return { resolved: true, value, input: docroot };
6284
+ }
6285
+ };
6286
+ }
6287
+ });
7190
6288
 
7191
6289
  // src/resolvers/registry.ts
7192
6290
  var registry_exports = {};
@@ -7285,6 +6383,7 @@ var init_registry = __esm({
7285
6383
  init_scene_path();
7286
6384
  init_components_index();
7287
6385
  init_region_properties();
6386
+ init_config_sync_dir();
7288
6387
  resolvers = /* @__PURE__ */ new Map();
7289
6388
  register(storyIdResolver);
7290
6389
  register(storyUrlResolver);
@@ -7293,6 +6392,7 @@ var init_registry = __esm({
7293
6392
  register(scenePathResolver);
7294
6393
  register(componentsIndexResolver);
7295
6394
  register(regionPropertiesResolver);
6395
+ register(configSyncDirResolver);
7296
6396
  resolverRegistry = {
7297
6397
  get(name) {
7298
6398
  return resolvers.get(name);
@@ -8094,10 +7194,10 @@ function walkNode(node, path, errors) {
8094
7194
  const slotPath = `${path}.slots.${slotName}`;
8095
7195
  if (typeof slotValue === "string") continue;
8096
7196
  if (Array.isArray(slotValue)) {
8097
- for (let j = 0; j < slotValue.length; j++) {
8098
- const el = slotValue[j];
7197
+ for (let j2 = 0; j2 < slotValue.length; j2++) {
7198
+ const el = slotValue[j2];
8099
7199
  if (typeof el === "string") continue;
8100
- walkNode(el, `${slotPath}[${j}]`, errors);
7200
+ walkNode(el, `${slotPath}[${j2}]`, errors);
8101
7201
  }
8102
7202
  } else if (typeof slotValue === "object" && slotValue !== null) {
8103
7203
  walkNode(slotValue, slotPath, errors);
@@ -8277,6 +7377,20 @@ async function validateSceneBuild(file, config) {
8277
7377
  if (!raw || !Array.isArray(raw.scenes) || raw.scenes.length === 0) {
8278
7378
  return { file, type: "scene", valid: true, last_validated: ts, last_passed: ts };
8279
7379
  }
7380
+ const RESERVED_SCENE_NAMES = /* @__PURE__ */ new Set(["overview"]);
7381
+ for (const scene of raw.scenes) {
7382
+ const name = typeof scene?.name === "string" ? scene.name.trim().toLowerCase() : "";
7383
+ if (RESERVED_SCENE_NAMES.has(name)) {
7384
+ return {
7385
+ file,
7386
+ type: "scene",
7387
+ valid: false,
7388
+ error: `Scene name "${scene.name?.trim()}" is reserved \u2014 every scenes file already exports an "overview" story (the section overview page). A scene named "overview" collides with it and renders the section page instead of the scene. Rename the scene (e.g. to the section id or a descriptive label like "default").`,
7389
+ last_validated: ts,
7390
+ last_failed: ts
7391
+ };
7392
+ }
7393
+ }
8280
7394
  const designbookDir = findDesignbookDir(file, config);
8281
7395
  try {
8282
7396
  await buildSceneModule(file, raw, designbookDir, {});
@@ -8766,7 +7880,7 @@ function assertNotRepoRoot(dataDir) {
8766
7880
  const hasGit = existsSync(resolve(parent, ".git"));
8767
7881
  if (hasPnpmWorkspace && hasGit) {
8768
7882
  throw new Error(
8769
- `designbook CLI cannot write runtime data to the repo root (resolved DESIGNBOOK_DATA=${dataDir}). Run from a workspace (cd workspaces/<suite>) or set DESIGNBOOK_DATA explicitly.`
7883
+ `designbook CLI cannot write runtime data to the repo root (resolved DESIGNBOOK_DATA=${dataDir}). Run from a workspace theme dir (cd workspaces/<suite>/web/themes/custom/<theme>) or set DESIGNBOOK_DATA explicitly.`
8770
7884
  );
8771
7885
  }
8772
7886
  }
@@ -9044,27 +8158,6 @@ function computeFlowRate(input) {
9044
8158
  metrics: { errors, retries, unresolved }
9045
8159
  };
9046
8160
  }
9047
- var ASSERTION_TIMEOUT_MS = 1e3;
9048
- function evalAssertions(assertions, output) {
9049
- let passed = 0;
9050
- let total = 0;
9051
- const failures = [];
9052
- for (const a of assertions) {
9053
- if (a.type !== "javascript") continue;
9054
- total += 1;
9055
- const ctx = vm.createContext({ output }, { codeGeneration: { strings: false, wasm: false } });
9056
- try {
9057
- if (vm.runInContext(a.value, ctx, { timeout: ASSERTION_TIMEOUT_MS })) {
9058
- passed += 1;
9059
- } else {
9060
- failures.push(a.value);
9061
- }
9062
- } catch {
9063
- failures.push(a.value);
9064
- }
9065
- }
9066
- return { passed, total, failures };
9067
- }
9068
8161
  function deboSuffix(data) {
9069
8162
  if (!data.workflow_id) throw new Error("workflow_id is required for direct engine stash-at-target");
9070
8163
  return `.${data.workflow_id}.debo`;
@@ -9187,7 +8280,7 @@ function interpolatePrompt(prompt, state) {
9187
8280
  }
9188
8281
 
9189
8282
  // src/workflow-resolve.ts
9190
- init_esm4();
8283
+ init_esm3();
9191
8284
  var cache = /* @__PURE__ */ new Map();
9192
8285
  function compile(expr) {
9193
8286
  const hit = cache.get(expr);
@@ -10282,6 +9375,8 @@ async function expandResultDeclarations(resultDecl, filesDecl, params, envMap, v
10282
9375
  $ref: _ref,
10283
9376
  submission: _sub,
10284
9377
  flush: _flush,
9378
+ prepare: _prepare,
9379
+ generator: _generator,
10285
9380
  ...schemaProps
10286
9381
  } = decl;
10287
9382
  if (Object.keys(schemaProps).length > 0) {
@@ -10293,9 +9388,24 @@ async function expandResultDeclarations(resultDecl, filesDecl, params, envMap, v
10293
9388
  entry.path = await interpolate(decl.path, params, { envMap, lenient });
10294
9389
  }
10295
9390
  if (schema) entry.schema = schema;
10296
- if (validators2.length > 0) entry.validators = validators2;
9391
+ if (validators2.length > 0) {
9392
+ entry.validators = await Promise.all(
9393
+ validators2.map((v) => interpolate(v, { ...params, file: "{{ file }}" }, { envMap, lenient }))
9394
+ );
9395
+ }
10297
9396
  if (providerByKey[key]) entry.provider_rule = providerByKey[key];
10298
9397
  if (requiredList) entry.required = requiredList.includes(key);
9398
+ if (decl.prepare) {
9399
+ entry.prepare = {
9400
+ cmd: await interpolate(decl.prepare.cmd, params, { envMap, lenient }),
9401
+ as: decl.prepare.as
9402
+ };
9403
+ }
9404
+ if (decl.generator) {
9405
+ entry.generator = {
9406
+ jsonata: await interpolate(decl.generator.jsonata, params, { envMap, lenient })
9407
+ };
9408
+ }
10299
9409
  result[key] = entry;
10300
9410
  }
10301
9411
  return Object.keys(result).length > 0 ? result : void 0;
@@ -10694,7 +9804,11 @@ function typeLabel(prop) {
10694
9804
  function renderSubmitResultsHint(taskId, results) {
10695
9805
  const data = [];
10696
9806
  const direct = [];
9807
+ const generators = [];
10697
9808
  for (const [key, prop] of Object.entries(results)) {
9809
+ if (prop.generator?.jsonata) {
9810
+ generators.push([key, prop]);
9811
+ }
10698
9812
  if (!prop.path) continue;
10699
9813
  const sub = prop.submission ?? "data";
10700
9814
  if (sub === "direct") {
@@ -10703,24 +9817,40 @@ function renderSubmitResultsHint(taskId, results) {
10703
9817
  data.push([key, prop]);
10704
9818
  }
10705
9819
  }
10706
- if (data.length === 0) return null;
9820
+ if (data.length === 0 && generators.length === 0) return null;
10707
9821
  const lines = [];
10708
- lines.push("## Submit results");
10709
- lines.push("");
10710
- lines.push("Return every `submission: data` result in a single call:");
10711
- lines.push("");
10712
- lines.push(` workflow done --task ${taskId} --data '<json>'`);
10713
- lines.push("");
10714
- lines.push("The JSON must match:");
10715
- lines.push("");
10716
- lines.push(" {");
10717
- for (let i = 0; i < data.length; i++) {
10718
- const [key, prop] = data[i];
10719
- const comma = i < data.length - 1 ? "," : "";
10720
- const flushNote = prop.flush === "immediate" ? " (flush: immediate)" : "";
10721
- lines.push(` "${key}": ${typeLabel(prop)}${comma} // \u2192 ${prop.path}${flushNote}`);
10722
- }
10723
- lines.push(" }");
9822
+ if (generators.length > 0) {
9823
+ lines.push("## Generator results");
9824
+ lines.push("");
9825
+ lines.push("Produce these results by authoring and running a JSONata transform:");
9826
+ lines.push("");
9827
+ for (const [key, prop] of generators) {
9828
+ lines.push(
9829
+ `- **${key}**: author a JSONata at \`${prop.generator.jsonata}\` and run it to produce the result value.`
9830
+ );
9831
+ }
9832
+ lines.push("");
9833
+ lines.push("The JSONata file must exist on disk before submitting the result.");
9834
+ }
9835
+ if (data.length > 0) {
9836
+ if (lines.length > 0) lines.push("");
9837
+ lines.push("## Submit results");
9838
+ lines.push("");
9839
+ lines.push("Return every `submission: data` result in a single call:");
9840
+ lines.push("");
9841
+ lines.push(` workflow done --task ${taskId} --data '<json>'`);
9842
+ lines.push("");
9843
+ lines.push("The JSON must match:");
9844
+ lines.push("");
9845
+ lines.push(" {");
9846
+ for (let i = 0; i < data.length; i++) {
9847
+ const [key, prop] = data[i];
9848
+ const comma = i < data.length - 1 ? "," : "";
9849
+ const flushNote = prop.flush === "immediate" ? " (flush: immediate)" : "";
9850
+ lines.push(` "${key}": ${typeLabel(prop)}${comma} // \u2192 ${prop.path}${flushNote}`);
9851
+ }
9852
+ lines.push(" }");
9853
+ }
10724
9854
  if (direct.length > 0) {
10725
9855
  lines.push("");
10726
9856
  lines.push("Direct-submission results (written by task code, not submitted via --data):");
@@ -11200,6 +10330,7 @@ async function workflowDone(dataDir, name, taskId, loaded, options) {
11200
10330
  if (task.status === "done") {
11201
10331
  throw new Error(`Task '${taskId}' is already done`);
11202
10332
  }
10333
+ const validationGate = data.scope?.validation_gate ?? "hard";
11203
10334
  if (options?.data && task.result) {
11204
10335
  const dataPayload = options.data;
11205
10336
  const declaredKeys = new Set(Object.keys(task.result));
@@ -11293,7 +10424,7 @@ async function workflowDone(dataDir, name, taskId, loaded, options) {
11293
10424
  resultEntry.last_validated = (/* @__PURE__ */ new Date()).toISOString();
11294
10425
  }
11295
10426
  }
11296
- if (validationErrors.length > 0) {
10427
+ if (validationErrors.length > 0 && validationGate === "hard") {
11297
10428
  writeWorkflowAtomic(filePath, data);
11298
10429
  return {
11299
10430
  archived: false,
@@ -11366,7 +10497,7 @@ async function workflowDone(dataDir, name, taskId, loaded, options) {
11366
10497
  );
11367
10498
  }
11368
10499
  const failed = (task.files ?? []).filter((f) => f.validation_result?.valid === false);
11369
- if (failed.length > 0) {
10500
+ if (failed.length > 0 && validationGate === "hard") {
11370
10501
  throw new Error(
11371
10502
  `Cannot mark '${taskId}' as done \u2014 ${failed.length} file(s) have errors:
11372
10503
  ` + failed.map((f) => ` \xB7 file \`${f.key}\` has errors: ${f.validation_result?.error ?? "invalid"}`).join("\n")
@@ -11392,7 +10523,7 @@ async function workflowDone(dataDir, name, taskId, loaded, options) {
11392
10523
  );
11393
10524
  }
11394
10525
  const failedResults = Object.entries(task.result).filter(([, r]) => r.valid === false);
11395
- if (failedResults.length > 0) {
10526
+ if (failedResults.length > 0 && validationGate === "hard") {
11396
10527
  throw new Error(
11397
10528
  `Cannot mark '${taskId}' as done \u2014 ${failedResults.length} result(s) have errors:
11398
10529
  ` + failedResults.map(([k, r]) => ` \xB7 result \`${k}\` has errors: ${r.error ?? "invalid"}`).join("\n")
@@ -11813,6 +10944,18 @@ async function workflowResult(dataDir, name, taskId, key, content, config) {
11813
10944
  }
11814
10945
  async function validateResultEntry(entry, content, schemas, config, mode) {
11815
10946
  const errors = [];
10947
+ if (entry.generator?.jsonata && !existsSync(entry.generator.jsonata)) {
10948
+ return [`generator artifact missing: ${entry.generator.jsonata}`];
10949
+ }
10950
+ if (entry.prepare) {
10951
+ try {
10952
+ const out2 = execSync(entry.prepare.cmd, { timeout: 3e4, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
10953
+ entry = { ...entry, schema: JSON.parse(out2) };
10954
+ } catch (err) {
10955
+ const execErr = err;
10956
+ return [`prepare command failed: ${execErr.stderr?.trim() || execErr.message || String(err)}`];
10957
+ }
10958
+ }
11816
10959
  if (entry.schema) {
11817
10960
  const Ajv = (await import('ajv')).default;
11818
10961
  const ajv = new Ajv({ allErrors: true });
@@ -11887,20 +11030,6 @@ function readSummary(opts) {
11887
11030
  return null;
11888
11031
  }
11889
11032
  const wo = tasksData?.scope?.workflow_output ?? {};
11890
- let assertions;
11891
- if (opts.caseFile && existsSync(opts.caseFile)) {
11892
- const caseDoc = load(readFileSync(opts.caseFile, "utf-8"));
11893
- const assertList = caseDoc?.assert ?? [];
11894
- if (assertList.length > 0) {
11895
- const output = {
11896
- flowRate: wo.flow_rate,
11897
- successRate: wo.success_rate,
11898
- comparePassed: wo.compare_passed,
11899
- metrics: wo.metrics
11900
- };
11901
- assertions = evalAssertions(assertList, output);
11902
- }
11903
- }
11904
11033
  const sr = wo["score-report"];
11905
11034
  const scoreReport = sr && typeof sr.first_shot?.score === "number" && typeof sr.final?.score === "number" ? {
11906
11035
  firstShot: sr.first_shot.score,
@@ -11921,8 +11050,7 @@ function readSummary(opts) {
11921
11050
  } : {},
11922
11051
  ...wo.summary ? { summary: wo.summary } : {},
11923
11052
  ...wo.warnings?.length ? { warnings: wo.warnings } : {},
11924
- ...scoreReport ? { scoreReport } : {},
11925
- ...assertions ? { assertions } : {}
11053
+ ...scoreReport ? { scoreReport } : {}
11926
11054
  };
11927
11055
  const children = tasksData?.children ?? [];
11928
11056
  if (children.length > 0) {
@@ -11952,14 +11080,6 @@ function readSummary(opts) {
11952
11080
  }
11953
11081
  return result;
11954
11082
  }
11955
- async function evaluateMetric(summary, expression) {
11956
- try {
11957
- const v = await jsonata6(expression).evaluate(summary);
11958
- return typeof v === "number" ? v : null;
11959
- } catch {
11960
- return null;
11961
- }
11962
- }
11963
11083
  function formatHuman(r) {
11964
11084
  const lines = [
11965
11085
  r.workflow,
@@ -11973,30 +11093,19 @@ function formatHuman(r) {
11973
11093
  ` fidelity: first_shot ${r.scoreReport.firstShot} \xB7 final ${r.scoreReport.final} \xB7 delta ${r.scoreReport.delta} (lower is better)`
11974
11094
  ] : [],
11975
11095
  ...r.summary ? [` summary: ${r.summary}`] : [],
11976
- ...r.warnings?.length ? r.warnings.map((w) => ` warning: ${w}`) : [],
11977
- ...r.assertions ? [` assertions: ${r.assertions.passed}/${r.assertions.total} passed`] : []
11096
+ ...r.warnings?.length ? r.warnings.map((w) => ` warning: ${w}`) : []
11978
11097
  ];
11979
11098
  return lines.join("\n");
11980
11099
  }
11981
11100
  function register2(workflow) {
11982
- workflow.command("summary").description("Show result of the most recent workflow run (flow_rate, success_rate, metrics).").requiredOption("--workflow <name>", "Workflow name (e.g. design-shell-2026-05-06-abcd)").option("--case <file>", "Case YAML with assert: block").option("--json", "JSON output (for research loop)").option(
11983
- "--metric <expression>",
11984
- "JSONata expression evaluated over the summary; included in JSON output; exit 1 when null"
11985
- ).action(async (opts) => {
11101
+ workflow.command("summary").description("Show result of the most recent workflow run (flow_rate, success_rate, metrics).").requiredOption("--workflow <name>", "Workflow name (e.g. design-shell-2026-05-06-abcd)").option("--json", "JSON output (for research loop)").action((opts) => {
11986
11102
  const config = loadConfig();
11987
- const r = readSummary({ dataDir: config.data, workflowName: opts.workflow, caseFile: opts.case });
11103
+ const r = readSummary({ dataDir: config.data, workflowName: opts.workflow });
11988
11104
  if (!r) {
11989
11105
  console.error(`No archived workflow found: ${opts.workflow}`);
11990
11106
  process.exit(1);
11991
11107
  }
11992
- if (opts.metric !== void 0) {
11993
- const metricValue = await evaluateMetric(r, opts.metric);
11994
- const output = { ...r, metric: metricValue };
11995
- console.log(JSON.stringify(output));
11996
- if (metricValue === null) {
11997
- process.exitCode = 1;
11998
- }
11999
- } else if (opts.json) {
11108
+ if (opts.json) {
12000
11109
  console.log(JSON.stringify(r));
12001
11110
  } else {
12002
11111
  console.log(formatHuman(r));
@@ -12005,7 +11114,7 @@ function register2(workflow) {
12005
11114
  }
12006
11115
 
12007
11116
  // src/cli/workflow-discovery.ts
12008
- init_esm4();
11117
+ init_esm3();
12009
11118
  function pluginSources2(sources) {
12010
11119
  return (sources ?? []).filter((s) => s.origin === "plugin");
12011
11120
  }
@@ -12090,6 +11199,12 @@ function buildInstructions(dataDir, workflowName, stageName) {
12090
11199
  ...stage.isolate ? { isolate: true } : {}
12091
11200
  };
12092
11201
  }
11202
+ function selectPrimaryResolvedStep(step, raw) {
11203
+ if (!raw) return void 0;
11204
+ if (!Array.isArray(raw)) return raw;
11205
+ const stepBasename = `${step.split(":").pop()}.md`;
11206
+ return raw.find((entry) => basename(entry.task_file) === stepBasename) ?? raw[0];
11207
+ }
12093
11208
  async function runWorkflowCreate(opts, config) {
12094
11209
  let initialParams = opts.params;
12095
11210
  const configPath = findConfig();
@@ -12138,8 +11253,7 @@ async function runWorkflowCreate(opts, config) {
12138
11253
  for (const [stageName, stageDef] of Object.entries(resolved.stages)) {
12139
11254
  const step = stageDef.steps?.[0];
12140
11255
  if (!step) continue;
12141
- const raw = resolved.step_resolved[step];
12142
- const res = raw && !Array.isArray(raw) ? raw : void 0;
11256
+ const res = selectPrimaryResolvedStep(step, resolved.step_resolved[step]);
12143
11257
  if (res) {
12144
11258
  firstStepName = step;
12145
11259
  firstStageName = stageName;
@@ -12709,9 +11823,9 @@ function extractExample(bodyMarkdown) {
12709
11823
  if (ANY_HEADING_RE.test(trimmed) && !HEADING_RE.test(trimmed)) return null;
12710
11824
  if (FENCE_OPEN_RE.test(trimmed)) {
12711
11825
  const buf = [];
12712
- for (let j = i + 1; j < lines.length; j++) {
12713
- if (FENCE_CLOSE_RE.test(lines[j].trim())) return buf.join("\n");
12714
- buf.push(lines[j]);
11826
+ for (let j2 = i + 1; j2 < lines.length; j2++) {
11827
+ if (FENCE_CLOSE_RE.test(lines[j2].trim())) return buf.join("\n");
11828
+ buf.push(lines[j2]);
12715
11829
  }
12716
11830
  return null;
12717
11831
  }