版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

1037 строки
36 KiB

  1. 'use strict';
  2. const jsoncEslintParser = require('jsonc-eslint-parser');
  3. const shared = require('@intlify/shared');
  4. const messageCompiler = require('@intlify/message-compiler');
  5. const sourceMap = require('source-map');
  6. const yamlEslintParser = require('yaml-eslint-parser');
  7. const acorn = require('acorn');
  8. const estreeWalker = require('estree-walker');
  9. const esquery = require('esquery');
  10. function createCodeGenerator(options = {
  11. filename: "bundle.json",
  12. sourceMap: false,
  13. env: "development",
  14. forceStringify: false
  15. }) {
  16. const { sourceMap: sourceMap$1, source, filename } = options;
  17. const _context = Object.assign(
  18. {
  19. code: "",
  20. column: 1,
  21. line: 1,
  22. offset: 0,
  23. map: void 0,
  24. indentLevel: 0
  25. },
  26. options
  27. );
  28. const context = () => _context;
  29. function push(code, node, name) {
  30. _context.code += code;
  31. if (_context.map && node) {
  32. if (node.loc && node.loc !== messageCompiler.LocationStub) {
  33. addMapping(node.loc.start, name);
  34. }
  35. advancePositionWithSource(_context, code);
  36. }
  37. }
  38. function _newline(n) {
  39. push("\n" + ` `.repeat(n));
  40. }
  41. function indent(withNewLine = true) {
  42. const level = ++_context.indentLevel;
  43. withNewLine && _newline(level);
  44. }
  45. function deindent(withNewLine = true) {
  46. const level = --_context.indentLevel;
  47. withNewLine && _newline(level);
  48. }
  49. function newline() {
  50. _newline(_context.indentLevel);
  51. }
  52. function pushline(code, node, name) {
  53. push(code, node, name);
  54. newline();
  55. }
  56. function addMapping(loc, name) {
  57. _context.map.addMapping({
  58. name,
  59. source: _context.filename,
  60. original: {
  61. line: loc.line,
  62. column: loc.column - 1
  63. },
  64. generated: {
  65. line: _context.line,
  66. column: _context.column - 1
  67. }
  68. });
  69. }
  70. if (sourceMap$1 && source) {
  71. _context.map = new sourceMap.SourceMapGenerator();
  72. _context.map.setSourceContent(filename, source);
  73. }
  74. return {
  75. context,
  76. push,
  77. indent,
  78. deindent,
  79. newline,
  80. pushline
  81. };
  82. }
  83. function advancePositionWithSource(pos, source, numberOfCharacters = source.length) {
  84. if (pos.offset == null) {
  85. return pos;
  86. }
  87. let linesCount = 0;
  88. let lastNewLinePos = -1;
  89. for (let i = 0; i < numberOfCharacters; i++) {
  90. if (source.charCodeAt(i) === 10) {
  91. linesCount++;
  92. lastNewLinePos = i;
  93. }
  94. }
  95. pos.offset += numberOfCharacters;
  96. pos.line += linesCount;
  97. pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;
  98. return pos;
  99. }
  100. function generateMessageFunction(msg, options, path) {
  101. const env = options.env != null ? options.env : "development";
  102. const onError = options.onError;
  103. const errors = [];
  104. const newOptions = Object.assign({ mode: "arrow" }, options);
  105. newOptions.onError = (err) => {
  106. if (onError) {
  107. const extra = {
  108. source: msg,
  109. path: path ? path.join(".") : "",
  110. code: err.code,
  111. domain: err.domain,
  112. location: err.location
  113. };
  114. onError(err.message, extra);
  115. errors.push(err);
  116. }
  117. };
  118. const { code, ast, map } = messageCompiler.baseCompile(msg, newOptions);
  119. const occured = errors.length > 0;
  120. const genCode = !occured ? env === "development" ? `(()=>{const fn=${code};fn.source=${JSON.stringify(msg)};return fn;})()` : `${code}` : msg;
  121. return { code: genCode, ast, map };
  122. }
  123. function mapLinesColumns(resMap, codeMaps, inSourceMap) {
  124. if (!resMap) {
  125. return null;
  126. }
  127. const resMapConsumer = new sourceMap.SourceMapConsumer(resMap);
  128. const inMapConsumer = inSourceMap ? new sourceMap.SourceMapConsumer(inSourceMap) : null;
  129. const mergedMapGenerator = new sourceMap.SourceMapGenerator();
  130. let inMapFirstItem = null;
  131. if (inMapConsumer) {
  132. inMapConsumer.eachMapping((m) => {
  133. if (inMapFirstItem) {
  134. return;
  135. }
  136. inMapFirstItem = m;
  137. });
  138. }
  139. resMapConsumer.eachMapping((res) => {
  140. if (res.originalLine == null) {
  141. return;
  142. }
  143. const map = codeMaps.get(res.name);
  144. if (!map) {
  145. return;
  146. }
  147. let inMapOrigin = null;
  148. if (inMapConsumer) {
  149. inMapOrigin = inMapConsumer.originalPositionFor({
  150. line: res.originalLine,
  151. column: res.originalColumn - 1
  152. });
  153. if (inMapOrigin.source == null) {
  154. inMapOrigin = null;
  155. return;
  156. }
  157. }
  158. const mapConsumer = new sourceMap.SourceMapConsumer(map);
  159. mapConsumer.eachMapping((m) => {
  160. mergedMapGenerator.addMapping({
  161. original: {
  162. line: inMapFirstItem ? inMapFirstItem.originalLine + res.originalLine - 2 : res.originalLine,
  163. column: inMapFirstItem ? inMapFirstItem.originalColumn + res.originalColumn : res.originalColumn
  164. },
  165. generated: {
  166. line: inMapFirstItem ? inMapFirstItem.generatedLine + res.originalLine - 2 : res.originalLine,
  167. // map column with message format compilation code map
  168. column: inMapFirstItem ? inMapFirstItem.generatedColumn + res.originalColumn + m.generatedColumn : res.originalColumn + m.generatedColumn
  169. },
  170. source: inMapOrigin ? inMapOrigin.source : res.source,
  171. name: m.name
  172. // message format compilation code
  173. });
  174. });
  175. });
  176. const generator = mergedMapGenerator;
  177. const targetConsumer = inMapConsumer || resMapConsumer;
  178. targetConsumer.sources.forEach((sourceFile) => {
  179. generator._sources.add(sourceFile);
  180. const sourceContent = targetConsumer.sourceContentFor(sourceFile);
  181. if (sourceContent != null) {
  182. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  183. }
  184. });
  185. generator._sourceRoot = inSourceMap ? inSourceMap.sourceRoot : resMap.sourceRoot;
  186. generator._file = inSourceMap ? inSourceMap.file : resMap.file;
  187. return generator.toJSON();
  188. }
  189. function generate$2(targetSource, {
  190. type = "plain",
  191. bridge = false,
  192. exportESM = false,
  193. filename = "vue-i18n-loader.json",
  194. inSourceMap = void 0,
  195. locale = "",
  196. isGlobal = false,
  197. sourceMap = false,
  198. env = "development",
  199. forceStringify = false,
  200. onError = void 0,
  201. useClassComponent = false
  202. }, injector) {
  203. const target = Buffer.isBuffer(targetSource) ? targetSource.toString() : targetSource;
  204. const value = target;
  205. const options = {
  206. type,
  207. bridge,
  208. exportESM,
  209. source: value,
  210. sourceMap,
  211. locale,
  212. isGlobal,
  213. inSourceMap,
  214. env,
  215. filename,
  216. forceStringify,
  217. onError,
  218. useClassComponent
  219. };
  220. const generator = createCodeGenerator(options);
  221. const ast = jsoncEslintParser.parseJSON(value, { filePath: filename });
  222. const codeMaps = generateNode$2(generator, ast, options, injector);
  223. const { code, map } = generator.context();
  224. const newMap = map ? mapLinesColumns(map.toJSON(), codeMaps, inSourceMap) || null : null;
  225. return {
  226. ast,
  227. code,
  228. map: newMap != null ? newMap : void 0
  229. };
  230. }
  231. function generateNode$2(generator, node, options, injector) {
  232. const propsCountStack = [];
  233. const pathStack = [];
  234. const itemsCountStack = [];
  235. const { forceStringify } = generator.context();
  236. const codeMaps = /* @__PURE__ */ new Map();
  237. const {
  238. type,
  239. bridge,
  240. exportESM,
  241. sourceMap,
  242. isGlobal,
  243. locale,
  244. useClassComponent
  245. } = options;
  246. const componentNamespace = bridge ? `Component.options` : useClassComponent ? `Component.__o` : `Component`;
  247. jsoncEslintParser.traverseNodes(node, {
  248. enterNode(node2, parent) {
  249. switch (node2.type) {
  250. case "Program":
  251. if (type === "plain") {
  252. generator.push(`export default `);
  253. } else if (type === "sfc") {
  254. const variableName = type === "sfc" ? !isGlobal ? "__i18n" : "__i18nGlobal" : "";
  255. const localeName = type === "sfc" ? locale != null ? locale : `""` : "";
  256. const exportSyntax = bridge ? exportESM ? `export default` : `module.exports =` : `export default`;
  257. generator.push(`${exportSyntax} function (Component) {`);
  258. generator.indent();
  259. generator.pushline(
  260. `${componentNamespace}.${variableName} = ${componentNamespace}.${variableName} || []`
  261. );
  262. generator.push(`${componentNamespace}.${variableName}.push({`);
  263. generator.indent();
  264. generator.pushline(`"locale": ${JSON.stringify(localeName)},`);
  265. generator.push(`"resource": `);
  266. }
  267. break;
  268. case "JSONObjectExpression":
  269. generator.push(`{`);
  270. generator.indent();
  271. propsCountStack.push(node2.properties.length);
  272. if (parent.type === "JSONArrayExpression") {
  273. const lastIndex2 = itemsCountStack.length - 1;
  274. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  275. pathStack.push(currentCount.toString());
  276. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  277. }
  278. break;
  279. case "JSONProperty":
  280. if (node2.value.type === "JSONLiteral" && (node2.key.type === "JSONLiteral" || node2.key.type === "JSONIdentifier")) {
  281. const name = node2.key.type === "JSONLiteral" ? node2.key.value : node2.key.name;
  282. const value = node2.value.value;
  283. if (shared.isString(value)) {
  284. generator.push(`${JSON.stringify(name)}: `);
  285. pathStack.push(name.toString());
  286. const { code, map } = generateMessageFunction(
  287. value,
  288. options,
  289. pathStack
  290. );
  291. sourceMap && map != null && codeMaps.set(value, map);
  292. generator.push(`${code}`, node2.value, value);
  293. } else {
  294. if (forceStringify) {
  295. const strValue = JSON.stringify(value);
  296. generator.push(`${JSON.stringify(name)}: `);
  297. pathStack.push(name.toString());
  298. const { code, map } = generateMessageFunction(
  299. strValue,
  300. options,
  301. pathStack
  302. );
  303. sourceMap && map != null && codeMaps.set(strValue, map);
  304. generator.push(`${code}`, node2.value, strValue);
  305. } else {
  306. generator.push(
  307. `${JSON.stringify(name)}: ${JSON.stringify(value)}`
  308. );
  309. pathStack.push(name.toString());
  310. }
  311. }
  312. } else if ((node2.value.type === "JSONObjectExpression" || node2.value.type === "JSONArrayExpression") && (node2.key.type === "JSONLiteral" || node2.key.type === "JSONIdentifier")) {
  313. const name = node2.key.type === "JSONLiteral" ? node2.key.value : node2.key.name;
  314. generator.push(`${JSON.stringify(name)}: `);
  315. pathStack.push(name.toString());
  316. }
  317. const lastIndex = propsCountStack.length - 1;
  318. propsCountStack[lastIndex] = --propsCountStack[lastIndex];
  319. break;
  320. case "JSONArrayExpression":
  321. generator.push(`[`);
  322. generator.indent();
  323. if (parent.type === "JSONArrayExpression") {
  324. const lastIndex2 = itemsCountStack.length - 1;
  325. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  326. pathStack.push(currentCount.toString());
  327. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  328. }
  329. itemsCountStack.push(node2.elements.length);
  330. break;
  331. case "JSONLiteral":
  332. if (parent.type === "JSONArrayExpression") {
  333. const lastIndex2 = itemsCountStack.length - 1;
  334. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  335. pathStack.push(currentCount.toString());
  336. if (node2.type === "JSONLiteral") {
  337. const value = node2.value;
  338. if (shared.isString(value)) {
  339. const { code, map } = generateMessageFunction(
  340. value,
  341. options,
  342. pathStack
  343. );
  344. sourceMap && map != null && codeMaps.set(value, map);
  345. generator.push(`${code}`, node2, value);
  346. } else {
  347. if (forceStringify) {
  348. const strValue = JSON.stringify(value);
  349. const { code, map } = generateMessageFunction(
  350. strValue,
  351. options,
  352. pathStack
  353. );
  354. sourceMap && map != null && codeMaps.set(strValue, map);
  355. generator.push(`${code}`, node2, strValue);
  356. } else {
  357. generator.push(`${JSON.stringify(value)}`);
  358. }
  359. }
  360. }
  361. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  362. }
  363. break;
  364. }
  365. },
  366. leaveNode(node2, parent) {
  367. switch (node2.type) {
  368. case "Program":
  369. if (type === "sfc") {
  370. generator.deindent();
  371. generator.push(`})`);
  372. if (bridge && injector) {
  373. generator.newline();
  374. generator.pushline(
  375. `${componentNamespace}.__i18nBridge = ${componentNamespace}.__i18nBridge || []`
  376. );
  377. generator.pushline(
  378. `${componentNamespace}.__i18nBridge.push('${injector()}')`
  379. );
  380. generator.pushline(`delete ${componentNamespace}._Ctor`);
  381. }
  382. generator.deindent();
  383. generator.pushline(`}`);
  384. }
  385. break;
  386. case "JSONObjectExpression":
  387. if (propsCountStack[propsCountStack.length - 1] === 0) {
  388. pathStack.pop();
  389. propsCountStack.pop();
  390. }
  391. generator.deindent();
  392. generator.push(`}`);
  393. if (parent.type === "JSONArrayExpression") {
  394. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  395. pathStack.pop();
  396. generator.pushline(`,`);
  397. }
  398. }
  399. break;
  400. case "JSONProperty":
  401. if (propsCountStack[propsCountStack.length - 1] !== 0) {
  402. pathStack.pop();
  403. generator.pushline(`,`);
  404. }
  405. break;
  406. case "JSONArrayExpression":
  407. if (itemsCountStack[itemsCountStack.length - 1] === 0) {
  408. pathStack.pop();
  409. itemsCountStack.pop();
  410. }
  411. generator.deindent();
  412. generator.push(`]`);
  413. if (parent.type === "JSONArrayExpression") {
  414. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  415. pathStack.pop();
  416. generator.pushline(`,`);
  417. }
  418. }
  419. break;
  420. case "JSONLiteral":
  421. if (parent.type === "JSONArrayExpression") {
  422. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  423. pathStack.pop();
  424. generator.pushline(`,`);
  425. } else {
  426. generator.pushline(`,`);
  427. }
  428. }
  429. break;
  430. }
  431. }
  432. });
  433. return codeMaps;
  434. }
  435. function generate$1(targetSource, {
  436. type = "plain",
  437. bridge = false,
  438. exportESM = false,
  439. useClassComponent = false,
  440. filename = "vue-i18n-loader.yaml",
  441. inSourceMap = void 0,
  442. locale = "",
  443. isGlobal = false,
  444. sourceMap = false,
  445. env = "development",
  446. forceStringify = false,
  447. onError = void 0
  448. }, injector) {
  449. const value = Buffer.isBuffer(targetSource) ? targetSource.toString() : targetSource;
  450. const options = {
  451. type,
  452. bridge,
  453. exportESM,
  454. source: value,
  455. sourceMap,
  456. locale,
  457. isGlobal,
  458. inSourceMap,
  459. env,
  460. filename,
  461. forceStringify,
  462. onError,
  463. useClassComponent
  464. };
  465. const generator = createCodeGenerator(options);
  466. const ast = yamlEslintParser.parseYAML(value, { filePath: filename });
  467. const codeMaps = generateNode$1(generator, ast, options, injector);
  468. const { code, map } = generator.context();
  469. const newMap = map ? mapLinesColumns(map.toJSON(), codeMaps, inSourceMap) || null : null;
  470. return {
  471. ast,
  472. code,
  473. map: newMap != null ? newMap : void 0
  474. };
  475. }
  476. function generateNode$1(generator, node, options, injector) {
  477. const propsCountStack = [];
  478. const pathStack = [];
  479. const itemsCountStack = [];
  480. const { forceStringify } = generator.context();
  481. const codeMaps = /* @__PURE__ */ new Map();
  482. const {
  483. type,
  484. bridge,
  485. exportESM,
  486. sourceMap,
  487. isGlobal,
  488. locale,
  489. useClassComponent
  490. } = options;
  491. const componentNamespace = bridge ? `Component.options` : useClassComponent ? `Component.__o` : `Component`;
  492. yamlEslintParser.traverseNodes(node, {
  493. enterNode(node2, parent) {
  494. switch (node2.type) {
  495. case "Program":
  496. if (type === "plain") {
  497. generator.push(`export default `);
  498. } else if (type === "sfc") {
  499. const variableName = type === "sfc" ? !isGlobal ? "__i18n" : "__i18nGlobal" : "";
  500. const localeName = type === "sfc" ? locale != null ? locale : `""` : "";
  501. const exportSyntax = bridge ? exportESM ? `export default` : `module.exports =` : `export default`;
  502. generator.push(`${exportSyntax} function (Component) {`);
  503. generator.indent();
  504. generator.pushline(
  505. `${componentNamespace}.${variableName} = ${componentNamespace}.${variableName} || []`
  506. );
  507. generator.push(`${componentNamespace}.${variableName}.push({`);
  508. generator.indent();
  509. generator.pushline(`"locale": ${JSON.stringify(localeName)},`);
  510. generator.push(`"resource": `);
  511. }
  512. break;
  513. case "YAMLMapping":
  514. generator.push(`{`);
  515. generator.indent();
  516. propsCountStack.push(node2.pairs.length);
  517. if (parent.type === "YAMLSequence") {
  518. const lastIndex2 = itemsCountStack.length - 1;
  519. const currentCount = parent.entries.length - itemsCountStack[lastIndex2];
  520. pathStack.push(currentCount.toString());
  521. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  522. }
  523. break;
  524. case "YAMLPair":
  525. if (node2.value && node2.value.type === "YAMLScalar" && node2.key && node2.key.type === "YAMLScalar") {
  526. const name = node2.key.value;
  527. const value = node2.value.value;
  528. if (shared.isString(value)) {
  529. generator.push(`${JSON.stringify(name)}: `);
  530. name && pathStack.push(name.toString());
  531. const { code, map } = generateMessageFunction(
  532. value,
  533. options,
  534. pathStack
  535. );
  536. sourceMap && map != null && codeMaps.set(value, map);
  537. generator.push(`${code}`, node2.value, value);
  538. } else {
  539. if (forceStringify) {
  540. const strValue = JSON.stringify(value);
  541. generator.push(`${JSON.stringify(name)}: `);
  542. name && pathStack.push(name.toString());
  543. const { code, map } = generateMessageFunction(
  544. strValue,
  545. options,
  546. pathStack
  547. );
  548. sourceMap && map != null && codeMaps.set(strValue, map);
  549. generator.push(`${code}`, node2.value, strValue);
  550. } else {
  551. generator.push(
  552. `${JSON.stringify(name)}: ${JSON.stringify(value)}`
  553. );
  554. name && pathStack.push(name.toString());
  555. }
  556. }
  557. } else if (node2.value && (node2.value.type === "YAMLMapping" || node2.value.type === "YAMLSequence") && node2.key && node2.key.type === "YAMLScalar") {
  558. const name = node2.key.value;
  559. generator.push(`${JSON.stringify(name)}: `);
  560. name && pathStack.push(name.toString());
  561. }
  562. const lastIndex = propsCountStack.length - 1;
  563. propsCountStack[lastIndex] = --propsCountStack[lastIndex];
  564. break;
  565. case "YAMLSequence":
  566. generator.push(`[`);
  567. generator.indent();
  568. if (parent.type === "YAMLSequence") {
  569. const lastIndex2 = itemsCountStack.length - 1;
  570. const currentCount = parent.entries.length - itemsCountStack[lastIndex2];
  571. pathStack.push(currentCount.toString());
  572. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  573. }
  574. itemsCountStack.push(node2.entries.length);
  575. break;
  576. case "YAMLScalar":
  577. if (parent.type === "YAMLSequence") {
  578. const lastIndex2 = itemsCountStack.length - 1;
  579. const currentCount = parent.entries.length - itemsCountStack[lastIndex2];
  580. pathStack.push(currentCount.toString());
  581. if (node2.type === "YAMLScalar") {
  582. const value = node2.value;
  583. if (shared.isString(value)) {
  584. const { code, map } = generateMessageFunction(
  585. value,
  586. options,
  587. pathStack
  588. );
  589. sourceMap && map != null && codeMaps.set(value, map);
  590. generator.push(`${code}`, node2, value);
  591. } else {
  592. if (forceStringify) {
  593. const strValue = JSON.stringify(value);
  594. const { code, map } = generateMessageFunction(
  595. strValue,
  596. options,
  597. pathStack
  598. );
  599. sourceMap && map != null && codeMaps.set(strValue, map);
  600. generator.push(`${code}`, node2, strValue);
  601. } else {
  602. generator.push(`${JSON.stringify(value)}`);
  603. }
  604. }
  605. }
  606. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  607. }
  608. break;
  609. }
  610. },
  611. leaveNode(node2, parent) {
  612. switch (node2.type) {
  613. case "Program":
  614. if (type === "sfc") {
  615. generator.deindent();
  616. generator.push(`})`);
  617. if (bridge && injector) {
  618. generator.newline();
  619. generator.pushline(
  620. `${componentNamespace}.__i18nBridge = ${componentNamespace}.__i18nBridge || []`
  621. );
  622. generator.pushline(
  623. `${componentNamespace}.__i18nBridge.push('${injector()}')`
  624. );
  625. generator.pushline(`delete ${componentNamespace}._Ctor`);
  626. }
  627. generator.deindent();
  628. generator.push(`}`);
  629. }
  630. break;
  631. case "YAMLMapping":
  632. if (propsCountStack[propsCountStack.length - 1] === 0) {
  633. pathStack.pop();
  634. propsCountStack.pop();
  635. }
  636. generator.deindent();
  637. generator.push(`}`);
  638. if (parent.type === "YAMLSequence") {
  639. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  640. pathStack.pop();
  641. generator.pushline(`,`);
  642. }
  643. }
  644. break;
  645. case "YAMLPair":
  646. if (propsCountStack[propsCountStack.length - 1] !== 0) {
  647. pathStack.pop();
  648. generator.pushline(`,`);
  649. }
  650. break;
  651. case "YAMLSequence":
  652. if (itemsCountStack[itemsCountStack.length - 1] === 0) {
  653. pathStack.pop();
  654. itemsCountStack.pop();
  655. }
  656. generator.deindent();
  657. generator.push(`]`);
  658. if (parent.type === "YAMLSequence") {
  659. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  660. pathStack.pop();
  661. generator.pushline(`,`);
  662. }
  663. }
  664. break;
  665. case "YAMLScalar":
  666. if (parent.type === "YAMLSequence") {
  667. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  668. pathStack.pop();
  669. generator.pushline(`,`);
  670. } else {
  671. generator.pushline(`,`);
  672. }
  673. }
  674. break;
  675. }
  676. }
  677. });
  678. return codeMaps;
  679. }
  680. function generate(targetSource, {
  681. type = "plain",
  682. bridge = false,
  683. exportESM = false,
  684. filename = "vue-i18n-loader.js",
  685. inSourceMap = void 0,
  686. locale = "",
  687. isGlobal = false,
  688. sourceMap = false,
  689. env = "development",
  690. forceStringify = false,
  691. onError = void 0,
  692. useClassComponent = false
  693. }, injector) {
  694. const target = Buffer.isBuffer(targetSource) ? targetSource.toString() : targetSource;
  695. const value = target;
  696. const options = {
  697. type,
  698. bridge,
  699. exportESM,
  700. source: value,
  701. sourceMap,
  702. locale,
  703. isGlobal,
  704. inSourceMap,
  705. env,
  706. filename,
  707. forceStringify,
  708. onError,
  709. useClassComponent
  710. };
  711. const generator = createCodeGenerator(options);
  712. const ast = acorn.parse(value, {
  713. ecmaVersion: "latest",
  714. sourceType: "module",
  715. sourceFile: filename,
  716. allowImportExportEverywhere: true
  717. });
  718. const selectedWithExportDefault = esquery(
  719. ast,
  720. "Program:has(ExportDefaultDeclaration, [declaration=ObjectExpression])"
  721. );
  722. if (!selectedWithExportDefault.length) {
  723. throw new Error(
  724. `You need to define an object as the locale message with "export default'.`
  725. );
  726. }
  727. const codeMaps = generateNode(generator, ast, options, injector);
  728. const { code, map } = generator.context();
  729. const newMap = map ? mapLinesColumns(map.toJSON(), codeMaps, inSourceMap) || null : null;
  730. return {
  731. ast,
  732. code,
  733. map: newMap != null ? newMap : void 0
  734. };
  735. }
  736. function generateNode(generator, node, options, injector) {
  737. const propsCountStack = [];
  738. const pathStack = [];
  739. const itemsCountStack = [];
  740. const skipStack = [];
  741. const { forceStringify } = generator.context();
  742. const codeMaps = /* @__PURE__ */ new Map();
  743. const {
  744. type,
  745. bridge,
  746. exportESM,
  747. sourceMap,
  748. isGlobal,
  749. locale,
  750. useClassComponent
  751. } = options;
  752. const componentNamespace = bridge ? `Component.options` : useClassComponent ? `Component.__o` : `Component`;
  753. estreeWalker.walk(node, {
  754. enter(node2, parent) {
  755. switch (node2.type) {
  756. case "Program":
  757. if (type === "plain") {
  758. generator.push(`export default `);
  759. } else if (type === "sfc") {
  760. const variableName = type === "sfc" ? !isGlobal ? "__i18n" : "__i18nGlobal" : "";
  761. const localeName = type === "sfc" ? locale != null ? locale : `""` : "";
  762. const exportSyntax = bridge ? exportESM ? `export default` : `module.exports =` : `export default`;
  763. generator.push(`${exportSyntax} function (Component) {`);
  764. generator.indent();
  765. generator.pushline(
  766. `${componentNamespace}.${variableName} = ${componentNamespace}.${variableName} || []`
  767. );
  768. generator.push(`${componentNamespace}.${variableName}.push({`);
  769. generator.indent();
  770. generator.pushline(`"locale": ${JSON.stringify(localeName)},`);
  771. generator.push(`"resource": `);
  772. }
  773. break;
  774. case "ObjectExpression":
  775. generator.push(`{`);
  776. generator.indent();
  777. propsCountStack.push(node2.properties.length);
  778. if (parent != null && parent.type === "ArrayExpression") {
  779. const lastIndex2 = itemsCountStack.length - 1;
  780. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  781. pathStack.push(currentCount.toString());
  782. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  783. }
  784. break;
  785. case "Property":
  786. if (node2 != null) {
  787. if (isJSONablePrimitiveLiteral(node2.value) && (node2.key.type === "Literal" || node2.key.type === "Identifier")) {
  788. const name = node2.key.type === "Literal" ? String(node2.key.value) : node2.key.name;
  789. if (node2.value.type === "Literal" && shared.isString(node2.value.value) || node2.value.type === "TemplateLiteral") {
  790. const value = getValue(node2.value);
  791. generator.push(`${JSON.stringify(name)}: `);
  792. pathStack.push(name);
  793. const { code, map } = generateMessageFunction(
  794. value,
  795. options,
  796. pathStack
  797. );
  798. sourceMap && map != null && codeMaps.set(value, map);
  799. generator.push(`${code}`, node2.value, value);
  800. skipStack.push(false);
  801. } else {
  802. const value = getValue(node2.value);
  803. if (forceStringify) {
  804. const strValue = JSON.stringify(value);
  805. generator.push(`${JSON.stringify(name)}: `);
  806. pathStack.push(name);
  807. const { code, map } = generateMessageFunction(
  808. strValue,
  809. options,
  810. pathStack
  811. );
  812. sourceMap && map != null && codeMaps.set(strValue, map);
  813. generator.push(`${code}`, node2.value, strValue);
  814. } else {
  815. generator.push(
  816. `${JSON.stringify(name)}: ${JSON.stringify(value)}`
  817. );
  818. pathStack.push(name);
  819. }
  820. skipStack.push(false);
  821. }
  822. } else if ((node2.value.type === "ObjectExpression" || node2.value.type === "ArrayExpression") && (node2.key.type === "Literal" || node2.key.type === "Identifier")) {
  823. const name = node2.key.type === "Literal" ? String(node2.key.value) : node2.key.name;
  824. generator.push(`${JSON.stringify(name)}: `);
  825. pathStack.push(name);
  826. } else {
  827. skipStack.push(true);
  828. }
  829. }
  830. const lastIndex = propsCountStack.length - 1;
  831. propsCountStack[lastIndex] = --propsCountStack[lastIndex];
  832. break;
  833. case "ArrayExpression":
  834. generator.push(`[`);
  835. generator.indent();
  836. if (parent != null && parent.type === "ArrayExpression") {
  837. const lastIndex2 = itemsCountStack.length - 1;
  838. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  839. pathStack.push(currentCount.toString());
  840. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  841. }
  842. itemsCountStack.push(node2.elements.length);
  843. break;
  844. default:
  845. if (node2 != null && parent != null) {
  846. if (parent.type === "ArrayExpression") {
  847. const lastIndex2 = itemsCountStack.length - 1;
  848. const currentCount = parent.elements.length - itemsCountStack[lastIndex2];
  849. pathStack.push(currentCount.toString());
  850. if (isJSONablePrimitiveLiteral(node2)) {
  851. if (node2.type === "Literal" && shared.isString(node2.value) || node2.type === "TemplateLiteral") {
  852. const value = getValue(node2);
  853. const { code, map } = generateMessageFunction(
  854. value,
  855. options,
  856. pathStack
  857. );
  858. sourceMap && map != null && codeMaps.set(value, map);
  859. generator.push(`${code}`, node2, value);
  860. } else {
  861. const value = getValue(node2);
  862. if (forceStringify) {
  863. const strValue = JSON.stringify(value);
  864. const { code, map } = generateMessageFunction(
  865. strValue,
  866. options,
  867. pathStack
  868. );
  869. sourceMap && map != null && codeMaps.set(strValue, map);
  870. generator.push(`${code}`, node2, strValue);
  871. } else {
  872. generator.push(`${JSON.stringify(value)}`);
  873. }
  874. }
  875. skipStack.push(false);
  876. } else {
  877. skipStack.push(true);
  878. }
  879. itemsCountStack[lastIndex2] = --itemsCountStack[lastIndex2];
  880. }
  881. }
  882. break;
  883. }
  884. },
  885. leave(node2, parent) {
  886. switch (node2.type) {
  887. case "Program":
  888. if (type === "sfc") {
  889. generator.deindent();
  890. generator.push(`})`);
  891. if (bridge && injector) {
  892. generator.newline();
  893. generator.pushline(
  894. `${componentNamespace}.__i18nBridge = ${componentNamespace}.__i18nBridge || []`
  895. );
  896. generator.pushline(
  897. `${componentNamespace}.__i18nBridge.push('${injector()}')`
  898. );
  899. generator.pushline(`delete ${componentNamespace}._Ctor`);
  900. }
  901. generator.deindent();
  902. generator.pushline(`}`);
  903. }
  904. break;
  905. case "ObjectExpression":
  906. if (propsCountStack[propsCountStack.length - 1] === 0) {
  907. pathStack.pop();
  908. propsCountStack.pop();
  909. }
  910. generator.deindent();
  911. generator.push(`}`);
  912. if (parent != null && parent.type === "ArrayExpression") {
  913. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  914. pathStack.pop();
  915. generator.pushline(`,`);
  916. }
  917. }
  918. break;
  919. case "Property":
  920. if (propsCountStack[propsCountStack.length - 1] !== 0) {
  921. pathStack.pop();
  922. if (!skipStack.pop()) {
  923. generator.pushline(`,`);
  924. }
  925. }
  926. break;
  927. case "ArrayExpression":
  928. if (itemsCountStack[itemsCountStack.length - 1] === 0) {
  929. pathStack.pop();
  930. itemsCountStack.pop();
  931. }
  932. generator.deindent();
  933. generator.push(`]`);
  934. if (parent != null && parent.type === "ArrayExpression") {
  935. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  936. pathStack.pop();
  937. if (!skipStack.pop()) {
  938. generator.pushline(`,`);
  939. }
  940. }
  941. }
  942. break;
  943. case "Literal":
  944. if (parent != null && parent.type === "ArrayExpression") {
  945. if (itemsCountStack[itemsCountStack.length - 1] !== 0) {
  946. pathStack.pop();
  947. if (!skipStack.pop()) {
  948. generator.pushline(`,`);
  949. }
  950. } else {
  951. if (!skipStack.pop()) {
  952. generator.pushline(`,`);
  953. }
  954. }
  955. }
  956. break;
  957. }
  958. }
  959. });
  960. return codeMaps;
  961. }
  962. function isJSONablePrimitiveLiteral(node) {
  963. return node.type === "Literal" && (shared.isString(node.value) || shared.isNumber(node.value) || shared.isBoolean(node.value) || node.value === null) || node.type === "TemplateLiteral";
  964. }
  965. function getValue(node) {
  966. return node.type === "Literal" ? node.value : node.type === "TemplateLiteral" ? node.quasis.map((quasi) => quasi.value.cooked).join("") : void 0;
  967. }
  968. function checkInstallPackage(pkg, debug) {
  969. let installedVueI18n = false;
  970. try {
  971. debug(`vue-i18n load path: ${require.resolve("vue-i18n")}`);
  972. installedVueI18n = true;
  973. } catch (e) {
  974. debug(`cannot find 'vue-i18n'`, e);
  975. }
  976. let installedPetiteVueI18n = false;
  977. try {
  978. debug(`petite-vue-i18n load path: ${require.resolve("petite-vue-i18n")}`);
  979. installedPetiteVueI18n = true;
  980. } catch (e) {
  981. debug(`cannot find 'petite-vue-i18n'`, e);
  982. }
  983. if (installedVueI18n) {
  984. return "vue-i18n";
  985. }
  986. if (installedPetiteVueI18n) {
  987. return "petite-vue-i18n";
  988. }
  989. throw new Error(
  990. `${pkg} requires 'vue-i18n' or 'petite-vue-i18n' to be present in the dependency tree.`
  991. );
  992. }
  993. function checkVueI18nBridgeInstallPackage(debug) {
  994. let ret = false;
  995. try {
  996. debug(`vue-i18n-bridge load path: ${require.resolve("vue-i18n-bridge")}`);
  997. ret = true;
  998. } catch (e) {
  999. debug(`cannot find 'vue-i18n-bridge'`, e);
  1000. }
  1001. return ret;
  1002. }
  1003. function getVueI18nVersion(debug) {
  1004. const VueI18n = loadModule("vue-i18n", debug);
  1005. if (VueI18n == null) {
  1006. return "";
  1007. }
  1008. if (VueI18n.version && VueI18n.version.startsWith("8.")) {
  1009. return "8";
  1010. }
  1011. if (VueI18n.VERSION && VueI18n.VERSION.startsWith("9.")) {
  1012. return "9";
  1013. }
  1014. return "unknown";
  1015. }
  1016. function loadModule(moduleName, debug) {
  1017. try {
  1018. return require(moduleName);
  1019. } catch (e) {
  1020. debug(`cannot load '${moduleName}'`, e);
  1021. return null;
  1022. }
  1023. }
  1024. exports.checkInstallPackage = checkInstallPackage;
  1025. exports.checkVueI18nBridgeInstallPackage = checkVueI18nBridgeInstallPackage;
  1026. exports.generateJSON = generate$2;
  1027. exports.generateJavaScript = generate;
  1028. exports.generateYAML = generate$1;
  1029. exports.getVueI18nVersion = getVueI18nVersion;