next-intl 4.13.7 → 4.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cjs/development/BuiltInPoCodec-B6w-kmTx.cjs +34 -0
  2. package/dist/cjs/development/plugin.cjs +1607 -8
  3. package/dist/esm/development/extractor/catalog/CatalogManager.js +3 -2
  4. package/dist/esm/development/extractor/catalog/CatalogPersister.js +21 -2
  5. package/dist/esm/development/extractor/catalogLoader.js +38 -16
  6. package/dist/esm/development/extractor/extractor/MessageExtractor.js +8 -1
  7. package/dist/esm/development/extractor/format/ExtractorCodec.js +3 -0
  8. package/dist/esm/development/extractor/format/codecs/BuiltInPoCodec.js +22 -0
  9. package/dist/esm/development/extractor/format/index.js +19 -4
  10. package/dist/esm/development/extractor/utils.js +8 -27
  11. package/dist/esm/development/plugin/getNextConfig.js +6 -2
  12. package/dist/esm/production/extractor/catalog/CatalogManager.js +1 -1
  13. package/dist/esm/production/extractor/catalog/CatalogPersister.js +1 -1
  14. package/dist/esm/production/extractor/catalogLoader.js +1 -1
  15. package/dist/esm/production/extractor/extractor/MessageExtractor.js +1 -1
  16. package/dist/esm/production/extractor/format/codecs/BuiltInPoCodec.js +1 -0
  17. package/dist/esm/production/extractor/format/index.js +1 -1
  18. package/dist/esm/production/extractor/utils.js +1 -1
  19. package/dist/esm/production/plugin/getNextConfig.js +1 -1
  20. package/dist/types/extractor/catalog/CatalogManager.d.ts +1 -1
  21. package/dist/types/extractor/catalog/CatalogPersister.d.ts +2 -0
  22. package/dist/types/extractor/extractor/MessageExtractor.d.ts +2 -2
  23. package/dist/types/extractor/format/ExtractorCodec.d.ts +11 -27
  24. package/dist/types/extractor/format/codecs/fixtures/POCodecLegacy.d.ts +50 -0
  25. package/dist/types/extractor/format/index.d.ts +2 -2
  26. package/dist/types/extractor/types.d.ts +9 -21
  27. package/dist/types/extractor/utils.d.ts +1 -1
  28. package/package.json +9 -12
  29. package/dist/cjs/development/ExtractorCodec-D9Tw618d.cjs +0 -7
  30. package/dist/cjs/development/JSONCodec-CzA8ubPy.cjs +0 -55
  31. package/dist/cjs/development/POCodec-CWGHK-Gp.cjs +0 -111
  32. package/dist/cjs/development/plugin-DlFYUFWh.cjs +0 -1613
  33. package/dist/esm/development/extractor/format/codecs/JSONCodec.js +0 -47
  34. package/dist/esm/development/extractor/format/codecs/POCodec.js +0 -99
  35. package/dist/esm/production/extractor/format/codecs/JSONCodec.js +0 -1
  36. package/dist/esm/production/extractor/format/codecs/POCodec.js +0 -1
  37. package/dist/types/extractor/format/codecs/POCodec.d.ts +0 -2
  38. package/dist/types/extractor/format/codecs/fixtures/POCodecSourceMessageKey.d.ts +0 -2
  39. /package/dist/types/extractor/format/codecs/{JSONCodec.d.ts → BuiltInPoCodec.d.ts} +0 -0
@@ -1,13 +1,1612 @@
1
1
  'use strict';
2
2
 
3
- var plugin = require('./plugin-DlFYUFWh.cjs');
4
- require('fs/promises');
5
- require('path');
6
- require('@parcel/watcher');
7
- require('fs');
8
- require('module');
9
- require('@swc/core');
3
+ var fs$1 = require('fs/promises');
4
+ var path = require('path');
5
+ var module$1 = require('module');
6
+ var url = require('url');
7
+ var watcher = require('@parcel/watcher');
8
+ var fs = require('fs');
9
+ var core = require('@swc/core');
10
10
 
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
11
13
 
14
+ var fs__default$1 = /*#__PURE__*/_interopDefaultCompat(fs$1);
15
+ var path__default = /*#__PURE__*/_interopDefaultCompat(path);
16
+ var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
12
17
 
