message-compiler.esm-browser.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. /*!
  2. * @intlify/message-compiler v9.1.9
  3. * (c) 2021 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. /**
  7. * Original Utilities
  8. * written by kazuya kawaguchi
  9. */
  10. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  11. /* eslint-disable */
  12. function format(message, ...args) {
  13. if (args.length === 1 && isObject(args[0])) {
  14. args = args[0];
  15. }
  16. if (!args || !args.hasOwnProperty) {
  17. args = {};
  18. }
  19. return message.replace(RE_ARGS, (match, identifier) => {
  20. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  21. });
  22. }
  23. const assign = Object.assign;
  24. const isString = (val) => typeof val === 'string';
  25. const isObject = (val) => // eslint-disable-line
  26. val !== null && typeof val === 'object';
  27. /** @internal */
  28. const errorMessages = {
  29. // tokenizer error messages
  30. [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
  31. [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
  32. [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
  33. [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
  34. [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
  35. [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
  36. [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
  37. [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
  38. [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
  39. [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
  40. // parser error messages
  41. [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
  42. [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`,
  43. [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`,
  44. [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
  45. };
  46. function createCompileError(code, loc, options = {}) {
  47. const { domain, messages, args } = options;
  48. const msg = format((messages || errorMessages)[code] || '', ...(args || []))
  49. ;
  50. const error = new SyntaxError(String(msg));
  51. error.code = code;
  52. if (loc) {
  53. error.location = loc;
  54. }
  55. error.domain = domain;
  56. return error;
  57. }
  58. /** @internal */
  59. function defaultOnError(error) {
  60. throw error;
  61. }
  62. const LocationStub = {
  63. start: { line: 1, column: 1, offset: 0 },
  64. end: { line: 1, column: 1, offset: 0 }
  65. };
  66. function createPosition(line, column, offset) {
  67. return { line, column, offset };
  68. }
  69. function createLocation(start, end, source) {
  70. const loc = { start, end };
  71. if (source != null) {
  72. loc.source = source;
  73. }
  74. return loc;
  75. }
  76. const CHAR_SP = ' ';
  77. const CHAR_CR = '\r';
  78. const CHAR_LF = '\n';
  79. const CHAR_LS = String.fromCharCode(0x2028);
  80. const CHAR_PS = String.fromCharCode(0x2029);
  81. function createScanner(str) {
  82. const _buf = str;
  83. let _index = 0;
  84. let _line = 1;
  85. let _column = 1;
  86. let _peekOffset = 0;
  87. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  88. const isLF = (index) => _buf[index] === CHAR_LF;
  89. const isPS = (index) => _buf[index] === CHAR_PS;
  90. const isLS = (index) => _buf[index] === CHAR_LS;
  91. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  92. const index = () => _index;
  93. const line = () => _line;
  94. const column = () => _column;
  95. const peekOffset = () => _peekOffset;
  96. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  97. const currentChar = () => charAt(_index);
  98. const currentPeek = () => charAt(_index + _peekOffset);
  99. function next() {
  100. _peekOffset = 0;
  101. if (isLineEnd(_index)) {
  102. _line++;
  103. _column = 0;
  104. }
  105. if (isCRLF(_index)) {
  106. _index++;
  107. }
  108. _index++;
  109. _column++;
  110. return _buf[_index];
  111. }
  112. function peek() {
  113. if (isCRLF(_index + _peekOffset)) {
  114. _peekOffset++;
  115. }
  116. _peekOffset++;
  117. return _buf[_index + _peekOffset];
  118. }
  119. function reset() {
  120. _index = 0;
  121. _line = 1;
  122. _column = 1;
  123. _peekOffset = 0;
  124. }
  125. function resetPeek(offset = 0) {
  126. _peekOffset = offset;
  127. }
  128. function skipToPeek() {
  129. const target = _index + _peekOffset;
  130. // eslint-disable-next-line no-unmodified-loop-condition
  131. while (target !== _index) {
  132. next();
  133. }
  134. _peekOffset = 0;
  135. }
  136. return {
  137. index,
  138. line,
  139. column,
  140. peekOffset,
  141. charAt,
  142. currentChar,
  143. currentPeek,
  144. next,
  145. peek,
  146. reset,
  147. resetPeek,
  148. skipToPeek
  149. };
  150. }
  151. const EOF = undefined;
  152. const LITERAL_DELIMITER = "'";
  153. const ERROR_DOMAIN$1 = 'tokenizer';
  154. function createTokenizer(source, options = {}) {
  155. const location = options.location !== false;
  156. const _scnr = createScanner(source);
  157. const currentOffset = () => _scnr.index();
  158. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  159. const _initLoc = currentPosition();
  160. const _initOffset = currentOffset();
  161. const _context = {
  162. currentType: 14 /* EOF */,
  163. offset: _initOffset,
  164. startLoc: _initLoc,
  165. endLoc: _initLoc,
  166. lastType: 14 /* EOF */,
  167. lastOffset: _initOffset,
  168. lastStartLoc: _initLoc,
  169. lastEndLoc: _initLoc,
  170. braceNest: 0,
  171. inLinked: false,
  172. text: ''
  173. };
  174. const context = () => _context;
  175. const { onError } = options;
  176. function emitError(code, pos, offset, ...args) {
  177. const ctx = context();
  178. pos.column += offset;
  179. pos.offset += offset;
  180. if (onError) {
  181. const loc = createLocation(ctx.startLoc, pos);
  182. const err = createCompileError(code, loc, {
  183. domain: ERROR_DOMAIN$1,
  184. args
  185. });
  186. onError(err);
  187. }
  188. }
  189. function getToken(context, type, value) {
  190. context.endLoc = currentPosition();
  191. context.currentType = type;
  192. const token = { type };
  193. if (location) {
  194. token.loc = createLocation(context.startLoc, context.endLoc);
  195. }
  196. if (value != null) {
  197. token.value = value;
  198. }
  199. return token;
  200. }
  201. const getEndToken = (context) => getToken(context, 14 /* EOF */);
  202. function eat(scnr, ch) {
  203. if (scnr.currentChar() === ch) {
  204. scnr.next();
  205. return ch;
  206. }
  207. else {
  208. emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
  209. return '';
  210. }
  211. }
  212. function peekSpaces(scnr) {
  213. let buf = '';
  214. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  215. buf += scnr.currentPeek();
  216. scnr.peek();
  217. }
  218. return buf;
  219. }
  220. function skipSpaces(scnr) {
  221. const buf = peekSpaces(scnr);
  222. scnr.skipToPeek();
  223. return buf;
  224. }
  225. function isIdentifierStart(ch) {
  226. if (ch === EOF) {
  227. return false;
  228. }
  229. const cc = ch.charCodeAt(0);
  230. return ((cc >= 97 && cc <= 122) || // a-z
  231. (cc >= 65 && cc <= 90) || // A-Z
  232. cc === 95 // _
  233. );
  234. }
  235. function isNumberStart(ch) {
  236. if (ch === EOF) {
  237. return false;
  238. }
  239. const cc = ch.charCodeAt(0);
  240. return cc >= 48 && cc <= 57; // 0-9
  241. }
  242. function isNamedIdentifierStart(scnr, context) {
  243. const { currentType } = context;
  244. if (currentType !== 2 /* BraceLeft */) {
  245. return false;
  246. }
  247. peekSpaces(scnr);
  248. const ret = isIdentifierStart(scnr.currentPeek());
  249. scnr.resetPeek();
  250. return ret;
  251. }
  252. function isListIdentifierStart(scnr, context) {
  253. const { currentType } = context;
  254. if (currentType !== 2 /* BraceLeft */) {
  255. return false;
  256. }
  257. peekSpaces(scnr);
  258. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  259. const ret = isNumberStart(ch);
  260. scnr.resetPeek();
  261. return ret;
  262. }
  263. function isLiteralStart(scnr, context) {
  264. const { currentType } = context;
  265. if (currentType !== 2 /* BraceLeft */) {
  266. return false;
  267. }
  268. peekSpaces(scnr);
  269. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  270. scnr.resetPeek();
  271. return ret;
  272. }
  273. function isLinkedDotStart(scnr, context) {
  274. const { currentType } = context;
  275. if (currentType !== 8 /* LinkedAlias */) {
  276. return false;
  277. }
  278. peekSpaces(scnr);
  279. const ret = scnr.currentPeek() === "." /* LinkedDot */;
  280. scnr.resetPeek();
  281. return ret;
  282. }
  283. function isLinkedModifierStart(scnr, context) {
  284. const { currentType } = context;
  285. if (currentType !== 9 /* LinkedDot */) {
  286. return false;
  287. }
  288. peekSpaces(scnr);
  289. const ret = isIdentifierStart(scnr.currentPeek());
  290. scnr.resetPeek();
  291. return ret;
  292. }
  293. function isLinkedDelimiterStart(scnr, context) {
  294. const { currentType } = context;
  295. if (!(currentType === 8 /* LinkedAlias */ ||
  296. currentType === 12 /* LinkedModifier */)) {
  297. return false;
  298. }
  299. peekSpaces(scnr);
  300. const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
  301. scnr.resetPeek();
  302. return ret;
  303. }
  304. function isLinkedReferStart(scnr, context) {
  305. const { currentType } = context;
  306. if (currentType !== 10 /* LinkedDelimiter */) {
  307. return false;
  308. }
  309. const fn = () => {
  310. const ch = scnr.currentPeek();
  311. if (ch === "{" /* BraceLeft */) {
  312. return isIdentifierStart(scnr.peek());
  313. }
  314. else if (ch === "@" /* LinkedAlias */ ||
  315. ch === "%" /* Modulo */ ||
  316. ch === "|" /* Pipe */ ||
  317. ch === ":" /* LinkedDelimiter */ ||
  318. ch === "." /* LinkedDot */ ||
  319. ch === CHAR_SP ||
  320. !ch) {
  321. return false;
  322. }
  323. else if (ch === CHAR_LF) {
  324. scnr.peek();
  325. return fn();
  326. }
  327. else {
  328. // other characters
  329. return isIdentifierStart(ch);
  330. }
  331. };
  332. const ret = fn();
  333. scnr.resetPeek();
  334. return ret;
  335. }
  336. function isPluralStart(scnr) {
  337. peekSpaces(scnr);
  338. const ret = scnr.currentPeek() === "|" /* Pipe */;
  339. scnr.resetPeek();
  340. return ret;
  341. }
  342. function isTextStart(scnr, reset = true) {
  343. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  344. const ch = scnr.currentPeek();
  345. if (ch === "{" /* BraceLeft */) {
  346. return prev === "%" /* Modulo */ ? false : hasSpace;
  347. }
  348. else if (ch === "@" /* LinkedAlias */ || !ch) {
  349. return prev === "%" /* Modulo */ ? true : hasSpace;
  350. }
  351. else if (ch === "%" /* Modulo */) {
  352. scnr.peek();
  353. return fn(hasSpace, "%" /* Modulo */, true);
  354. }
  355. else if (ch === "|" /* Pipe */) {
  356. return prev === "%" /* Modulo */ || detectModulo
  357. ? true
  358. : !(prev === CHAR_SP || prev === CHAR_LF);
  359. }
  360. else if (ch === CHAR_SP) {
  361. scnr.peek();
  362. return fn(true, CHAR_SP, detectModulo);
  363. }
  364. else if (ch === CHAR_LF) {
  365. scnr.peek();
  366. return fn(true, CHAR_LF, detectModulo);
  367. }
  368. else {
  369. return true;
  370. }
  371. };
  372. const ret = fn();
  373. reset && scnr.resetPeek();
  374. return ret;
  375. }
  376. function takeChar(scnr, fn) {
  377. const ch = scnr.currentChar();
  378. if (ch === EOF) {
  379. return EOF;
  380. }
  381. if (fn(ch)) {
  382. scnr.next();
  383. return ch;
  384. }
  385. return null;
  386. }
  387. function takeIdentifierChar(scnr) {
  388. const closure = (ch) => {
  389. const cc = ch.charCodeAt(0);
  390. return ((cc >= 97 && cc <= 122) || // a-z
  391. (cc >= 65 && cc <= 90) || // A-Z
  392. (cc >= 48 && cc <= 57) || // 0-9
  393. cc === 95 || // _
  394. cc === 36 // $
  395. );
  396. };
  397. return takeChar(scnr, closure);
  398. }
  399. function takeDigit(scnr) {
  400. const closure = (ch) => {
  401. const cc = ch.charCodeAt(0);
  402. return cc >= 48 && cc <= 57; // 0-9
  403. };
  404. return takeChar(scnr, closure);
  405. }
  406. function takeHexDigit(scnr) {
  407. const closure = (ch) => {
  408. const cc = ch.charCodeAt(0);
  409. return ((cc >= 48 && cc <= 57) || // 0-9
  410. (cc >= 65 && cc <= 70) || // A-F
  411. (cc >= 97 && cc <= 102)); // a-f
  412. };
  413. return takeChar(scnr, closure);
  414. }
  415. function getDigits(scnr) {
  416. let ch = '';
  417. let num = '';
  418. while ((ch = takeDigit(scnr))) {
  419. num += ch;
  420. }
  421. return num;
  422. }
  423. function readText(scnr) {
  424. let buf = '';
  425. while (true) {
  426. const ch = scnr.currentChar();
  427. if (ch === "{" /* BraceLeft */ ||
  428. ch === "}" /* BraceRight */ ||
  429. ch === "@" /* LinkedAlias */ ||
  430. ch === "|" /* Pipe */ ||
  431. !ch) {
  432. break;
  433. }
  434. else if (ch === "%" /* Modulo */) {
  435. if (isTextStart(scnr)) {
  436. buf += ch;
  437. scnr.next();
  438. }
  439. else {
  440. break;
  441. }
  442. }
  443. else if (ch === CHAR_SP || ch === CHAR_LF) {
  444. if (isTextStart(scnr)) {
  445. buf += ch;
  446. scnr.next();
  447. }
  448. else if (isPluralStart(scnr)) {
  449. break;
  450. }
  451. else {
  452. buf += ch;
  453. scnr.next();
  454. }
  455. }
  456. else {
  457. buf += ch;
  458. scnr.next();
  459. }
  460. }
  461. return buf;
  462. }
  463. function readNamedIdentifier(scnr) {
  464. skipSpaces(scnr);
  465. let ch = '';
  466. let name = '';
  467. while ((ch = takeIdentifierChar(scnr))) {
  468. name += ch;
  469. }
  470. if (scnr.currentChar() === EOF) {
  471. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  472. }
  473. return name;
  474. }
  475. function readListIdentifier(scnr) {
  476. skipSpaces(scnr);
  477. let value = '';
  478. if (scnr.currentChar() === '-') {
  479. scnr.next();
  480. value += `-${getDigits(scnr)}`;
  481. }
  482. else {
  483. value += getDigits(scnr);
  484. }
  485. if (scnr.currentChar() === EOF) {
  486. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  487. }
  488. return value;
  489. }
  490. function readLiteral(scnr) {
  491. skipSpaces(scnr);
  492. eat(scnr, `\'`);
  493. let ch = '';
  494. let literal = '';
  495. const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
  496. while ((ch = takeChar(scnr, fn))) {
  497. if (ch === '\\') {
  498. literal += readEscapeSequence(scnr);
  499. }
  500. else {
  501. literal += ch;
  502. }
  503. }
  504. const current = scnr.currentChar();
  505. if (current === CHAR_LF || current === EOF) {
  506. emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
  507. // TODO: Is it correct really?
  508. if (current === CHAR_LF) {
  509. scnr.next();
  510. eat(scnr, `\'`);
  511. }
  512. return literal;
  513. }
  514. eat(scnr, `\'`);
  515. return literal;
  516. }
  517. function readEscapeSequence(scnr) {
  518. const ch = scnr.currentChar();
  519. switch (ch) {
  520. case '\\':
  521. case `\'`:
  522. scnr.next();
  523. return `\\${ch}`;
  524. case 'u':
  525. return readUnicodeEscapeSequence(scnr, ch, 4);
  526. case 'U':
  527. return readUnicodeEscapeSequence(scnr, ch, 6);
  528. default:
  529. emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
  530. return '';
  531. }
  532. }
  533. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  534. eat(scnr, unicode);
  535. let sequence = '';
  536. for (let i = 0; i < digits; i++) {
  537. const ch = takeHexDigit(scnr);
  538. if (!ch) {
  539. emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  540. break;
  541. }
  542. sequence += ch;
  543. }
  544. return `\\${unicode}${sequence}`;
  545. }
  546. function readInvalidIdentifier(scnr) {
  547. skipSpaces(scnr);
  548. let ch = '';
  549. let identifiers = '';
  550. const closure = (ch) => ch !== "{" /* BraceLeft */ &&
  551. ch !== "}" /* BraceRight */ &&
  552. ch !== CHAR_SP &&
  553. ch !== CHAR_LF;
  554. while ((ch = takeChar(scnr, closure))) {
  555. identifiers += ch;
  556. }
  557. return identifiers;
  558. }
  559. function readLinkedModifier(scnr) {
  560. let ch = '';
  561. let name = '';
  562. while ((ch = takeIdentifierChar(scnr))) {
  563. name += ch;
  564. }
  565. return name;
  566. }
  567. function readLinkedRefer(scnr) {
  568. const fn = (detect = false, buf) => {
  569. const ch = scnr.currentChar();
  570. if (ch === "{" /* BraceLeft */ ||
  571. ch === "%" /* Modulo */ ||
  572. ch === "@" /* LinkedAlias */ ||
  573. ch === "|" /* Pipe */ ||
  574. !ch) {
  575. return buf;
  576. }
  577. else if (ch === CHAR_SP) {
  578. return buf;
  579. }
  580. else if (ch === CHAR_LF) {
  581. buf += ch;
  582. scnr.next();
  583. return fn(detect, buf);
  584. }
  585. else {
  586. buf += ch;
  587. scnr.next();
  588. return fn(true, buf);
  589. }
  590. };
  591. return fn(false, '');
  592. }
  593. function readPlural(scnr) {
  594. skipSpaces(scnr);
  595. const plural = eat(scnr, "|" /* Pipe */);
  596. skipSpaces(scnr);
  597. return plural;
  598. }
  599. // TODO: We need refactoring of token parsing ...
  600. function readTokenInPlaceholder(scnr, context) {
  601. let token = null;
  602. const ch = scnr.currentChar();
  603. switch (ch) {
  604. case "{" /* BraceLeft */:
  605. if (context.braceNest >= 1) {
  606. emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
  607. }
  608. scnr.next();
  609. token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
  610. skipSpaces(scnr);
  611. context.braceNest++;
  612. return token;
  613. case "}" /* BraceRight */:
  614. if (context.braceNest > 0 &&
  615. context.currentType === 2 /* BraceLeft */) {
  616. emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
  617. }
  618. scnr.next();
  619. token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  620. context.braceNest--;
  621. context.braceNest > 0 && skipSpaces(scnr);
  622. if (context.inLinked && context.braceNest === 0) {
  623. context.inLinked = false;
  624. }
  625. return token;
  626. case "@" /* LinkedAlias */:
  627. if (context.braceNest > 0) {
  628. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  629. }
  630. token = readTokenInLinked(scnr, context) || getEndToken(context);
  631. context.braceNest = 0;
  632. return token;
  633. default:
  634. let validNamedIdentifier = true;
  635. let validListIdentifier = true;
  636. let validLiteral = true;
  637. if (isPluralStart(scnr)) {
  638. if (context.braceNest > 0) {
  639. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  640. }
  641. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  642. // reset
  643. context.braceNest = 0;
  644. context.inLinked = false;
  645. return token;
  646. }
  647. if (context.braceNest > 0 &&
  648. (context.currentType === 5 /* Named */ ||
  649. context.currentType === 6 /* List */ ||
  650. context.currentType === 7 /* Literal */)) {
  651. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  652. context.braceNest = 0;
  653. return readToken(scnr, context);
  654. }
  655. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  656. token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
  657. skipSpaces(scnr);
  658. return token;
  659. }
  660. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  661. token = getToken(context, 6 /* List */, readListIdentifier(scnr));
  662. skipSpaces(scnr);
  663. return token;
  664. }
  665. if ((validLiteral = isLiteralStart(scnr, context))) {
  666. token = getToken(context, 7 /* Literal */, readLiteral(scnr));
  667. skipSpaces(scnr);
  668. return token;
  669. }
  670. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  671. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  672. token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
  673. emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
  674. skipSpaces(scnr);
  675. return token;
  676. }
  677. break;
  678. }
  679. return token;
  680. }
  681. // TODO: We need refactoring of token parsing ...
  682. function readTokenInLinked(scnr, context) {
  683. const { currentType } = context;
  684. let token = null;
  685. const ch = scnr.currentChar();
  686. if ((currentType === 8 /* LinkedAlias */ ||
  687. currentType === 9 /* LinkedDot */ ||
  688. currentType === 12 /* LinkedModifier */ ||
  689. currentType === 10 /* LinkedDelimiter */) &&
  690. (ch === CHAR_LF || ch === CHAR_SP)) {
  691. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  692. }
  693. switch (ch) {
  694. case "@" /* LinkedAlias */:
  695. scnr.next();
  696. token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
  697. context.inLinked = true;
  698. return token;
  699. case "." /* LinkedDot */:
  700. skipSpaces(scnr);
  701. scnr.next();
  702. return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
  703. case ":" /* LinkedDelimiter */:
  704. skipSpaces(scnr);
  705. scnr.next();
  706. return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
  707. default:
  708. if (isPluralStart(scnr)) {
  709. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  710. // reset
  711. context.braceNest = 0;
  712. context.inLinked = false;
  713. return token;
  714. }
  715. if (isLinkedDotStart(scnr, context) ||
  716. isLinkedDelimiterStart(scnr, context)) {
  717. skipSpaces(scnr);
  718. return readTokenInLinked(scnr, context);
  719. }
  720. if (isLinkedModifierStart(scnr, context)) {
  721. skipSpaces(scnr);
  722. return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
  723. }
  724. if (isLinkedReferStart(scnr, context)) {
  725. skipSpaces(scnr);
  726. if (ch === "{" /* BraceLeft */) {
  727. // scan the placeholder
  728. return readTokenInPlaceholder(scnr, context) || token;
  729. }
  730. else {
  731. return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
  732. }
  733. }
  734. if (currentType === 8 /* LinkedAlias */) {
  735. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  736. }
  737. context.braceNest = 0;
  738. context.inLinked = false;
  739. return readToken(scnr, context);
  740. }
  741. }
  742. // TODO: We need refactoring of token parsing ...
  743. function readToken(scnr, context) {
  744. let token = { type: 14 /* EOF */ };
  745. if (context.braceNest > 0) {
  746. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  747. }
  748. if (context.inLinked) {
  749. return readTokenInLinked(scnr, context) || getEndToken(context);
  750. }
  751. const ch = scnr.currentChar();
  752. switch (ch) {
  753. case "{" /* BraceLeft */:
  754. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  755. case "}" /* BraceRight */:
  756. emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
  757. scnr.next();
  758. return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  759. case "@" /* LinkedAlias */:
  760. return readTokenInLinked(scnr, context) || getEndToken(context);
  761. default:
  762. if (isPluralStart(scnr)) {
  763. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  764. // reset
  765. context.braceNest = 0;
  766. context.inLinked = false;
  767. return token;
  768. }
  769. if (isTextStart(scnr)) {
  770. return getToken(context, 0 /* Text */, readText(scnr));
  771. }
  772. if (ch === "%" /* Modulo */) {
  773. scnr.next();
  774. return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
  775. }
  776. break;
  777. }
  778. return token;
  779. }
  780. function nextToken() {
  781. const { currentType, offset, startLoc, endLoc } = _context;
  782. _context.lastType = currentType;
  783. _context.lastOffset = offset;
  784. _context.lastStartLoc = startLoc;
  785. _context.lastEndLoc = endLoc;
  786. _context.offset = currentOffset();
  787. _context.startLoc = currentPosition();
  788. if (_scnr.currentChar() === EOF) {
  789. return getToken(_context, 14 /* EOF */);
  790. }
  791. return readToken(_scnr, _context);
  792. }
  793. return {
  794. nextToken,
  795. currentOffset,
  796. currentPosition,
  797. context
  798. };
  799. }
  800. const ERROR_DOMAIN = 'parser';
  801. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  802. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  803. function fromEscapeSequence(match, codePoint4, codePoint6) {
  804. switch (match) {
  805. case `\\\\`:
  806. return `\\`;
  807. case `\\\'`:
  808. return `\'`;
  809. default: {
  810. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  811. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  812. return String.fromCodePoint(codePoint);
  813. }
  814. // invalid ...
  815. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  816. return '�';
  817. }
  818. }
  819. }
  820. function createParser(options = {}) {
  821. const location = options.location !== false;
  822. const { onError } = options;
  823. function emitError(tokenzer, code, start, offset, ...args) {
  824. const end = tokenzer.currentPosition();
  825. end.offset += offset;
  826. end.column += offset;
  827. if (onError) {
  828. const loc = createLocation(start, end);
  829. const err = createCompileError(code, loc, {
  830. domain: ERROR_DOMAIN,
  831. args
  832. });
  833. onError(err);
  834. }
  835. }
  836. function startNode(type, offset, loc) {
  837. const node = {
  838. type,
  839. start: offset,
  840. end: offset
  841. };
  842. if (location) {
  843. node.loc = { start: loc, end: loc };
  844. }
  845. return node;
  846. }
  847. function endNode(node, offset, pos, type) {
  848. node.end = offset;
  849. if (type) {
  850. node.type = type;
  851. }
  852. if (location && node.loc) {
  853. node.loc.end = pos;
  854. }
  855. }
  856. function parseText(tokenizer, value) {
  857. const context = tokenizer.context();
  858. const node = startNode(3 /* Text */, context.offset, context.startLoc);
  859. node.value = value;
  860. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  861. return node;
  862. }
  863. function parseList(tokenizer, index) {
  864. const context = tokenizer.context();
  865. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  866. const node = startNode(5 /* List */, offset, loc);
  867. node.index = parseInt(index, 10);
  868. tokenizer.nextToken(); // skip brach right
  869. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  870. return node;
  871. }
  872. function parseNamed(tokenizer, key) {
  873. const context = tokenizer.context();
  874. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  875. const node = startNode(4 /* Named */, offset, loc);
  876. node.key = key;
  877. tokenizer.nextToken(); // skip brach right
  878. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  879. return node;
  880. }
  881. function parseLiteral(tokenizer, value) {
  882. const context = tokenizer.context();
  883. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  884. const node = startNode(9 /* Literal */, offset, loc);
  885. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  886. tokenizer.nextToken(); // skip brach right
  887. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  888. return node;
  889. }
  890. function parseLinkedModifier(tokenizer) {
  891. const token = tokenizer.nextToken();
  892. const context = tokenizer.context();
  893. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  894. const node = startNode(8 /* LinkedModifier */, offset, loc);
  895. if (token.type !== 12 /* LinkedModifier */) {
  896. // empty modifier
  897. emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0);
  898. node.value = '';
  899. endNode(node, offset, loc);
  900. return {
  901. nextConsumeToken: token,
  902. node
  903. };
  904. }
  905. // check token
  906. if (token.value == null) {
  907. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  908. }
  909. node.value = token.value || '';
  910. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  911. return {
  912. node
  913. };
  914. }
  915. function parseLinkedKey(tokenizer, value) {
  916. const context = tokenizer.context();
  917. const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
  918. node.value = value;
  919. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  920. return node;
  921. }
  922. function parseLinked(tokenizer) {
  923. const context = tokenizer.context();
  924. const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
  925. let token = tokenizer.nextToken();
  926. if (token.type === 9 /* LinkedDot */) {
  927. const parsed = parseLinkedModifier(tokenizer);
  928. linkedNode.modifier = parsed.node;
  929. token = parsed.nextConsumeToken || tokenizer.nextToken();
  930. }
  931. // asset check token
  932. if (token.type !== 10 /* LinkedDelimiter */) {
  933. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  934. }
  935. token = tokenizer.nextToken();
  936. // skip brace left
  937. if (token.type === 2 /* BraceLeft */) {
  938. token = tokenizer.nextToken();
  939. }
  940. switch (token.type) {
  941. case 11 /* LinkedKey */:
  942. if (token.value == null) {
  943. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  944. }
  945. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  946. break;
  947. case 5 /* Named */:
  948. if (token.value == null) {
  949. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  950. }
  951. linkedNode.key = parseNamed(tokenizer, token.value || '');
  952. break;
  953. case 6 /* List */:
  954. if (token.value == null) {
  955. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  956. }
  957. linkedNode.key = parseList(tokenizer, token.value || '');
  958. break;
  959. case 7 /* Literal */:
  960. if (token.value == null) {
  961. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  962. }
  963. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  964. break;
  965. default:
  966. // empty key
  967. emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0);
  968. const nextContext = tokenizer.context();
  969. const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc);
  970. emptyLinkedKeyNode.value = '';
  971. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  972. linkedNode.key = emptyLinkedKeyNode;
  973. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  974. return {
  975. nextConsumeToken: token,
  976. node: linkedNode
  977. };
  978. }
  979. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  980. return {
  981. node: linkedNode
  982. };
  983. }
  984. function parseMessage(tokenizer) {
  985. const context = tokenizer.context();
  986. const startOffset = context.currentType === 1 /* Pipe */
  987. ? tokenizer.currentOffset()
  988. : context.offset;
  989. const startLoc = context.currentType === 1 /* Pipe */
  990. ? context.endLoc
  991. : context.startLoc;
  992. const node = startNode(2 /* Message */, startOffset, startLoc);
  993. node.items = [];
  994. let nextToken = null;
  995. do {
  996. const token = nextToken || tokenizer.nextToken();
  997. nextToken = null;
  998. switch (token.type) {
  999. case 0 /* Text */:
  1000. if (token.value == null) {
  1001. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1002. }
  1003. node.items.push(parseText(tokenizer, token.value || ''));
  1004. break;
  1005. case 6 /* List */:
  1006. if (token.value == null) {
  1007. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1008. }
  1009. node.items.push(parseList(tokenizer, token.value || ''));
  1010. break;
  1011. case 5 /* Named */:
  1012. if (token.value == null) {
  1013. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1014. }
  1015. node.items.push(parseNamed(tokenizer, token.value || ''));
  1016. break;
  1017. case 7 /* Literal */:
  1018. if (token.value == null) {
  1019. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1020. }
  1021. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1022. break;
  1023. case 8 /* LinkedAlias */:
  1024. const parsed = parseLinked(tokenizer);
  1025. node.items.push(parsed.node);
  1026. nextToken = parsed.nextConsumeToken || null;
  1027. break;
  1028. }
  1029. } while (context.currentType !== 14 /* EOF */ &&
  1030. context.currentType !== 1 /* Pipe */);
  1031. // adjust message node loc
  1032. const endOffset = context.currentType === 1 /* Pipe */
  1033. ? context.lastOffset
  1034. : tokenizer.currentOffset();
  1035. const endLoc = context.currentType === 1 /* Pipe */
  1036. ? context.lastEndLoc
  1037. : tokenizer.currentPosition();
  1038. endNode(node, endOffset, endLoc);
  1039. return node;
  1040. }
  1041. function parsePlural(tokenizer, offset, loc, msgNode) {
  1042. const context = tokenizer.context();
  1043. let hasEmptyMessage = msgNode.items.length === 0;
  1044. const node = startNode(1 /* Plural */, offset, loc);
  1045. node.cases = [];
  1046. node.cases.push(msgNode);
  1047. do {
  1048. const msg = parseMessage(tokenizer);
  1049. if (!hasEmptyMessage) {
  1050. hasEmptyMessage = msg.items.length === 0;
  1051. }
  1052. node.cases.push(msg);
  1053. } while (context.currentType !== 14 /* EOF */);
  1054. if (hasEmptyMessage) {
  1055. emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
  1056. }
  1057. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1058. return node;
  1059. }
  1060. function parseResource(tokenizer) {
  1061. const context = tokenizer.context();
  1062. const { offset, startLoc } = context;
  1063. const msgNode = parseMessage(tokenizer);
  1064. if (context.currentType === 14 /* EOF */) {
  1065. return msgNode;
  1066. }
  1067. else {
  1068. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1069. }
  1070. }
  1071. function parse(source) {
  1072. const tokenizer = createTokenizer(source, assign({}, options));
  1073. const context = tokenizer.context();
  1074. const node = startNode(0 /* Resource */, context.offset, context.startLoc);
  1075. if (location && node.loc) {
  1076. node.loc.source = source;
  1077. }
  1078. node.body = parseResource(tokenizer);
  1079. // assert whether achieved to EOF
  1080. if (context.currentType !== 14 /* EOF */) {
  1081. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || '');
  1082. }
  1083. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1084. return node;
  1085. }
  1086. return { parse };
  1087. }
  1088. function getTokenCaption(token) {
  1089. if (token.type === 14 /* EOF */) {
  1090. return 'EOF';
  1091. }
  1092. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1093. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1094. }
  1095. function createTransformer(ast, options = {} // eslint-disable-line
  1096. ) {
  1097. const _context = {
  1098. ast,
  1099. helpers: new Set()
  1100. };
  1101. const context = () => _context;
  1102. const helper = (name) => {
  1103. _context.helpers.add(name);
  1104. return name;
  1105. };
  1106. return { context, helper };
  1107. }
  1108. function traverseNodes(nodes, transformer) {
  1109. for (let i = 0; i < nodes.length; i++) {
  1110. traverseNode(nodes[i], transformer);
  1111. }
  1112. }
  1113. function traverseNode(node, transformer) {
  1114. // TODO: if we need pre-hook of transform, should be implemented to here
  1115. switch (node.type) {
  1116. case 1 /* Plural */:
  1117. traverseNodes(node.cases, transformer);
  1118. transformer.helper("plural" /* PLURAL */);
  1119. break;
  1120. case 2 /* Message */:
  1121. traverseNodes(node.items, transformer);
  1122. break;
  1123. case 6 /* Linked */:
  1124. const linked = node;
  1125. traverseNode(linked.key, transformer);
  1126. transformer.helper("linked" /* LINKED */);
  1127. break;
  1128. case 5 /* List */:
  1129. transformer.helper("interpolate" /* INTERPOLATE */);
  1130. transformer.helper("list" /* LIST */);
  1131. break;
  1132. case 4 /* Named */:
  1133. transformer.helper("interpolate" /* INTERPOLATE */);
  1134. transformer.helper("named" /* NAMED */);
  1135. break;
  1136. }
  1137. // TODO: if we need post-hook of transform, should be implemented to here
  1138. }
  1139. // transform AST
  1140. function transform(ast, options = {} // eslint-disable-line
  1141. ) {
  1142. const transformer = createTransformer(ast);
  1143. transformer.helper("normalize" /* NORMALIZE */);
  1144. // traverse
  1145. ast.body && traverseNode(ast.body, transformer);
  1146. // set meta information
  1147. const context = transformer.context();
  1148. ast.helpers = Array.from(context.helpers);
  1149. }
  1150. function createCodeGenerator(ast, options) {
  1151. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1152. const _context = {
  1153. source: ast.loc.source,
  1154. filename,
  1155. code: '',
  1156. column: 1,
  1157. line: 1,
  1158. offset: 0,
  1159. map: undefined,
  1160. breakLineCode,
  1161. needIndent: _needIndent,
  1162. indentLevel: 0
  1163. };
  1164. const context = () => _context;
  1165. function push(code, node) {
  1166. _context.code += code;
  1167. }
  1168. function _newline(n, withBreakLine = true) {
  1169. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1170. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1171. }
  1172. function indent(withNewLine = true) {
  1173. const level = ++_context.indentLevel;
  1174. withNewLine && _newline(level);
  1175. }
  1176. function deindent(withNewLine = true) {
  1177. const level = --_context.indentLevel;
  1178. withNewLine && _newline(level);
  1179. }
  1180. function newline() {
  1181. _newline(_context.indentLevel);
  1182. }
  1183. const helper = (key) => `_${key}`;
  1184. const needIndent = () => _context.needIndent;
  1185. return {
  1186. context,
  1187. push,
  1188. indent,
  1189. deindent,
  1190. newline,
  1191. helper,
  1192. needIndent
  1193. };
  1194. }
  1195. function generateLinkedNode(generator, node) {
  1196. const { helper } = generator;
  1197. generator.push(`${helper("linked" /* LINKED */)}(`);
  1198. generateNode(generator, node.key);
  1199. if (node.modifier) {
  1200. generator.push(`, `);
  1201. generateNode(generator, node.modifier);
  1202. }
  1203. generator.push(`)`);
  1204. }
  1205. function generateMessageNode(generator, node) {
  1206. const { helper, needIndent } = generator;
  1207. generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
  1208. generator.indent(needIndent());
  1209. const length = node.items.length;
  1210. for (let i = 0; i < length; i++) {
  1211. generateNode(generator, node.items[i]);
  1212. if (i === length - 1) {
  1213. break;
  1214. }
  1215. generator.push(', ');
  1216. }
  1217. generator.deindent(needIndent());
  1218. generator.push('])');
  1219. }
  1220. function generatePluralNode(generator, node) {
  1221. const { helper, needIndent } = generator;
  1222. if (node.cases.length > 1) {
  1223. generator.push(`${helper("plural" /* PLURAL */)}([`);
  1224. generator.indent(needIndent());
  1225. const length = node.cases.length;
  1226. for (let i = 0; i < length; i++) {
  1227. generateNode(generator, node.cases[i]);
  1228. if (i === length - 1) {
  1229. break;
  1230. }
  1231. generator.push(', ');
  1232. }
  1233. generator.deindent(needIndent());
  1234. generator.push(`])`);
  1235. }
  1236. }
  1237. function generateResource(generator, node) {
  1238. if (node.body) {
  1239. generateNode(generator, node.body);
  1240. }
  1241. else {
  1242. generator.push('null');
  1243. }
  1244. }
  1245. function generateNode(generator, node) {
  1246. const { helper } = generator;
  1247. switch (node.type) {
  1248. case 0 /* Resource */:
  1249. generateResource(generator, node);
  1250. break;
  1251. case 1 /* Plural */:
  1252. generatePluralNode(generator, node);
  1253. break;
  1254. case 2 /* Message */:
  1255. generateMessageNode(generator, node);
  1256. break;
  1257. case 6 /* Linked */:
  1258. generateLinkedNode(generator, node);
  1259. break;
  1260. case 8 /* LinkedModifier */:
  1261. generator.push(JSON.stringify(node.value), node);
  1262. break;
  1263. case 7 /* LinkedKey */:
  1264. generator.push(JSON.stringify(node.value), node);
  1265. break;
  1266. case 5 /* List */:
  1267. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
  1268. break;
  1269. case 4 /* Named */:
  1270. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1271. break;
  1272. case 9 /* Literal */:
  1273. generator.push(JSON.stringify(node.value), node);
  1274. break;
  1275. case 3 /* Text */:
  1276. generator.push(JSON.stringify(node.value), node);
  1277. break;
  1278. default:
  1279. {
  1280. throw new Error(`unhandled codegen node type: ${node.type}`);
  1281. }
  1282. }
  1283. }
  1284. // generate code from AST
  1285. const generate = (ast, options = {} // eslint-disable-line
  1286. ) => {
  1287. const mode = isString(options.mode) ? options.mode : 'normal';
  1288. const filename = isString(options.filename)
  1289. ? options.filename
  1290. : 'message.intl';
  1291. const sourceMap = !!options.sourceMap;
  1292. // prettier-ignore
  1293. const breakLineCode = options.breakLineCode != null
  1294. ? options.breakLineCode
  1295. : mode === 'arrow'
  1296. ? ';'
  1297. : '\n';
  1298. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1299. const helpers = ast.helpers || [];
  1300. const generator = createCodeGenerator(ast, {
  1301. mode,
  1302. filename,
  1303. sourceMap,
  1304. breakLineCode,
  1305. needIndent
  1306. });
  1307. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1308. generator.indent(needIndent);
  1309. if (helpers.length > 0) {
  1310. generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
  1311. generator.newline();
  1312. }
  1313. generator.push(`return `);
  1314. generateNode(generator, ast);
  1315. generator.deindent(needIndent);
  1316. generator.push(`}`);
  1317. const { code, map } = generator.context();
  1318. return {
  1319. ast,
  1320. code,
  1321. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1322. };
  1323. };
  1324. function baseCompile(source, options = {}) {
  1325. const assignedOptions = assign({}, options);
  1326. // parse source codes
  1327. const parser = createParser(assignedOptions);
  1328. const ast = parser.parse(source);
  1329. // transform ASTs
  1330. transform(ast, assignedOptions);
  1331. // generate javascript codes
  1332. return generate(ast, assignedOptions);
  1333. }
  1334. export { ERROR_DOMAIN, LocationStub, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, errorMessages };