@lingui/macro 4.8.0-next.0 → 4.8.0-next.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/dist/index.cjs CHANGED
@@ -1,1007 +1,36 @@
1
1
  'use strict';
2
2
 
3
3
  const babelPluginMacros = require('babel-plugin-macros');
4
- const conf = require('@lingui/conf');
5
- const t = require('@babel/types');
6
- const generateMessageId = require('@lingui/message-utils/generateMessageId');
7
-
8
- function _interopNamespaceCompat(e) {
9
- if (e && typeof e === 'object' && 'default' in e) return e;
10
- const n = Object.create(null);
11
- if (e) {
12
- for (const k in e) {
13
- n[k] = e[k];
14
- }
15
- }
16
- n.default = e;
17
- return n;
18
- }
19
-
20
- const t__namespace = /*#__PURE__*/_interopNamespaceCompat(t);
21
-
22
- const metaOptions = ["id", "comment", "props"];
23
- const escapedMetaOptionsRe = new RegExp(`^_(${metaOptions.join("|")})$`);
24
- class ICUMessageFormat {
25
- fromTokens(tokens) {
26
- return (Array.isArray(tokens) ? tokens : [tokens]).map((token) => this.processToken(token)).filter(Boolean).reduce(
27
- (props, message) => ({
28
- ...message,
29
- message: props.message + message.message,
30
- values: { ...props.values, ...message.values },
31
- jsxElements: { ...props.jsxElements, ...message.jsxElements }
32
- }),
33
- {
34
- message: "",
35
- values: {},
36
- jsxElements: {}
37
- }
38
- );
39
- }
40
- processToken(token) {
41
- const jsxElements = {};
42
- if (token.type === "text") {
43
- return {
44
- message: token.value
45
- };
46
- } else if (token.type === "arg") {
47
- if (token.value !== void 0 && t.isJSXEmptyExpression(token.value)) {
48
- return null;
49
- }
50
- const values = token.value !== void 0 ? { [token.name]: token.value } : {};
51
- switch (token.format) {
52
- case "plural":
53
- case "select":
54
- case "selectordinal":
55
- const formatOptions = Object.keys(token.options).filter((key) => token.options[key] != null).map((key) => {
56
- let value = token.options[key];
57
- key = key.replace(escapedMetaOptionsRe, "$1");
58
- if (key === "offset") {
59
- return `offset:${value}`;
60
- }
61
- if (typeof value !== "string") {
62
- const {
63
- message,
64
- values: childValues,
65
- jsxElements: childJsxElements
66
- } = this.fromTokens(value);
67
- Object.assign(values, childValues);
68
- Object.assign(jsxElements, childJsxElements);
69
- value = message;
70
- }
71
- return `${key} {${value}}`;
72
- }).join(" ");
73
- return {
74
- message: `{${token.name}, ${token.format}, ${formatOptions}}`,
75
- values,
76
- jsxElements
77
- };
78
- default:
79
- return {
80
- message: `{${token.name}}`,
81
- values
82
- };
83
- }
84
- } else if (token.type === "element") {
85
- let message = "";
86
- let elementValues = {};
87
- Object.assign(jsxElements, { [token.name]: token.value });
88
- token.children.forEach((child) => {
89
- const {
90
- message: childMessage,
91
- values: childValues,
92
- jsxElements: childJsxElements
93
- } = this.fromTokens(child);
94
- message += childMessage;
95
- Object.assign(elementValues, childValues);
96
- Object.assign(jsxElements, childJsxElements);
97
- });
98
- return {
99
- message: token.children.length ? `<${token.name}>${message}</${token.name}>` : `<${token.name}/>`,
100
- values: elementValues,
101
- jsxElements
102
- };
103
- }
104
- throw new Error(`Unknown token type ${token.type}`);
105
- }
106
- }
107
-
108
- const makeCounter = (index = 0) => () => index++;
109
-
110
- const ID = "id";
111
- const MESSAGE = "message";
112
- const COMMENT = "comment";
113
- const EXTRACT_MARK = "i18n";
114
- const CONTEXT = "context";
115
-
116
- var __defProp$1 = Object.defineProperty;
117
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118
- var __publicField$1 = (obj, key, value) => {
119
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
120
- return value;
121
- };
122
- const keepSpaceRe$1 = /(?:\\(?:\r\n|\r|\n))+\s+/g;
123
- const keepNewLineRe = /(?:\r\n|\r|\n)+\s+/g;
124
- function normalizeWhitespace$1(text) {
125
- return text.replace(keepSpaceRe$1, " ").replace(keepNewLineRe, "\n").trim();
126
- }
127
- function buildICUFromTokens(tokens) {
128
- const messageFormat = new ICUMessageFormat();
129
- const { message, values } = messageFormat.fromTokens(tokens);
130
- return { message: normalizeWhitespace$1(message), values };
131
- }
132
- class MacroJs {
133
- constructor({ types }, opts) {
134
- // Babel Types
135
- __publicField$1(this, "types");
136
- // Identifier of i18n object
137
- __publicField$1(this, "i18nImportName");
138
- __publicField$1(this, "stripNonEssentialProps");
139
- __publicField$1(this, "nameMap");
140
- __publicField$1(this, "nameMapReversed");
141
- __publicField$1(this, "needsUseLinguiImport", false);
142
- __publicField$1(this, "needsI18nImport", false);
143
- // Positional expressions counter (e.g. for placeholders `Hello {0}, today is {1}`)
144
- __publicField$1(this, "_expressionIndex", makeCounter());
145
- __publicField$1(this, "replacePathWithMessage", (path, tokens, linguiInstance) => {
146
- const newNode = this.createI18nCall(
147
- this.createMessageDescriptorFromTokens(tokens, path.node.loc),
148
- linguiInstance
149
- );
150
- path.replaceWith(newNode);
151
- });
152
- // Returns a boolean indicating if the replacement requires i18n import
153
- __publicField$1(this, "replacePath", (path) => {
154
- this._expressionIndex = makeCounter();
155
- if (this.types.isCallExpression(path.node) && this.isDefineMessage(path.node.callee)) {
156
- let descriptor = this.processDescriptor(path.node.arguments[0]);
157
- path.replaceWith(descriptor);
158
- return false;
159
- }
160
- if (this.types.isTaggedTemplateExpression(path.node) && this.isDefineMessage(path.node.tag)) {
161
- const tokens2 = this.tokenizeTemplateLiteral(path.node.quasi);
162
- const descriptor = this.createMessageDescriptorFromTokens(
163
- tokens2,
164
- path.node.loc
165
- );
166
- path.replaceWith(descriptor);
167
- return false;
168
- }
169
- if (this.types.isCallExpression(path.node) && this.types.isTaggedTemplateExpression(path.parentPath.node) && this.types.isExpression(path.node.arguments[0]) && this.isLinguiIdentifier(path.node.callee, "t")) {
170
- const i18nInstance = path.node.arguments[0];
171
- const tokens2 = this.tokenizeNode(path.parentPath.node);
172
- this.replacePathWithMessage(path.parentPath, tokens2, i18nInstance);
173
- return false;
174
- }
175
- if (this.types.isCallExpression(path.node) && this.types.isCallExpression(path.parentPath.node) && this.types.isExpression(path.node.arguments[0]) && path.parentPath.node.callee === path.node && this.isLinguiIdentifier(path.node.callee, "t")) {
176
- const i18nInstance = path.node.arguments[0];
177
- this.replaceTAsFunction(
178
- path.parentPath,
179
- i18nInstance
180
- );
181
- return false;
182
- }
183
- if (this.types.isCallExpression(path.node) && this.isLinguiIdentifier(path.node.callee, "t")) {
184
- this.replaceTAsFunction(path);
185
- this.needsI18nImport = true;
186
- return true;
187
- }
188
- if (path.isTaggedTemplateExpression() && this.isLinguiIdentifier(path.node.tag, "_t")) {
189
- this.needsUseLinguiImport = true;
190
- const tokens2 = this.tokenizeTemplateLiteral(path.node);
191
- const descriptor = this.createMessageDescriptorFromTokens(
192
- tokens2,
193
- path.node.loc
194
- );
195
- const callExpr = this.types.callExpression(
196
- this.types.isIdentifier(path.node.tag) && path.node.tag,
197
- [descriptor]
198
- );
199
- path.replaceWith(callExpr);
200
- return false;
201
- }
202
- if (path.isCallExpression() && this.isLinguiIdentifier(path.node.callee, "_t") && this.types.isExpression(path.node.arguments[0])) {
203
- this.needsUseLinguiImport = true;
204
- let descriptor = this.processDescriptor(path.node.arguments[0]);
205
- path.node.arguments = [descriptor];
206
- return false;
207
- }
208
- if (this.types.isCallExpression(path.node) && this.isLinguiIdentifier(path.node.callee, "useLingui") && this.types.isVariableDeclarator(path.parentPath.node)) {
209
- this.needsUseLinguiImport = true;
210
- return false;
211
- }
212
- const tokens = this.tokenizeNode(path.node);
213
- this.replacePathWithMessage(path, tokens);
214
- this.needsI18nImport = true;
215
- return true;
216
- });
217
- /**
218
- * macro `t` is called with MessageDescriptor, after that
219
- * we create a new node to append it to i18n._
220
- */
221
- __publicField$1(this, "replaceTAsFunction", (path, linguiInstance) => {
222
- const descriptor = this.processDescriptor(path.node.arguments[0]);
223
- path.replaceWith(this.createI18nCall(descriptor, linguiInstance));
224
- });
225
- /**
226
- * `processDescriptor` expand macros inside message descriptor.
227
- * Message descriptor is used in `defineMessage`.
228
- *
229
- * {
230
- * comment: "Description",
231
- * message: plural("value", { one: "book", other: "books" })
232
- * }
233
- *
234
- * ↓ ↓ ↓ ↓ ↓ ↓
235
- *
236
- * {
237
- * comment: "Description",
238
- * id: <hash>
239
- * message: "{value, plural, one {book} other {books}}"
240
- * }
241
- *
242
- */
243
- __publicField$1(this, "processDescriptor", (descriptor_) => {
244
- const descriptor = descriptor_;
245
- const messageProperty = this.getObjectPropertyByKey(descriptor, MESSAGE);
246
- const idProperty = this.getObjectPropertyByKey(descriptor, ID);
247
- const contextProperty = this.getObjectPropertyByKey(descriptor, CONTEXT);
248
- const properties = [idProperty];
249
- if (!this.stripNonEssentialProps) {
250
- properties.push(contextProperty);
251
- }
252
- if (messageProperty) {
253
- const tokens = this.types.isTemplateLiteral(messageProperty.value) ? this.tokenizeTemplateLiteral(messageProperty.value) : this.tokenizeNode(messageProperty.value, true);
254
- let messageNode = messageProperty.value;
255
- if (tokens) {
256
- const { message, values } = buildICUFromTokens(tokens);
257
- messageNode = this.types.stringLiteral(message);
258
- properties.push(this.createValuesProperty(values));
259
- }
260
- if (!this.stripNonEssentialProps) {
261
- properties.push(
262
- this.createObjectProperty(MESSAGE, messageNode)
263
- );
264
- }
265
- if (!idProperty && this.types.isStringLiteral(messageNode)) {
266
- const context = contextProperty && this.getTextFromExpression(contextProperty.value);
267
- properties.push(this.createIdProperty(messageNode.value, context));
268
- }
269
- }
270
- if (!this.stripNonEssentialProps) {
271
- properties.push(this.getObjectPropertyByKey(descriptor, COMMENT));
272
- }
273
- return this.createMessageDescriptor(properties, descriptor.loc);
274
- });
275
- this.types = types;
276
- this.i18nImportName = opts.i18nImportName;
277
- this.stripNonEssentialProps = opts.stripNonEssentialProps;
278
- this.nameMap = opts.nameMap;
279
- this.nameMapReversed = Array.from(opts.nameMap.entries()).reduce(
280
- (map, [key, value]) => map.set(value, key),
281
- /* @__PURE__ */ new Map()
282
- );
283
- }
284
- createIdProperty(message, context) {
285
- return this.createObjectProperty(
286
- ID,
287
- this.types.stringLiteral(generateMessageId.generateMessageId(message, context))
288
- );
289
- }
290
- createValuesProperty(values) {
291
- const valuesObject = Object.keys(values).map(
292
- (key) => this.types.objectProperty(this.types.identifier(key), values[key])
293
- );
294
- if (!valuesObject.length)
295
- return;
296
- return this.types.objectProperty(
297
- this.types.identifier("values"),
298
- this.types.objectExpression(valuesObject)
299
- );
300
- }
301
- tokenizeNode(node, ignoreExpression = false) {
302
- if (this.isI18nMethod(node)) {
303
- return this.tokenizeTemplateLiteral(node);
304
- } else if (this.isChoiceMethod(node)) {
305
- return [this.tokenizeChoiceComponent(node)];
306
- } else if (!ignoreExpression) {
307
- return [this.tokenizeExpression(node)];
308
- }
309
- }
310
- /**
311
- * `node` is a TemplateLiteral. node.quasi contains
312
- * text chunks and node.expressions contains expressions.
313
- * Both arrays must be zipped together to get the final list of tokens.
314
- */
315
- tokenizeTemplateLiteral(node) {
316
- const tpl = this.types.isTaggedTemplateExpression(node) ? node.quasi : node;
317
- const expressions = tpl.expressions;
318
- return tpl.quasis.flatMap((text, i) => {
319
- const value = /\\u[a-fA-F0-9]{4}|\\x[a-fA-F0-9]{2}/g.test(text.value.raw) ? text.value.cooked : text.value.raw;
320
- let argTokens = [];
321
- const currExp = expressions[i];
322
- if (currExp) {
323
- argTokens = this.types.isCallExpression(currExp) ? this.tokenizeNode(currExp) : [this.tokenizeExpression(currExp)];
324
- }
325
- const textToken = {
326
- type: "text",
327
- value: this.clearBackslashes(value)
328
- };
329
- return [...value ? [textToken] : [], ...argTokens];
330
- });
331
- }
332
- tokenizeChoiceComponent(node) {
333
- const name = node.callee.name;
334
- const format = (this.nameMapReversed.get(name) || name).toLowerCase();
335
- const token = {
336
- ...this.tokenizeExpression(node.arguments[0]),
337
- format,
338
- options: {
339
- offset: void 0
340
- }
341
- };
342
- const props = node.arguments[1].properties;
343
- for (const attr of props) {
344
- const { key, value: attrValue } = attr;
345
- const name2 = this.types.isNumericLiteral(key) ? `=${key.value}` : key.name || key.value;
346
- if (format !== "select" && name2 === "offset") {
347
- token.options.offset = attrValue.value;
348
- } else {
349
- let value;
350
- if (this.types.isTemplateLiteral(attrValue)) {
351
- value = this.tokenizeTemplateLiteral(attrValue);
352
- } else if (this.types.isCallExpression(attrValue)) {
353
- value = this.tokenizeNode(attrValue);
354
- } else if (this.types.isStringLiteral(attrValue)) {
355
- value = attrValue.value;
356
- } else if (this.types.isExpression(attrValue)) {
357
- value = this.tokenizeExpression(attrValue);
358
- } else {
359
- value = attrValue.value;
360
- }
361
- token.options[name2] = value;
362
- }
363
- }
364
- return token;
365
- }
366
- tokenizeExpression(node) {
367
- return {
368
- type: "arg",
369
- name: this.expressionToArgument(node),
370
- value: node
371
- };
372
- }
373
- expressionToArgument(exp) {
374
- if (this.types.isIdentifier(exp)) {
375
- return exp.name;
376
- } else if (this.types.isStringLiteral(exp)) {
377
- return exp.value;
378
- } else {
379
- return String(this._expressionIndex());
380
- }
381
- }
382
- /**
383
- * We clean '//\` ' to just '`'
384
- */
385
- clearBackslashes(value) {
386
- return value.replace(/\\`/g, "`");
387
- }
388
- createI18nCall(messageDescriptor, linguiInstance) {
389
- return this.types.callExpression(
390
- this.types.memberExpression(
391
- linguiInstance ?? this.types.identifier(this.i18nImportName),
392
- this.types.identifier("_")
393
- ),
394
- [messageDescriptor]
395
- );
396
- }
397
- createMessageDescriptorFromTokens(tokens, oldLoc) {
398
- const { message, values } = buildICUFromTokens(tokens);
399
- const properties = [
400
- this.createIdProperty(message),
401
- !this.stripNonEssentialProps ? this.createObjectProperty(MESSAGE, this.types.stringLiteral(message)) : null,
402
- this.createValuesProperty(values)
403
- ];
404
- return this.createMessageDescriptor(
405
- properties,
406
- // preserve line numbers for extractor
407
- oldLoc
408
- );
409
- }
410
- createMessageDescriptor(properties, oldLoc) {
411
- const newDescriptor = this.types.objectExpression(
412
- properties.filter(Boolean)
413
- );
414
- this.types.addComment(newDescriptor, "leading", EXTRACT_MARK);
415
- if (oldLoc) {
416
- newDescriptor.loc = oldLoc;
417
- }
418
- return newDescriptor;
419
- }
420
- createObjectProperty(key, value) {
421
- return this.types.objectProperty(this.types.identifier(key), value);
422
- }
423
- getObjectPropertyByKey(objectExp, key) {
424
- return objectExp.properties.find(
425
- (property) => t.isObjectProperty(property) && this.isLinguiIdentifier(property.key, key)
426
- );
427
- }
428
- /**
429
- * Custom matchers
430
- */
431
- isLinguiIdentifier(node, name) {
432
- return this.types.isIdentifier(node, {
433
- name: this.nameMap.get(name) || name
434
- });
435
- }
436
- isDefineMessage(node) {
437
- return this.isLinguiIdentifier(node, "defineMessage") || this.isLinguiIdentifier(node, "msg");
438
- }
439
- isI18nMethod(node) {
440
- return this.types.isTaggedTemplateExpression(node) && (this.isLinguiIdentifier(node.tag, "t") || this.types.isCallExpression(node.tag) && this.isLinguiIdentifier(node.tag.callee, "t"));
441
- }
442
- isChoiceMethod(node) {
443
- return this.types.isCallExpression(node) && (this.isLinguiIdentifier(node.callee, "plural") || this.isLinguiIdentifier(node.callee, "select") || this.isLinguiIdentifier(node.callee, "selectOrdinal"));
444
- }
445
- getTextFromExpression(exp) {
446
- if (this.types.isStringLiteral(exp)) {
447
- return exp.value;
448
- }
449
- if (this.types.isTemplateLiteral(exp)) {
450
- if (exp?.quasis.length === 1) {
451
- return exp.quasis[0]?.value?.cooked;
452
- }
453
- }
454
- }
455
- }
456
-
457
- var __defProp = Object.defineProperty;
458
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
459
- var __publicField = (obj, key, value) => {
460
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
461
- return value;
462
- };
463
- const pluralRuleRe = /(_[\d\w]+|zero|one|two|few|many|other)/;
464
- const jsx2icuExactChoice = (value) => value.replace(/_(\d+)/, "=$1").replace(/_(\w+)/, "$1");
465
- const keepSpaceRe = /\s*(?:\r\n|\r|\n)+\s*/g;
466
- const stripAroundTagsRe = /(?:([>}])(?:\r\n|\r|\n)+\s*|(?:\r\n|\r|\n)+\s*(?=[<{]))/g;
467
- function maybeNodeValue(node) {
468
- if (!node)
469
- return null;
470
- if (node.type === "StringLiteral")
471
- return node.value;
472
- if (node.type === "JSXAttribute")
473
- return maybeNodeValue(node.value);
474
- if (node.type === "JSXExpressionContainer")
475
- return maybeNodeValue(node.expression);
476
- if (node.type === "TemplateLiteral" && node.expressions.length === 0)
477
- return node.quasis[0].value.raw;
478
- return null;
479
- }
480
- function normalizeWhitespace(text) {
481
- return text.replace(stripAroundTagsRe, "$1").replace(keepSpaceRe, " ").replace(/\\n/g, "\n").replace(/\\s/g, " ").replace(/(\s+})/gm, "}").replace(/({\s+)/gm, "{").trim();
482
- }
483
- class MacroJSX {
484
- constructor({ types }, opts) {
485
- __publicField(this, "types");
486
- __publicField(this, "expressionIndex", makeCounter());
487
- __publicField(this, "elementIndex", makeCounter());
488
- __publicField(this, "stripNonEssentialProps");
489
- __publicField(this, "nameMap");
490
- __publicField(this, "nameMapReversed");
491
- __publicField(this, "createStringJsxAttribute", (name, value) => {
492
- return this.types.jsxAttribute(
493
- this.types.jsxIdentifier(name),
494
- this.types.jsxExpressionContainer(this.types.stringLiteral(value))
495
- );
496
- });
497
- __publicField(this, "replacePath", (path) => {
498
- if (!path.isJSXElement()) {
499
- return path;
500
- }
501
- const tokens = this.tokenizeNode(path);
502
- const messageFormat = new ICUMessageFormat();
503
- const {
504
- message: messageRaw,
505
- values,
506
- jsxElements
507
- } = messageFormat.fromTokens(tokens);
508
- const message = normalizeWhitespace(messageRaw);
509
- const { attributes, id, comment, context } = this.stripMacroAttributes(
510
- path
511
- );
512
- if (!id && !message) {
513
- return;
514
- }
515
- if (id) {
516
- attributes.push(
517
- this.types.jsxAttribute(
518
- this.types.jsxIdentifier(ID),
519
- this.types.stringLiteral(id)
520
- )
521
- );
522
- } else {
523
- attributes.push(
524
- this.createStringJsxAttribute(ID, generateMessageId.generateMessageId(message, context))
525
- );
526
- }
527
- if (!this.stripNonEssentialProps) {
528
- if (message) {
529
- attributes.push(this.createStringJsxAttribute(MESSAGE, message));
530
- }
531
- if (comment) {
532
- attributes.push(
533
- this.types.jsxAttribute(
534
- this.types.jsxIdentifier(COMMENT),
535
- this.types.stringLiteral(comment)
536
- )
537
- );
538
- }
539
- if (context) {
540
- attributes.push(
541
- this.types.jsxAttribute(
542
- this.types.jsxIdentifier(CONTEXT),
543
- this.types.stringLiteral(context)
544
- )
545
- );
546
- }
547
- }
548
- const valuesObject = Object.keys(values).map(
549
- (key) => this.types.objectProperty(this.types.identifier(key), values[key])
550
- );
551
- if (valuesObject.length) {
552
- attributes.push(
553
- this.types.jsxAttribute(
554
- this.types.jsxIdentifier("values"),
555
- this.types.jsxExpressionContainer(
556
- this.types.objectExpression(valuesObject)
557
- )
558
- )
559
- );
560
- }
561
- if (Object.keys(jsxElements).length) {
562
- attributes.push(
563
- this.types.jsxAttribute(
564
- this.types.jsxIdentifier("components"),
565
- this.types.jsxExpressionContainer(
566
- this.types.objectExpression(
567
- Object.keys(jsxElements).map(
568
- (key) => this.types.objectProperty(
569
- this.types.identifier(key),
570
- jsxElements[key]
571
- )
572
- )
573
- )
574
- )
575
- )
576
- );
577
- }
578
- const newNode = this.types.jsxElement(
579
- this.types.jsxOpeningElement(
580
- this.types.jsxIdentifier("Trans"),
581
- attributes,
582
- true
583
- ),
584
- null,
585
- [],
586
- true
587
- );
588
- newNode.loc = path.node.loc;
589
- path.replaceWith(newNode);
590
- });
591
- __publicField(this, "attrName", (names, exclude = false) => {
592
- const namesRe = new RegExp("^(" + names.join("|") + ")$");
593
- return (attr) => {
594
- const name = attr.name.name;
595
- return exclude ? !namesRe.test(name) : namesRe.test(name);
596
- };
597
- });
598
- __publicField(this, "stripMacroAttributes", (path) => {
599
- const { attributes } = path.node.openingElement;
600
- const id = attributes.find(this.attrName([ID]));
601
- const message = attributes.find(this.attrName([MESSAGE]));
602
- const comment = attributes.find(this.attrName([COMMENT]));
603
- const context = attributes.find(this.attrName([CONTEXT]));
604
- let reserved = [ID, MESSAGE, COMMENT, CONTEXT];
605
- if (this.isChoiceComponent(path)) {
606
- reserved = [
607
- ...reserved,
608
- "_\\w+",
609
- "_\\d+",
610
- "zero",
611
- "one",
612
- "two",
613
- "few",
614
- "many",
615
- "other",
616
- "value",
617
- "offset"
618
- ];
619
- }
620
- return {
621
- id: maybeNodeValue(id),
622
- message: maybeNodeValue(message),
623
- comment: maybeNodeValue(comment),
624
- context: maybeNodeValue(context),
625
- attributes: attributes.filter(this.attrName(reserved, true))
626
- };
627
- });
628
- __publicField(this, "tokenizeNode", (path) => {
629
- if (this.isTransComponent(path)) {
630
- return this.tokenizeTrans(path);
631
- } else if (this.isChoiceComponent(path)) {
632
- return [this.tokenizeChoiceComponent(path)];
633
- } else if (path.isJSXElement()) {
634
- return [this.tokenizeElement(path)];
635
- } else {
636
- return [this.tokenizeExpression(path)];
637
- }
638
- });
639
- __publicField(this, "tokenizeTrans", (path) => {
640
- return path.get("children").flatMap((child) => this.tokenizeChildren(child)).filter(Boolean);
641
- });
642
- __publicField(this, "tokenizeChildren", (path) => {
643
- if (path.isJSXExpressionContainer()) {
644
- const exp = path.get("expression");
645
- if (exp.isStringLiteral()) {
646
- return [this.tokenizeText(exp.node.value.replace(/\n/g, "\\n"))];
647
- }
648
- if (exp.isTemplateLiteral()) {
649
- return this.tokenizeTemplateLiteral(exp);
650
- }
651
- if (exp.isConditionalExpression()) {
652
- return [this.tokenizeConditionalExpression(exp)];
653
- }
654
- if (exp.isJSXElement()) {
655
- return this.tokenizeNode(exp);
656
- }
657
- return [this.tokenizeExpression(exp)];
658
- } else if (path.isJSXElement()) {
659
- return this.tokenizeNode(path);
660
- } else if (path.isJSXSpreadChild()) ; else if (path.isJSXText()) {
661
- return [this.tokenizeText(path.node.value)];
662
- } else ;
663
- });
664
- __publicField(this, "tokenizeChoiceComponent", (path) => {
665
- const element = path.get("openingElement");
666
- const name = this.getJsxTagName(path.node);
667
- const format = (this.nameMapReversed.get(name) || name).toLowerCase();
668
- const props = element.get("attributes").filter((attr) => {
669
- return this.attrName(
670
- [
671
- ID,
672
- COMMENT,
673
- MESSAGE,
674
- CONTEXT,
675
- "key",
676
- // we remove <Trans /> react props that are not useful for translation
677
- "render",
678
- "component",
679
- "components"
680
- ],
681
- true
682
- )(attr.node);
683
- });
684
- const token = {
685
- type: "arg",
686
- format,
687
- name: null,
688
- value: void 0,
689
- options: {
690
- offset: void 0
691
- }
692
- };
693
- for (const _attr of props) {
694
- if (_attr.isJSXSpreadAttribute()) {
695
- continue;
696
- }
697
- const attr = _attr;
698
- if (this.types.isJSXNamespacedName(attr.node.name)) {
699
- continue;
700
- }
701
- const name2 = attr.node.name.name;
702
- const value = attr.get("value");
703
- if (name2 === "value") {
704
- const exp = value.isLiteral() ? value : value.get("expression");
705
- token.name = this.expressionToArgument(exp);
706
- token.value = exp.node;
707
- } else if (format !== "select" && name2 === "offset") {
708
- token.options.offset = value.isStringLiteral() || value.isNumericLiteral() ? value.node.value : value.get(
709
- "expression"
710
- ).node.value;
711
- } else {
712
- let option;
713
- if (value.isStringLiteral()) {
714
- option = value.node.extra.raw.replace(
715
- /(["'])(.*)\1/,
716
- "$2"
717
- );
718
- } else {
719
- option = this.tokenizeChildren(value);
720
- }
721
- if (pluralRuleRe.test(name2)) {
722
- token.options[jsx2icuExactChoice(name2)] = option;
723
- } else {
724
- token.options[name2] = option;
725
- }
726
- }
727
- }
728
- return token;
729
- });
730
- __publicField(this, "tokenizeElement", (path) => {
731
- const name = this.elementIndex();
732
- return {
733
- type: "element",
734
- name,
735
- value: {
736
- ...path.node,
737
- children: [],
738
- openingElement: {
739
- ...path.node.openingElement,
740
- selfClosing: true
741
- }
742
- },
743
- children: this.tokenizeTrans(path)
744
- };
745
- });
746
- __publicField(this, "tokenizeExpression", (path) => {
747
- return {
748
- type: "arg",
749
- name: this.expressionToArgument(path),
750
- value: path.node
751
- };
752
- });
753
- __publicField(this, "tokenizeConditionalExpression", (exp) => {
754
- exp.traverse({
755
- JSXElement: (el) => {
756
- if (this.isTransComponent(el) || this.isChoiceComponent(el)) {
757
- this.replacePath(el);
758
- el.skip();
759
- }
760
- }
761
- });
762
- return {
763
- type: "arg",
764
- name: this.expressionToArgument(exp),
765
- value: exp.node
766
- };
767
- });
768
- __publicField(this, "tokenizeText", (value) => {
769
- return {
770
- type: "text",
771
- value
772
- };
773
- });
774
- __publicField(this, "isLinguiComponent", (path, name) => {
775
- return path.isJSXElement() && this.types.isJSXIdentifier(path.node.openingElement.name, {
776
- name: this.nameMap.get(name) || name
777
- });
778
- });
779
- __publicField(this, "isTransComponent", (path) => {
780
- return this.isLinguiComponent(path, "Trans");
781
- });
782
- __publicField(this, "isChoiceComponent", (path) => {
783
- return this.isLinguiComponent(path, "Plural") || this.isLinguiComponent(path, "Select") || this.isLinguiComponent(path, "SelectOrdinal");
784
- });
785
- __publicField(this, "getJsxTagName", (node) => {
786
- if (this.types.isJSXIdentifier(node.openingElement.name)) {
787
- return node.openingElement.name.name;
788
- }
789
- });
790
- this.types = types;
791
- this.stripNonEssentialProps = opts.stripNonEssentialProps;
792
- this.nameMap = opts.nameMap;
793
- this.nameMapReversed = Array.from(opts.nameMap.entries()).reduce(
794
- (map, [key, value]) => map.set(value, key),
795
- /* @__PURE__ */ new Map()
796
- );
797
- }
798
- tokenizeTemplateLiteral(exp) {
799
- const expressions = exp.get("expressions");
800
- return exp.get("quasis").flatMap(({ node: text }, i) => {
801
- const value = /\\u[a-fA-F0-9]{4}|\\x[a-fA-F0-9]{2}/g.test(text.value.raw) ? text.value.cooked : text.value.raw;
802
- let argTokens = [];
803
- const currExp = expressions[i];
804
- if (currExp) {
805
- argTokens = currExp.isCallExpression() ? this.tokenizeNode(currExp) : [this.tokenizeExpression(currExp)];
806
- }
807
- return [
808
- ...value ? [this.tokenizeText(this.clearBackslashes(value))] : [],
809
- ...argTokens
810
- ];
811
- });
812
- }
813
- expressionToArgument(path) {
814
- return path.isIdentifier() ? path.node.name : String(this.expressionIndex());
815
- }
816
- /**
817
- * We clean '//\` ' to just '`'
818
- **/
819
- clearBackslashes(value) {
820
- return value.replace(/\\`/g, "`");
821
- }
822
- }
823
-
824
- const jsMacroTags = /* @__PURE__ */ new Set([
825
- "defineMessage",
826
- "msg",
827
- "arg",
828
- "t",
829
- "useLingui",
830
- "plural",
831
- "select",
832
- "selectOrdinal"
833
- ]);
834
- const jsxMacroTags = /* @__PURE__ */ new Set(["Trans", "Plural", "Select", "SelectOrdinal"]);
835
- let config;
836
- function getConfig(_config) {
837
- if (_config) {
838
- config = _config;
839
- }
840
- if (!config) {
841
- config = conf.getConfig();
842
- }
843
- return config;
844
- }
845
- function macro({ references, state, babel, config: config2 }) {
846
- const opts = config2;
847
- const body = state.file.path.node.body;
848
- const {
849
- i18nImportModule,
850
- i18nImportName,
851
- TransImportModule,
852
- TransImportName,
853
- useLinguiImportModule,
854
- useLinguiImportName
855
- } = getConfig(opts.linguiConfig).runtimeConfigModule;
856
- const jsxNodes = /* @__PURE__ */ new Set();
857
- const jsNodes = /* @__PURE__ */ new Set();
858
- let needsI18nImport = false;
859
- let needsUseLinguiImport = false;
860
- const uniq_tIdentifier = state.file.scope.generateUidIdentifier("_t");
861
- let nameMap = /* @__PURE__ */ new Map();
862
- Object.keys(references).forEach((tagName) => {
863
- const nodes = references[tagName];
864
- if (jsMacroTags.has(tagName)) {
865
- nodes.forEach((path) => {
866
- if (tagName !== "useLingui") {
867
- nameMap.set(tagName, path.node.name);
868
- jsNodes.add(path.parentPath);
869
- } else {
870
- needsUseLinguiImport = true;
871
- nameMap.set("_t", uniq_tIdentifier.name);
872
- processUseLingui(
873
- path,
874
- useLinguiImportName,
875
- uniq_tIdentifier.name
876
- )?.forEach((n) => jsNodes.add(n));
877
- }
878
- });
879
- } else if (jsxMacroTags.has(tagName)) {
880
- nodes.forEach((path) => {
881
- nameMap.set(tagName, path.node.name);
882
- jsxNodes.add(path.parentPath.parentPath);
883
- });
884
- } else {
885
- throw nodes[0].buildCodeFrameError(`Unknown macro ${tagName}`);
886
- }
887
- });
888
- const stripNonEssentialProps = process.env.NODE_ENV == "production" && !opts.extract;
889
- const jsNodesArray = Array.from(jsNodes);
890
- jsNodesArray.filter(isRootPath(jsNodesArray)).forEach((path) => {
891
- const macro2 = new MacroJs(babel, {
892
- i18nImportName,
893
- stripNonEssentialProps,
894
- nameMap
895
- });
896
- try {
897
- macro2.replacePath(path);
898
- needsI18nImport = needsI18nImport || macro2.needsI18nImport;
899
- needsUseLinguiImport = needsUseLinguiImport || macro2.needsUseLinguiImport;
900
- } catch (e) {
901
- reportUnsupportedSyntax(path, e);
902
- }
903
- });
904
- const jsxNodesArray = Array.from(jsxNodes);
905
- jsxNodesArray.filter(isRootPath(jsxNodesArray)).forEach((path) => {
906
- const macro2 = new MacroJSX(babel, { stripNonEssentialProps, nameMap });
907
- try {
908
- macro2.replacePath(path);
909
- } catch (e) {
910
- reportUnsupportedSyntax(path, e);
911
- }
912
- });
913
- if (needsUseLinguiImport) {
914
- addImport(babel, body, useLinguiImportModule, useLinguiImportName);
915
- }
916
- if (needsI18nImport) {
917
- addImport(babel, body, i18nImportModule, i18nImportName);
918
- }
919
- if (jsxNodes.size) {
920
- addImport(babel, body, TransImportModule, TransImportName);
921
- }
922
- }
923
- function reportUnsupportedSyntax(path, e) {
924
- throw path.buildCodeFrameError(
925
- `Unsupported macro usage. Please check the examples at https://lingui.dev/ref/macro#examples-of-js-macros.
926
- If you think this is a bug, fill in an issue at https://github.com/lingui/js-lingui/issues
927
-
928
- Error: ${e.message}`
929
- );
930
- }
931
- function processUseLingui(path, useLinguiName, newIdentifier) {
932
- if (!path.parentPath.parentPath.isVariableDeclarator()) {
933
- reportUnsupportedSyntax(
934
- path,
935
- new Error(
936
- `\`useLingui\` macro must be used in variable declaration.
937
-
938
- Example:
939
-
940
- const { t } = useLingui()
941
- `
942
- )
943
- );
944
- return null;
945
- }
946
- const varDec = path.parentPath.parentPath.node;
947
- const _property = t__namespace.isObjectPattern(varDec.id) ? varDec.id.properties.find(
948
- (property) => t__namespace.isObjectProperty(property) && t__namespace.isIdentifier(property.key) && t__namespace.isIdentifier(property.value) && property.key.name == "t"
949
- ) : null;
950
- if (!_property) {
951
- reportUnsupportedSyntax(
952
- path.parentPath.parentPath,
953
- new Error(
954
- `You have to destructure \`t\` when using the \`useLingui\` macro, i.e:
955
- const { t } = useLingui()
956
- or
957
- const { t: _ } = useLingui()
958
- `
959
- )
960
- );
961
- return null;
962
- }
963
- if (t__namespace.isIdentifier(path.node)) {
964
- path.scope.rename(path.node.name, useLinguiName);
965
- }
966
- _property.key.name = "_";
967
- path.scope.rename(_property.value.name, newIdentifier);
968
- return path.scope.getBinding(_property.value.name)?.referencePaths.filter(
969
- // dont process array expression to allow use in dependency arrays
970
- (path2) => !path2.parentPath.isArrayExpression()
971
- ).map((path2) => path2.parentPath);
972
- }
973
- function addImport(babel, body, module2, importName) {
974
- const { types: t2 } = babel;
975
- const linguiImport = body.find(
976
- (importNode) => t2.isImportDeclaration(importNode) && importNode.source.value === module2 && // https://github.com/lingui/js-lingui/issues/777
977
- importNode.importKind !== "type"
978
- );
979
- const tIdentifier = t2.identifier(importName);
980
- if (linguiImport) {
981
- if (!linguiImport.specifiers.find(
982
- (specifier) => t2.isImportSpecifier(specifier) && t2.isIdentifier(specifier.imported, { name: importName })
983
- )) {
984
- linguiImport.specifiers.push(t2.importSpecifier(tIdentifier, tIdentifier));
985
- }
986
- } else {
987
- body.unshift(
988
- t2.importDeclaration(
989
- [t2.importSpecifier(tIdentifier, tIdentifier)],
990
- t2.stringLiteral(module2)
991
- )
992
- );
993
- }
994
- }
995
- function isRootPath(allPath) {
996
- return (node) => function traverse(path) {
997
- if (!path.parentPath) {
998
- return true;
999
- } else {
1000
- return !allPath.includes(path.parentPath) && traverse(path.parentPath);
1001
- }
1002
- }(node);
1003
- }
1004
- [...jsMacroTags, ...jsxMacroTags].forEach((name) => {
4
+ const plugin = require('./shared/macro.1cca3fdc.cjs');
5
+ require('@babel/types');
6
+ require('@lingui/message-utils/generateMessageId');
7
+ require('@lingui/conf');
8
+
9
+ function macro({ state, babel, config }) {
10
+ if (!state.get("linguiProcessed")) {
11
+ state.opts = config;
12
+ const plugin$1 = plugin.linguiPlugin(babel);
13
+ const { enter, exit } = plugin$1.visitor.Program;
14
+ enter(state.file.path, state);
15
+ state.file.path.traverse(plugin$1.visitor, state);
16
+ exit(state.file.path, state);
17
+ state.set("linguiProcessed", true);
18
+ }
19
+ return { keepImports: true };
20
+ }
21
+ [
22
+ plugin.JsMacroName.defineMessage,
23
+ plugin.JsMacroName.msg,
24
+ plugin.JsMacroName.t,
25
+ plugin.JsMacroName.useLingui,
26
+ plugin.JsMacroName.plural,
27
+ plugin.JsMacroName.select,
28
+ plugin.JsMacroName.selectOrdinal,
29
+ plugin.JsxMacroName.Trans,
30
+ plugin.JsxMacroName.Plural,
31
+ plugin.JsxMacroName.Select,
32
+ plugin.JsxMacroName.SelectOrdinal
33
+ ].forEach((name) => {
1005
34
  Object.defineProperty(module.exports, name, {
1006
35
  get() {
1007
36
  throw new Error(