@mpfrontend/i18n 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # @mpfrontend/i18n
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Local development package. Runtime: universal. Public API is exported from src/index.ts and compiled
4
+ into dist. Nx owns build, typecheck, lint and test targets. Consumer applications install packed artifacts.
5
+ See ../../docs/IMPLEMENTATION-STATUS.md for observed evidence and remaining work.
6
+
7
+ ## Locales
8
+
9
+ MP Frontend ships one language: English (`en`, left to right), which is also the default. Supporting
10
+ left-to-right and right-to-left locales is a base capability; which other languages exist is each
11
+ product's decision, made in its own front-end repository, never in MP Frontend.
12
+
13
+ `createLocaleRegistry({locales, defaultLocale})` configures an app's own set: each entry names its
14
+ `direction` (`ltr` or `rtl`) and, optionally, a `numberingSystem` for Intl digits. The default is
15
+ `defaultLocale`, or `en` when it is not set. A product may add locales next to English, or register only
16
+ its own locale and make it the default; a registry without `en` must name its default. `locale(value)`
17
+ returns a registered code or the default, and `direction` comes from the registry, so the document's
18
+ default direction follows the default locale. `Locale` is a plain locale code (a BCP 47 tag): MP Frontend
19
+ enumerates no language, and `LocaleOf<typeof registry>` is the type of one registry's codes. The built-in
20
+ `locales` registry, and the `locale` and `direction` helpers that use it, know English only.
21
+
22
+ A product adds a locale in its own repository, for example `'<code>': { direction: 'rtl' }` in its
23
+ registry, one `messages/<code>.ts` catalog per catalog set and the matching entry in each set's
24
+ `translations`; the catalog check then fails until every set has the new catalog.
25
+
26
+ `negotiateLocale(header, supported, defaultLocale)` picks the best allowlisted locale for an
27
+ Accept-Language header by quality, exact range and primary language; malformed or oversized input yields
28
+ the default, and the result is always a member of the allowlist, never text from the header. The Security
29
+ BFF uses it for the language it sends upstream.
30
+
31
+ `formatNumber` and `formatValue` format numbers with the locale's digits through Intl, or with the
32
+ registry's `numberingSystem` for that locale; strings are never reinterpreted. `formatValue` shows a
33
+ boolean with the product's own text when it passes `labels` (`{true, false}`), and with the built-in
34
+ English text otherwise. `translator(locale)(key)` and `catalogs` hold the built-in English messages only;
35
+ product text belongs to the product's catalogs.
36
+
37
+ ## Message catalogs
38
+
39
+ A consumer owns its catalogs. The catalog of the default locale defines the keys:
40
+ `defineMessages({...})` keeps their literal types, and every other locale is typed
41
+ `Translation<typeof base>`, so a key missing in a locale is a type error. `createMessages({defaultLocale,
42
+ base, translations, core, numberingSystem})` builds one translator per locale; `core` is the separate set of
43
+ neutral MP Frontend messages (`coreMessages`, English only) that the catalog may override by defining the
44
+ same key. A translator looks a message up in the requested locale and then in the set's default locale, so
45
+ a product whose default locale is its own never shows the English core text: it defines every key it
46
+ uses. The numbering system of a locale is passed to Intl as an option, so it also applies to a locale that
47
+ the runtime's Intl data does not know.
48
+
49
+ Messages use ICU MessageFormat: named parameters placed by the message (`Page {page, number} of {count,
50
+ number}`), `plural`, `selectordinal` and `select` by locale, and `number`, `date` and `time` arguments
51
+ formatted through Intl. The parameters of a message are part of its type: `t('pageOf', {page, count})`
52
+ compiles, while a missing or extra parameter, or a text where a number is expected, is a type error. A
53
+ missing message falls back, key by key, to the default locale; a formatting failure names the key, never a
54
+ parameter value.
55
+
56
+ Formatting uses FormatJS `intl-messageformat` 11.2.15 with its parser `@formatjs/icu-messageformat-parser`
57
+ 3.5.18. The reason: ICU plural and select rules and the grammar are easy to get wrong, and this is the
58
+ established ICU implementation for JavaScript, built on Intl.PluralRules, Intl.NumberFormat and
59
+ Intl.DateTimeFormat. `checkCatalogs` and `messageArguments` are the check behind
60
+ `mpfrontend catalog check`: a key missing in a locale or extra, an unused key, a key that code asks a
61
+ translator for and the base does not define (`UNDEFINED_KEY`), a message that does not parse and a
62
+ parameter that differs between locales each fail it. A typed translator accepts only the base's keys, so
63
+ the base defines every key its code uses.
64
+
65
+ `translator(locale)(key)` and `catalogs` keep working for their existing English keys.
66
+
67
+ ## Preference cookie
68
+
69
+ `createPreferenceCookie({name, locales, themes})` is the contract of the one readable cookie that carries a
70
+ person's language and theme and that an app shares with the identity provider's pages on a common parent
71
+ domain. Its value is `lang=<locale>&theme=<theme>` (cookie values cannot hold `;`), each value must be in
72
+ the allowlist, and `parse`/`read` drop anything else; an invalid value is ignored and never echoed. The
73
+ Security BFF reads it for `ui_locales`, and an app's server reads it for the first paint, setting `lang`,
74
+ `dir` and the theme on the document before any script runs. It never carries an identity claim and never
75
+ decides anything about authority.
@@ -0,0 +1,120 @@
1
+ export declare const catalogs: {
2
+ readonly en: {
3
+ readonly title: "MP Frontend";
4
+ readonly catalog: "Catalog";
5
+ readonly refresh: "Refresh";
6
+ readonly loading: "Loading";
7
+ readonly unavailable: "Backend is unavailable. Try again.";
8
+ readonly empty: "No records found.";
9
+ readonly previous: "Previous";
10
+ readonly next: "Next";
11
+ readonly page: "Page";
12
+ readonly language: "Language";
13
+ readonly brand: "Brand";
14
+ readonly mode: "Appearance";
15
+ readonly light: "Light";
16
+ readonly dark: "Dark";
17
+ readonly system: "System";
18
+ readonly docs: "API documentation";
19
+ readonly source: "Connected to MP Core";
20
+ readonly search: "Search";
21
+ readonly apply: "Apply";
22
+ readonly readOnly: "Read-only public catalog";
23
+ readonly fields: "Fields";
24
+ readonly true: "Yes";
25
+ readonly false: "No";
26
+ readonly detail: "Details";
27
+ readonly back: "Back";
28
+ readonly save: "Save";
29
+ readonly forbidden: "This operation is not permitted.";
30
+ readonly invalid: "Check the permitted fields.";
31
+ readonly remoteChange: "Data changed remotely. Your edits are preserved.";
32
+ readonly skipToContent: "Skip to content";
33
+ readonly navigation: "Main navigation";
34
+ };
35
+ };
36
+ export type MessageKey = keyof typeof catalogs.en;
37
+ declare const neutral: readonly ["loading", "unavailable", "empty", "previous", "next", "page", "language", "brand", "mode", "light", "dark", "system", "search", "apply", "fields", "true", "false", "detail", "back", "save", "refresh", "forbidden", "invalid", "remoteChange", "skipToContent", "navigation"];
38
+ export type CoreMessageKey = (typeof neutral)[number];
39
+ /**
40
+ * The neutral messages of MP Frontend, separate from any product text, in English: the only language that
41
+ * MP Frontend ships. A product's catalog set overrides any of them by defining the same key. A translator
42
+ * looks a message up in the requested locale and then in the set's default locale only, so a product whose
43
+ * default locale is not English never shows this English text. `catalogs` keeps its earlier keys.
44
+ */
45
+ export declare const coreMessages: Readonly<{
46
+ en: Readonly<Record<CoreMessageKey, string>>;
47
+ }>;
48
+ export { createMessages, defineMessages, checkCatalogs, messageArguments, MessageError, type Catalog, type Translation, type MessageArguments, type ArgumentList, type Translate, type Messages, type MessageValue, type ArgumentShape, type CatalogProblem } from './messages.js';
49
+ export type Direction = 'ltr' | 'rtl';
50
+ /** One locale of a registry: its writing direction and, optionally, the digits Intl uses for it. */
51
+ export type LocaleDefinition = Readonly<{
52
+ direction: Direction;
53
+ numberingSystem?: string;
54
+ }>;
55
+ /**
56
+ * The one locale MP Frontend ships: English, left to right. A product registers its own locales, left to
57
+ * right or right to left, in its own repository with `createLocaleRegistry`, never by editing MP Frontend.
58
+ */
59
+ export declare const builtInLocales: {
60
+ readonly en: {
61
+ readonly direction: "ltr";
62
+ };
63
+ };
64
+ /**
65
+ * A locale code (a BCP 47 language tag). MP Frontend enumerates no language: the set of locales is the
66
+ * product's, and `LocaleOf<typeof registry>` is the type of one product registry's codes.
67
+ */
68
+ export type Locale = string;
69
+ export type LocaleOf<R extends LocaleRegistry<string>> = R['locales'][number];
70
+ export type LocaleRegistry<L extends string = string> = Readonly<{
71
+ locales: readonly L[];
72
+ defaultLocale: L;
73
+ /** The registered code itself, or the default for anything else. */
74
+ locale: (value: unknown) => L;
75
+ direction: (value: string) => Direction;
76
+ numberingSystem: (value: string) => string | undefined;
77
+ /** The best registered locale for an Accept-Language header, or the default. */
78
+ negotiate: (header: string | null | undefined) => L;
79
+ }>;
80
+ /**
81
+ * Picks the best of `supported` for an Accept-Language header (RFC 9110 section 12.5.4) by quality, then by
82
+ * an exact range and then by the range's primary language. Malformed or oversized input yields the
83
+ * default; the result is always a member of `supported`, never text taken from the header.
84
+ */
85
+ export declare function negotiateLocale<const L extends string>(header: string | null | undefined, supported: readonly L[], defaultLocale: L): L;
86
+ /**
87
+ * A locale registry configured per app. The default is `defaultLocale`, or `en` when it is not set; a
88
+ * registry without English names its own default, which may be its only locale.
89
+ */
90
+ export declare function createLocaleRegistry<const L extends string>(options: Readonly<{
91
+ locales: Readonly<Record<L, LocaleDefinition>>;
92
+ defaultLocale?: NoInfer<L>;
93
+ }>): LocaleRegistry<L>;
94
+ /** The built-in registry: English only, and the default. A product passes its own registry instead. */
95
+ export declare const locales: Readonly<{
96
+ locales: readonly "en"[];
97
+ defaultLocale: "en";
98
+ /** The registered code itself, or the default for anything else. */
99
+ locale: (value: unknown) => "en";
100
+ direction: (value: string) => Direction;
101
+ numberingSystem: (value: string) => string | undefined;
102
+ /** The best registered locale for an Accept-Language header, or the default. */
103
+ negotiate: (header: string | null | undefined) => "en";
104
+ }>;
105
+ export declare function locale(value: unknown): Locale;
106
+ export declare function direction(value: string): Direction;
107
+ /** The built-in English messages; any other locale falls back, key by key, to English. */
108
+ export declare function translator(value: string): (key: MessageKey) => string;
109
+ /** The text of `true` and `false` from a product's own catalog. */
110
+ export type BooleanLabels = Readonly<{
111
+ true: string;
112
+ false: string;
113
+ }>;
114
+ /**
115
+ * Numbers use the locale's own digits through Intl; strings are never reinterpreted. A boolean is shown
116
+ * with `labels`, the product's own text, or with the built-in English text when no labels are given.
117
+ */
118
+ export declare function formatValue(value: unknown, language: string, registry?: LocaleRegistry, labels?: BooleanLabels): string;
119
+ export declare function formatNumber(value: number, language: string, options?: Intl.NumberFormatOptions, registry?: LocaleRegistry): string;
120
+ export { createPreferenceCookie, type Preference, type PreferenceCookie, type PreferenceCookieContract } from './preferences.js';
package/dist/index.js ADDED
@@ -0,0 +1,126 @@
1
+ export const catalogs = {
2
+ en: { title: 'MP Frontend', catalog: 'Catalog', refresh: 'Refresh', loading: 'Loading', unavailable: 'Backend is unavailable. Try again.', empty: 'No records found.', previous: 'Previous', next: 'Next', page: 'Page', language: 'Language', brand: 'Brand', mode: 'Appearance', light: 'Light', dark: 'Dark', system: 'System', docs: 'API documentation', source: 'Connected to MP Core', search: 'Search', apply: 'Apply', readOnly: 'Read-only public catalog', fields: 'Fields', true: 'Yes', false: 'No', detail: 'Details', back: 'Back', save: 'Save', forbidden: 'This operation is not permitted.', invalid: 'Check the permitted fields.', remoteChange: 'Data changed remotely. Your edits are preserved.', skipToContent: 'Skip to content', navigation: 'Main navigation' },
3
+ };
4
+ const neutral = ['loading', 'unavailable', 'empty', 'previous', 'next', 'page', 'language', 'brand', 'mode', 'light', 'dark', 'system', 'search', 'apply', 'fields', 'true', 'false', 'detail', 'back', 'save', 'refresh', 'forbidden', 'invalid', 'remoteChange', 'skipToContent', 'navigation'];
5
+ /**
6
+ * The neutral messages of MP Frontend, separate from any product text, in English: the only language that
7
+ * MP Frontend ships. A product's catalog set overrides any of them by defining the same key. A translator
8
+ * looks a message up in the requested locale and then in the set's default locale only, so a product whose
9
+ * default locale is not English never shows this English text. `catalogs` keeps its earlier keys.
10
+ */
11
+ export const coreMessages = {
12
+ en: Object.fromEntries(neutral.map(key => [key, catalogs.en[key]])),
13
+ };
14
+ export { createMessages, defineMessages, checkCatalogs, messageArguments, MessageError } from './messages.js';
15
+ /**
16
+ * The one locale MP Frontend ships: English, left to right. A product registers its own locales, left to
17
+ * right or right to left, in its own repository with `createLocaleRegistry`, never by editing MP Frontend.
18
+ */
19
+ export const builtInLocales = {
20
+ en: { direction: 'ltr' },
21
+ };
22
+ const localeCode = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;
23
+ const languageRange = /^(?:\*|[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4})$/;
24
+ const MAX_HEADER = 256, MAX_RANGES = 16;
25
+ /**
26
+ * Picks the best of `supported` for an Accept-Language header (RFC 9110 section 12.5.4) by quality, then by
27
+ * an exact range and then by the range's primary language. Malformed or oversized input yields the
28
+ * default; the result is always a member of `supported`, never text taken from the header.
29
+ */
30
+ export function negotiateLocale(header, supported, defaultLocale) {
31
+ if (!supported.includes(defaultLocale))
32
+ throw new Error('INVALID_DEFAULT_LOCALE');
33
+ if (typeof header !== 'string' || header.length > MAX_HEADER)
34
+ return defaultLocale;
35
+ const parts = header.split(',');
36
+ if (parts.length > MAX_RANGES)
37
+ return defaultLocale;
38
+ const ranges = [];
39
+ for (const [order, part] of parts.entries()) {
40
+ const [rawRange, ...parameters] = part.split(';').map(value => value.trim());
41
+ if (!rawRange || !languageRange.test(rawRange))
42
+ continue;
43
+ let quality = 1;
44
+ for (const parameter of parameters) {
45
+ const match = /^q=(0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.exec(parameter);
46
+ if (!match) {
47
+ quality = -1;
48
+ break;
49
+ }
50
+ quality = Number(match[1]);
51
+ }
52
+ if (quality > 0)
53
+ ranges.push({ range: rawRange.toLowerCase(), quality, order });
54
+ }
55
+ ranges.sort((left, right) => right.quality - left.quality || left.order - right.order);
56
+ const lower = supported.map(code => code.toLowerCase());
57
+ for (const { range } of ranges) {
58
+ if (range === '*')
59
+ return defaultLocale;
60
+ const exact = lower.indexOf(range);
61
+ if (exact >= 0)
62
+ return supported[exact];
63
+ const primary = lower.indexOf(range.split('-')[0]);
64
+ if (primary >= 0)
65
+ return supported[primary];
66
+ }
67
+ return defaultLocale;
68
+ }
69
+ /**
70
+ * A locale registry configured per app. The default is `defaultLocale`, or `en` when it is not set; a
71
+ * registry without English names its own default, which may be its only locale.
72
+ */
73
+ export function createLocaleRegistry(options) {
74
+ const codes = Object.keys(options.locales);
75
+ if (!codes.length)
76
+ throw new Error('EMPTY_LOCALE_REGISTRY');
77
+ for (const code of codes) {
78
+ const definition = options.locales[code];
79
+ if (!localeCode.test(code) || (definition.direction !== 'ltr' && definition.direction !== 'rtl'))
80
+ throw new Error('INVALID_LOCALE_DEFINITION');
81
+ if (definition.numberingSystem !== undefined && !/^[a-z]{3,8}$/.test(definition.numberingSystem))
82
+ throw new Error('INVALID_LOCALE_DEFINITION');
83
+ }
84
+ const defaultLocale = options.defaultLocale ?? 'en';
85
+ if (!codes.includes(defaultLocale))
86
+ throw new Error('INVALID_DEFAULT_LOCALE');
87
+ const known = (value) => typeof value === 'string' && codes.includes(value);
88
+ return Object.freeze({
89
+ locales: Object.freeze([...codes]),
90
+ defaultLocale,
91
+ locale: (value) => known(value) ? value : defaultLocale,
92
+ direction: (value) => (known(value) ? options.locales[value] : options.locales[defaultLocale]).direction,
93
+ numberingSystem: (value) => (known(value) ? options.locales[value] : options.locales[defaultLocale]).numberingSystem,
94
+ negotiate: (header) => negotiateLocale(header, codes, defaultLocale),
95
+ });
96
+ }
97
+ /** The built-in registry: English only, and the default. A product passes its own registry instead. */
98
+ export const locales = createLocaleRegistry({ locales: builtInLocales });
99
+ export function locale(value) { return locales.locale(value); }
100
+ export function direction(value) { return locales.direction(value); }
101
+ /** The built-in English messages; any other locale falls back, key by key, to English. */
102
+ export function translator(value) {
103
+ const own = catalogs[value];
104
+ return key => own?.[key] ?? catalogs.en[key];
105
+ }
106
+ /**
107
+ * Numbers use the locale's own digits through Intl; strings are never reinterpreted. A boolean is shown
108
+ * with `labels`, the product's own text, or with the built-in English text when no labels are given.
109
+ */
110
+ export function formatValue(value, language, registry = locales, labels) {
111
+ if (value === null || value === undefined)
112
+ return '—';
113
+ if (typeof value === 'boolean')
114
+ return labels ? (value ? labels.true : labels.false) : translator(language)(value ? 'true' : 'false');
115
+ if (typeof value === 'number')
116
+ return formatNumber(value, language, {}, registry);
117
+ if (typeof value === 'object')
118
+ return JSON.stringify(value);
119
+ return String(value);
120
+ }
121
+ export function formatNumber(value, language, options = {}, registry = locales) {
122
+ const numberingSystem = registry.numberingSystem(language);
123
+ return new Intl.NumberFormat(registry.locale(language), { maximumFractionDigits: 8, ...(numberingSystem ? { numberingSystem } : {}), ...options }).format(value);
124
+ }
125
+ export { createPreferenceCookie } from './preferences.js';
126
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,EAAE,EAAE,EAAE,KAAK,EAAC,aAAa,EAAE,OAAO,EAAC,SAAS,EAAE,OAAO,EAAC,SAAS,EAAE,OAAO,EAAC,SAAS,EAAE,WAAW,EAAC,oCAAoC,EAAE,KAAK,EAAC,mBAAmB,EAAE,QAAQ,EAAC,UAAU,EAAE,IAAI,EAAC,MAAM,EAAE,IAAI,EAAC,MAAM,EAAE,QAAQ,EAAC,UAAU,EAAE,KAAK,EAAC,OAAO,EAAE,IAAI,EAAC,YAAY,EAAE,KAAK,EAAC,OAAO,EAAE,IAAI,EAAC,MAAM,EAAE,MAAM,EAAC,QAAQ,EAAE,IAAI,EAAC,mBAAmB,EAAE,MAAM,EAAC,sBAAsB,EAAE,MAAM,EAAC,QAAQ,EAAE,KAAK,EAAC,OAAO,EAAE,QAAQ,EAAC,0BAA0B,EAAE,MAAM,EAAC,QAAQ,EAAE,IAAI,EAAC,KAAK,EAAE,KAAK,EAAC,IAAI,EAAE,MAAM,EAAC,SAAS,EAAE,IAAI,EAAC,MAAM,EAAE,IAAI,EAAC,MAAM,EAAE,SAAS,EAAC,kCAAkC,EAAE,OAAO,EAAC,6BAA6B,EAAE,YAAY,EAAC,kDAAkD,EAAE,aAAa,EAAC,iBAAiB,EAAE,UAAU,EAAC,iBAAiB,EAAE;CACptB,CAAC;AAEX,MAAM,OAAO,GAAG,CAAC,SAAS,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAA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CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnK,CAAC;AACD,OAAO,EAAE,sBAAsB,EAAyE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Typed ICU MessageFormat catalogs. A consumer's base-locale catalog defines the keys and, through its
3
+ * literal types, the named parameters of every message; every other locale has the same keys. Formatting
4
+ * uses FormatJS intl-messageformat, which applies Intl.PluralRules, Intl.NumberFormat and
5
+ * Intl.DateTimeFormat for the locale.
6
+ */
7
+ export type Catalog = Readonly<Record<string, string>>;
8
+ /** Another locale of a base catalog: the same keys, any text. */
9
+ export type Translation<Base extends Catalog> = Readonly<{
10
+ [K in keyof Base]: string;
11
+ }>;
12
+ type Trim<S extends string> = S extends ` ${infer R}` | `\n${infer R}` ? Trim<R> : S extends `${infer R} ` | `${infer R}\n` ? Trim<R> : S;
13
+ /** The top-level `{...}` bodies of a message, with nested braces kept inside each body. */
14
+ type Bodies<S extends string, Depth extends 0[] = [], Current extends string = '', Found extends string = never> = S extends `${infer C}${infer R}` ? C extends '{' ? Depth extends [] ? Bodies<R, [0], '', Found> : Bodies<R, [...Depth, 0], `${Current}{`, Found> : C extends '}' ? Depth extends [0] ? Bodies<R, [], '', Found | Current> : Depth extends [0, ...infer Rest extends 0[]] ? Bodies<R, Rest, `${Current}}`, Found> : Bodies<R, Depth, Current, Found> : Depth extends [] ? Bodies<R, Depth, Current, Found> : Bodies<R, Depth, `${Current}${C}`, Found> : Found;
15
+ type Kind<Body extends string> = Body extends `${string},${infer Rest}` ? Trim<Rest extends `${infer K},${string}` ? K : Rest> : '';
16
+ type ArgumentName<Body extends string> = Trim<Body extends `${infer N},${string}` ? N : Body>;
17
+ type Options<Body extends string> = Body extends `${string},${string},${infer Rest}` ? Rest : '';
18
+ type ValueOf<K extends string> = K extends 'plural' | 'selectordinal' | 'number' ? number : K extends 'date' | 'time' ? Date | number : K extends 'select' ? string : string | number;
19
+ type IsName<N extends string> = N extends '' | `${string} ${string}` | `${string}#${string}` ? false : true;
20
+ type ArgumentsOf<Body extends string> = IsName<ArgumentName<Body>> extends true ? {
21
+ [P in ArgumentName<Body>]: ValueOf<Kind<Body>>;
22
+ } & (Kind<Body> extends 'plural' | 'select' | 'selectordinal' ? NestedArguments<Bodies<Options<Body>>> : unknown) : unknown;
23
+ type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
24
+ type NestedArguments<Messages extends string> = UnionToIntersection<Messages extends string ? MessageArguments<Messages> : never>;
25
+ type Flatten<T> = {
26
+ [K in keyof T]: T[K];
27
+ };
28
+ /** The named parameters of an ICU message; `{}` when it has none. */
29
+ export type MessageArguments<S extends string> = Flatten<UnionToIntersection<Bodies<S> extends infer B ? B extends string ? ArgumentsOf<B> : never : never>>;
30
+ /** The arguments a translator call takes for one message: none, or exactly its named parameters. */
31
+ export type ArgumentList<S extends string> = keyof MessageArguments<S> extends never ? [] : [values: MessageArguments<S>];
32
+ /** Keeps the literal types of a base catalog, so that keys and parameters are checked by TypeScript. */
33
+ export declare function defineMessages<const M extends Catalog>(messages: M): M;
34
+ export type MessageValue = string | number | boolean | Date | null | undefined;
35
+ export type Translate<M extends Catalog> = <K extends keyof M & string>(key: K, ...values: ArgumentList<M[K]>) => string;
36
+ export type Messages<M extends Catalog, L extends string = string> = Readonly<{
37
+ locales: readonly L[];
38
+ defaultLocale: L;
39
+ /** A translator for one locale. A missing message falls back, key by key, to the default locale. */
40
+ translator: (locale: string) => Translate<M>;
41
+ }>;
42
+ export declare class MessageError extends Error {
43
+ }
44
+ /**
45
+ * Builds the translators of one catalog set: the base catalog of the default locale, which defines the
46
+ * keys and parameters, and its translations. `core` holds messages that the set may override, such as the
47
+ * neutral MP Frontend messages; the set's own keys win. `numberingSystem` returns the Intl digits of a
48
+ * locale when the app's registry configures them.
49
+ */
50
+ export declare function createMessages<const M extends Catalog, const L extends string>(options: Readonly<{
51
+ defaultLocale: L;
52
+ base: M;
53
+ translations: Readonly<Record<string, Translation<M>>>;
54
+ core?: Readonly<Record<string, Catalog>>;
55
+ numberingSystem?: (locale: string) => string | undefined;
56
+ }>): Messages<M, L>;
57
+ export type ArgumentShape = Readonly<Record<string, 'text' | 'number' | 'date' | 'time' | 'select' | 'plural'>>;
58
+ /** The named parameters of a message and their kinds, from the ICU parser. */
59
+ export declare function messageArguments(message: string): ArgumentShape;
60
+ export type CatalogProblem = Readonly<{
61
+ code: 'MISSING_LOCALE' | 'UNKNOWN_LOCALE' | 'MISSING_KEY' | 'EXTRA_KEY' | 'UNUSED_KEY' | 'UNDEFINED_KEY' | 'PARAMETER_MISMATCH' | 'INVALID_MESSAGE';
62
+ locale?: string;
63
+ key?: string;
64
+ }>;
65
+ /**
66
+ * Checks one catalog set: every locale has exactly the base keys, every message parses, every locale
67
+ * takes the same parameters as the base message, every key is used by code, and every key that code asks a
68
+ * translator for (`usedKeys`) is defined by the base. A typed translator cannot reach a key outside the base,
69
+ * so a key used without being defined is reported rather than left to a fallback.
70
+ */
71
+ export declare function checkCatalogs(input: Readonly<{
72
+ defaultLocale: string;
73
+ locales: readonly string[];
74
+ catalogs: Readonly<Record<string, Catalog | undefined>>;
75
+ isUsed: (key: string) => boolean;
76
+ usedKeys?: Iterable<string>;
77
+ }>): CatalogProblem[];
78
+ export {};
@@ -0,0 +1,156 @@
1
+ import { IntlMessageFormat } from 'intl-messageformat';
2
+ import { parse, TYPE } from '@formatjs/icu-messageformat-parser';
3
+ /** Keeps the literal types of a base catalog, so that keys and parameters are checked by TypeScript. */
4
+ export function defineMessages(messages) {
5
+ return messages;
6
+ }
7
+ export class MessageError extends Error {
8
+ }
9
+ /**
10
+ * Intl formatters that pass the registry's digits as an option. A Unicode extension in the locale tag
11
+ * (`-u-nu-`) is dropped when the runtime's Intl data does not know the locale, so a product's own locale
12
+ * would lose its digits; an option applies to whatever locale Intl resolves.
13
+ */
14
+ const digitFormatters = new Map();
15
+ function formattersWith(numberingSystem) {
16
+ let formatters = digitFormatters.get(numberingSystem);
17
+ if (!formatters) {
18
+ formatters = {
19
+ getNumberFormat: (locales, options) => new Intl.NumberFormat(locales, { ...options, numberingSystem }),
20
+ getDateTimeFormat: (locales, options) => new Intl.DateTimeFormat(locales, { ...options, numberingSystem }),
21
+ getPluralRules: (locales, options) => new Intl.PluralRules(locales, options),
22
+ };
23
+ digitFormatters.set(numberingSystem, formatters);
24
+ }
25
+ return formatters;
26
+ }
27
+ /**
28
+ * Builds the translators of one catalog set: the base catalog of the default locale, which defines the
29
+ * keys and parameters, and its translations. `core` holds messages that the set may override, such as the
30
+ * neutral MP Frontend messages; the set's own keys win. `numberingSystem` returns the Intl digits of a
31
+ * locale when the app's registry configures them.
32
+ */
33
+ export function createMessages(options) {
34
+ const catalogs = { ...options.translations, [options.defaultLocale]: options.base };
35
+ const locales = [options.defaultLocale, ...Object.keys(options.translations).filter(code => code !== options.defaultLocale)];
36
+ const formatters = new Map();
37
+ const lookup = (locale, key) => {
38
+ for (const candidate of [locale, options.defaultLocale]) {
39
+ const own = catalogs[candidate]?.[key];
40
+ if (own !== undefined)
41
+ return [candidate, own];
42
+ const core = options.core?.[candidate]?.[key];
43
+ if (core !== undefined)
44
+ return [candidate, core];
45
+ }
46
+ return undefined;
47
+ };
48
+ return Object.freeze({
49
+ locales: Object.freeze([...locales]),
50
+ defaultLocale: options.defaultLocale,
51
+ translator: (requested) => {
52
+ const locale = locales.includes(requested) ? requested : options.defaultLocale;
53
+ return ((key, values) => {
54
+ const found = lookup(locale, key);
55
+ if (!found)
56
+ throw new MessageError('UNKNOWN_MESSAGE:' + key);
57
+ const [source, message] = found;
58
+ const numbering = options.numberingSystem?.(source);
59
+ const cacheKey = source + '\u0000' + (numbering ?? '') + '\u0000' + key + '\u0000' + message;
60
+ let formatter = formatters.get(cacheKey);
61
+ if (!formatter) {
62
+ formatter = new IntlMessageFormat(message, source, undefined, { ignoreTag: true, ...(numbering ? { formatters: formattersWith(numbering) } : {}) });
63
+ formatters.set(cacheKey, formatter);
64
+ }
65
+ try {
66
+ return String(formatter.format(values));
67
+ }
68
+ catch {
69
+ // The values are never part of the error: a parameter may hold personal data.
70
+ throw new MessageError('MESSAGE_ARGUMENTS_INVALID:' + key);
71
+ }
72
+ });
73
+ },
74
+ });
75
+ }
76
+ /** The named parameters of a message and their kinds, from the ICU parser. */
77
+ export function messageArguments(message) {
78
+ const found = {};
79
+ const visit = (elements) => {
80
+ for (const element of elements) {
81
+ if (element.type === TYPE.argument)
82
+ found[element.value] = 'text';
83
+ else if (element.type === TYPE.number)
84
+ found[element.value] = 'number';
85
+ else if (element.type === TYPE.date)
86
+ found[element.value] = 'date';
87
+ else if (element.type === TYPE.time)
88
+ found[element.value] = 'time';
89
+ else if (element.type === TYPE.select || element.type === TYPE.plural) {
90
+ found[element.value] = element.type === TYPE.select ? 'select' : 'plural';
91
+ for (const option of Object.values(element.options))
92
+ visit(option.value);
93
+ }
94
+ else if (element.type === TYPE.tag)
95
+ visit(element.children);
96
+ }
97
+ };
98
+ visit(parse(message, { ignoreTag: true }));
99
+ return found;
100
+ }
101
+ /**
102
+ * Checks one catalog set: every locale has exactly the base keys, every message parses, every locale
103
+ * takes the same parameters as the base message, every key is used by code, and every key that code asks a
104
+ * translator for (`usedKeys`) is defined by the base. A typed translator cannot reach a key outside the base,
105
+ * so a key used without being defined is reported rather than left to a fallback.
106
+ */
107
+ export function checkCatalogs(input) {
108
+ const problems = [];
109
+ const base = input.catalogs[input.defaultLocale];
110
+ if (!base)
111
+ return [{ code: 'MISSING_LOCALE', locale: input.defaultLocale }];
112
+ const shapes = new Map();
113
+ for (const [key, message] of Object.entries(base)) {
114
+ try {
115
+ shapes.set(key, JSON.stringify(Object.entries(messageArguments(message)).sort()));
116
+ }
117
+ catch {
118
+ problems.push({ code: 'INVALID_MESSAGE', locale: input.defaultLocale, key });
119
+ }
120
+ if (!input.isUsed(key))
121
+ problems.push({ code: 'UNUSED_KEY', key });
122
+ }
123
+ for (const key of new Set(input.usedKeys ?? []))
124
+ if (!Object.hasOwn(base, key))
125
+ problems.push({ code: 'UNDEFINED_KEY', key });
126
+ for (const locale of input.locales) {
127
+ if (locale === input.defaultLocale)
128
+ continue;
129
+ const catalog = input.catalogs[locale];
130
+ if (!catalog) {
131
+ problems.push({ code: 'MISSING_LOCALE', locale });
132
+ continue;
133
+ }
134
+ for (const key of Object.keys(base))
135
+ if (!(key in catalog))
136
+ problems.push({ code: 'MISSING_KEY', locale, key });
137
+ for (const [key, message] of Object.entries(catalog)) {
138
+ if (!(key in base)) {
139
+ problems.push({ code: 'EXTRA_KEY', locale, key });
140
+ continue;
141
+ }
142
+ let shape;
143
+ try {
144
+ shape = JSON.stringify(Object.entries(messageArguments(message)).sort());
145
+ }
146
+ catch {
147
+ problems.push({ code: 'INVALID_MESSAGE', locale, key });
148
+ continue;
149
+ }
150
+ if (shapes.has(key) && shapes.get(key) !== shape)
151
+ problems.push({ code: 'PARAMETER_MISMATCH', locale, key });
152
+ }
153
+ }
154
+ return problems;
155
+ }
156
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.js","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAmB,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,KAAK,EAAE,IAAI,EAA6B,MAAM,oCAAoC,CAAC;AA6C5F,wGAAwG;AACxG,MAAM,UAAU,cAAc,CAA0B,QAAW;IACjE,OAAO,QAAQ,CAAC;AAClB,CAAC;AAYD,MAAM,OAAO,YAAa,SAAQ,KAAK;CAAG;AAE1C;;;;GAIG;AACH,MAAM,eAAe,GAAG,IAAI,GAAG,EAAsB,CAAC;AACtD,SAAS,cAAc,CAAC,eAAuB;IAC7C,IAAI,UAAU,GAAG,eAAe,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IACtD,IAAI,C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AO,CAAC,OAAO,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC;gBAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;gBAAC,SAAS;YAAC,CAAC;YACpF,IAAI,KAAa,CAAC;YAClB,IAAI,CAAC;gBAAC,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YAAC,CAAC;YACjF,MAAM,CAAC;gBAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;gBAAC,SAAS;YAAC,CAAC;YAC5E,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,KAAK;gBAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC/G,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The preference cookie: one readable cookie that carries a person's language and theme, shared between an
3
+ * app and the identity provider's pages. Its value is `lang=<locale>&theme=<theme>`; each value must be in
4
+ * the configured allowlist, and anything else is ignored, never echoed. It never carries identity or
5
+ * authority: a server reads it only to choose a presentation.
6
+ */
7
+ export type PreferenceCookieContract = Readonly<{
8
+ name: string;
9
+ locales: readonly string[];
10
+ themes: readonly string[];
11
+ }>;
12
+ export type Preference = Readonly<{
13
+ lang?: string;
14
+ theme?: string;
15
+ }>;
16
+ export type PreferenceCookie = Readonly<{
17
+ name: string;
18
+ /** The allowlisted preferences of a raw cookie value; an invalid part is dropped. */
19
+ parse: (value: string | null | undefined) => Preference;
20
+ /** The allowlisted preferences of a Cookie request header. */
21
+ read: (header: string | null | undefined) => Preference;
22
+ /** The cookie value for allowlisted preferences; a value outside the allowlist is refused. */
23
+ value: (preference: Preference) => string;
24
+ }>;
25
+ export declare function createPreferenceCookie(contract: PreferenceCookieContract): PreferenceCookie;
@@ -0,0 +1,48 @@
1
+ const cookieName = /^(?:__Secure-)?[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/;
2
+ const token = /^[A-Za-z0-9-]{1,32}$/;
3
+ const MAX_VALUE = 256;
4
+ export function createPreferenceCookie(contract) {
5
+ if (!cookieName.test(contract.name) || contract.name.startsWith('__Host-'))
6
+ throw new Error('INVALID_PREFERENCE_COOKIE_NAME');
7
+ for (const value of [...contract.locales, ...contract.themes])
8
+ if (!token.test(value))
9
+ throw new Error('INVALID_PREFERENCE_VALUE');
10
+ const allowed = { lang: contract.locales, theme: contract.themes };
11
+ const parse = (value) => {
12
+ if (typeof value !== 'string' || value.length > MAX_VALUE)
13
+ return {};
14
+ const found = {};
15
+ for (const part of value.split('&')) {
16
+ const separator = part.indexOf('=');
17
+ if (separator < 0)
18
+ continue;
19
+ const key = part.slice(0, separator), entry = part.slice(separator + 1);
20
+ if ((key === 'lang' || key === 'theme') && found[key] === undefined && allowed[key].includes(entry))
21
+ found[key] = entry;
22
+ }
23
+ return found;
24
+ };
25
+ return Object.freeze({
26
+ name: contract.name,
27
+ parse,
28
+ read: (header) => {
29
+ if (typeof header !== 'string')
30
+ return {};
31
+ const pair = header.split(';').map(part => part.trim()).find(part => part.startsWith(contract.name + '='));
32
+ return pair ? parse(pair.slice(contract.name.length + 1)) : {};
33
+ },
34
+ value: (preference) => {
35
+ const parts = [];
36
+ for (const key of ['lang', 'theme']) {
37
+ const entry = preference[key];
38
+ if (entry === undefined)
39
+ continue;
40
+ if (!allowed[key].includes(entry))
41
+ throw new Error('INVALID_PREFERENCE_VALUE');
42
+ parts.push(key + '=' + entry);
43
+ }
44
+ return parts.join('&');
45
+ },
46
+ });
47
+ }
48
+ //# sourceMappingURL=preferences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preferences.js","sourceRoot":"","sources":["../src/preferences.ts"],"names":[],"mappings":"AAkBA,MAAM,UAAU,GAAG,kDAAkD,CAAC;AACtE,MAAM,KAAK,GAAG,sBAAsB,CAAC;AACrC,MAAM,SAAS,GAAG,GAAG,CAAC;AAEtB,MAAM,UAAU,sBAAsB,CAAC,QAAkC;IACvE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IAC9H,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;QAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IACnI,MAAM,OAAO,GAA0D,EAAE,IAAI,EAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC1H,MAAM,KAAK,GAAG,CAAC,KAAgC,EAAc,EAAE;QAC7D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS;YAAE,OAAO,EAAE,CAAC;QACrE,MAAM,KAAK,GAAsC,EAAE,CAAC;QACpD,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;YACpC,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACpC,IAAI,SAAS,GAAG,CAAC;gBAAE,SAAS;YAC5B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,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,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;gBAC/E,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,KAAK,CAAC,CAAC;YAChC,CAAC;YACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACzB,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@mpfrontend/i18n",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/panahister/mpfrontend.git",
8
+ "directory": "packages/i18n"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "provenance": true
26
+ },
27
+ "dependencies": {
28
+ "@formatjs/icu-messageformat-parser": "3.5.18",
29
+ "intl-messageformat": "11.2.15"
30
+ }
6
31
  }