@proveanything/smartlinks 2.1.24 → 2.1.28

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/dist/docs/i18n.md CHANGED
@@ -1,4 +1,71 @@
1
- # Internationalization (i18n) System
1
+ # Internationalization (i18n): an app's own words
2
+
3
+ **Use the SDK's `i18n` helper** (SDK 2.1.27+). The copied-in `src/i18n/LanguageContext` scaffold further
4
+ down is the older way; new apps and upgrades use the helper.
5
+
6
+ ## How it works
7
+
8
+ 1. **Your app keeps its English as keys** in `public/i18n/en.json`. The build ships it at
9
+ `<bundle>/i18n/en.json`. That is your only translation job: don't hard-code English in components.
10
+ 2. **The platform translates.** When your app is published, SmartLinks translates the English into the
11
+ admin languages it supports (Simplified Chinese first) and adds `<bundle>/i18n/<lang>.json`. Keys whose
12
+ English hasn't changed keep their earlier (possibly human-reviewed) translation. If you ship your own
13
+ `public/i18n/<lang>.json`, its keys win and the platform fills only the gaps.
14
+ 3. **The host says which language.** Studio passes the person's own Studio language as `?lang=`, and later
15
+ changes arrive live (`smartlinks:root-state` with `lang`). A key with no translation shows its English.
16
+
17
+ In an admin app, `lang` is the person's **Studio language** (buttons and labels). The site's content
18
+ language arrives separately as `contentLang`: use it for the language your product data is written in.
19
+
20
+ ## Using it (React)
21
+
22
+ ```ts
23
+ // src/i18n.ts
24
+ import { useSyncExternalStore } from 'react'
25
+ import { i18n } from '@proveanything/smartlinks'
26
+
27
+ export const i18nReady = i18n.init() // await before first render (main.tsx)
28
+ export function useT() {
29
+ useSyncExternalStore(i18n.subscribe, i18n.snapshot)
30
+ return i18n.t
31
+ }
32
+ export const fmt = i18n.format // dates and numbers in the current language
33
+ ```
34
+
35
+ ```tsx
36
+ const t = useT()
37
+ <Button>{t('contacts.add')}</Button>
38
+ <span>{t('contacts.count', { count: rows.length })}</span>
39
+ <span>{fmt.date(contact.createdAt)}</span>
40
+ ```
41
+
42
+ `public/i18n/en.json`:
43
+
44
+ ```json
45
+ {
46
+ "contacts": {
47
+ "add": "Add contact",
48
+ "count_one": "{{count}} contact",
49
+ "count_other": "{{count}} contacts"
50
+ }
51
+ }
52
+ ```
53
+
54
+ - Nested keys are read with dots; group them by screen.
55
+ - `{{name}}` is filled from the values. With `count`, the language's plural form is picked
56
+ (`_one` / `_other` in English; Chinese uses only `_other`).
57
+ - Outside components, call `i18n.t(...)` at the moment the text is shown (not at module load), so a
58
+ language switch takes effect.
59
+ - Don't translate data (names from the server, ids, codes), or text you send to an AI model as
60
+ instructions.
61
+ - `i18n.language()` is the language in use; `i18n.setLanguage(code)` switches; `i18n.has(key)` says
62
+ whether a real translation exists.
63
+
64
+ ---
65
+
66
+ # The older scaffold (superseded)
67
+
68
+ ## Internationalization (i18n) System
2
69
 
3
70
  This document explains the i18n system for SmartLinks apps, covering URL-based language selection, static translations, and dynamic overrides.
4
71
 
