@kokimoki/app 3.1.3 → 3.1.4

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.
Files changed (61) hide show
  1. package/README.md +1 -2
  2. package/dist/core/kokimoki-client.d.ts +4 -4
  3. package/dist/core/kokimoki-client.js +4 -4
  4. package/dist/kokimoki.min.d.ts +3 -321
  5. package/dist/kokimoki.min.js +763 -2014
  6. package/dist/kokimoki.min.js.map +1 -1
  7. package/dist/utils/valtio.d.ts +2 -5
  8. package/dist/utils/valtio.js +4 -2
  9. package/dist/version.d.ts +1 -1
  10. package/dist/version.js +1 -1
  11. package/docs/kokimoki-ai.instructions.md +4 -2
  12. package/docs/kokimoki-dynamic-stores.instructions.md +3 -3
  13. package/docs/kokimoki-i18n.instructions.md +1 -1
  14. package/docs/kokimoki-sdk.instructions.md +46 -7
  15. package/package.json +8 -2
  16. package/dist/fields.d.ts +0 -110
  17. package/dist/fields.js +0 -158
  18. package/dist/kokimoki-ai.d.ts +0 -153
  19. package/dist/kokimoki-ai.js +0 -164
  20. package/dist/kokimoki-awareness.d.ts +0 -21
  21. package/dist/kokimoki-awareness.js +0 -48
  22. package/dist/kokimoki-client-refactored.d.ts +0 -80
  23. package/dist/kokimoki-client-refactored.js +0 -400
  24. package/dist/kokimoki-client.d.ts +0 -362
  25. package/dist/kokimoki-client.js +0 -823
  26. package/dist/kokimoki-leaderboard.d.ts +0 -175
  27. package/dist/kokimoki-leaderboard.js +0 -203
  28. package/dist/kokimoki-local-store.d.ts +0 -11
  29. package/dist/kokimoki-local-store.js +0 -40
  30. package/dist/kokimoki-queue.d.ts +0 -0
  31. package/dist/kokimoki-queue.js +0 -38
  32. package/dist/kokimoki-req-res.d.ts +0 -0
  33. package/dist/kokimoki-req-res.js +0 -198
  34. package/dist/kokimoki-schema.d.ts +0 -113
  35. package/dist/kokimoki-schema.js +0 -162
  36. package/dist/kokimoki-storage.d.ts +0 -156
  37. package/dist/kokimoki-storage.js +0 -208
  38. package/dist/kokimoki-store.d.ts +0 -23
  39. package/dist/kokimoki-store.js +0 -117
  40. package/dist/kokimoki-transaction.d.ts +0 -18
  41. package/dist/kokimoki-transaction.js +0 -143
  42. package/dist/message-queue.d.ts +0 -8
  43. package/dist/message-queue.js +0 -19
  44. package/dist/room-subscription-mode.d.ts +0 -5
  45. package/dist/room-subscription-mode.js +0 -6
  46. package/dist/room-subscription.d.ts +0 -15
  47. package/dist/room-subscription.js +0 -52
  48. package/dist/synced-schema.d.ts +0 -74
  49. package/dist/synced-schema.js +0 -83
  50. package/dist/synced-store.d.ts +0 -10
  51. package/dist/synced-store.js +0 -9
  52. package/dist/synced-types.d.ts +0 -47
  53. package/dist/synced-types.js +0 -67
  54. package/dist/ws-message-reader.d.ts +0 -11
  55. package/dist/ws-message-reader.js +0 -36
  56. package/dist/ws-message-type copy.d.ts +0 -6
  57. package/dist/ws-message-type copy.js +0 -7
  58. package/dist/ws-message-type.d.ts +0 -11
  59. package/dist/ws-message-type.js +0 -12
  60. package/dist/ws-message-writer.d.ts +0 -9
  61. package/dist/ws-message-writer.js +0 -45
@@ -1,8 +1,5 @@
1
- import i18next from 'i18next';
2
- import HttpBackend from 'i18next-http-backend';
3
1
  import require$$1 from 'path';
4
2
  import require$$2 from 'fs';
5
- import { useMemo, useRef, useSyncExternalStore, useCallback, useLayoutEffect, useEffect, useDebugValue } from 'react';
6
3
 
7
4
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8
5
 
@@ -495,12 +492,6 @@ var EventEmitter$1 = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
495
492
  * @module map
496
493
  */
497
494
 
498
- /**
499
- * @template K
500
- * @template V
501
- * @typedef {Map<K,V>} GlobalMap
502
- */
503
-
504
495
  /**
505
496
  * Creates a new Map instance.
506
497
  *
@@ -636,58 +627,6 @@ const appendTo = (dest, src) => {
636
627
  */
637
628
  const from = Array.from;
638
629
 
639
- /**
640
- * True iff condition holds on every element in the Array.
641
- *
642
- * @function
643
- * @template {ArrayLike<any>} ARR
644
- *
645
- * @param {ARR} arr
646
- * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : any} f
647
- * @return {boolean}
648
- */
649
- const every$1 = (arr, f) => {
650
- for (let i = 0; i < arr.length; i++) {
651
- if (!f(arr[i], i, arr)) {
652
- return false
653
- }
654
- }
655
- return true
656
- };
657
-
658
- /**
659
- * True iff condition holds on some element in the Array.
660
- *
661
- * @function
662
- * @template {ArrayLike<any>} ARR
663
- *
664
- * @param {ARR} arr
665
- * @param {ARR extends ArrayLike<infer S> ? ((value:S, index:number, arr:ARR) => boolean) : never} f
666
- * @return {boolean}
667
- */
668
- const some = (arr, f) => {
669
- for (let i = 0; i < arr.length; i++) {
670
- if (f(arr[i], i, arr)) {
671
- return true
672
- }
673
- }
674
- return false
675
- };
676
-
677
- /**
678
- * @template T
679
- * @param {number} len
680
- * @param {function(number, Array<T>):T} f
681
- * @return {Array<T>}
682
- */
683
- const unfold = (len, f) => {
684
- const array = new Array(len);
685
- for (let i = 0; i < len; i++) {
686
- array[i] = f(i, array);
687
- }
688
- return array
689
- };
690
-
691
630
  const isArray$1 = Array.isArray;
692
631
 
693
632
  /**
@@ -803,10 +742,8 @@ const min$2 = (a, b) => a < b ? a : b;
803
742
  const max$3 = (a, b) => a > b ? a : b;
804
743
 
805
744
  /**
806
- * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this
807
- * function returns true for -0,-1,,.. and returns false for 0,1,2,...
808
745
  * @param {number} n
809
- * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0
746
+ * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0
810
747
  */
811
748
  const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0;
812
749
 
@@ -846,19 +783,10 @@ const BITS31 = 0x7FFFFFFF;
846
783
 
847
784
 
848
785
  const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
849
- const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
850
786
 
851
787
  /* c8 ignore next */
852
788
  const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && floor$2(num) === num);
853
789
 
854
- /**
855
- * Utility module to work with strings.
856
- *
857
- * @module string
858
- */
859
-
860
- const fromCharCode = String.fromCharCode;
861
-
862
790
  /**
863
791
  * @param {string} s
864
792
  * @return {string}
@@ -884,7 +812,7 @@ const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, m
884
812
 
885
813
  /**
886
814
  * @param {string} str
887
- * @return {Uint8Array<ArrayBuffer>}
815
+ * @return {Uint8Array}
888
816
  */
889
817
  const _encodeUtf8Polyfill = str => {
890
818
  const encodedString = unescape(encodeURIComponent(str));
@@ -901,7 +829,7 @@ const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'unde
901
829
 
902
830
  /**
903
831
  * @param {string} str
904
- * @return {Uint8Array<ArrayBuffer>}
832
+ * @return {Uint8Array}
905
833
  */
906
834
  const _encodeUtf8Native = str => utf8TextEncoder.encode(str);
907
835
 
@@ -926,12 +854,6 @@ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
926
854
  utf8TextDecoder = null;
927
855
  }
928
856
 
929
- /**
930
- * @param {string} source
931
- * @param {number} n
932
- */
933
- const repeat = (source, n) => unfold(n, () => source).join('');
934
-
935
857
  /**
936
858
  * Efficient schema-less binary encoding with support for variable length encoding.
937
859
  *
@@ -1001,7 +923,7 @@ const length = encoder => {
1001
923
  *
1002
924
  * @function
1003
925
  * @param {Encoder} encoder
1004
- * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.
926
+ * @return {Uint8Array} The created ArrayBuffer.
1005
927
  */
