@yapyak/vite 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -47,6 +47,6 @@ type YapyakOptions = {
47
47
  * });
48
48
  * ```
49
49
  */
50
- declare function yapyak(options?: YapyakOptions): Plugin[];
50
+ export declare function yapyak(options?: YapyakOptions): Plugin[];
51
51
  //#endregion
52
- export { type YapyakOptions, yapyak };
52
+ export type { YapyakOptions };
package/dist/index.js CHANGED
@@ -1,29 +1,113 @@
1
- import { CorruptLocaleFileError, YAP_COMPILE, YAP_RUNTIME, autoTranslate, detectRenames, discoverLocales, extractFile, findTranslation, getDocsUrl, migrateLocales, readLocaleData, readLocaleFile, syncLocaleFiles, toMessageKey, toVariants, transformFile, validateLocaleCode, walkSourceFiles, writeRegister } from "yapyak/compiler/internal";
2
- import { createFilter, defineRuntime, loadYapyakConfig } from "yapyak/config/internal";
3
1
  import { basename, extname, join, relative, resolve, sep } from "node:path";
2
+ import { CorruptLocaleFileError, YAP_COMPILE, YAP_RUNTIME, autoTranslate, detectRenames, discoverLocales, extractFile, findTranslation, getDocsUrl, migrateLocales, readLocaleData, readLocaleFile, resolveProcessor, syncLocaleFiles, toMessageKey, toVariants, transformFile, validateLocaleCode, walkSourceFiles, writeRegister } from "yapyak/compiler/internal";
3
+ import { createFilter, defineRuntime, loadYapyakConfig } from "yapyak/config/internal";
4
4
  import { buildPatches } from "yapyak/internal";
5
5
  import { readFileSync } from "node:fs";
6
+ //#region src/plugin/file-id.ts
7
+ function toFileId(projectRoot, id) {
8
+ const path = id.split("?")[0] ?? id;
9
+ return relative(projectRoot, path).replaceAll("\\", "/");
10
+ }
11
+ //#endregion
12
+ //#region src/plugin/candidate-id.ts
13
+ function isCandidateId(id, filter, projectRoot) {
14
+ if (id.startsWith("\0")) return false;
15
+ return filter(toFileId(projectRoot, id));
16
+ }
17
+ //#endregion
18
+ //#region src/plugin/state.ts
19
+ function createState(options = {}) {
20
+ return {
21
+ command: "serve",
22
+ extractionCache: /* @__PURE__ */ new Map(),
23
+ filter: () => false,
24
+ ...options.fixedLocale !== void 0 && { fixedLocale: options.fixedLocale },
25
+ logger: createConsoleLogger(),
26
+ messagesByFile: /* @__PURE__ */ new Map(),
27
+ projectRoot: options.root === void 0 ? process.cwd() : resolve(options.root),
28
+ ...options.root !== void 0 && { rootOverride: resolve(options.root) },
29
+ teardownCallbacks: [],
30
+ yapyakDir: ""
31
+ };
32
+ }
33
+ function getNormalized(state) {
34
+ if (state.normalized === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
35
+ return state.normalized;
36
+ }
37
+ function getResolver(state) {
38
+ if (state.resolver === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
39
+ return state.resolver;
40
+ }
41
+ function createConsoleLogger() {
42
+ const noop = () => void 0;
43
+ return {
44
+ clearScreen: noop,
45
+ error: (message) => {
46
+ console.error(message);
47
+ },
48
+ hasErrorLogged: () => false,
49
+ hasWarned: false,
50
+ info: (message) => {
51
+ console.log(message);
52
+ },
53
+ warn: (message) => {
54
+ console.warn(message);
55
+ },
56
+ warnOnce: (message) => {
57
+ console.warn(message);
58
+ }
59
+ };
60
+ }
61
+ //#endregion
62
+ //#region src/plugin/compiler-runtime.ts
63
+ function createCompilerRuntimePlugin(state) {
64
+ return {
65
+ enforce: "pre",
66
+ name: "yapyak:compiler-runtime",
67
+ async resolveId(source, importer) {
68
+ const compilerRuntime = findCompilerRuntime(getNormalized(state).processors, source);
69
+ if (compilerRuntime === void 0 || importer === void 0 || !isCandidateId(importer, state.filter, state.projectRoot)) return null;
70
+ const resolved = await this.resolve(compilerRuntime.module, importer, { skipSelf: true });
71
+ if (resolved === null || resolved.id === importer) return null;
72
+ return resolved.id;
73
+ }
74
+ };
75
+ }
76
+ function findCompilerRuntime(processors, source) {
77
+ for (const processor of processors) {
78
+ const compilerRuntime = processor.runtime?.compilerRuntime;
79
+ if (compilerRuntime?.specifiers.includes(source)) return compilerRuntime;
80
+ }
81
+ }
82
+ //#endregion
6
83
  //#region src/locale-resolver.ts
7
- function createLocaleResolver(context, projectRoot, options) {
84
+ function createLocaleResolver(config, projectRoot, options) {
8
85
  const fixedLocale = options?.fixedLocale;
9
86
  let discovery;
10
87
  let emitted;
11
88
  let localeData;
12
89
  function getDiscovery() {
13
- if (discovery === void 0) discovery = discoverLocales(context.localesDir, projectRoot, { defaultLocale: context.defaultLocale });
90
+ if (discovery === void 0) discovery = discoverLocales(config.localesDir, projectRoot, {
91
+ defaultLocale: config.defaultLocale,
92
+ sourceLocale: config.sourceLocale
93
+ });
14
94
  return discovery;
15
95
  }
16
96
  function getProjectLocales() {
17
97
  const result = getDiscovery();
18
98
  return {
19
99
  defaultLocale: result.defaultLocale,
20
- locales: result.locales
100
+ locales: result.locales,
101
+ sourceLocale: result.sourceLocale
21
102
  };
22
103
  }
23
104
  function getEmittedLocales() {
24
105
  if (emitted === void 0) {
25
106
  const project = getProjectLocales();
26
- emitted = fixedLocale === void 0 ? project : {
107
+ emitted = fixedLocale === void 0 ? {
108
+ defaultLocale: project.defaultLocale,
109
+ locales: project.locales
110
+ } : {
27
111
  defaultLocale: fixedLocale,
28
112
  locales: [fixedLocale]
29
113
  };
@@ -33,7 +117,7 @@ function createLocaleResolver(context, projectRoot, options) {
33
117
  function getLocaleData() {
34
118
  if (localeData === void 0) localeData = readLocaleData({
35
119
  locales: getEmittedLocales().locales,
36
- localesDir: context.localesDir
120
+ localesDir: config.localesDir
37
121
  }, projectRoot);
38
122
  return localeData;
39
123
  }
@@ -102,7 +186,8 @@ function createConfigPlugin(state) {
102
186
  }
103
187
  state.resolver = createLocaleResolver({
104
188
  defaultLocale: result.config.defaultLocale,
105
- localesDir: result.config.localesDir
189
+ localesDir: result.config.localesDir,
190
+ sourceLocale: result.config.sourceLocale
106
191
  }, state.projectRoot, { fixedLocale: state.fixedLocale });
107
192
  const discovery = state.resolver.getDiscovery();
108
193
  for (const warning of discovery.warnings) state.logger.warn(renderLocaleWarning(warning, result.config.localesDir));
@@ -126,22 +211,11 @@ function toRuntimeModules(processors) {
126
211
  for (const processor of processors) {
127
212
  if (processor.runtime === void 0) continue;
128
213
  modules.push(processor.runtime.module);
214
+ if (processor.runtime.compilerRuntime !== void 0) modules.push(processor.runtime.compilerRuntime.module);
129
215
  }
130
216
  return modules;
131
217
  }
132
218
  //#endregion
133
- //#region src/plugin/file-id.ts
134
- function toFileId(projectRoot, id) {
135
- const path = id.split("?")[0] ?? id;
136
- return relative(projectRoot, path).replaceAll("\\", "/");
137
- }
138
- //#endregion
139
- //#region src/plugin/candidate-id.ts
140
- function isCandidateId(id, filter, projectRoot) {
141
- if (id.startsWith("\0")) return false;
142
- return filter(toFileId(projectRoot, id));
143
- }
144
- //#endregion
145
219
  //#region src/plugin/error-diagnostic.ts
146
220
  function renderErrorDiagnostics(logger, result) {
147
221
  const errors = [];
@@ -163,50 +237,6 @@ function formatDiagnostic(diagnostic) {
163
237
  return `[yapyak] ${diagnostic.code} ${location}: ${diagnostic.message}\nSee ${getDocsUrl(diagnostic.code)}`;
164
238
  }
165
239
  //#endregion
166
- //#region src/plugin/state.ts
167
- function createState(options = {}) {
168
- return {
169
- command: "serve",
170
- extractionCache: /* @__PURE__ */ new Map(),
171
- filter: () => false,
172
- ...options.fixedLocale !== void 0 && { fixedLocale: options.fixedLocale },
173
- logger: createConsoleLogger(),
174
- messagesByFile: /* @__PURE__ */ new Map(),
175
- projectRoot: options.root === void 0 ? process.cwd() : resolve(options.root),
176
- ...options.root !== void 0 && { rootOverride: resolve(options.root) },
177
- teardownCallbacks: [],
178
- yapyakDir: ""
179
- };
180
- }
181
- function getNormalized(state) {
182
- if (state.normalized === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
183
- return state.normalized;
184
- }
185
- function getResolver(state) {
186
- if (state.resolver === void 0) throw new Error("[yapyak] plugin used before configResolved — config is not loaded yet.");
187
- return state.resolver;
188
- }
189
- function createConsoleLogger() {
190
- const noop = () => void 0;
191
- return {
192
- clearScreen: noop,
193
- error: (message) => {
194
- console.error(message);
195
- },
196
- hasErrorLogged: () => false,
197
- hasWarned: false,
198
- info: (message) => {
199
- console.log(message);
200
- },
201
- warn: (message) => {
202
- console.warn(message);
203
- },
204
- warnOnce: (message) => {
205
- console.warn(message);
206
- }
207
- };
208
- }
209
- //#endregion
210
240
  //#region src/plugin/extraction.ts
211
241
  function resolveExtraction(state, fileId, source) {
212
242
  const { processors } = getNormalized(state);
@@ -262,25 +292,25 @@ function fillStubs(state) {
262
292
  const allMessages = [];
263
293
  for (const list of state.messagesByFile.values()) allMessages.push(...list);
264
294
  if (allMessages.length === 0) return;
265
- const { defaultLocale, locales } = getResolver(state).getProjectLocales();
295
+ const { locales, sourceLocale } = getResolver(state).getProjectLocales();
266
296
  const translatableLocales = locales.filter((locale) => validateLocaleCode(locale).valid);
267
- const missing = discoverMissingMessageKeys(allMessages, translatableLocales, defaultLocale, getResolver(state).getLocaleData());
297
+ const missing = discoverMissingMessageKeys(allMessages, translatableLocales, sourceLocale, getResolver(state).getLocaleData());
268
298
  if (missing.size === 0) return;
269
299
  if (missing.size > config.autoTranslateThreshold) {
270
300
  state.logger.info(`[yapyak] ${missing.size} new strings detected. Run \`${runYapyakCommand("translate")}\` to fill.`);
