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