@@ -0,0 +1,97 @@
1
+ # Tag codes: attaching a scanned tag to an asset
2
+
3
+ `SL.tagCodes` lets an admin app (Core Assets, Sidekick, a custom app) work with the tags on a collection's
4
+ things: what a scanned tag is, putting it on an asset, and taking it off. The same three calls work for
5
+ every claim-set tag:
6
+
7
+ - **printed QR codes from a computed claim set**: bought runs, and codes a business prints itself;
8
+ - **NFC tags and older QR sets**, whose codes are stored.
9
+
10
+ An *asset* is a proof; its *asset type* is the proof's product. Design note: prove
11
+ `server/docs/design/asset-tags-and-printed-codes.md`.
12
+
13
+ ## The calls
14
+
15
+ ```ts
16
+ import * as SL from '@proveanything/smartlinks'
17
+
18
+ // What was scanned: the address on the tag (or { claimSetId, code })
19
+ const tag = await SL.tagCodes.lookup(collectionId, { url: 'https://atag.co/4fK2qPx' })
20
+ // → { claimSetId, code, url, computed: true, tagType: 'qr', status: 'free' }
21
+
22
+ await SL.tagCodes.attach(collectionId, { url, productId: 'bed-sb755', proofId: 'bed14' })
23
+ // → { …, status: 'attached', productId: 'bed-sb755', proofId: 'bed14' }
24
+
25
+ await SL.tagCodes.detach(collectionId, { url })
26
+ // → { …, status: 'free', proofId: null }
27
+ ```
28
+
29
+ `status`:
30
+
31
+ | Status | Meaning |
32
+ |---|---|
33
+ | `free` | not on anything; this collection may attach it |
34
+ | `attached` | on one of this collection's assets (`productId`, `proofId` say which) |
35
+ | `elsewhere` | another organisation's tag; nothing more is shown |
36
+
37
+ ## The rules
38
+
39
+ - Admins of the collection only.
40
+ - Refused with `OTHER_ORGANISATION` when the tag's set belongs to another collection, or the run it's in was
41
+ sold to another collection.
42
+ - Refused with `ASSIGNED_ELSEWHERE` when the tag is already in use by another collection.
43
+ - Refused with `ALREADY_ATTACHED` when it's on another asset: `detach` first.
44
+ - After `attach`, scanning the tag opens the asset's page.
45
+
46
+ ## Computed claim sets (for whoever makes tags)
47
+
48
+ A claim set created with `codeSource: 'computed'` (QR only) stores nothing per code: each code is worked out from
49
+ its index with a signature (24 bits by default, `sigBits` 16 to 32). A run in such a set can hold up to
50
+ 1,000,000 tags. Its printer file downloads in parts:
51
+
52
+ ```ts
53
+ await SL.claimSet.ranges.exportFile(scope, claimSetId, rangeId, { from: 1, to: 200000 })
54
+ ```
55
+
56
+ A computed set with `bareCodes: true` answers bare codes on its tap domain: `https://{domain}/{code}`.
57
+ Each domain has at most one such set. Assigning a **whole** computed run to a collection
58
+ (`ranges.assign` without `start`/`end`) is one write on the range, however many tags it holds; the response
59
+ says `wholeRange: true`.
60
+
61
+ ## Chips and boxes (2.1.26)
62
+
63
+ The same three calls take an RFID or NFC chip by its id (`tagId`), or whatever a scanner read (`scan`: an address
64
+ is read as a claim code, anything else as a chip id):
65
+
66
+ ```ts
67
+ await SL.tagCodes.lookup(collectionId, { scan: 'E28011700000020F1E2D3C4B' })
68
+ // → { kind: 'chip', tagId, tagType: 'chip', status: 'free', on: null }
69
+ ```
70
+
71
+ A tag goes on **an item** or **a container** (it's the label on a box, a bag, a shelf, a cask), never both:
72
+
73
+ ```ts
74
+ await SL.tagCodes.attach(collectionId, { url, productId, proofId }) // on an item
75
+ await SL.tagCodes.attach(collectionId, { tagId, containerId }) // the label on an existing container
76
+ await SL.tagCodes.attach(collectionId, { url, container: { name: 'Box 12', parentContainerId: storeRoomId } }) // a new box
77
+ ```
78
+
79
+ `on` says what a tag is on: `{ type: 'item', productId, proofId }`, `{ type: 'container', containerId, name }`, or
80
+ for older RFID tags tagged only to a product, `{ type: 'product', productId }` (which can still be attached to an
81
+ item). A chip's label is recorded as the tag row's `refType: 'container'` (the label on that container, never
82
+ where the tag is); a claim code's in its own row.
83
+
84
+ ## Moving things
85
+
86
+ ```ts
87
+ await SL.places.move(collectionId, { to: vanId, items: [{ productId, proofId }, { containerId: boxId }], note: 'Acme job' })
88
+ // → { moved: [...], unchanged: [...], refused: [...] }
89
+ ```
90
+
91
+ - An item, or a chip without an item, is taken out of every place it's in and put in `to` (membership).
92
+ - A container is re-parented to `to`. A place can't go inside itself (`INSIDE_ITSELF`).
93
+ - `to: null` takes things out of every place.
94
+ - Each move leaves a history line: `asset.moved` on an item, `tag.moved` on a chip, `container.moved` on a container.
95
+
96
+ Where something is: an item's place is `containers.findForItem(cid, { itemType: 'proof', itemId })` (its
97
+ membership rows and the containers); a container's is its `parentContainerId`.
@@ -0,0 +1,87 @@
1
+ # Wallet passes
2
+
3
+ Put an **event ticket**, a **booking**, a **membership card** or a **loyalty card** in the person's Apple Wallet or
4
+ Google Wallet. SmartLinks is the issuer and signs the passes. Each pass is branded from your site's name, logo and
5
+ colour, and your app decides what it says.
6
+
7
+ - **Who gets one:** only someone the business knows. A pass is issued to the signed-in owner of what it's for, or
8
+ by your app's own server function.
9
+ - **What the phone does:** the pass shows its QR code offline, appears near the time (and place, if you give
10
+ `venue.lat` / `lng`), and updates when you change it.
11
+ - **Bookings look after themselves:** when a booking is moved its pass shows the new time, and when it's cancelled
12
+ the pass is voided.
13
+
14
+ ## In a page: "Add to Wallet"
15
+
16
+ ```typescript
17
+ import { wallet } from '@proveanything/smartlinks'
18
+
19
+ // The signed-in person's booking, membership card, or a pass your app issued them
20
+ const { pass } = await wallet.addLinks(collectionId, { type: 'booking', id: booking.id })
21
+ // pass.links.apple → opens the .pkpass on an iPhone
22
+ // pass.links.google → opens Google's "Save to Google Wallet" page
23
+ ```
24
+
25
+ - `{ type: 'booking', id }` and `{ type: 'contact', id: 'me' }` are made on first ask:
26
+ - a booking pass, from the booking's date and time
27
+ - a membership card, from the person's `level` and `memberUntil` fields
28
+ - For anything else (an event ticket with your own title, a loyalty card with points), issue the pass in your server
29
+ function first. `addLinks` then returns that pass for its owner.
30
+ - Show the official "Add to Apple Wallet" and "Add to Google Wallet" badges, and only the one that suits the
31
+ device. A wallet that isn't set up yet is left out of `links`.
32
+ - `wallet.mine(collectionId)` lists the person's passes.
33
+
34
+ ## In a server function: issue, change, void, message
35
+
36
+ Declare `sl:wallet:write` in the function's capabilities.
37
+
38
+ ```typescript
39
+ // An event ticket
40
+ const pass = await ctx.sl.wallet.issue({
41
+ ref: { type: 'booking', id: booking.id }, // what it's for; issuing again changes the same pass
42
+ pass: {
43
+ kind: 'event',
44
+ title: 'Jazz on the Terrace',
45
+ start: '2026-12-24T19:00:00Z', end: '2026-12-24T22:00:00Z', timezone: 'Europe/London',
46
+ venue: { name: 'The Terrace', address: '1 High St, Bath', lat: 51.38, lng: -2.36 },
47
+ holder: 'Sam Lee', number: 'T-0042',
48
+ fields: [{ label: 'Seat', value: 'Table 6' }],
49
+ },
50
+ })
51
+ return { links: pass.links } // hand these to the page
52
+
53
+ // A loyalty card, kept up to date
54
+ await ctx.sl.wallet.issue({ ref: { type: 'loyalty', id: accountId }, pass: { kind: 'loyalty', title: 'Bloom Rewards', points: 120, holder: 'Sam' } })
55
+ await ctx.sl.wallet.update(passId, { points: 145 })
56
+
57
+ await ctx.sl.wallet.void(passId, 'refunded')
58
+ await ctx.sl.wallet.message(passId, { header: 'Doors open', body: 'Doors open at 7pm. See you soon!' })
59
+ ```
60
+
61
+ - **Contact:** `contactId` defaults to the caller's contact.
62
+ - **Reading:** `ctx.sl.wallet.get(passId)`, `forRef(ref)`, `byCode(code)` and `mine()` need only `sl:wallet:read`.
63
+ - **Messages:** you can also send a message to wallet with `ctx.sl.messages` and `channel: 'wallet'`. It goes to the
64
+ person's passes about the message's `about`, otherwise to your app's own passes for them. It's worded from the
65
+ template's push version.
66
+
67
+ ## Checking a pass at the door
68
+
69
+ The QR holds the pass's own code, never an id. Scan it, then:
70
+
71
+ ```typescript
72
+ const { pass, valid } = await wallet.byCode(collectionId, scanned) // admin
73
+ // or in a function: await ctx.sl.wallet.byCode(scanned)
74
+ ```
75
+
76
+ ## What a pass can show
77
+
78
+ | Field | Use |
79
+ |---|---|
80
+ | `kind` | `event`, `booking`, `membership` or `loyalty` |
81
+ | `title` / `subtitle` | the main line and a second line |
82
+ | `start` / `end` / `timezone` | when; the pass surfaces near `start` |
83
+ | `venue` | `name`, `address`, and `lat` / `lng` for the lock screen nearby |
84
+ | `holder`, `number`, `level`, `points`, `validUntil` | the person, a reference or member number, a level, a balance, an end date |
85
+ | `fields` (up to 4), `back` | extra lines on the front and the back |
86
+ | `image`, `url` | https only: a picture, a link back to your site |
87
+ | `barcode` | your own QR value, instead of the pass's code |
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ export type Catalog = {
2
+ [key: string]: string | Catalog;
3
+ };
4
+ export interface I18nInitOptions {
5
+ /** Where the catalogs are. Default: `i18n/` next to the app's page (its bundle). */
6
+ baseUrl?: string;
7
+ /** The language to start in. Default: the host's `lang`, else `<html lang>`, else the browser's, else English. */
8
+ language?: string;
9
+ /** Catalogs supplied directly instead of fetched (tests, or an app that bundles its own). Keyed by language. */
10
+ catalogs?: Record<string, Catalog>;
11
+ /** The app's source language. Default 'en'. */
12
+ sourceLanguage?: string;
13
+ }
14
+ /** The language the host asked for, in a normal form ('zh-hans' -> 'zh-Hans', 'FR' -> 'fr'). */
15
+ export declare function normalizeLanguage(code: string | null | undefined): string | null;
16
+ /** Which language to start in: what the host passed, else the page's, else the browser's, else the source. */
17
+ export declare function detectLanguage(): string;
18
+ /**
19
+ * Load the source catalog and the current language's. Call once before the first render; safe to
20
+ * call again. Never throws: with nothing found, `t` returns the keys' English or the keys.
21
+ */
22
+ export declare function init(options?: I18nInitOptions): Promise<void>;
23
+ /** Switch language (loads its catalog first, so the switch happens in one step). */
24
+ export declare function setLanguage(lang: string): Promise<void>;
25
+ /** The language in use. */
26
+ export declare function language(): string;
27
+ /**
28
+ * Translate `key` into the current language, falling back to the source language, then to
29
+ * `values.defaultValue`, then to the key itself. `{{name}}` is filled from `values`; `count`
30
+ * picks the plural form.
31
+ */
32
+ export declare function t(key: string, values?: Record<string, unknown> & {
33
+ count?: number;
34
+ defaultValue?: string;
35
+ }): string;
36
+ /** Is there a translation for `key` in the current language (not just the English fallback)? */
37
+ export declare function has(key: string): boolean;
38
+ /** Subscribe to language/catalog changes. Returns an unsubscribe. (For React's useSyncExternalStore.) */
39
+ export declare function subscribe(fn: () => void): () => void;
40
+ /** Changes on every language or catalog change. (The snapshot for useSyncExternalStore.) */
41
+ export declare function snapshot(): number;
42
+ /** Dates and numbers in the current language. */
43
+ export declare const format: {
44
+ number: (n: number, opts?: Intl.NumberFormatOptions) => string;
45
+ date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string;
46
+ dateTime: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string;
47
+ };
48
+ /** Forget loaded catalogs and listeners (tests). */
49
+ export declare function _reset(): void;
package/dist/i18n.js ADDED
@@ -0,0 +1,298 @@
1
+ // src/i18n.ts
2
+ //
3
+ // An app's own words, in the person's language: buttons, labels, messages. (Translating CONTENT —
4
+ // product names, page text — is `translations.resolve`; this is the app's fixed strings.)
5
+ //
6
+ // How it fits together (prove docs/design/multi-language.md 8a):
7
+ // - The app keeps its English as keys in `public/i18n/en.json`, so the build ships it at
8
+ // `<bundle>/i18n/en.json`. That is the app's only translation job.
9
+ // - When the app is published, the platform translates the English into the admin languages it
10
+ // supports and adds `<bundle>/i18n/<lang>.json` (e.g. zh-Hans.json). An app may ship its own
11
+ // `<lang>.json` too: its keys win, the platform fills the gaps.
12
+ // - At run time the host says which language: `?lang=` (Studio passes the person's Studio
13
+ // language), later changes arrive live as `smartlinks:root-state` messages. A key missing in
14
+ // that language shows its English. Nothing ever shows a raw key unless English lacks it too.
15
+ //
16
+ // Framework-free. In React, re-render on a language change with useSyncExternalStore:
17
+ //
18
+ // import { i18n } from '@proveanything/smartlinks'
19
+ // await i18n.init() // once, before first render
20
+ // export function useT() {
21
+ // useSyncExternalStore(i18n.subscribe, i18n.snapshot)
22
+ // return i18n.t
23
+ // }
24
+ // const t = useT(); t('contacts.add') t('contacts.count', { count: 3 })
25
+ //
26
+ // Catalog format (the same shape i18next uses, so files move between tools):
27
+ // { "contacts": { "add": "Add contact", "count_one": "{{count}} contact", "count_other": "{{count}} contacts" } }
28
+ // Nested keys are read with dots. `{{name}}` is replaced from the values. With `count`, the plural
29
+ // form for the language is picked (`_one`, `_other`, …; Chinese has only `_other`).
30
+ import { readContext } from './context.js';
31
+ let source = 'en';
32
+ let current = 'en';
33
+ let base = null;
34
+ const loaded = new Map();
35
+ const supplied = new Map();
36
+ const listeners = new Set();
37
+ let version = 0;
38
+ let listening = false;
39
+ function emit() {
40
+ version++;
41
+ listeners.forEach((fn) => {
42
+ try {
43
+ fn();
44
+ }
45
+ catch ( /* a listener's own problem */_a) { /* a listener's own problem */ }
46
+ });
47
+ }
48
+ function bundleBase() {
49
+ if (base)
50
+ return base;
51
+ try {
52
+ // The page's own folder: an app served at .../apps/<id>/<channel>/admin.html#/... finds i18n/ beside it.
53
+ return new URL('i18n/', document.baseURI).toString();
54
+ }
55
+ catch (_a) {
56
+ return 'i18n/';
57
+ }
58
+ }
59
+ /** The language the host asked for, in a normal form ('zh-hans' -> 'zh-Hans', 'FR' -> 'fr'). */
60
+ export function normalizeLanguage(code) {
61
+ if (!code || typeof code !== 'string')
62
+ return null;
63
+ const m = /^([a-z]{2,3})(?:[-_]([a-z]{4}))?(?:[-_]([a-z]{2}|\d{3}))?$/i.exec(code.trim());
64
+ if (!m)
65
+ return null;
66
+ const [, lang, script, region] = m;
67
+ return [lang.toLowerCase(), script && script[0].toUpperCase() + script.slice(1).toLowerCase(), region && region.toUpperCase()]
68
+ .filter(Boolean)
69
+ .join('-');
70
+ }
71
+ /**
72
+ * The file a language is served as. Chinese is kept by script: zh-CN / zh-SG / bare zh read
73
+ * zh-Hans, zh-TW / zh-HK / zh-MO read zh-Hant. A region otherwise falls back to its language
74
+ * (fr-CA -> fr) when there is no file for the region.
75
+ */
76
+ function candidates(lang) {
77
+ const out = [lang];
78
+ const [l, second] = lang.split('-');
79
+ if (l === 'zh') {
80
+ const traditional = /^(Hant|TW|HK|MO)$/i.test(second || '');
81
+ out.push(traditional ? 'zh-Hant' : 'zh-Hans');
82
+ }
83
+ if (second && l !== 'zh')
84
+ out.push(l);
85
+ return Array.from(new Set(out));
86
+ }
87
+ /** Which language to start in: what the host passed, else the page's, else the browser's, else the source. */
88
+ export function detectLanguage() {
89
+ try {
90
+ const fromHost = normalizeLanguage(readContext().lang);
91
+ if (fromHost)
92
+ return fromHost;
93
+ const root = typeof document !== 'undefined' ? document.documentElement : undefined;
94
+ if (root && typeof root.getAttribute === 'function') {
95
+ const fromPage = normalizeLanguage(root.getAttribute('lang'));
96
+ if (fromPage)
97
+ return fromPage;
98
+ }
99
+ if (typeof navigator !== 'undefined') {
100
+ const fromBrowser = normalizeLanguage(navigator.language);
101
+ if (fromBrowser)
102
+ return fromBrowser;
103
+ }
104
+ }
105
+ catch ( /* not in a browser */_a) { /* not in a browser */ }
106
+ return source;
107
+ }
108
+ /** Mark the page with the language in use (screen readers, fonts), where there is a page. */
109
+ function setPageLanguage(lang) {
110
+ try {
111
+ const root = typeof document !== 'undefined' ? document.documentElement : undefined;
112
+ if (root && typeof root.setAttribute === 'function')
113
+ root.setAttribute('lang', lang);
114
+ }
115
+ catch ( /* not a browser page */_a) { /* not a browser page */ }
116
+ }
117
+ async function fetchCatalog(lang) {
118
+ if (supplied.has(lang))
119
+ return supplied.get(lang);
120
+ if (loaded.has(lang))
121
+ return loaded.get(lang);
122
+ for (const name of candidates(lang)) {
123
+ if (supplied.has(name))
124
+ return supplied.get(name);
125
+ try {
126
+ const res = await fetch(`${bundleBase()}${name}.json`, { cache: 'default' });
127
+ if (!res.ok)
128
+ continue;
129
+ const type = res.headers.get('content-type') || '';
130
+ // A host that answers every path with its index page isn't a catalog.
131
+ if (type && !type.includes('json'))
132
+ continue;
133
+ const data = (await res.json());
134
+ if (data && typeof data === 'object') {
135
+ loaded.set(lang, data);
136
+ return data;
137
+ }
138
+ }
139
+ catch ( /* not there, or offline: fall back */_a) { /* not there, or offline: fall back */ }
140
+ }
141
+ return null;
142
+ }
143
+ function listen() {
144
+ if (listening || typeof window === 'undefined')
145
+ return;
146
+ listening = true;
147
+ // The host says the language changed (Studio, the portal): same message theme-boot.js reads.
148
+ window.addEventListener('message', (e) => {
149
+ const d = e && e.data;
150
+ if (!d || typeof d !== 'object')
151
+ return;
152
+ if ((d.type === 'smartlinks:root-state' || d.type === 'smartlinks:language') && typeof d.lang === 'string') {
153
+ void setLanguage(d.lang);
154
+ }
155
+ });
156
+ }
157
+ /**
158
+ * Load the source catalog and the current language's. Call once before the first render; safe to
159
+ * call again. Never throws: with nothing found, `t` returns the keys' English or the keys.
160
+ */
161
+ export async function init(options = {}) {
162
+ source = normalizeLanguage(options.sourceLanguage) || 'en';
163
+ if (options.baseUrl)
164
+ base = options.baseUrl.endsWith('/') ? options.baseUrl : `${options.baseUrl}/`;
165
+ if (options.catalogs)
166
+ for (const [lang, cat] of Object.entries(options.catalogs)) {
167
+ const key = normalizeLanguage(lang) || lang;
168
+ supplied.set(key, cat);
169
+ }
170
+ current = normalizeLanguage(options.language) || detectLanguage();
171
+ listen();
172
+ await Promise.all([fetchCatalog(source), current === source ? null : fetchCatalog(current)]);
173
+ setPageLanguage(current);
174
+ emit();
175
+ }
176
+ /** Switch language (loads its catalog first, so the switch happens in one step). */
177
+ export async function setLanguage(lang) {
178
+ const next = normalizeLanguage(lang);
179
+ if (!next || next === current)
180
+ return;
181
+ await fetchCatalog(next);
182
+ current = next;
183
+ setPageLanguage(current);
184
+ emit();
185
+ }
186
+ /** The language in use. */
187
+ export function language() {
188
+ return current;
189
+ }
190
+ function lookup(cat, key) {
191
+ if (!cat)
192
+ return undefined;
193
+ if (typeof cat[key] === 'string')
194
+ return cat[key]; // flat keys with dots also work
195
+ let node = cat;
196
+ for (const part of key.split('.')) {
197
+ if (!node || typeof node !== 'object')
198
+ return undefined;
199
+ node = node[part];
200
+ }
201
+ return typeof node === 'string' ? node : undefined;
202
+ }
203
+ function pluralCategory(lang, count) {
204
+ try {
205
+ const PR = Intl.PluralRules;
206
+ if (PR)
207
+ return new PR(lang).select(count);
208
+ }
209
+ catch ( /* unknown locale */_a) { /* unknown locale */ }
210
+ return count === 1 ? 'one' : 'other';
211
+ }
212
+ /** The catalog for a language: supplied or fetched, trying its fallbacks (zh-CN -> zh-Hans, fr-CA -> fr). */
213
+ function catalogFor(lang) {
214
+ for (const name of candidates(lang)) {
215
+ const cat = supplied.get(name) || loaded.get(name);
216
+ if (cat)
217
+ return cat;
218
+ }
219
+ return loaded.get(lang);
220
+ }
221
+ function find(lang, key, count) {
222
+ var _a;
223
+ const cat = catalogFor(lang);
224
+ if (typeof count === 'number') {
225
+ const form = (_a = lookup(cat, `${key}_${pluralCategory(lang, count)}`)) !== null && _a !== void 0 ? _a : lookup(cat, `${key}_other`);
226
+ if (form !== undefined)
227
+ return form;
228
+ }
229
+ return lookup(cat, key);
230
+ }
231
+ /**
232
+ * Translate `key` into the current language, falling back to the source language, then to
233
+ * `values.defaultValue`, then to the key itself. `{{name}}` is filled from `values`; `count`
234
+ * picks the plural form.
235
+ */
236
+ export function t(key, values) {
237
+ var _a, _b, _c;
238
+ const count = values && typeof values.count === 'number' ? values.count : undefined;
239
+ const text = (_c = (_b = (_a = find(current, key, count)) !== null && _a !== void 0 ? _a : (current === source ? undefined : find(source, key, count))) !== null && _b !== void 0 ? _b : values === null || values === void 0 ? void 0 : values.defaultValue) !== null && _c !== void 0 ? _c : key;
240
+ if (!values)
241
+ return text;
242
+ return text.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (m, name) => {
243
+ const v = values[name];
244
+ if (v === undefined || v === null)
245
+ return m;
246
+ return typeof v === 'number' ? v.toLocaleString(current) : String(v);
247
+ });
248
+ }
249
+ /** Is there a translation for `key` in the current language (not just the English fallback)? */
250
+ export function has(key) {
251
+ return find(current, key) !== undefined;
252
+ }
253
+ /** Subscribe to language/catalog changes. Returns an unsubscribe. (For React's useSyncExternalStore.) */
254
+ export function subscribe(fn) {
255
+ listeners.add(fn);
256
+ return () => { listeners.delete(fn); };
257
+ }
258
+ /** Changes on every language or catalog change. (The snapshot for useSyncExternalStore.) */
259
+ export function snapshot() {
260
+ return version;
261
+ }
262
+ /** Dates and numbers in the current language. */
263
+ export const format = {
264
+ number: (n, opts) => {
265
+ try {
266
+ return new Intl.NumberFormat(current, opts).format(n);
267
+ }
268
+ catch (_a) {
269
+ return String(n);
270
+ }
271
+ },
272
+ date: (d, opts) => {
273
+ try {
274
+ return new Intl.DateTimeFormat(current, opts !== null && opts !== void 0 ? opts : { dateStyle: 'medium' }).format(new Date(d));
275
+ }
276
+ catch (_a) {
277
+ return String(d);
278
+ }
279
+ },
280
+ dateTime: (d, opts) => {
281
+ try {
282
+ return new Intl.DateTimeFormat(current, opts !== null && opts !== void 0 ? opts : { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(d));
283
+ }
284
+ catch (_a) {
285
+ return String(d);
286
+ }
287
+ },
288
+ };
289
+ /** Forget loaded catalogs and listeners (tests). */
290
+ export function _reset() {
291
+ source = 'en';
292
+ current = 'en';
293
+ base = null;
294
+ loaded.clear();
295
+ supplied.clear();
296
+ listeners.clear();
297
+ version = 0;
298
+ }
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from "./api/index.js";
3
3
  export * from "./types/index.js";
4
4
  export { iframe } from "./iframe.js";
5
5
  export { readContext } from "./context.js";
6
+ export * as i18n from "./i18n.js";
6
7
  export * as adminViews from "./adminViews.js";
7
8
  export type { NavigateRequest, NavigateTarget, OpenAppRequest } from "./adminViews.js";
8
9
  export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
package/dist/index.js CHANGED
@@ -7,6 +7,8 @@ export * from "./types/index.js";
7
7
  export { iframe } from "./iframe.js";
8
8
  // App context reader (props → hash → search), for pages and containers alike
9
9
  export { readContext } from "./context.js";
10
+ import * as i18n_1 from "./i18n.js";
11
+ export { i18n_1 as i18n };
10
12
  import * as adminViews_1 from "./adminViews.js";
11
13
  export { adminViews_1 as adminViews };
12
14
  export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";