1006
928
  const toUint8Array = encoder => {
1007
929
  const uint8arr = new Uint8Array(length(encoder));
@@ -1242,14 +1164,6 @@ const isFloat32 = num => {
1242
1164
  return floatTestBed.getFloat32(0) === num
1243
1165
  };
1244
1166
 
1245
- /**
1246
- * @typedef {Array<AnyEncodable>} AnyEncodableArray
1247
- */
1248
-
1249
- /**
1250
- * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable
1251
- */
1252
-
1253
1167
  /**
1254
1168
  * Encode data with efficient binary format.
1255
1169
  *
@@ -1285,7 +1199,7 @@ const isFloat32 = num => {
1285
1199
  * lib0/encoding.js
1286
1200
  *
1287
1201
  * @param {Encoder} encoder
1288
- * @param {AnyEncodable} data
1202
+ * @param {undefined|null|number|bigint|boolean|string|Object<string,any>|Array<any>|Uint8Array} data
1289
1203
  */
1290
1204
  const writeAny = (encoder, data) => {
1291
1205
  switch (typeof data) {
@@ -1639,17 +1553,16 @@ const errorIntegerOutOfRange = create$3('Integer out of Range');
1639
1553
 
1640
1554
  /**
1641
1555
  * A Decoder handles the decoding of an Uint8Array.
1642
- * @template {ArrayBufferLike} [Buf=ArrayBufferLike]
1643
1556
  */
1644
1557
  class Decoder {
1645
1558
  /**
1646
- * @param {Uint8Array<Buf>} uint8Array Binary data to decode
1559
+ * @param {Uint8Array} uint8Array Binary data to decode
1647
1560
  */
1648
1561
  constructor (uint8Array) {
1649
1562
  /**
1650
1563
  * Decoding target.
1651
1564
  *
1652
- * @type {Uint8Array<Buf>}
1565
+ * @type {Uint8Array}
1653
1566
  */
1654
1567
  this.arr = uint8Array;
1655
1568
  /**
@@ -1663,9 +1576,8 @@ class Decoder {
1663
1576
 
1664
1577
  /**
1665
1578
  * @function
1666
- * @template {ArrayBufferLike} Buf
1667
- * @param {Uint8Array<Buf>} uint8Array
1668
- * @return {Decoder<Buf>}
1579
+ * @param {Uint8Array} uint8Array
1580
+ * @return {Decoder}
1669
1581
  */
1670
1582
  const createDecoder = uint8Array => new Decoder(uint8Array);
1671
1583
 
@@ -1683,10 +1595,9 @@ const hasContent = decoder => decoder.pos !== decoder.arr.length;
1683
1595
  * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1684
1596
  *
1685
1597
  * @function
1686
- * @template {ArrayBufferLike} Buf
1687
- * @param {Decoder<Buf>} decoder The decoder instance
1598
+ * @param {Decoder} decoder The decoder instance
1688
1599
  * @param {number} len The length of bytes to read
1689
- * @return {Uint8Array<Buf>}
1600
+ * @return {Uint8Array}
1690
1601
  */
1691
1602
  const readUint8Array = (decoder, len) => {
1692
1603
  const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
@@ -1701,9 +1612,8 @@ const readUint8Array = (decoder, len) => {
1701
1612
  * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
1702
1613
  *
1703
1614
  * @function
1704
- * @template {ArrayBufferLike} Buf
1705
- * @param {Decoder<Buf>} decoder
1706
- * @return {Uint8Array<Buf>}
1615
+ * @param {Decoder} decoder
1616
+ * @return {Uint8Array}
1707
1617
  */
1708
1618
  const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder));
1709
1619
 
@@ -2159,43 +2069,17 @@ try {
2159
2069
  /* c8 ignore next */
2160
2070
  const varStorage = _localStorage;
2161
2071
 
2162
- const EqualityTraitSymbol = Symbol('Equality');
2163
-
2164
2072
  /**
2165
- * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait
2166
- */
2167
-
2168
- /**
2169
- *
2170
- * Utility function to compare any two objects.
2073
+ * Utility functions for working with EcmaScript objects.
2171
2074
  *
2172
- * Note that it is expected that the first parameter is more specific than the latter one.
2173
- *
2174
- * @example js
2175
- * class X { [traits.EqualityTraitSymbol] (other) { return other === this } }
2176
- * class X2 { [traits.EqualityTraitSymbol] (other) { return other === this }, x2 () { return 2 } }
2177
- * // this is fine
2178
- * traits.equals(new X2(), new X())
2179
- * // this is not, because the left type is less specific than the right one
2180
- * traits.equals(new X(), new X2())
2181
- *
2182
- * @template {EqualityTrait} T
2183
- * @param {NoInfer<T>} a
2184
- * @param {T} b
2185
- * @return {boolean}
2075
+ * @module object
2186
2076
  */
2187
- const equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false;
2188
2077
 
2189
- /**
2190
- * @param {any} o
2191
- * @return {o is { [k:string]:any }}
2192
- */
2193
- const isObject$2 = o => typeof o === 'object';
2194
2078
 
2195
2079
  /**
2196
2080
  * Object.assign
2197
2081
  */
2198
- const assign = Object.assign;
2082
+ const assign$1 = Object.assign;
2199
2083
 
2200
2084
  /**
2201
2085
  * @param {Object<string,any>} obj
@@ -2259,7 +2143,7 @@ const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
2259
2143
  * @param {Object<string,any>} b
2260
2144
  * @return {boolean}
2261
2145
  */
2262
- const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && equals(b[key], val)));
2146
+ const equalFlat = (a, b) => a === b || (size(a) === size(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val));
2263
2147
 
2264
2148
  /**
2265
2149
  * Make an object immutable. This hurts performance and is usually not needed if you perform good
@@ -2318,88 +2202,6 @@ const callAll = (fs, args, i = 0) => {
2318
2202
  */
2319
2203
  const id = a => a;
2320
2204
 
2321
- /* c8 ignore start */
2322
-
2323
- /**
2324
- * @param {any} a
2325
- * @param {any} b
2326
- * @return {boolean}
2327
- */
2328
- const equalityDeep = (a, b) => {
2329
- if (a === b) {
2330
- return true
2331
- }
2332
- if (a == null || b == null || (a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object))) {
2333
- return false
2334
- }
2335
- if (a[EqualityTraitSymbol] != null) {
2336
- return a[EqualityTraitSymbol](b)
2337
- }
2338
- switch (a.constructor) {
2339
- case ArrayBuffer:
2340
- a = new Uint8Array(a);
2341
- b = new Uint8Array(b);
2342
- // eslint-disable-next-line no-fallthrough
2343
- case Uint8Array: {
2344
- if (a.byteLength !== b.byteLength) {
2345
- return false
2346
- }
2347
- for (let i = 0; i < a.length; i++) {
2348
- if (a[i] !== b[i]) {
2349
- return false
2350
- }
2351
- }
2352
- break
2353
- }
2354
- case Set: {
2355
- if (a.size !== b.size) {
2356
- return false
2357
- }
2358
- for (const value of a) {
2359
- if (!b.has(value)) {
2360
- return false
2361
- }
2362
- }
2363
- break
2364
- }
2365
- case Map: {
2366
- if (a.size !== b.size) {
2367
- return false
2368
- }
2369
- for (const key of a.keys()) {
2370
- if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {
2371
- return false
2372
- }
2373
- }
2374
- break
2375
- }
2376
- case undefined:
2377
- case Object:
2378
- if (size(a) !== size(b)) {
2379
- return false
2380
- }
2381
- for (const key in a) {
2382
- if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) {
2383
- return false
2384
- }
2385
- }
2386
- break
2387
- case Array:
2388
- if (a.length !== b.length) {
2389
- return false
2390
- }
2391
- for (let i = 0; i < a.length; i++) {
2392
- if (!equalityDeep(a[i], b[i])) {
2393
- return false
2394
- }
2395
- }
2396
- break
2397
- default:
2398
- return false
2399
- }
2400
- return true
2401
- };
2402
-
2403
2205
  /**
2404
2206
  * @template V
2405
2207
  * @template {V} OPTS
@@ -2494,7 +2296,7 @@ const hasConf = (name) =>
2494
2296
  hasParam('--' + name) || getVariable(name) !== null;
2495
2297
 
2496
2298
  /* c8 ignore next */
2497
- const production = hasConf('production');
2299
+ hasConf('production');
2498
2300
 
2499
2301
  /* c8 ignore next 2 */
2500
2302
  const forceColor = isNode &&
@@ -2517,1285 +2319,71 @@ const supportsColor = forceColor || (
2517
2319
  getVariable('COLORTERM') !== null ||
2518
2320
  (getVariable('TERM') || '').includes('color')
2519
2321
  )
2520
- );
2521
- /* c8 ignore stop */
2522
-
2523
- /**
2524
- * Utility functions to work with buffers (Uint8Array).
2525
- *
2526
- * @module buffer
2527
- */
2528
-
2529
-
2530
- /**
2531
- * @param {number} len
2532
- */
2533
- const createUint8ArrayFromLen = len => new Uint8Array(len);
2534
-
2535
- /**
2536
- * Copy the content of an Uint8Array view to a new ArrayBuffer.
2537
- *
2538
- * @param {Uint8Array} uint8Array
2539
- * @return {Uint8Array}
2540
- */
2541
- const copyUint8Array = uint8Array => {
2542
- const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
2543
- newBuf.set(uint8Array);
2544
- return newBuf
2545
- };
2546
-
2547
- /**
2548
- * Working with value pairs.
2549
- *
2550
- * @module pair
2551
- */
2552
-
2553
- /**
2554
- * @template L,R
2555
- */
2556
- class Pair {
2557
- /**
2558
- * @param {L} left
2559
- * @param {R} right
2560
- */
2561
- constructor (left, right) {
2562
- this.left = left;
2563
- this.right = right;
2564
- }
2565
- }
2566
-
2567
- /**
2568
- * @template L,R
2569
- * @param {L} left
2570
- * @param {R} right
2571
- * @return {Pair<L,R>}
2572
- */
2573
- const create$1 = (left, right) => new Pair(left, right);
2574
-
2575
- /**
2576
- * Fast Pseudo Random Number Generators.
2577
- *
2578
- * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted.
2579
- * Two PRNGs must generate the same random sequence of numbers if given the same seed.
2580
- *
2581
- * @module prng
2582
- */
2583
-
2584
-
2585
- /**
2586
- * Generates a single random bool.
2587
- *
2588
- * @param {PRNG} gen A random number generator.
2589
- * @return {Boolean} A random boolean
2590
- */
2591
- const bool = gen => (gen.next() >= 0.5);
2592
-
2593
- /**
2594
- * Generates a random integer with 53 bit resolution.
2595
- *
2596
- * @param {PRNG} gen A random number generator.
2597
- * @param {Number} min The lower bound of the allowed return values (inclusive).
2598
- * @param {Number} max The upper bound of the allowed return values (inclusive).
2599
- * @return {Number} A random integer on [min, max]
2600
- */
2601
- const int53 = (gen, min, max) => floor$2(gen.next() * (max + 1 - min) + min);
2602
-
2603
- /**
2604
- * Generates a random integer with 32 bit resolution.
2605
- *
2606
- * @param {PRNG} gen A random number generator.
2607
- * @param {Number} min The lower bound of the allowed return values (inclusive).
2608
- * @param {Number} max The upper bound of the allowed return values (inclusive).
2609
- * @return {Number} A random integer on [min, max]
2610
- */
2611
- const int32 = (gen, min, max) => floor$2(gen.next() * (max + 1 - min) + min);
2612
-
2613
- /**
2614
- * @deprecated
2615
- * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when
2616
- * openaring on smaller ranges.
2617
- *
2618
- * @param {PRNG} gen A random number generator.
2619
- * @param {Number} min The lower bound of the allowed return values (inclusive).
2620
- * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1`
2621
- * @return {Number} A random integer on [min, max]
2622
- */
2623
- const int31 = (gen, min, max) => int32(gen, min, max);
2624
-
2625
- /**
2626
- * @param {PRNG} gen
2627
- * @return {string} A single letter (a-z)
2628
- */
2629
- const letter = gen => fromCharCode(int31(gen, 97, 122));
2630
-
2631
- /**
2632
- * @param {PRNG} gen
2633
- * @param {number} [minLen=0]
2634
- * @param {number} [maxLen=20]
2635
- * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z)
2636
- */
2637
- const word = (gen, minLen = 0, maxLen = 20) => {
2638
- const len = int31(gen, minLen, maxLen);
2639
- let str = '';
2640
- for (let i = 0; i < len; i++) {
2641
- str += letter(gen);
2642
- }
2643
- return str
2644
- };
2645
-
2646
- /**
2647
- * Returns one element of a given array.
2648
- *
2649
- * @param {PRNG} gen A random number generator.
2650
- * @param {Array<T>} array Non empty Array of possible values.
2651
- * @return {T} One of the values of the supplied Array.
2652
- * @template T
2653
- */
2654
- const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)];
2655
- /* c8 ignore stop */
2656
-
2657
- /**
2658
- * @experimental WIP
2659
- *
2660
- * Simple & efficient schemas for your data.
2661
- */
2662
-
2663
-
2664
- /**
2665
- * @typedef {string|number|bigint|boolean|null|undefined|symbol} Primitive
2666
- */
2667
-
2668
- /**
2669
- * @typedef {{ [k:string|number|symbol]: any }} AnyObject
2670
- */
2671
-
2672
- /**
2673
- * @template T
2674
- * @typedef {T extends Schema<infer X> ? X : T} Unwrap
2675
- */
2676
-
2677
- /**
2678
- * @template T
2679
- * @typedef {T extends Schema<infer X> ? X : T} TypeOf
2680
- */
2681
-
2682
- /**
2683
- * @template {readonly unknown[]} T
2684
- * @typedef {T extends readonly [Schema<infer First>, ...infer Rest] ? [First, ...UnwrapArray<Rest>] : [] } UnwrapArray
2685
- */
2686
-
2687
- /**
2688
- * @template T
2689
- * @typedef {T extends Schema<infer S> ? Schema<S> : never} CastToSchema
2690
- */
2691
-
2692
- /**
2693
- * @template {unknown[]} Arr
2694
- * @typedef {Arr extends [...unknown[], infer L] ? L : never} TupleLast
2695
- */
2696
-
2697
- /**
2698
- * @template {unknown[]} Arr
2699
- * @typedef {Arr extends [...infer Fs, unknown] ? Fs : never} TuplePop
2700
- */
2701
-
2702
- /**
2703
- * @template {readonly unknown[]} T
2704
- * @typedef {T extends []
2705
- * ? {}
2706
- * : T extends [infer First]
2707
- * ? First
2708
- * : T extends [infer First, ...infer Rest]
2709
- * ? First & Intersect<Rest>
2710
- * : never
2711
- * } Intersect
2712
- */
2713
-
2714
- const schemaSymbol = Symbol('0schema');
2715
-
2716
- class ValidationError {
2717
- constructor () {
2718
- /**
2719
- * Reverse errors
2720
- * @type {Array<{ path: string?, expected: string, has: string, message: string? }>}
2721
- */
2722
- this._rerrs = [];
2723
- }
2724
-
2725
- /**
2726
- * @param {string?} path
2727
- * @param {string} expected
2728
- * @param {string} has
2729
- * @param {string?} message
2730
- */
2731
- extend (path, expected, has, message = null) {
2732
- this._rerrs.push({ path, expected, has, message });
2733
- }
2734
-
2735
- toString () {
2736
- const s = [];
2737
- for (let i = this._rerrs.length - 1; i > 0; i--) {
2738
- const r = this._rerrs[i];
2739
- /* c8 ignore next */
2740
- s.push(repeat(' ', (this._rerrs.length - i) * 2) + `${r.path != null ? `[${r.path}] ` : ''}${r.has} doesn't match ${r.expected}. ${r.message}`);
2741
- }
2742
- return s.join('\n')
2743
- }
2744
- }
2745
-
2746
- /**
2747
- * @param {any} a
2748
- * @param {any} b
2749
- * @return {boolean}
2750
- */
2751
- const shapeExtends = (a, b) => {
2752
- if (a === b) return true
2753
- if (a == null || b == null || a.constructor !== b.constructor) return false
2754
- if (a[EqualityTraitSymbol]) return equals(a, b) // last resort: check equality (do this before array and obj check which don't implement the equality trait)
2755
- if (isArray$1(a)) {
2756
- return every$1(a, aitem =>
2757
- some(b, bitem => shapeExtends(aitem, bitem))
2758
- )
2759
- } else if (isObject$2(a)) {
2760
- return every(a, (aitem, akey) =>
2761
- shapeExtends(aitem, b[akey])
2762
- )
2763
- }
2764
- /* c8 ignore next */
2765
- return false
2766
- };
2767
-
2768
- /**
2769
- * @template T
2770
- * @implements {equalityTraits.EqualityTrait}
2771
- */
2772
- class Schema {
2773
- // this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore
2774
- /**
2775
- * If true, the more things are added to the shape the more objects this schema will accept (e.g.
2776
- * union). By default, the more objects are added, the the fewer objects this schema will accept.
2777
- * @protected
2778
- */
2779
- static _dilutes = false
2780
-
2781
- /**
2782
- * @param {Schema<any>} other
2783
- */
2784
- extends (other) {
2785
- let [a, b] = [/** @type {any} */(this).shape, /** @type {any} */ (other).shape];
2786
- if (/** @type {typeof Schema<any>} */ (this.constructor)._dilutes) [b, a] = [a, b];
2787
- return shapeExtends(a, b)
2788
- }
2789
-
2790
- /**
2791
- * Overwrite this when necessary. By default, we only check the `shape` property which every shape
2792
- * should have.
2793
- * @param {Schema<any>} other
2794
- */
2795
- equals (other) {
2796
- // @ts-ignore
2797
- return this.constructor === other.constructor && equalityDeep(this.shape, other.shape)
2798
- }
2799
-
2800
- [schemaSymbol] () { return true }
2801
-
2802
- /**
2803
- * @param {object} other
2804
- */
2805
- [EqualityTraitSymbol] (other) {
2806
- return this.equals(/** @type {any} */ (other))
2807
- }
2808
-
2809
- /**
2810
- * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of
2811
- * Schema. Validate will check the structure of the parameter and return true iff the instance
2812
- * really is an instance of Schema.
2813
- *
2814
- * @param {T} o
2815
- * @return {boolean}
2816
- */
2817
- validate (o) {
2818
- return this.check(o)
2819
- }
2820
-
2821
- /* c8 ignore start */
2822
- /**
2823
- * Similar to validate, but this method accepts untyped parameters.
2824
- *
2825
- * @param {any} _o
2826
- * @param {ValidationError} [_err]
2827
- * @return {_o is T}
2828
- */
2829
- check (_o, _err) {
2830
- methodUnimplemented();
2831
- }
2832
- /* c8 ignore stop */
2833
-
2834
- /**
2835
- * @type {Schema<T?>}
2836
- */
2837
- get nullable () {
2838
- // @ts-ignore
2839
- return $union(this, $null)
2840
- }
2841
-
2842
- /**
2843
- * @type {$Optional<Schema<T>>}
2844
- */
2845
- get optional () {
2846
- return new $Optional(/** @type {Schema<T>} */ (this))
2847
- }
2848
-
2849
- /**
2850
- * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise.
2851
- * Use this if you know that the type is of a specific type and you just want to convince the type
2852
- * system.
2853
- *
2854
- * **Do not rely on these error messages!**
2855
- * Performs an assertion check only if not in a production environment.
2856
- *
2857
- * @template OO
2858
- * @param {OO} o
2859
- * @return {Extract<OO, T> extends never ? T : (OO extends Array<never> ? T : Extract<OO,T>)}
2860
- */
2861
- cast (o) {
2862
- assert(o, this);
2863
- return /** @type {any} */ (o)
2864
- }
2865
-
2866
- /**
2867
- * EXPECTO PATRONUM!! 🪄
2868
- * This function protects against type errors. Though it may not work in the real world.
2869
- *
2870
- * "After all this time?"
2871
- * "Always." - Snape, talking about type safety
2872
- *
2873
- * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed.
2874
- * Use this if you know that the type is of a specific type and you just want to convince the type
2875
- * system.
2876
- *
2877
- * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)`
2878
- *
2879
- * **Do not rely on these error messages!**
2880
- * Performs an assertion check if not in a production environment.
2881
- *
2882
- * @param {T} o
2883
- * @return {o extends T ? T : never}
2884
- */
2885
- expect (o) {
2886
- assert(o, this);
2887
- return o
2888
- }
2889
- }
2890
-
2891
- /**
2892
- * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} Constr
2893
- * @typedef {Constr extends ((...args:any[]) => infer T) ? T : (Constr extends (new (...args:any[]) => any) ? InstanceType<Constr> : never)} Instance
2894
- */
2895
-
2896
- /**
2897
- * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} C
2898
- * @extends {Schema<Instance<C>>}
2899
- */
2900
- class $ConstructedBy extends Schema {
2901
- /**
2902
- * @param {C} c
2903
- * @param {((o:Instance<C>)=>boolean)|null} check
2904
- */
2905
- constructor (c, check) {
2906
- super();
2907
- this.shape = c;
2908
- this._c = check;
2909
- }
2910
-
2911
- /**
2912
- * @param {any} o
2913
- * @param {ValidationError} [err]
2914
- * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType<C> : never)} o
2915
- */
2916
- check (o, err = undefined) {
2917
- const c = o?.constructor === this.shape && (this._c == null || this._c(o));
2918
- /* c8 ignore next */
2919
- !c && err?.extend(null, this.shape.name, o?.constructor.name, o?.constructor !== this.shape ? 'Constructor match failed' : 'Check failed');
2920
- return c
2921
- }
2922
- }
2923
-
2924
- /**
2925
- * @template {(new (...args:any[]) => any) | ((...args:any[]) => any)} C
2926
- * @param {C} c
2927
- * @param {((o:Instance<C>) => boolean)|null} check
2928
- * @return {CastToSchema<$ConstructedBy<C>>}
2929
- */
2930
- const $constructedBy = (c, check = null) => new $ConstructedBy(c, check);
2931
- $constructedBy($ConstructedBy);
2932
-
2933
- /**
2934
- * Check custom properties on any object. You may want to overwrite the generated Schema<any>.
2935
- *
2936
- * @extends {Schema<any>}
2937
- */
2938
- class $Custom extends Schema {
2939
- /**
2940
- * @param {(o:any) => boolean} check
2941
- */
2942
- constructor (check) {
2943
- super();
2944
- /**
2945
- * @type {(o:any) => boolean}
2946
- */
2947
- this.shape = check;
2948
- }
2949
-
2950
- /**
2951
- * @param {any} o
2952
- * @param {ValidationError} err
2953
- * @return {o is any}
2954
- */
2955
- check (o, err) {
2956
- const c = this.shape(o);
2957
- /* c8 ignore next */
2958
- !c && err?.extend(null, 'custom prop', o?.constructor.name, 'failed to check custom prop');
2959
- return c
2960
- }
2961
- }
2962
-
2963
- /**
2964
- * @param {(o:any) => boolean} check
2965
- * @return {Schema<any>}
2966
- */
2967
- const $custom = (check) => new $Custom(check);
2968
- $constructedBy($Custom);
2969
-
2970
- /**
2971
- * @template {Primitive} T
2972
- * @extends {Schema<T>}
2973
- */
2974
- class $Literal extends Schema {
2975
- /**
2976
- * @param {Array<T>} literals
2977
- */
2978
- constructor (literals) {
2979
- super();
2980
- this.shape = literals;
2981
- }
2982
-
2983
- /**
2984
- *
2985
- * @param {any} o
2986
- * @param {ValidationError} [err]
2987
- * @return {o is T}
2988
- */
2989
- check (o, err) {
2990
- const c = this.shape.some(a => a === o);
2991
- /* c8 ignore next */
2992
- !c && err?.extend(null, this.shape.join(' | '), o.toString());
2993
- return c
2994
- }
2995
- }
2996
-
2997
- /**
2998
- * @template {Primitive[]} T
2999
- * @param {T} literals
3000
- * @return {CastToSchema<$Literal<T[number]>>}
3001
- */
3002
- const $literal = (...literals) => new $Literal(literals);
3003
- const $$literal = $constructedBy($Literal);
3004
-
3005
- /**
3006
- * @template {Array<string|Schema<string|number>>} Ts
3007
- * @typedef {Ts extends [] ? `` : (Ts extends [infer T] ? (Unwrap<T> extends (string|number) ? Unwrap<T> : never) : (Ts extends [infer T1, ...infer Rest] ? `${Unwrap<T1> extends (string|number) ? Unwrap<T1> : never}${Rest extends Array<string|Schema<string|number>> ? CastStringTemplateArgsToTemplate<Rest> : never}` : never))} CastStringTemplateArgsToTemplate
3008
- */
3009
-
3010
- /**
3011
- * @param {string} str
3012
- * @return {string}
3013
- */
3014
- const _regexEscape = /** @type {any} */ (RegExp).escape || /** @type {(str:string) => string} */ (str =>
3015
- str.replace(/[().|&,$^[\]]/g, s => '\\' + s)
3016
- );
3017
-
3018
- /**
3019
- * @param {string|Schema<any>} s
3020
- * @return {string[]}
3021
- */
3022
- const _schemaStringTemplateToRegex = s => {
3023
- if ($string.check(s)) {
3024
- return [_regexEscape(s)]
3025
- }
3026
- if ($$literal.check(s)) {
3027
- return /** @type {Array<string|number>} */ (s.shape).map(v => v + '')
3028
- }
3029
- if ($$number.check(s)) {
3030
- return ['[+-]?\\d+.?\\d*']
3031
- }
3032
- if ($$string.check(s)) {
3033
- return ['.*']
3034
- }
3035
- if ($$union.check(s)) {
3036
- return s.shape.map(_schemaStringTemplateToRegex).flat(1)
3037
- }
3038
- /* c8 ignore next 2 */
3039
- // unexpected schema structure (only supports unions and string in literal types)
3040
- unexpectedCase();
3041
- };
3042
-
3043
- /**
3044
- * @template {Array<string|Schema<string|number>>} T
3045
- * @extends {Schema<CastStringTemplateArgsToTemplate<T>>}
3046
- */
3047
- class $StringTemplate extends Schema {
3048
- /**
3049
- * @param {T} shape
3050
- */
3051
- constructor (shape) {
3052
- super();
3053
- this.shape = shape;
3054
- this._r = new RegExp('^' + shape.map(_schemaStringTemplateToRegex).map(opts => `(${opts.join('|')})`).join('') + '$');
3055
- }
3056
-
3057
- /**
3058
- * @param {any} o
3059
- * @param {ValidationError} [err]
3060
- * @return {o is CastStringTemplateArgsToTemplate<T>}
3061
- */
3062
- check (o, err) {
3063
- const c = this._r.exec(o) != null;
3064
- /* c8 ignore next */
3065
- !c && err?.extend(null, this._r.toString(), o.toString(), 'String doesn\'t match string template.');
3066
- return c
3067
- }
3068
- }
3069
- $constructedBy($StringTemplate);
3070
-
3071
- const isOptionalSymbol = Symbol('optional');
3072
- /**
3073
- * @template {Schema<any>} S
3074
- * @extends Schema<Unwrap<S>|undefined>
3075
- */
3076
- class $Optional extends Schema {
3077
- /**
3078
- * @param {S} shape
3079
- */
3080
- constructor (shape) {
3081
- super();
3082
- this.shape = shape;
3083
- }
3084
-
3085
- /**
3086
- * @param {any} o
3087
- * @param {ValidationError} [err]
3088
- * @return {o is (Unwrap<S>|undefined)}
3089
- */
3090
- check (o, err) {
3091
- const c = o === undefined || this.shape.check(o);
3092
- /* c8 ignore next */
3093
- !c && err?.extend(null, 'undefined (optional)', '()');
3094
- return c
3095
- }
3096
-
3097
- get [isOptionalSymbol] () { return true }
3098
- }
3099
- const $$optional = $constructedBy($Optional);
3100
-
3101
- /**
3102
- * @extends Schema<never>
3103
- */
3104
- class $Never extends Schema {
3105
- /**
3106
- * @param {any} _o
3107
- * @param {ValidationError} [err]
3108
- * @return {_o is never}
3109
- */
3110
- check (_o, err) {
3111
- /* c8 ignore next */
3112
- err?.extend(null, 'never', typeof _o);
3113
- return false
3114
- }
3115
- }
3116
- $constructedBy($Never);
3117
-
3118
- /**
3119
- * @template {{ [key: string|symbol|number]: Schema<any> }} S
3120
- * @typedef {{ [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? Key : never]?: S[Key] extends $Optional<Schema<infer Type>> ? Type : never } & { [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? never : Key]: S[Key] extends Schema<infer Type> ? Type : never }} $ObjectToType
3121
- */
3122
-
3123
- /**
3124
- * @template {{[key:string|symbol|number]: Schema<any>}} S
3125
- * @extends {Schema<$ObjectToType<S>>}
3126
- */
3127
- let $Object$3 = class $Object extends Schema {
3128
- /**
3129
- * @param {S} shape
3130
- * @param {boolean} partial
3131
- */
3132
- constructor (shape, partial = false) {
3133
- super();
3134
- /**
3135
- * @type {S}
3136
- */
3137
- this.shape = shape;
3138
- this._isPartial = partial;
3139
- }
3140
-
3141
- static _dilutes = true
3142
-
3143
- /**
3144
- * @type {Schema<Partial<$ObjectToType<S>>>}
3145
- */
3146
- get partial () {
3147
- return new $Object(this.shape, true)
3148
- }
3149
-
3150
- /**
3151
- * @param {any} o
3152
- * @param {ValidationError} err
3153
- * @return {o is $ObjectToType<S>}
3154
- */
3155
- check (o, err) {
3156
- if (o == null) {
3157
- /* c8 ignore next */
3158
- err?.extend(null, 'object', 'null');
3159
- return false
3160
- }
3161
- return every(this.shape, (vv, vk) => {
3162
- const c = (this._isPartial && !hasProperty(o, vk)) || vv.check(o[vk], err);
3163
- !c && err?.extend(vk.toString(), vv.toString(), typeof o[vk], 'Object property does not match');
3164
- return c
3165
- })
3166
- }
3167
- };
3168
-
3169
- /**
3170
- * @template S
3171
- * @typedef {Schema<{ [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? Key : never]?: S[Key] extends $Optional<Schema<infer Type>> ? Type : never } & { [Key in keyof S as S[Key] extends $Optional<Schema<any>> ? never : Key]: S[Key] extends Schema<infer Type> ? Type : never }>} _ObjectDefToSchema
3172
- */
3173
-
3174
- // I used an explicit type annotation instead of $ObjectToType, so that the user doesn't see the
3175
- // weird type definitions when inspecting type definions.
3176
- /**
3177
- * @template {{ [key:string|symbol|number]: Schema<any> }} S
3178
- * @param {S} def
3179
- * @return {_ObjectDefToSchema<S> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never}
3180
- */
3181
- const $object = def => /** @type {any} */ (new $Object$3(def));
3182
- const $$object = $constructedBy($Object$3);
3183
- /**
3184
- * @type {Schema<{[key:string]: any}>}
3185
- */
3186
- const $objectAny = $custom(o => o != null && (o.constructor === Object || o.constructor == null));
3187
-
3188
- /**
3189
- * @template {Schema<string|number|symbol>} Keys
3190
- * @template {Schema<any>} Values
3191
- * @extends {Schema<{ [key in Unwrap<Keys>]: Unwrap<Values> }>}
3192
- */
3193
- class $Record extends Schema {
3194
- /**
3195
- * @param {Keys} keys
3196
- * @param {Values} values
3197
- */
3198
- constructor (keys, values) {
3199
- super();
3200
- this.shape = {
3201
- keys, values
3202
- };
3203
- }
3204
-
3205
- /**
3206
- * @param {any} o
3207
- * @param {ValidationError} err
3208
- * @return {o is { [key in Unwrap<Keys>]: Unwrap<Values> }}
3209
- */
3210
- check (o, err) {
3211
- return o != null && every(o, (vv, vk) => {
3212
- const ck = this.shape.keys.check(vk, err);
3213
- /* c8 ignore next */
3214
- !ck && err?.extend(vk + '', 'Record', typeof o, ck ? 'Key doesn\'t match schema' : 'Value doesn\'t match value');
3215
- return ck && this.shape.values.check(vv, err)
3216
- })
3217
- }
3218
- }
3219
-
3220
- /**
3221
- * @template {Schema<string|number|symbol>} Keys
3222
- * @template {Schema<any>} Values
3223
- * @param {Keys} keys
3224
- * @param {Values} values
3225
- * @return {CastToSchema<$Record<Keys,Values>>}
3226
- */
3227
- const $record = (keys, values) => new $Record(keys, values);
3228
- const $$record = $constructedBy($Record);
3229
-
3230
- /**
3231
- * @template {Schema<any>[]} S
3232
- * @extends {Schema<{ [Key in keyof S]: S[Key] extends Schema<infer Type> ? Type : never }>}
3233
- */
3234
- class $Tuple extends Schema {
3235
- /**
3236
- * @param {S} shape
3237
- */
3238
- constructor (shape) {
3239
- super();
3240
- this.shape = shape;
3241
- }
3242
-
3243
- /**
3244
- * @param {any} o
3245
- * @param {ValidationError} err
3246
- * @return {o is { [K in keyof S]: S[K] extends Schema<infer Type> ? Type : never }}
3247
- */
3248
- check (o, err) {
3249
- return o != null && every(this.shape, (vv, vk) => {
3250
- const c = /** @type {Schema<any>} */ (vv).check(o[vk], err);
3251
- /* c8 ignore next */
3252
- !c && err?.extend(vk.toString(), 'Tuple', typeof vv);
3253
- return c
3254
- })
3255
- }
3256
- }
3257
-
3258
- /**
3259
- * @template {Array<Schema<any>>} T
3260
- * @param {T} def
3261
- * @return {CastToSchema<$Tuple<T>>}
3262
- */
3263
- const $tuple = (...def) => new $Tuple(def);
3264
- $constructedBy($Tuple);
3265
-
3266
- /**
3267
- * @template {Schema<any>} S
3268
- * @extends {Schema<Array<S extends Schema<infer T> ? T : never>>}
3269
- */
3270
- class $Array extends Schema {
3271
- /**
3272
- * @param {Array<S>} v
3273
- */
3274
- constructor (v) {
3275
- super();
3276
- /**
3277
- * @type {Schema<S extends Schema<infer T> ? T : never>}
3278
- */
3279
- this.shape = v.length === 1 ? v[0] : new $Union(v);
3280
- }
3281
-
3282
- /**
3283
- * @param {any} o
3284
- * @param {ValidationError} [err]
3285
- * @return {o is Array<S extends Schema<infer T> ? T : never>} o
3286
- */
3287
- check (o, err) {
3288
- const c = isArray$1(o) && every$1(o, oi => this.shape.check(oi));
3289
- /* c8 ignore next */
3290
- !c && err?.extend(null, 'Array', '');
3291
- return c
3292
- }
3293
- }
3294
-
3295
- /**
3296
- * @template {Array<Schema<any>>} T
3297
- * @param {T} def
3298
- * @return {Schema<Array<T extends Array<Schema<infer S>> ? S : never>>}
3299
- */
3300
- const $array = (...def) => new $Array(def);
3301
- const $$array = $constructedBy($Array);
3302
- /**
3303
- * @type {Schema<Array<any>>}
3304
- */
3305
- const $arrayAny = $custom(o => isArray$1(o));
3306
-
3307
- /**
3308
- * @template T
3309
- * @extends {Schema<T>}
3310
- */
3311
- class $InstanceOf extends Schema {
3312
- /**
3313
- * @param {new (...args:any) => T} constructor
3314
- * @param {((o:T) => boolean)|null} check
3315
- */
3316
- constructor (constructor, check) {
3317
- super();
3318
- this.shape = constructor;
3319
- this._c = check;
3320
- }
3321
-
3322
- /**
3323
- * @param {any} o
3324
- * @param {ValidationError} err
3325
- * @return {o is T}
3326
- */
3327
- check (o, err) {
3328
- const c = o instanceof this.shape && (this._c == null || this._c(o));
3329
- /* c8 ignore next */
3330
- !c && err?.extend(null, this.shape.name, o?.constructor.name);
3331
- return c
3332
- }
3333
- }
3334
-
3335
- /**
3336
- * @template T
3337
- * @param {new (...args:any) => T} c
3338
- * @param {((o:T) => boolean)|null} check
3339
- * @return {Schema<T>}
3340
- */
3341
- const $instanceOf = (c, check = null) => new $InstanceOf(c, check);
3342
- $constructedBy($InstanceOf);
3343
-
3344
- const $$schema = $instanceOf(Schema);
3345
-
3346
- /**
3347
- * @template {Schema<any>[]} Args
3348
- * @typedef {(...args:UnwrapArray<TuplePop<Args>>)=>Unwrap<TupleLast<Args>>} _LArgsToLambdaDef
3349
- */
3350
-
3351
- /**
3352
- * @template {Array<Schema<any>>} Args
3353
- * @extends {Schema<_LArgsToLambdaDef<Args>>}
3354
- */
3355
- class $Lambda extends Schema {
3356
- /**
3357
- * @param {Args} args
3358
- */
3359
- constructor (args) {
3360
- super();
3361
- this.len = args.length - 1;
3362
- this.args = $tuple(...args.slice(-1));
3363
- this.res = args[this.len];
3364
- }
3365
-
3366
- /**
3367
- * @param {any} f
3368
- * @param {ValidationError} err
3369
- * @return {f is _LArgsToLambdaDef<Args>}
3370
- */
3371
- check (f, err) {
3372
- const c = f.constructor === Function && f.length <= this.len;
3373
- /* c8 ignore next */
3374
- !c && err?.extend(null, 'function', typeof f);
3375
- return c
3376
- }
3377
- }
3378
- const $$lambda = $constructedBy($Lambda);
3379
-
3380
- /**
3381
- * @type {Schema<Function>}
3382
- */
3383
- const $function = $custom(o => typeof o === 'function');
3384
-
3385
- /**
3386
- * @template {Array<Schema<any>>} T
3387
- * @extends {Schema<Intersect<UnwrapArray<T>>>}
3388
- */
3389
- class $Intersection extends Schema {
3390
- /**
3391
- * @param {T} v
3392
- */
3393
- constructor (v) {
3394
- super();
3395
- /**
3396
- * @type {T}
3397
- */
3398
- this.shape = v;
3399
- }
3400
-
3401
- /**
3402
- * @param {any} o
3403
- * @param {ValidationError} [err]
3404
- * @return {o is Intersect<UnwrapArray<T>>}
3405
- */
3406
- check (o, err) {
3407
- // @ts-ignore
3408
- const c = every$1(this.shape, check => check.check(o, err));
3409
- /* c8 ignore next */
3410
- !c && err?.extend(null, 'Intersectinon', typeof o);
3411
- return c
3412
- }
3413
- }
3414
- $constructedBy($Intersection, o => o.shape.length > 0); // Intersection with length=0 is considered "any"
3415
-
3416
- /**
3417
- * @template S
3418
- * @extends {Schema<S>}
3419
- */
3420
- class $Union extends Schema {
3421
- static _dilutes = true
3422
-
3423
- /**
3424
- * @param {Array<Schema<S>>} v
3425
- */
3426
- constructor (v) {
3427
- super();
3428
- this.shape = v;
3429
- }
3430
-
3431
- /**
3432
- * @param {any} o
3433
- * @param {ValidationError} [err]
3434
- * @return {o is S}
3435
- */
3436
- check (o, err) {
3437
- const c = some(this.shape, (vv) => vv.check(o, err));
3438
- err?.extend(null, 'Union', typeof o);
3439
- return c
3440
- }
3441
- }
3442
-
3443
- /**
3444
- * @template {Array<any>} T
3445
- * @param {T} schemas
3446
- * @return {CastToSchema<$Union<Unwrap<ReadSchema<T>>>>}
3447
- */
3448
- const $union = (...schemas) => schemas.findIndex($s => $$union.check($s)) >= 0
3449
- ? $union(...schemas.map($s => $($s)).map($s => $$union.check($s) ? $s.shape : [$s]).flat(1))
3450
- : (schemas.length === 1
3451
- ? schemas[0]
3452
- : new $Union(schemas));
3453
- const $$union = /** @type {Schema<$Union<any>>} */ ($constructedBy($Union));
3454
-
3455
- const _t = () => true;
3456
- /**
3457
- * @type {Schema<any>}
3458
- */
3459
- const $any = $custom(_t);
3460
- const $$any = /** @type {Schema<Schema<any>>} */ ($constructedBy($Custom, o => o.shape === _t));
3461
-
3462
- /**
3463
- * @type {Schema<bigint>}
3464
- */
3465
- const $bigint = $custom(o => typeof o === 'bigint');
3466
- const $$bigint = /** @type {Schema<Schema<BigInt>>} */ ($custom(o => o === $bigint));
3467
-
3468
- /**
3469
- * @type {Schema<symbol>}
3470
- */
3471
- const $symbol = $custom(o => typeof o === 'symbol');
3472
- /** @type {Schema<Schema<Symbol>>} */ ($custom(o => o === $symbol));
3473
-
3474
- /**
3475
- * @type {Schema<number>}
3476
- */
3477
- const $number = $custom(o => typeof o === 'number');
3478
- const $$number = /** @type {Schema<Schema<number>>} */ ($custom(o => o === $number));
3479
-
3480
- /**
3481
- * @type {Schema<string>}
3482
- */
3483
- const $string = $custom(o => typeof o === 'string');
3484
- const $$string = /** @type {Schema<Schema<string>>} */ ($custom(o => o === $string));
3485
-
3486
- /**
3487
- * @type {Schema<boolean>}
3488
- */
3489
- const $boolean = $custom(o => typeof o === 'boolean');
3490
- const $$boolean = /** @type {Schema<Schema<Boolean>>} */ ($custom(o => o === $boolean));
3491
-
3492
- /**
3493
- * @type {Schema<undefined>}
3494
- */
3495
- const $undefined = $literal(undefined);
3496
- /** @type {Schema<Schema<undefined>>} */ ($constructedBy($Literal, o => o.shape.length === 1 && o.shape[0] === undefined));
3497
-
3498
- /**
3499
- * @type {Schema<void>}
3500
- */
3501
- $literal(undefined);
3502
-
3503
- const $null = $literal(null);
3504
- const $$null = /** @type {Schema<Schema<null>>} */ ($constructedBy($Literal, o => o.shape.length === 1 && o.shape[0] === null));
3505
-
3506
- $constructedBy(Uint8Array);
3507
- /** @type {Schema<Schema<Uint8Array>>} */ ($constructedBy($ConstructedBy, o => o.shape === Uint8Array));
3508
-
3509
- /**
3510
- * @type {Schema<Primitive>}
3511
- */
3512
- const $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol);
3513
-
3514
- /**
3515
- * @typedef {JSON[]} JSONArray
3516
- */
3517
- /**
3518
- * @typedef {Primitive|JSONArray|{ [key:string]:JSON }} JSON
3519
- */
3520
- /**
3521
- * @type {Schema<null|number|string|boolean|JSON[]|{[key:string]:JSON}>}
3522
- */
3523
- (() => {
3524
- const $jsonArr = /** @type {$Array<$any>} */ ($array($any));
3525
- const $jsonRecord = /** @type {$Record<$string,$any>} */ ($record($string, $any));
3526
- const $json = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord);
3527
- $jsonArr.shape = $json;
3528
- $jsonRecord.shape.values = $json;
3529
- return $json
3530
- })();
3531
-
3532
- /**
3533
- * @template {any} IN
3534
- * @typedef {IN extends Schema<any> ? IN
3535
- * : (IN extends string|number|boolean|null ? Schema<IN>
3536
- * : (IN extends new (...args:any[])=>any ? Schema<InstanceType<IN>>
3537
- * : (IN extends any[] ? Schema<{ [K in keyof IN]: Unwrap<ReadSchema<IN[K]>> }[number]>
3538
- * : (IN extends object ? (_ObjectDefToSchema<{[K in keyof IN]:ReadSchema<IN[K]>}> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never)
3539
- * : never)
3540
- * )
3541
- * )
3542
- * )
3543
- * } ReadSchemaOld
3544
- */
3545
-
3546
- /**
3547
- * @template {any} IN
3548
- * @typedef {[Extract<IN,Schema<any>>,Extract<IN,string|number|boolean|null>,Extract<IN,new (...args:any[])=>any>,Extract<IN,any[]>,Extract<Exclude<IN,Schema<any>|string|number|boolean|null|(new (...args:any[])=>any)|any[]>,object>] extends [infer Schemas, infer Primitives, infer Constructors, infer Arrs, infer Obj]
3549
- * ? Schema<
3550
- * (Schemas extends Schema<infer S> ? S : never)
3551
- * | Primitives
3552
- * | (Constructors extends new (...args:any[])=>any ? InstanceType<Constructors> : never)
3553
- * | (Arrs extends any[] ? { [K in keyof Arrs]: Unwrap<ReadSchema<Arrs[K]>> }[number] : never)
3554
- * | (Obj extends object ? Unwrap<(_ObjectDefToSchema<{[K in keyof Obj]:ReadSchema<Obj[K]>}> extends Schema<infer S> ? Schema<{ [K in keyof S]: S[K] }> : never)> : never)>
3555
- * : never
3556
- * } ReadSchema
3557
- */
3558
-
3559
- /**
3560
- * @typedef {ReadSchema<{x:42}|{y:99}|Schema<string>|[1,2,{}]>} Q
3561
- */
3562
-
3563
- /**
3564
- * @template IN
3565
- * @param {IN} o
3566
- * @return {ReadSchema<IN>}
3567
- */
3568
- const $ = o => {
3569
- if ($$schema.check(o)) {
3570
- return /** @type {any} */ (o)
3571
- } else if ($objectAny.check(o)) {
3572
- /**
3573
- * @type {any}
3574
- */
3575
- const o2 = {};
3576
- for (const k in o) {
3577
- o2[k] = $(o[k]);
3578
- }
3579
- return /** @type {any} */ ($object(o2))
3580
- } else if ($arrayAny.check(o)) {
3581
- return /** @type {any} */ ($union(...o.map($)))
3582
- } else if ($primitive.check(o)) {
3583
- return /** @type {any} */ ($literal(o))
3584
- } else if ($function.check(o)) {
3585
- return /** @type {any} */ ($constructedBy(/** @type {any} */ (o)))
3586
- }
3587
- /* c8 ignore next */
3588
- unexpectedCase();
3589
- };
3590
-
3591
- /* c8 ignore start */
3592
- /**
3593
- * Assert that a variable is of this specific type.
3594
- * The assertion check is only performed in non-production environments.
3595
- *
3596
- * @type {<T>(o:any,schema:Schema<T>) => asserts o is T}
3597
- */
3598
- const assert = production
3599
- ? () => {}
3600
- : (o, schema) => {
3601
- const err = new ValidationError();
3602
- if (!schema.check(o, err)) {
3603
- throw create$3(`Expected value to be of type ${schema.constructor.name}.\n${err.toString()}`)
3604
- }
3605
- };
3606
- /* c8 ignore end */
3607
-
3608
- /**
3609
- * @template In
3610
- * @template Out
3611
- * @typedef {{ if: Schema<In>, h: (o:In,state?:any)=>Out }} Pattern
3612
- */
3613
-
3614
- /**
3615
- * @template {Pattern<any,any>} P
3616
- * @template In
3617
- * @typedef {ReturnType<Extract<P,Pattern<In extends number ? number : (In extends string ? string : In),any>>['h']>} PatternMatchResult
3618
- */
3619
-
3620
- /**
3621
- * @todo move this to separate library
3622
- * @template {any} [State=undefined]
3623
- * @template {Pattern<any,any>} [Patterns=never]
3624
- */
3625
- class PatternMatcher {
3626
- /**
3627
- * @param {Schema<State>} [$state]
3628
- */
3629
- constructor ($state) {
3630
- /**
3631
- * @type {Array<Patterns>}
3632
- */
3633
- this.patterns = [];
3634
- this.$state = $state;
3635
- }
3636
-
3637
- /**
3638
- * @template P
3639
- * @template R
3640
- * @param {P} pattern
3641
- * @param {(o:NoInfer<Unwrap<ReadSchema<P>>>,s:State)=>R} handler
3642
- * @return {PatternMatcher<State,Patterns|Pattern<Unwrap<ReadSchema<P>>,R>>}
3643
- */
3644
- if (pattern, handler) {
3645
- // @ts-ignore
3646
- this.patterns.push({ if: $(pattern), h: handler });
3647
- // @ts-ignore
3648
- return this
3649
- }
3650
-
3651
- /**
3652
- * @template R
3653
- * @param {(o:any,s:State)=>R} h
3654
- */
3655
- else (h) {
3656
- return this.if($any, h)
3657
- }
3658
-
3659
- /**
3660
- * @return {State extends undefined
3661
- * ? <In extends Unwrap<Patterns['if']>>(o:In,state?:undefined)=>PatternMatchResult<Patterns,In>
3662
- * : <In extends Unwrap<Patterns['if']>>(o:In,state:State)=>PatternMatchResult<Patterns,In>}
3663
- */
3664
- done () {
3665
- // @ts-ignore
3666
- return /** @type {any} */ (o, s) => {
3667
- for (let i = 0; i < this.patterns.length; i++) {
3668
- const p = this.patterns[i];
3669
- if (p.if.check(o)) {
3670
- // @ts-ignore
3671
- return p.h(o, s)
3672
- }
3673
- }
3674
- throw create$3('Unhandled pattern')
3675
- }
3676
- }
3677
- }
3678
-
3679
- /**
3680
- * @template [State=undefined]
3681
- * @param {State} [state]
3682
- * @return {PatternMatcher<State extends undefined ? undefined : Unwrap<ReadSchema<State>>>}
3683
- */
3684
- const match = state => new PatternMatcher(/** @type {any} */ (state));
3685
-
3686
- /**
3687
- * Helper function to generate a (non-exhaustive) sample set from a gives schema.
3688
- *
3689
- * @type {<T>(o:T,gen:prng.PRNG)=>T}
3690
- */
3691
- const _random = /** @type {any} */ (match(/** @type {Schema<prng.PRNG>} */ ($any))
3692
- .if($$number, (_o, gen) => int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER))
3693
- .if($$string, (_o, gen) => word(gen))
3694
- .if($$boolean, (_o, gen) => bool(gen))
3695
- .if($$bigint, (_o, gen) => BigInt(int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)))
3696
- .if($$union, (o, gen) => random(gen, oneOf(gen, o.shape)))
3697
- .if($$object, (o, gen) => {
3698
- /**
3699
- * @type {any}
3700
- */
3701
- const res = {};
3702
- for (const k in o.shape) {
3703
- let prop = o.shape[k];
3704
- if ($$optional.check(prop)) {
3705
- if (bool(gen)) { continue }
3706
- prop = prop.shape;
3707
- }
3708
- res[k] = _random(prop, gen);
3709
- }
3710
- return res
3711
- })
3712
- .if($$array, (o, gen) => {
3713
- const arr = [];
3714
- const n = int32(gen, 0, 42);
3715
- for (let i = 0; i < n; i++) {
3716
- arr.push(random(gen, o.shape));
3717
- }
3718
- return arr
3719
- })
3720
- .if($$literal, (o, gen) => {
3721
- return oneOf(gen, o.shape)
3722
- })
3723
- .if($$null, (o, gen) => {
3724
- return null
3725
- })
3726
- .if($$lambda, (o, gen) => {
3727
- const res = random(gen, o.res);
3728
- return () => res
3729
- })
3730
- .if($$any, (o, gen) => random(gen, oneOf(gen, [
3731
- $number, $string, $null, $undefined, $bigint, $boolean,
3732
- $array($number),
3733
- $record($union('a', 'b', 'c'), $number)
3734
- ])))
3735
- .if($$record, (o, gen) => {
3736
- /**
3737
- * @type {any}
3738
- */
3739
- const res = {};
3740
- const keysN = int53(gen, 0, 3);
3741
- for (let i = 0; i < keysN; i++) {
3742
- const key = random(gen, o.shape.keys);
3743
- const val = random(gen, o.shape.values);
3744
- res[key] = val;
3745
- }
3746
- return res
3747
- })
3748
- .done());
2322
+ );
2323
+ /* c8 ignore stop */
3749
2324
 
