@formatjs/unplugin 1.1.6 → 1.1.7
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/esbuild.d.ts +19 -4
- package/esbuild.js +254 -2
- package/esbuild.js.map +1 -0
- package/index.d.ts +21 -6
- package/index.js +244 -4
- package/index.js.map +1 -0
- package/package.json +4 -4
- package/rollup.d.ts +19 -4
- package/rollup.js +254 -2
- package/rollup.js.map +1 -0
- package/rspack.d.ts +19 -4
- package/rspack.js +254 -2
- package/rspack.js.map +1 -0
- package/transform.d.ts +17 -12
- package/transform.js +57 -137
- package/transform.js.map +1 -0
- package/vite.d.ts +19 -4
- package/vite.js +254 -2
- package/vite.js.map +1 -0
- package/webpack.d.ts +19 -4
- package/webpack.js +254 -2
- package/webpack.js.map +1 -0
package/rspack.js
CHANGED
|
@@ -1,4 +1,256 @@
|
|
|
1
1
|
import { createRspackPlugin } from "unplugin";
|
|
2
|
-
import {
|
|
2
|
+
import { Visitor, parseSync } from "oxc-parser";
|
|
3
|
+
import MagicString from "magic-string";
|
|
4
|
+
import { interpolateName } from "@formatjs/ts-transformer";
|
|
5
|
+
import { parse } from "@formatjs/icu-messageformat-parser";
|
|
6
|
+
import { hoistSelectors } from "@formatjs/icu-messageformat-parser/manipulator.js";
|
|
7
|
+
import { printAST } from "@formatjs/icu-messageformat-parser/printer.js";
|
|
8
|
+
//#region packages/unplugin/transform.ts
|
|
9
|
+
const DEFAULT_ID_INTERPOLATION_PATTERN = "[sha512:contenthash:base64:6]";
|
|
10
|
+
function transform(code, id, options) {
|
|
11
|
+
const { overrideIdFn, idInterpolationPattern = DEFAULT_ID_INTERPOLATION_PATTERN, removeDefaultMessage = false, additionalComponentNames = [], additionalFunctionNames = [], ast: preParseAst = false, preserveWhitespace = false, flatten = true } = options;
|
|
12
|
+
const componentNames = new Set(["FormattedMessage", ...additionalComponentNames]);
|
|
13
|
+
const functionNames = new Set([
|
|
14
|
+
"formatMessage",
|
|
15
|
+
"$t",
|
|
16
|
+
"$formatMessage",
|
|
17
|
+
"defineMessage",
|
|
18
|
+
"defineMessages",
|
|
19
|
+
...additionalFunctionNames
|
|
20
|
+
]);
|
|
21
|
+
const jsxRuntimeFunctions = new Set([
|
|
22
|
+
"jsx",
|
|
23
|
+
"_jsx",
|
|
24
|
+
"jsxs",
|
|
25
|
+
"_jsxs",
|
|
26
|
+
"jsxDEV",
|
|
27
|
+
"_jsxDEV",
|
|
28
|
+
"createElement"
|
|
29
|
+
]);
|
|
30
|
+
const program = parseSync(id, code, { sourceType: "module" }).program;
|
|
31
|
+
let s;
|
|
32
|
+
function getStaticValue(node) {
|
|
33
|
+
if (!node) return void 0;
|
|
34
|
+
if (node.type === "StringLiteral" || node.type === "Literal") {
|
|
35
|
+
if (typeof node.value === "string") return node.value;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (node.type === "TemplateLiteral") {
|
|
39
|
+
if (node.quasis.length === 1 && node.expressions.length === 0) return node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (node.type === "BinaryExpression" && node.operator === "+") {
|
|
43
|
+
const left = getStaticValue(node.left);
|
|
44
|
+
const right = getStaticValue(node.right);
|
|
45
|
+
if (left !== void 0 && right !== void 0) return left + right;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function extractDescriptor(objNode) {
|
|
50
|
+
const properties = objNode.properties;
|
|
51
|
+
const descriptor = {};
|
|
52
|
+
const locations = {};
|
|
53
|
+
locations.insertionPoint = objNode.start + 1;
|
|
54
|
+
for (const prop of properties) {
|
|
55
|
+
if (prop.type !== "Property" && prop.type !== "ObjectProperty") continue;
|
|
56
|
+
const key = prop.key;
|
|
57
|
+
let name;
|
|
58
|
+
if (key.type === "Identifier") name = key.name;
|
|
59
|
+
else if (key.type === "StringLiteral" || key.type === "Literal") name = key.value;
|
|
60
|
+
if (!name) continue;
|
|
61
|
+
if (name !== "id" && name !== "defaultMessage" && name !== "description") continue;
|
|
62
|
+
const keyName = name;
|
|
63
|
+
const val = getStaticValue(prop.value);
|
|
64
|
+
if (val === void 0) continue;
|
|
65
|
+
descriptor[keyName] = val;
|
|
66
|
+
locations[keyName] = {
|
|
67
|
+
start: prop.value.start,
|
|
68
|
+
end: prop.value.end,
|
|
69
|
+
value: val
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
if (!descriptor.defaultMessage && !descriptor.id) return void 0;
|
|
73
|
+
return {
|
|
74
|
+
descriptor,
|
|
75
|
+
locations
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function extractJSXDescriptor(elementNode) {
|
|
79
|
+
const attributes = elementNode.attributes || [];
|
|
80
|
+
const descriptor = {};
|
|
81
|
+
const locations = {};
|
|
82
|
+
locations.insertionPoint = elementNode.name.end;
|
|
83
|
+
for (const attr of attributes) {
|
|
84
|
+
if (attr.type !== "JSXAttribute") continue;
|
|
85
|
+
const attrName = attr.name;
|
|
86
|
+
if (!attrName || attrName.type !== "JSXIdentifier") continue;
|
|
87
|
+
const n = attrName.name;
|
|
88
|
+
if (n !== "id" && n !== "defaultMessage" && n !== "description") continue;
|
|
89
|
+
const keyName = n;
|
|
90
|
+
let val;
|
|
91
|
+
const valueNode = attr.value;
|
|
92
|
+
if (!valueNode) continue;
|
|
93
|
+
if (valueNode.type === "StringLiteral" || valueNode.type === "Literal") val = valueNode.value;
|
|
94
|
+
else if (valueNode.type === "JSXExpressionContainer") val = getStaticValue(valueNode.expression);
|
|
95
|
+
if (val === void 0) continue;
|
|
96
|
+
descriptor[keyName] = val;
|
|
97
|
+
locations[keyName] = {
|
|
98
|
+
start: attr.value.start,
|
|
99
|
+
end: attr.value.end,
|
|
100
|
+
value: val
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (!descriptor.defaultMessage && !descriptor.id) return void 0;
|
|
104
|
+
return {
|
|
105
|
+
descriptor,
|
|
106
|
+
locations
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function processDescriptor(descriptor, locations, isJSX) {
|
|
110
|
+
let { defaultMessage, description } = descriptor;
|
|
111
|
+
let existingId = descriptor.id;
|
|
112
|
+
if (defaultMessage && !preserveWhitespace) defaultMessage = defaultMessage.trim().replace(/\s+/gm, " ");
|
|
113
|
+
if (flatten && defaultMessage) try {
|
|
114
|
+
defaultMessage = printAST(hoistSelectors(parse(defaultMessage)));
|
|
115
|
+
} catch {}
|
|
116
|
+
let newId = existingId;
|
|
117
|
+
if (overrideIdFn) newId = overrideIdFn(existingId, defaultMessage, description, id);
|
|
118
|
+
else if (!existingId && idInterpolationPattern && defaultMessage) newId = interpolateName({ resourcePath: id }, idInterpolationPattern, { content: description ? `${defaultMessage}#${description}` : defaultMessage });
|
|
119
|
+
if (!newId && !defaultMessage) return;
|
|
120
|
+
if (!s) s = new MagicString(code);
|
|
121
|
+
if (newId) {
|
|
122
|
+
if (locations.id) s.overwrite(locations.id.start, locations.id.end, JSON.stringify(newId));
|
|
123
|
+
else if (locations.insertionPoint != null) if (isJSX) s.appendLeft(locations.insertionPoint, ` id=${JSON.stringify(newId)}`);
|
|
124
|
+
else s.appendRight(locations.insertionPoint, `id: ${JSON.stringify(newId)}, `);
|
|
125
|
+
}
|
|
126
|
+
if (locations.description) if (isJSX) removeJSXAttribute(locations.description);
|
|
127
|
+
else removeObjectProperty(locations.description);
|
|
128
|
+
if (locations.defaultMessage) {
|
|
129
|
+
if (removeDefaultMessage) if (isJSX) removeJSXAttribute(locations.defaultMessage);
|
|
130
|
+
else removeObjectProperty(locations.defaultMessage);
|
|
131
|
+
else if (defaultMessage) {
|
|
132
|
+
if (preParseAst) {
|
|
133
|
+
const parsed = parse(defaultMessage);
|
|
134
|
+
const jsonStr = JSON.stringify(parsed);
|
|
135
|
+
s.overwrite(locations.defaultMessage.start, locations.defaultMessage.end, isJSX ? `{${jsonStr}}` : jsonStr);
|
|
136
|
+
} else if (defaultMessage !== locations.defaultMessage.value) s.overwrite(locations.defaultMessage.start, locations.defaultMessage.end, JSON.stringify(defaultMessage));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function removeObjectProperty(loc) {
|
|
141
|
+
if (!s) return;
|
|
142
|
+
let propStart = loc.start;
|
|
143
|
+
let i = loc.start - 1;
|
|
144
|
+
while (i >= 0 && (code[i] === " " || code[i] === " " || code[i] === "\n" || code[i] === "\r")) i--;
|
|
145
|
+
if (i >= 0 && code[i] === ":") i--;
|
|
146
|
+
while (i >= 0 && (code[i] === " " || code[i] === " " || code[i] === "\n" || code[i] === "\r")) i--;
|
|
147
|
+
if (i >= 0 && (code[i] === "\"" || code[i] === "'")) {
|
|
148
|
+
const quote = code[i];
|
|
149
|
+
i--;
|
|
150
|
+
while (i >= 0 && code[i] !== quote) i--;
|
|
151
|
+
if (i >= 0) i--;
|
|
152
|
+
} else while (i >= 0 && /[a-zA-Z0-9_$]/.test(code[i])) i--;
|
|
153
|
+
propStart = i + 1;
|
|
154
|
+
let propEnd = loc.end;
|
|
155
|
+
let j = loc.end;
|
|
156
|
+
while (j < code.length && (code[j] === " " || code[j] === " ")) j++;
|
|
157
|
+
if (j < code.length && code[j] === ",") {
|
|
158
|
+
j++;
|
|
159
|
+
while (j < code.length && (code[j] === " " || code[j] === " ")) j++;
|
|
160
|
+
if (j < code.length && code[j] === "\n") j++;
|
|
161
|
+
else if (j < code.length && code[j] === "\r") {
|
|
162
|
+
j++;
|
|
163
|
+
if (j < code.length && code[j] === "\n") j++;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
propEnd = j;
|
|
167
|
+
let k = propStart - 1;
|
|
168
|
+
while (k >= 0 && (code[k] === " " || code[k] === " ")) k--;
|
|
169
|
+
if (k >= 0 && (code[k] === "\n" || code[k] === ",")) propStart = k + 1;
|
|
170
|
+
s.remove(propStart, propEnd);
|
|
171
|
+
}
|
|
172
|
+
function removeJSXAttribute(loc) {
|
|
173
|
+
if (!s) return;
|
|
174
|
+
let i = loc.start - 1;
|
|
175
|
+
if (i >= 0 && code[i] === "=") i--;
|
|
176
|
+
while (i >= 0 && /[a-zA-Z0-9_$]/.test(code[i])) i--;
|
|
177
|
+
const attrStart = i + 1;
|
|
178
|
+
const attrEnd = loc.end;
|
|
179
|
+
let k = attrStart - 1;
|
|
180
|
+
while (k >= 0 && (code[k] === " " || code[k] === " ")) k--;
|
|
181
|
+
if (k >= 0 && code[k] === "\n") k--;
|
|
182
|
+
if (k >= 0 && code[k] === "\r") k--;
|
|
183
|
+
const removeStart = k + 1;
|
|
184
|
+
s.remove(removeStart, attrEnd);
|
|
185
|
+
}
|
|
186
|
+
function getCalleeName(node) {
|
|
187
|
+
if (node.type === "Identifier") return node.name;
|
|
188
|
+
if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
|
|
189
|
+
if (node.property?.type === "Identifier") return node.property.name;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function handleCallExpression(node) {
|
|
193
|
+
const calleeName = getCalleeName(node.callee);
|
|
194
|
+
if (calleeName && jsxRuntimeFunctions.has(calleeName)) {
|
|
195
|
+
const firstArg = node.arguments?.[0];
|
|
196
|
+
const componentName = firstArg?.type === "Identifier" ? firstArg.name : void 0;
|
|
197
|
+
if (componentName && componentNames.has(componentName)) {
|
|
198
|
+
const propsArg = node.arguments?.[1];
|
|
199
|
+
if (propsArg?.type === "ObjectExpression") {
|
|
200
|
+
const result = extractDescriptor(propsArg);
|
|
201
|
+
if (result) processDescriptor(result.descriptor, result.locations, false);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (calleeName && functionNames.has(calleeName)) if (calleeName === "defineMessages") {
|
|
206
|
+
const arg = node.arguments?.[0];
|
|
207
|
+
if (arg?.type === "ObjectExpression") {
|
|
208
|
+
for (const prop of arg.properties) if (prop.type === "Property" && prop.value?.type === "ObjectExpression") {
|
|
209
|
+
const result = extractDescriptor(prop.value);
|
|
210
|
+
if (result) processDescriptor(result.descriptor, result.locations, false);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
const arg = node.arguments?.[0];
|
|
215
|
+
if (arg?.type === "ObjectExpression") {
|
|
216
|
+
const result = extractDescriptor(arg);
|
|
217
|
+
if (result) processDescriptor(result.descriptor, result.locations, false);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function handleJSXOpeningElement(node) {
|
|
222
|
+
const name = node.name?.type === "JSXIdentifier" ? node.name.name : void 0;
|
|
223
|
+
if (name && componentNames.has(name)) {
|
|
224
|
+
const result = extractJSXDescriptor(node);
|
|
225
|
+
if (result) processDescriptor(result.descriptor, result.locations, true);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
new Visitor({
|
|
229
|
+
CallExpression: handleCallExpression,
|
|
230
|
+
JSXOpeningElement: handleJSXOpeningElement
|
|
231
|
+
}).visit(program);
|
|
232
|
+
if (!s) return void 0;
|
|
233
|
+
return {
|
|
234
|
+
code: s.toString(),
|
|
235
|
+
map: s.generateMap({ hires: "boundary" })
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region packages/unplugin/index.ts
|
|
240
|
+
const unpluginFactory = (options = {}) => ({
|
|
241
|
+
name: "formatjs",
|
|
242
|
+
enforce: "pre",
|
|
243
|
+
transformInclude(id) {
|
|
244
|
+
return /\.[jt]sx?$/.test(id) && !id.includes("node_modules");
|
|
245
|
+
},
|
|
246
|
+
transform(code, id) {
|
|
247
|
+
return transform(code, id, options);
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
//#endregion
|
|
251
|
+
//#region packages/unplugin/rspack.ts
|
|
3
252
|
const plugin = createRspackPlugin(unpluginFactory);
|
|
4
|
-
|
|
253
|
+
//#endregion
|
|
254
|
+
export { plugin as default };
|
|
255
|
+
|
|
256
|
+
//# sourceMappingURL=rspack.js.map
|
package/rspack.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rspack.js","names":[],"sources":["../transform.ts","../index.ts","../rspack.ts"],"sourcesContent":["import {parseSync, Visitor} from 'oxc-parser'\nimport type {CallExpression, JSXOpeningElement} from 'oxc-parser'\nimport MagicString from 'magic-string'\nimport {interpolateName} from '@formatjs/ts-transformer'\nimport {parse} from '@formatjs/icu-messageformat-parser'\nimport {hoistSelectors} from '@formatjs/icu-messageformat-parser/manipulator.js'\nimport {printAST} from '@formatjs/icu-messageformat-parser/printer.js'\n\nexport interface Options {\n overrideIdFn?: (\n id: string | undefined,\n defaultMessage: string | undefined,\n description: string | undefined,\n filePath: string\n ) => string\n idInterpolationPattern?: string\n removeDefaultMessage?: boolean\n additionalComponentNames?: string[]\n additionalFunctionNames?: string[]\n ast?: boolean\n preserveWhitespace?: boolean\n flatten?: boolean\n}\n\nconst DEFAULT_ID_INTERPOLATION_PATTERN = '[sha512:contenthash:base64:6]'\n\ninterface MessageDescriptor {\n id?: string\n defaultMessage?: string\n description?: string\n}\n\ninterface DescriptorLocation {\n id?: {start: number; end: number; value: string}\n defaultMessage?: {start: number; end: number; value: string}\n description?: {start: number; end: number; value: string}\n /** Position right after the opening `{` or element name — stable insertion point for `id` */\n insertionPoint?: number\n}\n\nexport function transform(\n code: string,\n id: string,\n options: Options\n): {code: string; map: ReturnType<MagicString['generateMap']>} | undefined {\n const {\n overrideIdFn,\n idInterpolationPattern = DEFAULT_ID_INTERPOLATION_PATTERN,\n removeDefaultMessage = false,\n additionalComponentNames = [],\n additionalFunctionNames = [],\n ast: preParseAst = false,\n preserveWhitespace = false,\n flatten = true,\n } = options\n\n const componentNames = new Set([\n 'FormattedMessage',\n ...additionalComponentNames,\n ])\n const functionNames = new Set([\n 'formatMessage',\n '$t',\n '$formatMessage',\n 'defineMessage',\n 'defineMessages',\n ...additionalFunctionNames,\n ])\n // Compiled JSX runtime functions: _jsx(Component, props), React.createElement(Component, props)\n const jsxRuntimeFunctions = new Set([\n 'jsx',\n '_jsx',\n 'jsxs',\n '_jsxs',\n 'jsxDEV',\n '_jsxDEV',\n 'createElement',\n ])\n\n const result = parseSync(id, code, {sourceType: 'module'})\n const program = result.program\n\n let s: MagicString | undefined\n\n function getStaticValue(node: any): string | undefined {\n if (!node) return undefined\n if (node.type === 'StringLiteral' || node.type === 'Literal') {\n if (typeof node.value === 'string') return node.value\n return undefined\n }\n if (node.type === 'TemplateLiteral') {\n if (node.quasis.length === 1 && node.expressions.length === 0) {\n return node.quasis[0].value.cooked ?? node.quasis[0].value.raw\n }\n return undefined\n }\n if (node.type === 'BinaryExpression' && node.operator === '+') {\n const left = getStaticValue(node.left)\n const right = getStaticValue(node.right)\n if (left !== undefined && right !== undefined) return left + right\n return undefined\n }\n return undefined\n }\n\n function extractDescriptor(\n objNode: any\n ):\n | {descriptor: MessageDescriptor; locations: DescriptorLocation}\n | undefined {\n const properties = objNode.properties\n const descriptor: MessageDescriptor = {}\n const locations: DescriptorLocation = {}\n\n // Use the position right after `{` as a stable insertion point\n locations.insertionPoint = objNode.start + 1\n\n for (const prop of properties) {\n if (prop.type !== 'Property' && prop.type !== 'ObjectProperty') continue\n const key = prop.key\n let name: string | undefined\n if (key.type === 'Identifier') name = key.name\n else if (key.type === 'StringLiteral' || key.type === 'Literal') {\n name = key.value as string\n }\n if (!name) continue\n if (name !== 'id' && name !== 'defaultMessage' && name !== 'description')\n continue\n const keyName: keyof MessageDescriptor = name\n\n const val = getStaticValue(prop.value)\n if (val === undefined) continue\n\n descriptor[keyName] = val\n locations[keyName] = {\n start: prop.value.start,\n end: prop.value.end,\n value: val,\n }\n }\n\n if (!descriptor.defaultMessage && !descriptor.id) return undefined\n return {descriptor, locations}\n }\n\n function extractJSXDescriptor(\n elementNode: any\n ):\n | {descriptor: MessageDescriptor; locations: DescriptorLocation}\n | undefined {\n const attributes = elementNode.attributes || []\n const descriptor: MessageDescriptor = {}\n const locations: DescriptorLocation = {}\n\n // Always insert after the element name so the id survives even when the\n // first attribute (e.g. description) is removed.\n locations.insertionPoint = elementNode.name.end\n\n for (const attr of attributes) {\n if (attr.type !== 'JSXAttribute') continue\n const attrName = attr.name\n if (!attrName || attrName.type !== 'JSXIdentifier') continue\n const n = attrName.name\n if (n !== 'id' && n !== 'defaultMessage' && n !== 'description') continue\n const keyName: keyof MessageDescriptor = n\n\n let val: string | undefined\n const valueNode = attr.value\n if (!valueNode) continue\n\n if (valueNode.type === 'StringLiteral' || valueNode.type === 'Literal') {\n val = valueNode.value as string\n } else if (valueNode.type === 'JSXExpressionContainer') {\n val = getStaticValue(valueNode.expression)\n }\n\n if (val === undefined) continue\n\n descriptor[keyName] = val\n locations[keyName] = {\n start: attr.value.start,\n end: attr.value.end,\n value: val,\n }\n }\n\n if (!descriptor.defaultMessage && !descriptor.id) return undefined\n return {descriptor, locations}\n }\n\n function processDescriptor(\n descriptor: MessageDescriptor,\n locations: DescriptorLocation,\n isJSX: boolean\n ): void {\n let {defaultMessage, description} = descriptor\n let existingId = descriptor.id\n\n // Normalize whitespace on defaultMessage\n if (defaultMessage && !preserveWhitespace) {\n defaultMessage = defaultMessage.trim().replace(/\\s+/gm, ' ')\n }\n\n // Apply flatten transformation (hoist selectors + normalize ICU format via printAST)\n // This must happen before ID generation so the ID matches formatjs extract and babel-plugin-formatjs\n if (flatten && defaultMessage) {\n try {\n defaultMessage = printAST(hoistSelectors(parse(defaultMessage)))\n } catch {\n // If parsing fails, keep the original message\n }\n }\n\n // Generate ID\n let newId = existingId\n if (overrideIdFn) {\n newId = overrideIdFn(existingId, defaultMessage, description, id)\n } else if (!existingId && idInterpolationPattern && defaultMessage) {\n newId = interpolateName(\n {resourcePath: id} as any,\n idInterpolationPattern,\n {\n content: description\n ? `${defaultMessage}#${description}`\n : defaultMessage,\n }\n )\n }\n\n if (!newId && !defaultMessage) return\n\n if (!s) s = new MagicString(code)\n\n // Insert/update id\n if (newId) {\n if (locations.id) {\n // Replace existing id value\n s.overwrite(locations.id.start, locations.id.end, JSON.stringify(newId))\n } else if (locations.insertionPoint != null) {\n // Insert id at a stable position (after `{` for objects, before first attr for JSX)\n if (isJSX) {\n s.appendLeft(locations.insertionPoint, ` id=${JSON.stringify(newId)}`)\n } else {\n s.appendRight(\n locations.insertionPoint,\n `id: ${JSON.stringify(newId)}, `\n )\n }\n }\n }\n\n // Remove description\n if (locations.description) {\n if (isJSX) {\n // For JSX, we need to remove the whole attribute including the key\n // Find the JSX attribute that contains this value\n removeJSXAttribute(locations.description)\n } else {\n removeObjectProperty(locations.description)\n }\n }\n\n // Handle defaultMessage\n if (locations.defaultMessage) {\n if (removeDefaultMessage) {\n if (isJSX) {\n removeJSXAttribute(locations.defaultMessage)\n } else {\n removeObjectProperty(locations.defaultMessage)\n }\n } else if (defaultMessage) {\n if (preParseAst) {\n const parsed = parse(defaultMessage)\n const jsonStr = JSON.stringify(parsed)\n s.overwrite(\n locations.defaultMessage.start,\n locations.defaultMessage.end,\n isJSX ? `{${jsonStr}}` : jsonStr\n )\n } else if (defaultMessage !== locations.defaultMessage.value) {\n // Whitespace was normalized, update the value\n s.overwrite(\n locations.defaultMessage.start,\n locations.defaultMessage.end,\n JSON.stringify(defaultMessage)\n )\n }\n }\n }\n }\n\n function removeObjectProperty(loc: {start: number; end: number}): void {\n if (!s) return\n // Find the property boundaries: walk back to find key start, walk forward past trailing comma\n let propStart = loc.start\n // Walk backward past value, colon, key, and any whitespace\n let i = loc.start - 1\n while (\n i >= 0 &&\n (code[i] === ' ' ||\n code[i] === '\\t' ||\n code[i] === '\\n' ||\n code[i] === '\\r')\n )\n i--\n // Skip colon\n if (i >= 0 && code[i] === ':') i--\n while (\n i >= 0 &&\n (code[i] === ' ' ||\n code[i] === '\\t' ||\n code[i] === '\\n' ||\n code[i] === '\\r')\n )\n i--\n // Walk backward through key (identifier or string literal)\n if (i >= 0 && (code[i] === '\"' || code[i] === \"'\")) {\n const quote = code[i]\n i--\n while (i >= 0 && code[i] !== quote) i--\n if (i >= 0) i-- // skip opening quote\n } else {\n while (i >= 0 && /[a-zA-Z0-9_$]/.test(code[i])) i--\n }\n propStart = i + 1\n\n let propEnd = loc.end\n // Walk forward past trailing comma and whitespace\n let j = loc.end\n while (j < code.length && (code[j] === ' ' || code[j] === '\\t')) j++\n if (j < code.length && code[j] === ',') {\n j++\n // Also skip whitespace after comma\n while (j < code.length && (code[j] === ' ' || code[j] === '\\t')) j++\n // Skip one newline\n if (j < code.length && code[j] === '\\n') j++\n else if (j < code.length && code[j] === '\\r') {\n j++\n if (j < code.length && code[j] === '\\n') j++\n }\n }\n propEnd = j\n\n // Also remove leading whitespace/newline\n let k = propStart - 1\n while (k >= 0 && (code[k] === ' ' || code[k] === '\\t')) k--\n if (k >= 0 && (code[k] === '\\n' || code[k] === ',')) {\n propStart = k + 1\n }\n\n s.remove(propStart, propEnd)\n }\n\n function removeJSXAttribute(loc: {start: number; end: number}): void {\n if (!s) return\n // Walk backward from the value to find attribute name\n let i = loc.start - 1\n // Skip the `=`\n if (i >= 0 && code[i] === '=') i--\n // Walk backward through attribute name\n while (i >= 0 && /[a-zA-Z0-9_$]/.test(code[i])) i--\n const attrStart = i + 1\n\n const attrEnd = loc.end\n\n // Remove leading whitespace/newline before attribute name.\n // We intentionally do NOT consume trailing whitespace so that when attributes\n // are on the same line the space before the next attribute is preserved.\n // e.g. `<FM description=\"x\" defaultMessage=\"y\" />` → `<FM defaultMessage=\"y\" />`\n let k = attrStart - 1\n while (k >= 0 && (code[k] === ' ' || code[k] === '\\t')) k--\n // Also include the preceding newline for multi-line JSX so the whole line is removed.\n if (k >= 0 && code[k] === '\\n') k--\n if (k >= 0 && code[k] === '\\r') k--\n const removeStart = k + 1\n\n s.remove(removeStart, attrEnd)\n }\n\n function getCalleeName(node: any): string | undefined {\n if (node.type === 'Identifier') return node.name\n if (\n node.type === 'MemberExpression' ||\n node.type === 'OptionalMemberExpression'\n ) {\n if (node.property?.type === 'Identifier') return node.property.name\n }\n return undefined\n }\n\n function handleCallExpression(node: CallExpression): void {\n const calleeName = getCalleeName(node.callee)\n\n // Handle compiled JSX: _jsx(FormattedMessage, { id, description, defaultMessage })\n if (calleeName && jsxRuntimeFunctions.has(calleeName)) {\n const firstArg = node.arguments?.[0]\n const componentName =\n firstArg?.type === 'Identifier' ? firstArg.name : undefined\n if (componentName && componentNames.has(componentName)) {\n const propsArg = node.arguments?.[1]\n if (propsArg?.type === 'ObjectExpression') {\n const result = extractDescriptor(propsArg)\n if (result) {\n processDescriptor(result.descriptor, result.locations, false)\n }\n }\n }\n }\n\n if (calleeName && functionNames.has(calleeName)) {\n if (calleeName === 'defineMessages') {\n // Process each value in the object\n const arg = node.arguments?.[0]\n if (arg?.type === 'ObjectExpression') {\n for (const prop of arg.properties) {\n if (\n prop.type === 'Property' &&\n prop.value?.type === 'ObjectExpression'\n ) {\n const result = extractDescriptor(prop.value)\n if (result) {\n processDescriptor(result.descriptor, result.locations, false)\n }\n }\n }\n }\n } else {\n const arg = node.arguments?.[0]\n if (arg?.type === 'ObjectExpression') {\n const result = extractDescriptor(arg)\n if (result) {\n processDescriptor(result.descriptor, result.locations, false)\n }\n }\n }\n }\n }\n\n function handleJSXOpeningElement(node: JSXOpeningElement): void {\n const name =\n node.name?.type === 'JSXIdentifier' ? node.name.name : undefined\n if (name && componentNames.has(name)) {\n const result = extractJSXDescriptor(node)\n if (result) {\n processDescriptor(result.descriptor, result.locations, true)\n }\n }\n }\n\n const visitor = new Visitor({\n CallExpression: handleCallExpression,\n JSXOpeningElement: handleJSXOpeningElement,\n })\n\n visitor.visit(program)\n\n if (!s) return undefined\n\n return {\n code: s.toString(),\n map: s.generateMap({hires: 'boundary'}),\n }\n}\n","import {\n createUnplugin,\n type UnpluginFactory,\n type UnpluginInstance,\n} from 'unplugin'\nimport {transform, type Options} from '#packages/unplugin/transform.js'\n\nexport type {Options} from '#packages/unplugin/transform.js'\n\nexport const unpluginFactory: UnpluginFactory<Options | undefined> = (\n options = {}\n) => ({\n name: 'formatjs',\n enforce: 'pre' as const,\n transformInclude(id: string): boolean {\n return /\\.[jt]sx?$/.test(id) && !id.includes('node_modules')\n },\n transform(code: string, id: string) {\n return transform(code, id, options)\n },\n})\n\nexport const unplugin: UnpluginInstance<Options | undefined> =\n /* #__PURE__ */ createUnplugin(unpluginFactory)\n\nexport default unplugin\n","import {createRspackPlugin, type UnpluginInstance} from 'unplugin'\nimport {unpluginFactory} from '#packages/unplugin/index.js'\nimport type {Options} from '#packages/unplugin/transform.js'\n\nconst plugin: UnpluginInstance<Options | undefined>['rspack'] =\n createRspackPlugin(unpluginFactory)\nexport default plugin\nexport type {Options} from '#packages/unplugin/transform.js'\n"],"mappings":";;;;;;;;AAwBA,MAAM,mCAAmC;AAgBzC,SAAgB,UACd,MACA,IACA,SACyE;CACzE,MAAM,EACJ,cACA,yBAAyB,kCACzB,uBAAuB,OACvB,2BAA2B,EAAE,EAC7B,0BAA0B,EAAE,EAC5B,KAAK,cAAc,OACnB,qBAAqB,OACrB,UAAU,SACR;CAEJ,MAAM,iBAAiB,IAAI,IAAI,CAC7B,oBACA,GAAG,yBACJ,CAAC;CACF,MAAM,gBAAgB,IAAI,IAAI;EAC5B;EACA;EACA;EACA;EACA;EACA,GAAG;EACJ,CAAC;CAEF,MAAM,sBAAsB,IAAI,IAAI;EAClC;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;CAGF,MAAM,UADS,UAAU,IAAI,MAAM,EAAC,YAAY,UAAS,CAAC,CACnC;CAEvB,IAAI;CAEJ,SAAS,eAAe,MAA+B;AACrD,MAAI,CAAC,KAAM,QAAO,KAAA;AAClB,MAAI,KAAK,SAAS,mBAAmB,KAAK,SAAS,WAAW;AAC5D,OAAI,OAAO,KAAK,UAAU,SAAU,QAAO,KAAK;AAChD;;AAEF,MAAI,KAAK,SAAS,mBAAmB;AACnC,OAAI,KAAK,OAAO,WAAW,KAAK,KAAK,YAAY,WAAW,EAC1D,QAAO,KAAK,OAAO,GAAG,MAAM,UAAU,KAAK,OAAO,GAAG,MAAM;AAE7D;;A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SAAS,eAAe;;CAE9D,UAAU,MAAc,IAAY;AAClC,SAAO,UAAU,MAAM,IAAI,QAAQ;;CAEtC;;;AChBD,MAAM,SACJ,mBAAmB,gBAAgB"}
|
package/transform.d.ts
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import MagicString from "magic-string";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
2
|
+
|
|
3
|
+
//#region packages/unplugin/transform.d.ts
|
|
4
|
+
interface Options {
|
|
5
|
+
overrideIdFn?: (id: string | undefined, defaultMessage: string | undefined, description: string | undefined, filePath: string) => string;
|
|
6
|
+
idInterpolationPattern?: string;
|
|
7
|
+
removeDefaultMessage?: boolean;
|
|
8
|
+
additionalComponentNames?: string[];
|
|
9
|
+
additionalFunctionNames?: string[];
|
|
10
|
+
ast?: boolean;
|
|
11
|
+
preserveWhitespace?: boolean;
|
|
12
|
+
flatten?: boolean;
|
|
11
13
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
declare function transform(code: string, id: string, options: Options): {
|
|
15
|
+
code: string;
|
|
16
|
+
map: ReturnType<MagicString["generateMap"]>;
|
|
15
17
|
} | undefined;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { Options, transform };
|
|
20
|
+
//# sourceMappingURL=transform.d.ts.map
|