@krizaka/i18n 0.0.0-stage → 0.1.0-beta.1
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 +202 -0
- package/README.md +128 -2
- package/dist/bin.js +319 -0
- package/dist/bin.js.map +1 -0
- package/dist/check.d.ts +73 -0
- package/dist/check.js +314 -0
- package/dist/check.js.map +1 -0
- package/dist/chunk-62MK7X4K.js +25 -0
- package/dist/chunk-62MK7X4K.js.map +1 -0
- package/dist/index.d.ts +100 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +43 -0
- package/dist/react.js +42 -0
- package/dist/react.js.map +1 -0
- package/dist/rich.d.ts +31 -0
- package/dist/rich.js +39 -0
- package/dist/rich.js.map +1 -0
- package/package.json +125 -3
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,129 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/i18n
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**The i18n engine of every Krizaka app, written once.** Typed message keys and placeholders from `en.json`, `format()`,
|
|
4
|
+
plural sets on `@krizaka/intl`, `<Rich>` for `<b>` and `<a>`, a React provider, and the `krizaka-i18n` CLI that checks
|
|
5
|
+
the catalogues and finds text written in the code. It replaces the `lib/i18n.ts` and the check script each app used to
|
|
6
|
+
carry.
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/@krizaka/i18n)
|
|
9
|
+
[](../../LICENSE)
|
|
10
|
+
|
|
11
|
+
## The rule
|
|
12
|
+
|
|
13
|
+
> **Every user-facing string lives in `messages/<locale>.json`.** `en.json` is the reference: its shape types the keys,
|
|
14
|
+
> every other locale has exactly the same keys, the same `{placeholders}` and the same markup. The code holds keys,
|
|
15
|
+
> never words.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @krizaka/i18n
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Node ≥ 20, ESM only. React (≥ 18) only for `./rich` and `./react`; TypeScript only for `krizaka-i18n scan`.
|
|
24
|
+
|
|
25
|
+
| Entry | What | React |
|
|
26
|
+
| :-- | :-- | :-- |
|
|
27
|
+
| `@krizaka/i18n` | `createI18n`, `format`, `placeholdersOf`, `isPluralMessage`, the types | no |
|
|
28
|
+
| `@krizaka/i18n/rich` | `<Rich text href? renderLink?>` | no hook — Server Components too |
|
|
29
|
+
| `@krizaka/i18n/react` | `createI18nReact(i18n)` → `I18nProvider`, `useI18n` | client (`"use client"`) |
|
|
30
|
+
| `@krizaka/i18n/check` | `checkMessages`, `findUnused`, `scanHardcoded`, `main` (the CLI, programmatic) | no |
|
|
31
|
+
| `krizaka-i18n` (bin) | `check` · `scan` | no |
|
|
32
|
+
|
|
33
|
+
## Bind it once in the app
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// lib/i18n.ts
|
|
37
|
+
import { createI18n } from "@krizaka/i18n";
|
|
38
|
+
import en from "@/messages/en.json";
|
|
39
|
+
import fr from "@/messages/fr.json";
|
|
40
|
+
|
|
41
|
+
export type Locale = "en" | "fr";
|
|
42
|
+
export type Messages = typeof en;
|
|
43
|
+
// The type arguments make fr.json type-check against en.json: a missing key fails to compile.
|
|
44
|
+
export const i18n = createI18n<Messages, Locale>({ en, fr }, { defaultLocale: "en" });
|
|
45
|
+
export const { getDictionary, asLocale, t } = i18n;
|
|
46
|
+
export { format } from "@krizaka/i18n";
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
i18n.locales; // ["en", "fr"]
|
|
51
|
+
i18n.asLocale("de"); // "en" — the default for anything unsupported
|
|
52
|
+
i18n.getDictionary("fr").home.title; // the catalogue, for Server Components and long content
|
|
53
|
+
t("auction.phase.SOLD"); // the key is typed: a typo fails to compile
|
|
54
|
+
i18n.translator("fr")("home.lead", { count: 3, org: "krizaka" });
|
|
55
|
+
format("{count} repositories", { count: 23 }); // "23 repositories"; a missing value stays "{count}"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- **Keys** are dotted paths to a string or a plural set (`MessageKey<typeof en>`). Lists are content, read as a branch.
|
|
59
|
+
- **Placeholders**: a JSON import types messages as `string`, so `t` accepts any values; a catalogue written `as const`
|
|
60
|
+
makes them required (`t("lead", {})` fails when `lead` is `"{count} items"`).
|
|
61
|
+
- **Plurals**: a plural set is an object of CLDR categories with `other`; `count` picks the form through
|
|
62
|
+
`@krizaka/intl`'s `plural` (`zero` is the explicit "exactly 0" form, in any language):
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{ "bids": { "zero": "No bid yet", "one": "{count} bid", "other": "{count} bids" } }
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`t("bids", { count: 2 })` → `"2 bids"`; in French `0` and `1` take `one`.
|
|
69
|
+
- **Missing keys** fall back to the default locale, then to the key itself — never an empty string.
|
|
70
|
+
|
|
71
|
+
## React
|
|
72
|
+
|
|
73
|
+
```tsx
|
|
74
|
+
// app/components/I18nProvider.tsx
|
|
75
|
+
"use client";
|
|
76
|
+
import { createI18nReact } from "@krizaka/i18n/react";
|
|
77
|
+
import { i18n } from "@/lib/i18n";
|
|
78
|
+
|
|
79
|
+
export const { I18nProvider, useI18n } = createI18nReact(i18n);
|
|
80
|
+
// <I18nProvider locale={locale} setLocale={(l) => router.push(`/${l}`)}>…</I18nProvider>
|
|
81
|
+
// const { locale, messages, t, format, setLocale } = useI18n();
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`setLocale` is the app's (a route, a cookie); outside a provider `useI18n()` reads the default locale. Server Components
|
|
85
|
+
skip the context and call `getDictionary(locale)`.
|
|
86
|
+
|
|
87
|
+
## `<Rich>` — `<b>` and `<a>`, nothing else
|
|
88
|
+
|
|
89
|
+
```tsx
|
|
90
|
+
import { Rich } from "@krizaka/i18n/rich";
|
|
91
|
+
|
|
92
|
+
<Rich text={t("home.lead")} /> // "<b>Open</b> source" → <strong>Open</strong> source
|
|
93
|
+
<Rich text={t("legal.read")} href={["/terms", "/privacy"]} renderLink={({ href, children }) => <Link href={href!}>{children}</Link>} />
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Messages are text, never HTML: an unknown or unbalanced tag is shown as written. Each `<a>` takes the next `href`; a
|
|
97
|
+
link without one renders its words only. `<b>` and `<a>` may hold each other.
|
|
98
|
+
|
|
99
|
+
## The CLI
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
krizaka-i18n check messages # same keys as en.json, no empty string, same {placeholders}, same markup
|
|
103
|
+
krizaka-i18n check messages --unused app --unused lib # …and fail on keys no source reads
|
|
104
|
+
krizaka-i18n check messages --json # machine-readable report for CI
|
|
105
|
+
krizaka-i18n scan app components --allow Krizaka --skip /app/api/ # hard-coded strings in .tsx (needs typescript)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
- **`check <dir>`** — every `<locale>.json` of `<dir>` against `--reference` (default `en`): missing and unknown keys,
|
|
109
|
+
empty strings, placeholders and markup that differ, a plural set where the reference has a string (or the reverse),
|
|
110
|
+
markup other than `<b>`/`<a>`. A plural set may carry the categories its language needs (French `many`), as long as
|
|
111
|
+
it has `other` and the same placeholders. `--unused <src>` (repeatable) is a heuristic: a key is read when its path
|
|
112
|
+
appears in a source, when a branch is read dynamically (`` `phase.${p}` ``, `nav[id]`, `"plus." + k`) or taken whole
|
|
113
|
+
(`const h = t.home;`, `messages("legal")`).
|
|
114
|
+
- **`scan <path>…`** — JSX text, `placeholder`/`title`/`aria-label`/`alt`/`label` literals, messages given to
|
|
115
|
+
`set…Error`/`Message`/`Notice`/`Hint`/`Status`/`Feedback`/`Toast` setters, `label`/`hint`/`title`/`placeholder`/
|
|
116
|
+
`description`/`message`/`text`/`caption` in data, and `alert`/`confirm`/`prompt`. `--allow` (comma-separated,
|
|
117
|
+
repeatable) lists brand names; `--skip` (regular expression on the path, repeatable) leaves files out; tests and
|
|
118
|
+
stories are always skipped, and Next.js `metadata`/`generateMetadata` objects too. `i18n-ignore` in a comment on the
|
|
119
|
+
line or the line above is a deliberate exception. `--summary` counts per file.
|
|
120
|
+
- Exit codes: `0` clean, `1` problems, `2` usage error. `--json` prints `{ ok, reference, locales, messages, problems }`
|
|
121
|
+
(`check`) or `{ ok, offenders }` (`scan`) on stdout.
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{ "scripts": { "lint": "eslint && krizaka-i18n check messages" } }
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
[Apache-2.0](LICENSE)
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import path3 from "path";
|
|
5
|
+
import { parseArgs } from "util";
|
|
6
|
+
|
|
7
|
+
// src/check.ts
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
|
|
11
|
+
// src/format.ts
|
|
12
|
+
var PLACEHOLDER = /\{(\w+)\}/g;
|
|
13
|
+
var PLURAL_CATEGORIES = ["zero", "one", "two", "few", "many", "other"];
|
|
14
|
+
function placeholdersOf(message) {
|
|
15
|
+
return [...new Set([...message.matchAll(PLACEHOLDER)].map((m) => m[1]))].sort();
|
|
16
|
+
}
|
|
17
|
+
function isPluralMessage(value) {
|
|
18
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
19
|
+
const keys = Object.keys(value);
|
|
20
|
+
return typeof value.other === "string" && keys.every((k) => PLURAL_CATEGORIES.includes(k) && typeof value[k] === "string");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/check.ts
|
|
24
|
+
function flatten(value, prefix = "", out = /* @__PURE__ */ new Map()) {
|
|
25
|
+
if (Array.isArray(value)) value.forEach((item, i) => flatten(item, `${prefix}[${i}]`, out));
|
|
26
|
+
else if (value && typeof value === "object" && !isPluralMessage(value)) {
|
|
27
|
+
for (const [key, item] of Object.entries(value)) flatten(item, prefix ? `${prefix}.${key}` : key, out);
|
|
28
|
+
} else out.set(prefix, value);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
var forms = (leaf) => typeof leaf === "string" ? [leaf] : Object.values(leaf);
|
|
32
|
+
var signature = (list) => list.sort().join(",");
|
|
33
|
+
var placeholders = (leaf) => signature([...new Set(forms(leaf).flatMap(placeholdersOf))]);
|
|
34
|
+
var TAG = /<\/?([A-Za-z][\w-]*)[^>]*>/g;
|
|
35
|
+
var tags = (text) => [...text.matchAll(TAG)].map((m) => m[0]);
|
|
36
|
+
var markup = (leaf) => signature([...new Set(forms(leaf).flatMap(tags))]);
|
|
37
|
+
var ALLOWED_TAGS = /* @__PURE__ */ new Set(["<b>", "</b>", "<a>", "</a>"]);
|
|
38
|
+
function checkLeaf(locale, key, value, problems) {
|
|
39
|
+
if (typeof value !== "string" && !isPluralMessage(value)) {
|
|
40
|
+
problems.push({ locale, key, kind: "invalid", message: `${locale}: ${key} is not a message (${JSON.stringify(value)})` });
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
for (const text of forms(value)) {
|
|
44
|
+
if (!text.trim()) problems.push({ locale, key, kind: "empty", message: `${locale}: empty ${key}` });
|
|
45
|
+
const bad = tags(text).filter((tag) => !ALLOWED_TAGS.has(tag));
|
|
46
|
+
if (bad.length) problems.push({ locale, key, kind: "markup", message: `${locale}: unsupported markup ${bad.join(" ")} in ${key} (only <b> and <a>)` });
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
function load(file, problems, locale) {
|
|
51
|
+
try {
|
|
52
|
+
return flatten(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
53
|
+
} catch (error) {
|
|
54
|
+
problems.push({ locale, key: file, kind: "invalid", message: `${locale}: cannot read ${file} (${error.message})` });
|
|
55
|
+
return void 0;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function checkMessages(options) {
|
|
59
|
+
const reference = options.reference ?? "en";
|
|
60
|
+
const problems = [];
|
|
61
|
+
const files = fs.existsSync(options.dir) ? fs.readdirSync(options.dir).filter((f) => f.endsWith(".json")).sort() : [];
|
|
62
|
+
const locales = files.map((f) => f.slice(0, -".json".length));
|
|
63
|
+
const result = (messages) => ({ ok: problems.length === 0, reference, locales, messages, problems });
|
|
64
|
+
if (!locales.includes(reference)) {
|
|
65
|
+
problems.push({ locale: reference, key: options.dir, kind: "invalid", message: `no ${reference}.json in ${options.dir}` });
|
|
66
|
+
return result(0);
|
|
67
|
+
}
|
|
68
|
+
const ref = load(path.join(options.dir, `${reference}.json`), problems, reference);
|
|
69
|
+
if (!ref) return result(0);
|
|
70
|
+
for (const [key, value] of ref) checkLeaf(reference, key, value, problems);
|
|
71
|
+
for (const locale of locales.filter((l) => l !== reference)) {
|
|
72
|
+
const other = load(path.join(options.dir, `${locale}.json`), problems, locale);
|
|
73
|
+
if (!other) continue;
|
|
74
|
+
for (const key of ref.keys()) if (!other.has(key)) problems.push({ locale, key, kind: "missing", message: `${locale}: missing ${key}` });
|
|
75
|
+
for (const [key, value] of other) {
|
|
76
|
+
if (!ref.has(key)) {
|
|
77
|
+
problems.push({ locale, key, kind: "unknown", message: `${locale}: unknown ${key} (not in ${reference}.json)` });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (!checkLeaf(locale, key, value, problems)) continue;
|
|
81
|
+
const expected = ref.get(key);
|
|
82
|
+
if (typeof expected !== "string" && !isPluralMessage(expected)) continue;
|
|
83
|
+
if (typeof expected !== typeof value) {
|
|
84
|
+
problems.push({ locale, key, kind: "plural", message: `${locale}: ${key} must be ${typeof expected === "string" ? "a string" : "a plural set"} as in ${reference}.json` });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (placeholders(expected) !== placeholders(value)) problems.push({ locale, key, kind: "placeholders", message: `${locale}: placeholders differ in ${key}` });
|
|
88
|
+
if (markup(expected) !== markup(value)) problems.push({ locale, key, kind: "markup", message: `${locale}: markup differs in ${key}` });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (options.unused?.length) {
|
|
92
|
+
for (const key of findUnused([...ref.keys()], options.unused)) {
|
|
93
|
+
problems.push({ locale: reference, key, kind: "unused", message: `unused ${key} (read nowhere in ${options.unused.join(", ")})` });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return result(ref.size);
|
|
97
|
+
}
|
|
98
|
+
var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
|
|
99
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".next", "dist", "build", "coverage", ".turbo", ".git"]);
|
|
100
|
+
function readSources(entry, out = []) {
|
|
101
|
+
const stat = fs.statSync(entry, { throwIfNoEntry: false });
|
|
102
|
+
if (!stat) return out;
|
|
103
|
+
if (stat.isFile()) {
|
|
104
|
+
if (SOURCE.test(entry)) out.push(fs.readFileSync(entry, "utf8"));
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
for (const name of fs.readdirSync(entry)) if (!SKIP_DIRS.has(name)) readSources(path.join(entry, name), out);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
var wholeBranch = (branch) => new RegExp(`[.'"\`]${branch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w.$-])`);
|
|
111
|
+
function findUnused(keys, sources) {
|
|
112
|
+
const text = sources.flatMap((entry) => readSources(entry)).join("\n");
|
|
113
|
+
return keys.filter((full) => {
|
|
114
|
+
const key = full.replace(/\[\d+\].*$/, "");
|
|
115
|
+
if (text.includes(key)) return false;
|
|
116
|
+
const parts = key.split(".");
|
|
117
|
+
for (let i = parts.length - 1; i > 0; i--) {
|
|
118
|
+
const branch = parts.slice(0, i).join(".");
|
|
119
|
+
if (text.includes(`${branch}.\${`) || text.includes(`${branch}[`) || text.includes(`${branch}." +`) || text.includes(`${branch}.' +`)) return false;
|
|
120
|
+
if (wholeBranch(branch).test(text)) return false;
|
|
121
|
+
}
|
|
122
|
+
return true;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function formatReport(result, limit = 50) {
|
|
126
|
+
if (result.ok) {
|
|
127
|
+
return `\u2713 i18n: ${result.messages} messages, ${result.locales.length > 1 ? "every locale complete" : `${result.reference} only`}`;
|
|
128
|
+
}
|
|
129
|
+
const shown = result.problems.slice(0, limit).map((p) => p.message);
|
|
130
|
+
const more = result.problems.length > limit ? `
|
|
131
|
+
\u2026 and ${result.problems.length - limit} more` : "";
|
|
132
|
+
return `\u2717 i18n: ${result.problems.length} problem(s)
|
|
133
|
+
${shown.join("\n ")}${more}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/scan.ts
|
|
137
|
+
import fs2 from "fs";
|
|
138
|
+
import path2 from "path";
|
|
139
|
+
var ATTRS = /* @__PURE__ */ new Set(["placeholder", "title", "aria-label", "alt", "label"]);
|
|
140
|
+
var SETTER = /^set\w*(Error|Message|Notice|Hint|Status|Feedback|Toast)$/;
|
|
141
|
+
var PROPS = /* @__PURE__ */ new Set(["label", "hint", "title", "placeholder", "description", "message", "text", "caption"]);
|
|
142
|
+
var ALWAYS_SKIP = [/\.test\.tsx?$/, /\.spec\.tsx?$/, /\.stories\.tsx$/];
|
|
143
|
+
var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", ".next", "dist", "build", "coverage"]);
|
|
144
|
+
function* tsxFiles(entry) {
|
|
145
|
+
const stat = fs2.statSync(entry, { throwIfNoEntry: false });
|
|
146
|
+
if (!stat) return;
|
|
147
|
+
if (stat.isFile()) {
|
|
148
|
+
if (entry.endsWith(".tsx")) yield entry;
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
for (const name of fs2.readdirSync(entry).sort()) if (!SKIP_DIRS2.has(name)) yield* tsxFiles(path2.join(entry, name));
|
|
152
|
+
}
|
|
153
|
+
function scanHardcoded(ts, options) {
|
|
154
|
+
const allowed = new Set(options.allow ?? []);
|
|
155
|
+
const skip = [...ALWAYS_SKIP, ...(options.skip ?? []).map((s) => typeof s === "string" ? new RegExp(s) : s)];
|
|
156
|
+
const root = options.root ?? process.cwd();
|
|
157
|
+
const words = (text) => (text.match(/[A-Za-zÀ-ÿ]{3,}/g) ?? []).filter((w) => !allowed.has(w));
|
|
158
|
+
const shownStrings = (expr) => {
|
|
159
|
+
if (ts.isParenthesizedExpression(expr)) return shownStrings(expr.expression);
|
|
160
|
+
if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) return words(expr.text).length ? [{ text: expr.text, node: expr }] : [];
|
|
161
|
+
if (ts.isTemplateExpression(expr)) {
|
|
162
|
+
const parts = [expr.head, ...expr.templateSpans.map((s) => s.literal)].map((p) => p.text);
|
|
163
|
+
return words(parts.join(" ")).length ? [{ text: parts.join("\u2026"), node: expr }] : [];
|
|
164
|
+
}
|
|
165
|
+
if (ts.isConditionalExpression(expr)) return [...shownStrings(expr.whenTrue), ...shownStrings(expr.whenFalse)];
|
|
166
|
+
if (ts.isBinaryExpression(expr)) {
|
|
167
|
+
const op = expr.operatorToken.kind;
|
|
168
|
+
if (op === ts.SyntaxKind.AmpersandAmpersandToken) return shownStrings(expr.right);
|
|
169
|
+
if (op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken) return [...shownStrings(expr.right), ...shownStrings(expr.left)];
|
|
170
|
+
}
|
|
171
|
+
return [];
|
|
172
|
+
};
|
|
173
|
+
const isMetadata = (node) => {
|
|
174
|
+
for (let n = node.parent; n; n = n.parent) {
|
|
175
|
+
if (ts.isVariableDeclaration(n) && n.name.getText() === "metadata") return true;
|
|
176
|
+
if (ts.isFunctionDeclaration(n) && n.name?.getText() === "generateMetadata") return true;
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
};
|
|
180
|
+
const offenders = [];
|
|
181
|
+
for (const entry of options.paths) {
|
|
182
|
+
for (const file of tsxFiles(entry)) {
|
|
183
|
+
if (skip.some((re) => re.test(file.split(path2.sep).join("/")))) continue;
|
|
184
|
+
const source = fs2.readFileSync(file, "utf8");
|
|
185
|
+
const lines = source.split("\n");
|
|
186
|
+
const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
187
|
+
const report = (node, kind, text) => {
|
|
188
|
+
const line = sf.getLineAndCharacterOfPosition(node.getStart()).line;
|
|
189
|
+
if (lines.slice(Math.max(0, line - 1), line + 1).some((l) => l.includes("i18n-ignore"))) return;
|
|
190
|
+
offenders.push({ file: path2.relative(root, file), line: line + 1, kind, text: text.replace(/\s+/g, " ").trim().slice(0, 80) });
|
|
191
|
+
};
|
|
192
|
+
const visit = (node) => {
|
|
193
|
+
if (ts.isJsxText(node)) {
|
|
194
|
+
if (words(node.text).length) report(node, "text", node.text);
|
|
195
|
+
} else if (ts.isJsxAttribute(node) && ATTRS.has(node.name.getText()) && node.initializer && ts.isStringLiteral(node.initializer)) {
|
|
196
|
+
if (words(node.initializer.text).length) report(node, `attr ${node.name.getText()}`, node.initializer.text);
|
|
197
|
+
} else if (ts.isJsxExpression(node) && node.expression && (!ts.isJsxAttribute(node.parent) || ATTRS.has(node.parent.name.getText()))) {
|
|
198
|
+
for (const lit of shownStrings(node.expression)) report(lit.node, "text", lit.text);
|
|
199
|
+
} else if (ts.isCallExpression(node)) {
|
|
200
|
+
const callee = node.expression.getText();
|
|
201
|
+
if (/^(window\.)?(alert|confirm|prompt)$/.test(callee)) report(node, "dialog", callee);
|
|
202
|
+
else if (SETTER.test(callee)) for (const arg of node.arguments) for (const lit of shownStrings(arg)) report(lit.node, `set ${callee}`, lit.text);
|
|
203
|
+
} else if (ts.isPropertyAssignment(node) && PROPS.has(node.name.getText()) && !isMetadata(node)) {
|
|
204
|
+
for (const lit of shownStrings(node.initializer)) report(lit.node, `prop ${node.name.getText()}`, lit.text);
|
|
205
|
+
}
|
|
206
|
+
ts.forEachChild(node, visit);
|
|
207
|
+
};
|
|
208
|
+
visit(sf);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return offenders;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/cli.ts
|
|
215
|
+
var USAGE = `Usage:
|
|
216
|
+
krizaka-i18n check <dir> [--reference en] [--unused <src>]\u2026 [--json]
|
|
217
|
+
The catalogues of <dir> (<locale>.json) against the reference: same keys, no empty string, same {placeholders},
|
|
218
|
+
same markup (<b>, <a> only). --unused <src> also fails on keys no source under <src> reads.
|
|
219
|
+
krizaka-i18n scan <path>\u2026 [--allow <word,\u2026>]\u2026 [--skip <regex>]\u2026 [--summary] [--json]
|
|
220
|
+
Hard-coded user-facing strings in .tsx sources (needs the typescript package). --allow lists brand names,
|
|
221
|
+
--skip leaves files out (regular expression on the path), --summary counts per file.
|
|
222
|
+
--json prints a machine-readable report on stdout (for CI).`;
|
|
223
|
+
var defaultIO = {
|
|
224
|
+
stdout: (line) => console.log(line),
|
|
225
|
+
stderr: (line) => console.error(line),
|
|
226
|
+
cwd: process.cwd(),
|
|
227
|
+
loadTypeScript: async () => (await import("typescript")).default
|
|
228
|
+
};
|
|
229
|
+
async function main(argv, io = defaultIO) {
|
|
230
|
+
const [command, ...rest] = argv;
|
|
231
|
+
if (command === void 0 || command === "--help" || command === "-h" || command === "help") {
|
|
232
|
+
io.stdout(USAGE);
|
|
233
|
+
return command === void 0 ? 2 : 0;
|
|
234
|
+
}
|
|
235
|
+
let parsed;
|
|
236
|
+
try {
|
|
237
|
+
parsed = parseArgs({
|
|
238
|
+
args: [...rest],
|
|
239
|
+
allowPositionals: true,
|
|
240
|
+
options: {
|
|
241
|
+
json: { type: "boolean" },
|
|
242
|
+
reference: { type: "string" },
|
|
243
|
+
unused: { type: "string", multiple: true },
|
|
244
|
+
allow: { type: "string", multiple: true },
|
|
245
|
+
skip: { type: "string", multiple: true },
|
|
246
|
+
summary: { type: "boolean" }
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
} catch (error) {
|
|
250
|
+
io.stderr(`${error.message}
|
|
251
|
+
|
|
252
|
+
${USAGE}`);
|
|
253
|
+
return 2;
|
|
254
|
+
}
|
|
255
|
+
const { values, positionals } = parsed;
|
|
256
|
+
const resolve = (p) => path3.resolve(io.cwd, p);
|
|
257
|
+
if (command === "check") {
|
|
258
|
+
if (positionals.length !== 1) {
|
|
259
|
+
io.stderr(`check takes one folder of catalogues.
|
|
260
|
+
|
|
261
|
+
${USAGE}`);
|
|
262
|
+
return 2;
|
|
263
|
+
}
|
|
264
|
+
const result = checkMessages({
|
|
265
|
+
dir: resolve(positionals[0]),
|
|
266
|
+
reference: values.reference,
|
|
267
|
+
unused: values.unused?.map(resolve)
|
|
268
|
+
});
|
|
269
|
+
if (values.json) io.stdout(JSON.stringify(result, null, 2));
|
|
270
|
+
else (result.ok ? io.stdout : io.stderr)(formatReport(result));
|
|
271
|
+
return result.ok ? 0 : 1;
|
|
272
|
+
}
|
|
273
|
+
if (command === "scan") {
|
|
274
|
+
if (!positionals.length) {
|
|
275
|
+
io.stderr(`scan takes at least one folder.
|
|
276
|
+
|
|
277
|
+
${USAGE}`);
|
|
278
|
+
return 2;
|
|
279
|
+
}
|
|
280
|
+
let ts;
|
|
281
|
+
try {
|
|
282
|
+
ts = await io.loadTypeScript();
|
|
283
|
+
} catch {
|
|
284
|
+
io.stderr("scan needs the typescript package: npm install -D typescript");
|
|
285
|
+
return 2;
|
|
286
|
+
}
|
|
287
|
+
const offenders = scanHardcoded(ts, {
|
|
288
|
+
paths: positionals.map(resolve),
|
|
289
|
+
allow: values.allow?.flatMap((list) => list.split(",")).map((w) => w.trim()).filter(Boolean),
|
|
290
|
+
skip: values.skip,
|
|
291
|
+
root: io.cwd
|
|
292
|
+
});
|
|
293
|
+
if (values.json) io.stdout(JSON.stringify({ ok: offenders.length === 0, offenders }, null, 2));
|
|
294
|
+
else printScan(offenders, Boolean(values.summary), io);
|
|
295
|
+
return offenders.length ? 1 : 0;
|
|
296
|
+
}
|
|
297
|
+
io.stderr(`Unknown command "${command}".
|
|
298
|
+
|
|
299
|
+
${USAGE}`);
|
|
300
|
+
return 2;
|
|
301
|
+
}
|
|
302
|
+
function printScan(offenders, summary, io) {
|
|
303
|
+
if (!offenders.length) {
|
|
304
|
+
io.stdout("\u2713 i18n: no hard-coded user-facing string.");
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (summary) {
|
|
308
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
309
|
+
for (const o of offenders) byFile.set(o.file, (byFile.get(o.file) ?? 0) + 1);
|
|
310
|
+
for (const [file, n] of [...byFile].sort((a, b) => b[1] - a[1])) io.stdout(`${String(n).padStart(4)} ${file}`);
|
|
311
|
+
} else {
|
|
312
|
+
for (const o of offenders) io.stdout(`${o.file}:${o.line} [${o.kind}] ${o.text}`);
|
|
313
|
+
}
|
|
314
|
+
io.stderr(`\u2717 i18n: ${offenders.length} hard-coded user-facing string(s): move them to the message catalogue.`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/bin.ts
|
|
318
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
319
|
+
//# sourceMappingURL=bin.js.map
|