13
- module.exports = plugin.createNextIntlPlugin;
18
+ function formatMessage(message) {
19
+ return `\n[next-intl] ${message}\n`;
20
+ }
21
+ function throwError(message) {
22
+ throw new Error(formatMessage(message));
23
+ }
24
+ function warn(message) {
25
+ console.warn(formatMessage(message));
26
+ }
27
+
28
+ /**
29
+ * Returns a function that runs the provided callback only once per process.
30
+ * Next.js can call the config multiple times - this ensures we only run once.
31
+ * Uses an environment variable to track execution across config loads.
32
+ */
33
+ function once(namespace) {
34
+ return function runOnce(fn) {
35
+ if (process.env[namespace] === '1') {
36
+ return;
37
+ }
38
+ process.env[namespace] = '1';
39
+ fn();
40
+ };
41
+ }
42
+
43
+ function stripTrailingSlash(dirPath) {
44
+ if (dirPath.endsWith('/')) {
45
+ return dirPath.slice(0, -1);
46
+ } else {
47
+ return dirPath;
48
+ }
49
+ }
50
+ function normalizeMessagesCatalogPaths(messagesPath) {
51
+ const rawPaths = Array.isArray(messagesPath) ? messagesPath : [messagesPath];
52
+ return rawPaths.map(dirPath => stripTrailingSlash(String(dirPath).trim())).filter(dirPath => dirPath.length > 0);
53
+ }
54
+ function normalizeExtractorConfig(input) {
55
+ if (input.messages == null) {
56
+ throwError('`messages` is required when extracting messages.');
57
+ }
58
+ const extract = input.extract;
59
+ let extractPath;
60
+ let sourceLocale;
61
+ if (extract !== undefined && extract !== true) {
62
+ if (extract.sourceLocale) {
63
+ warn('`extract.sourceLocale` is deprecated in favor of `messages.sourceLocale`.');
64
+ sourceLocale = extract.sourceLocale;
65
+ }
66
+ if (extract.path) {
67
+ extractPath = stripTrailingSlash(extract.path);
68
+ }
69
+ }
70
+ const locales = input.messages.locales;
71
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
72
+ if (!locales) {
73
+ throwError('`messages.locales` is required when extracting messages.');
74
+ }
75
+ if (input.messages.sourceLocale) {
76
+ sourceLocale = input.messages.sourceLocale;
77
+ }
78
+ if (!sourceLocale) {
79
+ throwError('`messages.sourceLocale` is required when extracting messages.');
80
+ }
81
+ const srcPath = input.srcPath;
82
+ if (srcPath == null) {
83
+ throwError('`srcPath` is required when extracting messages.');
84
+ }
85
+ const pathIsArray = Array.isArray(input.messages.path);
86
+ const messagesPath = normalizeMessagesCatalogPaths(input.messages.path);
87
+ if (messagesPath.length === 0) {
88
+ throwError('`messages.path` must not be empty.');
89
+ }
90
+ if (extractPath == null) {
91
+ if (pathIsArray) {
92
+ throwError('When `messages.path` is an array, `extract.path` is required to select the writable catalog directory.');
93
+ }
94
+ extractPath = messagesPath[0];
95
+ }
96
+ return {
97
+ extract: {
98
+ locales,
99
+ path: extractPath,
100
+ sourceLocale,
101
+ srcPath
102
+ },
103
+ messages: {
104
+ format: input.messages.format,
105
+ path: messagesPath
106
+ }
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Wrapper around `fs.watch` that provides a workaround
112
+ * for https://github.com/nodejs/node/issues/5039.
113
+ */
114
+ function watchFile(filepath, callback) {
115
+ const directory = path__default.default.dirname(filepath);
116
+ const filename = path__default.default.basename(filepath);
117
+ return fs__default.default.watch(directory, {
118
+ persistent: false,
119
+ recursive: false
120
+ }, (event, changedFilename) => {
121
+ if (changedFilename === filename) {
122
+ callback();
123
+ }
124
+ });
125
+ }
126
+
127
+ const runOnce$1 = once('_NEXT_INTL_COMPILE_MESSAGES');
128
+ function createMessagesDeclaration(messagesPaths) {
129
+ // Instead of running _only_ in certain cases, it's
130
+ // safer to _avoid_ running for certain known cases.
131
+ // https://github.com/amannn/next-intl/issues/2006
132
+ const shouldBailOut = ['info', 'start'
133
+
134
+ // Note: These commands don't consult the
135
+ // Next.js config, so we can't detect them here.
136
+ // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`)
137
+ // - lint
138
+ //
139
+ // What remains are:
140
+ // - dev
141
+ // - build
142
+ // - typegen
143
+ ].some(arg => process.argv.includes(arg));
144
+ if (shouldBailOut) {
145
+ return;
146
+ }
147
+ runOnce$1(() => {
148
+ for (const messagesPath of messagesPaths) {
149
+ const fullPath = path__default.default.resolve(messagesPath);
150
+ if (!fs__default.default.existsSync(fullPath)) {
151
+ throwError(`\`createMessagesDeclaration\` points to a non-existent file: ${fullPath}`);
152
+ }
153
+ if (!fullPath.endsWith('.json')) {
154
+ throwError(`\`createMessagesDeclaration\` needs to point to a JSON file. Received: ${fullPath}`);
155
+ }
156
+
157
+ // Keep this as a runtime check and don't replace
158
+ // this with a constant during the build process
159
+ const env = process.env['NODE_ENV'.trim()];
160
+ compileDeclaration(messagesPath);
161
+ if (env === 'development') {
162
+ startWatching(messagesPath);
163
+ }
164
+ }
165
+ });
166
+ }
167
+ function startWatching(messagesPath) {
168
+ const watcher = watchFile(messagesPath, () => {
169
+ compileDeclaration(messagesPath, true);
170
+ });
171
+ process.on('exit', () => {
172
+ watcher.close();
173
+ });
174
+ }
175
+ function compileDeclaration(messagesPath, async = false) {
176
+ const declarationPath = messagesPath.replace(/\.json$/, '.d.json.ts');
177
+ function createDeclaration(content) {
178
+ return `// This file is auto-generated by next-intl, do not edit directly.
179
+ // See: https://next-intl.dev/docs/workflows/typescript#messages-arguments
180
+
181
+ declare const messages: ${content.trim()};
182
+ export default messages;`;
183
+ }
184
+ if (async) {
185
+ return fs__default.default.promises.readFile(messagesPath, 'utf-8').then(content => fs__default.default.promises.writeFile(declarationPath, createDeclaration(content)));
186
+ }
187
+ const content = fs__default.default.readFileSync(messagesPath, 'utf-8');
188
+ fs__default.default.writeFileSync(declarationPath, createDeclaration(content));
189
+ }
190
+
191
+ const formats = {
192
+ json: {
193
+ codec: () => import('@eloqnt/format-json'),
194
+ extension: '.json'
195
+ },
196
+ po: {
197
+ codec: () => Promise.resolve().then(function () { return require('./BuiltInPoCodec-B6w-kmTx.cjs'); }),
198
+ extension: '.po'
199
+ }
200
+ };
201
+ function isBuiltInFormat(format) {
202
+ return typeof format === 'string' && format in formats;
203
+ }
204
+ function getFormatExtension(format) {
205
+ if (isBuiltInFormat(format)) {
206
+ return formats[format].extension;
207
+ } else {
208
+ return format.extension;
209
+ }
210
+ }
211
+ async function resolveCodec(format, projectRoot) {
212
+ if (isBuiltInFormat(format)) {
213
+ const factory = (await formats[format].codec()).default;
214
+ return factory();
215
+ } else {
216
+ // A codec that starts with `.` or a filesystem root is a file path;
217
+ // everything else reads as a package specifier, mirroring how imports
218
+ // distinguish the two. Packages resolve from the project's dependencies.
219
+ const isPath = format.codec.startsWith('.') || path__default.default.isAbsolute(format.codec);
220
+ let resolvedPath;
221
+ if (isPath) {
222
+ resolvedPath = path__default.default.resolve(projectRoot, format.codec);
223
+ } else {
224
+ try {
225
+ resolvedPath = module$1.createRequire(path__default.default.join(projectRoot, 'noop.js')).resolve(format.codec);
226
+ } catch (error) {
227
+ throwError(`Could not resolve the codec package "${format.codec}". Is it installed?\n${error}`);
228
+ }
229
+ }
230
+ let module;
231
+ try {
232
+ module = await import(url.pathToFileURL(resolvedPath).href);
233
+ } catch (error) {
234
+ throwError(`Could not load codec from "${resolvedPath}".\n${error}`);
235
+ }
236
+ const factory = module.default;
237
+ if (!factory || typeof factory !== 'function') {
238
+ throwError(`Codec at "${resolvedPath}" must have a default export returned from \`defineCodec\`.`);
239
+ }
240
+ return factory();
241
+ }
242
+ }
243
+
244
+ class SourceFileFilter {
245
+ static EXTENSIONS = ['ts', 'tsx', 'js', 'jsx'];
246
+
247
+ // Will not be entered, except if explicitly asked for
248
+ // TODO: At some point we should infer these from .gitignore
249
+ static IGNORED_DIRECTORIES = ['node_modules', '.next', '.git'];
250
+ static isSourceFile(filePath) {
251
+ const ext = path__default.default.extname(filePath);
252
+ return SourceFileFilter.EXTENSIONS.map(cur => '.' + cur).includes(ext);
253
+ }
254
+ static shouldEnterDirectory(dirPath, srcPaths) {
255
+ const dirName = path__default.default.basename(dirPath);
256
+ if (SourceFileFilter.IGNORED_DIRECTORIES.includes(dirName)) {
257
+ return SourceFileFilter.isIgnoredDirectoryExplicitlyIncluded(dirPath, srcPaths);
258
+ }
259
+ return true;
260
+ }
261
+ static isIgnoredDirectoryExplicitlyIncluded(ignoredDirPath, srcPaths) {
262
+ return srcPaths.some(srcPath => SourceFileFilter.isWithinPath(srcPath, ignoredDirPath));
263
+ }
264
+ static isWithinPath(targetPath, basePath) {
265
+ const relativePath = path__default.default.relative(basePath, targetPath);
266
+ return relativePath === '' || !relativePath.startsWith('..');
267
+ }
268
+ }
269
+
270
+ class SourceFileScanner {
271
+ static async walkSourceFiles(dir, srcPaths, acc = []) {
272
+ const entries = await fs__default$1.default.readdir(dir, {
273
+ withFileTypes: true
274
+ });
275
+ for (const entry of entries) {
276
+ const entryPath = path__default.default.join(dir, entry.name);
277
+ if (entry.isDirectory()) {
278
+ if (!SourceFileFilter.shouldEnterDirectory(entryPath, srcPaths)) {
279
+ continue;
280
+ }
281
+ await SourceFileScanner.walkSourceFiles(entryPath, srcPaths, acc);
282
+ } else {
283
+ if (SourceFileFilter.isSourceFile(entry.name)) {
284
+ acc.push(entryPath);
285
+ }
286
+ }
287
+ }
288
+ return acc;
289
+ }
290
+ static async getSourceFiles(srcPaths) {
291
+ const files = (await Promise.all(srcPaths.map(srcPath => SourceFileScanner.walkSourceFiles(srcPath, srcPaths)))).flat();
292
+ return new Set(files);
293
+ }
294
+ }
295
+
296
+ class SourceFileWatcher {
297
+ subscriptions = [];
298
+ constructor(roots, onChange) {
299
+ this.roots = roots;
300
+ this.onChange = onChange;
301
+ }
302
+ async start() {
303
+ if (this.subscriptions.length > 0) {
304
+ return;
305
+ }
306
+ const ignore = SourceFileFilter.IGNORED_DIRECTORIES.map(dir => `**/${dir}/**`);
307
+ for (const root of this.roots) {
308
+ const sub = await watcher.subscribe(root, async (err, events) => {
309
+ if (err) {
310
+ console.error(err);
311
+ return;
312
+ }
313
+ const filtered = await this.normalizeEvents(events);
314
+ if (filtered.length > 0) {
315
+ await this.onChange(filtered);
316
+ }
317
+ }, {
318
+ ignore
319
+ });
320
+ this.subscriptions.push(sub);
321
+ }
322
+ }
323
+ async normalizeEvents(events) {
324
+ const directoryCreatePaths = [];
325
+ const otherEvents = [];
326
+
327
+ // We need to expand directory creates because during rename operations,
328
+ // @parcel/watcher emits a directory create event but may not emit individual
329
+ // file events for the moved files
330
+ await Promise.all(events.map(async event => {
331
+ if (event.type === 'create') {
332
+ try {
333
+ const stats = await fs__default$1.default.stat(event.path);
334
+ if (stats.isDirectory()) {
335
+ directoryCreatePaths.push(event.path);
336
+ return;
337
+ }
338
+ } catch {
339
+ // Path doesn't exist or is inaccessible, treat as file
340
+ }
341
+ }
342
+ otherEvents.push(event);
343
+ }));
344
+
345
+ // Expand directory create events to find source files inside
346
+ let expandedCreateEvents = [];
347
+ if (directoryCreatePaths.length > 0) {
348
+ try {
349
+ const sourceFiles = await SourceFileScanner.getSourceFiles(directoryCreatePaths);
350
+ expandedCreateEvents = Array.from(sourceFiles).map(filePath => ({
351
+ type: 'create',
352
+ path: filePath
353
+ }));
354
+ } catch {
355
+ // Directories might have been deleted or are inaccessible
356
+ }
357
+ }
358
+
359
+ // Combine original events with expanded directory creates.
360
+ // Deduplicate by path to avoid processing the same file twice
361
+ // in case @parcel/watcher also emitted individual file events.
362
+ const allEvents = [...otherEvents, ...expandedCreateEvents];
363
+ const seenPaths = new Set();
364
+ const deduplicated = [];
365
+ for (const event of allEvents) {
366
+ const key = `${event.type}:${event.path}`;
367
+ if (!seenPaths.has(key)) {
368
+ seenPaths.add(key);
369
+ deduplicated.push(event);
370
+ }
371
+ }
372
+ return deduplicated.filter(event => {
373
+ // Keep all delete events (might be deleted directories that no longer exist)
374
+ if (event.type === 'delete') {
375
+ return true;
376
+ }
377
+ // Keep source files
378
+ return SourceFileFilter.isSourceFile(event.path);
379
+ });
380
+ }
381
+ async expandDirectoryDeleteEvents(events, prevKnownFiles) {
382
+ const expanded = [];
383
+ for (const event of events) {
384
+ if (event.type === 'delete' && !SourceFileFilter.isSourceFile(event.path)) {
385
+ const dirPath = path__default.default.resolve(event.path);
386
+ const filesInDirectory = [];
387
+ for (const filePath of prevKnownFiles) {
388
+ if (SourceFileFilter.isWithinPath(filePath, dirPath)) {
389
+ filesInDirectory.push(filePath);
390
+ }
391
+ }
392
+
393
+ // If we found files within this path, it was a directory
394
+ if (filesInDirectory.length > 0) {
395
+ for (const filePath of filesInDirectory) {
396
+ expanded.push({
397
+ type: 'delete',
398
+ path: filePath
399
+ });
400
+ }
401
+ } else {
402
+ // Not a directory or no files in it, pass through as-is
403
+ expanded.push(event);
404
+ }
405
+ } else {
406
+ // Pass through as-is
407
+ expanded.push(event);
408
+ }
409
+ }
410
+ return expanded;
411
+ }
412
+ async stop() {
413
+ await Promise.all(this.subscriptions.map(sub => sub.unsubscribe()));
414
+ this.subscriptions = [];
415
+ }
416
+ [Symbol.dispose]() {
417
+ void this.stop();
418
+ }
419
+ }
420
+
421
+ function normalizePathToPosix(filePath) {
422
+ // `path.relative` uses OS-specific separators. For stable `.po` references we
423
+ // always use POSIX separators, regardless of the OS that ran extraction.
424
+ return path__default.default.posix.normalize(filePath.split(path__default.default.win32.sep).join(path__default.default.posix.sep));
425
+ }
426
+ function hasLocalesToExtract(config) {
427
+ const {
428
+ locales
429
+ } = config.extract;
430
+ return locales === 'infer' || locales.length > 0;
431
+ }
432
+ function warnAboutMissingReferences(messages) {
433
+ const warnedIds = new Set();
434
+ for (const message of messages) {
435
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
436
+ if (message.references[0] == null && !warnedIds.has(message.id)) {
437
+ warnedIds.add(message.id);
438
+ warn(`Missing file reference for extracted message: ${message.id}`);
439
+ }
440
+ }
441
+ }
442
+ function localeCompare(a, b) {
443
+ return a.localeCompare(b, 'en');
444
+ }
445
+ function compareReferences(refA, refB) {
446
+ const pathCompare = localeCompare(refA.path, refB.path);
447
+ if (pathCompare !== 0) return pathCompare;
448
+ return (refA.line ?? 0) - (refB.line ?? 0);
449
+ }
450
+ function getDefaultProjectRoot() {
451
+ return process.cwd();
452
+ }
453
+
454
+ class CatalogLocales {
455
+ onChangeCallbacks = new Set();
456
+ constructor(params) {
457
+ this.messagesDir = params.messagesDir;
458
+ this.sourceLocale = params.sourceLocale;
459
+ this.extension = params.extension;
460
+ this.locales = params.locales;
461
+ }
462
+ async getTargetLocales() {
463
+ if (this.targetLocales) {
464
+ return this.targetLocales;
465
+ }
466
+ if (this.locales === 'infer') {
467
+ this.targetLocales = await this.readTargetLocales();
468
+ } else {
469
+ this.targetLocales = this.locales.filter(locale => locale !== this.sourceLocale);
470
+ }
471
+ return this.targetLocales;
472
+ }
473
+ async readTargetLocales() {
474
+ try {
475
+ const files = await fs__default$1.default.readdir(this.messagesDir);
476
+ return files.filter(file => file.endsWith(this.extension)).map(file => path__default.default.basename(file, this.extension)).filter(locale => locale !== this.sourceLocale);
477
+ } catch {
478
+ return [];
479
+ }
480
+ }
481
+ subscribeLocalesChange(callback) {
482
+ this.onChangeCallbacks.add(callback);
483
+ if (this.locales === 'infer' && !this.watcher) {
484
+ void this.startWatcher();
485
+ }
486
+ }
487
+ unsubscribeLocalesChange(callback) {
488
+ this.onChangeCallbacks.delete(callback);
489
+ if (this.onChangeCallbacks.size === 0) {
490
+ this.stopWatcher();
491
+ }
492
+ }
493
+ async startWatcher() {
494
+ if (this.watcher) {
495
+ return;
496
+ }
497
+ await fs__default$1.default.mkdir(this.messagesDir, {
498
+ recursive: true
499
+ });
500
+ this.watcher = fs__default.default.watch(this.messagesDir, {
501
+ persistent: false,
502
+ recursive: false
503
+ }, (event, filename) => {
504
+ const isCatalogFile = filename != null && filename.endsWith(this.extension) && !filename.includes(path__default.default.sep);
505
+ if (isCatalogFile) {
506
+ void this.onChange();
507
+ }
508
+ });
509
+ }
510
+ stopWatcher() {
511
+ if (this.watcher) {
512
+ this.watcher.close();
513
+ this.watcher = undefined;
514
+ }
515
+ }
516
+ async onChange() {
517
+ const oldLocales = new Set(this.targetLocales || []);
518
+ this.targetLocales = await this.readTargetLocales();
519
+ const newLocalesSet = new Set(this.targetLocales);
520
+ const added = this.targetLocales.filter(locale => !oldLocales.has(locale));
521
+ const removed = Array.from(oldLocales).filter(locale => !newLocalesSet.has(locale));
522
+ if (added.length > 0 || removed.length > 0) {
523
+ for (const callback of this.onChangeCallbacks) {
524
+ callback({
525
+ added,
526
+ removed
527
+ });
528
+ }
529
+ }
530
+ }
531
+ }
532
+
533
+ class CatalogPersister {
534
+ constructor(params) {
535
+ this.messagesPath = params.messagesPath;
536
+ this.codec = params.codec;
537
+ this.extension = params.extension;
538
+ this.sourceLocale = params.sourceLocale;
539
+ }
540
+ getFileName(locale) {
541
+ return locale + this.extension;
542
+ }
543
+ getFilePath(locale) {
544
+ return path__default.default.join(this.messagesPath, this.getFileName(locale));
545
+ }
546
+ async read(locale) {
547
+ const filePath = this.getFilePath(locale);
548
+ let content;
549
+ try {
550
+ content = await fs__default$1.default.readFile(filePath, 'utf8');
551
+ } catch (error) {
552
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {
553
+ return [];
554
+ }
555
+ throw new Error(`Error while reading ${this.getFileName(locale)}:\n> ${error}`, {
556
+ cause: error
557
+ });
558
+ }
559
+ try {
560
+ const messages = this.codec.decode(content, {
561
+ locale,
562
+ sourceLocale: this.sourceLocale
563
+ });
564
+ assertNoArrayMessages(messages);
565
+ return messages;
566
+ } catch (error) {
567
+ throw new Error(`Error while decoding ${this.getFileName(locale)}:\n> ${error}`, {
568
+ cause: error
569
+ });
570
+ }
571
+ }
572
+ async write(messages, context) {
573
+ const filePath = this.getFilePath(context.locale);
574
+ warnAboutMissingReferences(messages);
575
+ const content = this.codec.encode(messages, context);
576
+ try {
577
+ const outputDir = path__default.default.dirname(filePath);
578
+ await fs__default$1.default.mkdir(outputDir, {
579
+ recursive: true
580
+ });
581
+ await fs__default$1.default.writeFile(filePath, content);
582
+ } catch (error) {
583
+ console.error(`❌ Failed to write catalog: ${error}`);
584
+ }
585
+ }
586
+ async getLastModified(locale) {
587
+ const filePath = this.getFilePath(locale);
588
+ try {
589
+ const stats = await fs__default$1.default.stat(filePath);
590
+ return stats.mtime;
591
+ } catch {
592
+ return undefined;
593
+ }
594
+ }
595
+ }
596
+
597
+ // The codecs read arrays fine (numeric path segments), but the runtime only
598
+ // supports strings — enforced here where the runtime's rules apply.
599
+ function assertNoArrayMessages(messages) {
600
+ for (const message of messages) {
601
+ const segments = message.segments;
602
+ if (!Array.isArray(segments)) continue;
603
+ const firstIndex = segments.findIndex(segment => typeof segment === 'number');
604
+ if (firstIndex === -1) continue;
605
+ const arrayPath = segments.slice(0, firstIndex).join('.');
606
+ throw new Error(`Message at \`${arrayPath}\` resolved to an array, but only strings are supported. See https://next-intl.dev/docs/usage/translations#arrays-of-messages`);
607
+ }
608
+ }
609
+
610
+ /**
611
+ * De-duplicates excessive save invocations,
612
+ * while keeping a single one instant.
613
+ */
614
+ class SaveScheduler {
615
+ isSaving = false;
616
+ pendingResolvers = [];
617
+ constructor(delayMs = 50) {
618
+ this.delayMs = delayMs;
619
+ }
620
+ async schedule(saveTask) {
621
+ return new Promise((resolve, reject) => {
622
+ this.pendingResolvers.push({
623
+ resolve,
624
+ reject
625
+ });
626
+ this.nextSaveTask = saveTask;
627
+ if (!this.isSaving && !this.saveTimeout) {
628
+ // Not currently saving and no scheduled save, save immediately
629
+ this.executeSave();
630
+ } else if (this.saveTimeout) {
631
+ // A save is already scheduled, reschedule to debounce
632
+ this.scheduleSave();
633
+ }
634
+ // If isSaving is true and no timeout is scheduled, the current save
635
+ // will check for pending resolvers when it completes and schedule
636
+ // another save if needed (see finally block in executeSave)
637
+ });
638
+ }
639
+ scheduleSave() {
640
+ if (this.saveTimeout) {
641
+ clearTimeout(this.saveTimeout);
642
+ }
643
+ this.saveTimeout = setTimeout(() => {
644
+ this.saveTimeout = undefined;
645
+ this.executeSave();
646
+ }, this.delayMs);
647
+ }
648
+ async executeSave() {
649
+ if (this.isSaving) {
650
+ return;
651
+ }
652
+ const saveTask = this.nextSaveTask;
653
+ if (!saveTask) {
654
+ return;
655
+ }
656
+
657
+ // Capture current pending resolvers for this save
658
+ const resolversForThisSave = this.pendingResolvers;
659
+ this.pendingResolvers = [];
660
+ this.nextSaveTask = undefined;
661
+ this.isSaving = true;
662
+ try {
663
+ const result = await saveTask();
664
+
665
+ // Resolve only the promises that were pending when this save started
666
+ resolversForThisSave.forEach(({
667
+ resolve
668
+ }) => resolve(result));
669
+ } catch (error) {
670
+ // Reject only the promises that were pending when this save started
671
+ resolversForThisSave.forEach(({
672
+ reject
673
+ }) => reject(error));
674
+ } finally {
675
+ this.isSaving = false;
676
+
677
+ // If new saves were requested during this save, schedule another
678
+ if (this.pendingResolvers.length > 0) {
679
+ this.scheduleSave();
680
+ }
681
+ }
682
+ }
683
+ [Symbol.dispose]() {
684
+ if (this.saveTimeout) {
685
+ clearTimeout(this.saveTimeout);
686
+ this.saveTimeout = undefined;
687
+ }
688
+ this.pendingResolvers = [];
689
+ this.nextSaveTask = undefined;
690
+ this.isSaving = false;
691
+ }
692
+ }
693
+
694
+ class CatalogManager {
695
+ /**
696
+ * Extraction-derived fields aggregated into `ExtractorMessage`.
697
+ * Source code is the source of truth for these fields, only ancillary
698
+ * codec fields may merge from disk (e.g. flags).
699
+ */
700
+ static extractorOwnedAggregatorKeys = new Set(['description', 'id', 'message', 'references']);
701
+ /**
702
+ * Source of truth for statically extracted source messages,
703
+ * grouped by file and message ID.
704
+ */
705
+ sourceMessagesByFile = new Map();
706
+
707
+ /**
708
+ * Reverse index for rebuilding aggregated messages without scanning all files.
709
+ * Contains the same `SourceExtractedMessage` arrays as `sourceMessagesByFile` and is
710
+ * kept in sync with it.
711
+ */
712
+ sourceMessagesById = new Map();
713
+
714
+ /**
715
+ * Fast lookup for messages by ID, aggregated across all files. This combines
716
+ * metadata from `sourceMessagesById`, e.g. references and descriptions.
717
+ */
718
+ messagesById = new Map();
719
+
720
+ /**
721
+ * This potentially also includes outdated ones that were initially available,
722
+ * but are not used anymore. This allows to restore them if they are used again.
723
+ **/
724
+ translationsByTargetLocale = new Map();
725
+ lastWriteByLocale = new Map();
726
+
727
+ // Cached instances
728
+
729
+ // Resolves when all catalogs are loaded
730
+
731
+ // Resolves when the initial project scan and processing is complete
732
+
733
+ constructor(config, opts) {
734
+ this.config = config;
735
+ this.saveScheduler = new SaveScheduler(opts.saveDebounceMs ?? 50);
736
+ this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot();
737
+ this.isDevelopment = opts.isDevelopment ?? false;
738
+ this.extractor = opts.extractor;
739
+ if (this.isDevelopment) {
740
+ // We kick this off as early as possible, so we get notified about changes
741
+ // that happen during the initial project scan (while awaiting it to
742
+ // complete though)
743
+ this.sourceWatcher = new SourceFileWatcher(this.getSrcPaths(), this.handleFileEvents.bind(this));
744
+ void this.sourceWatcher.start();
745
+ }
746
+ }
747
+ async getCodec() {
748
+ if (!this.codec) {
749
+ this.codec = await resolveCodec(this.config.messages.format, this.projectRoot);
750
+ }
751
+ return this.codec;
752
+ }
753
+ async getPersister() {
754
+ if (this.persister) {
755
+ return this.persister;
756
+ } else {
757
+ this.persister = new CatalogPersister({
758
+ messagesPath: this.config.extract.path,
759
+ codec: await this.getCodec(),
760
+ extension: getFormatExtension(this.config.messages.format),
761
+ sourceLocale: this.config.extract.sourceLocale
762
+ });
763
+ return this.persister;
764
+ }
765
+ }
766
+ getCatalogLocales() {
767
+ if (this.catalogLocales) {
768
+ return this.catalogLocales;
769
+ } else {
770
+ const messagesDir = path__default.default.join(this.projectRoot, this.config.extract.path);
771
+ this.catalogLocales = new CatalogLocales({
772
+ messagesDir,
773
+ extension: getFormatExtension(this.config.messages.format),
774
+ locales: this.config.extract.locales,
775
+ sourceLocale: this.config.extract.sourceLocale
776
+ });
777
+ return this.catalogLocales;
778
+ }
779
+ }
780
+ async getTargetLocales() {
781
+ return this.getCatalogLocales().getTargetLocales();
782
+ }
783
+ getSrcPaths() {
784
+ return (Array.isArray(this.config.extract.srcPath) ? this.config.extract.srcPath : [this.config.extract.srcPath]).map(srcPath => path__default.default.join(this.projectRoot, srcPath));
785
+ }
786
+ async loadMessages() {
787
+ const sourceDiskMessages = await this.loadSourceMessages();
788
+ this.loadCatalogsPromise = this.loadTargetMessages();
789
+ await this.loadCatalogsPromise;
790
+ this.scanCompletePromise = (async () => {
791
+ const sourceFiles = Array.from(await SourceFileScanner.getSourceFiles(this.getSrcPaths()))
792
+ // Stable file order keeps catalog ties independent of processing timing
793
+ .toSorted(localeCompare);
794
+ const extractedFiles = await Promise.all(sourceFiles.map(async filePath => ({
795
+ filePath,
796
+ messages: await this.extractFile(filePath)
797
+ })));
798
+ for (const {
799
+ filePath,
800
+ messages
801
+ } of extractedFiles) {
802
+ if (messages) {
803
+ this.applyFileMessages(filePath, messages);
804
+ }
805
+ }
806
+ this.mergeSourceDiskMetadata(sourceDiskMessages);
807
+ })();
808
+ await this.scanCompletePromise;
809
+ if (this.isDevelopment) {
810
+ const catalogLocales = this.getCatalogLocales();
811
+ catalogLocales.subscribeLocalesChange(this.onLocalesChange);
812
+ }
813
+ }
814
+ async loadSourceMessages() {
815
+ // Load source catalog to hydrate metadata (e.g. flags) later without
816
+ // treating catalog entries as source of truth.
817
+ const diskMessages = await this.loadLocaleMessages(this.config.extract.sourceLocale);
818
+ const byId = new Map();
819
+ for (const diskMessage of diskMessages) {
820
+ byId.set(diskMessage.id, diskMessage);
821
+ }
822
+ return byId;
823
+ }
824
+ async loadLocaleMessages(locale) {
825
+ const persister = await this.getPersister();
826
+ const messages = await persister.read(locale);
827
+ const fileTime = await persister.getLastModified(locale);
828
+ this.lastWriteByLocale.set(locale, fileTime);
829
+ return messages;
830
+ }
831
+ async loadTargetMessages() {
832
+ const targetLocales = await this.getTargetLocales();
833
+ await Promise.all(targetLocales.map(locale => this.reloadLocaleCatalog(locale)));
834
+ }
835
+ async reloadLocaleCatalog(locale) {
836
+ const diskMessages = await this.loadLocaleMessages(locale);
837
+ if (locale === this.config.extract.sourceLocale) {
838
+ // For source: Merge additional properties like flags
839
+ for (const diskMessage of diskMessages) {
840
+ const prev = this.messagesById.get(diskMessage.id);
841
+ if (prev) {
842
+ for (const key of Object.keys(diskMessage)) {
843
+ if (!CatalogManager.extractorOwnedAggregatorKeys.has(key)) {
844
+ // For unknown properties (like flags), disk wins
845
+ prev[key] = diskMessage[key];
846
+ }
847
+ }
848
+ }
849
+ }
850
+ } else {
851
+ // For target: disk wins completely, BUT preserve existing translations
852
+ // if we read empty (likely a write in progress by an external tool
853
+ // that causes the file to temporarily be empty)
854
+ const existingTranslations = this.translationsByTargetLocale.get(locale);
855
+ const hasExistingTranslations = existingTranslations && existingTranslations.size > 0;
856
+ if (diskMessages.length > 0) {
857
+ // We got content from disk, replace with it
858
+ const translations = new Map();
859
+ for (const message of diskMessages) {
860
+ translations.set(message.id, message);
861
+ }
862
+ this.translationsByTargetLocale.set(locale, translations);
863
+ } else if (hasExistingTranslations) ; else {
864
+ // We read empty and have no existing translations
865
+ const translations = new Map();
866
+ this.translationsByTargetLocale.set(locale, translations);
867
+ }
868
+ }
869
+ }
870
+ mergeSourceDiskMetadata(diskMessages) {
871
+ for (const [id, diskMessage] of diskMessages) {
872
+ const existing = this.messagesById.get(id);
873
+ if (!existing) continue;
874
+
875
+ // Fill unknown metadata from disk without replacing extraction-owned fields.
876
+ for (const key of Object.keys(diskMessage)) {
877
+ if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && existing[key] == null) {
878
+ existing[key] = diskMessage[key];
879
+ }
880
+ }
881
+ }
882
+ }
883
+ async processFile(absoluteFilePath) {
884
+ const messages = await this.extractFile(absoluteFilePath);
885
+
886
+ // `undefined` only when `extractFile()` throws. An empty array is success
887
+ // and must still run `applyFileMessages` to clear stale ids for this file.
888
+ if (!messages) return false;
889
+ return this.applyFileMessages(absoluteFilePath, messages);
890
+ }
891
+ async extractFile(absoluteFilePath) {
892
+ let messages = [];
893
+ try {
894
+ const content = await fs__default$1.default.readFile(absoluteFilePath, 'utf8');
895
+ let extraction;
896
+ try {
897
+ extraction = await this.extractor.extract(absoluteFilePath, content);
898
+ } catch {
899
+ return undefined;
900
+ }
901
+ messages = extraction.messages;
902
+ } catch (err) {
903
+ if (err.code !== 'ENOENT') {
904
+ throw err;
905
+ }
906
+ // ENOENT -> treat as no messages
907
+ }
908
+ return messages;
909
+ }
910
+ applyFileMessages(absoluteFilePath, messages) {
911
+ const prevFileMessages = this.sourceMessagesByFile.get(absoluteFilePath);
912
+ const nextFileMessages = this.groupSourceMessagesById(messages);
913
+ const affectedIds = new Set([...(prevFileMessages?.keys() ?? []), ...nextFileMessages.keys()]);
914
+ if (nextFileMessages.size > 0) {
915
+ this.sourceMessagesByFile.set(absoluteFilePath, nextFileMessages);
916
+ } else {
917
+ this.sourceMessagesByFile.delete(absoluteFilePath);
918
+ }
919
+
920
+ // Clear this file's contribution from the reverse index, then re-insert
921
+ // fresh rows and rebuild aggregates (messagesById) per touched id.
922
+ for (const id of affectedIds) {
923
+ const sourceMessagesForId = this.sourceMessagesById.get(id);
924
+ if (sourceMessagesForId) {
925
+ sourceMessagesForId.delete(absoluteFilePath);
926
+ // No files left for this id: drop the reverse-index entry.
927
+ if (sourceMessagesForId.size === 0) {
928
+ this.sourceMessagesById.delete(id);
929
+ }
930
+ }
931
+ const nextSourceMessagesForId = nextFileMessages.get(id);
932
+ if (nextSourceMessagesForId) {
933
+ let sourceMessagesByFile = this.sourceMessagesById.get(id);
934
+ if (!sourceMessagesByFile) {
935
+ sourceMessagesByFile = new Map();
936
+ this.sourceMessagesById.set(id, sourceMessagesByFile);
937
+ }
938
+ sourceMessagesByFile.set(absoluteFilePath, nextSourceMessagesForId);
939
+ }
940
+ this.rebuildMessageById(id);
941
+ }
942
+ const changed = this.haveMessagesChangedForFile(prevFileMessages, nextFileMessages);
943
+ return changed;
944
+ }
945
+ groupSourceMessagesById(messages) {
946
+ const result = new Map();
947
+ for (const message of messages) {
948
+ const messagesById = result.get(message.id);
949
+ if (messagesById) {
950
+ messagesById.push(message);
951
+ } else {
952
+ result.set(message.id, [message]);
953
+ }
954
+ }
955
+ return result;
956
+ }
957
+ rebuildMessageById(id) {
958
+ const sourceMessages = Array.from(this.sourceMessagesById.get(id)?.values() ?? []).flat();
959
+ if (sourceMessages.length === 0) {
960
+ this.messagesById.delete(id);
961
+ return;
962
+ }
963
+ const previousMessage = this.messagesById.get(id);
964
+ const aggregate = {
965
+ description: this.mergeDescriptions(sourceMessages),
966
+ id,
967
+ message: sourceMessages[0].message,
968
+ references: sourceMessages.map(message => message.reference).sort(compareReferences)
969
+ };
970
+ if (previousMessage) {
971
+ for (const key of Object.keys(previousMessage)) {
972
+ // Preserve extra fields (e.g. from disk/codec) across rebuilds; the
973
+ // four core fields above are always recomputed from source messages.
974
+ if (!CatalogManager.extractorOwnedAggregatorKeys.has(key) && aggregate[key] == null) {
975
+ aggregate[key] = previousMessage[key];
976
+ }
977
+ }
978
+ }
979
+ this.messagesById.set(id, aggregate);
980
+ }
981
+ mergeDescriptions(messages) {
982
+ const sortedByReference = messages.toSorted((a, b) => compareReferences(a.reference, b.reference));
983
+ const merged = [];
984
+ for (const message of sortedByReference) {
985
+ const {
986
+ description
987
+ } = message;
988
+ if (description != null && !merged.includes(description)) {
989
+ merged.push(description);
990
+ }
991
+ }
992
+ return merged;
993
+ }
994
+ haveMessagesChangedForFile(beforeMessages, afterMessages) {
995
+ // If one exists and the other doesn't, there's a change
996
+ if (!beforeMessages) {
997
+ return afterMessages.size > 0;
998
+ }
999
+
1000
+ // Different sizes means changes
1001
+ if (beforeMessages.size !== afterMessages.size) {
1002
+ return true;
1003
+ }
1004
+
1005
+ // Check differences in beforeMessages vs afterMessages
1006
+ for (const [id, prevSourceMessages] of beforeMessages) {
1007
+ const nextSourceMessages = afterMessages.get(id);
1008
+ if (!nextSourceMessages) {
1009
+ return true;
1010
+ }
1011
+ if (!this.areSourceMessageArraysEqual(prevSourceMessages, nextSourceMessages)) {
1012
+ return true; // Early exit on first difference
1013
+ }
1014
+ }
1015
+ return false;
1016
+ }
1017
+ areSourceMessageArraysEqual(messages1, messages2) {
1018
+ return messages1.length === messages2.length && messages1.every((message, index) => this.areSourceMessagesEqual(message, messages2[index]));
1019
+ }
1020
+ areSourceMessagesEqual(msg1, msg2) {
1021
+ return msg1.id === msg2.id && msg1.message === msg2.message && msg1.description === msg2.description && msg1.reference.path === msg2.reference.path && msg1.reference.line === msg2.reference.line;
1022
+ }
1023
+ async save() {
1024
+ return this.saveScheduler.schedule(() => this.saveImpl());
1025
+ }
1026
+ async saveImpl() {
1027
+ await this.saveLocale(this.config.extract.sourceLocale);
1028
+ const targetLocales = await this.getTargetLocales();
1029
+ await Promise.all(targetLocales.map(locale => this.saveLocale(locale)));
1030
+ }
1031
+ async saveLocale(locale) {
1032
+ await this.loadCatalogsPromise;
1033
+ const messages = Array.from(this.messagesById.values());
1034
+ const persister = await this.getPersister();
1035
+ const isSourceLocale = locale === this.config.extract.sourceLocale;
1036
+
1037
+ // Check if file was modified externally (poll-at-save is cheaper than
1038
+ // watchers here since stat() is fast and avoids continuous overhead)
1039
+ const lastWriteTime = this.lastWriteByLocale.get(locale);
1040
+ const currentFileTime = await persister.getLastModified(locale);
1041
+ if (currentFileTime && lastWriteTime && currentFileTime > lastWriteTime) {
1042
+ await this.reloadLocaleCatalog(locale);
1043
+ }
1044
+ const localeMessages = isSourceLocale ? this.messagesById : this.translationsByTargetLocale.get(locale);
1045
+ const messagesToPersist = messages.map(message => {
1046
+ const localeMessage = localeMessages?.get(message.id);
1047
+ return {
1048
+ ...localeMessage,
1049
+ id: message.id,
1050
+ description: message.description,
1051
+ references: message.references,
1052
+ message: isSourceLocale ? message.message : localeMessage?.message ?? ''
1053
+ };
1054
+ });
1055
+ await persister.write(messagesToPersist, {
1056
+ locale,
1057
+ sourceMessagesById: this.messagesById
1058
+ });
1059
+
1060
+ // Update timestamps
1061
+ const newTime = await persister.getLastModified(locale);
1062
+ this.lastWriteByLocale.set(locale, newTime);
1063
+ }
1064
+ onLocalesChange = async params => {
1065
+ // Chain to existing promise
1066
+ this.loadCatalogsPromise = Promise.all([this.loadCatalogsPromise, ...params.added.map(locale => this.reloadLocaleCatalog(locale))]);
1067
+ for (const locale of params.added) {
1068
+ await this.saveLocale(locale);
1069
+ }
1070
+ for (const locale of params.removed) {
1071
+ this.translationsByTargetLocale.delete(locale);
1072
+ this.lastWriteByLocale.delete(locale);
1073
+ }
1074
+ };
1075
+ async handleFileEvents(events) {
1076
+ if (this.loadCatalogsPromise) {
1077
+ await this.loadCatalogsPromise;
1078
+ }
1079
+
1080
+ // Wait for initial scan to complete to avoid race conditions
1081
+ if (this.scanCompletePromise) {
1082
+ await this.scanCompletePromise;
1083
+ }
1084
+ let changed = false;
1085
+ const expandedEvents = await this.sourceWatcher.expandDirectoryDeleteEvents(events, Array.from(this.sourceMessagesByFile.keys()));
1086
+ // Stable file order keeps catalog ties independent of event timing.
1087
+ for (const event of expandedEvents.toSorted((a, b) => localeCompare(a.path, b.path))) {
1088
+ const hasChanged = await this.processFile(event.path);
1089
+ changed ||= hasChanged;
1090
+ }
1091
+ if (changed) {
1092
+ await this.save();
1093
+ }
1094
+ }
1095
+ [Symbol.dispose]() {
1096
+ this.sourceWatcher?.stop();
1097
+ this.sourceWatcher = undefined;
1098
+ this.saveScheduler[Symbol.dispose]();
1099
+ if (this.catalogLocales && this.isDevelopment) {
1100
+ this.catalogLocales.unsubscribeLocalesChange(this.onLocalesChange);
1101
+ }
1102
+ }
1103
+ }
1104
+
1105
+ class LRUCache {
1106
+ constructor(maxSize) {
1107
+ this.maxSize = maxSize;
1108
+ this.cache = new Map();
1109
+ }
1110
+ set(key, value) {
1111
+ const isNewKey = !this.cache.has(key);
1112
+ if (isNewKey && this.cache.size >= this.maxSize) {
1113
+ const lruKey = this.cache.keys().next().value;
1114
+ if (lruKey !== undefined) {
1115
+ this.cache.delete(lruKey);
1116
+ }
1117
+ }
1118
+ this.cache.set(key, {
1119
+ key,
1120
+ value
1121
+ });
1122
+ }
1123
+ get(key) {
1124
+ const item = this.cache.get(key);
1125
+ if (item) {
1126
+ this.cache.delete(key);
1127
+ this.cache.set(key, item);
1128
+ return item.value;
1129
+ }
1130
+ return undefined;
1131
+ }
1132
+ }
1133
+
1134
+ const require$2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href)));
1135
+ class MessageExtractor {
1136
+ compileCache = new LRUCache(750);
1137
+ constructor(opts) {
1138
+ this.isDevelopment = opts.isDevelopment ?? false;
1139
+ this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot();
1140
+ this.sourceMap = opts.sourceMap ?? false;
1141
+ }
1142
+ async extract(absoluteFilePath, source) {
1143
+ const cacheKey = [source, absoluteFilePath].join('!');
1144
+ const cached = this.compileCache.get(cacheKey);
1145
+ if (cached) return cached;
1146
+
1147
+ // Shortcut parsing if hook is not used. The Turbopack integration already
1148
+ // pre-filters this, but for webpack this feature doesn't exist, so we need
1149
+ // to do it here.
1150
+ if (!source.includes('useExtracted') && !source.includes('getExtracted')) {
1151
+ return {
1152
+ messages: [],
1153
+ code: source
1154
+ };
1155
+ }
1156
+ const filePath = normalizePathToPosix(path__default.default.relative(this.projectRoot, absoluteFilePath));
1157
+ const result = await core.transform(source, {
1158
+ jsc: {
1159
+ target: 'esnext',
1160
+ parser: {
1161
+ syntax: 'typescript',
1162
+ tsx: true,
1163
+ decorators: true
1164
+ },
1165
+ experimental: {
1166
+ cacheRoot: 'node_modules/.cache/swc',
1167
+ disableBuiltinTransformsForInternalTesting: true,
1168
+ disableAllLints: true,
1169
+ plugins: [[require$2.resolve('next-intl-swc-plugin-extractor'), {
1170
+ isDevelopment: this.isDevelopment,
1171
+ filePath
1172
+ }]]
1173
+ }
1174
+ },
1175
+ sourceMaps: this.sourceMap,
1176
+ sourceFileName: filePath,
1177
+ filename: filePath
1178
+ });
1179
+
1180
+ // TODO: Improve the typing of @swc/core
1181
+ const output = result.output;
1182
+ // The plugin emits a tagged union of extracted messages and
1183
+ // `useTranslations` usages; this extractor only consumes the former.
1184
+ const messages = JSON.parse(JSON.parse(output).results).filter(item => item.type === 'extracted').map(item => ({
1185
+ id: item.id,
1186
+ message: item.message,
1187
+ description: item.description,
1188
+ reference: item.reference
1189
+ }));
1190
+ const extractionResult = {
1191
+ code: result.code,
1192
+ map: result.map,
1193
+ messages
1194
+ };
1195
+ this.compileCache.set(cacheKey, extractionResult);
1196
+ return extractionResult;
1197
+ }
1198
+ }
1199
+
1200
+ class ExtractionCompiler {
1201
+ constructor(config, opts = {}) {
1202
+ const extractor = opts.extractor ?? new MessageExtractor(opts);
1203
+ this.manager = new CatalogManager(config, {
1204
+ ...opts,
1205
+ extractor
1206
+ });
1207
+ this[Symbol.dispose] = this[Symbol.dispose].bind(this);
1208
+ this.installExitHandlers();
1209
+ }
1210
+ async extractAll() {
1211
+ // We can't rely on all files being compiled (e.g. due to persistent
1212
+ // caching), so loading the messages initially is necessary.
1213
+ await this.manager.loadMessages();
1214
+ await this.manager.save();
1215
+ }
1216
+ [Symbol.dispose]() {
1217
+ this.uninstallExitHandlers();
1218
+ this.manager[Symbol.dispose]();
1219
+ }
1220
+ installExitHandlers() {
1221
+ const cleanup = this[Symbol.dispose];
1222
+ process.on('exit', cleanup);
1223
+ process.on('SIGINT', cleanup);
1224
+ process.on('SIGTERM', cleanup);
1225
+ }
1226
+ uninstallExitHandlers() {
1227
+ const cleanup = this[Symbol.dispose];
1228
+ process.off('exit', cleanup);
1229
+ process.off('SIGINT', cleanup);
1230
+ process.off('SIGTERM', cleanup);
1231
+ }
1232
+ }
1233
+
1234
+ // Avoid rollup's `replace` plugin to compile this away
1235
+ const nodeEnvKey = 'NODE_ENV'.trim();
1236
+
1237
+ // We avoid reading `argv.includes('dev')` related to
1238
+ // https://github.com/amannn/next-intl/issues/2006
1239
+ const isDevelopment = process.env[nodeEnvKey] === 'development';
1240
+ const isNextBuild = process.argv.includes('build');
1241
+ const isDevelopmentOrNextBuild = isDevelopment || isNextBuild;
1242
+
1243
+ // Single compiler instance, initialized once per process
1244
+ let compiler;
1245
+ const runOnce = once('_NEXT_INTL_EXTRACT');
1246
+ function initExtractionCompiler(extractorConfig) {
1247
+ if (!extractorConfig || !hasLocalesToExtract(extractorConfig)) {
1248
+ return;
1249
+ }
1250
+
1251
+ // Avoid running for:
1252
+ // - info
1253
+ // - start
1254
+ // - typegen
1255
+ //
1256
+ // Doesn't consult Next.js config anyway:
1257
+ // - lint
1258
+ // - telemetry (however, the `detached-flush` DOES - see `createNextIntlPlugin`)
1259
+ //
1260
+ // What remains are:
1261
+ // - dev (NODE_ENV=development)
1262
+ // - build (NODE_ENV=production)
1263
+ const shouldRun = isDevelopment || isNextBuild;
1264
+ if (!shouldRun) return;
1265
+ runOnce(() => {
1266
+ compiler = new ExtractionCompiler(extractorConfig, {
1267
+ isDevelopment,
1268
+ projectRoot: process.cwd()
1269
+ });
1270
+
1271
+ // Fire-and-forget: Start extraction, don't block config return.
1272
+ // In dev mode, this also starts the file watcher.
1273
+ // In prod, ideally we would wait until the extraction is complete,
1274
+ // but we can't `await` anywhere (at least for Turbopack).
1275
+ // The result is ok though, as if we encounter untranslated messages,
1276
+ // we'll simply add empty messages to the catalog. So for actually
1277
+ // running the app, there is no difference.
1278
+ compiler.extractAll();
1279
+ function cleanup() {
1280
+ if (compiler) {
1281
+ compiler[Symbol.dispose]();
1282
+ compiler = undefined;
1283
+ }
1284
+ }
1285
+ process.on('exit', cleanup);
1286
+ process.on('SIGINT', cleanup);
1287
+ process.on('SIGTERM', cleanup);
1288
+ });
1289
+ }
1290
+
1291
+ function getCurrentVersion() {
1292
+ try {
1293
+ const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href)));
1294
+ const pkg = require$1('next/package.json');
1295
+ return pkg.version;
1296
+ } catch (error) {
1297
+ throw new Error('Failed to get current Next.js version. This can happen if next-intl/plugin is imported into your app code outside of your next.config.js.', {
1298
+ cause: error
1299
+ });
1300
+ }
1301
+ }
1302
+ function compareVersions(version1, version2) {
1303
+ const v1Parts = version1.split('.').map(Number);
1304
+ const v2Parts = version2.split('.').map(Number);
1305
+ for (let i = 0; i < 3; i++) {
1306
+ const v1 = v1Parts[i] || 0;
1307
+ const v2 = v2Parts[i] || 0;
1308
+ if (v1 > v2) return 1;
1309
+ if (v1 < v2) return -1;
1310
+ }
1311
+ return 0;
1312
+ }
1313
+ function hasStableTurboConfig() {
1314
+ return compareVersions(getCurrentVersion(), '15.3.0') >= 0;
1315
+ }
1316
+ function isNextJs16OrHigher() {
1317
+ return compareVersions(getCurrentVersion(), '16.0.0') >= 0;
1318
+ }
1319
+
1320
+ const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugin.cjs', document.baseURI).href)));
1321
+ function withExtensions(localPath) {
1322
+ return [`${localPath}.ts`, `${localPath}.tsx`, `${localPath}.js`, `${localPath}.jsx`];
1323
+ }
1324
+ function normalizeTurbopackAliasPath(pathname) {
1325
+ // Turbopack alias targets should use forward slashes; Windows backslashes can
1326
+ // break resolution in dev (see `next-intl/config` alias path style).
1327
+ return pathname.replace(/\\/g, '/');
1328
+ }
1329
+ function resolveI18nPath(providedPath, cwd) {
1330
+ function resolvePath(pathname) {
1331
+ const parts = [];
1332
+ if (cwd) parts.push(cwd);
1333
+ parts.push(pathname);
1334
+ return path__default.default.resolve(...parts);
1335
+ }
1336
+ function pathExists(pathname) {
1337
+ return fs__default.default.existsSync(resolvePath(pathname));
1338
+ }
1339
+ if (providedPath) {
1340
+ // We use the `isNextDevOrBuild` condition to avoid throwing errors
1341
+ // if `next.config.ts` is read by a non-Next.js process.
1342
+ // https://github.com/amannn/next-intl/discussions/2209#discussioncomment-15650927
1343
+ if (isDevelopmentOrNextBuild && !pathExists(providedPath)) {
1344
+ throwError(`Could not find i18n config at ${providedPath}, please provide a valid path.`);
1345
+ }
1346
+ return providedPath;
1347
+ } else {
1348
+ for (const candidate of [...withExtensions('./i18n/request'), ...withExtensions('./src/i18n/request')]) {
1349
+ if (pathExists(candidate)) {
1350
+ return candidate;
1351
+ }
1352
+ }
1353
+ if (isDevelopmentOrNextBuild) {
1354
+ throwError(`Could not locate request configuration module.\n\nThis path is supported by default: ./(src/)i18n/request.{js,jsx,ts,tsx}\n\nAlternatively, you can specify a custom location in your Next.js config:\n\nconst withNextIntl = createNextIntlPlugin(\n './path/to/i18n/request.tsx'\n);`);
1355
+ }
1356
+
1357
+ // Default as fallback
1358
+ if (pathExists('./src')) {
1359
+ return './src/i18n/request.ts';
1360
+ } else {
1361
+ return './i18n/request.ts';
1362
+ }
1363
+ }
1364
+ }
1365
+ function getNextConfig(pluginConfig, nextConfig, extractorConfig) {
1366
+ const useTurbo = process.env.TURBOPACK != null;
1367
+
1368
+ // `experimental-analyze` doesn’t set the TURBOPACK env param. Since Next.js
1369
+ // 16 doesn't print a warning when we configure both Turbo- and Webpack, just
1370
+ // always configure Turbopack just in case.
1371
+ const shouldConfigureTurbo = useTurbo || isNextJs16OrHigher();
1372
+ const nextIntlConfig = {};
1373
+ let messageLoadPaths = [];
1374
+ if (pluginConfig.experimental?.messages) {
1375
+ messageLoadPaths = normalizeMessagesCatalogPaths(pluginConfig.experimental.messages.path);
1376
+ }
1377
+ function getExtractMessagesLoaderConfig(config) {
1378
+ return {
1379
+ loader: 'next-intl/extractor/extractionLoader',
1380
+ options: config
1381
+ };
1382
+ }
1383
+ function getCatalogLoaderConfig() {
1384
+ const experimental = pluginConfig.experimental;
1385
+ const messages = experimental.messages;
1386
+ // Normalization enforces a source locale before extraction runs.
1387
+ const sourceLocale = messages.sourceLocale ?? (typeof experimental.extract === 'object' ? experimental.extract.sourceLocale : undefined);
1388
+ return {
1389
+ loader: 'next-intl/extractor/catalogLoader',
1390
+ options: {
1391
+ messages: {
1392
+ format: messages.format,
1393
+ ...(messages.precompile !== undefined && {
1394
+ precompile: messages.precompile
1395
+ }),
1396
+ sourceLocale
1397
+ }
1398
+ }
1399
+ };
1400
+ }
1401
+ function getTurboRules() {
1402
+ return nextConfig?.turbopack?.rules ||
1403
+ // @ts-expect-error -- For Next.js <16
1404
+ nextConfig?.experimental?.turbo?.rules || {};
1405
+ }
1406
+ function addTurboRule(rules, glob, rule) {
1407
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1408
+ if (rules[glob]) {
1409
+ if (Array.isArray(rules[glob])) {
1410
+ rules[glob].push(rule);
1411
+ } else {
1412
+ rules[glob] = [rules[glob], rule];
1413
+ }
1414
+ } else {
1415
+ rules[glob] = rule;
1416
+ }
1417
+ }
1418
+ if (shouldConfigureTurbo) {
1419
+ if (pluginConfig.requestConfig && path__default.default.isAbsolute(pluginConfig.requestConfig)) {
1420
+ throwError("Turbopack support for next-intl currently does not support absolute paths, please provide a relative one (e.g. './src/i18n/config.ts').\n\nFound: " + pluginConfig.requestConfig);
1421
+ }
1422
+
1423
+ // Assign alias for `next-intl/config`
1424
+ const resolveAlias = {
1425
+ // Turbo aliases don't work with absolute
1426
+ // paths (see error handling above)
1427
+ 'next-intl/config': resolveI18nPath(pluginConfig.requestConfig)
1428
+ };
1429
+
1430
+ // Add alias for precompiled message formatting
1431
+ if (pluginConfig.experimental?.messages?.precompile) {
1432
+ // Workaround for https://github.com/vercel/next.js/issues/88540
1433
+ let formatOnlyPath = path__default.default.relative(process.cwd(), require$1.resolve('use-intl/format-message/format-only'));
1434
+
1435
+ // Turbopack seems to require this, otherwise `use-intl/format-message` is
1436
+ // still bundled (despite the code correctly calling into `format-only`).
1437
+ // Note that in this monorepo this is not necessary, because we'll end
1438
+ // up with a path like `../…` — but for actual consumers this is required.
1439
+ if (!formatOnlyPath.startsWith('.')) {
1440
+ formatOnlyPath = `./${formatOnlyPath}`;
1441
+ }
1442
+ resolveAlias['use-intl/format-message'] = normalizeTurbopackAliasPath(formatOnlyPath);
1443
+ }
1444
+
1445
+ // Add loaders
1446
+ let rules;
1447
+
1448
+ // Add loader for extractor
1449
+ if (pluginConfig.experimental?.extract) {
1450
+ if (!isNextJs16OrHigher()) {
1451
+ throwError('Message extraction requires Next.js 16 or higher.');
1452
+ }
1453
+ rules ??= getTurboRules();
1454
+ addTurboRule(rules, `*.{${SourceFileFilter.EXTENSIONS.join(',')}}`, {
1455
+ loaders: [getExtractMessagesLoaderConfig(extractorConfig)],
1456
+ condition: {
1457
+ // We don't filter for `path` here to allow transformation
1458
+ // of `useExtracted` calls in external packages (e.g. monorepos)
1459
+ content: /(useExtracted|getExtracted)/
1460
+ }
1461
+ });
1462
+ }
1463
+
1464
+ // Add loader for catalog
1465
+ if (pluginConfig.experimental?.messages) {
1466
+ if (!isNextJs16OrHigher()) {
1467
+ throwError('Message catalog loading requires Next.js 16 or higher.');
1468
+ }
1469
+ rules ??= getTurboRules();
1470
+ const extension = getFormatExtension(pluginConfig.experimental.messages.format);
1471
+ addTurboRule(rules, `*${extension}`, {
1472
+ loaders: [getCatalogLoaderConfig()],
1473
+ condition: {
1474
+ path: `{${messageLoadPaths.join(',')}}/**/*`
1475
+ },
1476
+ as: '*.js'
1477
+ });
1478
+ }
1479
+ if (hasStableTurboConfig() &&
1480
+ // @ts-expect-error -- For Next.js <16
1481
+ !nextConfig?.experimental?.turbo) {
1482
+ nextIntlConfig.turbopack = {
1483
+ ...nextConfig?.turbopack,
1484
+ ...(rules && {
1485
+ rules
1486
+ }),
1487
+ resolveAlias: {
1488
+ ...nextConfig?.turbopack?.resolveAlias,
1489
+ ...resolveAlias
1490
+ }
1491
+ };
1492
+ } else {
1493
+ nextIntlConfig.experimental = {
1494
+ ...nextConfig?.experimental,
1495
+ // @ts-expect-error -- For Next.js <16
1496
+ turbo: {
1497
+ // @ts-expect-error -- For Next.js <16
1498
+ ...nextConfig?.experimental?.turbo,
1499
+ ...(rules && {
1500
+ rules
1501
+ }),
1502
+ resolveAlias: {
1503
+ // @ts-expect-error -- For Next.js <16
1504
+ ...nextConfig?.experimental?.turbo?.resolveAlias,
1505
+ ...resolveAlias
1506
+ }
1507
+ }
1508
+ };
1509
+ }
1510
+ }
1511
+ if (!useTurbo) {
1512
+ nextIntlConfig.webpack = function webpack(config, context) {
1513
+ if (!config.resolve) config.resolve = {};
1514
+ if (!config.resolve.alias) config.resolve.alias = {};
1515
+
1516
+ // Assign alias for `next-intl/config`
1517
+ // (Webpack requires absolute paths)
1518
+ config.resolve.alias['next-intl/config'] = path__default.default.resolve(config.context, resolveI18nPath(pluginConfig.requestConfig, config.context));
1519
+
1520
+ // Add alias for precompiled message formatting
1521
+ if (pluginConfig.experimental?.messages?.precompile) {
1522
+ // Use require.resolve to get the actual file path, since
1523
+ // bundlers don't properly resolve package subpath exports
1524
+ // when used as alias targets
1525
+ config.resolve.alias['use-intl/format-message'] = require$1.resolve('use-intl/format-message/format-only');
1526
+ }
1527
+
1528
+ // Add loader for extractor
1529
+ if (pluginConfig.experimental?.extract) {
1530
+ if (!config.module) config.module = {};
1531
+ if (!config.module.rules) config.module.rules = [];
1532
+ config.module.rules.push({
1533
+ test: new RegExp(`\\.(${SourceFileFilter.EXTENSIONS.join('|')})$`),
1534
+ use: [getExtractMessagesLoaderConfig(extractorConfig)]
1535
+ });
1536
+ }
1537
+
1538
+ // Add loader for catalog
1539
+ if (pluginConfig.experimental?.messages) {
1540
+ if (!config.module) config.module = {};
1541
+ if (!config.module.rules) config.module.rules = [];
1542
+ const extension = getFormatExtension(pluginConfig.experimental.messages.format);
1543
+ config.module.rules.push({
1544
+ test: new RegExp(`${extension.replace(/\./g, '\\.')}$`),
1545
+ include: messageLoadPaths.map(dirPath => path__default.default.resolve(config.context, dirPath)),
1546
+ use: [getCatalogLoaderConfig()],
1547
+ type: 'javascript/auto'
1548
+ });
1549
+ }
1550
+ if (typeof nextConfig?.webpack === 'function') {
1551
+ return nextConfig.webpack(config, context);
1552
+ }
1553
+ return config;
1554
+ };
1555
+ }
1556
+
1557
+ // Forward config
1558
+ if (nextConfig?.trailingSlash) {
1559
+ nextIntlConfig.env = {
1560
+ ...nextConfig.env,
1561
+ _next_intl_trailing_slash: 'true'
1562
+ };
1563
+ }
1564
+ return Object.assign({}, nextConfig, nextIntlConfig);
1565
+ }
1566
+
1567
+ function initPlugin(pluginConfig, nextConfig) {
1568
+ if (nextConfig?.i18n != null) {
1569
+ warn("An `i18n` property was found in your Next.js config. This likely causes conflicts and should therefore be removed if you use the App Router.\n\nIf you're in progress of migrating from the Pages Router, you can refer to this example: https://next-intl.dev/examples#app-router-migration\n");
1570
+ }
1571
+ const skipWatchers = isNextTelemetryDetachedFlushProcess();
1572
+ const messagesPathOrPaths = pluginConfig.experimental?.createMessagesDeclaration;
1573
+ if (messagesPathOrPaths && !skipWatchers) {
1574
+ createMessagesDeclaration(typeof messagesPathOrPaths === 'string' ? [messagesPathOrPaths] : messagesPathOrPaths);
1575
+ }
1576
+ let extractorConfig;
1577
+ const experimental = pluginConfig.experimental;
1578
+ const extract = experimental?.extract;
1579
+ if (extract) {
1580
+ extractorConfig = normalizeExtractorConfig({
1581
+ extract,
1582
+ messages: experimental.messages,
1583
+ srcPath: experimental.srcPath
1584
+ });
1585
+ }
1586
+ if (!skipWatchers) {
1587
+ initExtractionCompiler(extractorConfig);
1588
+ }
1589
+ return getNextConfig(pluginConfig, nextConfig, extractorConfig);
1590
+ }
1591
+ function createNextIntlPlugin(i18nPathOrConfig = {}) {
1592
+ const config = typeof i18nPathOrConfig === 'string' ? {
1593
+ requestConfig: i18nPathOrConfig
1594
+ } : i18nPathOrConfig;
1595
+ return function withNextIntl(nextConfig) {
1596
+ return initPlugin(config, nextConfig);
1597
+ };
1598
+ }
1599
+
1600
+ /**
1601
+ * Next runs `telemetry/detached-flush.js` in a detached process to flush telemetry
1602
+ * (often when `next dev` exits). That loads dev `next.config` with inherited
1603
+ * `NODE_ENV=development`, which would otherwise start orphan plugin watchers.
1604
+ */
1605
+ function isNextTelemetryDetachedFlushProcess() {
1606
+ const scriptPath = process.argv[1];
1607
+ if (!scriptPath) return false;
1608
+ const normalized = scriptPath.replace(/\\/g, '/');
1609
+ return normalized.includes('/telemetry/detached-flush');
1610
+ }
1611
+
1612
+ module.exports = createNextIntlPlugin;