Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(macro): make message stripping configurable via Babel options #2054

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/babel-plugin-lingui-macro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ let config: LinguiConfigNormalized
export type LinguiPluginOpts = {
// explicitly set by CLI when running extraction process
extract?: boolean
stripMessageField?: boolean
linguiConfig?: LinguiConfigNormalized
}

Expand All @@ -46,6 +47,19 @@ function reportUnsupportedSyntax(path: NodePath, e: Error) {
throw codeFrameError
}

function shouldStripMessageProp(opts: LinguiPluginOpts) {
if (opts.extract) {
// never strip message during extraction process
return false
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this is not needed, because this case is not possible. The babel options which extractor uses are not exposed to the userland and could not be overridden by users. So i could not imagine the situation when {extract: true, stripMessageProp: true} would be passed together.

This will allow to delete some of the tests, less code, less things to maintain.

Thanks!

Copy link
Contributor Author

@toblu toblu Oct 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well spotted! I added it in the initial implementation based on v4. In that version when I ran the extract command the message was stripped if I had stripMessageProp: true set in the Babel config unless I had this line to explicitly return false during extraction.

I tested it now against the new v5 implementation and it indeed seems like the stripMessageField: true option does not affect extract. However if I remove this check, some of the existing test cases will break. For example this one since it will remove the message prop due to production: true:

name: "Production - all props kept if extract: true",
production: true,
macroOpts: {
extract: true,
},
code: `
import { t } from '@lingui/core/macro';
const msg = t({
message: \`Hello $\{name\}\`,
id: 'msgId',
comment: 'description for translators',
context: 'My Context',
})
`,
},

How do you think it should be handled?

One alternative that I see could be to change the implementation to something like:

function shouldStripMessageProp(opts: LinguiPluginOpts) {
  if (typeof opts.stripMessageField === "boolean") {
    // if explicitly set in options, use it
    return opts.stripMessageField
  }
  // default to strip message in production if no explicit option is set and not during extract
  return process.env.NODE_ENV === "production" && !opts.extract

This way it would be more aligned with the stripNonEssentialProps value and won't mess up extract if someone runs extract with NODE_ENV set to "production".

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well spotted! I added it in the initial implementation based on v4. In that version when I ran the extract command the message was stripped if I had stripMessageProp: true set in the Babel config unless I had this line to explicitly return false during extraction.

That's strange, because nothing was changed between 4 and 5 in that regard. Lingui extractor does not use user's babel config (intentionally) and no options from there could affect extraction process.

Your proposed alternative is fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might have been me that messed something up when I tested it before, as I was testing a few different implementations in v4. Anyway I confirmed in v5 that it doesn't seem to be a possible case like you said. I have changed the implementation now to what I proposed in my previous comment since that doesn't break any of the existing test cases.

if (typeof opts.stripMessageField === "boolean") {
// if explicitly set in options, use it
return opts.stripMessageField
}
// default to strip message in production if no explicit option is set
return process.env.NODE_ENV === "production"
}

type LinguiSymbol = "Trans" | "useLingui" | "i18n"

const getIdentifierPath = ((path: NodePath, node: Identifier) => {
Expand Down Expand Up @@ -186,6 +200,9 @@ export default function ({
stripNonEssentialProps:
process.env.NODE_ENV == "production" &&
!(state.opts as LinguiPluginOpts).extract,
stripMessageProp: shouldStripMessageProp(
state.opts as LinguiPluginOpts
),
}
)

Expand Down Expand Up @@ -214,6 +231,9 @@ export default function ({
stripNonEssentialProps:
process.env.NODE_ENV == "production" &&
!(state.opts as LinguiPluginOpts).extract,
stripMessageProp: shouldStripMessageProp(
state.opts as LinguiPluginOpts
),
i18nImportName: getSymbolIdentifier(state, "i18n").name,
useLinguiImportName: getSymbolIdentifier(state, "useLingui")
.name,
Expand Down
13 changes: 9 additions & 4 deletions packages/babel-plugin-lingui-macro/src/macroJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type MacroJsOpts = {
useLinguiImportName: string

stripNonEssentialProps: boolean
stripMessageProp: boolean
isLinguiIdentifier: (node: Identifier, macro: JsMacroName) => boolean
}

Expand All @@ -46,7 +47,8 @@ export class MacroJs {

this._ctx = createMacroJsContext(
opts.isLinguiIdentifier,
opts.stripNonEssentialProps
opts.stripNonEssentialProps,
opts.stripMessageProp
)
}

Expand All @@ -59,7 +61,8 @@ export class MacroJs {
createMessageDescriptorFromTokens(
tokens,
path.node.loc,
this._ctx.stripNonEssentialProps
this._ctx.stripNonEssentialProps,
this._ctx.stripMessageProp
),
linguiInstance
)
Expand Down Expand Up @@ -89,7 +92,8 @@ export class MacroJs {
return createMessageDescriptorFromTokens(
tokens,
path.node.loc,
ctx.stripNonEssentialProps
ctx.stripNonEssentialProps,
ctx.stripMessageProp
)
}

Expand Down Expand Up @@ -260,7 +264,8 @@ export class MacroJs {
const descriptor = createMessageDescriptorFromTokens(
tokens,
currentPath.node.loc,
ctx.stripNonEssentialProps
ctx.stripNonEssentialProps,
ctx.stripMessageProp
)

const callExpr = t.callExpression(
Expand Down
10 changes: 7 additions & 3 deletions packages/babel-plugin-lingui-macro/src/macroJsAst.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,13 @@ const parseExpression = (expression: string) => {
}

function createMacroCtx() {
return createMacroJsContext((identifier, macro) => {
return identifier.name === macro
}, false)
return createMacroJsContext(
(identifier, macro) => {
return identifier.name === macro
},
false, // stripNonEssentialProps
false // stripMessageProp
)
}

describe("js macro", () => {
Expand Down
6 changes: 5 additions & 1 deletion packages/babel-plugin-lingui-macro/src/macroJsAst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,20 @@ export type MacroJsContext = {
// Positional expressions counter (e.g. for placeholders `Hello {0}, today is {1}`)
getExpressionIndex: () => number
stripNonEssentialProps: boolean
stripMessageProp: boolean
isLinguiIdentifier: (node: Identifier, macro: JsMacroName) => boolean
}

export function createMacroJsContext(
isLinguiIdentifier: MacroJsContext["isLinguiIdentifier"],
stripNonEssentialProps: boolean
stripNonEssentialProps: boolean,
stripMessageProp: boolean
): MacroJsContext {
return {
getExpressionIndex: makeCounter(),
isLinguiIdentifier,
stripNonEssentialProps,
stripMessageProp,
}
}

Expand Down Expand Up @@ -85,6 +88,7 @@ export function processDescriptor(
tokens,
descriptor.loc,
ctx.stripNonEssentialProps,
ctx.stripMessageProp,
{
id: idProperty,
context: contextProperty,
Expand Down
6 changes: 5 additions & 1 deletion packages/babel-plugin-lingui-macro/src/macroJsx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ const parseExpression = (expression: string) => {
function createMacro() {
return new MacroJSX(
{ types },
{ stripNonEssentialProps: false, transImportName: "Trans" }
{
stripNonEssentialProps: false,
stripMessageProp: false,
transImportName: "Trans",
}
)
}

Expand Down
4 changes: 4 additions & 0 deletions packages/babel-plugin-lingui-macro/src/macroJsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function maybeNodeValue(node: Node): { text: string; loc: SourceLocation } {

export type MacroJsxOpts = {
stripNonEssentialProps: boolean
stripMessageProp: boolean
transImportName: string
}

Expand All @@ -53,11 +54,13 @@ export class MacroJSX {
expressionIndex = makeCounter()
elementIndex = makeCounter()
stripNonEssentialProps: boolean
stripMessageProp: boolean
transImportName: string

constructor({ types }: { types: typeof babelTypes }, opts: MacroJsxOpts) {
this.types = types
this.stripNonEssentialProps = opts.stripNonEssentialProps
this.stripMessageProp = opts.stripMessageProp
this.transImportName = opts.transImportName
}

Expand All @@ -84,6 +87,7 @@ export class MacroJSX {
tokens,
path.node.loc,
this.stripNonEssentialProps,
this.stripMessageProp,
{
id,
context,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export function createMessageDescriptorFromTokens(
tokens: Tokens,
oldLoc: SourceLocation,
stripNonEssentialProps: boolean,
stripMessageProp: boolean,
defaults: {
id?: TextWithLoc | ObjectProperty
context?: TextWithLoc | ObjectProperty
Expand All @@ -39,6 +40,7 @@ export function createMessageDescriptorFromTokens(
buildICUFromTokens(tokens),
oldLoc,
stripNonEssentialProps,
stripMessageProp,
defaults
)
}
Expand All @@ -47,6 +49,7 @@ export function createMessageDescriptor(
result: Partial<ParsedResult>,
oldLoc: SourceLocation,
stripNonEssentialProps: boolean,
stripMessageProp: boolean,
defaults: {
id?: TextWithLoc | ObjectProperty
context?: TextWithLoc | ObjectProperty
Expand Down Expand Up @@ -76,13 +79,15 @@ export function createMessageDescriptor(
)
)

if (!stripNonEssentialProps) {
if (!stripMessageProp) {
if (message) {
properties.push(
createStringObjectProperty(MsgDescriptorPropKey.message, message)
)
}
}

if (!stripNonEssentialProps) {
if (defaults.comment) {
properties.push(
isObjectProperty(defaults.comment)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,31 @@ const msg = _i18n._(

`;

exports[`Production - message prop is kept if stripMessageField: false 1`] = `
import { t } from "@lingui/macro";
const msg = t({
message: \`Hello \${name}\`,
id: "msgId",
comment: "description for translators",
context: "My Context",
});

↓ ↓ ↓ ↓ ↓ ↓

import { i18n as _i18n } from "@lingui/core";
const msg = _i18n._(
/*i18n*/
{
id: "msgId",
message: "Hello {name}",
values: {
name: name,
},
}
);

`;

exports[`Production - only essential props are kept 1`] = `
import { t } from "@lingui/core/macro";
const msg = t\`Message\`;
Expand Down Expand Up @@ -570,6 +595,39 @@ const msg = _i18n._();

`;

exports[`stripMessageField option - Message prop is kept during extraction process if extract: true and stripMessageField: true 1`] = `
import { t } from "@lingui/macro";
const msg = t\`Message\`;

↓ ↓ ↓ ↓ ↓ ↓

import { i18n as _i18n } from "@lingui/core";
const msg = _i18n._(
/*i18n*/
{
id: "xDAtGP",
message: "Message",
}
);

`;

exports[`stripMessageField option - message prop is removed if stripMessageField: true 1`] = `
import { t } from "@lingui/macro";
const msg = t\`Message\`;

↓ ↓ ↓ ↓ ↓ ↓

import { i18n as _i18n } from "@lingui/core";
const msg = _i18n._(
/*i18n*/
{
id: "xDAtGP",
}
);

`;

exports[`t\`\` macro could be renamed 1`] = `
import { t as t2 } from "@lingui/core/macro";
const a = t2\`Expression assignment\`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,27 @@ import { Trans as _Trans } from "@lingui/react";

`;

exports[`Production - message prop is kept if stripMessageField: false 1`] = `
import { Trans } from "@lingui/macro";
<Trans id="msg.hello" comment="Hello World">
Hello World
</Trans>;

↓ ↓ ↓ ↓ ↓ ↓

import { Trans as _Trans } from "@lingui/react";
<_Trans
{
/*i18n*/
...{
id: "msg.hello",
message: "Hello World",
}
}
/>;

`;

exports[`Production - only essential props are kept 1`] = `
import { Trans } from "@lingui/react/macro";
<Trans id="msg.hello" context="my context" comment="Hello World">
Expand Down Expand Up @@ -791,3 +812,40 @@ import { Trans as _Trans } from "@lingui/react";
/>;

`;

exports[`stripMessageField option - Message prop is kept during extraction process if extract: true and stripMessageField: true 1`] = `
import { Trans } from "@lingui/macro";
<Trans id="msg.hello">Hello World</Trans>;

↓ ↓ ↓ ↓ ↓ ↓

import { Trans as _Trans } from "@lingui/react";
<_Trans
{
/*i18n*/
...{
id: "msg.hello",
message: "Hello World",
}
}
/>;

`;

exports[`stripMessageField option - message prop is removed if stripMessageField: true 1`] = `
import { Trans } from "@lingui/macro";
<Trans id="msg.hello">Hello World</Trans>;

↓ ↓ ↓ ↓ ↓ ↓

import { Trans as _Trans } from "@lingui/react";
<_Trans
{
/*i18n*/
...{
id: "msg.hello",
}
}
/>;

`;
Loading
Loading