@yapyak/vite 0.0.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 +21 -0
- package/README.md +17 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +862 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joakim Uhrwing
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @yapyak/vite
|
|
2
|
+
|
|
3
|
+
> Node-only
|
|
4
|
+
|
|
5
|
+
Vite plugin for yapyak.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @yapyak/vite
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @yapyak/vite
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Documentation
|
|
16
|
+
|
|
17
|
+
[yapyak.dev/reference/vite](https://yapyak.dev/reference/vite)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
//#region src/plugin.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Options for {@link yapyak}.
|
|
5
|
+
*/
|
|
6
|
+
type YapyakOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* Locks the build to a single locale.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Must be one of the configured locales. Throws at config resolution if not.
|
|
12
|
+
*/
|
|
13
|
+
fixedLocale?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Creates the yapyak Vite plugin.
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* Configuration is read from `yapyak.config.{ts,mts,mjs,js}` in the project root.
|
|
20
|
+
*
|
|
21
|
+
* @param options - The options.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts [vite.config.ts]
|
|
25
|
+
* import { yapyak } from '@yapyak/vite';
|
|
26
|
+
* import { defineConfig } from 'vite';
|
|
27
|
+
*
|
|
28
|
+
* export default defineConfig({
|
|
29
|
+
* plugins: [yapyak()]
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @example Lock the build to a single locale
|
|
34
|
+
* ```ts [vite.config.ts]
|
|
35
|
+
* import { yapyak } from '@yapyak/vite';
|
|
36
|
+
* import { defineConfig } from 'vite';
|
|
37
|
+
*
|
|
38
|
+
* export default defineConfig({
|
|
39
|
+
* plugins: [yapyak({ fixedLocale: process.env.YAPYAK_LOCALE })]
|
|
40
|
+
* });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
declare function yapyak(options?: YapyakOptions): Plugin[];
|
|
44
|
+
//#endregion
|
|
45
|
+
export { type YapyakOptions, yapyak };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
import { CorruptLocaleFileError, YAP_RUNTIME, autoTranslate, detectRenames, discoverLocales, extractFile, findTranslation, getDocsUrl, migrateLocales, parseTemplate, readLocaleData, readLocaleFile, syncLocaleFiles, toMessageKey, toVariants, transformFile, validateLocaleCode, walkSourceFiles, writeRegister } from "yapyak/compiler/internal";
|
|
2
|
+
import { createFilter, defineRuntime, loadYapyakConfig } from "yapyak/config/internal";
|
|
3
|
+
import { basename, extname, join, relative, sep } from "node:path";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
//#region src/locale-resolver.ts
|
|
6
|
+
function createLocaleResolver(context, projectRoot, options) {
|
|
7
|
+
const fixedLocale = options?.fixedLocale;
|
|
8
|
+
let discovery;
|
|
9
|
+
let emitted;
|
|
10
|
+
let localeData;
|
|
11
|
+
function getDiscovery() {
|
|
12
|
+
if (discovery === void 0) discovery = discoverLocales(context.localesDir, projectRoot, { defaultLocale: context.defaultLocale });
|
|
13
|
+
return discovery;
|
|
14
|
+
}
|
|
15
|
+
function getProjectLocales() {
|
|
16
|
+
const result = getDiscovery();
|
|
17
|
+
return {
|
|
18
|
+
defaultLocale: result.defaultLocale,
|
|
19
|
+
locales: result.locales
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function getEmittedLocales() {
|
|
23
|
+
if (emitted === void 0) {
|
|
24
|
+
const project = getProjectLocales();
|
|
25
|
+
emitted = fixedLocale === void 0 ? project : {
|
|
26
|
+
defaultLocale: fixedLocale,
|
|
27
|
+
locales: [fixedLocale]
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return emitted;
|
|
31
|
+
}
|
|
32
|
+
function getLocaleData() {
|
|
33
|
+
if (localeData === void 0) localeData = readLocaleData({
|
|
34
|
+
locales: getEmittedLocales().locales,
|
|
35
|
+
localesDir: context.localesDir
|
|
36
|
+
}, projectRoot);
|
|
37
|
+
return localeData;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
getDiscovery,
|
|
41
|
+
getEmittedLocales,
|
|
42
|
+
getLocaleData,
|
|
43
|
+
getProjectLocales,
|
|
44
|
+
invalidateData() {
|
|
45
|
+
localeData = void 0;
|
|
46
|
+
},
|
|
47
|
+
invalidateStructure() {
|
|
48
|
+
discovery = void 0;
|
|
49
|
+
emitted = void 0;
|
|
50
|
+
localeData = void 0;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/virtual-runtime.ts
|
|
56
|
+
const RUNTIME_ID = "yapyak/runtime";
|
|
57
|
+
const RUNTIME_RESOLVED = "\0yapyak:runtime";
|
|
58
|
+
const RUNTIME_NO_EXTERNAL = ["yapyak", /^@yapyak\//];
|
|
59
|
+
function isRuntimeExternal(id) {
|
|
60
|
+
return RUNTIME_NO_EXTERNAL.some((pattern) => typeof pattern === "string" ? pattern === id : pattern.test(id));
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/plugin/locale-warning.ts
|
|
64
|
+
function renderLocaleWarning(warning, localesDir) {
|
|
65
|
+
const reason = warning.issue === "invalid-structure" ? "does not look like a BCP 47 locale tag" : "is not a recognized ISO 639-1 language code";
|
|
66
|
+
const action = "yapyak will skip syncing stubs and translating for this locale.";
|
|
67
|
+
const hint = warning.suggestion ? ` Did you mean '${warning.suggestion}'? Rename \`${localesDir}/${warning.code}.json\` to \`${localesDir}/${warning.suggestion}.json\` to enable.` : ` Rename \`${localesDir}/${warning.code}.json\` to a valid locale code, or remove the file.`;
|
|
68
|
+
return `[yapyak] locale '${warning.code}' ${reason}. ${action}${hint}`;
|
|
69
|
+
}
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/plugin/config.ts
|
|
72
|
+
function createConfigPlugin(state) {
|
|
73
|
+
return {
|
|
74
|
+
config() {
|
|
75
|
+
return {
|
|
76
|
+
optimizeDeps: { exclude: [RUNTIME_ID] },
|
|
77
|
+
ssr: { noExternal: RUNTIME_NO_EXTERNAL }
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
async configResolved(config) {
|
|
81
|
+
state.projectRoot = config.root;
|
|
82
|
+
state.yapyakDir = join(state.projectRoot, ".yapyak");
|
|
83
|
+
state.command = config.command;
|
|
84
|
+
state.logger = config.logger;
|
|
85
|
+
const result = await loadYapyakConfig(state.projectRoot);
|
|
86
|
+
state.normalized = result.config;
|
|
87
|
+
state.configFile = result.configFile;
|
|
88
|
+
state.filter = createFilter(result.config.include, result.config.exclude);
|
|
89
|
+
const ssrExternal = config.ssr?.external;
|
|
90
|
+
if (Array.isArray(ssrExternal) && config.ssr) config.ssr.external = ssrExternal.filter((id) => !isRuntimeExternal(id));
|
|
91
|
+
else if (ssrExternal === true || typeof ssrExternal === "function") {
|
|
92
|
+
const description = typeof ssrExternal === "function" ? "a function" : "`true`";
|
|
93
|
+
state.logger.warn(`[yapyak] config.ssr.external is set to ${description}. yapyak's runtime must not be externalized for SSR — translations would not inline. Use an array form for ssr.external, or have your function return false/null for 'yapyak' and 'yapyak/runtime'.`);
|
|
94
|
+
}
|
|
95
|
+
state.resolver = createLocaleResolver({
|
|
96
|
+
defaultLocale: result.config.defaultLocale,
|
|
97
|
+
localesDir: result.config.localesDir
|
|
98
|
+
}, state.projectRoot, { fixedLocale: state.fixedLocale });
|
|
99
|
+
const discovery = state.resolver.getDiscovery();
|
|
100
|
+
for (const warning of discovery.warnings) state.logger.warn(renderLocaleWarning(warning, result.config.localesDir));
|
|
101
|
+
if (state.fixedLocale !== void 0 && !discovery.locales.includes(state.fixedLocale)) throw new Error(`[yapyak] fixedLocale '${state.fixedLocale}' is not configured in this project. Available locales: ${discovery.locales.join(", ")}. Either add '${state.fixedLocale}' to your locales/ directory or pick an existing locale.`);
|
|
102
|
+
writeRegister(state.resolver.getEmittedLocales().locales, state.yapyakDir);
|
|
103
|
+
},
|
|
104
|
+
name: "yapyak:config"
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/plugin/file-id.ts
|
|
109
|
+
function toFileId(projectRoot, id) {
|
|
110
|
+
return relative(projectRoot, id.split("?")[0] ?? id).replaceAll("\\", "/");
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/plugin/candidate-id.ts
|
|
114
|
+
function isCandidateId(id, filter, projectRoot) {
|
|
115
|
+
if (id.startsWith("\0")) return false;
|
|
116
|
+
return filter(toFileId(projectRoot, id));
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/plugin/error-diagnostic.ts
|
|
120
|
+
function renderErrorDiagnostics(logger, result) {
|
|
121
|
+
const errors = [];
|
|
122
|
+
for (const diagnostic of result.diagnostics) {
|
|
123
|
+
if (diagnostic.severity === "error") {
|
|
124
|
+
errors.push(diagnostic);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
logger.warn(formatDiagnostic(diagnostic));
|
|
128
|
+
}
|
|
129
|
+
return errors;
|
|
130
|
+
}
|
|
131
|
+
function formatDiagnostic(diagnostic) {
|
|
132
|
+
const location = `${diagnostic.fileId}:${diagnostic.range.start.line}:${diagnostic.range.start.column}`;
|
|
133
|
+
return `[yapyak] ${diagnostic.code} ${location}: ${diagnostic.message}\nSee ${getDocsUrl(diagnostic.code)}`;
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/plugin/state.ts
|
|
137
|
+
function createState(options = {}) {
|
|
138
|
+
return {
|
|
139
|
+
command: "serve",
|
|
140
|
+
extractionCache: /* @__PURE__ */ new Map(),
|
|
141
|
+
filter: () => false,
|
|
142
|
+
...options.fixedLocale !== void 0 && { fixedLocale: options.fixedLocale },
|
|
143
|
+
logger: createConsoleLogger(),
|
|
144
|
+
messagesByFile: /* @__PURE__ */ new Map(),
|
|
145
|
+
projectRoot: process.cwd(),
|
|
146
|
+
teardownCallbacks: [],
|
|
147
|
+
yapyakDir: ""
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function getNormalized(state) {
|
|
151
|
+
if (state.normalized === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
|
|
152
|
+
return state.normalized;
|
|
153
|
+
}
|
|
154
|
+
function getResolver(state) {
|
|
155
|
+
if (state.resolver === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
|
|
156
|
+
return state.resolver;
|
|
157
|
+
}
|
|
158
|
+
function createConsoleLogger() {
|
|
159
|
+
const noop = () => void 0;
|
|
160
|
+
return {
|
|
161
|
+
clearScreen: noop,
|
|
162
|
+
error: (message) => {
|
|
163
|
+
console.error(message);
|
|
164
|
+
},
|
|
165
|
+
hasErrorLogged: () => false,
|
|
166
|
+
hasWarned: false,
|
|
167
|
+
info: (message) => {
|
|
168
|
+
console.log(message);
|
|
169
|
+
},
|
|
170
|
+
warn: (message) => {
|
|
171
|
+
console.warn(message);
|
|
172
|
+
},
|
|
173
|
+
warnOnce: (message) => {
|
|
174
|
+
console.warn(message);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/plugin/extraction.ts
|
|
180
|
+
function resolveExtraction(state, fileId, source) {
|
|
181
|
+
if (!source.includes("yapyak")) return {
|
|
182
|
+
callSites: [],
|
|
183
|
+
diagnostics: [],
|
|
184
|
+
messages: []
|
|
185
|
+
};
|
|
186
|
+
const entry = state.extractionCache.get(fileId);
|
|
187
|
+
if (entry && entry.source === source && entry.callSiteCount === 0) return {
|
|
188
|
+
callSites: [],
|
|
189
|
+
diagnostics: entry.diagnostics,
|
|
190
|
+
messages: entry.messages
|
|
191
|
+
};
|
|
192
|
+
const result = extractFile(fileId, source, { processors: getNormalized(state).processors });
|
|
193
|
+
state.extractionCache.set(fileId, {
|
|
194
|
+
callSiteCount: result.callSites.length,
|
|
195
|
+
diagnostics: result.diagnostics,
|
|
196
|
+
messages: result.messages,
|
|
197
|
+
source
|
|
198
|
+
});
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region src/plugin/locale-file.ts
|
|
203
|
+
function isLocaleFile(state, path) {
|
|
204
|
+
const relativePath = relative(join(state.projectRoot, getNormalized(state).localesDir), path);
|
|
205
|
+
if (relativePath === "" || relativePath.startsWith("..") || relativePath.includes(sep)) return false;
|
|
206
|
+
return extname(relativePath) === ".json";
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/plugin/yapyak-command.ts
|
|
210
|
+
function runYapyakCommand(args) {
|
|
211
|
+
const userAgent = process.env.npm_config_user_agent ?? "";
|
|
212
|
+
if (userAgent.startsWith("pnpm/")) return `pnpm yapyak ${args}`;
|
|
213
|
+
if (userAgent.startsWith("yarn/")) return `yarn yapyak ${args}`;
|
|
214
|
+
if (userAgent.startsWith("bun/")) return `bunx yapyak ${args}`;
|
|
215
|
+
return `npx yapyak ${args}`;
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/plugin/stub.ts
|
|
219
|
+
function fillStubs(state) {
|
|
220
|
+
state.autoTranslateController?.abort();
|
|
221
|
+
state.autoTranslateController = void 0;
|
|
222
|
+
const config = getNormalized(state);
|
|
223
|
+
const translator = config.translator;
|
|
224
|
+
if (!translator) return;
|
|
225
|
+
if (config.autoTranslateThreshold <= 0) return;
|
|
226
|
+
const allMessages = [];
|
|
227
|
+
for (const list of state.messagesByFile.values()) allMessages.push(...list);
|
|
228
|
+
if (allMessages.length === 0) return;
|
|
229
|
+
const { defaultLocale, locales } = getResolver(state).getProjectLocales();
|
|
230
|
+
const translatableLocales = locales.filter((locale) => validateLocaleCode(locale).valid);
|
|
231
|
+
const missing = discoverMissingMessageKeys(allMessages, translatableLocales, defaultLocale, getResolver(state).getLocaleData());
|
|
232
|
+
if (missing.size === 0) return;
|
|
233
|
+
if (missing.size > config.autoTranslateThreshold) {
|
|
234
|
+
state.logger.info(`[yapyak] ${missing.size} new strings detected. Run \`${runYapyakCommand("translate")}\` to fill.`);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const filtered = allMessages.filter((message) => missing.has(toMessageKey(message.source, message.context)));
|
|
238
|
+
const targetLocaleCount = translatableLocales.filter((locale) => locale !== defaultLocale).length;
|
|
239
|
+
const startedAt = Date.now();
|
|
240
|
+
state.logger.info(`[yapyak] translating ${filtered.length} ${pluralize("string", filtered.length)} × ${targetLocaleCount} ${pluralize("locale", targetLocaleCount)} via ${translator.id}…`);
|
|
241
|
+
const controller = new AbortController();
|
|
242
|
+
state.autoTranslateController = controller;
|
|
243
|
+
runAutoTranslate(state, {
|
|
244
|
+
defaultLocale,
|
|
245
|
+
filtered,
|
|
246
|
+
locales,
|
|
247
|
+
signal: controller.signal,
|
|
248
|
+
startedAt,
|
|
249
|
+
translator
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async function runAutoTranslate(state, input) {
|
|
253
|
+
const config = getNormalized(state);
|
|
254
|
+
try {
|
|
255
|
+
const result = await autoTranslate({
|
|
256
|
+
messages: input.filtered,
|
|
257
|
+
translator: input.translator
|
|
258
|
+
}, {
|
|
259
|
+
defaultLocale: input.defaultLocale,
|
|
260
|
+
locales: input.locales,
|
|
261
|
+
localesDir: config.localesDir
|
|
262
|
+
}, state.projectRoot, {
|
|
263
|
+
examples: config.examples,
|
|
264
|
+
signal: input.signal,
|
|
265
|
+
yapyakDir: state.yapyakDir
|
|
266
|
+
});
|
|
267
|
+
if (input.signal.aborted) return;
|
|
268
|
+
if (result.translated > 0) getResolver(state).invalidateData();
|
|
269
|
+
const elapsed = formatElapsed(Date.now() - input.startedAt);
|
|
270
|
+
if (result.errors.length === 0) state.logger.info(`[yapyak] ✓ ${result.translated} translated · ${elapsed}`);
|
|
271
|
+
else state.logger.info(`[yapyak] ${result.translated} translated, ${result.errors.length} failed · ${elapsed}`);
|
|
272
|
+
for (const group of buildErrorGroups(result.errors)) state.logger.warn(renderTranslationErrorGroup(group));
|
|
273
|
+
} catch (error) {
|
|
274
|
+
if (input.signal.aborted) return;
|
|
275
|
+
const elapsed = formatElapsed(Date.now() - input.startedAt);
|
|
276
|
+
state.logger.warn(`[yapyak] auto-translate error · ${elapsed} · ${String(error)}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function discoverMissingMessageKeys(messages, locales, defaultLocale, localeData) {
|
|
280
|
+
const missing = /* @__PURE__ */ new Set();
|
|
281
|
+
for (const message of messages) {
|
|
282
|
+
const messageKey = toMessageKey(message.source, message.context);
|
|
283
|
+
if (missing.has(messageKey)) continue;
|
|
284
|
+
let isFlagged = false;
|
|
285
|
+
for (const locale of locales) {
|
|
286
|
+
if (locale === defaultLocale) continue;
|
|
287
|
+
const localeFile = localeData[locale];
|
|
288
|
+
for (const location of message.locations) {
|
|
289
|
+
const existing = findTranslation(localeFile?.[location.fileId]?.[message.source], message.context);
|
|
290
|
+
if (existing === void 0 || existing === "") {
|
|
291
|
+
missing.add(messageKey);
|
|
292
|
+
isFlagged = true;
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (isFlagged) break;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return missing;
|
|
300
|
+
}
|
|
301
|
+
function buildErrorGroups(errors) {
|
|
302
|
+
const groups = /* @__PURE__ */ new Map();
|
|
303
|
+
for (const entry of errors) {
|
|
304
|
+
const key = `${entry.locale}\0${String(entry.error)}`;
|
|
305
|
+
let group = groups.get(key);
|
|
306
|
+
if (!group) {
|
|
307
|
+
group = {
|
|
308
|
+
entries: [],
|
|
309
|
+
error: entry.error,
|
|
310
|
+
locale: entry.locale
|
|
311
|
+
};
|
|
312
|
+
groups.set(key, group);
|
|
313
|
+
}
|
|
314
|
+
group.entries.push(entry);
|
|
315
|
+
}
|
|
316
|
+
return [...groups.values()];
|
|
317
|
+
}
|
|
318
|
+
function renderTranslationErrorGroup(group) {
|
|
319
|
+
const message = group.error instanceof Error ? group.error.message : String(group.error);
|
|
320
|
+
const [firstEntry] = group.entries;
|
|
321
|
+
if (!firstEntry) return `[yapyak] translation failed: ${group.locale} — ${message}`;
|
|
322
|
+
if (group.entries.length === 1) return `[yapyak] translation failed: ${firstEntry.locale} ${firstEntry.fileId} "${firstEntry.source}" — ${message}`;
|
|
323
|
+
const fileCount = new Set(group.entries.map((entry) => entry.fileId)).size;
|
|
324
|
+
const stringPart = `${group.entries.length} ${pluralize("string", group.entries.length)}`;
|
|
325
|
+
const filePart = fileCount === 1 ? `in ${firstEntry.fileId}` : `across ${fileCount} ${pluralize("file", fileCount)}`;
|
|
326
|
+
return `[yapyak] batch failed: ${group.locale} (${stringPart} ${filePart}) — ${message}`;
|
|
327
|
+
}
|
|
328
|
+
function pluralize(word, count) {
|
|
329
|
+
return count === 1 ? word : `${word}s`;
|
|
330
|
+
}
|
|
331
|
+
function formatElapsed(ms) {
|
|
332
|
+
if (ms < 1e3) return `${ms}ms`;
|
|
333
|
+
return `${(ms / 1e3).toFixed(1)}s`;
|
|
334
|
+
}
|
|
335
|
+
//#endregion
|
|
336
|
+
//#region src/plugin/sync.ts
|
|
337
|
+
function syncAll(state) {
|
|
338
|
+
const allMessages = [];
|
|
339
|
+
for (const list of state.messagesByFile.values()) allMessages.push(...list);
|
|
340
|
+
const { defaultLocale, locales } = getResolver(state).getProjectLocales();
|
|
341
|
+
emitSyncDiagnostics(state, syncLocaleFiles({
|
|
342
|
+
filter: state.filter,
|
|
343
|
+
messages: allMessages
|
|
344
|
+
}, {
|
|
345
|
+
defaultLocale,
|
|
346
|
+
locales,
|
|
347
|
+
localesDir: getNormalized(state).localesDir
|
|
348
|
+
}, state.projectRoot, { yapyakDir: state.yapyakDir }));
|
|
349
|
+
getResolver(state).invalidateData();
|
|
350
|
+
}
|
|
351
|
+
function emitSyncDiagnostics(state, result) {
|
|
352
|
+
for (const entry of result.orphaned) state.logger.warn(`[yapyak] preserved '${entry.source}' (${entry.locale}) — call site removed from ${entry.fileId}, translation saved in case it returns.`);
|
|
353
|
+
for (const entry of result.restored) state.logger.info(`[yapyak] restored '${entry.source}' (${entry.locale}) in ${entry.fileId} — translation kept from when the call site was removed earlier.`);
|
|
354
|
+
}
|
|
355
|
+
//#endregion
|
|
356
|
+
//#region src/plugin/dev-server.ts
|
|
357
|
+
function createDevServerPlugin(state) {
|
|
358
|
+
return {
|
|
359
|
+
buildEnd() {
|
|
360
|
+
for (const cancel of state.teardownCallbacks) cancel();
|
|
361
|
+
state.teardownCallbacks.length = 0;
|
|
362
|
+
},
|
|
363
|
+
configureServer(server) {
|
|
364
|
+
if (state.configFile !== void 0) server.watcher.add(state.configFile);
|
|
365
|
+
const pendingActionByFileId = /* @__PURE__ */ new Map();
|
|
366
|
+
const flush = debounce(() => {
|
|
367
|
+
if (pendingActionByFileId.size === 0) return;
|
|
368
|
+
for (const [fileId, kind] of pendingActionByFileId) {
|
|
369
|
+
if (kind === "unlink") {
|
|
370
|
+
state.extractionCache.delete(fileId);
|
|
371
|
+
state.messagesByFile.delete(fileId);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
let code;
|
|
375
|
+
try {
|
|
376
|
+
code = readFileSync(join(state.projectRoot, fileId), "utf8");
|
|
377
|
+
} catch {
|
|
378
|
+
state.extractionCache.delete(fileId);
|
|
379
|
+
state.messagesByFile.delete(fileId);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const result = resolveExtraction(state, fileId, code);
|
|
383
|
+
renderErrorDiagnostics(state.logger, result);
|
|
384
|
+
if (result.messages.length > 0) state.messagesByFile.set(fileId, result.messages);
|
|
385
|
+
else state.messagesByFile.delete(fileId);
|
|
386
|
+
}
|
|
387
|
+
pendingActionByFileId.clear();
|
|
388
|
+
syncAll(state);
|
|
389
|
+
fillStubs(state);
|
|
390
|
+
}, 50, state.logger);
|
|
391
|
+
state.teardownCallbacks.push(flush.cancel);
|
|
392
|
+
const previousLocaleData = /* @__PURE__ */ new Map();
|
|
393
|
+
const { localesDir } = getNormalized(state);
|
|
394
|
+
for (const locale of getResolver(state).getProjectLocales().locales) {
|
|
395
|
+
const initial = tryReadLocaleFile(join(state.projectRoot, localesDir, `${locale}.json`), state.logger);
|
|
396
|
+
if (initial === void 0) continue;
|
|
397
|
+
previousLocaleData.set(locale, initial);
|
|
398
|
+
}
|
|
399
|
+
const pendingLocalePaths = /* @__PURE__ */ new Set();
|
|
400
|
+
const sendLocalePatches = debounce(() => {
|
|
401
|
+
if (pendingLocalePaths.size === 0) return;
|
|
402
|
+
const allPatches = [];
|
|
403
|
+
const filesToReload = /* @__PURE__ */ new Set();
|
|
404
|
+
const skipHmrExtensions = getNormalized(state).processors.filter((processor) => processor.skipHmrCallback === true).flatMap((processor) => processor.extensions);
|
|
405
|
+
for (const localePath of pendingLocalePaths) {
|
|
406
|
+
const locale = localeFromPath(localePath);
|
|
407
|
+
const before = previousLocaleData.get(locale) ?? {};
|
|
408
|
+
const after = tryReadLocaleFile(localePath, state.logger);
|
|
409
|
+
if (after === void 0) continue;
|
|
410
|
+
previousLocaleData.set(locale, after);
|
|
411
|
+
const localePatches = buildPatches(before, after, locale);
|
|
412
|
+
for (const patch of localePatches) if (skipHmrExtensions.some((extension) => patch.fileId.endsWith(extension))) filesToReload.add(join(state.projectRoot, patch.fileId));
|
|
413
|
+
else allPatches.push(patch);
|
|
414
|
+
}
|
|
415
|
+
pendingLocalePaths.clear();
|
|
416
|
+
if (allPatches.length === 0 && filesToReload.size === 0) return;
|
|
417
|
+
getResolver(state).invalidateData();
|
|
418
|
+
for (const file of filesToReload) server.ws.send({
|
|
419
|
+
path: file,
|
|
420
|
+
type: "full-reload"
|
|
421
|
+
});
|
|
422
|
+
if (allPatches.length > 0) server.ws.send({
|
|
423
|
+
data: { patches: allPatches },
|
|
424
|
+
event: "yapyak:patch",
|
|
425
|
+
type: "custom"
|
|
426
|
+
});
|
|
427
|
+
}, 50, state.logger);
|
|
428
|
+
state.teardownCallbacks.push(sendLocalePatches.cancel);
|
|
429
|
+
const syncLocaleStructure = debounce(() => {
|
|
430
|
+
syncAll(state);
|
|
431
|
+
writeRegister(getResolver(state).getEmittedLocales().locales, state.yapyakDir);
|
|
432
|
+
}, 50, state.logger);
|
|
433
|
+
state.teardownCallbacks.push(syncLocaleStructure.cancel);
|
|
434
|
+
server.watcher.on("change", (path) => {
|
|
435
|
+
if (state.configFile !== void 0 && path === state.configFile) {
|
|
436
|
+
server.restart();
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (isLocaleFile(state, path)) {
|
|
440
|
+
pendingLocalePaths.add(path);
|
|
441
|
+
sendLocalePatches();
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
server.watcher.on("add", (path) => {
|
|
445
|
+
if (isCandidateId(path, state.filter, state.projectRoot)) {
|
|
446
|
+
pendingActionByFileId.set(toFileId(state.projectRoot, path), "add");
|
|
447
|
+
flush();
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (isLocaleFile(state, path)) {
|
|
451
|
+
const locale = localeFromPath(path);
|
|
452
|
+
const validation = validateLocaleCode(locale);
|
|
453
|
+
if (!validation.valid && validation.issue) {
|
|
454
|
+
const warning = {
|
|
455
|
+
code: locale,
|
|
456
|
+
issue: validation.issue
|
|
457
|
+
};
|
|
458
|
+
if (validation.suggestion !== void 0) warning.suggestion = validation.suggestion;
|
|
459
|
+
state.logger.warn(renderLocaleWarning(warning, getNormalized(state).localesDir));
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
getResolver(state).invalidateStructure();
|
|
463
|
+
reloadAllModules(server);
|
|
464
|
+
syncLocaleStructure();
|
|
465
|
+
const initial = tryReadLocaleFile(path, state.logger);
|
|
466
|
+
state.logger.info(renderNewLocaleMessage(locale, initial, getNormalized(state)));
|
|
467
|
+
if (initial === void 0) return;
|
|
468
|
+
previousLocaleData.set(locale, initial);
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
server.watcher.on("unlink", (path) => {
|
|
472
|
+
if (isCandidateId(path, state.filter, state.projectRoot)) {
|
|
473
|
+
pendingActionByFileId.set(toFileId(state.projectRoot, path), "unlink");
|
|
474
|
+
flush();
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
if (isLocaleFile(state, path)) {
|
|
478
|
+
const locale = localeFromPath(path);
|
|
479
|
+
previousLocaleData.delete(locale);
|
|
480
|
+
getResolver(state).invalidateStructure();
|
|
481
|
+
reloadAllModules(server);
|
|
482
|
+
syncLocaleStructure();
|
|
483
|
+
state.logger.info(`[yapyak] Locale '${locale}' removed.`);
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
},
|
|
487
|
+
async hotUpdate(options) {
|
|
488
|
+
if (!isCandidateId(options.file, state.filter, state.projectRoot)) return;
|
|
489
|
+
if (options.type === "delete") return [];
|
|
490
|
+
if (options.type === "create") return;
|
|
491
|
+
const fileId = toFileId(state.projectRoot, options.file);
|
|
492
|
+
const code = await options.read();
|
|
493
|
+
const { defaultLocale, locales } = getResolver(state).getProjectLocales();
|
|
494
|
+
const result = resolveExtraction(state, fileId, code);
|
|
495
|
+
renderErrorDiagnostics(state.logger, result);
|
|
496
|
+
const before = state.messagesByFile.get(fileId) ?? [];
|
|
497
|
+
const after = result.messages;
|
|
498
|
+
if (areMessagesEqual(before, after)) return;
|
|
499
|
+
const renames = detectRenames(before.flatMap(toCallSitePositions), after.flatMap(toCallSitePositions));
|
|
500
|
+
if (renames.length > 0 && getNormalized(state).preserveTranslationsOnRename) {
|
|
501
|
+
const migrationResult = migrateLocales({
|
|
502
|
+
extractedKeys: toExtractedKeysForFile(fileId, after),
|
|
503
|
+
fileId,
|
|
504
|
+
renames
|
|
505
|
+
}, {
|
|
506
|
+
defaultLocale,
|
|
507
|
+
locales,
|
|
508
|
+
localesDir: getNormalized(state).localesDir
|
|
509
|
+
}, state.projectRoot, { preserveTranslations: true });
|
|
510
|
+
for (const conflict of migrationResult.conflicts) state.logger.warn(`[yapyak] rename '${conflict.from}' → '${conflict.to}' skipped for '${conflict.locale}' in ${conflict.fileId} — target already has a translation.`);
|
|
511
|
+
getResolver(state).invalidateData();
|
|
512
|
+
}
|
|
513
|
+
if (after.length === 0) state.messagesByFile.delete(fileId);
|
|
514
|
+
else state.messagesByFile.set(fileId, after);
|
|
515
|
+
syncAll(state);
|
|
516
|
+
fillStubs(state);
|
|
517
|
+
},
|
|
518
|
+
name: "yapyak:dev-server"
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
function reloadAllModules(server) {
|
|
522
|
+
server.moduleGraph.invalidateAll();
|
|
523
|
+
server.ws.send({ type: "full-reload" });
|
|
524
|
+
}
|
|
525
|
+
function tryReadLocaleFile(path, logger) {
|
|
526
|
+
try {
|
|
527
|
+
return readLocaleFile(path);
|
|
528
|
+
} catch (error) {
|
|
529
|
+
if (error instanceof CorruptLocaleFileError) {
|
|
530
|
+
logger.warn(`${error.message}\nSee ${getDocsUrl(YAP_RUNTIME.CATALOG_LOCALE_FILE_CORRUPT.code)}`);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
534
|
+
logger.warn(`${YAP_RUNTIME.CATALOG_LOCALE_FILE_UNREADABLE.message({
|
|
535
|
+
path,
|
|
536
|
+
reason
|
|
537
|
+
})}\nSee ${getDocsUrl(YAP_RUNTIME.CATALOG_LOCALE_FILE_UNREADABLE.code)}`);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function localeFromPath(path) {
|
|
542
|
+
const base = basename(path);
|
|
543
|
+
return base.slice(0, -extname(base).length);
|
|
544
|
+
}
|
|
545
|
+
function renderNewLocaleMessage(locale, localeFile, config) {
|
|
546
|
+
const detected = `[yapyak] New locale '${locale}' detected.`;
|
|
547
|
+
if (localeFile !== void 0 && isTranslated(localeFile)) return detected;
|
|
548
|
+
if (config.translator) return `${detected} \`${runYapyakCommand(`translate ${locale}`)}\` fills anything untranslated.`;
|
|
549
|
+
return `${detected} Fill in ${config.localesDir}/${locale}.json.`;
|
|
550
|
+
}
|
|
551
|
+
function isTranslated(localeFile) {
|
|
552
|
+
let hasTranslations = false;
|
|
553
|
+
for (const entries of Object.values(localeFile)) for (const entry of Object.values(entries)) for (const { value } of toVariants(entry)) {
|
|
554
|
+
if (value === "") return false;
|
|
555
|
+
hasTranslations = true;
|
|
556
|
+
}
|
|
557
|
+
return hasTranslations;
|
|
558
|
+
}
|
|
559
|
+
function buildPatches(before, after, locale) {
|
|
560
|
+
const patches = [];
|
|
561
|
+
const fileIds = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
562
|
+
for (const fileId of fileIds) {
|
|
563
|
+
const beforeEntries = before[fileId] ?? {};
|
|
564
|
+
const afterEntries = after[fileId] ?? {};
|
|
565
|
+
const sources = /* @__PURE__ */ new Set([...Object.keys(beforeEntries), ...Object.keys(afterEntries)]);
|
|
566
|
+
for (const source of sources) {
|
|
567
|
+
const beforeEntry = beforeEntries[source];
|
|
568
|
+
const afterEntry = afterEntries[source];
|
|
569
|
+
walkEntry(patches, fileId, source, locale, beforeEntry, afterEntry);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return patches;
|
|
573
|
+
}
|
|
574
|
+
function walkEntry(patches, fileId, source, locale, beforeEntry, afterEntry) {
|
|
575
|
+
if (typeof afterEntry === "string") {
|
|
576
|
+
if (beforeEntry && typeof beforeEntry === "object") for (const context of Object.keys(beforeEntry)) patches.push({
|
|
577
|
+
fileId,
|
|
578
|
+
id: toMessageKey(source, context),
|
|
579
|
+
locale,
|
|
580
|
+
value: ""
|
|
581
|
+
});
|
|
582
|
+
if (typeof beforeEntry !== "string" || beforeEntry !== afterEntry) patches.push({
|
|
583
|
+
fileId,
|
|
584
|
+
id: toMessageKey(source),
|
|
585
|
+
locale,
|
|
586
|
+
value: parseLocaleValue(afterEntry)
|
|
587
|
+
});
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (afterEntry && typeof afterEntry === "object") {
|
|
591
|
+
if (typeof beforeEntry === "string") patches.push({
|
|
592
|
+
fileId,
|
|
593
|
+
id: toMessageKey(source),
|
|
594
|
+
locale,
|
|
595
|
+
value: ""
|
|
596
|
+
});
|
|
597
|
+
const beforeMap = beforeEntry && typeof beforeEntry === "object" ? beforeEntry : {};
|
|
598
|
+
const contexts = /* @__PURE__ */ new Set([...Object.keys(beforeMap), ...Object.keys(afterEntry)]);
|
|
599
|
+
for (const context of contexts) {
|
|
600
|
+
const beforeValue = beforeMap[context];
|
|
601
|
+
const afterValue = afterEntry[context];
|
|
602
|
+
if (typeof afterValue === "string") {
|
|
603
|
+
if (beforeValue !== afterValue) patches.push({
|
|
604
|
+
fileId,
|
|
605
|
+
id: toMessageKey(source, context),
|
|
606
|
+
locale,
|
|
607
|
+
value: parseLocaleValue(afterValue)
|
|
608
|
+
});
|
|
609
|
+
} else if (afterValue === void 0 && typeof beforeValue === "string") patches.push({
|
|
610
|
+
fileId,
|
|
611
|
+
id: toMessageKey(source, context),
|
|
612
|
+
locale,
|
|
613
|
+
value: ""
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (typeof beforeEntry === "string") patches.push({
|
|
619
|
+
fileId,
|
|
620
|
+
id: toMessageKey(source),
|
|
621
|
+
locale,
|
|
622
|
+
value: ""
|
|
623
|
+
});
|
|
624
|
+
if (beforeEntry && typeof beforeEntry === "object") for (const context of Object.keys(beforeEntry)) patches.push({
|
|
625
|
+
fileId,
|
|
626
|
+
id: toMessageKey(source, context),
|
|
627
|
+
locale,
|
|
628
|
+
value: ""
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
function parseLocaleValue(raw) {
|
|
632
|
+
const { template } = parseTemplate(raw);
|
|
633
|
+
if (template.length === 0) return "";
|
|
634
|
+
if (template.length === 1 && template[0]?.kind === "literal") return template[0].value;
|
|
635
|
+
return template;
|
|
636
|
+
}
|
|
637
|
+
function toCallSitePositions(message) {
|
|
638
|
+
return message.locations.map((location) => ({
|
|
639
|
+
column: location.range.start.column,
|
|
640
|
+
line: location.range.start.line,
|
|
641
|
+
source: message.source
|
|
642
|
+
}));
|
|
643
|
+
}
|
|
644
|
+
function toExtractedKeysForFile(fileId, messages) {
|
|
645
|
+
const keys = /* @__PURE__ */ new Set();
|
|
646
|
+
for (const message of messages) keys.add(toMessageKey(message.source, message.context));
|
|
647
|
+
return { [fileId]: keys };
|
|
648
|
+
}
|
|
649
|
+
function areMessagesEqual(a, b) {
|
|
650
|
+
if (a.length !== b.length) return false;
|
|
651
|
+
for (let index = 0; index < a.length; index++) {
|
|
652
|
+
const left = a[index];
|
|
653
|
+
const right = b[index];
|
|
654
|
+
if (!left || !right) return false;
|
|
655
|
+
if (left.id !== right.id || left.locations.length !== right.locations.length) return false;
|
|
656
|
+
for (let locationIndex = 0; locationIndex < left.locations.length; locationIndex++) {
|
|
657
|
+
const leftLocation = left.locations[locationIndex];
|
|
658
|
+
const rightLocation = right.locations[locationIndex];
|
|
659
|
+
if (!leftLocation || !rightLocation) return false;
|
|
660
|
+
if (leftLocation.range.start.line !== rightLocation.range.start.line || leftLocation.range.start.column !== rightLocation.range.start.column) return false;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
return true;
|
|
664
|
+
}
|
|
665
|
+
function debounce(fn, milliseconds, logger) {
|
|
666
|
+
let timer;
|
|
667
|
+
const debounced = (() => {
|
|
668
|
+
if (timer) clearTimeout(timer);
|
|
669
|
+
timer = setTimeout(() => {
|
|
670
|
+
try {
|
|
671
|
+
fn();
|
|
672
|
+
} catch (error) {
|
|
673
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
674
|
+
logger.error(`[yapyak] ${message}`);
|
|
675
|
+
}
|
|
676
|
+
}, milliseconds);
|
|
677
|
+
});
|
|
678
|
+
debounced.cancel = () => {
|
|
679
|
+
if (timer) {
|
|
680
|
+
clearTimeout(timer);
|
|
681
|
+
timer = void 0;
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
return debounced;
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/plugin/scan.ts
|
|
688
|
+
function createScanPlugin(state) {
|
|
689
|
+
return {
|
|
690
|
+
buildStart() {
|
|
691
|
+
if (state.command === "build") return;
|
|
692
|
+
scanAllSources(state);
|
|
693
|
+
fillStubs(state);
|
|
694
|
+
},
|
|
695
|
+
name: "yapyak:scan"
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
function scanAllSources(state) {
|
|
699
|
+
const files = walkSourceFiles(state.filter, state.projectRoot);
|
|
700
|
+
state.messagesByFile.clear();
|
|
701
|
+
for (const file of files) {
|
|
702
|
+
const result = resolveExtraction(state, file.fileId, file.code);
|
|
703
|
+
renderErrorDiagnostics(state.logger, result);
|
|
704
|
+
if (result.messages.length > 0) state.messagesByFile.set(file.fileId, result.messages);
|
|
705
|
+
}
|
|
706
|
+
syncAll(state);
|
|
707
|
+
}
|
|
708
|
+
//#endregion
|
|
709
|
+
//#region src/plugin/transform.ts
|
|
710
|
+
function createTransformPlugin(state) {
|
|
711
|
+
return {
|
|
712
|
+
enforce: "pre",
|
|
713
|
+
name: "yapyak:transform",
|
|
714
|
+
transform(code, id) {
|
|
715
|
+
if (id.startsWith("\0")) return null;
|
|
716
|
+
if (VITE_NON_CODE_QUERY_RX.test(id)) return null;
|
|
717
|
+
const queryStart = id.indexOf("?");
|
|
718
|
+
const filePath = queryStart === -1 ? id : id.slice(0, queryStart);
|
|
719
|
+
if (!isCandidateId(filePath, state.filter, state.projectRoot)) return null;
|
|
720
|
+
const fileId = toFileId(state.projectRoot, filePath);
|
|
721
|
+
const { locales } = getResolver(state).getEmittedLocales();
|
|
722
|
+
const extracted = resolveExtraction(state, fileId, code);
|
|
723
|
+
const errorDiagnostics = renderErrorDiagnostics(state.logger, extracted);
|
|
724
|
+
const firstError = errorDiagnostics[0];
|
|
725
|
+
if (firstError !== void 0) {
|
|
726
|
+
for (let index = 1; index < errorDiagnostics.length; index += 1) {
|
|
727
|
+
const subsequent = errorDiagnostics[index];
|
|
728
|
+
if (subsequent !== void 0) state.logger.error(formatDiagnostic(subsequent));
|
|
729
|
+
}
|
|
730
|
+
this.error({
|
|
731
|
+
code: firstError.code,
|
|
732
|
+
id: firstError.fileId,
|
|
733
|
+
loc: {
|
|
734
|
+
column: firstError.range.start.column,
|
|
735
|
+
file: firstError.fileId,
|
|
736
|
+
line: firstError.range.start.line
|
|
737
|
+
},
|
|
738
|
+
message: `${firstError.message}\nSee ${getDocsUrl(firstError.code)}`
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
if (extracted.callSites.length === 0) return null;
|
|
742
|
+
const translations = buildTranslations({
|
|
743
|
+
extracted,
|
|
744
|
+
fileId,
|
|
745
|
+
localeData: getResolver(state).getLocaleData(),
|
|
746
|
+
locales
|
|
747
|
+
});
|
|
748
|
+
const result = transformFile({
|
|
749
|
+
defaultLocale: getResolver(state).getProjectLocales().defaultLocale,
|
|
750
|
+
dev: state.command === "serve",
|
|
751
|
+
extracted,
|
|
752
|
+
fileId,
|
|
753
|
+
locales,
|
|
754
|
+
processors: getNormalized(state).processors,
|
|
755
|
+
source: code,
|
|
756
|
+
sourcePath: filePath,
|
|
757
|
+
translations
|
|
758
|
+
});
|
|
759
|
+
if (result.code === code) return null;
|
|
760
|
+
if (state.command === "build") {
|
|
761
|
+
const localesDir = join(state.projectRoot, getNormalized(state).localesDir);
|
|
762
|
+
for (const locale of getResolver(state).getProjectLocales().locales) this.addWatchFile(join(localesDir, `${locale}.json`));
|
|
763
|
+
}
|
|
764
|
+
return {
|
|
765
|
+
code: result.code,
|
|
766
|
+
map: result.map
|
|
767
|
+
};
|
|
768
|
+
},
|
|
769
|
+
watchChange(id, change) {
|
|
770
|
+
if (state.command !== "build") return;
|
|
771
|
+
if (!isLocaleFile(state, id)) return;
|
|
772
|
+
if (change.event === "update") {
|
|
773
|
+
getResolver(state).invalidateData();
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
getResolver(state).invalidateStructure();
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
const VITE_NON_CODE_QUERY_RX = /\?(?:raw|url|inline|worker|sharedworker|init)\b/;
|
|
781
|
+
function buildTranslations(input) {
|
|
782
|
+
const translations = {};
|
|
783
|
+
for (const message of input.extracted.messages) for (const locale of input.locales) {
|
|
784
|
+
const value = findTranslation(input.localeData[locale]?.[input.fileId]?.[message.source], message.context);
|
|
785
|
+
if (value === void 0 || value === "") continue;
|
|
786
|
+
let localeMap = translations[locale];
|
|
787
|
+
if (!localeMap) {
|
|
788
|
+
localeMap = {};
|
|
789
|
+
translations[locale] = localeMap;
|
|
790
|
+
}
|
|
791
|
+
localeMap[message.id] = value;
|
|
792
|
+
}
|
|
793
|
+
return translations;
|
|
794
|
+
}
|
|
795
|
+
//#endregion
|
|
796
|
+
//#region src/plugin/virtual-module.ts
|
|
797
|
+
function createVirtualModulePlugin(state) {
|
|
798
|
+
return {
|
|
799
|
+
enforce: "pre",
|
|
800
|
+
load(id) {
|
|
801
|
+
if (id === "\0yapyak:runtime") {
|
|
802
|
+
const normalized = getNormalized(state);
|
|
803
|
+
const emitted = getResolver(state).getEmittedLocales();
|
|
804
|
+
return defineRuntime({
|
|
805
|
+
defaultLocale: emitted.defaultLocale,
|
|
806
|
+
detectUserLocale: normalized.detectUserLocale,
|
|
807
|
+
locales: emitted.locales,
|
|
808
|
+
persistence: normalized.persistence,
|
|
809
|
+
syncHtmlLang: normalized.syncHtmlLang
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
return null;
|
|
813
|
+
},
|
|
814
|
+
name: "yapyak:virtual-module",
|
|
815
|
+
resolveId(id) {
|
|
816
|
+
if (id === "yapyak/runtime") return RUNTIME_RESOLVED;
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
//#endregion
|
|
822
|
+
//#region src/plugin.ts
|
|
823
|
+
/**
|
|
824
|
+
* Creates the yapyak Vite plugin.
|
|
825
|
+
*
|
|
826
|
+
* @remarks
|
|
827
|
+
* Configuration is read from `yapyak.config.{ts,mts,mjs,js}` in the project root.
|
|
828
|
+
*
|
|
829
|
+
* @param options - The options.
|
|
830
|
+
*
|
|
831
|
+
* @example
|
|
832
|
+
* ```ts [vite.config.ts]
|
|
833
|
+
* import { yapyak } from '@yapyak/vite';
|
|
834
|
+
* import { defineConfig } from 'vite';
|
|
835
|
+
*
|
|
836
|
+
* export default defineConfig({
|
|
837
|
+
* plugins: [yapyak()]
|
|
838
|
+
* });
|
|
839
|
+
* ```
|
|
840
|
+
*
|
|
841
|
+
* @example Lock the build to a single locale
|
|
842
|
+
* ```ts [vite.config.ts]
|
|
843
|
+
* import { yapyak } from '@yapyak/vite';
|
|
844
|
+
* import { defineConfig } from 'vite';
|
|
845
|
+
*
|
|
846
|
+
* export default defineConfig({
|
|
847
|
+
* plugins: [yapyak({ fixedLocale: process.env.YAPYAK_LOCALE })]
|
|
848
|
+
* });
|
|
849
|
+
* ```
|
|
850
|
+
*/
|
|
851
|
+
function yapyak(options = {}) {
|
|
852
|
+
const state = createState({ fixedLocale: options.fixedLocale });
|
|
853
|
+
return [
|
|
854
|
+
createConfigPlugin(state),
|
|
855
|
+
createVirtualModulePlugin(state),
|
|
856
|
+
createScanPlugin(state),
|
|
857
|
+
createTransformPlugin(state),
|
|
858
|
+
createDevServerPlugin(state)
|
|
859
|
+
];
|
|
860
|
+
}
|
|
861
|
+
//#endregion
|
|
862
|
+
export { yapyak };
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@yapyak/vite",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Vite plugin for yapyak.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"i18n",
|
|
7
|
+
"plugin",
|
|
8
|
+
"translation",
|
|
9
|
+
"vite",
|
|
10
|
+
"yapyak"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://yapyak.dev",
|
|
13
|
+
"bugs": "https://github.com/yapyak/yapyak/issues",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/yapyak/yapyak.git",
|
|
17
|
+
"directory": "packages/vite"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"author": "Joakim Uhrwing",
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"type": "module",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist"
|
|
31
|
+
],
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/node": "26.1.1",
|
|
34
|
+
"tsdown": "0.22.12",
|
|
35
|
+
"typescript": "6.0.3",
|
|
36
|
+
"vite": "8.1.5",
|
|
37
|
+
"vitest": "4.1.10",
|
|
38
|
+
"@yapyak/tsdown-config": "0.0.0",
|
|
39
|
+
"@yapyak/typescript-config": "0.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"vite": ">=8",
|
|
43
|
+
"yapyak": "0.0.1"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22.22"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsdown",
|
|
53
|
+
"test": "pnpm -w vitest --run --project=@yapyak/vite",
|
|
54
|
+
"typecheck": "tsc --noEmit"
|
|
55
|
+
}
|
|
56
|
+
}
|