271
301
  return;
272
302
  }
273
303
  const filtered = allMessages.filter((message) => missing.has(toMessageKey(message.source, message.context)));
274
- const targetLocaleCount = translatableLocales.filter((locale) => locale !== defaultLocale).length;
304
+ const targetLocaleCount = translatableLocales.filter((locale) => locale !== sourceLocale).length;
275
305
  const startedAt = Date.now();
276
306
  state.logger.info(`[yapyak] translating ${filtered.length} ${pluralize("string", filtered.length)} × ${targetLocaleCount} ${pluralize("locale", targetLocaleCount)} via ${translator.id}…`);
277
307
  const controller = new AbortController();
278
308
  state.autoTranslateController = controller;
279
309
  runAutoTranslate(state, {
280
- defaultLocale,
281
310
  filtered,
282
311
  locales,
283
312
  signal: controller.signal,
313
+ sourceLocale,
284
314
  startedAt,
285
315
  translator
286
316
  });
@@ -292,9 +322,9 @@ async function runAutoTranslate(state, input) {
292
322
  messages: input.filtered,
293
323
  translator: input.translator
294
324
  }, {
295
- defaultLocale: input.defaultLocale,
296
325
  locales: input.locales,
297
- localesDir: config.localesDir
326
+ localesDir: config.localesDir,
327
+ sourceLocale: input.sourceLocale
298
328
  }, state.projectRoot, {
299
329
  signal: input.signal,
300
330
  yapyakDir: state.yapyakDir
@@ -311,14 +341,14 @@ async function runAutoTranslate(state, input) {
311
341
  state.logger.warn(`[yapyak] auto-translate error · ${elapsed} · ${String(error)}`);
312
342
  }
313
343
  }
