@baukit/localization-core 0.7.2 → 0.7.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.
- package/package.json +2 -1
- package/src/catalog-segment.test.ts +60 -0
- package/src/catalog-segment.ts +66 -0
- package/src/catalog.ts +73 -0
- package/src/civil-date.test.ts +254 -0
- package/src/civil-date.ts +127 -0
- package/src/codes.ts +37 -0
- package/src/formatters.ts +33 -0
- package/src/index.test.ts +220 -0
- package/src/index.ts +46 -0
- package/src/locale.ts +140 -0
- package/src/zoned-time-vectors.ts +78 -0
- package/src/zoned-time.test.ts +91 -0
- package/src/zoned-time.ts +171 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/localization-core",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Dependency-free locale resolution, catalog key comparison, stable-code localization, and explicit-locale Intl formatter factories.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Patrick Koss",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
},
|
|
36
36
|
"files": [
|
|
37
37
|
"dist",
|
|
38
|
+
"src",
|
|
38
39
|
"README.md",
|
|
39
40
|
"LICENSE"
|
|
40
41
|
],
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { defineCatalogSegment, type LocalizedCatalogSegment } from './index.js';
|
|
4
|
+
|
|
5
|
+
const english = {
|
|
6
|
+
title: 'Account',
|
|
7
|
+
devices: { one: '{{count}} device', other: '{{count}} devices' },
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
describe('typed catalog segments', () => {
|
|
11
|
+
it('uses any caller-selected reference locale and freezes the locale map', () => {
|
|
12
|
+
const catalogs = defineCatalogSegment(['de', 'en', 'es'] as const, 'en', english, {
|
|
13
|
+
de: { title: 'Konto', devices: { one: '{{count}} Gerät', other: '{{count}} Geräte' } },
|
|
14
|
+
es: {
|
|
15
|
+
title: 'Cuenta',
|
|
16
|
+
devices: { one: '{{count}} dispositivo', other: '{{count}} dispositivos' },
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
expect(catalogs.en).toBe(english);
|
|
21
|
+
expect(catalogs.de.devices.other).toBe('{{count}} Geräte');
|
|
22
|
+
expect(Object.isFrozen(catalogs)).toBe(true);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('rejects invalid dynamic locale lists', () => {
|
|
26
|
+
expect(() =>
|
|
27
|
+
defineCatalogSegment(['en', 'en'] as [string, ...string[]], 'en', english, {}),
|
|
28
|
+
).toThrow('Supported locales must not contain duplicates.');
|
|
29
|
+
expect(() =>
|
|
30
|
+
defineCatalogSegment(['en', 'de'] as [string, ...string[]], 'en', english, {}),
|
|
31
|
+
).toThrow('Localized catalogs must match the supported locales.');
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('keeps exact message keys and string versus plural shape in the public type', () => {
|
|
35
|
+
const valid: LocalizedCatalogSegment<typeof english> = {
|
|
36
|
+
title: 'Konto',
|
|
37
|
+
devices: { one: 'Gerät', other: 'Geräte' },
|
|
38
|
+
};
|
|
39
|
+
expect(valid.title).toBe('Konto');
|
|
40
|
+
|
|
41
|
+
// @ts-expect-error The reference locale requires devices.
|
|
42
|
+
const missingKey: LocalizedCatalogSegment<typeof english> = {
|
|
43
|
+
title: 'Konto',
|
|
44
|
+
};
|
|
45
|
+
const wrongShape: LocalizedCatalogSegment<typeof english> = {
|
|
46
|
+
title: 'Konto',
|
|
47
|
+
// @ts-expect-error A plural reference message requires one and other.
|
|
48
|
+
devices: 'Geräte',
|
|
49
|
+
};
|
|
50
|
+
const extraKey: LocalizedCatalogSegment<typeof english> = {
|
|
51
|
+
title: 'Konto',
|
|
52
|
+
devices: { one: 'Gerät', other: 'Geräte' },
|
|
53
|
+
// @ts-expect-error Translations cannot add keys absent from the reference.
|
|
54
|
+
retry: 'Erneut versuchen',
|
|
55
|
+
};
|
|
56
|
+
expect(missingKey.title).toBe('Konto');
|
|
57
|
+
expect(wrongShape.devices).toBe('Geräte');
|
|
58
|
+
expect(extraKey.title).toBe('Konto');
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export interface PluralMessage {
|
|
2
|
+
readonly one: string;
|
|
3
|
+
readonly other: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export type CatalogMessage = string | PluralMessage;
|
|
7
|
+
export type CatalogSegment = Readonly<Record<string, CatalogMessage>>;
|
|
8
|
+
|
|
9
|
+
export type LocalizedCatalogSegment<TCatalog extends CatalogSegment> = {
|
|
10
|
+
readonly [TKey in keyof TCatalog]: TCatalog[TKey] extends string
|
|
11
|
+
? string
|
|
12
|
+
: TCatalog[TKey] extends PluralMessage
|
|
13
|
+
? PluralMessage
|
|
14
|
+
: never;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type CatalogSegmentLocales<
|
|
18
|
+
TLocales extends string,
|
|
19
|
+
TReferenceLocale extends TLocales,
|
|
20
|
+
TReferenceCatalog extends CatalogSegment,
|
|
21
|
+
> = Readonly<
|
|
22
|
+
Record<TReferenceLocale, TReferenceCatalog> &
|
|
23
|
+
Record<Exclude<TLocales, TReferenceLocale>, LocalizedCatalogSegment<TReferenceCatalog>>
|
|
24
|
+
>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Defines one product-owned catalog segment against a reference locale.
|
|
28
|
+
*
|
|
29
|
+
* TypeScript rejects missing or extra locale keys, missing or extra message
|
|
30
|
+
* keys, and translations that change a string into a plural message or back.
|
|
31
|
+
*/
|
|
32
|
+
export function defineCatalogSegment<
|
|
33
|
+
const TLocales extends readonly [string, ...string[]],
|
|
34
|
+
const TReferenceLocale extends TLocales[number],
|
|
35
|
+
const TReferenceCatalog extends CatalogSegment,
|
|
36
|
+
>(
|
|
37
|
+
supportedLocales: TLocales,
|
|
38
|
+
referenceLocale: TReferenceLocale,
|
|
39
|
+
referenceCatalog: TReferenceCatalog,
|
|
40
|
+
localizedCatalogs: Readonly<
|
|
41
|
+
Record<Exclude<TLocales[number], TReferenceLocale>, LocalizedCatalogSegment<TReferenceCatalog>>
|
|
42
|
+
>,
|
|
43
|
+
): CatalogSegmentLocales<TLocales[number], TReferenceLocale, TReferenceCatalog> {
|
|
44
|
+
if (new Set(supportedLocales).size !== supportedLocales.length) {
|
|
45
|
+
throw new RangeError('Supported locales must not contain duplicates.');
|
|
46
|
+
}
|
|
47
|
+
if (!supportedLocales.includes(referenceLocale)) {
|
|
48
|
+
throw new RangeError('The reference locale must be supported.');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const expectedLocalizedLocales = supportedLocales.filter((locale) => locale !== referenceLocale);
|
|
52
|
+
const suppliedLocalizedLocales = Object.keys(localizedCatalogs);
|
|
53
|
+
if (
|
|
54
|
+
suppliedLocalizedLocales.length !== expectedLocalizedLocales.length ||
|
|
55
|
+
expectedLocalizedLocales.some(
|
|
56
|
+
(locale) => !Object.prototype.hasOwnProperty.call(localizedCatalogs, locale),
|
|
57
|
+
)
|
|
58
|
+
) {
|
|
59
|
+
throw new RangeError('Localized catalogs must match the supported locales.');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
...localizedCatalogs,
|
|
64
|
+
[referenceLocale]: referenceCatalog,
|
|
65
|
+
}) as CatalogSegmentLocales<TLocales[number], TReferenceLocale, TReferenceCatalog>;
|
|
66
|
+
}
|
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export interface CatalogDifference {
|
|
2
|
+
readonly missing: readonly string[];
|
|
3
|
+
readonly extra: readonly string[];
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
function escapeKeySegment(segment: string): string {
|
|
7
|
+
return segment.replaceAll('\\', '\\\\').replaceAll('.', '\\.');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function enumerableProperties(value: object): readonly [string, unknown][] | null {
|
|
11
|
+
try {
|
|
12
|
+
return Object.entries(Object.getOwnPropertyDescriptors(value))
|
|
13
|
+
.filter(([, descriptor]) => descriptor.enumerable)
|
|
14
|
+
.map(([key, descriptor]) => [key, 'value' in descriptor ? descriptor.value : undefined]);
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function plainRecordProperties(value: unknown): readonly [string, unknown][] | null {
|
|
21
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const prototype = Object.getPrototypeOf(value) as unknown;
|
|
27
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return enumerableProperties(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function collectCatalogKeys(
|
|
38
|
+
value: unknown,
|
|
39
|
+
prefix: string,
|
|
40
|
+
ancestors: WeakSet<object>,
|
|
41
|
+
): readonly string[] {
|
|
42
|
+
const properties = plainRecordProperties(value);
|
|
43
|
+
if (properties === null || properties.length === 0) {
|
|
44
|
+
return prefix === '' ? [] : [prefix];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (typeof value !== 'object' || value === null || ancestors.has(value)) {
|
|
48
|
+
return prefix === '' ? [] : [prefix];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
ancestors.add(value);
|
|
52
|
+
const keys = properties.flatMap(([key, child]) => {
|
|
53
|
+
const escapedKey = escapeKeySegment(key);
|
|
54
|
+
const path = prefix === '' ? escapedKey : `${prefix}.${escapedKey}`;
|
|
55
|
+
return collectCatalogKeys(child, path, ancestors);
|
|
56
|
+
});
|
|
57
|
+
ancestors.delete(value);
|
|
58
|
+
return keys;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function catalogKeySet(catalog: unknown): readonly string[] {
|
|
62
|
+
return [...collectCatalogKeys(catalog, '', new WeakSet())].sort();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function compareCatalogKeys(reference: unknown, candidate: unknown): CatalogDifference {
|
|
66
|
+
const referenceKeys = new Set(catalogKeySet(reference));
|
|
67
|
+
const candidateKeys = new Set(catalogKeySet(candidate));
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
missing: [...referenceKeys].filter((key) => !candidateKeys.has(key)).sort(),
|
|
71
|
+
extra: [...candidateKeys].filter((key) => !referenceKeys.has(key)).sort(),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
addCivilDays,
|
|
5
|
+
assertCivilDate,
|
|
6
|
+
assertCivilTime,
|
|
7
|
+
assertTimeZone,
|
|
8
|
+
civilDateForInstant,
|
|
9
|
+
civilDateValidationCode,
|
|
10
|
+
civilDaysBetween,
|
|
11
|
+
civilToday,
|
|
12
|
+
compareCivilDates,
|
|
13
|
+
INVALID_CIVIL_DATE_CODE,
|
|
14
|
+
isCivilDate,
|
|
15
|
+
isInstantOnCivilDate,
|
|
16
|
+
parseCivilDate,
|
|
17
|
+
resolvedTimeZone,
|
|
18
|
+
} from './civil-date.js';
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
vi.useRealTimers();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('parseCivilDate', () => {
|
|
25
|
+
it('accepts a well-formed calendar date', () => {
|
|
26
|
+
expect(parseCivilDate('2026-08-22')).toEqual({ ok: true, value: '2026-08-22' });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('accepts February 29 in a leap year and rejects it otherwise', () => {
|
|
30
|
+
expect(parseCivilDate('2024-02-29').ok).toBe(true);
|
|
31
|
+
expect(parseCivilDate('2000-02-29').ok).toBe(true);
|
|
32
|
+
expect(parseCivilDate('2026-02-29')).toEqual({ ok: false, code: INVALID_CIVIL_DATE_CODE });
|
|
33
|
+
expect(parseCivilDate('1900-02-29')).toEqual({ ok: false, code: INVALID_CIVIL_DATE_CODE });
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it.each([
|
|
37
|
+
'not-a-date',
|
|
38
|
+
'',
|
|
39
|
+
'2026-02-30',
|
|
40
|
+
'2026-13-01',
|
|
41
|
+
'2026-00-10',
|
|
42
|
+
'2026-01-00',
|
|
43
|
+
'2026-1-01',
|
|
44
|
+
'26-01-01',
|
|
45
|
+
'2026/01/01',
|
|
46
|
+
'2026-01-01T00:00:00Z',
|
|
47
|
+
' 2026-01-01',
|
|
48
|
+
'2026-01-01 ',
|
|
49
|
+
'+2026-01-01',
|
|
50
|
+
'2026-04-31',
|
|
51
|
+
])('rejects %j', (candidate) => {
|
|
52
|
+
expect(parseCivilDate(candidate)).toEqual({ ok: false, code: INVALID_CIVIL_DATE_CODE });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('exposes boolean and code-shaped validation', () => {
|
|
56
|
+
expect(isCivilDate('2026-08-22')).toBe(true);
|
|
57
|
+
expect(isCivilDate('2026-02-30')).toBe(false);
|
|
58
|
+
expect(civilDateValidationCode('2026-02-28')).toBeNull();
|
|
59
|
+
expect(civilDateValidationCode('nope')).toBe(INVALID_CIVIL_DATE_CODE);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('assertCivilDate', () => {
|
|
64
|
+
it('throws on an impossible date and stays silent on a real one', () => {
|
|
65
|
+
expect(() => {
|
|
66
|
+
assertCivilDate('2026-02-30');
|
|
67
|
+
}).toThrow(new RangeError('Invalid civil date: 2026-02-30'));
|
|
68
|
+
expect(() => {
|
|
69
|
+
assertCivilDate('2026-02-28');
|
|
70
|
+
}).not.toThrow();
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe('assertCivilTime', () => {
|
|
75
|
+
it.each(['00:00', '23:59', '12:30:45', null])('accepts %j', (candidate) => {
|
|
76
|
+
expect(() => {
|
|
77
|
+
assertCivilTime(candidate);
|
|
78
|
+
}).not.toThrow();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it.each(['24:00', '12:60', '7:30', '12:30:60', '', 'noon'])('rejects %j', (candidate) => {
|
|
82
|
+
expect(() => {
|
|
83
|
+
assertCivilTime(candidate);
|
|
84
|
+
}).toThrow(RangeError);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe('assertTimeZone', () => {
|
|
89
|
+
it('accepts real IANA zones and UTC', () => {
|
|
90
|
+
for (const zone of ['UTC', 'Europe/Berlin', 'Pacific/Auckland', 'America/Los_Angeles']) {
|
|
91
|
+
expect(() => {
|
|
92
|
+
assertTimeZone(zone);
|
|
93
|
+
}).not.toThrow();
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('rejects empty and unknown zones', () => {
|
|
98
|
+
expect(() => {
|
|
99
|
+
assertTimeZone(' ');
|
|
100
|
+
}).toThrow(new RangeError('Time zone must be non-empty'));
|
|
101
|
+
expect(() => {
|
|
102
|
+
assertTimeZone('Mars/Olympus_Mons');
|
|
103
|
+
}).toThrow(new RangeError('Invalid IANA time zone: Mars/Olympus_Mons'));
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe('addCivilDays', () => {
|
|
108
|
+
it('crosses month and year boundaries', () => {
|
|
109
|
+
expect(addCivilDays('2026-01-31', 1)).toBe('2026-02-01');
|
|
110
|
+
expect(addCivilDays('2026-12-31', 1)).toBe('2027-01-01');
|
|
111
|
+
expect(addCivilDays('2026-01-01', -1)).toBe('2025-12-31');
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('lands on February 29 in a leap year and skips it otherwise', () => {
|
|
115
|
+
expect(addCivilDays('2024-02-28', 1)).toBe('2024-02-29');
|
|
116
|
+
expect(addCivilDays('2026-02-28', 1)).toBe('2026-03-01');
|
|
117
|
+
expect(addCivilDays('2024-02-29', 365)).toBe('2025-02-28');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('ignores DST because civil days have no clock', () => {
|
|
121
|
+
expect(addCivilDays('2026-03-28', 1)).toBe('2026-03-29');
|
|
122
|
+
expect(addCivilDays('2026-10-24', 1)).toBe('2026-10-25');
|
|
123
|
+
expect(addCivilDays('2026-03-07', 1)).toBe('2026-03-08');
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('returns the same date for zero days', () => {
|
|
127
|
+
expect(addCivilDays('2026-08-22', 0)).toBe('2026-08-22');
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('rejects an invalid date and a non-integer offset', () => {
|
|
131
|
+
expect(() => addCivilDays('2026-02-30', 1)).toThrow(RangeError);
|
|
132
|
+
expect(() => addCivilDays('2026-02-28', 1.5)).toThrow(
|
|
133
|
+
new RangeError('Days must be an integer'),
|
|
134
|
+
);
|
|
135
|
+
expect(() => addCivilDays('2026-02-28', Number.NaN)).toThrow(
|
|
136
|
+
new RangeError('Days must be an integer'),
|
|
137
|
+
);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('rejects an offset that leaves the representable range', () => {
|
|
141
|
+
expect(() => addCivilDays('2026-08-22', 400_000_000)).toThrow(RangeError);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe('civilDateForInstant', () => {
|
|
146
|
+
it('splits an instant that is two different civil days in two zones', () => {
|
|
147
|
+
const instant = '2026-08-24T10:00:00Z';
|
|
148
|
+
expect(civilDateForInstant(instant, 'Pacific/Auckland')).toBe('2026-08-24');
|
|
149
|
+
expect(civilDateForInstant(instant, 'America/Los_Angeles')).toBe('2026-08-24');
|
|
150
|
+
|
|
151
|
+
const nightInstant = '2026-08-25T06:00:00Z';
|
|
152
|
+
expect(civilDateForInstant(nightInstant, 'Pacific/Auckland')).toBe('2026-08-25');
|
|
153
|
+
expect(civilDateForInstant(nightInstant, 'America/Los_Angeles')).toBe('2026-08-24');
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('resolves the civil day across a spring-forward gap', () => {
|
|
157
|
+
expect(civilDateForInstant('2026-03-08T09:59:00Z', 'America/Los_Angeles')).toBe('2026-03-08');
|
|
158
|
+
expect(civilDateForInstant('2026-03-08T10:00:00Z', 'America/Los_Angeles')).toBe('2026-03-08');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('resolves both passes of a repeated fall-back hour to the same civil day', () => {
|
|
162
|
+
expect(civilDateForInstant('2026-11-01T08:30:00Z', 'America/Los_Angeles')).toBe('2026-11-01');
|
|
163
|
+
expect(civilDateForInstant('2026-11-01T09:30:00Z', 'America/Los_Angeles')).toBe('2026-11-01');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('flips the civil day exactly at local midnight', () => {
|
|
167
|
+
expect(civilDateForInstant('2026-08-21T21:59:59Z', 'Europe/Berlin')).toBe('2026-08-21');
|
|
168
|
+
expect(civilDateForInstant('2026-08-21T22:00:00Z', 'Europe/Berlin')).toBe('2026-08-22');
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('accepts a Date, an ISO string, and epoch milliseconds', () => {
|
|
172
|
+
expect(civilDateForInstant(new Date('2026-08-22T12:00:00Z'), 'UTC')).toBe('2026-08-22');
|
|
173
|
+
expect(civilDateForInstant('2026-08-22T12:00:00Z', 'UTC')).toBe('2026-08-22');
|
|
174
|
+
expect(civilDateForInstant(Date.parse('2026-08-22T12:00:00Z'), 'UTC')).toBe('2026-08-22');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('zero-pads single-digit months and days', () => {
|
|
178
|
+
expect(civilDateForInstant('2026-01-05T12:00:00Z', 'UTC')).toBe('2026-01-05');
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it('rejects an unparsable instant and an unknown zone', () => {
|
|
182
|
+
expect(() => civilDateForInstant('yesterday', 'UTC')).toThrow(
|
|
183
|
+
new RangeError('Invalid instant: yesterday'),
|
|
184
|
+
);
|
|
185
|
+
expect(() => civilDateForInstant(Number.NaN, 'UTC')).toThrow(RangeError);
|
|
186
|
+
expect(() => civilDateForInstant('2026-08-22T12:00:00Z', 'Mars/Olympus_Mons')).toThrow(
|
|
187
|
+
RangeError,
|
|
188
|
+
);
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe('civilToday', () => {
|
|
193
|
+
it('reads the current instant in the requested zone', () => {
|
|
194
|
+
vi.useFakeTimers();
|
|
195
|
+
vi.setSystemTime(new Date('2026-08-24T23:30:00Z'));
|
|
196
|
+
expect(civilToday('UTC')).toBe('2026-08-24');
|
|
197
|
+
expect(civilToday('Pacific/Auckland')).toBe('2026-08-25');
|
|
198
|
+
expect(civilToday('America/Los_Angeles')).toBe('2026-08-24');
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
describe('resolvedTimeZone', () => {
|
|
203
|
+
it('returns a zone the assertion accepts', () => {
|
|
204
|
+
const zone = resolvedTimeZone();
|
|
205
|
+
expect(typeof zone).toBe('string');
|
|
206
|
+
expect(() => {
|
|
207
|
+
assertTimeZone(zone);
|
|
208
|
+
}).not.toThrow();
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
describe('isInstantOnCivilDate', () => {
|
|
213
|
+
it('answers differently per zone for one instant', () => {
|
|
214
|
+
const instant = '2026-08-25T06:00:00Z';
|
|
215
|
+
expect(isInstantOnCivilDate(instant, '2026-08-25', 'Pacific/Auckland')).toBe(true);
|
|
216
|
+
expect(isInstantOnCivilDate(instant, '2026-08-25', 'America/Los_Angeles')).toBe(false);
|
|
217
|
+
expect(isInstantOnCivilDate(instant, '2026-08-24', 'America/Los_Angeles')).toBe(true);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it('rejects an invalid civil day', () => {
|
|
221
|
+
expect(() => isInstantOnCivilDate('2026-08-22T12:00:00Z', '2026-02-30', 'UTC')).toThrow(
|
|
222
|
+
RangeError,
|
|
223
|
+
);
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
describe('compareCivilDates', () => {
|
|
228
|
+
it('orders civil dates and reports equality', () => {
|
|
229
|
+
expect(compareCivilDates('2026-08-22', '2026-08-23')).toBe(-1);
|
|
230
|
+
expect(compareCivilDates('2026-08-23', '2026-08-22')).toBe(1);
|
|
231
|
+
expect(compareCivilDates('2026-08-22', '2026-08-22')).toBe(0);
|
|
232
|
+
expect(compareCivilDates('2025-12-31', '2026-01-01')).toBe(-1);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('rejects an invalid operand', () => {
|
|
236
|
+
expect(() => compareCivilDates('2026-02-30', '2026-03-01')).toThrow(RangeError);
|
|
237
|
+
expect(() => compareCivilDates('2026-03-01', 'nope')).toThrow(RangeError);
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
describe('civilDaysBetween', () => {
|
|
242
|
+
it('counts whole days including across DST and leap days', () => {
|
|
243
|
+
expect(civilDaysBetween('2026-08-22', '2026-08-25')).toBe(3);
|
|
244
|
+
expect(civilDaysBetween('2026-08-25', '2026-08-22')).toBe(-3);
|
|
245
|
+
expect(civilDaysBetween('2026-08-22', '2026-08-22')).toBe(0);
|
|
246
|
+
expect(civilDaysBetween('2026-03-07', '2026-03-09')).toBe(2);
|
|
247
|
+
expect(civilDaysBetween('2024-02-28', '2024-03-01')).toBe(2);
|
|
248
|
+
expect(civilDaysBetween('2026-02-28', '2026-03-01')).toBe(1);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('rejects an invalid operand', () => {
|
|
252
|
+
expect(() => civilDaysBetween('2026-02-30', '2026-03-01')).toThrow(RangeError);
|
|
253
|
+
});
|
|
254
|
+
});
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const CIVIL_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
2
|
+
const CIVIL_TIME_PATTERN = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/;
|
|
3
|
+
|
|
4
|
+
export const INVALID_CIVIL_DATE_CODE = 'invalid_civil_date';
|
|
5
|
+
export type CivilDateValidationCode = typeof INVALID_CIVIL_DATE_CODE;
|
|
6
|
+
|
|
7
|
+
export type CivilDateParseResult =
|
|
8
|
+
| { readonly ok: true; readonly value: string }
|
|
9
|
+
| { readonly ok: false; readonly code: CivilDateValidationCode };
|
|
10
|
+
|
|
11
|
+
export function parseCivilDate(civilDate: string): CivilDateParseResult {
|
|
12
|
+
const match = CIVIL_DATE_PATTERN.exec(civilDate);
|
|
13
|
+
if (match === null) {
|
|
14
|
+
return { ok: false, code: INVALID_CIVIL_DATE_CODE };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const year = Number(match[1]);
|
|
18
|
+
const month = Number(match[2]);
|
|
19
|
+
const day = Number(match[3]);
|
|
20
|
+
const candidate = new Date(Date.UTC(year, month - 1, day));
|
|
21
|
+
const roundTrips =
|
|
22
|
+
candidate.getUTCFullYear() === year &&
|
|
23
|
+
candidate.getUTCMonth() === month - 1 &&
|
|
24
|
+
candidate.getUTCDate() === day;
|
|
25
|
+
|
|
26
|
+
return roundTrips ? { ok: true, value: civilDate } : { ok: false, code: INVALID_CIVIL_DATE_CODE };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isCivilDate(civilDate: string): boolean {
|
|
30
|
+
return parseCivilDate(civilDate).ok;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function civilDateValidationCode(civilDate: string): CivilDateValidationCode | null {
|
|
34
|
+
return parseCivilDate(civilDate).ok ? null : INVALID_CIVIL_DATE_CODE;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function assertCivilDate(civilDate: string): void {
|
|
38
|
+
if (!parseCivilDate(civilDate).ok) {
|
|
39
|
+
throw new RangeError(`Invalid civil date: ${civilDate}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function assertCivilTime(civilTime: string | null): void {
|
|
44
|
+
if (civilTime !== null && !CIVIL_TIME_PATTERN.test(civilTime)) {
|
|
45
|
+
throw new RangeError(`Invalid civil time: ${civilTime}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function assertTimeZone(timeZone: string): void {
|
|
50
|
+
if (timeZone.trim().length === 0) {
|
|
51
|
+
throw new RangeError('Time zone must be non-empty');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
new Intl.DateTimeFormat('en-US', { timeZone }).format(new Date(0));
|
|
56
|
+
} catch {
|
|
57
|
+
throw new RangeError(`Invalid IANA time zone: ${timeZone}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function addCivilDays(civilDate: string, days: number): string {
|
|
62
|
+
assertCivilDate(civilDate);
|
|
63
|
+
if (!Number.isInteger(days)) {
|
|
64
|
+
throw new RangeError('Days must be an integer');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const [year, month, day] = civilDate.split('-').map(Number) as [number, number, number];
|
|
68
|
+
const shifted = new Date(Date.UTC(year, month - 1, day + days));
|
|
69
|
+
if (Number.isNaN(shifted.getTime())) {
|
|
70
|
+
throw new RangeError(`Civil date out of range: ${civilDate} + ${String(days)} days`);
|
|
71
|
+
}
|
|
72
|
+
return shifted.toISOString().slice(0, 10);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function civilDateForInstant(instant: Date | string | number, timeZone: string): string {
|
|
76
|
+
assertTimeZone(timeZone);
|
|
77
|
+
const date = instant instanceof Date ? instant : new Date(instant);
|
|
78
|
+
if (Number.isNaN(date.getTime())) {
|
|
79
|
+
throw new RangeError(`Invalid instant: ${String(instant)}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
83
|
+
timeZone,
|
|
84
|
+
year: 'numeric',
|
|
85
|
+
month: '2-digit',
|
|
86
|
+
day: '2-digit',
|
|
87
|
+
}).formatToParts(date);
|
|
88
|
+
const part = (type: Intl.DateTimeFormatPartTypes): string =>
|
|
89
|
+
parts.find((candidate) => candidate.type === type)?.value ?? '';
|
|
90
|
+
|
|
91
|
+
return `${part('year')}-${part('month')}-${part('day')}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function civilToday(timeZone: string): string {
|
|
95
|
+
return civilDateForInstant(new Date(), timeZone);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function resolvedTimeZone(): string {
|
|
99
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function isInstantOnCivilDate(
|
|
103
|
+
instant: Date | string | number,
|
|
104
|
+
civilDate: string,
|
|
105
|
+
timeZone: string,
|
|
106
|
+
): boolean {
|
|
107
|
+
assertCivilDate(civilDate);
|
|
108
|
+
return civilDateForInstant(instant, timeZone) === civilDate;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function compareCivilDates(left: string, right: string): number {
|
|
112
|
+
assertCivilDate(left);
|
|
113
|
+
assertCivilDate(right);
|
|
114
|
+
if (left === right) {
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
return left < right ? -1 : 1;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function civilDaysBetween(from: string, to: string): number {
|
|
121
|
+
assertCivilDate(from);
|
|
122
|
+
assertCivilDate(to);
|
|
123
|
+
const millisecondsPerDay = 86_400_000;
|
|
124
|
+
return Math.round(
|
|
125
|
+
(Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / millisecondsPerDay,
|
|
126
|
+
);
|
|
127
|
+
}
|
package/src/codes.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type LocalizedCodeEntry = string | ((details?: unknown) => string | null | undefined);
|
|
2
|
+
|
|
3
|
+
export interface CodeResolverOptions<TCode extends string> {
|
|
4
|
+
readonly catalog: Readonly<Partial<Record<TCode, LocalizedCodeEntry>>>;
|
|
5
|
+
readonly fallback: string | ((code: TCode, details?: unknown) => string);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function catalogEntry<TCode extends string>(
|
|
9
|
+
catalog: Readonly<Partial<Record<TCode, LocalizedCodeEntry>>>,
|
|
10
|
+
code: TCode,
|
|
11
|
+
): LocalizedCodeEntry | undefined {
|
|
12
|
+
try {
|
|
13
|
+
return Object.hasOwn(catalog, code) ? catalog[code] : undefined;
|
|
14
|
+
} catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createLocalizedCodeResolver<TCode extends string>(
|
|
20
|
+
options: CodeResolverOptions<TCode>,
|
|
21
|
+
): (code: TCode, details?: unknown) => string {
|
|
22
|
+
return (code, details) => {
|
|
23
|
+
const entry = catalogEntry(options.catalog, code);
|
|
24
|
+
try {
|
|
25
|
+
const localized = typeof entry === 'function' ? entry(details) : entry;
|
|
26
|
+
if (typeof localized === 'string' && localized.trim().length > 0) {
|
|
27
|
+
return localized;
|
|
28
|
+
}
|
|
29
|
+
} catch {
|
|
30
|
+
// The safe API message is used when structured details cannot be rendered.
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return typeof options.fallback === 'function'
|
|
34
|
+
? options.fallback(code, details)
|
|
35
|
+
: options.fallback;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { canonicalizeResolvedLocale } from './locale.js';
|
|
2
|
+
|
|
3
|
+
function supportedNumberLocale(locale: string): string {
|
|
4
|
+
const canonical = canonicalizeResolvedLocale(locale);
|
|
5
|
+
if (Intl.NumberFormat.supportedLocalesOf([canonical], { localeMatcher: 'lookup' }).length === 0) {
|
|
6
|
+
throw new RangeError(`number formatting does not support locale ${canonical}`);
|
|
7
|
+
}
|
|
8
|
+
return canonical;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function supportedDateTimeLocale(locale: string): string {
|
|
12
|
+
const canonical = canonicalizeResolvedLocale(locale);
|
|
13
|
+
if (
|
|
14
|
+
Intl.DateTimeFormat.supportedLocalesOf([canonical], { localeMatcher: 'lookup' }).length === 0
|
|
15
|
+
) {
|
|
16
|
+
throw new RangeError(`date and time formatting does not support locale ${canonical}`);
|
|
17
|
+
}
|
|
18
|
+
return canonical;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createNumberFormatter(
|
|
22
|
+
locale: string,
|
|
23
|
+
options?: Intl.NumberFormatOptions,
|
|
24
|
+
): Intl.NumberFormat {
|
|
25
|
+
return new Intl.NumberFormat(supportedNumberLocale(locale), options);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createDateTimeFormatter(
|
|
29
|
+
locale: string,
|
|
30
|
+
options?: Intl.DateTimeFormatOptions,
|
|
31
|
+
): Intl.DateTimeFormat {
|
|
32
|
+
return new Intl.DateTimeFormat(supportedDateTimeLocale(locale), options);
|
|
33
|
+
}
|