@antha/util 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # @antha/util
2
+
3
+ Utilities for game development with Antha, though not necessarily specific to or needed by Antha.
4
+
5
+ Includes:
6
+
7
+ - stabilized, seeded random functions
8
+ - stabilized Math operations through rounding
9
+
10
+ - Demo: https://electrovir.github.io/antha/demo
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm i @antha/util
16
+ ```
@@ -0,0 +1,4 @@
1
+ export * from './listen-to-object.js';
2
+ export * from './stable-math.js';
3
+ export * from './stable-random.js';
4
+ export * from './throttle-log.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './listen-to-object.js';
2
+ export * from './stable-math.js';
3
+ export * from './stable-random.js';
4
+ export * from './throttle-log.js';
@@ -0,0 +1,10 @@
1
+ import { type AnyObject, type MaybePromise } from '@augment-vir/common';
2
+ /**
3
+ * Listen to sets on a specific object key. Note that this does not trigger on:
4
+ *
5
+ * - Mutations of anything at the given key
6
+ * - Deletions of the given key
7
+ *
8
+ * @category Util
9
+ */
10
+ export declare function listenToObject<const Original extends AnyObject, const Key extends keyof Original>(original: Original, key: Key, listener: (this: void, value: Original[Key]) => MaybePromise<void>): (this: void) => void;
@@ -0,0 +1,45 @@
1
+ import { getOrSetFromMap } from '@augment-vir/common';
2
+ const registry = new WeakMap();
3
+ /**
4
+ * Listen to sets on a specific object key. Note that this does not trigger on:
5
+ *
6
+ * - Mutations of anything at the given key
7
+ * - Deletions of the given key
8
+ *
9
+ * @category Util
10
+ */
11
+ export function listenToObject(original, key, listener) {
12
+ const registryEntry = getOrSetFromMap(registry, original, () => {
13
+ return {};
14
+ });
15
+ /** Fix the internal type of {@link key}. */
16
+ const actualKey = key;
17
+ if (!registryEntry[actualKey]) {
18
+ registryEntry[actualKey] = new Set();
19
+ let currentValue = original[actualKey];
20
+ Object.defineProperty(original, actualKey, {
21
+ get() {
22
+ return currentValue;
23
+ },
24
+ set(newValue) {
25
+ currentValue = newValue;
26
+ registryEntry[actualKey]?.forEach((listener) => {
27
+ void listener(newValue);
28
+ });
29
+ },
30
+ configurable: true,
31
+ });
32
+ }
33
+ registryEntry[actualKey].add(listener);
34
+ return function removeListener() {
35
+ if (registryEntry[actualKey]) {
36
+ registryEntry[actualKey].delete(listener);
37
+ if (!registryEntry[actualKey].size) {
38
+ delete registryEntry[actualKey];
39
+ }
40
+ if (!Object.keys(registryEntry).length) {
41
+ registry.delete(original);
42
+ }
43
+ }
44
+ };
45
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Number of decimal places used by default to normalize floating-point math results.
3
+ *
4
+ * @category Internal
5
+ */
6
+ export declare const defaultStableMathDigits = 12;
7
+ /**
8
+ * Options for stable math helpers.
9
+ *
10
+ * @category Antha Util
11
+ */
12
+ export type StableMathOptions = {
13
+ /**
14
+ * Number of digits to round all values to.
15
+ *
16
+ * @default 12
17
+ */
18
+ digits?: number | undefined;
19
+ };
20
+ /**
21
+ * Stable, rounded math variants of `Math` object.
22
+ *
23
+ * @category Antha Util
24
+ */
25
+ export declare const StableMath: {
26
+ /**
27
+ * Stable wrapper for `Math.acos`.
28
+ *
29
+ * @category Math
30
+ */
31
+ acos(value: number, options?: Readonly<StableMathOptions> | undefined): number;
32
+ /**
33
+ * Stable wrapper for `Math.asin`.
34
+ *
35
+ * @category Math
36
+ */
37
+ asin(value: number, options?: Readonly<StableMathOptions> | undefined): number;
38
+ /**
39
+ * Stable wrapper for `Math.atan`.
40
+ *
41
+ * @category Math
42
+ */
43
+ atan(value: number, options?: Readonly<StableMathOptions> | undefined): number;
44
+ /**
45
+ * Stable wrapper for `Math.atan2`.
46
+ *
47
+ * @category Math
48
+ */
49
+ atan2({ y, x, options, }: Readonly<{
50
+ y: number;
51
+ x: number;
52
+ options?: Readonly<StableMathOptions> | undefined;
53
+ }>): number;
54
+ /**
55
+ * Stable wrapper for `Math.cos`.
56
+ *
57
+ * @category Math
58
+ */
59
+ cos(radians: number, options?: Readonly<StableMathOptions> | undefined): number;
60
+ /**
61
+ * Convert degrees to radians with stable rounding.
62
+ *
63
+ * @category Math
64
+ */
65
+ degreesToRadians(degrees: number, options?: Readonly<StableMathOptions> | undefined): number;
66
+ /**
67
+ * Stable wrapper for `Math.hypot`.
68
+ *
69
+ * @category Math
70
+ */
71
+ hypot(values: ReadonlyArray<number>, options?: Readonly<StableMathOptions> | undefined): number;
72
+ /**
73
+ * Convert radians to degrees with stable rounding.
74
+ *
75
+ * @category Math
76
+ */
77
+ radiansToDegrees(radians: number, options?: Readonly<StableMathOptions> | undefined): number;
78
+ /**
79
+ * Round a number to a stable number of digits.
80
+ *
81
+ * @category Math
82
+ */
83
+ round(value: number, { digits }?: Readonly<StableMathOptions>): number;
84
+ /**
85
+ * Stable wrapper for `Math.sin`.
86
+ *
87
+ * @category Math
88
+ */
89
+ sin(radians: number, options?: Readonly<StableMathOptions> | undefined): number;
90
+ /**
91
+ * Stable wrapper for `Math.sqrt`.
92
+ *
93
+ * @category Math
94
+ */
95
+ sqrt(value: number, options?: Readonly<StableMathOptions> | undefined): number;
96
+ /**
97
+ * Stable wrapper for `Math.tan`.
98
+ *
99
+ * @category Math
100
+ */
101
+ tan(radians: number, options?: Readonly<StableMathOptions> | undefined): number;
102
+ };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Number of decimal places used by default to normalize floating-point math results.
3
+ *
4
+ * @category Internal
5
+ */
6
+ export const defaultStableMathDigits = 12;
7
+ /**
8
+ * Stable, rounded math variants of `Math` object.
9
+ *
10
+ * @category Antha Util
11
+ */
12
+ export const StableMath = {
13
+ /**
14
+ * Stable wrapper for `Math.acos`.
15
+ *
16
+ * @category Math
17
+ */
18
+ acos(value, options) {
19
+ return StableMath.round(Math.acos(value), options);
20
+ },
21
+ /**
22
+ * Stable wrapper for `Math.asin`.
23
+ *
24
+ * @category Math
25
+ */
26
+ asin(value, options) {
27
+ return StableMath.round(Math.asin(value), options);
28
+ },
29
+ /**
30
+ * Stable wrapper for `Math.atan`.
31
+ *
32
+ * @category Math
33
+ */
34
+ atan(value, options) {
35
+ return StableMath.round(Math.atan(value), options);
36
+ },
37
+ /**
38
+ * Stable wrapper for `Math.atan2`.
39
+ *
40
+ * @category Math
41
+ */
42
+ atan2({ y, x, options, }) {
43
+ return StableMath.round(Math.atan2(y, x), options);
44
+ },
45
+ /**
46
+ * Stable wrapper for `Math.cos`.
47
+ *
48
+ * @category Math
49
+ */
50
+ cos(radians, options) {
51
+ return StableMath.round(Math.cos(radians), options);
52
+ },
53
+ /**
54
+ * Convert degrees to radians with stable rounding.
55
+ *
56
+ * @category Math
57
+ */
58
+ degreesToRadians(degrees, options) {
59
+ return StableMath.round((Math.PI * degrees) / 180, options);
60
+ },
61
+ /**
62
+ * Stable wrapper for `Math.hypot`.
63
+ *
64
+ * @category Math
65
+ */
66
+ hypot(values, options) {
67
+ return StableMath.round(Math.hypot(...values), options);
68
+ },
69
+ /**
70
+ * Convert radians to degrees with stable rounding.
71
+ *
72
+ * @category Math
73
+ */
74
+ radiansToDegrees(radians, options) {
75
+ return StableMath.round((radians * 180) / Math.PI, options);
76
+ },
77
+ /**
78
+ * Round a number to a stable number of digits.
79
+ *
80
+ * @category Math
81
+ */
82
+ round(value, { digits = defaultStableMathDigits } = {}) {
83
+ if (!Number.isFinite(value)) {
84
+ return value;
85
+ }
86
+ const multiplier = 10 ** digits;
87
+ return Math.round((value + Number.EPSILON) * multiplier) / multiplier;
88
+ },
89
+ /**
90
+ * Stable wrapper for `Math.sin`.
91
+ *
92
+ * @category Math
93
+ */
94
+ sin(radians, options) {
95
+ return StableMath.round(Math.sin(radians), options);
96
+ },
97
+ /**
98
+ * Stable wrapper for `Math.sqrt`.
99
+ *
100
+ * @category Math
101
+ */
102
+ sqrt(value, options) {
103
+ return StableMath.round(Math.sqrt(value), options);
104
+ },
105
+ /**
106
+ * Stable wrapper for `Math.tan`.
107
+ *
108
+ * @category Math
109
+ */
110
+ tan(radians, options) {
111
+ return StableMath.round(Math.tan(radians), options);
112
+ },
113
+ };
@@ -0,0 +1,39 @@
1
+ import { SeededRandom, type SeededRandomState } from '@augment-vir/common';
2
+ export { SeededRandom } from '@augment-vir/common';
3
+ /**
4
+ * Create a deterministic pseudo-random generator from a seed.
5
+ *
6
+ * @category Random
7
+ */
8
+ export declare function createStableRandom(seed: string | number): SeededRandom;
9
+ /**
10
+ * Recreate a deterministic pseudo-random generator from exported state.
11
+ *
12
+ * @category Random
13
+ */
14
+ export declare function createStableRandomFromState(state: Readonly<SeededRandomState>): SeededRandom;
15
+ /**
16
+ * Generate the next deterministic pseudo-random number.
17
+ *
18
+ * @category Random
19
+ */
20
+ export declare function stableRandom(random: Readonly<SeededRandom>): number;
21
+ /**
22
+ * Generate a deterministic pseudo-random integer between `min` and `max`, inclusive.
23
+ *
24
+ * @category Random
25
+ */
26
+ export declare function stableRandomInteger({ random, min, max, }: Readonly<{
27
+ random: Readonly<SeededRandom>;
28
+ min: number;
29
+ max: number;
30
+ }>): number;
31
+ /**
32
+ * Generate a deterministic pseudo-random boolean at the given percent chance.
33
+ *
34
+ * @category Random
35
+ */
36
+ export declare function stableRandomBoolean({ random, percentLikelyToBeTrue, }: Readonly<{
37
+ random: Readonly<SeededRandom>;
38
+ percentLikelyToBeTrue?: number | undefined;
39
+ }>): boolean;
@@ -0,0 +1,54 @@
1
+ import { clamp, SeededRandom } from '@augment-vir/common';
2
+ export { SeededRandom } from '@augment-vir/common';
3
+ /**
4
+ * Create a deterministic pseudo-random generator from a seed.
5
+ *
6
+ * @category Random
7
+ */
8
+ export function createStableRandom(seed) {
9
+ return SeededRandom.fromSeed(seed);
10
+ }
11
+ /**
12
+ * Recreate a deterministic pseudo-random generator from exported state.
13
+ *
14
+ * @category Random
15
+ */
16
+ export function createStableRandomFromState(state) {
17
+ return SeededRandom.fromState([
18
+ ...state,
19
+ ]);
20
+ }
21
+ /**
22
+ * Generate the next deterministic pseudo-random number.
23
+ *
24
+ * @category Random
25
+ */
26
+ export function stableRandom(random) {
27
+ return random.next();
28
+ }
29
+ /**
30
+ * Generate a deterministic pseudo-random integer between `min` and `max`, inclusive.
31
+ *
32
+ * @category Random
33
+ */
34
+ export function stableRandomInteger({ random, min, max, }) {
35
+ const integerMin = Math.ceil(min);
36
+ const integerMax = Math.floor(max);
37
+ return Math.floor(random.next() * (integerMax - integerMin + 1)) + integerMin;
38
+ }
39
+ /**
40
+ * Generate a deterministic pseudo-random boolean at the given percent chance.
41
+ *
42
+ * @category Random
43
+ */
44
+ export function stableRandomBoolean({ random, percentLikelyToBeTrue = 50, }) {
45
+ return (stableRandomInteger({
46
+ random,
47
+ min: 0,
48
+ max: 99,
49
+ }) <
50
+ clamp(Math.floor(percentLikelyToBeTrue), {
51
+ min: 0,
52
+ max: 100,
53
+ }));
54
+ }
@@ -0,0 +1,62 @@
1
+ import { type Logger, type PartialWithUndefined } from '@augment-vir/common';
2
+ import { type AnyDuration, type FullDate, type UtcTimezone } from 'date-vir';
3
+ import { FuzzyIndex, type FuzzyIndexKey } from 'fuzzy-vir';
4
+ /** @category Internal */
5
+ export type ThrottleLogCacheEntry = {
6
+ intervalCount: number;
7
+ intervalStartAt: FullDate<UtcTimezone>;
8
+ };
9
+ /** @category Internal */
10
+ export declare const throttleLogCache: Map<FuzzyIndexKey, ThrottleLogCacheEntry>;
11
+ /** @category Internal */
12
+ export declare const fuzzyLogIndex: FuzzyIndex;
13
+ /** @category Internal */
14
+ export type ThrottleLogOptions = {
15
+ disableThrottling: boolean;
16
+ throttleInterval: AnyDuration;
17
+ };
18
+ /** @category Internal */
19
+ export declare const defaultThrottleLogOptions: ThrottleLogOptions;
20
+ /** @category Internal */
21
+ export declare enum ThrottleLogTransitionKind {
22
+ None = "none",
23
+ Started = "started",
24
+ Ended = "ended"
25
+ }
26
+ /** @category Internal */
27
+ export type ThrottleLogTransition = {
28
+ kind: ThrottleLogTransitionKind.None;
29
+ } | {
30
+ kind: ThrottleLogTransitionKind.Started;
31
+ } | {
32
+ kind: ThrottleLogTransitionKind.Ended;
33
+ suppressedCount: number;
34
+ };
35
+ /**
36
+ * Output from {@link shouldThrottleLog}.
37
+ *
38
+ * @category Internal
39
+ */
40
+ export type ThrottleLogResult = {
41
+ shouldThrottle: boolean;
42
+ logKey: string | undefined;
43
+ transition: ThrottleLogTransition;
44
+ };
45
+ /** @category Internal */
46
+ export declare function clearThrottleLogCache(): void;
47
+ /** @category Internal */
48
+ export declare function shouldThrottleLog(logMessage: string, throttleOptions?: Readonly<PartialWithUndefined<ThrottleLogOptions>>): ThrottleLogResult;
49
+ /**
50
+ * Create a custom throttle logger.
51
+ *
52
+ * @category Internal
53
+ */
54
+ export declare function createThrottleLog({ logger, ...options }?: Readonly<PartialWithUndefined<{
55
+ logger: Logger;
56
+ } & ThrottleLogOptions>>): Logger;
57
+ /**
58
+ * A logger that throttles logs so you can put logs in every frame without blowing up your console.
59
+ *
60
+ * @category Util
61
+ */
62
+ export declare const throttleLog: Logger;
@@ -0,0 +1,118 @@
1
+ import { defaultLoggerOptions, emptyLog, getOrSetFromMap, log, LogColorKey, mapEnumToObject, mergeDefinedProperties, toLogString, } from '@augment-vir/common';
2
+ import { calculateRelativeDate, getNowInUtcTimezone, isDateAfter, } from 'date-vir';
3
+ import { FuzzyIndex } from 'fuzzy-vir';
4
+ /** @category Internal */
5
+ export const throttleLogCache = new Map();
6
+ /** @category Internal */
7
+ export const fuzzyLogIndex = new FuzzyIndex({
8
+ onEvict(logKey) {
9
+ throttleLogCache.delete(logKey);
10
+ },
11
+ });
12
+ /** @category Internal */
13
+ export const defaultThrottleLogOptions = {
14
+ disableThrottling: false,
15
+ throttleInterval: {
16
+ seconds: 5,
17
+ },
18
+ };
19
+ /** @category Internal */
20
+ export var ThrottleLogTransitionKind;
21
+ (function (ThrottleLogTransitionKind) {
22
+ ThrottleLogTransitionKind["None"] = "none";
23
+ ThrottleLogTransitionKind["Started"] = "started";
24
+ ThrottleLogTransitionKind["Ended"] = "ended";
25
+ })(ThrottleLogTransitionKind || (ThrottleLogTransitionKind = {}));
26
+ /** @category Internal */
27
+ export function clearThrottleLogCache() {
28
+ throttleLogCache.clear();
29
+ fuzzyLogIndex.destroy();
30
+ }
31
+ const throttleLogStringOptions = {
32
+ ...defaultLoggerOptions,
33
+ omitColors: true,
34
+ };
35
+ /** @category Internal */
36
+ export function shouldThrottleLog(logMessage, throttleOptions = {}) {
37
+ const options = mergeDefinedProperties(defaultThrottleLogOptions, throttleOptions);
38
+ if (options.disableThrottling) {
39
+ return {
40
+ shouldThrottle: false,
41
+ logKey: undefined,
42
+ transition: {
43
+ kind: ThrottleLogTransitionKind.None,
44
+ },
45
+ };
46
+ }
47
+ const logKey = fuzzyLogIndex.insert(logMessage);
48
+ const now = getNowInUtcTimezone();
49
+ const logThrottleData = getOrSetFromMap(throttleLogCache, logKey, () => {
50
+ return {
51
+ intervalCount: 0,
52
+ intervalStartAt: now,
53
+ };
54
+ });
55
+ const transitionCandidates = [];
56
+ if (isDateAfter({
57
+ fullDate: now,
58
+ relativeTo: calculateRelativeDate(logThrottleData.intervalStartAt, options.throttleInterval),
59
+ })) {
60
+ const suppressedCount = logThrottleData.intervalCount - 1;
61
+ if (suppressedCount > 0) {
62
+ transitionCandidates.push({
63
+ kind: ThrottleLogTransitionKind.Ended,
64
+ suppressedCount,
65
+ });
66
+ }
67
+ logThrottleData.intervalStartAt = now;
68
+ logThrottleData.intervalCount = 0;
69
+ }
70
+ logThrottleData.intervalCount++;
71
+ const shouldThrottle = logThrottleData.intervalCount > 1;
72
+ if (shouldThrottle && logThrottleData.intervalCount === 2) {
73
+ transitionCandidates.push({
74
+ kind: ThrottleLogTransitionKind.Started,
75
+ });
76
+ }
77
+ return {
78
+ shouldThrottle,
79
+ logKey,
80
+ transition: transitionCandidates[0] || {
81
+ kind: ThrottleLogTransitionKind.None,
82
+ },
83
+ };
84
+ }
85
+ /**
86
+ * Create a custom throttle logger.
87
+ *
88
+ * @category Internal
89
+ */
90
+ export function createThrottleLog({ logger = log, ...options } = {}) {
91
+ const throttledLoggerLogs = mapEnumToObject(LogColorKey, (colorKey) => {
92
+ return (...args) => {
93
+ const throttleResult = shouldThrottleLog(createThrottleLogMessage(args), options);
94
+ if (!throttleResult.shouldThrottle) {
95
+ logger[colorKey](...args);
96
+ }
97
+ };
98
+ });
99
+ return {
100
+ ...throttledLoggerLogs,
101
+ if(condition) {
102
+ return condition ? throttledLoggerLogs : emptyLog;
103
+ },
104
+ };
105
+ }
106
+ /**
107
+ * A logger that throttles logs so you can put logs in every frame without blowing up your console.
108
+ *
109
+ * @category Util
110
+ */
111
+ export const throttleLog = createThrottleLog();
112
+ function createThrottleLogMessage(args) {
113
+ return toLogString({
114
+ args,
115
+ colorKey: LogColorKey.Plain,
116
+ options: throttleLogStringOptions,
117
+ }).text;
118
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@antha/util",
3
+ "version": "0.0.1",
4
+ "description": "Utilities for the Antha game engine.",
5
+ "keywords": [
6
+ "vir",
7
+ "antha"
8
+ ],
9
+ "homepage": "https://github.com/electrovir/antha",
10
+ "bugs": {
11
+ "url": "https://github.com/electrovir/antha/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/electrovir/antha.git"
16
+ },
17
+ "license": "(MIT OR CC0-1.0)",
18
+ "author": {
19
+ "name": "electrovir",
20
+ "url": "https://github.com/electrovir"
21
+ },
22
+ "sideEffects": false,
23
+ "type": "module",
24
+ "main": "dist/index.js",
25
+ "module": "dist/index.js",
26
+ "types": "dist/index.d.ts",
27
+ "scripts": {
28
+ "build": "virmator frontend build",
29
+ "compile": "virmator compile",
30
+ "docs": "virmator docs",
31
+ "start": "virmator frontend",
32
+ "test": "virmator test web",
33
+ "test:coverage": "npm run test coverage",
34
+ "test:docs": "virmator docs check",
35
+ "test:update": "npm test update"
36
+ },
37
+ "dependencies": {
38
+ "@augment-vir/common": "^31.73.1",
39
+ "date-vir": "^8.5.0",
40
+ "fuzzy-vir": "^0.0.2"
41
+ },
42
+ "devDependencies": {
43
+ "@augment-vir/assert": "^31.73.1",
44
+ "@augment-vir/test": "^31.73.1",
45
+ "@web/dev-server-esbuild": "^1.0.5",
46
+ "@web/test-runner": "^0.20.2",
47
+ "@web/test-runner-playwright": "^0.11.1",
48
+ "istanbul-smart-text-reporter": "^1.1.5"
49
+ },
50
+ "engines": {
51
+ "node": ">=22"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }