prosebook 0.0.1 → 0.2.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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +604 -0
  3. package/dist/cli.d.ts +1 -0
  4. package/dist/cli.js +508 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/config-D--RITk2.js +1208 -0
  7. package/dist/config-D--RITk2.js.map +1 -0
  8. package/dist/config-_4HfnJQu.d.ts +517 -0
  9. package/dist/config-_4HfnJQu.d.ts.map +1 -0
  10. package/dist/config.d.ts +2 -0
  11. package/dist/config.js +1 -0
  12. package/dist/copy-DXnzXsJa.d.ts +162 -0
  13. package/dist/copy-DXnzXsJa.d.ts.map +1 -0
  14. package/dist/helpers-BPuPGjQP.js +61 -0
  15. package/dist/helpers-BPuPGjQP.js.map +1 -0
  16. package/dist/index.d.ts +24 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +188 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/inspector.d.ts +37 -0
  21. package/dist/inspector.d.ts.map +1 -0
  22. package/dist/inspector.js +572 -0
  23. package/dist/inspector.js.map +1 -0
  24. package/dist/react/index.d.ts +37 -0
  25. package/dist/react/index.d.ts.map +1 -0
  26. package/dist/react/index.js +86 -0
  27. package/dist/react/index.js.map +1 -0
  28. package/dist/sarif-CI8HOokm.js +1033 -0
  29. package/dist/sarif-CI8HOokm.js.map +1 -0
  30. package/dist/scan-Ch2BfIUD.js +2561 -0
  31. package/dist/scan-Ch2BfIUD.js.map +1 -0
  32. package/dist/tools.d.ts +377 -0
  33. package/dist/tools.d.ts.map +1 -0
  34. package/dist/tools.js +4 -0
  35. package/dist/vite.d.ts +24 -0
  36. package/dist/vite.d.ts.map +1 -0
  37. package/dist/vite.js +264 -0
  38. package/dist/vite.js.map +1 -0
  39. package/package.json +148 -15
  40. package/src/cli.ts +528 -0
  41. package/src/index.ts +31 -0
  42. package/src/inspector-dialog.ts +450 -0
  43. package/src/inspector.ts +228 -0
  44. package/src/react/index.tsx +112 -0
  45. package/src/runtime/copy.ts +221 -0
  46. package/src/runtime/helpers.ts +66 -0
  47. package/src/runtime/locale.ts +49 -0
  48. package/src/runtime/types.ts +106 -0
  49. package/src/tools/catalog.ts +449 -0
  50. package/src/tools/compile.ts +121 -0
  51. package/src/tools/config.ts +211 -0
  52. package/src/tools/diff.ts +84 -0
  53. package/src/tools/entry.ts +325 -0
  54. package/src/tools/extract.ts +694 -0
  55. package/src/tools/generate.ts +257 -0
  56. package/src/tools/icu.ts +211 -0
  57. package/src/tools/index.ts +91 -0
  58. package/src/tools/lint.ts +865 -0
  59. package/src/tools/lock.ts +95 -0
  60. package/src/tools/mf1.ts +246 -0
  61. package/src/tools/mf2.ts +752 -0
  62. package/src/tools/migrate.ts +138 -0
  63. package/src/tools/presets.ts +159 -0
  64. package/src/tools/pseudo.ts +40 -0
  65. package/src/tools/sarif.ts +80 -0
  66. package/src/tools/scan.ts +303 -0
  67. package/src/tools/syntax.ts +24 -0
  68. package/src/tools/types.ts +137 -0
  69. package/src/vite.ts +296 -0
  70. package/index.js +0 -1