314
- function discoverMissingMessageKeys(messages, locales, defaultLocale, localeData) {
344
+ function discoverMissingMessageKeys(messages, locales, sourceLocale, localeData) {
315
345
  const missing = /* @__PURE__ */ new Set();
316
346
  for (const message of messages) {
317
347
  const messageKey = toMessageKey(message.source, message.context);
318
348
  if (missing.has(messageKey)) continue;
319
349
  let isFlagged = false;
320
350
  for (const locale of locales) {
321
- if (locale === defaultLocale) continue;
351
+ if (locale === sourceLocale) continue;
322
352
  const localeFile = localeData[locale];
323
353
  for (const location of message.locations) {
324
354
  const existing = findTranslation(localeFile?.[location.fileId]?.[message.source], message.context);
@@ -372,14 +402,14 @@ function formatElapsed(ms) {
372
402
  function syncAll(state) {
373
403
  const allMessages = [];
374
404
  for (const list of state.messagesByFile.values()) allMessages.push(...list);
375
- const { defaultLocale, locales } = getResolver(state).getProjectLocales();
405
+ const { locales, sourceLocale } = getResolver(state).getProjectLocales();
376
406
  emitSyncDiagnostics(state, syncLocaleFiles({
377
407
  filter: state.filter,
378
408
  messages: allMessages
379
409
  }, {
380
- defaultLocale,
381
410
  locales,
382
- localesDir: getNormalized(state).localesDir
411
+ localesDir: getNormalized(state).localesDir,
412
+ sourceLocale
383
413
  }, state.projectRoot, { yapyakDir: state.yapyakDir }));
384
414
  getResolver(state).invalidateData();
385
415
  }
@@ -532,7 +562,7 @@ function createDevServerPlugin(state) {
532
562
  if (options.type === "create") return;
533
563
  const fileId = toFileId(state.projectRoot, options.file);
534
564
  const code = await options.read();
535
- const { defaultLocale, locales } = getResolver(state).getProjectLocales();
565
+ const { locales, sourceLocale } = getResolver(state).getProjectLocales();
536
566
  const result = resolveExtraction(state, fileId, code);
537
567
  renderErrorDiagnostics(state.logger, result);
538
568
  if (hasParseFailure(result)) return;
@@ -546,9 +576,9 @@ function createDevServerPlugin(state) {
546
576
  fileId,
547
577
  renames
548
578
  }, {
549
- defaultLocale,
550
579
  locales,
551
- localesDir: getNormalized(state).localesDir
580
+ localesDir: getNormalized(state).localesDir,
581
+ sourceLocale
552
582
  }, state.projectRoot, { preserveTranslations: true });
553
583
  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.`);
554
584
  getResolver(state).invalidateData();
@@ -688,67 +718,70 @@ function createTransformPlugin(state) {
688
718
  return {
689
719
  enforce: "pre",
690
720
  name: "yapyak:transform",
691
- transform(code, id) {
692
- if (id.startsWith("\0")) return null;
693
- if (VITE_NON_CODE_QUERY_RX.test(id)) return null;
694
- const queryStart = id.indexOf("?");
695
- const filePath = queryStart === -1 ? id : id.slice(0, queryStart);
696
- if (!isCandidateId(filePath, state.filter, state.projectRoot)) return null;
697
- const fileId = toFileId(state.projectRoot, filePath);
698
- const { locales } = getResolver(state).getEmittedLocales();
699
- const extracted = resolveExtraction(state, fileId, code);
700
- const errorDiagnostics = renderErrorDiagnostics(state.logger, extracted);
701
- const firstError = errorDiagnostics[0];
702
- if (firstError !== void 0) {
703
- for (let index = 1; index < errorDiagnostics.length; index += 1) {
704
- const subsequent = errorDiagnostics[index];
705
- if (subsequent !== void 0) state.logger.error(formatDiagnostic(subsequent));
721
+ transform: {
722
+ handler(code, id) {
723
+ if (id.startsWith("\0")) return null;
724
+ if (VITE_NON_CODE_QUERY_RX.test(id)) return null;
725
+ const queryStart = id.indexOf("?");
726
+ const filePath = queryStart === -1 ? id : id.slice(0, queryStart);
727
+ if (!isCandidateId(filePath, state.filter, state.projectRoot)) return null;
728
+ const fileId = toFileId(state.projectRoot, filePath);
729
+ const { locales } = getResolver(state).getEmittedLocales();
730
+ const extracted = resolveExtraction(state, fileId, code);
731
+ const errorDiagnostics = renderErrorDiagnostics(state.logger, extracted);
732
+ const firstError = errorDiagnostics[0];
733
+ if (firstError !== void 0) {
734
+ for (let index = 1; index < errorDiagnostics.length; index += 1) {
735
+ const subsequent = errorDiagnostics[index];
736
+ if (subsequent !== void 0) state.logger.error(formatDiagnostic(subsequent));
737
+ }
738
+ this.error({
739
+ code: firstError.code,
740
+ id: firstError.fileId,
741
+ loc: {
742
+ column: firstError.range.start.column,
743
+ file: firstError.fileId,
744
+ line: firstError.range.start.line
745
+ },
746
+ message: `${firstError.message}\nSee ${getDocsUrl(firstError.code)}`
747
+ });
706
748
  }
707
- this.error({
708
- code: firstError.code,
709
- id: firstError.fileId,
710
- loc: {
711
- column: firstError.range.start.column,
712
- file: firstError.fileId,
713
- line: firstError.range.start.line
714
- },
715
- message: `${firstError.message}\nSee ${getDocsUrl(firstError.code)}`
749
+ if (extracted.callSites.length === 0 && resolveProcessor(fileId, code, getNormalized(state).processors).runtime?.componentHook === void 0) return null;
750
+ const translations = buildTranslations({
751
+ extracted,
752
+ fileId,
753
+ localeData: getResolver(state).getLocaleData(),
754
+ locales
716
755
  });
717
- }
718
- if (extracted.callSites.length === 0) return null;
719
- const translations = buildTranslations({
720
- extracted,
721
- fileId,
722
- localeData: getResolver(state).getLocaleData(),
723
- locales
724
- });
725
- let localeFilePaths;
726
- if (state.command === "serve" && this.environment.config.consumer === "server") {
727
- const localesDir = join(state.projectRoot, getNormalized(state).localesDir);
728
- localeFilePaths = {};
729
- for (const locale of locales) localeFilePaths[locale] = join(localesDir, `${locale}.json`);
730
- }
731
- const result = transformFile({
732
- defaultLocale: getResolver(state).getProjectLocales().defaultLocale,
733
- dev: state.command === "serve",
734
- extracted,
735
- fileId,
736
- localeFilePaths,
737
- locales,
738
- processors: getNormalized(state).processors,
739
- source: code,
740
- sourcePath: filePath,
741
- translations
742
- });
743
- if (result.code === code) return null;
744
- if (state.command === "build") {
745
- const localesDir = join(state.projectRoot, getNormalized(state).localesDir);
746
- for (const locale of getResolver(state).getProjectLocales().locales) this.addWatchFile(join(localesDir, `${locale}.json`));
747
- }
748
- return {
749
- code: result.code,
750
- map: result.map
751
- };
756
+ let localeFilePaths;
757
+ if (state.command === "serve" && this.environment.config.consumer === "server") {
758
+ const localesDir = join(state.projectRoot, getNormalized(state).localesDir);
759
+ localeFilePaths = {};
760
+ for (const locale of locales) localeFilePaths[locale] = join(localesDir, `${locale}.json`);
761
+ }
762
+ const result = transformFile({
763
+ dev: state.command === "serve",
764
+ extracted,
765
+ fileId,
766
+ localeFilePaths,
767
+ locales,
768
+ processors: getNormalized(state).processors,
769
+ source: code,
770
+ sourceLocale: getResolver(state).getProjectLocales().sourceLocale,
771
+ sourcePath: filePath,
772
+ translations
773
+ });
774
+ if (result.code === code) return null;
775
+ if (state.command === "build") {
776
+ const localesDir = join(state.projectRoot, getNormalized(state).localesDir);
777
+ for (const locale of getResolver(state).getProjectLocales().locales) this.addWatchFile(join(localesDir, `${locale}.json`));
778
+ }
779
+ return {
780
+ code: result.code,
781
+ map: result.map
782
+ };
783
+ },
784
+ order: "pre"
752
785
  },
753
786
  watchChange(id, change) {
754
787
  if (state.command !== "build") return;
@@ -842,6 +875,7 @@ function yapyak(options = {}) {
842
875
  createVirtualModulePlugin(state),
843
876
  createScanPlugin(state),
844
877
  createTransformPlugin(state),
878
+ createCompilerRuntimePlugin(state),
845
879
  createDevServerPlugin(state)
846
880
  ];
847
881
  }
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@yapyak/vite",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "description": "Vite plugin for yapyak.",
5
5
  "keywords": [
6
6
  "i18n",
7
7
  "plugin",
8
8
  "translation",
9
9
  "vite",
10
+ "vite-plugin",
10
11
  "yapyak"
11
12
  ],
12
13
  "homepage": "https://yapyak.dev",
@@ -31,17 +32,17 @@
31
32
  "dist"
32
33
  ],
33
34
  "devDependencies": {
34
- "@types/node": "26.1.2",
35
- "tsdown": "0.22.14",
35
+ "@types/node": "26.6.2",
36
+ "tsdown": "0.23.0",
36
37
  "typescript": "6.0.3",
37
- "vite": "8.2.0",
38
- "vitest": "4.1.10",
38
+ "vite": "8.3.1",
39
+ "vitest": "5.0.1",
39
40
  "@yapyak/tsdown-config": "0.0.0",
40
41
  "@yapyak/typescript-config": "0.0.0"
41
42
  },
42
43
  "peerDependencies": {
43
44
  "vite": ">=8",
44
- "yapyak": "0.0.13"
45
+ "yapyak": "0.0.15"
45
46
  },
46
47
  "engines": {
47
48
  "node": ">=22.22"