@absoluteui/helpers 0.0.0-stage → 0.13.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 +201 -0
- package/NOTICE +5 -0
- package/README.md +47 -2
- package/SECURITY.md +102 -0
- package/dist/array/compare.d.ts +8 -0
- package/dist/array/compare.js +2 -0
- package/dist/array/index.d.ts +328 -0
- package/dist/array/index.js +2 -0
- package/dist/array/tree.d.ts +48 -0
- package/dist/array/tree.js +2 -0
- package/dist/async/batch.d.ts +103 -0
- package/dist/async/batch.js +2 -0
- package/dist/async/concurrency.d.ts +92 -0
- package/dist/async/concurrency.js +2 -0
- package/dist/async/control.d.ts +77 -0
- package/dist/async/control.js +2 -0
- package/dist/async/index.d.ts +8 -0
- package/dist/async/index.js +2 -0
- package/dist/async/signal.d.ts +95 -0
- package/dist/async/signal.js +2 -0
- package/dist/boolean/index.d.ts +83 -0
- package/dist/boolean/index.js +2 -0
- package/dist/business-calendar/days.d.ts +397 -0
- package/dist/business-calendar/days.js +2 -0
- package/dist/business-calendar/describe.d.ts +45 -0
- package/dist/business-calendar/describe.js +2 -0
- package/dist/business-calendar/engine.d.ts +305 -0
- package/dist/business-calendar/engine.js +2 -0
- package/dist/business-calendar/hours.d.ts +96 -0
- package/dist/business-calendar/hours.js +2 -0
- package/dist/business-calendar/index.d.ts +29 -0
- package/dist/business-calendar/index.js +2 -0
- package/dist/business-calendar/internal.d.ts +44 -0
- package/dist/business-calendar/internal.js +2 -0
- package/dist/business-calendar/rules.d.ts +260 -0
- package/dist/business-calendar/rules.js +2 -0
- package/dist/color/index.d.ts +200 -0
- package/dist/color/index.js +2 -0
- package/dist/color/named.d.ts +4 -0
- package/dist/color/named.js +2 -0
- package/dist/compare/index.d.ts +186 -0
- package/dist/compare/index.js +2 -0
- package/dist/convert/index.d.ts +152 -0
- package/dist/convert/index.js +2 -0
- package/dist/csv/index.d.ts +6 -0
- package/dist/csv/index.js +2 -0
- package/dist/csv/parse.d.ts +85 -0
- package/dist/csv/parse.js +12 -0
- package/dist/csv/stringify.d.ts +48 -0
- package/dist/csv/stringify.js +5 -0
- package/dist/date/calendar.d.ts +339 -0
- package/dist/date/calendar.js +2 -0
- package/dist/date/format.d.ts +66 -0
- package/dist/date/format.js +2 -0
- package/dist/date/index.d.ts +26 -0
- package/dist/date/index.js +2 -0
- package/dist/date/intervals.d.ts +110 -0
- package/dist/date/intervals.js +2 -0
- package/dist/date/intl-cache.d.ts +10 -0
- package/dist/date/intl-cache.js +2 -0
- package/dist/date/locale.d.ts +58 -0
- package/dist/date/locale.js +2 -0
- package/dist/date/plain-date.d.ts +105 -0
- package/dist/date/plain-date.js +2 -0
- package/dist/date/plain-time.d.ts +121 -0
- package/dist/date/plain-time.js +2 -0
- package/dist/date/zone.d.ts +121 -0
- package/dist/date/zone.js +2 -0
- package/dist/decimal/index.d.ts +149 -0
- package/dist/decimal/index.js +2 -0
- package/dist/ds/avl.d.ts +50 -0
- package/dist/ds/avl.js +2 -0
- package/dist/ds/bitset.d.ts +46 -0
- package/dist/ds/bitset.js +2 -0
- package/dist/ds/bloom.d.ts +41 -0
- package/dist/ds/bloom.js +2 -0
- package/dist/ds/caches.d.ts +141 -0
- package/dist/ds/caches.js +2 -0
- package/dist/ds/disjoint-set.d.ts +38 -0
- package/dist/ds/disjoint-set.js +2 -0
- package/dist/ds/emitter.d.ts +53 -0
- package/dist/ds/emitter.js +2 -0
- package/dist/ds/graph.d.ts +84 -0
- package/dist/ds/graph.js +2 -0
- package/dist/ds/heap.d.ts +49 -0
- package/dist/ds/heap.js +2 -0
- package/dist/ds/index.d.ts +20 -0
- package/dist/ds/index.js +2 -0
- package/dist/ds/internal.d.ts +19 -0
- package/dist/ds/internal.js +2 -0
- package/dist/ds/interval-tree.d.ts +49 -0
- package/dist/ds/interval-tree.js +2 -0
- package/dist/ds/linked-list.d.ts +54 -0
- package/dist/ds/linked-list.js +2 -0
- package/dist/ds/maps.d.ts +89 -0
- package/dist/ds/maps.js +2 -0
- package/dist/ds/ring.d.ts +99 -0
- package/dist/ds/ring.js +2 -0
- package/dist/ds/sorted.d.ts +104 -0
- package/dist/ds/sorted.js +2 -0
- package/dist/ds/stack.d.ts +28 -0
- package/dist/ds/stack.js +2 -0
- package/dist/ds/trie.d.ts +84 -0
- package/dist/ds/trie.js +2 -0
- package/dist/duration/index.d.ts +146 -0
- package/dist/duration/index.js +2 -0
- package/dist/encoding/index.d.ts +144 -0
- package/dist/encoding/index.js +2 -0
- package/dist/error/index.d.ts +316 -0
- package/dist/error/index.js +2 -0
- package/dist/fn/index.d.ts +129 -0
- package/dist/fn/index.js +2 -0
- package/dist/fn/memo.d.ts +46 -0
- package/dist/fn/memo.js +2 -0
- package/dist/fn/timing.d.ts +64 -0
- package/dist/fn/timing.js +2 -0
- package/dist/http/headers.d.ts +160 -0
- package/dist/http/headers.js +2 -0
- package/dist/http/index.d.ts +10 -0
- package/dist/http/index.js +2 -0
- package/dist/http/problem.d.ts +37 -0
- package/dist/http/problem.js +2 -0
- package/dist/http/response.d.ts +43 -0
- package/dist/http/response.js +2 -0
- package/dist/http/status.d.ts +169 -0
- package/dist/http/status.js +2 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +2 -0
- package/dist/internal/keys.d.ts +6 -0
- package/dist/internal/keys.js +2 -0
- package/dist/is/index.d.ts +219 -0
- package/dist/is/index.js +2 -0
- package/dist/json/index.d.ts +9 -0
- package/dist/json/index.js +2 -0
- package/dist/json/internal.d.ts +12 -0
- package/dist/json/internal.js +2 -0
- package/dist/json/ndjson.d.ts +28 -0
- package/dist/json/ndjson.js +4 -0
- package/dist/json/parse.d.ts +45 -0
- package/dist/json/parse.js +2 -0
- package/dist/json/patch.d.ts +62 -0
- package/dist/json/patch.js +2 -0
- package/dist/json/pointer.d.ts +43 -0
- package/dist/json/pointer.js +2 -0
- package/dist/json/stringify.d.ts +42 -0
- package/dist/json/stringify.js +2 -0
- package/dist/linq/enumerable.d.ts +208 -0
- package/dist/linq/enumerable.js +2 -0
- package/dist/linq/index.d.ts +6 -0
- package/dist/linq/index.js +2 -0
- package/dist/linq/operators.d.ts +503 -0
- package/dist/linq/operators.js +2 -0
- package/dist/number/core.d.ts +164 -0
- package/dist/number/core.js +2 -0
- package/dist/number/format.d.ts +80 -0
- package/dist/number/format.js +2 -0
- package/dist/number/index.d.ts +12 -0
- package/dist/number/index.js +2 -0
- package/dist/number/internal.d.ts +18 -0
- package/dist/number/internal.js +2 -0
- package/dist/number/parse.d.ts +45 -0
- package/dist/number/parse.js +2 -0
- package/dist/number/words.d.ts +19 -0
- package/dist/number/words.js +2 -0
- package/dist/object/basic.d.ts +130 -0
- package/dist/object/basic.js +2 -0
- package/dist/object/deep.d.ts +90 -0
- package/dist/object/deep.js +2 -0
- package/dist/object/diff.d.ts +57 -0
- package/dist/object/diff.js +2 -0
- package/dist/object/index.d.ts +8 -0
- package/dist/object/index.js +2 -0
- package/dist/object/internal.d.ts +21 -0
- package/dist/object/internal.js +2 -0
- package/dist/object/path.d.ts +17 -0
- package/dist/object/path.js +2 -0
- package/dist/random/core.d.ts +14 -0
- package/dist/random/core.js +2 -0
- package/dist/random/index.d.ts +167 -0
- package/dist/random/index.js +2 -0
- package/dist/random/seeded.d.ts +27 -0
- package/dist/random/seeded.js +2 -0
- package/dist/sanitize/index.d.ts +8 -0
- package/dist/sanitize/index.js +2 -0
- package/dist/sanitize/pii.d.ts +48 -0
- package/dist/sanitize/pii.js +2 -0
- package/dist/sanitize/records.d.ts +100 -0
- package/dist/sanitize/records.js +2 -0
- package/dist/sanitize/text.d.ts +101 -0
- package/dist/sanitize/text.js +2 -0
- package/dist/set/index.d.ts +162 -0
- package/dist/set/index.js +2 -0
- package/dist/stats/index.d.ts +190 -0
- package/dist/stats/index.js +2 -0
- package/dist/string/index.d.ts +494 -0
- package/dist/string/index.js +8 -0
- package/dist/string/internal.d.ts +33 -0
- package/dist/string/internal.js +2 -0
- package/dist/string/words.d.ts +14 -0
- package/dist/string/words.js +2 -0
- package/dist/timezone/index.d.ts +76 -0
- package/dist/timezone/index.js +2 -0
- package/dist/url/index.d.ts +178 -0
- package/dist/url/index.js +2 -0
- package/dist/validate/builders.d.ts +6 -0
- package/dist/validate/builders.js +2 -0
- package/dist/validate/formats.d.ts +237 -0
- package/dist/validate/formats.js +2 -0
- package/dist/validate/index.d.ts +13 -0
- package/dist/validate/index.js +2 -0
- package/dist/validate/schema.d.ts +220 -0
- package/dist/validate/schema.js +2 -0
- package/dist/zip/index.d.ts +8 -0
- package/dist/zip/index.js +2 -0
- package/dist/zip/internal.d.ts +69 -0
- package/dist/zip/internal.js +2 -0
- package/dist/zip/reader.d.ts +56 -0
- package/dist/zip/reader.js +2 -0
- package/dist/zip/writer.d.ts +65 -0
- package/dist/zip/writer.js +2 -0
- package/package.json +150 -4
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { type DateInput, type InstantInput, type PlainDate, type PlainDateTime } from '../date/index.js';
|
|
2
|
+
import { type Disambiguation } from '../date/zone.js';
|
|
3
|
+
/** Duration field names, largest first. */
|
|
4
|
+
export type DurationUnit = 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds';
|
|
5
|
+
export type DurationFields = Readonly<Record<DurationUnit, number>>;
|
|
6
|
+
/** Immutable duration: non-negative integer fields and a sign (0 only for the zero duration). */
|
|
7
|
+
export interface Duration extends DurationFields {
|
|
8
|
+
readonly sign: -1 | 0 | 1;
|
|
9
|
+
}
|
|
10
|
+
/** Input for `duration`: any subset of fields, all >= 0 or all <= 0. */
|
|
11
|
+
export type DurationLike = Partial<DurationFields>;
|
|
12
|
+
/**
|
|
13
|
+
* Creates a validated, frozen duration. Fields must be safe integers with one sign.
|
|
14
|
+
* @example formatIsoDuration(duration({ hours: 1, minutes: 30 })) // => 'PT1H30M'
|
|
15
|
+
* @example
|
|
16
|
+
* const back = duration({ days: -2 });
|
|
17
|
+
* [back.sign, back.days]; // => [-1, 2]
|
|
18
|
+
* duration({ days: 1, hours: -1 }); // => throws HLP_DURATION_MIXED_SIGNS
|
|
19
|
+
*/
|
|
20
|
+
export declare function duration(fields: DurationLike): Duration;
|
|
21
|
+
/**
|
|
22
|
+
* Type guard for `Duration` values.
|
|
23
|
+
* @example isDuration(duration({ days: 1 })) // => true
|
|
24
|
+
*/
|
|
25
|
+
export declare function isDuration(value: unknown): value is Duration;
|
|
26
|
+
/**
|
|
27
|
+
* The same duration with the opposite sign.
|
|
28
|
+
* @example negateDuration(duration({ days: 1 })).sign // => -1
|
|
29
|
+
*/
|
|
30
|
+
export declare function negateDuration(d: Duration): Duration;
|
|
31
|
+
/**
|
|
32
|
+
* Parses an ISO 8601 duration (`P1Y2M3DT4H5M6.5S`, `PT0S`, `P2W`, `-P1D`; weeks may mix with
|
|
33
|
+
* other units per ISO 8601-2). Only seconds may be fractional, to millisecond precision
|
|
34
|
+
* (`PT0.1234S` is rejected, `PT0.123000S` accepted). Returns `undefined` for `P`, `PT`, `P1YT`, and anything else invalid.
|
|
35
|
+
* @example
|
|
36
|
+
* parseIsoDuration('PT1H30M'); // => duration({ hours: 1, minutes: 30 })
|
|
37
|
+
* parseIsoDuration('-P1D')?.sign; // => -1
|
|
38
|
+
* parseIsoDuration('PT'); // => undefined
|
|
39
|
+
*/
|
|
40
|
+
export declare function parseIsoDuration(text: string): Duration | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* ISO 8601 text for a duration; zero is `PT0S`, negative durations get a leading `-`.
|
|
43
|
+
* @example formatIsoDuration(duration({ days: 1, minutes: 5, milliseconds: 500 })) // => 'P1DT5M0.5S'
|
|
44
|
+
*/
|
|
45
|
+
export declare function formatIsoDuration(d: Duration): string;
|
|
46
|
+
/** Reference point for calendar units. A plain date/date-time uses 24-hour days; a zoned one respects DST. */
|
|
47
|
+
export type RelativeTo = DateInput | PlainDateTime | ZonedRelativeTo;
|
|
48
|
+
export interface ZonedRelativeTo {
|
|
49
|
+
readonly dateTime: DateInput | PlainDateTime;
|
|
50
|
+
readonly timeZone: string;
|
|
51
|
+
/** How `dateTime` maps to an instant if it is ambiguous or skipped. Default `'compatible'`. */
|
|
52
|
+
readonly disambiguation?: Disambiguation;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Adds a duration to a date or wall-clock date-time, calendar-aware: years and months first
|
|
56
|
+
* (month-end clamped), then weeks and days, then clock time. For a date, time units are
|
|
57
|
+
* converted to whole days (remainder dropped), as Temporal's `PlainDate#add` does.
|
|
58
|
+
* @example addDuration('2026-01-31', duration({ months: 1, days: 1 })) // => '2026-03-01'
|
|
59
|
+
*/
|
|
60
|
+
export declare function addDuration(value: PlainDateTime, d: Duration): PlainDateTime;
|
|
61
|
+
export declare function addDuration(value: DateInput, d: Duration): PlainDate;
|
|
62
|
+
/**
|
|
63
|
+
* Adds a duration to an instant in a zone, like Temporal's `ZonedDateTime#add`: calendar units
|
|
64
|
+
* move the wall-clock date (DST-aware, `compatible` disambiguation), then clock units add
|
|
65
|
+
* exact elapsed time. Returns epoch milliseconds.
|
|
66
|
+
* @example
|
|
67
|
+
* const noon = Date.UTC(2026, 2, 7, 17); // Saturday 12:00 EST, the day before clocks spring forward
|
|
68
|
+
* addDurationInZone(noon, duration({ days: 1 }), 'America/New_York'); // => Date.UTC(2026, 2, 8, 16) // Sunday 12:00 EDT, 23 h later
|
|
69
|
+
* addDurationInZone(noon, duration({ hours: 24 }), 'America/New_York'); // => Date.UTC(2026, 2, 8, 17) // exactly 24 h: 13:00 EDT
|
|
70
|
+
*/
|
|
71
|
+
export declare function addDurationInZone(instant: InstantInput, d: Duration, timeZone: string): number;
|
|
72
|
+
export interface RelativeToOptions {
|
|
73
|
+
readonly relativeTo?: RelativeTo;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Total length in milliseconds (negative for negative durations). Years or months require
|
|
77
|
+
* `relativeTo`, otherwise `HLP_DURATION_RELATIVE_TO_REQUIRED` is thrown.
|
|
78
|
+
* @example durationToMilliseconds(duration({ hours: 1, minutes: 30 })) // => 5400000
|
|
79
|
+
* @example durationToMilliseconds(duration({ days: 1 }), { relativeTo: { dateTime: '2026-03-08', timeZone: 'America/New_York' } }) // => 82800000
|
|
80
|
+
*/
|
|
81
|
+
export declare function durationToMilliseconds(d: Duration, options?: RelativeToOptions): number;
|
|
82
|
+
/** Fixed-length units usable as `largestUnit`. */
|
|
83
|
+
export type FixedUnit = 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds';
|
|
84
|
+
/**
|
|
85
|
+
* Splits milliseconds into fixed units up to `largestUnit` (default `'hours'`; days are 24 h,
|
|
86
|
+
* weeks 7 days). Fractional milliseconds are truncated.
|
|
87
|
+
* @example
|
|
88
|
+
* formatIsoDuration(millisecondsToDuration(90_061_001, { largestUnit: 'days' })); // => 'P1DT1H1M1.001S'
|
|
89
|
+
* formatIsoDuration(millisecondsToDuration(90_061_001)); // => 'PT25H1M1.001S' // default largest unit: hours
|
|
90
|
+
*/
|
|
91
|
+
export declare function millisecondsToDuration(ms: number, options?: {
|
|
92
|
+
readonly largestUnit?: FixedUnit;
|
|
93
|
+
}): Duration;
|
|
94
|
+
/**
|
|
95
|
+
* Rebalances fixed units at or below `largestUnit` (default `'hours'`): 90 minutes -> 1 h 30 min.
|
|
96
|
+
* Units above `largestUnit`, and always years and months, are kept as they are.
|
|
97
|
+
* @example
|
|
98
|
+
* formatIsoDuration(normalizeDuration(duration({ minutes: 90 }))); // => 'PT1H30M'
|
|
99
|
+
* formatIsoDuration(normalizeDuration(duration({ hours: 49 }), { largestUnit: 'days' })); // => 'P2DT1H'
|
|
100
|
+
*/
|
|
101
|
+
export declare function normalizeDuration(d: Duration, options?: {
|
|
102
|
+
readonly largestUnit?: FixedUnit;
|
|
103
|
+
}): Duration;
|
|
104
|
+
/**
|
|
105
|
+
* Orders two durations by total length (`relativeTo` is required when either has years or months).
|
|
106
|
+
* @example compareDurations(duration({ minutes: 90 }), duration({ hours: 1 })) // => 1
|
|
107
|
+
*/
|
|
108
|
+
export declare function compareDurations(a: Duration, b: Duration, options?: RelativeToOptions): -1 | 0 | 1;
|
|
109
|
+
export interface FormatDurationOptions {
|
|
110
|
+
readonly locale?: string;
|
|
111
|
+
/** `'long'` (default, spoken-friendly: "3 hours, 5 minutes"), `'short'`, `'narrow'`, or `'digital'` ("3:05:00"). */
|
|
112
|
+
readonly style?: 'long' | 'short' | 'narrow' | 'digital';
|
|
113
|
+
/** Use `Intl.DurationFormat` when present. Default true; false forces the NumberFormat/ListFormat path for identical output on every engine. */
|
|
114
|
+
readonly useNative?: boolean;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Localized duration text, spoken-friendly by default.
|
|
118
|
+
* @example formatDuration(duration({ hours: 3, minutes: 5 }), { locale: 'en' }) // => '3 hours, 5 minutes'
|
|
119
|
+
*/
|
|
120
|
+
export declare function formatDuration(d: Duration, options?: FormatDurationOptions): string;
|
|
121
|
+
export interface HumanizeOptions {
|
|
122
|
+
readonly locale?: string;
|
|
123
|
+
/** Maximum number of units shown. Default 2. */
|
|
124
|
+
readonly largestUnits?: number;
|
|
125
|
+
readonly style?: 'long' | 'short' | 'narrow';
|
|
126
|
+
/** Largest unit used. Default `'days'`. */
|
|
127
|
+
readonly largestUnit?: FixedUnit;
|
|
128
|
+
/** Smallest unit shown. Default `'seconds'`. */
|
|
129
|
+
readonly smallestUnit?: FixedUnit;
|
|
130
|
+
/** See `FormatDurationOptions.useNative`. */
|
|
131
|
+
readonly useNative?: boolean;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Approximate, human-friendly length of `ms`: the largest non-zero units, at most
|
|
135
|
+
* `largestUnits` of them, with the last one rounded half-up.
|
|
136
|
+
* @example humanizeDuration(5_430_000, { locale: 'en' }) // => '1 hour, 31 minutes'
|
|
137
|
+
*/
|
|
138
|
+
export declare function humanizeDuration(ms: number, options?: HumanizeOptions): string;
|
|
139
|
+
/**
|
|
140
|
+
* Stopwatch text `HH:MM:SS` (hours grow past 99; `.SSS` with `milliseconds: true`). Sub-unit remainders are
|
|
141
|
+
* truncated; negative values get a leading `-` unless they display as zero.
|
|
142
|
+
* @example formatClock(3_909_000) // => '01:05:09'
|
|
143
|
+
*/
|
|
144
|
+
export declare function formatClock(ms: number, options?: {
|
|
145
|
+
readonly milliseconds?: boolean;
|
|
146
|
+
}): string;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.1 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{LimitError as X,ValidationError as l}from"../error/index.js";import{addDays as v,addMonths as W,isPlainDateTime as H,plainDateTime as T,plainDateTimeToEpochMilliseconds as A,timeFromMilliseconds as Q,toPlainDate as q,fromEpochDay as B}from"../date/index.js";import{cachedIntl as J,listFormat as V,numberFormat as y}from"../date/intl-cache.js";import{instantToZoned as K,toEpochMs as Z,zonedToInstant as z}from"../date/zone.js";const w=["years","months","weeks","days","hours","minutes","seconds","milliseconds"],g=864e5,U={weeks:7*g,days:g,hours:36e5,minutes:6e4,seconds:1e3,milliseconds:1};function h(){return new X("HLP_DURATION_OUT_OF_RANGE","Duration exceeds the safe integer range.")}function N(n){let t=0;const e={years:0,months:0,weeks:0,days:0,hours:0,minutes:0,seconds:0,milliseconds:0};for(const i of w){const o=n[i]??0;if(!Number.isSafeInteger(o))throw new l("HLP_DURATION_INVALID_FIELD","Duration fields must be safe integers.",{details:{property:i}});if(o===0)continue;const r=o<0?-1:1;if(t!==0&&r!==t)throw new l("HLP_DURATION_MIXED_SIGNS","Duration fields must not mix signs.");t=r,e[i]=Math.abs(o)}return Object.freeze({...e,sign:t})}function b(n){if(typeof n!="object"||n===null)return!1;const t=n;if(t.sign!==-1&&t.sign!==0&&t.sign!==1)return!1;let e=!1;for(const i of w){const o=t[i];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)return!1;o&&(e=!0)}return e===(t.sign!==0)}function x(n){return Object.freeze({...n,sign:0-n.sign})}const G=(n,t)=>n[t]===0?0:n.sign*n[t],nn=/^([+-])?P(?:(\d{1,16})Y)?(?:(\d{1,16})M)?(?:(\d{1,16})W)?(?:(\d{1,16})D)?(?:T(?:(\d{1,16})H)?(?:(\d{1,16})M)?(?:(\d{1,16})(?:[.,](\d{1,9}))?S)?)?$/;function dn(n){if(typeof n!="string"||n.length>128)return;const t=nn.exec(n);if(!t)return;const e=t[2]!==void 0||t[3]!==void 0||t[4]!==void 0||t[5]!==void 0,i=t[6]!==void 0||t[7]!==void 0||t[8]!==void 0;if(!e&&!i||n.includes("T")&&!i)return;const o=t[9]??"";if(/[1-9]/.test(o.slice(3)))return;const r=[t[2],t[3],t[4],t[5],t[6],t[7],t[8]].map(d=>Number(d??0));if(!r.every(d=>Number.isSafeInteger(d)))return;const[s=0,a=0,u=0,f=0,p=0,F=0,_=0]=r,O=Number(o.slice(0,3).padEnd(3,"0")),I=N({years:s,months:a,weeks:u,days:f,hours:p,minutes:F,seconds:_,milliseconds:O});return t[1]==="-"?x(I):I}function mn(n){let t="";n.years&&(t+=`${String(n.years)}Y`),n.months&&(t+=`${String(n.months)}M`),n.weeks&&(t+=`${String(n.weeks)}W`),n.days&&(t+=`${String(n.days)}D`);let e="";return n.hours&&(e+=`${String(n.hours)}H`),n.minutes&&(e+=`${String(n.minutes)}M`),(n.seconds||n.milliseconds)&&(e+=`${String(n.seconds)}${n.milliseconds?`.${String(n.milliseconds).padStart(3,"0").replace(/0{1,2}$/,"")}`:""}S`),!t&&!e?"PT0S":`${n.sign<0?"-":""}P${t}${e?`T${e}`:""}`}const tn=n=>typeof n=="object"&&"timeZone"in n,j=n=>H(n)?n:T(n);function S(n){const t=n.hours*36e5+n.minutes*6e4+n.seconds*1e3+n.milliseconds;if(!Number.isSafeInteger(t))throw h();return n.sign*t}function E(n,t){const e=t.years*12+t.months,i=t.weeks*7+t.days;if(!Number.isSafeInteger(e)||!Number.isSafeInteger(i))throw h();return v(W(n,t.sign*e+0),t.sign*i+0)}function en(n,t){if(!b(t))throw new l("HLP_DURATION_INVALID","Expected a Duration.");if(H(n)){const e=E(n.date,t),i=A(T(e,n.time))+S(t),o=Math.floor(i/g);return T(B(o),Q(i-o*g))}return v(E(q(n),t),Math.trunc(S(t)/g)+0)}function on(n,t,e){if(!b(t))throw new l("HLP_DURATION_INVALID","Expected a Duration.");const i=Z(n);let o=i;if(t.years||t.months||t.weeks||t.days){const r=K(i,e);o=z(T(E(r.date,t),r.time),e)}return Z(o+S(t))}function Y(n,t={}){if(!b(n))throw new l("HLP_DURATION_INVALID","Expected a Duration.");const{relativeTo:e}=t;if(e===void 0){if(n.years||n.months)throw new l("HLP_DURATION_RELATIVE_TO_REQUIRED","Years and months need a relativeTo date.");const o=n.weeks*U.weeks+n.days*g+n.hours*36e5+n.minutes*6e4+n.seconds*1e3+n.milliseconds;if(!Number.isSafeInteger(o))throw h();return o===0?0:n.sign*o}if(tn(e)){const o=z(j(e.dateTime),e.timeZone,{disambiguation:e.disambiguation??"compatible"});return on(o,n,e.timeZone)-o+0}const i=j(e);return A(en(i,n))-A(i)+0}const c=["weeks","days","hours","minutes","seconds","milliseconds"];function R(n){if(!c.includes(n))throw new l("HLP_DURATION_INVALID_UNIT","Unsupported largest unit.")}function P(n,t){const e={weeks:0,days:0,hours:0,minutes:0,seconds:0,milliseconds:0};let i=n;for(const o of c.slice(c.indexOf(t))){const r=U[o];e[o]=Math.floor(i/r),i-=e[o]*r}return e}function Dn(n,t={}){if(!Number.isFinite(n))throw new l("HLP_DURATION_INVALID_FIELD","Milliseconds must be finite.");const e=Math.trunc(n);if(!Number.isSafeInteger(e))throw h();const i=t.largestUnit??"hours";R(i);const o=P(Math.abs(e),i),r=N(o);return e<0?x(r):r}function gn(n,t={}){if(!b(n))throw new l("HLP_DURATION_INVALID","Expected a Duration.");const e=t.largestUnit??"hours";R(e);const i=c.slice(c.indexOf(e));let o=0;for(const u of i)o+=n[u]*U[u];if(!Number.isSafeInteger(o))throw h();const r=P(o,e),s={...n};for(const u of i)s[u]=r[u];const a=N(s);return n.sign<0?x(a):a}function hn(n,t,e={}){const i=Y(n,e),o=Y(t,e);return i<o?-1:i>o?1:0}const rn={years:"year",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second",milliseconds:"millisecond"};function L(n,t,e,i){return y(e,{style:"unit",unit:rn[t],unitDisplay:i}).format(n)}function sn(n,t,e){const i=e==="digital"?"short":e,o=e==="digital"?w.slice(0,4):w,r=[];for(const s of o)n[s]&&r.push(L(r.length===0?G(n,s):n[s],s,t,i));if(e==="digital"){const s=y(t,{minimumIntegerDigits:2,useGrouping:!1}),a=n.sign<0&&r.length===0;let u=`${y(t,{useGrouping:!1}).format(a?-n.hours:n.hours)}:${s.format(n.minutes)}:${s.format(n.seconds)}`;return n.milliseconds&&(u+=`${y(t,{}).formatToParts(1.5).find(f=>f.type==="decimal")?.value??"."}${y(t,{minimumIntegerDigits:3,useGrouping:!1}).format(n.milliseconds)}`),r.push(u),V(t,{type:"unit",style:"narrow"}).format(r)}return r.length===0?L(0,"seconds",t,i):V(t,{type:"unit",style:i}).format(r)}function an(n,t={}){if(!b(n))throw new l("HLP_DURATION_INVALID","Expected a Duration.");const e=t.style??"long",{locale:i}=t,o=Intl.DurationFormat;if(o&&(t.useNative??!0)){const r=J("df",i,{style:e},()=>new o(i,{style:e}));if(n.sign===0)return e==="digital"?r.format({seconds:0}):L(0,"seconds",i,e);const s={};for(const a of w)n[a]&&(s[a]=G(n,a));return r.format(s)}return sn(n,i,e)}function pn(n,t={}){if(!Number.isFinite(n))throw new l("HLP_DURATION_INVALID_FIELD","Milliseconds must be finite.");const e=t.largestUnits??2;if(!Number.isInteger(e)||e<1||e>6)throw new l("HLP_DURATION_INVALID_UNIT","largestUnits must be an integer 1 to 6.");const i=t.largestUnit??"days",o=t.smallestUnit??"seconds";R(i),R(o);const r=c.indexOf(i),s=c.indexOf(o);if(s<r)throw new l("HLP_DURATION_INVALID_UNIT","smallestUnit is larger than largestUnit.");const a=Math.abs(Math.trunc(n));if(!Number.isSafeInteger(a))throw h();const u=P(a,i);let f=c.findIndex((m,D)=>D>=r&&u[m]>0);(f<0||f>s)&&(f=s);const p=Math.min(f+e-1,s),F=c[p]??"seconds",_=U[F],O=Math.round(a/_)*_,I=P(O,i),d=c.findIndex((m,D)=>D>=r&&I[m]>0),$={};if(d>=0)for(let m=d;m<=Math.min(d+e-1,s);m++){const D=c[m];D&&($[D]=I[D])}const M=N($),k=t.style??"long",C={style:k,...t.locale===void 0?{}:{locale:t.locale},...t.useNative===void 0?{}:{useNative:t.useNative}};return M.sign===0?L(0,o,t.locale,k):an(n<0?x(M):M,C)}function In(n,t={}){if(!Number.isFinite(n))throw new l("HLP_DURATION_INVALID_FIELD","Milliseconds must be finite.");const e=Math.floor(Math.abs(n)),i=Math.floor(e/36e5),o=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),s=(f,p=2)=>String(f).padStart(p,"0"),a=`${s(i)}:${s(o)}:${s(r)}${t.milliseconds?`.${s(e%1e3,3)}`:""}`,u=t.milliseconds?e:e-e%1e3;return n<0&&u>0?`-${a}`:a}export{en as addDuration,on as addDurationInZone,hn as compareDurations,N as duration,Y as durationToMilliseconds,In as formatClock,an as formatDuration,mn as formatIsoDuration,pn as humanizeDuration,b as isDuration,Dn as millisecondsToDuration,x as negateDuration,gn as normalizeDuration,dn as parseIsoDuration};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/** Anything that can be viewed as bytes. */
|
|
2
|
+
export type BytesLike = Uint8Array | ArrayBuffer | ArrayBufferView;
|
|
3
|
+
/** Bytes, or a string that is encoded as UTF-8 first. */
|
|
4
|
+
export type BinaryInput = BytesLike | string;
|
|
5
|
+
/**
|
|
6
|
+
* Encodes a string as UTF-8. Lone surrogates become U+FFFD.
|
|
7
|
+
* @example
|
|
8
|
+
* utf8Encode('€'); // => new Uint8Array([226, 130, 172])
|
|
9
|
+
*/
|
|
10
|
+
export declare function utf8Encode(text: string): Uint8Array<ArrayBuffer>;
|
|
11
|
+
export interface Utf8DecodeOptions {
|
|
12
|
+
/** Throw `HLP_ENCODING_INVALID_UTF8` on malformed input instead of inserting U+FFFD. Default false. */
|
|
13
|
+
readonly fatal?: boolean;
|
|
14
|
+
/** Keep a leading byte-order mark. Default false (the BOM is stripped). */
|
|
15
|
+
readonly keepBom?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Decodes UTF-8 bytes to a string.
|
|
19
|
+
* @example
|
|
20
|
+
* utf8Decode(new Uint8Array([226, 130, 172])); // => '€'
|
|
21
|
+
*/
|
|
22
|
+
export declare function utf8Decode(bytes: BytesLike, options?: Utf8DecodeOptions): string;
|
|
23
|
+
/**
|
|
24
|
+
* Base64-encodes bytes, or a string as UTF-8 (never raw `btoa`, so any Unicode is safe).
|
|
25
|
+
* @example
|
|
26
|
+
* base64Encode('héllo ✓'); // => 'aMOpbGxvIOKckw=='
|
|
27
|
+
*/
|
|
28
|
+
export declare function base64Encode(input: BinaryInput): string;
|
|
29
|
+
/**
|
|
30
|
+
* Decodes standard base64 (whitespace ignored, padding optional) to bytes.
|
|
31
|
+
* Throws `HLP_ENCODING_INVALID_BASE64` on malformed input.
|
|
32
|
+
* @example
|
|
33
|
+
* base64Decode('AQID'); // => new Uint8Array([1, 2, 3])
|
|
34
|
+
*/
|
|
35
|
+
export declare function base64Decode(text: string): Uint8Array<ArrayBuffer>;
|
|
36
|
+
/**
|
|
37
|
+
* Decodes base64 to a UTF-8 string.
|
|
38
|
+
* @example
|
|
39
|
+
* base64DecodeText('aMOpbGxvIOKckw=='); // => 'héllo ✓'
|
|
40
|
+
*/
|
|
41
|
+
export declare function base64DecodeText(text: string, options?: Utf8DecodeOptions): string;
|
|
42
|
+
/**
|
|
43
|
+
* Base64url-encodes (RFC 4648 section 5) without padding.
|
|
44
|
+
* @example
|
|
45
|
+
* base64UrlEncode(new Uint8Array([251, 255])); // => '-_8'
|
|
46
|
+
*/
|
|
47
|
+
export declare function base64UrlEncode(input: BinaryInput): string;
|
|
48
|
+
/**
|
|
49
|
+
* Decodes base64url (padding optional). Throws `HLP_ENCODING_INVALID_BASE64` on malformed input.
|
|
50
|
+
* @example
|
|
51
|
+
* base64UrlDecode('-_8'); // => new Uint8Array([251, 255])
|
|
52
|
+
*/
|
|
53
|
+
export declare function base64UrlDecode(text: string): Uint8Array<ArrayBuffer>;
|
|
54
|
+
/**
|
|
55
|
+
* Decodes base64url to a UTF-8 string.
|
|
56
|
+
* @example
|
|
57
|
+
* base64UrlDecodeText(base64UrlEncode('{"a":1}')); // => '{"a":1}'
|
|
58
|
+
*/
|
|
59
|
+
export declare function base64UrlDecodeText(text: string, options?: Utf8DecodeOptions): string;
|
|
60
|
+
export interface IsBase64Options {
|
|
61
|
+
/** Default `'base64'`. */
|
|
62
|
+
readonly alphabet?: 'base64' | 'base64url';
|
|
63
|
+
/** Require canonical `=` padding. Default false. */
|
|
64
|
+
readonly requirePadding?: boolean;
|
|
65
|
+
/** Allow ASCII whitespace. Default false. */
|
|
66
|
+
readonly allowWhitespace?: boolean;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* True when `text` is decodable base64 (strict by default: no whitespace).
|
|
70
|
+
* @example
|
|
71
|
+
* isBase64('AQID'); // => true
|
|
72
|
+
* isBase64('AQI*'); // => false
|
|
73
|
+
*/
|
|
74
|
+
export declare function isBase64(text: string, options?: IsBase64Options): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Lowercase hex encoding of bytes (or a UTF-8 string).
|
|
77
|
+
* @example
|
|
78
|
+
* hexEncode(new Uint8Array([0, 255])); // => '00ff'
|
|
79
|
+
*/
|
|
80
|
+
export declare function hexEncode(input: BinaryInput, options?: {
|
|
81
|
+
readonly uppercase?: boolean;
|
|
82
|
+
}): string;
|
|
83
|
+
/**
|
|
84
|
+
* Decodes hex (either case, even length). Throws `HLP_ENCODING_INVALID_HEX` otherwise.
|
|
85
|
+
* @example
|
|
86
|
+
* hexDecode('00FF'); // => new Uint8Array([0, 255])
|
|
87
|
+
*/
|
|
88
|
+
export declare function hexDecode(text: string): Uint8Array<ArrayBuffer>;
|
|
89
|
+
/**
|
|
90
|
+
* Byte-wise equality. Not constant-time: use the services `crypto` module to compare secrets.
|
|
91
|
+
* @example
|
|
92
|
+
* bytesEqual(new Uint8Array([1]), new Uint8Array([1])); // => true
|
|
93
|
+
*/
|
|
94
|
+
export declare function bytesEqual(a: BytesLike, b: BytesLike): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Concatenates byte arrays into a new `Uint8Array`.
|
|
97
|
+
* @example
|
|
98
|
+
* concatBytes(new Uint8Array([1]), new Uint8Array([2, 3])); // => new Uint8Array([1, 2, 3])
|
|
99
|
+
*/
|
|
100
|
+
export declare function concatBytes(...parts: readonly BytesLike[]): Uint8Array<ArrayBuffer>;
|
|
101
|
+
/**
|
|
102
|
+
* Builds a base64 `data:` URL.
|
|
103
|
+
* @example
|
|
104
|
+
* toDataUrl('hi', 'text/plain'); // => 'data:text/plain;base64,aGk='
|
|
105
|
+
*/
|
|
106
|
+
export declare function toDataUrl(input: BinaryInput, mimeType?: string): string;
|
|
107
|
+
export interface ParsedDataUrl {
|
|
108
|
+
/** Lowercased MIME type; `text/plain` when omitted. */
|
|
109
|
+
readonly mimeType: string;
|
|
110
|
+
/** Media-type parameters (for example `charset`), keys lowercased. Null-prototype object. */
|
|
111
|
+
readonly parameters: Readonly<Record<string, string>>;
|
|
112
|
+
readonly base64: boolean;
|
|
113
|
+
readonly bytes: Uint8Array<ArrayBuffer>;
|
|
114
|
+
}
|
|
115
|
+
export interface ParseDataUrlOptions {
|
|
116
|
+
/** Maximum decoded size in bytes. Default 10 MiB. Exceeding it throws `HLP_ENCODING_DATA_URL_TOO_LARGE`. */
|
|
117
|
+
readonly maxBytes?: number;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Parses a `data:` URL. Returns `undefined` when malformed; throws `LimitError` when over `maxBytes`.
|
|
121
|
+
* @example
|
|
122
|
+
* parseDataUrl('data:text/plain;charset=utf-8,hi%21')?.bytes; // => new Uint8Array([104, 105, 33]) // 'hi!'
|
|
123
|
+
*/
|
|
124
|
+
export declare function parseDataUrl(url: string, options?: ParseDataUrlOptions): ParsedDataUrl | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* CRC-32/ISO-HDLC (zlib, ZIP, PNG). Pass the previous result to continue over chunks.
|
|
127
|
+
* Returns an unsigned 32-bit integer.
|
|
128
|
+
* @example
|
|
129
|
+
* crc32('123456789'); // => 0xcbf43926
|
|
130
|
+
* crc32(' world', crc32('hello')); // => crc32('hello world') // incremental over chunks
|
|
131
|
+
*/
|
|
132
|
+
export declare function crc32(data: BinaryInput, previous?: number): number;
|
|
133
|
+
/**
|
|
134
|
+
* Adler-32 (zlib). Pass the previous result to continue over chunks (initial value 1).
|
|
135
|
+
* @example
|
|
136
|
+
* adler32('Wikipedia'); // => 0x11e60398
|
|
137
|
+
*/
|
|
138
|
+
export declare function adler32(data: BinaryInput, previous?: number): number;
|
|
139
|
+
/**
|
|
140
|
+
* FNV-1a 32-bit hash (strings are hashed as UTF-8). Non-cryptographic: use for buckets and cache keys.
|
|
141
|
+
* @example
|
|
142
|
+
* fnv1a32('a'); // => 0xe40c292c
|
|
143
|
+
*/
|
|
144
|
+
export declare function fnv1a32(data: BinaryInput, previous?: number): number;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.1 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{LimitError as x,ValidationError as d}from"../error/index.js";const D=Uint8Array,g=Uint8Array.prototype;function y(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function h(e){return typeof e=="string"?C(e):y(e)}let L;const _=new Map;function C(e){return L??=new TextEncoder,L.encode(e)}function E(e,t={}){const n=t.fatal??!1,o=y(e);if(t.keepBom===!0)try{return new TextDecoder("utf-8",{fatal:n,ignoreBOM:!0}).decode(o)}catch(a){throw new d("HLP_ENCODING_INVALID_UTF8","The bytes are not valid UTF-8.",{cause:a})}let r=_.get(n);r||(r=new TextDecoder("utf-8",{fatal:n}),_.set(n,r));try{return r.decode(o)}catch(a){throw new d("HLP_ENCODING_INVALID_UTF8","The bytes are not valid UTF-8.",{cause:a})}}const B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",N=new Map;function O(e){let t=N.get(e);if(!t){t=new Int16Array(128).fill(-1);for(let n=0;n<64;n++)t[e.charCodeAt(n)]=n;N.set(e,t)}return t}function T(e,t,n){if(g.toBase64)return g.toBase64.call(e,{alphabet:t?"base64url":"base64",omitPadding:!n});const o=t?U:B,r=[];let a="";const s=e.length;let i=0;for(;i+2<s;i+=3){const f=(e[i]??0)<<16|(e[i+1]??0)<<8|(e[i+2]??0);a+=o.charAt(f>>>18)+o.charAt(f>>>12&63)+o.charAt(f>>>6&63)+o.charAt(f&63),a.length>=8192&&(r.push(a),a="")}const c=s-i;if(c===1){const f=(e[i]??0)<<16;a+=o.charAt(f>>>18)+o.charAt(f>>>12&63)+(n?"==":"")}else if(c===2){const f=(e[i]??0)<<16|(e[i+1]??0)<<8;a+=o.charAt(f>>>18)+o.charAt(f>>>12&63)+o.charAt(f>>>6&63)+(n?"=":"")}return r.push(a),r.join("")}const w=e=>e===32||e===9||e===10||e===12||e===13;function p(e,t){const n=O(t?U:B);let o="",r=0;for(let s=0;s<e.length;s++){const i=e.charCodeAt(s);if(!w(i)){if(i===61){r++;continue}if(r>0||i>127||(n[i]??-1)<0)return;o+=e.charAt(s)}}if(o.length%4!==1&&!(r>0&&(r>2||(o.length+r)%4!==0)))return o}function I(e,t){if(D.fromBase64)return D.fromBase64(e,{alphabet:t?"base64url":"base64"});const n=O(t?U:B),o=e.length,r=new Uint8Array(Math.floor(o*3/4));let a=0,s=0,i=0;for(let c=0;c<o;c++)s=s<<6|(n[e.charCodeAt(c)]??0),i+=6,i>=8&&(i-=8,r[a++]=s>>>i&255),s&=255;return r}function k(e){return T(h(e),!1,!0)}function R(e){const t=p(e,!1);if(t===void 0)throw new d("HLP_ENCODING_INVALID_BASE64","The input is not valid base64.");return I(t,!1)}function F(e,t={}){return E(R(e),t)}function S(e){return T(h(e),!0,!1)}function M(e){const t=p(e,!0);if(t===void 0)throw new d("HLP_ENCODING_INVALID_BASE64","The input is not valid base64url.");return I(t,!0)}function j(e,t={}){return E(M(e),t)}function z(e,t={}){const n=t.alphabet==="base64url";if(t.allowWhitespace!==!0){for(let r=0;r<e.length;r++)if(w(e.charCodeAt(r)))return!1}if(p(e,n)===void 0)return!1;if(t.requirePadding===!0){let r=0;for(let a=0;a<e.length;a++)w(e.charCodeAt(a))||r++;return r%4===0}return!0}const P="0123456789abcdef";function W(e,t={}){const n=h(e);let o;if(g.toHex)o=g.toHex.call(n);else{const r=new Array(n.length);for(let a=0;a<n.length;a++){const s=n[a]??0;r[a]=P.charAt(s>>>4)+P.charAt(s&15)}o=r.join("")}return t.uppercase===!0?o.toUpperCase():o}function b(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e>=65&&e<=70?e-55:-1}function X(e){if(e.length%2!==0)throw new d("HLP_ENCODING_INVALID_HEX","The input is not valid hex.");const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const o=b(e.charCodeAt(2*n)),r=b(e.charCodeAt(2*n+1));if(o<0||r<0)throw new d("HLP_ENCODING_INVALID_HEX","The input is not valid hex.");t[n]=o<<4|r}return t}function $(e,t){const n=y(e),o=y(t);if(n.length!==o.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!==o[r])return!1;return!0}function J(...e){const t=e.map(y);let n=0;for(const a of t)n+=a.length;const o=new Uint8Array(n);let r=0;for(const a of t)o.set(a,r),r+=a.length;return o}const v=/^[\w!#$%&'*+.^`|~-]+\/[\w!#$%&'*+.^`|~-]+$/;function K(e,t="application/octet-stream"){if(t.length>255||!v.test(t))throw new d("HLP_ENCODING_INVALID_MIME","The MIME type is not valid.");return`data:${t.toLowerCase()};base64,${k(e)}`}function Q(e,t={}){const n=t.maxBytes??10485760;if(e.length>n*3+1024)throw new x("HLP_ENCODING_DATA_URL_TOO_LARGE","The data URL exceeds the size limit.");const o=e.trim();if(o.slice(0,5).toLowerCase()!=="data:")return;const r=o.indexOf(",");if(r<0)return;const a=o.slice(5,r).split(";").map(l=>l.trim()),s=o.slice(r+1);let i=!1;a.length>1&&a[a.length-1]?.toLowerCase()==="base64"&&(i=!0,a.pop());const c=(a.shift()??"").toLowerCase();if(c!==""&&(c.length>255||!v.test(c)))return;const f=Object.create(null);for(const l of a){const u=l.indexOf("=");if(u<=0)continue;const H=l.slice(0,u).trim().toLowerCase();f[H]=l.slice(u+1).trim()}c===""&&!("charset"in f)&&(f.charset="US-ASCII");let A;if(i){let l;try{l=decodeURIComponent(s)}catch{return}const u=p(l,!1);if(u===void 0)return;if(Math.floor(u.length*3/4)>n)throw new x("HLP_ENCODING_DATA_URL_TOO_LARGE","The data URL exceeds the size limit.");A=I(u,!1)}else if(A=G(s),A.length>n)throw new x("HLP_ENCODING_DATA_URL_TOO_LARGE","The data URL exceeds the size limit.");return{mimeType:c===""?"text/plain":c,parameters:f,base64:i,bytes:A}}function G(e){const t=C(e),n=new Uint8Array(t.length);let o=0;for(let r=0;r<t.length;r++){const a=t[r]??0;if(a===37&&r+2<t.length){const s=b(t[r+1]??0),i=b(t[r+2]??0);if(s>=0&&i>=0){n[o++]=s<<4|i,r+=2;continue}}n[o++]=a}return n.slice(0,o)}let m;function V(){if(m)return m;const e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let o=0;o<8;o++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return m=e,e}function Y(e,t=0){const n=V(),o=h(e);let r=(t^4294967295)>>>0;for(const a of o)r=(n[(r^a)&255]??0)^r>>>8;return(r^4294967295)>>>0}function Z(e,t=1){const n=h(e);let o=t&65535,r=t>>>16&65535;const a=65521;for(let s=0;s<n.length;){const i=Math.min(s+5552,n.length);for(;s<i;s++)o+=n[s]??0,r+=o;o%=a,r%=a}return(r<<16|o)>>>0}function ee(e,t=2166136261){const n=h(e);let o=t>>>0;for(const r of n)o^=r,o=Math.imul(o,16777619)>>>0;return o}export{Z as adler32,R as base64Decode,F as base64DecodeText,k as base64Encode,M as base64UrlDecode,j as base64UrlDecodeText,S as base64UrlEncode,$ as bytesEqual,J as concatBytes,Y as crc32,ee as fnv1a32,X as hexDecode,W as hexEncode,z as isBase64,Q as parseDataUrl,K as toDataUrl,E as utf8Decode,C as utf8Encode};
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error model for helpers and services (docs/PLAN-HELPERS.md section 2, section 5).
|
|
3
|
+
* Messages never contain user-supplied values; put data in `details` only when it is safe.
|
|
4
|
+
*/
|
|
5
|
+
/** Stable error category used for mapping errors to UI and HTTP responses. */
|
|
6
|
+
export type ErrorKind = 'validation' | 'not-found' | 'conflict' | 'http' | 'timeout' | 'aborted' | 'unauthorized' | 'forbidden' | 'unsupported' | 'limit' | 'internal';
|
|
7
|
+
export interface HelperErrorOptions {
|
|
8
|
+
/** Underlying error (ES2022 `cause`). */
|
|
9
|
+
readonly cause?: unknown;
|
|
10
|
+
/** Structured, non-sensitive context. Never include secrets or raw user input. */
|
|
11
|
+
readonly details?: Readonly<Record<string, unknown>>;
|
|
12
|
+
/** Field-level messages keyed by field path, for form error summaries. */
|
|
13
|
+
readonly fields?: Readonly<Record<string, string>>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Base error with a stable machine-readable `code`.
|
|
17
|
+
* @example
|
|
18
|
+
* const e = new HelperError('HLP_JSON_TOO_DEEP', 'JSON nesting exceeds the limit.', { kind: 'limit' });
|
|
19
|
+
* e.code; // => 'HLP_JSON_TOO_DEEP'
|
|
20
|
+
* e.kind; // => 'limit'
|
|
21
|
+
* e instanceof Error; // => true
|
|
22
|
+
*/
|
|
23
|
+
export declare class HelperError extends Error {
|
|
24
|
+
name: string;
|
|
25
|
+
readonly code: string;
|
|
26
|
+
readonly kind: ErrorKind;
|
|
27
|
+
readonly details: Readonly<Record<string, unknown>>;
|
|
28
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
29
|
+
constructor(code: string, message: string, options?: HelperErrorOptions & {
|
|
30
|
+
readonly kind?: ErrorKind;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Input failed validation. `fields` maps field paths to messages.
|
|
35
|
+
* @example
|
|
36
|
+
* const e = new ValidationError('HRM_EMP_INVALID', 'Fix the highlighted fields.', { fields: { email: 'Enter a valid email address.' } });
|
|
37
|
+
* e.kind; // => 'validation'
|
|
38
|
+
* e.fields; // => { email: 'Enter a valid email address.' }
|
|
39
|
+
*/
|
|
40
|
+
export declare class ValidationError extends HelperError {
|
|
41
|
+
name: string;
|
|
42
|
+
constructor(code: string, message: string, options?: HelperErrorOptions);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* @example
|
|
46
|
+
* new NotFoundError('HRM_EMP_NOT_FOUND', 'Employee not found.').kind; // => 'not-found'
|
|
47
|
+
*/
|
|
48
|
+
export declare class NotFoundError extends HelperError {
|
|
49
|
+
name: string;
|
|
50
|
+
constructor(code: string, message: string, options?: HelperErrorOptions);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* @example
|
|
54
|
+
* new ConflictError('HRM_EMP_VERSION', 'The record was changed by someone else.').kind; // => 'conflict'
|
|
55
|
+
*/
|
|
56
|
+
export declare class ConflictError extends HelperError {
|
|
57
|
+
name: string;
|
|
58
|
+
constructor(code: string, message: string, options?: HelperErrorOptions);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* @example
|
|
62
|
+
* const e = new TimeoutError();
|
|
63
|
+
* [e.code, e.kind, e.message]; // => ['HLP_TIMEOUT', 'timeout', 'The operation timed out.']
|
|
64
|
+
*/
|
|
65
|
+
export declare class TimeoutError extends HelperError {
|
|
66
|
+
name: string;
|
|
67
|
+
constructor(code?: string, message?: string, options?: HelperErrorOptions);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* @example
|
|
71
|
+
* const e = new AbortError();
|
|
72
|
+
* e.code; // => 'HLP_ABORTED'
|
|
73
|
+
* isAbortError(e); // => true
|
|
74
|
+
*/
|
|
75
|
+
export declare class AbortError extends HelperError {
|
|
76
|
+
name: string;
|
|
77
|
+
constructor(code?: string, message?: string, options?: HelperErrorOptions);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A limit (size, depth, count, quota) was exceeded.
|
|
81
|
+
* @example
|
|
82
|
+
* const e = new LimitError('HRM_IMPORT_TOO_LARGE', 'The import has too many rows.', { details: { max: 10000 } });
|
|
83
|
+
* [e.kind, e.details]; // => ['limit', { max: 10000 }]
|
|
84
|
+
*/
|
|
85
|
+
export declare class LimitError extends HelperError {
|
|
86
|
+
name: string;
|
|
87
|
+
constructor(code: string, message: string, options?: HelperErrorOptions);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Why an HTTP call failed, for choosing a message, a retry, or a sign-in flow. `client` covers
|
|
91
|
+
* the 4xx statuses without a more specific category.
|
|
92
|
+
*/
|
|
93
|
+
export type HttpFailureCategory = 'network' | 'offline' | 'timeout' | 'cancelled' | 'unauthorized' | 'forbidden' | 'not-found' | 'conflict' | 'validation' | 'rate-limited' | 'client' | 'server' | 'unavailable' | 'bad-response' | 'too-large';
|
|
94
|
+
/**
|
|
95
|
+
* Failure category of a status: specific statuses first, then `client` (4xx) or `server` (5xx).
|
|
96
|
+
* @example httpFailureCategory(422) // => 'validation'
|
|
97
|
+
* @example httpFailureCategory(503) // => 'unavailable'
|
|
98
|
+
* @example httpFailureCategory(418) // => 'client'
|
|
99
|
+
*/
|
|
100
|
+
export declare function httpFailureCategory(status: number): HttpFailureCategory;
|
|
101
|
+
export interface HttpErrorOptions extends HelperErrorOptions {
|
|
102
|
+
/** HTTP status; 0 when no response arrived (network failure, timeout, cancellation). */
|
|
103
|
+
readonly status: number;
|
|
104
|
+
readonly statusText?: string;
|
|
105
|
+
/** Parsed RFC 9457 problem details, if the server sent them. */
|
|
106
|
+
readonly problem?: Readonly<Record<string, unknown>>;
|
|
107
|
+
/** Request method and URL without query string (safe for logs). */
|
|
108
|
+
readonly method?: string;
|
|
109
|
+
readonly url?: string;
|
|
110
|
+
/** Default: `httpFailureCategory(status)`. */
|
|
111
|
+
readonly category?: HttpFailureCategory;
|
|
112
|
+
/** Default: true for network, offline, timeout, rate-limited, and unavailable failures, and for 425 and 500. */
|
|
113
|
+
readonly retryable?: boolean;
|
|
114
|
+
/** Server-requested wait before retrying (`Retry-After`), in milliseconds. */
|
|
115
|
+
readonly retryAfterMs?: number;
|
|
116
|
+
/** Correlation id from the response (`X-Request-Id`, `X-Correlation-Id`, or the `traceparent` trace id). */
|
|
117
|
+
readonly requestId?: string;
|
|
118
|
+
/** Parsed JSON error body (application error codes, custom envelopes). Never included in `toJSON`. */
|
|
119
|
+
readonly body?: unknown;
|
|
120
|
+
}
|
|
121
|
+
/** Log-safe summary of an `HttpError` (`JSON.stringify` uses it). */
|
|
122
|
+
export interface HttpErrorJson {
|
|
123
|
+
readonly name: string;
|
|
124
|
+
readonly code: string;
|
|
125
|
+
readonly message: string;
|
|
126
|
+
readonly status: number;
|
|
127
|
+
readonly category: HttpFailureCategory;
|
|
128
|
+
readonly retryable: boolean;
|
|
129
|
+
readonly method: string | undefined;
|
|
130
|
+
readonly url: string | undefined;
|
|
131
|
+
readonly requestId: string | undefined;
|
|
132
|
+
readonly retryAfterMs: number | undefined;
|
|
133
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
134
|
+
readonly problemType: string | undefined;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A failed HTTP call: an unsuccessful status, or no response at all (status 0 with category
|
|
138
|
+
* `network`, `offline`, `timeout`, or `cancelled`). `message` is the user-facing message.
|
|
139
|
+
* @example
|
|
140
|
+
* const e = new HttpError('HLP_HTTP_404', 'Not found.', { status: 404, method: 'GET', url: '/api/employees/42' });
|
|
141
|
+
* [e.status, e.kind, e.category, e.retryable]; // => [404, 'not-found', 'not-found', false]
|
|
142
|
+
* @example
|
|
143
|
+
* const e = new HttpError('SVC_HTTP_STATUS', 'Too many requests.', { status: 429, retryAfterMs: 2000, requestId: 'req-7' });
|
|
144
|
+
* [e.category, e.retryable, e.retryAfterMs]; // => ['rate-limited', true, 2000]
|
|
145
|
+
* JSON.parse(JSON.stringify(e)).requestId; // => 'req-7'
|
|
146
|
+
*/
|
|
147
|
+
export declare class HttpError extends HelperError {
|
|
148
|
+
name: string;
|
|
149
|
+
readonly status: number;
|
|
150
|
+
readonly statusText: string;
|
|
151
|
+
readonly problem: Readonly<Record<string, unknown>> | undefined;
|
|
152
|
+
readonly method: string | undefined;
|
|
153
|
+
readonly url: string | undefined;
|
|
154
|
+
readonly category: HttpFailureCategory;
|
|
155
|
+
readonly retryable: boolean;
|
|
156
|
+
readonly retryAfterMs: number | undefined;
|
|
157
|
+
readonly requestId: string | undefined;
|
|
158
|
+
readonly body: unknown;
|
|
159
|
+
constructor(code: string, message: string, options: HttpErrorOptions);
|
|
160
|
+
/** Log-safe summary: no headers, `body`, query string, or problem details beyond the type. */
|
|
161
|
+
toJSON(): HttpErrorJson;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* True when `value` is a `HelperError`, optionally with the given code.
|
|
165
|
+
* @example
|
|
166
|
+
* const e = new ConflictError('HRM_EMP_VERSION', 'The record was changed by someone else.');
|
|
167
|
+
* isHelperError(e, 'HRM_EMP_VERSION'); // => true
|
|
168
|
+
* isHelperError(new Error('Plain.')); // => false
|
|
169
|
+
*/
|
|
170
|
+
export declare function isHelperError(value: unknown, code?: string): value is HelperError;
|
|
171
|
+
/**
|
|
172
|
+
* True for any abort, from `AbortController`, DOM, or this package.
|
|
173
|
+
* @example
|
|
174
|
+
* isAbortError(new DOMException('Stopped.', 'AbortError')); // => true
|
|
175
|
+
* isAbortError(new TimeoutError()); // => false
|
|
176
|
+
*/
|
|
177
|
+
export declare function isAbortError(value: unknown): boolean;
|
|
178
|
+
/**
|
|
179
|
+
* Normalizes anything thrown into an `Error`. Non-error values become a `HelperError`
|
|
180
|
+
* with code `HLP_NON_ERROR_THROWN` and the value kept only as `cause`.
|
|
181
|
+
* @example
|
|
182
|
+
* toError(new RangeError('Out of range.')).message; // => 'Out of range.'
|
|
183
|
+
* isHelperError(toError('boom'), 'HLP_NON_ERROR_THROWN'); // => true
|
|
184
|
+
*/
|
|
185
|
+
export declare function toError(value: unknown): Error;
|
|
186
|
+
/** Plain, JSON-safe representation of an error. */
|
|
187
|
+
export interface SerializedError {
|
|
188
|
+
readonly name: string;
|
|
189
|
+
readonly message: string;
|
|
190
|
+
readonly code?: string;
|
|
191
|
+
readonly kind?: ErrorKind;
|
|
192
|
+
readonly status?: number;
|
|
193
|
+
readonly details?: Readonly<Record<string, unknown>>;
|
|
194
|
+
readonly fields?: Readonly<Record<string, string>>;
|
|
195
|
+
readonly stack?: string;
|
|
196
|
+
readonly cause?: SerializedError;
|
|
197
|
+
}
|
|
198
|
+
export interface SerializeErrorOptions {
|
|
199
|
+
/** Include stack traces. Default false: stacks leak paths and code structure. */
|
|
200
|
+
readonly includeStack?: boolean;
|
|
201
|
+
/** Maximum `cause` chain depth. Default 5. */
|
|
202
|
+
readonly maxDepth?: number;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Converts an error (and its `cause` chain) into a JSON-safe object.
|
|
206
|
+
* @example
|
|
207
|
+
* const e = new HttpError('HLP_HTTP_503', 'Service unavailable.', { status: 503 });
|
|
208
|
+
* serializeError(e); // => { name: 'HttpError', message: 'Service unavailable.', code: 'HLP_HTTP_503', kind: 'http', status: 503 }
|
|
209
|
+
*/
|
|
210
|
+
export declare function serializeError(value: unknown, options?: SerializeErrorOptions): SerializedError;
|
|
211
|
+
/**
|
|
212
|
+
* Rebuilds a `HelperError` from `serializeError` output (for example, received from a worker).
|
|
213
|
+
* Unknown shapes become `HLP_INVALID_SERIALIZED_ERROR`.
|
|
214
|
+
* @example
|
|
215
|
+
* const e = deserializeError({ name: 'NotFoundError', message: 'Employee not found.', code: 'HRM_EMP_NOT_FOUND', kind: 'not-found' });
|
|
216
|
+
* [e.name, e.code, e.kind]; // => ['NotFoundError', 'HRM_EMP_NOT_FOUND', 'not-found']
|
|
217
|
+
* deserializeError(42).code; // => 'HLP_INVALID_SERIALIZED_ERROR'
|
|
218
|
+
*/
|
|
219
|
+
export declare function deserializeError(value: unknown): HelperError;
|
|
220
|
+
export interface Ok<T> {
|
|
221
|
+
readonly ok: true;
|
|
222
|
+
readonly value: T;
|
|
223
|
+
}
|
|
224
|
+
export interface Err<E> {
|
|
225
|
+
readonly ok: false;
|
|
226
|
+
readonly error: E;
|
|
227
|
+
}
|
|
228
|
+
/** Discriminated success/failure value for code paths that must not throw. */
|
|
229
|
+
export type Result<T, E = Error> = Ok<T> | Err<E>;
|
|
230
|
+
/**
|
|
231
|
+
* @example
|
|
232
|
+
* const r = ok(42); // => { ok: true, value: 42 }
|
|
233
|
+
*/
|
|
234
|
+
export declare function ok<T>(value: T): Ok<T>;
|
|
235
|
+
/**
|
|
236
|
+
* @example
|
|
237
|
+
* const r = err(new ValidationError('HRM_LEAVE_RANGE', 'The end date is before the start date.'));
|
|
238
|
+
* r.ok; // => false
|
|
239
|
+
* r.error.code; // => 'HRM_LEAVE_RANGE'
|
|
240
|
+
*/
|
|
241
|
+
export declare function err<E>(error: E): Err<E>;
|
|
242
|
+
/**
|
|
243
|
+
* Runs `fn`, capturing a throw as `Err`.
|
|
244
|
+
* @example
|
|
245
|
+
* const r = tryCatch(() => JSON.parse('{"id":1}')); // => { ok: true, value: { id: 1 } }
|
|
246
|
+
* tryCatch(() => JSON.parse('{')).ok; // => false
|
|
247
|
+
*/
|
|
248
|
+
export declare function tryCatch<T>(fn: () => T): Result<T>;
|
|
249
|
+
/**
|
|
250
|
+
* Awaits `fn`, capturing a rejection as `Err`.
|
|
251
|
+
* @example
|
|
252
|
+
* const r = await tryCatchAsync(async () => { throw new TimeoutError(); });
|
|
253
|
+
* r.ok; // => false
|
|
254
|
+
*/
|
|
255
|
+
export declare function tryCatchAsync<T>(fn: () => Promise<T> | T): Promise<Result<T>>;
|
|
256
|
+
/**
|
|
257
|
+
* Returns the value or throws the error.
|
|
258
|
+
* @example
|
|
259
|
+
* unwrap(ok(5)); // => 5
|
|
260
|
+
* unwrap(err(new NotFoundError('HRM_EMP_NOT_FOUND', 'Employee not found.'))); // => throws HRM_EMP_NOT_FOUND
|
|
261
|
+
*/
|
|
262
|
+
export declare function unwrap<T, E>(result: Result<T, E>): T;
|
|
263
|
+
/**
|
|
264
|
+
* Returns the value or `fallback`.
|
|
265
|
+
* @example
|
|
266
|
+
* unwrapOr(tryCatch(() => JSON.parse('{')), {}); // => {}
|
|
267
|
+
*/
|
|
268
|
+
export declare function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T;
|
|
269
|
+
/**
|
|
270
|
+
* Maps the success value.
|
|
271
|
+
* @example
|
|
272
|
+
* mapResult(ok(20), (days) => days * 8); // => { ok: true, value: 160 }
|
|
273
|
+
*/
|
|
274
|
+
export declare function mapResult<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;
|
|
275
|
+
/**
|
|
276
|
+
* Maps the error value.
|
|
277
|
+
* @example
|
|
278
|
+
* mapError(err(404), (status) => `HTTP ${status}`); // => { ok: false, error: 'HTTP 404' }
|
|
279
|
+
*/
|
|
280
|
+
export declare function mapError<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;
|
|
281
|
+
/**
|
|
282
|
+
* Collects results: all values, or the first error.
|
|
283
|
+
* @example
|
|
284
|
+
* combineResults([ok(1), ok(2)]); // => { ok: true, value: [1, 2] }
|
|
285
|
+
* combineResults([ok(1), err('E_ROW_2'), err('E_ROW_3')]); // => { ok: false, error: 'E_ROW_2' }
|
|
286
|
+
*/
|
|
287
|
+
export declare function combineResults<T, E>(results: readonly Result<T, E>[]): Result<T[], E>;
|
|
288
|
+
/**
|
|
289
|
+
* Field-error map for form error summaries (`error-summary`, `form-field`).
|
|
290
|
+
* Collects `fields` from `ValidationError`s; other errors go under `formKey`.
|
|
291
|
+
* @example
|
|
292
|
+
* const errors = [new ValidationError('HLP_V', 'Invalid.', { fields: { email: 'Enter a valid email address.' } }), new Error('Server unavailable.')];
|
|
293
|
+
* fieldErrors(errors); // => { email: 'Enter a valid email address.', _form: 'Server unavailable.' }
|
|
294
|
+
*/
|
|
295
|
+
export declare function fieldErrors(errors: readonly unknown[], formKey?: string): Record<string, string>;
|
|
296
|
+
/**
|
|
297
|
+
* Throws a `HelperError` with code `HLP_ASSERT` when `condition` is falsy.
|
|
298
|
+
* @example
|
|
299
|
+
* const budget = -5;
|
|
300
|
+
* invariant(budget >= 0, 'Budget must not be negative.'); // => throws HLP_ASSERT
|
|
301
|
+
*/
|
|
302
|
+
export declare function invariant(condition: unknown, message?: string, code?: string): asserts condition;
|
|
303
|
+
/**
|
|
304
|
+
* Exhaustiveness check for `switch` statements.
|
|
305
|
+
* @example
|
|
306
|
+
* type Shift = 'day' | 'night';
|
|
307
|
+
* function label(shift: Shift): string {
|
|
308
|
+
* switch (shift) {
|
|
309
|
+
* case 'day': return 'Day shift';
|
|
310
|
+
* case 'night': return 'Night shift';
|
|
311
|
+
* default: return assertNever(shift); // compile error if a Shift is not handled
|
|
312
|
+
* }
|
|
313
|
+
* }
|
|
314
|
+
* label('night'); // => 'Night shift'
|
|
315
|
+
*/
|
|
316
|
+
export declare function assertNever(value: never, message?: string): never;
|