3750
2325
  /**
3751
- * @template S
3752
- * @param {prng.PRNG} gen
3753
- * @param {S} schema
3754
- * @return {Unwrap<ReadSchema<S>>}
2326
+ * Utility functions to work with buffers (Uint8Array).
2327
+ *
2328
+ * @module buffer
3755
2329
  */
3756
- const random = (gen, schema) => /** @type {any} */ (_random($(schema), gen));
3757
-
3758
- /* eslint-env browser */
3759
2330
 
3760
2331
 
3761
- /* c8 ignore start */
3762
2332
  /**
3763
- * @type {Document}
2333
+ * @param {number} len
3764
2334
  */
3765
- const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {});
2335
+ const createUint8ArrayFromLen = len => new Uint8Array(len);
3766
2336
 
3767
2337
  /**
3768
- * @type {$.Schema<DocumentFragment>}
2338
+ * Copy the content of an Uint8Array view to a new ArrayBuffer.
2339
+ *
2340
+ * @param {Uint8Array} uint8Array
2341
+ * @return {Uint8Array}
3769
2342
  */
3770
- $custom(el => el.nodeType === DOCUMENT_FRAGMENT_NODE);
3771
-
3772
- /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null);
2343
+ const copyUint8Array = uint8Array => {
2344
+ const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
2345
+ newBuf.set(uint8Array);
2346
+ return newBuf
2347
+ };
3773
2348
 
3774
2349
  /**
3775
- * @type {$.Schema<Element>}
2350
+ * Working with value pairs.
2351
+ *
2352
+ * @module pair
3776
2353
  */
3777
- $custom(el => el.nodeType === ELEMENT_NODE);
3778
2354
 
3779
2355
  /**
3780
- * @type {$.Schema<Text>}
2356
+ * @template L,R
3781
2357
  */
3782
- $custom(el => el.nodeType === TEXT_NODE);
2358
+ class Pair {
2359
+ /**
2360
+ * @param {L} left
2361
+ * @param {R} right
2362
+ */
2363
+ constructor (left, right) {
2364
+ this.left = left;
2365
+ this.right = right;
2366
+ }
2367
+ }
3783
2368
 
3784
2369
  /**
3785
- * @param {Map<string,string>} m
3786
- * @return {string}
2370
+ * @template L,R
2371
+ * @param {L} left
2372
+ * @param {R} right
2373
+ * @return {Pair<L,R>}
3787
2374
  */
3788
- const mapToStyleString = m => map(m, (value, key) => `${key}:${value};`).join('');
2375
+ const create$1 = (left, right) => new Pair(left, right);
2376
+
2377
+ /* eslint-env browser */
2378
+
3789
2379
 
3790
- const ELEMENT_NODE = doc.ELEMENT_NODE;
3791
- const TEXT_NODE = doc.TEXT_NODE;
3792
- const DOCUMENT_NODE = doc.DOCUMENT_NODE;
3793
- const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE;
2380
+ /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null);
3794
2381
 