@@ -0,0 +1,112 @@
1
+ /**
2
+ * `prosebook/react`: the catalog in components.
3
+ *
4
+ * `useCopy()` re-renders its component when the locale changes, and its `rich` returns a ready
5
+ * `ReactNode`: elements are keyed and tag functions receive keyed children, so a sentence with a
6
+ * link inside it is one catalog entry and one call, with no wrapper to remember.
7
+ */
8
+ import { createContext, Fragment, isValidElement, use, useMemo, useSyncExternalStore, type ReactNode } from 'react';
9
+
10
+ import type { Copy } from '#src/runtime/copy.ts';
11
+ import type { MessageShape, RegisteredLocale, RegisteredMessages, RichKey, RichParam, TagFn } from '#src/runtime/types.ts';
12
+
13
+ type M = RegisteredMessages;
14
+ type L = RegisteredLocale;
15
+
16
+ /** `Copy`, with `rich` returning a `ReactNode`. */
17
+ export interface ReactCopy extends Omit<Copy<M, L>, 'rich'> {
18
+ rich<K extends RichKey<M>>(this: void, key: K, ...values: RichParam<M[K], ReactNode>): ReactNode;
19
+ }
20
+
21
+ const CopyContext = createContext<{ copy: Copy<M, L>; tags: Tags } | null>(null);
22
+
23
+ type Tags = { readonly [tag: string]: TagFn<ReactNode> };
24
+
25
+ export interface CopyProviderProps {
26
+ copy: Copy<M, L> | Copy;
27
+ /** Tag renderers every rich read under this provider gets, beside the copy's own. */
28
+ tags?: Tags;
29
+ children?: ReactNode;
30
+ }
31
+
32
+ export function CopyProvider({ copy, tags, children }: CopyProviderProps) {
33
+ const value = useMemo(() => ({ copy: copy as Copy<M, L>, tags: { ...(copy.tags as unknown as Tags), ...tags } }), [copy, tags]);
34
+ return <CopyContext value={value}>{children}</CopyContext>;
35
+ }
36
+
37
+ /** The catalog, in the current locale. Re-renders the component when the locale changes, or in dev the catalog. */
38
+ export function useCopy(): ReactCopy {
39
+ const context = use(CopyContext);
40
+ if (context === null) throw new Error('prosebook: useCopy() needs a <CopyProvider> above it');
41
+ const { copy, tags } = context;
42
+ const version = useSyncExternalStore(
43
+ copy.subscribe,
44
+ () => copy.version,
45
+ () => copy.version,
46
+ );
47
+ return useMemo(() => readerFor(copy, tags, version), [copy, tags, version]);
48
+ }
49
+
50
+ /** The current locale alone, for components that only format or switch. */
51
+ export function useLocale(): L {
52
+ const context = use(CopyContext);
53
+ if (context === null) throw new Error('prosebook: useLocale() needs a <CopyProvider> above it');
54
+ return useSyncExternalStore(
55
+ context.copy.subscribe,
56
+ () => context.copy.locale,
57
+ () => context.copy.locale,
58
+ );
59
+ }
60
+
61
+ // Takes the version only so the reader is rebuilt, and its identity changes, when what it reads does.
62
+ function readerFor(copy: Copy<M, L>, tags: Tags, version: number): ReactCopy {
63
+ return {
64
+ locale: copy.locale,
65
+ version,
66
+ locales: copy.locales,
67
+ source: copy.source,
68
+ tags: copy.tags,
69
+ ready: copy.ready,
70
+ t: copy.t,
71
+ has: copy.has,
72
+ setLocale: copy.setLocale,
73
+ subscribe: copy.subscribe,
74
+ number: copy.number,
75
+ date: copy.date,
76
+ list: copy.list,
77
+ relative: copy.relative,
78
+ rich(key, ...values) {
79
+ const given = (values[0] ?? {}) as Record<string, unknown>;
80
+ const merged: Record<string, unknown> = { ...tags, ...given };
81
+ for (const [name, value] of Object.entries(merged))
82
+ if (typeof value === 'function') merged[name] = (chunks: unknown[]) => (value as TagFn<ReactNode>)(keyed(chunks));
83
+
84
+ return <>{keyed(copy.rich(key as never, merged as never))}</>;
85
+ },
86
+ };
87
+ }
88
+
89
+ /** Text joined where it can be, and each element under its own key, so React never warns about a list. */
90
+ function keyed(parts: unknown[]): (string | ReactNode)[] {
91
+ if (parts.every((p) => typeof p === 'string')) return [parts.join('')];
92
+ return parts.map((p, i) =>
93
+ // oxlint-disable-next-line react/no-array-index-key -- the parts of one message never reorder, so positions are stable keys
94
+ isValidElement(p) || typeof p === 'object' ? <Fragment key={i}>{p as ReactNode}</Fragment> : (p as ReactNode),
95
+ );
96
+ }
97
+
98
+ type ValuesProp<S extends MessageShape> = {} extends S['args'] & { [T in S['tags']]: unknown }
99
+ ? { values?: S['args'] & { [T in S['tags']]?: TagFn<ReactNode> } }
100
+ : { values: RichParam<S, ReactNode>[0] };
101
+
102
+ export type TextProps<K extends Extract<keyof M, string>> = { id: K } & ValuesProp<M[K]>;
103
+
104
+ /**
105
+ * A message as an element: `<Text id="cart.items" values={{ count }} />`. Rich messages render their
106
+ * tags through the provider's renderers and any given in `values`.
107
+ */
108
+ export function Text<K extends Extract<keyof M, string>>(props: TextProps<K>) {
109
+ const copy = useCopy();
110
+ const values = (props as { values?: object }).values;
111
+ return <>{copy.rich(props.id as RichKey<M>, values)}</>;
112
+ }
@@ -0,0 +1,221 @@
1
+ import { createHelpers, flatten } from './helpers.ts';
2
+ import { chainOf, negotiate } from './locale.ts';
3
+ import type {
4
+ AnyTagFn,
5
+ ArgsParam,
6
+ Chunks,
7
+ Compiled,
8
+ CompiledMessages,
9
+ Helpers,
10
+ DevHooks,
11
+ MessageShapes,
12
+ RichKey,
13
+ RichParam,
14
+ Values,
15
+ } from './types.ts';
16
+
17
+ type Loader = () => Promise<{ default: CompiledMessages }>;
18
+
19
+ /** A generated catalog: which locales exist, which ship in the bundle and how to fetch the rest. */
20
+ export interface Catalog<M extends MessageShapes = MessageShapes, L extends string = string> {
21
+ /** The locale the catalog is written in, which every other falls back to. */
22
+ readonly source: L;
23
+ readonly locales: readonly L[];
24
+ /** Locales whose messages ship in the bundle. Always holds the source. */
25
+ readonly messages: { readonly [locale in L]?: CompiledMessages };
26
+ /** Locales fetched when first asked for. */
27
+ readonly loaders: { readonly [locale in L]?: Loader };
28
+ /** Type-only: carries the message shapes from the generated module to `createCopy`. */
29
+ readonly '~messages'?: M;
30
+ }
31
+
32
+ /** Ties a generated catalog to its message shapes. Called by generated code. */
33
+ export function defineCatalog<M extends MessageShapes, L extends string = string>(
34
+ catalog: Omit<Catalog<M, L>, '~messages'>,
35
+ ): Catalog<M, L> {
36
+ return catalog;
37
+ }
38
+
39
+ export interface CopyOptions<L extends string> {
40
+ /** The locale to start in, or the locales a reader prefers, most preferred first. Defaults to the source. */
41
+ locale?: L | (string & {}) | readonly string[];
42
+ /** Tag renderers every rich read gets unless it supplies its own, such as `b` or `link`. */
43
+ tags?: { [tag: string]: AnyTagFn };
44
+ /** What a key the catalog lacks reads as. Defaults to the key itself. */
45
+ onMissing?: (key: string, locale: L) => string;
46
+ }
47
+
48
+ /** Its methods don't use `this`, so they can be passed around and destructured: `const { t } = copy`. */
49
+ export interface Copy<M extends MessageShapes = MessageShapes, L extends string = string> {
50
+ /** The locale messages are coming back in. */
51
+ readonly locale: L;
52
+ readonly locales: readonly L[];
53
+ readonly source: L;
54
+ /** The tag renderers rich reads fall back to, from `CopyOptions.tags`. */
55
+ readonly tags: { readonly [tag: string]: AnyTagFn };
56
+ /** Settles once the starting locale's messages are loaded. */
57
+ readonly ready: Promise<void>;
58
+ /** A message as plain text. Tags render as the text they wrap. */
59
+ t<K extends keyof M & string>(this: void, key: K, ...args: ArgsParam<M[K]>): string;
60
+ /** A message with elements inside it: each tag's function turns what it wraps into a node. */
61
+ rich<K extends RichKey<M>, N = unknown>(this: void, key: K, ...values: RichParam<M[K], N>): Chunks<N>;
62
+ has(this: void, key: string): key is keyof M & string;
63
+ /** Switches locale once its messages (and its fallbacks') are loaded. */
64
+ setLocale(this: void, next: L | (string & {}) | readonly string[]): Promise<void>;
65
+ /** Counts changes to what messages read as: each locale switch, and each catalog edit in dev. */
66
+ readonly version: number;
67
+ /** Called after each locale switch, and in dev after each catalog edit. Returns the unsubscribe. */
68
+ subscribe(this: void, listener: () => void): () => void;
69
+ /** Formats a number in the current locale. */
70
+ number(this: void, value: number | bigint, options?: Intl.NumberFormatOptions): string;
71
+ /** Formats a date in the current locale. */
72
+ date(this: void, value: Date | number, options?: Intl.DateTimeFormatOptions): string;
73
+ /** Joins items as a list in the current locale: `a, b and c`. */
74
+ list(this: void, items: Iterable<string>, options?: Intl.ListFormatOptions): string;
75
+ /** `in 3 days`, `2 hours ago`, in the current locale. */
76
+ relative(this: void, value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;
77
+ }
78
+
79
+ type Layer = { messages: CompiledMessages; h: Helpers };
80
+
81
+ /** A message as the text it puts on screen: rendered again with its tags left as their text. */
82
+ function textOf(message: Compiled, values: Values, h: Helpers): string {
83
+ if (typeof message === 'string') return message;
84
+ const plain = Object.fromEntries(Object.entries(values).filter(([, v]) => typeof v !== 'function'));
85
+ return flatten(message(plain, h)).join('');
86
+ }
87
+
88
+ /** A catalog reader with a current locale. Create one per app, or one per request on a server. */
89
+ export function createCopy<M extends MessageShapes, L extends string>(catalog: Catalog<M, L>, options: CopyOptions<L> = {}): Copy<M, L> {
90
+ const loaded = new Map<L, Layer>();
91
+ const pending = new Map<L, Promise<Layer>>();
92
+ const listeners = new Set<() => void>();
93
+ const defaultTags = options.tags ?? {};
94
+ const formatters = new Map<string, Intl.NumberFormat | Intl.DateTimeFormat | Intl.ListFormat | Intl.RelativeTimeFormat>();
95
+
96
+ for (const [locale, messages] of Object.entries(catalog.messages) as [L, CompiledMessages][])
97
+ loaded.set(locale, { messages, h: createHelpers(locale) });
98
+
99
+ let locale = catalog.source;
100
+ let chain: Layer[] = layers(chainOf(locale, catalog.locales, catalog.source));
101
+ let latest = 0;
102
+ let version = 0;
103
+
104
+ function changed() {
105
+ version++;
106
+ for (const listener of listeners) listener();
107
+ }
108
+
109
+ // A layer's messages are swapped in place, so the chain that holds it reads the new ones.
110
+ (globalThis as DevHooks).__PROSEBOOK_HOT__?.add((l, messages) => {
111
+ const layer = loaded.get(l as L);
112
+ if (layer === undefined) return;
113
+ layer.messages = messages;
114
+ changed();
115
+ });
116
+
117
+ function layers(locales: L[]): Layer[] {
118
+ return locales.flatMap((l) => loaded.get(l) ?? []);
119
+ }
120
+
121
+ function load(l: L): Promise<Layer> {
122
+ const done = loaded.get(l);
123
+ if (done) return Promise.resolve(done);
124
+ let p = pending.get(l);
125
+ if (p === undefined) {
126
+ // oxlint-disable-next-line typescript/no-unsafe-enum-assignment -- `L` is a string union, not an enum; the rule misreads the mapped type
127
+ const loader = catalog.loaders[l];
128
+ if (loader === undefined) return Promise.reject(new Error(`prosebook: no messages for locale "${l}"`));
129
+ p = loader().then((mod) => {
130
+ const layer = { messages: mod.default, h: createHelpers(l) };
131
+ loaded.set(l, layer);
132
+ pending.delete(l);
133
+ return layer;
134
+ });
135
+ p.catch(() => pending.delete(l));
136
+ pending.set(l, p);
137
+ }
138
+ return p;
139
+ }
140
+
141
+ async function setLocale(next: L | (string & {}) | readonly string[]): Promise<void> {
142
+ const target = negotiate(next, catalog.locales, catalog.source);
143
+ const ticket = ++latest;
144
+ const locales = chainOf(target, catalog.locales, catalog.source);
145
+ await Promise.all(locales.map(load));
146
+ // A slower load must not undo a later switch.
147
+ if (ticket !== latest || target === locale) return;
148
+ locale = target;
149
+ chain = layers(locales);
150
+ formatters.clear();
151
+ changed();
152
+ }
153
+
154
+ function find(key: string): [Compiled, Helpers] | undefined {
155
+ for (const layer of chain) {
156
+ const message = layer.messages[key];
157
+ if (message !== undefined) return [message, layer.h];
158
+ }
159
+ return undefined;
160
+ }
161
+
162
+ function render(key: string, values: Values): unknown {
163
+ const found = find(key);
164
+ if (found === undefined) return options.onMissing ? options.onMissing(key, locale) : key;
165
+ const [message, h] = found;
166
+ const out = typeof message === 'string' ? message : message(values, h);
167
+ const read = (globalThis as DevHooks).__PROSEBOOK_READ__;
168
+ if (read !== undefined) read(key, typeof out === 'string' ? out : textOf(message, values, h), h.locale);
169
+ return out;
170
+ }
171
+
172
+ function formatter<F>(kind: string, options: object | undefined, make: () => F): F {
173
+ const id = `${kind}${JSON.stringify(options ?? {})}`;
174
+ let made = formatters.get(id) as F | undefined;
175
+ if (made === undefined) formatters.set(id, (made = make()) as never);
176
+ return made;
177
+ }
178
+
179
+ const ready = options.locale === undefined ? Promise.resolve() : setLocale(options.locale);
180
+
181
+ return {
182
+ get locale() {
183
+ return locale;
184
+ },
185
+ get version() {
186
+ return version;
187
+ },
188
+ locales: catalog.locales,
189
+ source: catalog.source,
190
+ tags: defaultTags,
191
+ ready,
192
+ t(key, ...args) {
193
+ const out = render(key, (args[0] as Values | undefined) ?? {});
194
+ return typeof out === 'string' ? out : flatten(out).join('');
195
+ },
196
+ rich(key, ...values) {
197
+ const out = render(key, { ...defaultTags, ...(values[0] as Values | undefined) });
198
+ return flatten(out) as Chunks<never>;
199
+ },
200
+ has(key): key is keyof M & string {
201
+ return find(key) !== undefined;
202
+ },
203
+ setLocale,
204
+ subscribe(listener) {
205
+ listeners.add(listener);
206
+ return () => listeners.delete(listener);
207
+ },
208
+ number(value, opts) {
209
+ return formatter('n', opts, () => new Intl.NumberFormat(locale, opts)).format(value);
210
+ },
211
+ date(value, opts) {
212
+ return formatter('d', opts, () => new Intl.DateTimeFormat(locale, opts)).format(value);
213
+ },
214
+ list(items, opts) {
215
+ return formatter('l', opts, () => new Intl.ListFormat(locale, opts)).format(items);
216
+ },
217
+ relative(value, unit, opts) {
218
+ return formatter('r', opts, () => new Intl.RelativeTimeFormat(locale, opts)).format(value, unit);
219
+ },
220
+ };
221
+ }
@@ -0,0 +1,66 @@
1
+ import type { Arms, Helpers, Values } from './types.ts';
2
+
3
+ /**
4
+ * The helpers compiled messages call, for one locale. Formatters are built once per options object:
5
+ * the generator hoists each message's options to a module-level constant, so identity is a stable key.
6
+ */
7
+ export function createHelpers(locale: string): Helpers {
8
+ const numbers = new Map<Intl.NumberFormatOptions | undefined, Intl.NumberFormat>();
9
+ const dates = new Map<Intl.DateTimeFormatOptions | undefined, Intl.DateTimeFormat>();
10
+ let cardinal: Intl.PluralRules | undefined;
11
+ let ordinal: Intl.PluralRules | undefined;
12
+
13
+ return {
14
+ locale,
15
+ n(value, options) {
16
+ let format = numbers.get(options);
17
+ if (format === undefined) numbers.set(options, (format = new Intl.NumberFormat(locale, options)));
18
+ return format.format(value);
19
+ },
20
+ d(value, options) {
21
+ let format = dates.get(options);
22
+ if (format === undefined) dates.set(options, (format = new Intl.DateTimeFormat(locale, options)));
23
+ return format.format(value);
24
+ },
25
+ p(value, offset, isOrdinal, arms) {
26
+ const exact = arms[`=${value}`];
27
+ if (exact !== undefined) return exact();
28
+ const rules = isOrdinal
29
+ ? (ordinal ??= new Intl.PluralRules(locale, { type: 'ordinal' }))
30
+ : (cardinal ??= new Intl.PluralRules(locale));
31
+ return pick(arms, rules.select(value - offset));
32
+ },
33
+ s(value, arms) {
34
+ return pick(arms, String(value));
35
+ },
36
+ t(values: Values, tag, children) {
37
+ const render = values[tag];
38
+ return typeof render === 'function' ? (render as (chunks: unknown[]) => unknown)(flatten(children)) : children;
39
+ },
40
+ };
41
+ }
42
+
43
+ function pick(arms: Arms, arm: string): unknown {
44
+ // ICU requires an `other` arm, and the generator refuses a message without one.
45
+ return (Object.hasOwn(arms, arm) ? arms[arm]! : arms['other']!)();
46
+ }
47
+
48
+ /**
49
+ * A compiled message's output as a flat list: nested arrays opened, adjacent text joined, and
50
+ * `null`, `undefined` and booleans dropped, as React drops them.
51
+ */
52
+ export function flatten(output: unknown): unknown[] {
53
+ const out: unknown[] = [];
54
+ const walk = (part: unknown) => {
55
+ if (Array.isArray(part)) {
56
+ for (const p of part) walk(p);
57
+ return;
58
+ }
59
+ if (part === null || part === undefined || typeof part === 'boolean') return;
60
+ if (typeof part === 'number' || typeof part === 'bigint') part = String(part);
61
+ if (typeof part === 'string' && typeof out.at(-1) === 'string') out[out.length - 1] += part;
62
+ else out.push(part);
63
+ };
64
+ walk(output);
65
+ return out;
66
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Picks the best available locale for what was asked, in the order it was asked.
3
+ *
4
+ * Each requested tag tries an exact match, then its parents (`pt-BR` finds `pt`), then any locale
5
+ * of the same language (`pt` finds `pt-BR`). Matching ignores case, as BCP 47 does.
6
+ */
7
+ export function negotiate<L extends string>(requested: string | readonly string[], available: readonly L[], fallback: L): L {
8
+ const find = (tag: string) => available.find((a) => a.toLowerCase() === tag.toLowerCase());
9
+ for (const want of typeof requested === 'string' ? [requested] : requested) {
10
+ let tag = want;
11
+ for (;;) {
12
+ const found = find(tag);
13
+ if (found !== undefined) return found;
14
+ const cut = tag.lastIndexOf('-');
15
+ if (cut < 0) break;
16
+ tag = tag.slice(0, cut);
17
+ }
18
+ const language = languageOf(want);
19
+ const sibling = available.find((a) => languageOf(a) === language);
20
+ if (sibling !== undefined) return sibling;
21
+ }
22
+ return fallback;
23
+ }
24
+
25
+ /** The locales a message is looked up in, in order: the locale, its available parents, then the source. */
26
+ export function chainOf<L extends string>(locale: L, available: readonly L[], source: L): L[] {
27
+ const chain: L[] = [locale];
28
+ let tag: string = locale;
29
+ while (tag.includes('-')) {
30
+ tag = tag.slice(0, tag.lastIndexOf('-'));
31
+ const parent = available.find((a) => a.toLowerCase() === tag.toLowerCase());
32
+ if (parent !== undefined && !chain.includes(parent)) chain.push(parent);
33
+ }
34
+ if (!chain.includes(source)) chain.push(source);
35
+ return chain;
36
+ }
37
+
38
+ /** The locales the browser or the environment asks for, most preferred first. */
39
+ export function preferredLocales(): string[] {
40
+ const nav = (globalThis as { navigator?: { languages?: readonly string[]; language?: string } }).navigator;
41
+ if (nav?.languages && nav.languages.length > 0) return [...nav.languages];
42
+ if (nav?.language) return [nav.language];
43
+ const resolved = Intl.DateTimeFormat().resolvedOptions().locale;
44
+ return resolved ? [resolved] : [];
45
+ }
46
+
47
+ function languageOf(tag: string): string {
48
+ return tag.split('-', 1)[0]!.toLowerCase();
49
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The shapes the generated catalog and the runtime agree on.
3
+ *
4
+ * A catalog is compiled at build time: every ICU message becomes either a string (no placeholders)
5
+ * or a small function over its arguments and a set of locale-bound helpers. The runtime never parses
6
+ * ICU, so it carries no parser, needs no `eval`, and a message costs a property read or one call.
7
+ */
8
+
9
+ /** What the generator knows about one message: the arguments it takes and the tags it wraps text in. */
10
+ export interface MessageShape {
11
+ args: object;
12
+ tags: string;
13
+ }
14
+
15
+ /** Every key of a catalog, mapped to its shape. The generated `Messages` interface is one of these. */
16
+ export type MessageShapes = { [key: string]: MessageShape };
17
+
18
+ /**
19
+ * Augmented by the generated module, so hooks and components that are not handed a catalog
20
+ * (`useCopy()`, `<Text>`) still know its keys:
21
+ *
22
+ * ```ts
23
+ * declare module 'prosebook' {
24
+ * interface Register { messages: Messages; locale: Locale }
25
+ * }
26
+ * ```
27
+ *
28
+ * Add `tags: 'b' | 'link'` to say which tags the provider renders by default, so a call site
29
+ * needs to supply only the others.
30
+ */
31
+ // oxlint-disable-next-line typescript/no-empty-interface -- filled in by declaration merging
32
+ export interface Register {}
33
+
34
+ export type RegisteredMessages = Register extends { messages: infer M extends MessageShapes } ? M : MessageShapes;
35
+ export type RegisteredLocale = Register extends { locale: infer L extends string } ? L : string;
36
+ /** Tags the provider renders unless a call site says otherwise. */
37
+ export type DefaultTags = Register extends { tags: infer T extends string } ? T : never;
38
+
39
+ /**
40
+ * The helpers a compiled message calls, bound to the locale its words are in. Names are one letter
41
+ * because they appear once per placeholder in every generated module.
42
+ */
43
+ export interface Helpers {
44
+ readonly locale: string;
45
+ /** `{x, number, …}` and the `#` of a plural. */
46
+ n(value: number, options?: Intl.NumberFormatOptions): string;
47
+ /** `{x, date, …}` and `{x, time, …}`. */
48
+ d(value: Date | number, options?: Intl.DateTimeFormatOptions): string;
49
+ /** `{x, plural, …}` and `{x, selectordinal, …}`: picks an arm and renders it. */
50
+ p(value: number, offset: number, ordinal: boolean, arms: Arms): unknown;
51
+ /** `{x, select, …}`. */
52
+ s(value: unknown, arms: Arms): unknown;
53
+ /** `<tag>…</tag>`: the tag's function from the values, or the bare children when there is none. */
54
+ t(values: Values, tag: string, children: unknown): unknown;
55
+ }
56
+
57
+ export type Arms = { [arm: string]: () => unknown };
58
+ // `any`, not `unknown`: call sites are checked against the generated `Messages`, so a compiled
59
+ // message can hand its arguments to the helpers without a cast per placeholder.
60
+ // oxlint-disable-next-line typescript/no-explicit-any
61
+ export type Values = { readonly [name: string]: any };
62
+
63
+ /**
64
+ * Told of every message read: its key, the text it came to and the locale it was found in, which is
65
+ * the fallback's when the current locale lacks it. The Vite plugin's dev inspector sets one on
66
+ * `globalThis` to map text on screen back to keys; nothing sets it in a build.
67
+ */
68
+ export type ReadHook = (key: string, text: string, locale: string) => void;
69
+
70
+ /** Hands a copy a locale's messages, regenerated after a catalog edit, in place of the ones it loaded. */
71
+ export type HotHook = (locale: string, messages: CompiledMessages) => void;
72
+
73
+ /**
74
+ * What the Vite plugin sets on `globalThis` in dev. `__PROSEBOOK_HOT__` is there before the app runs,
75
+ * so each copy adds itself, and the generated modules call every copy when they are updated.
76
+ */
77
+ export type DevHooks = { __PROSEBOOK_READ__?: ReadHook; __PROSEBOOK_HOT__?: Set<HotHook> };
78
+
79
+ /** One compiled message. */
80
+ export type Compiled = string | ((values: Values, h: Helpers) => unknown);
81
+
82
+ /** One locale's compiled messages: what a generated `<locale>.ts` module exports by default. */
83
+ export type CompiledMessages = { readonly [key: string]: Compiled };
84
+
85
+ /** What a tag's function receives: the pieces it wraps, adjacent text already joined. */
86
+ export type Chunks<N> = (string | N)[];
87
+ export type TagFn<N> = (chunks: Chunks<N>) => N;
88
+ /** A tag renderer for any kind of node, as configured once on a `Copy`. */
89
+ export type AnyTagFn = (chunks: never) => unknown;
90
+
91
+ type NoArgs<T> = {} extends T ? true : false;
92
+
93
+ /** The arguments of a plain read: optional when the message takes none. */
94
+ export type ArgsParam<S extends MessageShape> = NoArgs<S['args']> extends true ? [args?: S['args']] : [args: S['args']];
95
+
96
+ type TagValues<S extends MessageShape, N> = { [T in Exclude<S['tags'], DefaultTags>]: TagFn<N> } & {
97
+ [T in Extract<S['tags'], DefaultTags>]?: TagFn<N>;
98
+ };
99
+
100
+ /** A rich read takes the message's arguments and a function per tag it wraps, beside the defaults. */
101
+ export type RichValues<S extends MessageShape, N> = S['args'] & TagValues<S, N>;
102
+ export type RichParam<S extends MessageShape, N> =
103
+ NoArgs<RichValues<S, N>> extends true ? [values?: RichValues<S, N>] : [values: RichValues<S, N>];
104
+
105
+ /** The keys whose message wraps part of itself in a tag. */
106
+ export type RichKey<M extends MessageShapes> = { [K in keyof M]: [M[K]['tags']] extends [never] ? never : K }[keyof M] & string;