@baukit/localization-core 0.7.1 → 0.7.3
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
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
catalogKeySet,
|
|
7
|
+
compareCatalogKeys,
|
|
8
|
+
createDateTimeFormatter,
|
|
9
|
+
createLocalizedCodeResolver,
|
|
10
|
+
createNumberFormatter,
|
|
11
|
+
normalizeLocalePreference,
|
|
12
|
+
resolveLocale,
|
|
13
|
+
} from './index.js';
|
|
14
|
+
|
|
15
|
+
interface LocaleResolutionCase {
|
|
16
|
+
readonly name: string;
|
|
17
|
+
readonly preference: unknown;
|
|
18
|
+
readonly deviceLocales: readonly string[];
|
|
19
|
+
readonly supported: readonly string[];
|
|
20
|
+
readonly fallback: string;
|
|
21
|
+
readonly expected: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fixtureUrl = new URL(
|
|
25
|
+
'../../../../fixtures/product-experience/locale-resolution.json',
|
|
26
|
+
import.meta.url,
|
|
27
|
+
);
|
|
28
|
+
const readUtf8File = readFileSync as unknown as (path: URL, encoding: 'utf8') => string;
|
|
29
|
+
const localeCases = JSON.parse(readUtf8File(fixtureUrl, 'utf8')) as readonly LocaleResolutionCase[];
|
|
30
|
+
|
|
31
|
+
describe('locale preference normalization', () => {
|
|
32
|
+
const options = { supported: ['en', 'de', 'de-AT'] as const, fallback: 'en' as const };
|
|
33
|
+
|
|
34
|
+
it('keeps system and returns the allowlisted spelling for normalized locale tags', () => {
|
|
35
|
+
expect(normalizeLocalePreference({ ...options, value: 'system' })).toBe('system');
|
|
36
|
+
expect(normalizeLocalePreference({ ...options, value: 'DE_at' })).toBe('de-AT');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it.each([
|
|
40
|
+
undefined,
|
|
41
|
+
null,
|
|
42
|
+
false,
|
|
43
|
+
12,
|
|
44
|
+
[],
|
|
45
|
+
{},
|
|
46
|
+
new String('de'),
|
|
47
|
+
Symbol('de'),
|
|
48
|
+
'__proto__',
|
|
49
|
+
'constructor',
|
|
50
|
+
'de/../../catalog',
|
|
51
|
+
'',
|
|
52
|
+
' ',
|
|
53
|
+
' de ',
|
|
54
|
+
'a'.repeat(129),
|
|
55
|
+
])('normalizes malformed value %p to the fallback', (value) => {
|
|
56
|
+
expect(normalizeLocalePreference({ ...options, value })).toBe('en');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('rejects a fallback outside the valid supported locale set', () => {
|
|
60
|
+
expect(() =>
|
|
61
|
+
normalizeLocalePreference({ value: 'system', supported: ['de'] as const, fallback: 'en' }),
|
|
62
|
+
).toThrow(RangeError);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('locale resolution fixtures', () => {
|
|
67
|
+
it.each(localeCases)('$name', ({ preference, deviceLocales, supported, fallback, expected }) => {
|
|
68
|
+
expect(resolveLocale({ preference, deviceLocales, supported, fallback })).toBe(expected);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('executes every shared fixture case', () => {
|
|
72
|
+
expect(localeCases).toHaveLength(18);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe('catalog key comparison', () => {
|
|
77
|
+
it('returns the sorted recursive leaf-key set', () => {
|
|
78
|
+
expect(
|
|
79
|
+
catalogKeySet({
|
|
80
|
+
title: 'Title',
|
|
81
|
+
account: { actions: { delete: 'Delete' }, empty: {} },
|
|
82
|
+
choices: ['one', 'two'],
|
|
83
|
+
}),
|
|
84
|
+
).toEqual(['account.actions.delete', 'account.empty', 'choices', 'title']);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('reports exact missing and extra keys without comparing translated values', () => {
|
|
88
|
+
const reference = { actions: { save: 'Save', cancel: 'Cancel' }, title: 'Settings' };
|
|
89
|
+
const candidate = { actions: { save: 'Speichern', retry: 'Erneut versuchen' }, title: '' };
|
|
90
|
+
|
|
91
|
+
expect(compareCatalogKeys(reference, candidate)).toEqual({
|
|
92
|
+
missing: ['actions.cancel'],
|
|
93
|
+
extra: ['actions.retry'],
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('supports exact immutable catalog-ID coverage', () => {
|
|
98
|
+
const emittedIds = { account_locked: true, rate_limited: true };
|
|
99
|
+
const translatedIds = { account_locked: 'Konto gesperrt', stale_code: 'Veraltet' };
|
|
100
|
+
expect(compareCatalogKeys(emittedIds, translatedIds)).toEqual({
|
|
101
|
+
missing: ['rate_limited'],
|
|
102
|
+
extra: ['stale_code'],
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('does not confuse dotted keys with nested paths', () => {
|
|
107
|
+
expect(catalogKeySet({ 'account.title': 'literal', account: { title: 'nested' } })).toEqual([
|
|
108
|
+
'account.title',
|
|
109
|
+
'account\\.title',
|
|
110
|
+
]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('handles malformed and cyclic catalogs without invoking getters', () => {
|
|
114
|
+
const catalog: Record<string, unknown> = { safe: 'text' };
|
|
115
|
+
catalog['cycle'] = catalog;
|
|
116
|
+
Object.defineProperty(catalog, 'getter', {
|
|
117
|
+
enumerable: true,
|
|
118
|
+
get: () => {
|
|
119
|
+
throw new Error('must not run');
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
expect(catalogKeySet(catalog)).toEqual(['cycle', 'getter', 'safe']);
|
|
124
|
+
expect(catalogKeySet(null)).toEqual([]);
|
|
125
|
+
expect(catalogKeySet(['not', 'a', 'catalog'])).toEqual([]);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
describe('localized backend codes', () => {
|
|
130
|
+
type Code = 'invalid_name' | 'rate_limited' | 'unknown_code';
|
|
131
|
+
|
|
132
|
+
it('resolves stable codes and passes structured details to message renderers', () => {
|
|
133
|
+
const fallback = vi.fn(() => 'Safe API message');
|
|
134
|
+
const resolve = createLocalizedCodeResolver<Code>({
|
|
135
|
+
catalog: {
|
|
136
|
+
invalid_name: 'Enter a name.',
|
|
137
|
+
rate_limited: (details) => {
|
|
138
|
+
if (
|
|
139
|
+
details === null ||
|
|
140
|
+
typeof details !== 'object' ||
|
|
141
|
+
!('retryAfter' in details) ||
|
|
142
|
+
typeof details.retryAfter !== 'number'
|
|
143
|
+
) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
return `Try again in ${String(details.retryAfter)} seconds.`;
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
fallback,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
expect(resolve('invalid_name')).toBe('Enter a name.');
|
|
153
|
+
expect(resolve('rate_limited', { retryAfter: 30 })).toBe('Try again in 30 seconds.');
|
|
154
|
+
expect(fallback).not.toHaveBeenCalled();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('uses the safe API message for unknown, empty, or unrenderable entries', () => {
|
|
158
|
+
const apiMessage = 'The request could not be completed.';
|
|
159
|
+
const resolve = createLocalizedCodeResolver<Code>({
|
|
160
|
+
catalog: {
|
|
161
|
+
invalid_name: ' ',
|
|
162
|
+
rate_limited: () => {
|
|
163
|
+
throw new Error('bad details');
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
fallback: apiMessage,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
expect(resolve('unknown_code')).toBe(apiMessage);
|
|
170
|
+
expect(resolve('invalid_name')).toBe(apiMessage);
|
|
171
|
+
expect(resolve('rate_limited', {})).toBe(apiMessage);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('does not resolve object-prototype properties as catalog codes', () => {
|
|
175
|
+
const resolve = createLocalizedCodeResolver<string>({
|
|
176
|
+
catalog: {},
|
|
177
|
+
fallback: 'Safe API message',
|
|
178
|
+
});
|
|
179
|
+
expect(resolve('__proto__')).toBe('Safe API message');
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe('explicit-locale formatters', () => {
|
|
184
|
+
it('creates number and unit formatters with the supplied resolved locale', () => {
|
|
185
|
+
const english = createNumberFormatter('en-US', { style: 'unit', unit: 'kilometer' });
|
|
186
|
+
const german = createNumberFormatter('de_DE', { style: 'unit', unit: 'kilometer' });
|
|
187
|
+
|
|
188
|
+
expect(english.resolvedOptions().locale).toBe('en-US');
|
|
189
|
+
expect(german.resolvedOptions().locale).toBe('de-DE');
|
|
190
|
+
expect(english.format(1234.5)).not.toBe(german.format(1234.5));
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('creates date and time formatters with the supplied locale and options', () => {
|
|
194
|
+
const british = createDateTimeFormatter('en-GB', {
|
|
195
|
+
dateStyle: 'short',
|
|
196
|
+
timeStyle: 'short',
|
|
197
|
+
timeZone: 'UTC',
|
|
198
|
+
});
|
|
199
|
+
const german = createDateTimeFormatter('de-DE', {
|
|
200
|
+
dateStyle: 'short',
|
|
201
|
+
timeStyle: 'short',
|
|
202
|
+
timeZone: 'UTC',
|
|
203
|
+
});
|
|
204
|
+
const instant = new Date('2024-01-02T15:04:00Z');
|
|
205
|
+
|
|
206
|
+
expect(british.resolvedOptions().locale).toBe('en-GB');
|
|
207
|
+
expect(german.resolvedOptions().locale).toBe('de-DE');
|
|
208
|
+
expect(british.format(instant)).not.toBe(german.format(instant));
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('rejects missing, blank, padded, and malformed locale values', () => {
|
|
212
|
+
expect(() => createNumberFormatter(undefined as never)).toThrow(RangeError);
|
|
213
|
+
expect(() => createNumberFormatter('')).toThrow(RangeError);
|
|
214
|
+
expect(() => createNumberFormatter(' de ')).toThrow(RangeError);
|
|
215
|
+
expect(() => createNumberFormatter('system')).toThrow(RangeError);
|
|
216
|
+
expect(() => createNumberFormatter('und')).toThrow(RangeError);
|
|
217
|
+
expect(() => createNumberFormatter('zz')).toThrow(RangeError);
|
|
218
|
+
expect(() => createDateTimeFormatter('../de')).toThrow(RangeError);
|
|
219
|
+
});
|
|
220
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export { catalogKeySet, compareCatalogKeys, type CatalogDifference } from './catalog.js';
|
|
2
|
+
export {
|
|
3
|
+
defineCatalogSegment,
|
|
4
|
+
type CatalogMessage,
|
|
5
|
+
type CatalogSegment,
|
|
6
|
+
type CatalogSegmentLocales,
|
|
7
|
+
type LocalizedCatalogSegment,
|
|
8
|
+
type PluralMessage,
|
|
9
|
+
} from './catalog-segment.js';
|
|
10
|
+
export {
|
|
11
|
+
addCivilDays,
|
|
12
|
+
assertCivilDate,
|
|
13
|
+
assertCivilTime,
|
|
14
|
+
assertTimeZone,
|
|
15
|
+
civilDateForInstant,
|
|
16
|
+
civilDateValidationCode,
|
|
17
|
+
civilDaysBetween,
|
|
18
|
+
civilToday,
|
|
19
|
+
compareCivilDates,
|
|
20
|
+
INVALID_CIVIL_DATE_CODE,
|
|
21
|
+
isCivilDate,
|
|
22
|
+
isInstantOnCivilDate,
|
|
23
|
+
parseCivilDate,
|
|
24
|
+
resolvedTimeZone,
|
|
25
|
+
type CivilDateParseResult,
|
|
26
|
+
type CivilDateValidationCode,
|
|
27
|
+
} from './civil-date.js';
|
|
28
|
+
export {
|
|
29
|
+
createLocalizedCodeResolver,
|
|
30
|
+
type CodeResolverOptions,
|
|
31
|
+
type LocalizedCodeEntry,
|
|
32
|
+
} from './codes.js';
|
|
33
|
+
export { createDateTimeFormatter, createNumberFormatter } from './formatters.js';
|
|
34
|
+
export { normalizeLocalePreference, resolveLocale, type LocalePreference } from './locale.js';
|
|
35
|
+
export {
|
|
36
|
+
INVALID_CIVIL_TIME_CODE,
|
|
37
|
+
INVALID_TIME_ZONE_CODE,
|
|
38
|
+
NONEXISTENT_LOCAL_TIME_CODE,
|
|
39
|
+
resolveZonedLocalTime,
|
|
40
|
+
type FoldPolicy,
|
|
41
|
+
type GapPolicy,
|
|
42
|
+
type LocalTimeTransition,
|
|
43
|
+
type ZonedLocalTime,
|
|
44
|
+
type ZonedLocalTimeCode,
|
|
45
|
+
type ZonedLocalTimeResult,
|
|
46
|
+
} from './zoned-time.js';
|
package/src/locale.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
export type LocalePreference<TLocale extends string> = 'system' | TLocale;
|
|
2
|
+
|
|
3
|
+
const MAX_LOCALE_TAG_LENGTH = 128;
|
|
4
|
+
|
|
5
|
+
interface SupportedLocale<TLocale extends string> {
|
|
6
|
+
readonly canonical: string;
|
|
7
|
+
readonly locale: TLocale;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface LocaleConfiguration<TLocale extends string> {
|
|
11
|
+
readonly fallback: TLocale;
|
|
12
|
+
readonly supported: readonly SupportedLocale<TLocale>[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function canonicalLocale(value: unknown, allowSurroundingWhitespace: boolean): string | null {
|
|
16
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_LOCALE_TAG_LENGTH) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const trimmed = value.trim();
|
|
21
|
+
if (
|
|
22
|
+
trimmed.length === 0 ||
|
|
23
|
+
trimmed.length > MAX_LOCALE_TAG_LENGTH ||
|
|
24
|
+
(!allowSurroundingWhitespace && trimmed !== value)
|
|
25
|
+
) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
return Intl.getCanonicalLocales(trimmed.replaceAll('_', '-'))[0] ?? null;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function localeConfiguration<TLocale extends string>(
|
|
37
|
+
supported: readonly TLocale[],
|
|
38
|
+
fallback: TLocale,
|
|
39
|
+
): LocaleConfiguration<TLocale> {
|
|
40
|
+
const normalized: SupportedLocale<TLocale>[] = [];
|
|
41
|
+
|
|
42
|
+
for (const locale of supported) {
|
|
43
|
+
const canonical = canonicalLocale(locale, false);
|
|
44
|
+
if (canonical !== null && canonical.toLowerCase() !== 'system') {
|
|
45
|
+
normalized.push({ canonical, locale });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const canonicalFallback = canonicalLocale(fallback, false);
|
|
50
|
+
const supportedFallback = normalized.find(({ canonical }) => canonical === canonicalFallback);
|
|
51
|
+
if (supportedFallback === undefined) {
|
|
52
|
+
throw new RangeError('fallback must be a valid member of supported locales');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return { fallback: supportedFallback.locale, supported: normalized };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function exactSupportedLocale<TLocale extends string>(
|
|
59
|
+
canonical: string,
|
|
60
|
+
supported: readonly SupportedLocale<TLocale>[],
|
|
61
|
+
): TLocale | undefined {
|
|
62
|
+
return supported.find((entry) => entry.canonical === canonical)?.locale;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizedPreference<TLocale extends string>(
|
|
66
|
+
value: unknown,
|
|
67
|
+
configuration: LocaleConfiguration<TLocale>,
|
|
68
|
+
): LocalePreference<TLocale> {
|
|
69
|
+
if (value === 'system') {
|
|
70
|
+
return 'system';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const canonical = canonicalLocale(value, false);
|
|
74
|
+
return canonical === null
|
|
75
|
+
? configuration.fallback
|
|
76
|
+
: (exactSupportedLocale(canonical, configuration.supported) ?? configuration.fallback);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function normalizeLocalePreference<TLocale extends string>(options: {
|
|
80
|
+
readonly value: unknown;
|
|
81
|
+
readonly supported: readonly TLocale[];
|
|
82
|
+
readonly fallback: TLocale;
|
|
83
|
+
}): LocalePreference<TLocale> {
|
|
84
|
+
const configuration = localeConfiguration(options.supported, options.fallback);
|
|
85
|
+
return normalizedPreference(options.value, configuration);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function resolveLocale<TLocale extends string>(options: {
|
|
89
|
+
readonly preference: unknown;
|
|
90
|
+
readonly deviceLocales: readonly string[];
|
|
91
|
+
readonly supported: readonly TLocale[];
|
|
92
|
+
readonly fallback: TLocale;
|
|
93
|
+
}): TLocale {
|
|
94
|
+
const configuration = localeConfiguration(options.supported, options.fallback);
|
|
95
|
+
const preference = normalizedPreference(options.preference, configuration);
|
|
96
|
+
if (preference !== 'system') {
|
|
97
|
+
return preference;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const deviceLocales = options.deviceLocales
|
|
101
|
+
.map((locale) => canonicalLocale(locale, true))
|
|
102
|
+
.filter((locale): locale is string => locale !== null);
|
|
103
|
+
|
|
104
|
+
for (const deviceLocale of deviceLocales) {
|
|
105
|
+
const exact = exactSupportedLocale(deviceLocale, configuration.supported);
|
|
106
|
+
if (exact !== undefined) {
|
|
107
|
+
return exact;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const deviceLocale of deviceLocales) {
|
|
112
|
+
const base = deviceLocale.split('-', 1)[0];
|
|
113
|
+
if (base === undefined) {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const exactBase = exactSupportedLocale(base, configuration.supported);
|
|
118
|
+
if (exactBase !== undefined) {
|
|
119
|
+
return exactBase;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const regionalBase = configuration.supported.find(
|
|
123
|
+
({ canonical }) => canonical.split('-', 1)[0] === base,
|
|
124
|
+
);
|
|
125
|
+
if (regionalBase !== undefined) {
|
|
126
|
+
return regionalBase.locale;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return configuration.fallback;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function canonicalizeResolvedLocale(locale: string): string {
|
|
134
|
+
const canonical = canonicalLocale(locale, false);
|
|
135
|
+
const base = canonical?.split('-', 1)[0]?.toLowerCase();
|
|
136
|
+
if (canonical === null || base === 'system' || base === 'und') {
|
|
137
|
+
throw new RangeError('locale must be an explicit, valid locale tag');
|
|
138
|
+
}
|
|
139
|
+
return canonical;
|
|
140
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveZonedLocalTime,
|
|
3
|
+
type FoldPolicy,
|
|
4
|
+
type GapPolicy,
|
|
5
|
+
type LocalTimeTransition,
|
|
6
|
+
type ZonedLocalTimeCode,
|
|
7
|
+
type ZonedLocalTimeResult,
|
|
8
|
+
} from './zoned-time.js';
|
|
9
|
+
|
|
10
|
+
export interface ZonedTimeVectorOutcome {
|
|
11
|
+
readonly gap: GapPolicy;
|
|
12
|
+
readonly fold: FoldPolicy;
|
|
13
|
+
readonly instant?: string;
|
|
14
|
+
readonly error?: ZonedLocalTimeCode;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ZonedTimeVectorCase {
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly civilDate: string;
|
|
20
|
+
readonly civilTime: string;
|
|
21
|
+
readonly timeZone: string;
|
|
22
|
+
readonly transition: LocalTimeTransition | null;
|
|
23
|
+
readonly outcomes: readonly ZonedTimeVectorOutcome[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ZonedTimeVectorFixture {
|
|
27
|
+
readonly version: number;
|
|
28
|
+
readonly gapPolicies: readonly GapPolicy[];
|
|
29
|
+
readonly foldPolicies: readonly FoldPolicy[];
|
|
30
|
+
readonly cases: readonly ZonedTimeVectorCase[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ZonedTimeVectorExpectation =
|
|
34
|
+
| { readonly ok: false; readonly code: ZonedLocalTimeCode }
|
|
35
|
+
| {
|
|
36
|
+
readonly ok: true;
|
|
37
|
+
readonly epochMilliseconds: number;
|
|
38
|
+
readonly transition: LocalTimeTransition | null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** One vector: `actual()` must deep-equal `expected` (`undefined` fields count as absent). */
|
|
42
|
+
export interface ZonedTimeVectorCheck {
|
|
43
|
+
readonly label: string;
|
|
44
|
+
readonly expected: ZonedTimeVectorExpectation;
|
|
45
|
+
readonly actual: () => ZonedLocalTimeResult;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Expands `fixtures/zoned-time/vectors-v1.json` into one check per case and policy pair. */
|
|
49
|
+
export function zonedTimeVectorChecks(fixture: ZonedTimeVectorFixture): ZonedTimeVectorCheck[] {
|
|
50
|
+
return fixture.cases.flatMap((entry) =>
|
|
51
|
+
entry.outcomes.map((outcome) => ({
|
|
52
|
+
label: `${entry.name} gap=${outcome.gap} fold=${outcome.fold}`,
|
|
53
|
+
expected: expectedResult(entry, outcome),
|
|
54
|
+
actual: () =>
|
|
55
|
+
resolveZonedLocalTime({
|
|
56
|
+
civilDate: entry.civilDate,
|
|
57
|
+
civilTime: entry.civilTime,
|
|
58
|
+
timeZone: entry.timeZone,
|
|
59
|
+
gap: outcome.gap,
|
|
60
|
+
fold: outcome.fold,
|
|
61
|
+
}),
|
|
62
|
+
})),
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function expectedResult(
|
|
67
|
+
entry: ZonedTimeVectorCase,
|
|
68
|
+
outcome: ZonedTimeVectorOutcome,
|
|
69
|
+
): ZonedTimeVectorExpectation {
|
|
70
|
+
if (outcome.error !== undefined) {
|
|
71
|
+
return { ok: false, code: outcome.error };
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
ok: true,
|
|
75
|
+
epochMilliseconds: Date.parse(outcome.instant ?? ''),
|
|
76
|
+
transition: entry.transition,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
INVALID_TIME_ZONE_CODE,
|
|
7
|
+
NONEXISTENT_LOCAL_TIME_CODE,
|
|
8
|
+
resolveZonedLocalTime,
|
|
9
|
+
type FoldPolicy,
|
|
10
|
+
type GapPolicy,
|
|
11
|
+
type ZonedLocalTime,
|
|
12
|
+
} from './zoned-time.js';
|
|
13
|
+
import { zonedTimeVectorChecks, type ZonedTimeVectorFixture } from './zoned-time-vectors.js';
|
|
14
|
+
|
|
15
|
+
const fixtureUrl = new URL('../../../../fixtures/zoned-time/vectors-v1.json', import.meta.url);
|
|
16
|
+
const readUtf8File = readFileSync as unknown as (path: URL, encoding: 'utf8') => string;
|
|
17
|
+
const fixture = JSON.parse(readUtf8File(fixtureUrl, 'utf8')) as ZonedTimeVectorFixture;
|
|
18
|
+
|
|
19
|
+
const berlinGap: ZonedLocalTime = {
|
|
20
|
+
civilDate: '2026-03-29',
|
|
21
|
+
civilTime: '02:30',
|
|
22
|
+
timeZone: 'Europe/Berlin',
|
|
23
|
+
gap: 'reject',
|
|
24
|
+
fold: 'earlier',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
describe('zoned local time vectors', () => {
|
|
28
|
+
it('reads version 1 of the shared vectors', () => {
|
|
29
|
+
expect(fixture.version).toBe(1);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('covers every gap and fold policy pair for every case', () => {
|
|
33
|
+
const pairs = fixture.gapPolicies.length * fixture.foldPolicies.length;
|
|
34
|
+
for (const entry of fixture.cases) {
|
|
35
|
+
expect(entry.outcomes).toHaveLength(pairs);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it.each(zonedTimeVectorChecks(fixture))('$label', ({ actual, expected }) => {
|
|
40
|
+
expect(actual()).toEqual(expected);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('resolveZonedLocalTime', () => {
|
|
45
|
+
it('rejects a gap only under the reject policy', () => {
|
|
46
|
+
expect(resolveZonedLocalTime(berlinGap)).toEqual({
|
|
47
|
+
ok: false,
|
|
48
|
+
code: NONEXISTENT_LOCAL_TIME_CODE,
|
|
49
|
+
});
|
|
50
|
+
expect(resolveZonedLocalTime({ ...berlinGap, gap: 'shiftForward' })).toEqual({
|
|
51
|
+
ok: true,
|
|
52
|
+
epochMilliseconds: Date.parse('2026-03-29T01:30:00Z'),
|
|
53
|
+
transition: 'gap',
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('accepts a zone name in any case the runtime canonicalizes', () => {
|
|
58
|
+
expect(
|
|
59
|
+
resolveZonedLocalTime({ ...berlinGap, civilDate: '2026-06-15', timeZone: 'europe/berlin' }),
|
|
60
|
+
).toEqual({
|
|
61
|
+
ok: true,
|
|
62
|
+
epochMilliseconds: Date.parse('2026-06-15T00:30:00Z'),
|
|
63
|
+
transition: 'none',
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('rejects a zone with surrounding whitespace', () => {
|
|
68
|
+
expect(resolveZonedLocalTime({ ...berlinGap, timeZone: ' Europe/Berlin' })).toEqual({
|
|
69
|
+
ok: false,
|
|
70
|
+
code: INVALID_TIME_ZONE_CODE,
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it.each([undefined, 'compatible', 'earlier'])('throws for gap policy %p', (gap) => {
|
|
75
|
+
expect(() => resolveZonedLocalTime({ ...berlinGap, gap: gap as GapPolicy })).toThrow(
|
|
76
|
+
RangeError,
|
|
77
|
+
);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it.each([undefined, 'compatible', 'reject'])('throws for fold policy %p', (fold) => {
|
|
81
|
+
expect(() => resolveZonedLocalTime({ ...berlinGap, fold: fold as FoldPolicy })).toThrow(
|
|
82
|
+
RangeError,
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('checks the policies before the inputs', () => {
|
|
87
|
+
expect(() =>
|
|
88
|
+
resolveZonedLocalTime({ ...berlinGap, civilDate: 'nope', gap: undefined as never }),
|
|
89
|
+
).toThrow(RangeError);
|
|
90
|
+
});
|
|
91
|
+
});
|