3795
2382
  /**
3796
- * @type {$.Schema<Node>}
2383
+ * @param {Map<string,string>} m
2384
+ * @return {string}
3797
2385
  */
3798
- $custom(el => el.nodeType === DOCUMENT_NODE);
2386
+ const mapToStyleString = m => map(m, (value, key) => `${key}:${value};`).join('');
3799
2387
  /* c8 ignore stop */
3800
2388
 
3801
2389
  /**
@@ -6458,21 +5046,17 @@ const cleanupTransactions = (transactionCleanups, i) => {
6458
5046
  // sort events by path length so that top-level events are fired first.
6459
5047
  events
6460
5048
  .sort((event1, event2) => event1.path.length - event2.path.length);
6461
- fs.push(() => {
6462
- // We don't need to check for events.length
6463
- // because we know it has at least one element
6464
- callEventHandlerListeners(type._dEH, events, transaction);
6465
- });
6466
- }
6467
- });
6468
- fs.push(() => doc.emit('afterTransaction', [transaction, doc]));
6469
- fs.push(() => {
6470
- if (transaction._needFormattingCleanup) {
6471
- cleanupYTextAfterTransaction(transaction);
5049
+ // We don't need to check for events.length
5050
+ // because we know it has at least one element
5051
+ callEventHandlerListeners(type._dEH, events, transaction);
6472
5052
  }
6473
5053
  });
6474
5054
  });
5055
+ fs.push(() => doc.emit('afterTransaction', [transaction, doc]));
6475
5056
  callAll(fs, []);
5057
+ if (transaction._needFormattingCleanup) {
5058
+ cleanupYTextAfterTransaction(transaction);
5059
+ }
6476
5060
  } finally {
6477
5061
  // Replace deleted items with ItemDeleted / GC.
6478
5062
  // This is where content is actually remove from the Yjs Doc.
@@ -7034,7 +5618,7 @@ class YEvent {
7034
5618
  */
7035
5619
  this._changes = null;
7036
5620
  /**
7037
- * @type {null | Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>}
5621
+ * @type {null | Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
7038
5622
  */
7039
5623
  this._keys = null;
7040
5624
  /**
@@ -7077,7 +5661,7 @@ class YEvent {
7077
5661
  }
7078
5662
 
7079
5663
  /**
7080
- * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>}
5664
+ * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
7081
5665
  */
7082
5666
  get keys () {
7083
5667
  if (this._keys === null) {
@@ -9354,7 +7938,7 @@ class YTextEvent extends YEvent {
9354
7938
  if (retain > 0) {
9355
7939
  op = { retain };
9356
7940
  if (!isEmpty(attributes)) {
9357
- op.attributes = assign({}, attributes);
7941
+ op.attributes = assign$1({}, attributes);
9358
7942
  }
9359
7943
  }
9360
7944
  retain = 0;
@@ -10452,10 +9036,12 @@ class YXmlElement extends YXmlFragment {
10452
9036
  const el = new YXmlElement(this.nodeName);
10453
9037
  const attrs = this.getAttributes();
10454
9038
  forEach$2(attrs, (value, key) => {
10455
- el.setAttribute(key, /** @type {any} */ (value));
9039
+ if (typeof value === 'string') {
9040
+ el.setAttribute(key, value);
9041
+ }
10456
9042
  });
10457
9043
  // @ts-ignore
10458
- el.insert(0, this.toArray().map(v => v instanceof AbstractType ? v.clone() : v));
9044
+ el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item));
10459
9045
  return el
10460
9046
  }
10461
9047
 
@@ -12727,448 +11313,124 @@ class KokimokiAiService {
12727
11313
  this.client = client;
12728
11314
  }
12729
11315
  /**
12730
- * Generate a chat response from the AI model.
12731
- *
12732
- * Sends a chat request to the AI service and returns the generated response.
12733
- * Supports multiple AI models including GPT and Gemini variants with configurable
12734
- * parameters for fine-tuning the response behavior.
12735
- *
12736
- * @param req The chat request parameters.
12737
- * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
12738
- * Available models:
12739
- * - `gpt-4o`: OpenAI GPT-4 Optimized
12740
- * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
12741
- * - `gpt-5`: OpenAI GPT-5 (latest)
12742
- * - `gpt-5-mini`: Smaller GPT-5 variant
12743
- * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
12744
- * - `gemini-2.5-flash-lite`: Google Gemini lite variant
12745
- * - `gemini-2.5-flash`: Google Gemini fast variant
12746
- * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
12747
- * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
12748
- * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
12749
- * This helps define the AI's role, personality, and constraints.
12750
- * @param req.userPrompt The user's message or question to send to the AI.
12751
- * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
12752
- * Lower values make output more focused and deterministic,
12753
- * higher values make it more creative and varied.
12754
- * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
12755
- * Controls the length of the AI's output.
12756
- * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
12757
- * Allows the AI to analyze and respond based on the provided images.
12758
- *
12759
- * @returns A promise that resolves to an object containing the AI-generated response.
12760
- * @returns {string} content The text content of the AI's response.
12761
- *
12762
- * @throws An error object if the API request fails.
12763
- *
12764
- * @example
12765
- * ```typescript
12766
- * const response = await client.ai.chat({
12767
- * model: "gpt-4o",
12768
- * systemPrompt: "You are a helpful coding assistant.",
12769
- * userPrompt: "Explain what TypeScript is in one sentence.",
12770
- * temperature: 0.7,
12771
- * maxTokens: 100
12772
- * });
12773
- * console.log(response.content);
12774
- * ```
12775
- */
12776
- async chat(req) {
12777
- const res = await fetch(`${this.client.apiUrl}/ai/chat`, {
12778
- method: "POST",
12779
- headers: this.client.apiHeaders,
12780
- body: JSON.stringify(req),
12781
- });
12782
- if (!res.ok) {
12783
- throw await res.json();
12784
- }
12785
- return await res.json();
12786
- }
12787
- /**
12788
- * Generate structured JSON output from the AI model.
12789
- *
12790
- * Sends a chat request to the AI service with the expectation of receiving
12791
- * a JSON-formatted response. This is useful for scenarios where the output
12792
- * needs to be parsed or processed programmatically.
12793
- *
12794
- * **Important:** Your prompt must include the word "json" and should describe
12795
- * the expected output schema (field names, types, and structure) to ensure
12796
- * the AI generates properly formatted responses.
12797
- *
12798
- * @param req The chat request parameters.
12799
- * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
12800
- * Available models:
12801
- * - `gpt-4o`: OpenAI GPT-4 Optimized
12802
- * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
12803
- * - `gpt-5`: OpenAI GPT-5 (latest)
12804
- * - `gpt-5-mini`: Smaller GPT-5 variant
12805
- * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
12806
- * - `gemini-2.5-flash-lite`: Google Gemini lite variant
12807
- * - `gemini-2.5-flash`: Google Gemini fast variant
12808
- * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
12809
- * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
12810
- * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
12811
- * This helps define the AI's role, personality, and constraints.
12812
- * @param req.userPrompt The user's message or question to send to the AI.
12813
- * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
12814
- * Lower values make output more focused and deterministic,
12815
- * higher values make it more creative and varied.
12816
- * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
12817
- * Controls the length of the AI's output.
12818
- * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
12819
- * Allows the AI to analyze images and generate structured JSON based on them.
12820
- *
12821
- * @returns A promise that resolves to the parsed JSON object generated by the AI.
12822
- *
12823
- * @throws An error object if the API request fails or if the response is not valid JSON.
12824
- */
12825
- async generateJson(req) {
12826
- const { content } = await this.chat({
12827
- ...req,
12828
- responseMimeType: "application/json",
12829
- });
12830
- return JSON.parse(content);
12831
- }
12832
- /**
12833
- * Modify an image using the AI service.
12834
- * @param baseImageUrl The URL of the base image to modify.
12835
- * @param prompt The modification prompt to apply to the image.
12836
- * @param tags Optional. Tags to associate with the image.
12837
- * @returns A promise that resolves to the modified image upload information.
12838
- */
12839
- async modifyImage(baseImageUrl, prompt, tags = [], model = 'gemini-2.5-flash-image') {
12840
- const res = await fetch(`${this.client.apiUrl}/ai/modify-image`, {
12841
- method: "POST",
12842
- headers: this.client.apiHeaders,
12843
- body: JSON.stringify({ baseImageUrl, prompt, tags, model }),
12844
- });
12845
- if (!res.ok) {
12846
- throw await res.json();
12847
- }
12848
- return await res.json();
12849
- }
12850
- }
12851
-
12852
- let _kmEnv;
12853
- /**
12854
- * Parses and returns the Kokimoki environment configuration.
12855
- *
12856
- * The environment is injected into the HTML by @kokimoki/kit as a JSON script tag
12857
- * with id `kokimoki-env`. In production, placeholder values are replaced by the server.
12858
- *
12859
- * @returns The parsed KokimokiEnv object
12860
- * @throws Error if the kokimoki-env element is not found
12861
- *
12862
- * @example
12863
- * ```typescript
12864
- * import { getKmEnv } from '@kokimoki/app';
12865
- *
12866
- * const env = getKmEnv();
12867
- * console.log(env.dev); // true in development
12868
- * console.log(env.assets); // CDN URL in production
12869
- *
12870
- * // Cast i18n to your app's type if needed
12871
- * const i18n = env.i18n as typeof i18nResources;
12872
- * ```
12873
- */
12874
- function getKmEnv() {
12875
- if (_kmEnv) {
12876
- return _kmEnv;
12877
- }
12878
- const element = document.getElementById("kokimoki-env");
12879
- if (!element) {
12880
- throw new Error("kokimoki-env element not found. Ensure the app is built with @kokimoki/kit.");
12881
- }
12882
- _kmEnv = JSON.parse(element.textContent);
12883
- return _kmEnv;
12884
- }
12885
-
12886
- /**
12887
- * Kokimoki i18n Service
12888
- *
12889
- * Provides translation loading via HTTP backend. Both development and production
12890
- * use HTTP to load translations consistently.
12891
- *
12892
- * In development, translations are served by @kokimoki/kit's dev server middleware.
12893
- * In production, translations are served from the assets CDN.
12894
- *
12895
- * **Key Features:**
12896
- * - Pre-configured i18next instance creation
12897
- * - Consistent HTTP-based loading in dev and prod
12898
- * - URL resolution for translation namespaces
12899
- * - AI-powered translation requests
12900
- *
12901
- * Access via `kmClient.i18n`
12902
- *
12903
- * @example
12904
- * ```typescript
12905
- * // Setup with React
12906
- * import { initReactI18next } from 'react-i18next';
12907
- *
12908
- * export const i18n = kmClient.i18n.createI18n({
12909
- * use: [initReactI18next]
12910
- * });
12911
- *
12912
- * // Initialize with primary language
12913
- * await kmClient.i18n.init('en');
12914
- *
12915
- * // Request AI translation for another language
12916
- * const result = await kmClient.i18n.requestTranslation('de');
12917
- * // Then poll getTranslationStatus('de') until available
12918
- * ```
12919
- */
12920
- class KokimokiI18nService {
12921
- client;
12922
- initPromise = null;
12923
- instance = null;
12924
- options = {};
12925
- constructor(client) {
12926
- this.client = client;
12927
- }
12928
- /**
12929
- * Create and configure an i18next instance.
12930
- *
12931
- * This sets up the instance with plugins but does NOT initialize it.
12932
- * Call `init(lng)` to initialize with a specific language.
12933
- *
12934
- * @param options - Configuration options (plugins, fallback, defaultNS)
12935
- * @returns Configured i18next instance (not yet initialized)
12936
- *
12937
- * @example
12938
- * ```typescript
12939
- * // With React
12940
- * import { initReactI18next } from 'react-i18next';
12941
- *
12942
- * export const i18n = kmClient.i18n.createI18n({
12943
- * use: [initReactI18next]
12944
- * });
12945
- *
12946
- * // Later, when you know the language:
12947
- * await kmClient.i18n.init('en');
12948
- *
12949
- * // Then in components:
12950
- * const { t } = useTranslation('game');
12951
- * ```
12952
- */
12953
- createI18n(options) {
12954
- const env = getKmEnv();
12955
- const namespaces = env.i18nNamespaces ?? [];
12956
- if (namespaces.length === 0) {
12957
- console.warn("[KokimokiI18n] No i18n namespaces found. Make sure i18n is configured in @kokimoki/kit plugin.");
12958
- }
12959
- this.options = options ?? {};
12960
- this.instance = i18next.createInstance();
12961
- // Apply plugins
12962
- if (options?.use) {
12963
- for (const plugin of options.use) {
12964
- this.instance.use(plugin);
12965
- }
12966
- }
12967
- // Add HTTP backend
12968
- this.instance.use(HttpBackend);
12969
- return this.instance;
12970
- }
12971
- /**
12972
- * Initialize the i18next instance with a specific language.
12973
- *
12974
- * Must call `createI18n()` first to set up the instance.
12975
- *
12976
- * @param lng - The language code to initialize with (e.g., 'en', 'de')
12977
- * @returns Promise that resolves when i18n is ready
12978
- *
12979
- * @example
12980
- * ```typescript
12981
- * // Create instance first
12982
- * const i18n = kmClient.i18n.createI18n({ use: [initReactI18next] });
12983
- *
12984
- * // Then initialize when you know the language
12985
- * await kmClient.i18n.init('en');
12986
- * ```
12987
- */
12988
- async init(lng) {
12989
- if (!this.instance) {
12990
- throw new Error("Call createI18n() before init()");
12991
- }
12992
- if (this.initPromise) {
12993
- return this.initPromise;
12994
- }
12995
- const env = getKmEnv();
12996
- const namespaces = env.i18nNamespaces ?? [];
12997
- const fallbackLng = this.options.fallbackLng ?? lng;
12998
- const defaultNS = this.options.defaultNS;
12999
- this.initPromise = this.instance.init({
13000
- lng,
13001
- fallbackLng,
13002
- ns: namespaces,
13003
- defaultNS,
13004
- backend: {
13005
- loadPath: (lng, ns) => this.getNamespaceUrl(lng, ns),
13006
- },
13007
- interpolation: {
13008
- escapeValue: false,
13009
- },
13010
- });
13011
- return this.initPromise;
13012
- }
13013
- /**
13014
- * Get the URL for a translation namespace.
13015
- *
13016
- * Returns the appropriate URL based on environment:
13017
- * - Development: `/__kokimoki/i18n/{lng}/{ns}.json`
13018
- * - Production: `{assets}/km-i18n/{lng}/{ns}.json`
13019
- *
13020
- * @param lng - Language code (e.g., 'en', 'et', 'de')
13021
- * @param ns - Namespace (e.g., 'ui', 'game', 'setup')
13022
- * @returns Full URL to the translation JSON file
13023
- *
13024
- * @example
13025
- * ```typescript
13026
- * const url = kmClient.i18n.getNamespaceUrl('en', 'game');
13027
- * // Dev: "/__kokimoki/i18n/en/game.json"
13028
- * // Prod: "https://cdn.kokimoki.com/build-123/km-i18n/en/game.json"
13029
- * ```
13030
- */
13031
- getNamespaceUrl(lng, ns) {
13032
- const env = getKmEnv();
13033
- if (env.dev) {
13034
- // Development: use kit plugin's middleware
13035
- return `/__kokimoki/i18n/${lng}/${ns}.json`;
13036
- }
13037
- // Production: use assets CDN with configured i18n path
13038
- const i18nPath = env.i18nPath ?? 'km-i18n';
13039
- return `${env.assets}/${i18nPath}/${lng}/${ns}.json`;
13040
- }
13041
- /**
13042
- * Get the list of available namespaces.
13043
- *
13044
- * @returns Array of namespace names configured in @kokimoki/kit
13045
- */
13046
- getNamespaces() {
13047
- return getKmEnv().i18nNamespaces ?? [];
13048
- }
13049
- /**
13050
- * Get the list of available languages.
11316
+ * Generate a chat response from the AI model.
13051
11317
  *
13052
- * @returns Array of language codes configured in @kokimoki/kit
13053
- */
13054
- getLanguages() {
13055
- return getKmEnv().i18nLanguages ?? [];
13056
- }
13057
- /**
13058
- * Get the status of all languages that have been requested for AI translation.
11318
+ * Sends a chat request to the AI service and returns the generated response.
11319
+ * Supports multiple AI models including GPT and Gemini variants with configurable
11320
+ * parameters for fine-tuning the response behavior.
11321
+ *
11322
+ * @param req The chat request parameters.
11323
+ * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
11324
+ * Available models:
11325
+ * - `gpt-4o`: OpenAI GPT-4 Optimized
11326
+ * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
11327
+ * - `gpt-5`: OpenAI GPT-5 (latest)
11328
+ * - `gpt-5-mini`: Smaller GPT-5 variant
11329
+ * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
11330
+ * - `gemini-2.5-flash-lite`: Google Gemini lite variant
11331
+ * - `gemini-2.5-flash`: Google Gemini fast variant
11332
+ * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
11333
+ * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
11334
+ * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
11335
+ * This helps define the AI's role, personality, and constraints.
11336
+ * @param req.userPrompt The user's message or question to send to the AI.
11337
+ * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
11338
+ * Lower values make output more focused and deterministic,
11339
+ * higher values make it more creative and varied.
11340
+ * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
11341
+ * Controls the length of the AI's output.
11342
+ * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
11343
+ * Allows the AI to analyze and respond based on the provided images.
13059
11344
  *
13060
- * Only available in production. In development, returns an empty array.
11345
+ * @returns A promise that resolves to an object containing the AI-generated response.
11346
+ * @returns {string} content The text content of the AI's response.
13061
11347
  *
13062
- * @returns Promise with array of language statuses
11348
+ * @throws An error object if the API request fails.
13063
11349
  *
13064
11350
  * @example
13065
11351
  * ```typescript
13066
- * const { languages } = await kmClient.i18n.getAllLanguagesStatus();
13067
- * // [{ lng: 'de', status: 'available' }, { lng: 'fr', status: 'processing' }]
11352
+ * const response = await client.ai.chat({
11353
+ * model: "gpt-4o",
11354
+ * systemPrompt: "You are a helpful coding assistant.",
11355
+ * userPrompt: "Explain what TypeScript is in one sentence.",
11356
+ * temperature: 0.7,
11357
+ * maxTokens: 100
11358
+ * });
11359
+ * console.log(response.content);
13068
11360
  * ```
13069
11361
  */
13070
- async getAllLanguagesStatus() {
13071
- const env = getKmEnv();
13072
- if (env.dev) {
13073
- return { languages: [] };
13074
- }
13075
- const res = await fetch(`${this.client.apiUrl}/i18n`, {
13076
- method: "GET",
11362
+ async chat(req) {
11363
+ const res = await fetch(`${this.client.apiUrl}/ai/chat`, {
11364
+ method: "POST",
13077
11365
  headers: this.client.apiHeaders,
11366
+ body: JSON.stringify(req),
13078
11367
  });
11368
+ if (!res.ok) {
11369
+ throw await res.json();
11370
+ }
13079
11371
  return await res.json();
13080
11372
  }
13081
11373
  /**
13082
- * Get the translation status for a specific language.
11374
+ * Generate structured JSON output from the AI model.
13083
11375
  *
13084
- * Returns the overall status and per-namespace status for the given language.
13085
- * In development, returns 'available' for local languages and 'not_available' for others.
13086
- * In production, queries the API for the actual status.
11376
+ * Sends a chat request to the AI service with the expectation of receiving
11377
+ * a JSON-formatted response. This is useful for scenarios where the output
11378
+ * needs to be parsed or processed programmatically.
13087
11379
  *
13088
- * @param lng - Target language code (e.g., 'de', 'fr', 'es')
13089
- * @returns Promise with translation status
11380
+ * **Important:** Your prompt must include the word "json" and should describe
11381
+ * the expected output schema (field names, types, and structure) to ensure
11382
+ * the AI generates properly formatted responses.
13090
11383
  *
13091
- * @example
13092
- * ```typescript
13093
- * const status = await kmClient.i18n.getTranslationStatus('de');
13094
- * if (status.status === 'available') {
13095
- * // All translations ready, can switch language
13096
- * i18next.changeLanguage('de');
13097
- * } else if (status.status === 'processing') {
13098
- * // Show loading indicator
13099
- * } else {
13100
- * // Request translation
13101
- * await kmClient.i18n.requestTranslation('de');
13102
- * }
13103
- * ```
11384
+ * @param req The chat request parameters.
11385
+ * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
11386
+ * Available models:
11387
+ * - `gpt-4o`: OpenAI GPT-4 Optimized
11388
+ * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
11389
+ * - `gpt-5`: OpenAI GPT-5 (latest)
11390
+ * - `gpt-5-mini`: Smaller GPT-5 variant
11391
+ * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
11392
+ * - `gemini-2.5-flash-lite`: Google Gemini lite variant
11393
+ * - `gemini-2.5-flash`: Google Gemini fast variant
11394
+ * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
11395
+ * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
11396
+ * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
11397
+ * This helps define the AI's role, personality, and constraints.
11398
+ * @param req.userPrompt The user's message or question to send to the AI.
11399
+ * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
11400
+ * Lower values make output more focused and deterministic,
11401
+ * higher values make it more creative and varied.
11402
+ * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
11403
+ * Controls the length of the AI's output.
11404
+ * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
11405
+ * Allows the AI to analyze images and generate structured JSON based on them.
11406
+ *
11407
+ * @returns A promise that resolves to the parsed JSON object generated by the AI.
11408
+ *
11409
+ * @throws An error object if the API request fails or if the response is not valid JSON.
13104
11410
  */
13105
- async getTranslationStatus(lng) {
13106
- const env = getKmEnv();
13107
- if (env.dev) {
13108
- // In dev, only local languages are available
13109
- const localLanguages = this.getLanguages();
13110
- const namespaces = this.getNamespaces();
13111
- const isLocal = localLanguages.includes(lng);
13112
- const status = isLocal ? "available" : "not_available";
13113
- return {
13114
- status,
13115
- namespaces: Object.fromEntries(namespaces.map((ns) => [ns, status])),
13116
- };
13117
- }
13118
- const res = await fetch(`${this.client.apiUrl}/i18n/${encodeURIComponent(lng)}/status`, {
13119
- method: "GET",
13120
- headers: this.client.apiHeaders,
11411
+ async generateJson(req) {
11412
+ const { content } = await this.chat({
11413
+ ...req,
11414
+ responseMimeType: "application/json",
13121
11415
  });
13122
- return await res.json();
11416
+ return JSON.parse(content);
13123
11417
  }
13124
11418
  /**
13125
- * Request AI translation for a target language.
13126
- *
13127
- * Triggers background AI translation jobs for all namespaces that are not yet available.
13128
- * Uses the build's configured primary language as the source.
13129
- *
13130
- * In development, returns 'already_available' for local languages and throws an error for others.
13131
- * In production, triggers the API to start translation.
13132
- *
13133
- * @param lng - Target language code (e.g., 'de', 'fr', 'es')
13134
- * @returns Promise with the result of the request
13135
- *
13136
- * @example
13137
- * ```typescript
13138
- * const result = await kmClient.i18n.requestTranslation('de');
13139
- *
13140
- * if (result.status === 'started') {
13141
- * // Translation started, poll for status
13142
- * const checkStatus = async () => {
13143
- * const status = await kmClient.i18n.getTranslationStatus('de');
13144
- * if (status.status === 'available') {
13145
- * i18next.changeLanguage('de');
13146
- * } else if (status.status === 'processing') {
13147
- * setTimeout(checkStatus, 2000);
13148
- * }
13149
- * };
13150
- * checkStatus();
13151
- * } else if (result.status === 'already_available') {
13152
- * // Already translated, switch immediately
13153
- * i18next.changeLanguage('de');
13154
- * }
13155
- * ```
11419
+ * Modify an image using the AI service.
11420
+ * @param baseImageUrl The URL of the base image to modify.
11421
+ * @param prompt The modification prompt to apply to the image.
11422
+ * @param tags Optional. Tags to associate with the image.
11423
+ * @returns A promise that resolves to the modified image upload information.
13156
11424
  */
13157
- async requestTranslation(lng) {
13158
- const env = getKmEnv();
13159
- if (env.dev) {
13160
- // In dev, only local languages are available
13161
- const localLanguages = this.getLanguages();
13162
- if (localLanguages.includes(lng)) {
13163
- return { status: "already_available" };
13164
- }
13165
- // AI translation not available in dev mode
13166
- throw new Error(`AI translation not available in dev mode. Add local translations for '${lng}' in src/i18n/${lng}/`);
13167
- }
13168
- const res = await fetch(`${this.client.apiUrl}/i18n/${encodeURIComponent(lng)}/translate`, {
11425
+ async modifyImage(baseImageUrl, prompt, tags = [], model = "gemini-2.5-flash-image") {
11426
+ const res = await fetch(`${this.client.apiUrl}/ai/modify-image`, {
13169
11427
  method: "POST",
13170
11428
  headers: this.client.apiHeaders,
11429
+ body: JSON.stringify({ baseImageUrl, prompt, tags, model }),
13171
11430
  });
11431
+ if (!res.ok) {
11432
+ throw await res.json();
11433
+ }
13172
11434
  return await res.json();
13173
11435
  }
13174
11436
  }
@@ -13865,16 +12127,16 @@ var functionApply = Function.prototype.apply;
13865
12127
  /** @type {import('./reflectApply')} */
13866
12128
  var reflectApply$1 = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;
13867
12129
 
13868
- var bind$5 = functionBind;
12130
+ var bind$4 = functionBind;
13869
12131
 
13870
12132
  var $apply$2 = functionApply;
13871
12133
  var $call$2 = functionCall;
13872
12134
  var $reflectApply = reflectApply$1;
13873
12135
 
13874
12136
  /** @type {import('./actualApply')} */
13875
- var actualApply$1 = $reflectApply || bind$5.call($call$2, $apply$2);
12137
+ var actualApply$1 = $reflectApply || bind$4.call($call$2, $apply$2);
13876
12138
 
13877
- var bind$4 = functionBind;
12139
+ var bind$3 = functionBind;
13878
12140
  var $TypeError$4 = requireType();
13879
12141
 
13880
12142
  var $call$1 = functionCall;
@@ -13885,7 +12147,7 @@ var callBindApplyHelpers = function callBindBasic(args) {
13885
12147
  if (args.length < 1 || typeof args[0] !== 'function') {
13886
12148
  throw new $TypeError$4('a function is required');
13887
12149
  }
13888
- return $actualApply(bind$4, $call$1, args);
12150
+ return $actualApply(bind$3, $call$1, args);
13889
12151
  };
13890
12152
 
13891
12153
  var callBind$2 = callBindApplyHelpers;
@@ -13943,12 +12205,21 @@ var getProto$4 = reflectGetProto
13943
12205
  }
13944
12206
  : null;
13945
12207
 
13946
- var call = Function.prototype.call;
13947
- var $hasOwn = Object.prototype.hasOwnProperty;
13948
- var bind$3 = functionBind;
12208
+ var hasown;
12209
+ var hasRequiredHasown;
13949
12210
 
13950
- /** @type {import('.')} */
13951
- var hasown = bind$3.call(call, $hasOwn);
12211
+ function requireHasown () {
12212
+ if (hasRequiredHasown) return hasown;
12213
+ hasRequiredHasown = 1;
12214
+
12215
+ var call = Function.prototype.call;
12216
+ var $hasOwn = Object.prototype.hasOwnProperty;
12217
+ var bind = functionBind;
12218
+
12219
+ /** @type {import('.')} */
12220
+ hasown = bind.call(call, $hasOwn);
12221
+ return hasown;
12222
+ }
13952
12223
 
13953
12224
  var undefined$1;
13954
12225
 
@@ -14191,7 +12462,7 @@ var LEGACY_ALIASES = {
14191
12462
  };
14192
12463
 
14193
12464
  var bind$2 = functionBind;
14194
- var hasOwn$1 = hasown;
12465
+ var hasOwn$1 = requireHasown();
14195
12466
  var $concat = bind$2.call($call, Array.prototype.concat);
14196
12467
  var $spliceApply = bind$2.call($apply$1, Array.prototype.splice);
14197
12468
  var $replace = bind$2.call($call, String.prototype.replace);
@@ -14390,7 +12661,7 @@ var isArguments = supportsStandardArguments ? isStandardArguments : isLegacyArgu
14390
12661
 
14391
12662
  var callBound$3 = callBound$5;
14392
12663
  var hasToStringTag$3 = shams();
14393
- var hasOwn = hasown;
12664
+ var hasOwn = requireHasown();
14394
12665
  var gOPD$2 = gopd$1;
14395
12666
 
14396
12667
  /** @type {import('.')} */
@@ -14620,12 +12891,12 @@ var isCallable$1 = reflectApply
14620
12891
  var isCallable = isCallable$1;
14621
12892
 
14622
12893
  var toStr = Object.prototype.toString;
14623
- var hasOwnProperty = Object.prototype.hasOwnProperty;
12894
+ var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
14624
12895
 
14625
12896
  /** @type {<This, A extends readonly unknown[]>(arr: A, iterator: (this: This | void, value: A[number], index: number, arr: A) => void, receiver: This | undefined) => void} */
14626
12897
  var forEachArray = function forEachArray(array, iterator, receiver) {
14627
12898
  for (var i = 0, len = array.length; i < len; i++) {
14628
- if (hasOwnProperty.call(array, i)) {
12899
+ if (hasOwnProperty$1.call(array, i)) {
14629
12900
  if (receiver == null) {
14630
12901
  iterator(array[i], i, array);
14631
12902
  } else {
@@ -14650,7 +12921,7 @@ var forEachString = function forEachString(string, iterator, receiver) {
14650
12921
  /** @type {<This, O>(obj: O, iterator: (this: This | void, value: O[keyof O], index: keyof O, obj: O) => void, receiver: This | undefined) => void} */
14651
12922
  var forEachObject = function forEachObject(object, iterator, receiver) {
14652
12923
  for (var k in object) {
14653
- if (hasOwnProperty.call(object, k)) {
12924
+ if (hasOwnProperty$1.call(object, k)) {
14654
12925
  if (receiver == null) {
14655
12926
  iterator(object[k], k, object);
14656
12927
  } else {
@@ -16784,7 +15055,7 @@ const createHandlerDefault = (isInitializing, addPropListener, removePropListene
16784
15055
  removePropListener(prop);
16785
15056
  const deleted = Reflect.deleteProperty(target, prop);
16786
15057
  if (deleted) {
16787
- notifyUpdate(createOp == null ? void 0 : createOp("delete", prop, prevValue));
15058
+ notifyUpdate(["delete", [prop], prevValue]);
16788
15059
  }
16789
15060
  return deleted;
16790
15061
  },
@@ -16801,11 +15072,10 @@ const createHandlerDefault = (isInitializing, addPropListener, removePropListene
16801
15072
  const nextValue = !proxyStateMap.has(value) && canProxy(value) ? proxy(value) : value;
16802
15073
  addPropListener(prop, nextValue);
16803
15074
  Reflect.set(target, prop, nextValue, receiver);
16804
- notifyUpdate(createOp == null ? void 0 : createOp("set", prop, value, prevValue));
15075
+ notifyUpdate(["set", [prop], value, prevValue]);
16805
15076
  return true;
16806
15077
  }
16807
15078
  });
16808
- const createOpDefault = (type, prop, ...args) => [type, [prop], ...args];
16809
15079
  const proxyStateMap = /* @__PURE__ */ new WeakMap();
16810
15080
  const refSet = /* @__PURE__ */ new WeakSet();
16811
15081
  const snapCache = /* @__PURE__ */ new WeakMap();
@@ -16816,7 +15086,6 @@ let newProxy = (target, handler) => new Proxy(target, handler);
16816
15086
  let canProxy = canProxyDefault;
16817
15087
  let createSnapshot = createSnapshotDefault;
16818
15088
  let createHandler = createHandlerDefault;
16819
- let createOp;
16820
15089
  function proxy(baseObject = {}) {
16821
15090
  if (!isObject(baseObject)) {
16822
15091
  throw new Error("object required");
@@ -16847,11 +15116,8 @@ function proxy(baseObject = {}) {
16847
15116
  return version;
16848
15117
  };
16849
15118
  const createPropListener = (prop) => (op, nextVersion) => {
16850
- let newOp;
16851
- if (op) {
16852
- newOp = [...op];
16853
- newOp[1] = [prop, ...newOp[1]];
16854
- }
15119
+ const newOp = [...op];
15120
+ newOp[1] = [prop, ...newOp[1]];
16855
15121
  notifyUpdate(newOp, nextVersion);
16856
15122
  };
16857
15123
  const propProxyStates = /* @__PURE__ */ new Map();
@@ -16938,9 +15204,7 @@ function subscribe(proxyObject, callback, notifyInSync) {
16938
15204
  const addListener = proxyState[2];
16939
15205
  let isListenerActive = false;
16940
15206
  const listener = (op) => {
16941
- if (op) {
16942
- ops.push(op);
16943
- }
15207
+ ops.push(op);
16944
15208
  if (notifyInSync) {
16945
15209
  callback(ops.splice(0));
16946
15210
  return;
@@ -16973,15 +15237,6 @@ function ref(obj) {
16973
15237
  refSet.add(obj);
16974
15238
  return obj;
16975
15239
  }
16976
- function unstable_enableOp(enabled = true) {
16977
- if (enabled === true) {
16978
- createOp = createOpDefault;
16979
- } else if (enabled === false) {
16980
- createOp = void 0;
16981
- } else {
16982
- createOp = enabled;
16983
- }
16984
- }
16985
15240
 
16986
15241
  const parseProxyOps = (ops) => {
16987
15242
  const indexed = new Set();
@@ -17955,7 +16210,6 @@ class KokimokiClient extends EventEmitter$1 {
17955
16210
  _clientTokenKey = "KM_TOKEN";
17956
16211
  _editorContext;
17957
16212
  _ai;
17958
- _i18n;
17959
16213
  _storage;
17960
16214
  _leaderboard;
17961
16215
  constructor(host, appId, code = "") {
@@ -17969,7 +16223,6 @@ class KokimokiClient extends EventEmitter$1 {
17969
16223
  this._apiUrl = `http${secure ? "s" : ""}://${this.host}`;
17970
16224
  // Initialize modules
17971
16225
  this._ai = new KokimokiAiService(this);
17972
- this._i18n = new KokimokiI18nService(this);
17973
16226
  this._storage = new KokimokiStorageService(this);
17974
16227
  this._leaderboard = new KokimokiLeaderboardService(this);
17975
16228
  // Set up ping interval
@@ -18479,44 +16732,6 @@ class KokimokiClient extends EventEmitter$1 {
18479
16732
  clearInterval(this._pingInterval);
18480
16733
  }
18481
16734
  }
18482
- /**
18483
- * Waits for all subscriptions to be fully joined.
18484
- *
18485
- * This is useful when you need to ensure all stores have completed their initial
18486
- * synchronization before proceeding (e.g., before running tests or taking snapshots).
18487
- *
18488
- * @param timeout - Maximum time to wait in milliseconds (default: 5000ms).
18489
- * @returns A promise that resolves when all subscriptions are joined, or when timeout is reached.
18490
- *
18491
- * @example
18492
- * ```ts
18493
- * // Wait for all stores to sync before starting game
18494
- * await client.waitForSubscriptions();
18495
- *
18496
- * // Wait with custom timeout
18497
- * await client.waitForSubscriptions(10000);
18498
- * ```
18499
- */
18500
- async waitForSubscriptions(timeout = 5000) {
18501
- const checkInterval = 10;
18502
- const maxChecks = Math.ceil(timeout / checkInterval);
18503
- return new Promise((resolve) => {
18504
- let checks = 0;
18505
- const intervalId = setInterval(() => {
18506
- let allJoined = true;
18507
- for (const subscription of this._subscriptionsByName.values()) {
18508
- if (!subscription.joined) {
18509
- allJoined = false;
18510
- break;
18511
- }
18512
- }
18513
- if (allJoined || ++checks >= maxChecks) {
18514
- clearInterval(intervalId);
18515
- resolve();
18516
- }
18517
- }, checkInterval);
18518
- });
18519
- }
18520
16735
  /**
18521
16736
  * Gets the internal room hash identifier for a store.
18522
16737
  *
@@ -18608,15 +16823,6 @@ class KokimokiClient extends EventEmitter$1 {
18608
16823
  }
18609
16824
  return this._ai;
18610
16825
  }
18611
- /**
18612
- * Access i18n URL resolution and translation loading utilities.
18613
- */
18614
- get i18n() {
18615
- if (!this._i18n) {
18616
- throw new Error("I18n client not initialized");
18617
- }
18618
- return this._i18n;
18619
- }
18620
16826
  /**
18621
16827
  * Access file upload and management for media files, images, and user-generated content.
18622
16828
  */
@@ -18637,25 +16843,576 @@ class KokimokiClient extends EventEmitter$1 {
18637
16843
  }
18638
16844
  }
18639
16845
 
16846
+ var react = {exports: {}};
16847
+
16848
+ var react_production = {};
16849
+
16850
+ /**
16851
+ * @license React
16852
+ * react.production.js
16853
+ *
16854
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
16855
+ *
16856
+ * This source code is licensed under the MIT license found in the
16857
+ * LICENSE file in the root directory of this source tree.
16858
+ */
16859
+ var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
16860
+ REACT_PORTAL_TYPE = Symbol.for("react.portal"),
16861
+ REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
16862
+ REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
16863
+ REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
16864
+ REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
16865
+ REACT_CONTEXT_TYPE = Symbol.for("react.context"),
16866
+ REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
16867
+ REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
16868
+ REACT_MEMO_TYPE = Symbol.for("react.memo"),
16869
+ REACT_LAZY_TYPE = Symbol.for("react.lazy"),
16870
+ REACT_ACTIVITY_TYPE = Symbol.for("react.activity"),
16871
+ MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
16872
+ function getIteratorFn(maybeIterable) {
16873
+ if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
16874
+ maybeIterable =
16875
+ (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||
16876
+ maybeIterable["@@iterator"];
16877
+ return "function" === typeof maybeIterable ? maybeIterable : null;
16878
+ }
16879
+ var ReactNoopUpdateQueue = {
16880
+ isMounted: function () {
16881
+ return false;
16882
+ },
16883
+ enqueueForceUpdate: function () {},
16884
+ enqueueReplaceState: function () {},
16885
+ enqueueSetState: function () {}
16886
+ },
16887
+ assign = Object.assign,
16888
+ emptyObject = {};
16889
+ function Component(props, context, updater) {
16890
+ this.props = props;
16891
+ this.context = context;
16892
+ this.refs = emptyObject;
16893
+ this.updater = updater || ReactNoopUpdateQueue;
16894
+ }
16895
+ Component.prototype.isReactComponent = {};
16896
+ Component.prototype.setState = function (partialState, callback) {
16897
+ if (
16898
+ "object" !== typeof partialState &&
16899
+ "function" !== typeof partialState &&
16900
+ null != partialState
16901
+ )
16902
+ throw Error(
16903
+ "takes an object of state variables to update or a function which returns an object of state variables."
16904
+ );
16905
+ this.updater.enqueueSetState(this, partialState, callback, "setState");
16906
+ };
16907
+ Component.prototype.forceUpdate = function (callback) {
16908
+ this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
16909
+ };
16910
+ function ComponentDummy() {}
16911
+ ComponentDummy.prototype = Component.prototype;
16912
+ function PureComponent(props, context, updater) {
16913
+ this.props = props;
16914
+ this.context = context;
16915
+ this.refs = emptyObject;
16916
+ this.updater = updater || ReactNoopUpdateQueue;
16917
+ }
16918
+ var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
16919
+ pureComponentPrototype.constructor = PureComponent;
16920
+ assign(pureComponentPrototype, Component.prototype);
16921
+ pureComponentPrototype.isPureReactComponent = true;
16922
+ var isArrayImpl = Array.isArray;
16923
+ function noop() {}
16924
+ var ReactSharedInternals = { H: null, A: null, T: null, S: null },
16925
+ hasOwnProperty = Object.prototype.hasOwnProperty;
16926
+ function ReactElement(type, key, props) {
16927
+ var refProp = props.ref;
16928
+ return {
16929
+ $$typeof: REACT_ELEMENT_TYPE,
16930
+ type: type,
16931
+ key: key,
16932
+ ref: void 0 !== refProp ? refProp : null,
16933
+ props: props
16934
+ };
16935
+ }
16936
+ function cloneAndReplaceKey(oldElement, newKey) {
16937
+ return ReactElement(oldElement.type, newKey, oldElement.props);
16938
+ }
16939
+ function isValidElement(object) {
16940
+ return (
16941
+ "object" === typeof object &&
16942
+ null !== object &&
16943
+ object.$$typeof === REACT_ELEMENT_TYPE
16944
+ );
16945
+ }
16946
+ function escape$1(key) {
16947
+ var escaperLookup = { "=": "=0", ":": "=2" };
16948
+ return (
16949
+ "$" +
16950
+ key.replace(/[=:]/g, function (match) {
16951
+ return escaperLookup[match];
16952
+ })
16953
+ );
16954
+ }
16955
+ var userProvidedKeyEscapeRegex = /\/+/g;
16956
+ function getElementKey(element, index) {
16957
+ return "object" === typeof element && null !== element && null != element.key
16958
+ ? escape$1("" + element.key)
16959
+ : index.toString(36);
16960
+ }
16961
+ function resolveThenable(thenable) {
16962
+ switch (thenable.status) {
16963
+ case "fulfilled":
16964
+ return thenable.value;
16965
+ case "rejected":
16966
+ throw thenable.reason;
16967
+ default:
16968
+ switch (
16969
+ ("string" === typeof thenable.status
16970
+ ? thenable.then(noop, noop)
16971
+ : ((thenable.status = "pending"),
16972
+ thenable.then(
16973
+ function (fulfilledValue) {
16974
+ "pending" === thenable.status &&
16975
+ ((thenable.status = "fulfilled"),
16976
+ (thenable.value = fulfilledValue));
16977
+ },
16978
+ function (error) {
16979
+ "pending" === thenable.status &&
16980
+ ((thenable.status = "rejected"), (thenable.reason = error));
16981
+ }
16982
+ )),
16983
+ thenable.status)
16984
+ ) {
16985
+ case "fulfilled":
16986
+ return thenable.value;
16987
+ case "rejected":
16988
+ throw thenable.reason;
16989
+ }
16990
+ }
16991
+ throw thenable;
16992
+ }
16993
+ function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
16994
+ var type = typeof children;
16995
+ if ("undefined" === type || "boolean" === type) children = null;
16996
+ var invokeCallback = false;
16997
+ if (null === children) invokeCallback = true;
16998
+ else
16999
+ switch (type) {
17000
+ case "bigint":
17001
+ case "string":
17002
+ case "number":
17003
+ invokeCallback = true;
17004
+ break;
17005
+ case "object":
17006
+ switch (children.$$typeof) {
17007
+ case REACT_ELEMENT_TYPE:
17008
+ case REACT_PORTAL_TYPE:
17009
+ invokeCallback = true;
17010
+ break;
17011
+ case REACT_LAZY_TYPE:
17012
+ return (
17013
+ (invokeCallback = children._init),
17014
+ mapIntoArray(
17015
+ invokeCallback(children._payload),
17016
+ array,
17017
+ escapedPrefix,
17018
+ nameSoFar,
17019
+ callback
17020
+ )
17021
+ );
17022
+ }
17023
+ }
17024
+ if (invokeCallback)
17025
+ return (
17026
+ (callback = callback(children)),
17027
+ (invokeCallback =
17028
+ "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar),
17029
+ isArrayImpl(callback)
17030
+ ? ((escapedPrefix = ""),
17031
+ null != invokeCallback &&
17032
+ (escapedPrefix =
17033
+ invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"),
17034
+ mapIntoArray(callback, array, escapedPrefix, "", function (c) {
17035
+ return c;
17036
+ }))
17037
+ : null != callback &&
17038
+ (isValidElement(callback) &&
17039
+ (callback = cloneAndReplaceKey(
17040
+ callback,
17041
+ escapedPrefix +
17042
+ (null == callback.key ||
17043
+ (children && children.key === callback.key)
17044
+ ? ""
17045
+ : ("" + callback.key).replace(
17046
+ userProvidedKeyEscapeRegex,
17047
+ "$&/"
17048
+ ) + "/") +
17049
+ invokeCallback
17050
+ )),
17051
+ array.push(callback)),
17052
+ 1
17053
+ );
17054
+ invokeCallback = 0;
17055
+ var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
17056
+ if (isArrayImpl(children))
17057
+ for (var i = 0; i < children.length; i++)
17058
+ (nameSoFar = children[i]),
17059
+ (type = nextNamePrefix + getElementKey(nameSoFar, i)),
17060
+ (invokeCallback += mapIntoArray(
17061
+ nameSoFar,
17062
+ array,
17063
+ escapedPrefix,
17064
+ type,
17065
+ callback
17066
+ ));
17067
+ else if (((i = getIteratorFn(children)), "function" === typeof i))
17068
+ for (
17069
+ children = i.call(children), i = 0;
17070
+ !(nameSoFar = children.next()).done;
17071
+
17072
+ )
17073
+ (nameSoFar = nameSoFar.value),
17074
+ (type = nextNamePrefix + getElementKey(nameSoFar, i++)),
17075
+ (invokeCallback += mapIntoArray(
17076
+ nameSoFar,
17077
+ array,
17078
+ escapedPrefix,
17079
+ type,
17080
+ callback
17081
+ ));
17082
+ else if ("object" === type) {
17083
+ if ("function" === typeof children.then)
17084
+ return mapIntoArray(
17085
+ resolveThenable(children),
17086
+ array,
17087
+ escapedPrefix,
17088
+ nameSoFar,
17089
+ callback
17090
+ );
17091
+ array = String(children);
17092
+ throw Error(
17093
+ "Objects are not valid as a React child (found: " +
17094
+ ("[object Object]" === array
17095
+ ? "object with keys {" + Object.keys(children).join(", ") + "}"
17096
+ : array) +
17097
+ "). If you meant to render a collection of children, use an array instead."
17098
+ );
17099
+ }
17100
+ return invokeCallback;
17101
+ }
17102
+ function mapChildren(children, func, context) {
17103
+ if (null == children) return children;
17104
+ var result = [],
17105
+ count = 0;
17106
+ mapIntoArray(children, result, "", "", function (child) {
17107
+ return func.call(context, child, count++);
17108
+ });
17109
+ return result;
17110
+ }
17111
+ function lazyInitializer(payload) {
17112
+ if (-1 === payload._status) {
17113
+ var ctor = payload._result;
17114
+ ctor = ctor();
17115
+ ctor.then(
17116
+ function (moduleObject) {
17117
+ if (0 === payload._status || -1 === payload._status)
17118
+ (payload._status = 1), (payload._result = moduleObject);
17119
+ },
17120
+ function (error) {
17121
+ if (0 === payload._status || -1 === payload._status)
17122
+ (payload._status = 2), (payload._result = error);
17123
+ }
17124
+ );
17125
+ -1 === payload._status && ((payload._status = 0), (payload._result = ctor));
17126
+ }
17127
+ if (1 === payload._status) return payload._result.default;
17128
+ throw payload._result;
17129
+ }
17130
+ var reportGlobalError =
17131
+ "function" === typeof reportError
17132
+ ? reportError
17133
+ : function (error) {
17134
+ if (
17135
+ "object" === typeof window &&
17136
+ "function" === typeof window.ErrorEvent
17137
+ ) {
17138
+ var event = new window.ErrorEvent("error", {
17139
+ bubbles: true,
17140
+ cancelable: true,
17141
+ message:
17142
+ "object" === typeof error &&
17143
+ null !== error &&
17144
+ "string" === typeof error.message
17145
+ ? String(error.message)
17146
+ : String(error),
17147
+ error: error
17148
+ });
17149
+ if (!window.dispatchEvent(event)) return;
17150
+ } else if (
17151
+ "object" === typeof process &&
17152
+ "function" === typeof process.emit
17153
+ ) {
17154
+ process.emit("uncaughtException", error);
17155
+ return;
17156
+ }
17157
+ console.error(error);
17158
+ },
17159
+ Children = {
17160
+ map: mapChildren,
17161
+ forEach: function (children, forEachFunc, forEachContext) {
17162
+ mapChildren(
17163
+ children,
17164
+ function () {
17165
+ forEachFunc.apply(this, arguments);
17166
+ },
17167
+ forEachContext
17168
+ );
17169
+ },
17170
+ count: function (children) {
17171
+ var n = 0;
17172
+ mapChildren(children, function () {
17173
+ n++;
17174
+ });
17175
+ return n;
17176
+ },
17177
+ toArray: function (children) {
17178
+ return (
17179
+ mapChildren(children, function (child) {
17180
+ return child;
17181
+ }) || []
17182
+ );
17183
+ },
17184
+ only: function (children) {
17185
+ if (!isValidElement(children))
17186
+ throw Error(
17187
+ "React.Children.only expected to receive a single React element child."
17188
+ );
17189
+ return children;
17190
+ }
17191
+ };
17192
+ react_production.Activity = REACT_ACTIVITY_TYPE;
17193
+ react_production.Children = Children;
17194
+ react_production.Component = Component;
17195
+ react_production.Fragment = REACT_FRAGMENT_TYPE;
17196
+ react_production.Profiler = REACT_PROFILER_TYPE;
17197
+ react_production.PureComponent = PureComponent;
17198
+ react_production.StrictMode = REACT_STRICT_MODE_TYPE;
17199
+ react_production.Suspense = REACT_SUSPENSE_TYPE;
17200
+ react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =
17201
+ ReactSharedInternals;
17202
+ react_production.__COMPILER_RUNTIME = {
17203
+ __proto__: null,
17204
+ c: function (size) {
17205
+ return ReactSharedInternals.H.useMemoCache(size);
17206
+ }
17207
+ };
17208
+ react_production.cache = function (fn) {
17209
+ return function () {
17210
+ return fn.apply(null, arguments);
17211
+ };
17212
+ };
17213
+ react_production.cacheSignal = function () {
17214
+ return null;
17215
+ };
17216
+ react_production.cloneElement = function (element, config, children) {
17217
+ if (null === element || void 0 === element)
17218
+ throw Error(
17219
+ "The argument must be a React element, but you passed " + element + "."
17220
+ );
17221
+ var props = assign({}, element.props),
17222
+ key = element.key;
17223
+ if (null != config)
17224
+ for (propName in (void 0 !== config.key && (key = "" + config.key), config))
17225
+ !hasOwnProperty.call(config, propName) ||
17226
+ "key" === propName ||
17227
+ "__self" === propName ||
17228
+ "__source" === propName ||
17229
+ ("ref" === propName && void 0 === config.ref) ||
17230
+ (props[propName] = config[propName]);
17231
+ var propName = arguments.length - 2;
17232
+ if (1 === propName) props.children = children;
17233
+ else if (1 < propName) {
17234
+ for (var childArray = Array(propName), i = 0; i < propName; i++)
17235
+ childArray[i] = arguments[i + 2];
17236
+ props.children = childArray;
17237
+ }
17238
+ return ReactElement(element.type, key, props);
17239
+ };
17240
+ react_production.createContext = function (defaultValue) {
17241
+ defaultValue = {
17242
+ $$typeof: REACT_CONTEXT_TYPE,
17243
+ _currentValue: defaultValue,
17244
+ _currentValue2: defaultValue,
17245
+ _threadCount: 0,
17246
+ Provider: null,
17247
+ Consumer: null
17248
+ };
17249
+ defaultValue.Provider = defaultValue;
17250
+ defaultValue.Consumer = {
17251
+ $$typeof: REACT_CONSUMER_TYPE,
17252
+ _context: defaultValue
17253
+ };
17254
+ return defaultValue;
17255
+ };
17256
+ react_production.createElement = function (type, config, children) {
17257
+ var propName,
17258
+ props = {},
17259
+ key = null;
17260
+ if (null != config)
17261
+ for (propName in (void 0 !== config.key && (key = "" + config.key), config))
17262
+ hasOwnProperty.call(config, propName) &&
17263
+ "key" !== propName &&
17264
+ "__self" !== propName &&
17265
+ "__source" !== propName &&
17266
+ (props[propName] = config[propName]);
17267
+ var childrenLength = arguments.length - 2;
17268
+ if (1 === childrenLength) props.children = children;
17269
+ else if (1 < childrenLength) {
17270
+ for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
17271
+ childArray[i] = arguments[i + 2];
17272
+ props.children = childArray;
17273
+ }
17274
+ if (type && type.defaultProps)
17275
+ for (propName in ((childrenLength = type.defaultProps), childrenLength))
17276
+ void 0 === props[propName] &&
17277
+ (props[propName] = childrenLength[propName]);
17278
+ return ReactElement(type, key, props);
17279
+ };
17280
+ react_production.createRef = function () {
17281
+ return { current: null };
17282
+ };
17283
+ react_production.forwardRef = function (render) {
17284
+ return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };
17285
+ };
17286
+ react_production.isValidElement = isValidElement;
17287
+ react_production.lazy = function (ctor) {
17288
+ return {
17289
+ $$typeof: REACT_LAZY_TYPE,
17290
+ _payload: { _status: -1, _result: ctor },
17291
+ _init: lazyInitializer
17292
+ };
17293
+ };
17294
+ react_production.memo = function (type, compare) {
17295
+ return {
17296
+ $$typeof: REACT_MEMO_TYPE,
17297
+ type: type,
17298
+ compare: void 0 === compare ? null : compare
17299
+ };
17300
+ };
17301
+ react_production.startTransition = function (scope) {
17302
+ var prevTransition = ReactSharedInternals.T,
17303
+ currentTransition = {};
17304
+ ReactSharedInternals.T = currentTransition;
17305
+ try {
17306
+ var returnValue = scope(),
17307
+ onStartTransitionFinish = ReactSharedInternals.S;
17308
+ null !== onStartTransitionFinish &&
17309
+ onStartTransitionFinish(currentTransition, returnValue);
17310
+ "object" === typeof returnValue &&
17311
+ null !== returnValue &&
17312
+ "function" === typeof returnValue.then &&
17313
+ returnValue.then(noop, reportGlobalError);
17314
+ } catch (error) {
17315
+ reportGlobalError(error);
17316
+ } finally {
17317
+ null !== prevTransition &&
17318
+ null !== currentTransition.types &&
17319
+ (prevTransition.types = currentTransition.types),
17320
+ (ReactSharedInternals.T = prevTransition);
17321
+ }
17322
+ };
17323
+ react_production.unstable_useCacheRefresh = function () {
17324
+ return ReactSharedInternals.H.useCacheRefresh();
17325
+ };
17326
+ react_production.use = function (usable) {
17327
+ return ReactSharedInternals.H.use(usable);
17328
+ };
17329
+ react_production.useActionState = function (action, initialState, permalink) {
17330
+ return ReactSharedInternals.H.useActionState(action, initialState, permalink);
17331
+ };
17332
+ react_production.useCallback = function (callback, deps) {
17333
+ return ReactSharedInternals.H.useCallback(callback, deps);
17334
+ };
17335
+ react_production.useContext = function (Context) {
17336
+ return ReactSharedInternals.H.useContext(Context);
17337
+ };
17338
+ react_production.useDebugValue = function () {};
17339
+ react_production.useDeferredValue = function (value, initialValue) {
17340
+ return ReactSharedInternals.H.useDeferredValue(value, initialValue);
17341
+ };
17342
+ react_production.useEffect = function (create, deps) {
17343
+ return ReactSharedInternals.H.useEffect(create, deps);
17344
+ };
17345
+ react_production.useEffectEvent = function (callback) {
17346
+ return ReactSharedInternals.H.useEffectEvent(callback);
17347
+ };
17348
+ react_production.useId = function () {
17349
+ return ReactSharedInternals.H.useId();
17350
+ };
17351
+ react_production.useImperativeHandle = function (ref, create, deps) {
17352
+ return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);
17353
+ };
17354
+ react_production.useInsertionEffect = function (create, deps) {
17355
+ return ReactSharedInternals.H.useInsertionEffect(create, deps);
17356
+ };
17357
+ react_production.useLayoutEffect = function (create, deps) {
17358
+ return ReactSharedInternals.H.useLayoutEffect(create, deps);
17359
+ };
17360
+ react_production.useMemo = function (create, deps) {
17361
+ return ReactSharedInternals.H.useMemo(create, deps);
17362
+ };
17363
+ react_production.useOptimistic = function (passthrough, reducer) {
17364
+ return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
17365
+ };
17366
+ react_production.useReducer = function (reducer, initialArg, init) {
17367
+ return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
17368
+ };
17369
+ react_production.useRef = function (initialValue) {
17370
+ return ReactSharedInternals.H.useRef(initialValue);
17371
+ };
17372
+ react_production.useState = function (initialState) {
17373
+ return ReactSharedInternals.H.useState(initialState);
17374
+ };
17375
+ react_production.useSyncExternalStore = function (
17376
+ subscribe,
17377
+ getSnapshot,
17378
+ getServerSnapshot
17379
+ ) {
17380
+ return ReactSharedInternals.H.useSyncExternalStore(
17381
+ subscribe,
17382
+ getSnapshot,
17383
+ getServerSnapshot
17384
+ );
17385
+ };
17386
+ react_production.useTransition = function () {
17387
+ return ReactSharedInternals.H.useTransition();
17388
+ };
17389
+ react_production.version = "19.2.3";
17390
+
17391
+ {
17392
+ react.exports = react_production;
17393
+ }
17394
+
17395
+ var reactExports = react.exports;
17396
+
18640
17397
  const useAffectedDebugValue = (state, affected) => {
18641
- const pathList = useRef(void 0);
18642
- useEffect(() => {
17398
+ const pathList = reactExports.useRef(void 0);
17399
+ reactExports.useEffect(() => {
18643
17400
  pathList.current = affectedToPathList(state, affected);
18644
17401
  });
18645
- useDebugValue(pathList.current);
17402
+ reactExports.useDebugValue(pathList.current);
18646
17403
  };
18647
17404
  const condUseAffectedDebugValue = useAffectedDebugValue;
18648
17405
  const targetCache = /* @__PURE__ */ new WeakMap();
18649
17406
  function useSnapshot(proxyObject, options) {
18650
17407
  const notifyInSync = options == null ? void 0 : options.sync;
18651
- const affected = useMemo(
17408
+ const affected = reactExports.useMemo(
18652
17409
  () => proxyObject && /* @__PURE__ */ new WeakMap(),
18653
17410
  [proxyObject]
18654
17411
  );
18655
- const lastSnapshot = useRef(void 0);
18656
- const subscribed = useRef(false);
18657
- const currSnapshot = useSyncExternalStore(
18658
- useCallback(
17412
+ const lastSnapshot = reactExports.useRef(void 0);
17413
+ const subscribed = reactExports.useRef(false);
17414
+ const currSnapshot = reactExports.useSyncExternalStore(
17415
+ reactExports.useCallback(
18659
17416
  (callback) => {
18660
17417
  subscribed.current = true;
18661
17418
  const unsub = subscribe(proxyObject, callback, notifyInSync);
@@ -18684,13 +17441,13 @@ function useSnapshot(proxyObject, options) {
18684
17441
  },
18685
17442
  () => snapshot(proxyObject)
18686
17443
  );
18687
- useLayoutEffect(() => {
17444
+ reactExports.useLayoutEffect(() => {
18688
17445
  lastSnapshot.current = currSnapshot;
18689
17446
  });
18690
17447
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
18691
17448
  condUseAffectedDebugValue(currSnapshot, affected);
18692
17449
  }
18693
- const proxyCache = useMemo(() => /* @__PURE__ */ new WeakMap(), []);
17450
+ const proxyCache = reactExports.useMemo(() => /* @__PURE__ */ new WeakMap(), []);
18694
17451
  return createProxy(currSnapshot, affected, proxyCache, targetCache);
18695
17452
  }
18696
17453
 
@@ -18947,14 +17704,7 @@ function subscribeKey(proxyObject, key, callback, notifyInSync) {
18947
17704
  }
18948
17705
 
18949
17706
  let currentCleanups;
18950
- let didWarnDeprecation = false;
18951
17707
  function watch(callback, options) {
18952
- if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && !didWarnDeprecation) {
18953
- console.warn(
18954
- "[DEPRECATED] The `watch` util is no longer maintained. Please migrate to [valtio-reactive](https://github.com/valtiojs/valtio-reactive)."
18955
- );
18956
- didWarnDeprecation = true;
18957
- }
18958
17708
  let alive = true;
18959
17709
  const cleanups = /* @__PURE__ */ new Set();
18960
17710
  const subscriptions = /* @__PURE__ */ new Map();
@@ -19010,7 +17760,7 @@ function watch(callback, options) {
19010
17760
  return cleanup;
19011
17761
  }
19012
17762
 
19013
- const DEVTOOLS = /* @__PURE__ */ Symbol();
17763
+ const DEVTOOLS = Symbol();
19014
17764
  function devtools(proxyObject, options) {
19015
17765
  const { enabled, name = "", ...rest } = options || {};
19016
17766
  let extension;
@@ -19024,11 +17774,10 @@ function devtools(proxyObject, options) {
19024
17774
  }
19025
17775
  return;
19026
17776
  }
19027
- unstable_enableOp();
19028
17777
  let isTimeTraveling = false;
19029
17778
  const devtools2 = extension.connect({ name, ...rest });
19030
- const unsub1 = subscribe(proxyObject, (unstable_ops) => {
19031
- const action = unstable_ops.filter(([_, path]) => path[0] !== DEVTOOLS).map(([op, path]) => `${op}:${path.map(String).join(".")}`).join(", ");
17779
+ const unsub1 = subscribe(proxyObject, (ops) => {
17780
+ const action = ops.filter(([_, path]) => path[0] !== DEVTOOLS).map(([op, path]) => `${op}:${path.map(String).join(".")}`).join(", ");
19032
17781
  if (!action) {
19033
17782
  return;
19034
17783
  }
@@ -19089,12 +17838,12 @@ function devtools(proxyObject, options) {
19089
17838
  };
19090
17839
  }
19091
17840
 
19092
- const DUMMY_SYMBOL = /* @__PURE__ */ Symbol();
17841
+ const DUMMY_SYMBOL = Symbol();
19093
17842
  function useProxy(proxy, options) {
19094
17843
  const snapshot = useSnapshot(proxy, options);
19095
17844
  snapshot[DUMMY_SYMBOL];
19096
17845
  let isRendering = true;
19097
- useLayoutEffect(() => {
17846
+ reactExports.useLayoutEffect(() => {
19098
17847
  isRendering = false;
19099
17848
  });
19100
17849
  return new Proxy(proxy, {
@@ -19104,5 +17853,5 @@ function useProxy(proxy, options) {
19104
17853
  });
19105
17854
  }
19106
17855
 
19107
- export { KokimokiClient, KokimokiStore, derive, devtools, getKmEnv, proxy, ref, snapshot, subscribe, subscribeKey, underive, useProxy, useSnapshot, watch };
17856
+ export { KokimokiClient, KokimokiStore, derive, devtools, proxy, ref, snapshot, subscribe, subscribeKey, underive, useProxy, useSnapshot, watch };
19108
17857
  //# sourceMappingURL=kokimoki.min.js.map