compiler.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167
  1. 'use strict';
  2. var parser = require('@messageformat/parser');
  3. var Runtime = require('@messageformat/runtime');
  4. var Formatters = require('@messageformat/runtime/lib/formatters');
  5. var safeIdentifier = require('safe-identifier');
  6. function _interopNamespaceDefault(e) {
  7. var n = Object.create(null);
  8. if (e) {
  9. Object.keys(e).forEach(function (k) {
  10. if (k !== 'default') {
  11. var d = Object.getOwnPropertyDescriptor(e, k);
  12. Object.defineProperty(n, k, d.get ? d : {
  13. enumerable: true,
  14. get: function () { return e[k]; }
  15. });
  16. }
  17. });
  18. }
  19. n.default = e;
  20. return Object.freeze(n);
  21. }
  22. var Runtime__namespace = /*#__PURE__*/_interopNamespaceDefault(Runtime);
  23. var Formatters__namespace = /*#__PURE__*/_interopNamespaceDefault(Formatters);
  24. /**
  25. * Parent class for errors.
  26. *
  27. * @remarks
  28. * Errors with `type: "warning"` do not necessarily indicate that the parser
  29. * encountered an error. In addition to a human-friendly `message`, may also
  30. * includes the `token` at which the error was encountered.
  31. *
  32. * @public
  33. */
  34. class DateFormatError extends Error {
  35. /** @internal */
  36. constructor(msg, token, type) {
  37. super(msg);
  38. this.token = token;
  39. this.type = type || 'error';
  40. }
  41. }
  42. const alpha = (width) => width < 4 ? 'short' : width === 4 ? 'long' : 'narrow';
  43. const numeric = (width) => (width % 2 === 0 ? '2-digit' : 'numeric');
  44. function yearOptions(token, onError) {
  45. switch (token.char) {
  46. case 'y':
  47. return { year: numeric(token.width) };
  48. case 'r':
  49. return { calendar: 'gregory', year: 'numeric' };
  50. case 'u':
  51. case 'U':
  52. case 'Y':
  53. default:
  54. onError(`${token.desc} is not supported; falling back to year:numeric`, DateFormatError.WARNING);
  55. return { year: 'numeric' };
  56. }
  57. }
  58. function monthStyle(token, onError) {
  59. switch (token.width) {
  60. case 1:
  61. return 'numeric';
  62. case 2:
  63. return '2-digit';
  64. case 3:
  65. return 'short';
  66. case 4:
  67. return 'long';
  68. case 5:
  69. return 'narrow';
  70. default:
  71. onError(`${token.desc} is not supported with width ${token.width}`);
  72. return undefined;
  73. }
  74. }
  75. function dayStyle(token, onError) {
  76. const { char, desc, width } = token;
  77. if (char === 'd')
  78. return numeric(width);
  79. else {
  80. onError(`${desc} is not supported`);
  81. return undefined;
  82. }
  83. }
  84. function weekdayStyle(token, onError) {
  85. const { char, desc, width } = token;
  86. if ((char === 'c' || char === 'e') && width < 3) {
  87. // ignoring stand-alone-ness
  88. const msg = `Numeric value is not supported for ${desc}; falling back to weekday:short`;
  89. onError(msg, DateFormatError.WARNING);
  90. }
  91. // merging narrow styles
  92. return alpha(width);
  93. }
  94. function hourOptions(token) {
  95. const hour = numeric(token.width);
  96. let hourCycle;
  97. switch (token.char) {
  98. case 'h':
  99. hourCycle = 'h12';
  100. break;
  101. case 'H':
  102. hourCycle = 'h23';
  103. break;
  104. case 'k':
  105. hourCycle = 'h24';
  106. break;
  107. case 'K':
  108. hourCycle = 'h11';
  109. break;
  110. }
  111. return hourCycle ? { hour, hourCycle } : { hour };
  112. }
  113. function timeZoneNameStyle(token, onError) {
  114. // so much fallback behaviour here
  115. const { char, desc, width } = token;
  116. switch (char) {
  117. case 'v':
  118. case 'z':
  119. return width === 4 ? 'long' : 'short';
  120. case 'V':
  121. if (width === 4)
  122. return 'long';
  123. onError(`${desc} is not supported with width ${width}`);
  124. return undefined;
  125. case 'X':
  126. onError(`${desc} is not supported`);
  127. return undefined;
  128. }
  129. return 'short';
  130. }
  131. function compileOptions(token, onError) {
  132. switch (token.field) {
  133. case 'era':
  134. return { era: alpha(token.width) };
  135. case 'year':
  136. return yearOptions(token, onError);
  137. case 'month':
  138. return { month: monthStyle(token, onError) };
  139. case 'day':
  140. return { day: dayStyle(token, onError) };
  141. case 'weekday':
  142. return { weekday: weekdayStyle(token, onError) };
  143. case 'period':
  144. return undefined;
  145. case 'hour':
  146. return hourOptions(token);
  147. case 'min':
  148. return { minute: numeric(token.width) };
  149. case 'sec':
  150. return { second: numeric(token.width) };
  151. case 'tz':
  152. return { timeZoneName: timeZoneNameStyle(token, onError) };
  153. case 'quarter':
  154. case 'week':
  155. case 'sec-frac':
  156. case 'ms':
  157. onError(`${token.desc} is not supported`);
  158. }
  159. return undefined;
  160. }
  161. function getDateFormatOptions(tokens, onError = error => {
  162. throw error;
  163. }) {
  164. const options = {};
  165. const fields = [];
  166. for (const token of tokens) {
  167. const { error, field, str } = token;
  168. if (error) {
  169. const dte = new DateFormatError(error.message, token);
  170. dte.stack = error.stack;
  171. onError(dte);
  172. }
  173. if (str) {
  174. const msg = `Ignoring string part: ${str}`;
  175. onError(new DateFormatError(msg, token, DateFormatError.WARNING));
  176. }
  177. if (field) {
  178. if (fields.indexOf(field) === -1)
  179. fields.push(field);
  180. else
  181. onError(new DateFormatError(`Duplicate ${field} token`, token));
  182. }
  183. const opt = compileOptions(token, (msg, isWarning) => onError(new DateFormatError(msg, token, isWarning)));
  184. if (opt)
  185. Object.assign(options, opt);
  186. }
  187. return options;
  188. }
  189. const fields = {
  190. G: { field: 'era', desc: 'Era' },
  191. y: { field: 'year', desc: 'Year' },
  192. Y: { field: 'year', desc: 'Year of "Week of Year"' },
  193. u: { field: 'year', desc: 'Extended year' },
  194. U: { field: 'year', desc: 'Cyclic year name' },
  195. r: { field: 'year', desc: 'Related Gregorian year' },
  196. Q: { field: 'quarter', desc: 'Quarter' },
  197. q: { field: 'quarter', desc: 'Stand-alone quarter' },
  198. M: { field: 'month', desc: 'Month in year' },
  199. L: { field: 'month', desc: 'Stand-alone month in year' },
  200. w: { field: 'week', desc: 'Week of year' },
  201. W: { field: 'week', desc: 'Week of month' },
  202. d: { field: 'day', desc: 'Day in month' },
  203. D: { field: 'day', desc: 'Day of year' },
  204. F: { field: 'day', desc: 'Day of week in month' },
  205. g: { field: 'day', desc: 'Modified julian day' },
  206. E: { field: 'weekday', desc: 'Day of week' },
  207. e: { field: 'weekday', desc: 'Local day of week' },
  208. c: { field: 'weekday', desc: 'Stand-alone local day of week' },
  209. a: { field: 'period', desc: 'AM/PM marker' },
  210. b: { field: 'period', desc: 'AM/PM/noon/midnight marker' },
  211. B: { field: 'period', desc: 'Flexible day period' },
  212. h: { field: 'hour', desc: 'Hour in AM/PM (1~12)' },
  213. H: { field: 'hour', desc: 'Hour in day (0~23)' },
  214. k: { field: 'hour', desc: 'Hour in day (1~24)' },
  215. K: { field: 'hour', desc: 'Hour in AM/PM (0~11)' },
  216. j: { field: 'hour', desc: 'Hour in preferred cycle' },
  217. J: { field: 'hour', desc: 'Hour in preferred cycle without marker' },
  218. C: { field: 'hour', desc: 'Hour in preferred cycle with flexible marker' },
  219. m: { field: 'min', desc: 'Minute in hour' },
  220. s: { field: 'sec', desc: 'Second in minute' },
  221. S: { field: 'sec-frac', desc: 'Fractional second' },
  222. A: { field: 'ms', desc: 'Milliseconds in day' },
  223. z: { field: 'tz', desc: 'Time Zone: specific non-location' },
  224. Z: { field: 'tz', desc: 'Time Zone' },
  225. O: { field: 'tz', desc: 'Time Zone: localized' },
  226. v: { field: 'tz', desc: 'Time Zone: generic non-location' },
  227. V: { field: 'tz', desc: 'Time Zone: ID' },
  228. X: { field: 'tz', desc: 'Time Zone: ISO8601 with Z' },
  229. x: { field: 'tz', desc: 'Time Zone: ISO8601' }
  230. };
  231. const isLetter = (char) => (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z');
  232. function readFieldToken(src, pos) {
  233. const char = src[pos];
  234. let width = 1;
  235. while (src[++pos] === char)
  236. ++width;
  237. const field = fields[char];
  238. if (!field) {
  239. const msg = `The letter ${char} is not a valid field identifier`;
  240. return { char, error: new Error(msg), width };
  241. }
  242. return { char, field: field.field, desc: field.desc, width };
  243. }
  244. function readQuotedToken(src, pos) {
  245. let str = src[++pos];
  246. let width = 2;
  247. if (str === "'")
  248. return { char: "'", str, width };
  249. while (true) {
  250. const next = src[++pos];
  251. ++width;
  252. if (next === undefined) {
  253. const msg = `Unterminated quoted literal in pattern: ${str || src}`;
  254. return { char: "'", error: new Error(msg), str, width };
  255. }
  256. else if (next === "'") {
  257. if (src[++pos] !== "'")
  258. return { char: "'", str, width };
  259. else
  260. ++width;
  261. }
  262. str += next;
  263. }
  264. }
  265. function readToken(src, pos) {
  266. const char = src[pos];
  267. if (!char)
  268. return null;
  269. if (isLetter(char))
  270. return readFieldToken(src, pos);
  271. if (char === "'")
  272. return readQuotedToken(src, pos);
  273. let str = char;
  274. let width = 1;
  275. while (true) {
  276. const next = src[++pos];
  277. if (!next || isLetter(next) || next === "'")
  278. return { char, str, width };
  279. str += next;
  280. width += 1;
  281. }
  282. }
  283. /**
  284. * Parse an {@link http://userguide.icu-project.org/formatparse/datetime | ICU
  285. * DateFormat skeleton} string into a {@link DateToken} array.
  286. *
  287. * @remarks
  288. * Errors will not be thrown, but if encountered are included as the relevant
  289. * token's `error` value.
  290. *
  291. * @public
  292. * @param src - The skeleton string
  293. *
  294. * @example
  295. * ```js
  296. * import { parseDateTokens } from '@messageformat/date-skeleton'
  297. *
  298. * parseDateTokens('GrMMMdd', console.error)
  299. * // [
  300. * // { char: 'G', field: 'era', desc: 'Era', width: 1 },
  301. * // { char: 'r', field: 'year', desc: 'Related Gregorian year', width: 1 },
  302. * // { char: 'M', field: 'month', desc: 'Month in year', width: 3 },
  303. * // { char: 'd', field: 'day', desc: 'Day in month', width: 2 }
  304. * // ]
  305. * ```
  306. */
  307. function parseDateTokens(src) {
  308. const tokens = [];
  309. let pos = 0;
  310. while (true) {
  311. const token = readToken(src, pos);
  312. if (!token)
  313. return tokens;
  314. tokens.push(token);
  315. pos += token.width;
  316. }
  317. }
  318. /**
  319. * Returns a date formatter function for the given locales and date skeleton
  320. *
  321. * @remarks
  322. * Uses `Intl.DateTimeFormat` internally.
  323. *
  324. * @public
  325. * @param locales - One or more valid BCP 47 language tags, e.g. `fr` or `en-CA`
  326. * @param tokens - An ICU DateFormat skeleton string, or an array or parsed
  327. * `DateToken` tokens
  328. * @param onError - If defined, will be called separately for each encountered
  329. * parsing error and unsupported feature.
  330. * @example
  331. * ```js
  332. * import { getDateFormatter } from '@messageformat/date-skeleton'
  333. *
  334. * // 2006 Jan 2, 15:04:05.789 in local time
  335. * const date = new Date(2006, 0, 2, 15, 4, 5, 789)
  336. *
  337. * let fmt = getDateFormatter('en-CA', 'GrMMMdd', console.error)
  338. * fmt(date) // 'Jan. 02, 2006 AD'
  339. *
  340. * fmt = getDateFormatter('en-CA', 'hamszzzz', console.error)
  341. * fmt(date) // '3:04:05 p.m. Newfoundland Daylight Time'
  342. * ```
  343. */
  344. function getDateFormatter(locales, tokens, onError) {
  345. if (typeof tokens === 'string')
  346. tokens = parseDateTokens(tokens);
  347. const opt = getDateFormatOptions(tokens, onError);
  348. const dtf = new Intl.DateTimeFormat(locales, opt);
  349. return (date) => dtf.format(date);
  350. }
  351. /**
  352. * Returns a string of JavaScript source that evaluates to a date formatter
  353. * function with the same `(date: Date | number) => string` signature as the
  354. * function returned by {@link getDateFormatter}.
  355. *
  356. * @remarks
  357. * The returned function will memoize an `Intl.DateTimeFormat` instance.
  358. *
  359. * @public
  360. * @param locales - One or more valid BCP 47 language tags, e.g. `fr` or `en-CA`
  361. * @param tokens - An ICU DateFormat skeleton string, or an array or parsed
  362. * `DateToken` tokens
  363. * @param onError - If defined, will be called separately for each encountered
  364. * parsing error and unsupported feature.
  365. * @example
  366. * ```js
  367. * import { getDateFormatterSource } from '@messageformat/date-skeleton'
  368. *
  369. * getDateFormatterSource('en-CA', 'GrMMMdd', console.error)
  370. * // '(function() {\n' +
  371. * // ' var opt = {"era":"short","calendar":"gregory","year":"numeric",' +
  372. * // '"month":"short","day":"2-digit"};\n' +
  373. * // ' var dtf = new Intl.DateTimeFormat("en-CA", opt);\n' +
  374. * // ' return function(value) { return dtf.format(value); }\n' +
  375. * // '})()'
  376. *
  377. * const src = getDateFormatterSource('en-CA', 'hamszzzz', console.error)
  378. * // '(function() {\n' +
  379. * // ' var opt = {"hour":"numeric","hourCycle":"h12","minute":"numeric",' +
  380. * // '"second":"numeric","timeZoneName":"long"};\n' +
  381. * // ' var dtf = new Intl.DateTimeFormat("en-CA", opt);\n' +
  382. * // ' return function(value) { return dtf.format(value); }\n' +
  383. * // '})()'
  384. *
  385. * const fmt = new Function(`return ${src}`)()
  386. * const date = new Date(2006, 0, 2, 15, 4, 5, 789)
  387. * fmt(date) // '3:04:05 p.m. Newfoundland Daylight Time'
  388. * ```
  389. */
  390. function getDateFormatterSource(locales, tokens, onError) {
  391. if (typeof tokens === 'string')
  392. tokens = parseDateTokens(tokens);
  393. const opt = getDateFormatOptions(tokens, onError);
  394. const lines = [
  395. `(function() {`,
  396. `var opt = ${JSON.stringify(opt)};`,
  397. `var dtf = new Intl.DateTimeFormat(${JSON.stringify(locales)}, opt);`,
  398. `return function(value) { return dtf.format(value); }`
  399. ];
  400. return lines.join('\n ') + '\n})()';
  401. }
  402. /**
  403. * Base class for errors. In addition to a `code` and a human-friendly
  404. * `message`, may also includes the token `stem` as well as other fields.
  405. *
  406. * @public
  407. */
  408. class NumberFormatError extends Error {
  409. /** @internal */
  410. constructor(code, msg) {
  411. super(msg);
  412. this.code = code;
  413. }
  414. }
  415. /** @internal */
  416. class BadOptionError extends NumberFormatError {
  417. constructor(stem, opt) {
  418. super('BAD_OPTION', `Unknown ${stem} option: ${opt}`);
  419. this.stem = stem;
  420. this.option = opt;
  421. }
  422. }
  423. /** @internal */
  424. class BadStemError extends NumberFormatError {
  425. constructor(stem) {
  426. super('BAD_STEM', `Unknown stem: ${stem}`);
  427. this.stem = stem;
  428. }
  429. }
  430. /** @internal */
  431. class MaskedValueError extends NumberFormatError {
  432. constructor(type, prev) {
  433. super('MASKED_VALUE', `Value for ${type} is set multiple times`);
  434. this.type = type;
  435. this.prev = prev;
  436. }
  437. }
  438. /** @internal */
  439. class MissingOptionError extends NumberFormatError {
  440. constructor(stem) {
  441. super('MISSING_OPTION', `Required option missing for ${stem}`);
  442. this.stem = stem;
  443. }
  444. }
  445. /** @internal */
  446. class PatternError extends NumberFormatError {
  447. constructor(char, msg) {
  448. super('BAD_PATTERN', msg);
  449. this.char = char;
  450. }
  451. }
  452. /** @internal */
  453. class TooManyOptionsError extends NumberFormatError {
  454. constructor(stem, options, maxOpt) {
  455. const maxOptStr = maxOpt > 1 ? `${maxOpt} options` : 'one option';
  456. super('TOO_MANY_OPTIONS', `Token ${stem} only supports ${maxOptStr} (got ${options.length})`);
  457. this.stem = stem;
  458. this.options = options;
  459. }
  460. }
  461. /** @internal */
  462. class UnsupportedError extends NumberFormatError {
  463. constructor(stem, source) {
  464. super('UNSUPPORTED', `The stem ${stem} is not supported`);
  465. this.stem = stem;
  466. if (source) {
  467. this.message += ` with value ${source}`;
  468. this.source = source;
  469. }
  470. }
  471. }
  472. /**
  473. * Add
  474. * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation | numbering-system tags}
  475. * to locale identifiers
  476. *
  477. * @internal
  478. */
  479. function getNumberFormatLocales(locales, { numberingSystem }) {
  480. if (!Array.isArray(locales))
  481. locales = [locales];
  482. return numberingSystem
  483. ? locales
  484. .map(lc => {
  485. const ext = lc.indexOf('-u-') === -1 ? 'u-nu' : 'nu';
  486. return `${lc}-${ext}-${numberingSystem}`;
  487. })
  488. .concat(locales)
  489. : locales;
  490. }
  491. // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  492. function round(x, precision) {
  493. const y = +x + precision / 2;
  494. return y - (y % +precision);
  495. }
  496. function getNumberFormatMultiplier({ scale, unit }) {
  497. let mult = typeof scale === 'number' && scale >= 0 ? scale : 1;
  498. if (unit && unit.style === 'percent')
  499. mult *= 0.01;
  500. return mult;
  501. }
  502. /**
  503. * Determine a modifier for the input value to account for any `scale`,
  504. * `percent`, and `precision-increment` tokens in the skeleton.
  505. *
  506. * @internal
  507. * @remarks
  508. * With ICU NumberFormatter, the `percent` skeleton would style `25` as "25%".
  509. * To achieve the same with `Intl.NumberFormat`, the input value must be `0.25`.
  510. */
  511. function getNumberFormatModifier(skeleton) {
  512. const mult = getNumberFormatMultiplier(skeleton);
  513. const { precision } = skeleton;
  514. if (precision && precision.style === 'precision-increment') {
  515. return (n) => round(n, precision.increment) * mult;
  516. }
  517. else {
  518. return (n) => n * mult;
  519. }
  520. }
  521. /**
  522. * Returns a string of JavaScript source that evaluates to a modifier for the
  523. * input value to account for any `scale`, `percent`, and `precision-increment`
  524. * tokens in the skeleton.
  525. *
  526. * @internal
  527. * @remarks
  528. * With ICU NumberFormatter, the `percent` skeleton would style `25` as "25%".
  529. * To achieve the same with `Intl.NumberFormat`, the input value must be `0.25`.
  530. */
  531. function getNumberFormatModifierSource(skeleton) {
  532. const mult = getNumberFormatMultiplier(skeleton);
  533. const { precision } = skeleton;
  534. if (precision && precision.style === 'precision-increment') {
  535. // see round() above for source
  536. const setX = `+n + ${precision.increment / 2}`;
  537. let res = `x - (x % +${precision.increment})`;
  538. if (mult !== 1)
  539. res = `(${res}) * ${mult}`;
  540. return `function(n) { var x = ${setX}; return ${res}; }`;
  541. }
  542. return mult !== 1 ? `function(n) { return n * ${mult}; }` : null;
  543. }
  544. /**
  545. * Given an input ICU NumberFormatter skeleton, does its best to construct a
  546. * corresponding `Intl.NumberFormat` options structure.
  547. *
  548. * @remarks
  549. * Some features depend on `Intl.NumberFormat` features defined in ES2020.
  550. *
  551. * @internal
  552. * @param onUnsupported - If defined, called when encountering unsupported (but
  553. * valid) tokens, such as `decimal-always` or `permille`. The error `source`
  554. * may specify the source of an unsupported option.
  555. *
  556. * @example
  557. * ```js
  558. * import {
  559. * getNumberFormatOptions,
  560. * parseNumberSkeleton
  561. * } from '@messageformat/number-skeleton'
  562. *
  563. * const src = 'currency/CAD unit-width-narrow'
  564. * const skeleton = parseNumberSkeleton(src, console.error)
  565. * // {
  566. * // unit: { style: 'currency', currency: 'CAD' },
  567. * // unitWidth: 'unit-width-narrow'
  568. * // }
  569. *
  570. * getNumberFormatOptions(skeleton, console.error)
  571. * // {
  572. * // style: 'currency',
  573. * // currency: 'CAD',
  574. * // currencyDisplay: 'narrowSymbol',
  575. * // unitDisplay: 'narrow'
  576. * // }
  577. *
  578. * const sk2 = parseNumberSkeleton('group-min2')
  579. * // { group: 'group-min2' }
  580. *
  581. * getNumberFormatOptions(sk2, console.error)
  582. * // Error: The stem group-min2 is not supported
  583. * // at UnsupportedError.NumberFormatError ... {
  584. * // code: 'UNSUPPORTED',
  585. * // stem: 'group-min2'
  586. * // }
  587. * // {}
  588. * ```
  589. */
  590. function getNumberFormatOptions(skeleton, onUnsupported) {
  591. const { decimal, group, integerWidth, notation, precision, roundingMode, sign, unit, unitPer, unitWidth } = skeleton;
  592. const fail = (stem, source) => {
  593. if (onUnsupported)
  594. onUnsupported(new UnsupportedError(stem, source));
  595. };
  596. const opt = {};
  597. if (unit) {
  598. switch (unit.style) {
  599. case 'base-unit':
  600. opt.style = 'decimal';
  601. break;
  602. case 'currency':
  603. opt.style = 'currency';
  604. opt.currency = unit.currency;
  605. break;
  606. case 'measure-unit':
  607. opt.style = 'unit';
  608. opt.unit = unit.unit.replace(/.*-/, '');
  609. if (unitPer)
  610. opt.unit += '-per-' + unitPer.replace(/.*-/, '');
  611. break;
  612. case 'percent':
  613. opt.style = 'percent';
  614. break;
  615. case 'permille':
  616. fail('permille');
  617. break;
  618. }
  619. }
  620. switch (unitWidth) {
  621. case 'unit-width-full-name':
  622. opt.currencyDisplay = 'name';
  623. opt.unitDisplay = 'long';
  624. break;
  625. case 'unit-width-hidden':
  626. fail(unitWidth);
  627. break;
  628. case 'unit-width-iso-code':
  629. opt.currencyDisplay = 'code';
  630. break;
  631. case 'unit-width-narrow':
  632. opt.currencyDisplay = 'narrowSymbol';
  633. opt.unitDisplay = 'narrow';
  634. break;
  635. case 'unit-width-short':
  636. opt.currencyDisplay = 'symbol';
  637. opt.unitDisplay = 'short';
  638. break;
  639. }
  640. switch (group) {
  641. case 'group-off':
  642. opt.useGrouping = false;
  643. break;
  644. case 'group-auto':
  645. opt.useGrouping = true;
  646. break;
  647. case 'group-min2':
  648. case 'group-on-aligned':
  649. case 'group-thousands':
  650. fail(group);
  651. opt.useGrouping = true;
  652. break;
  653. }
  654. if (precision) {
  655. switch (precision.style) {
  656. case 'precision-fraction': {
  657. const { minFraction: minF, maxFraction: maxF, minSignificant: minS, maxSignificant: maxS, source } = precision;
  658. if (typeof minF === 'number') {
  659. opt.minimumFractionDigits = minF;
  660. if (typeof minS === 'number')
  661. fail('precision-fraction', source);
  662. }
  663. if (typeof maxF === 'number')
  664. opt.maximumFractionDigits = maxF;
  665. if (typeof minS === 'number')
  666. opt.minimumSignificantDigits = minS;
  667. if (typeof maxS === 'number')
  668. opt.maximumSignificantDigits = maxS;
  669. break;
  670. }
  671. case 'precision-integer':
  672. opt.maximumFractionDigits = 0;
  673. break;
  674. case 'precision-unlimited':
  675. opt.maximumFractionDigits = 20;
  676. break;
  677. case 'precision-increment':
  678. break;
  679. case 'precision-currency-standard':
  680. opt.trailingZeroDisplay = precision.trailingZero;
  681. break;
  682. case 'precision-currency-cash':
  683. fail(precision.style);
  684. break;
  685. }
  686. }
  687. if (notation) {
  688. switch (notation.style) {
  689. case 'compact-short':
  690. opt.notation = 'compact';
  691. opt.compactDisplay = 'short';
  692. break;
  693. case 'compact-long':
  694. opt.notation = 'compact';
  695. opt.compactDisplay = 'long';
  696. break;
  697. case 'notation-simple':
  698. opt.notation = 'standard';
  699. break;
  700. case 'scientific':
  701. case 'engineering': {
  702. const { expDigits, expSign, source, style } = notation;
  703. opt.notation = style;
  704. if ((expDigits && expDigits > 1) ||
  705. (expSign && expSign !== 'sign-auto'))
  706. fail(style, source);
  707. break;
  708. }
  709. }
  710. }
  711. if (integerWidth) {
  712. const { min, max, source } = integerWidth;
  713. if (min > 0)
  714. opt.minimumIntegerDigits = min;
  715. if (Number(max) > 0) {
  716. const hasExp = opt.notation === 'engineering' || opt.notation === 'scientific';
  717. if (max === 3 && hasExp)
  718. opt.notation = 'engineering';
  719. else
  720. fail('integer-width', source);
  721. }
  722. }
  723. switch (sign) {
  724. case 'sign-auto':
  725. opt.signDisplay = 'auto';
  726. break;
  727. case 'sign-always':
  728. opt.signDisplay = 'always';
  729. break;
  730. case 'sign-except-zero':
  731. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  732. // @ts-ignore https://github.com/microsoft/TypeScript/issues/46712
  733. opt.signDisplay = 'exceptZero';
  734. break;
  735. case 'sign-never':
  736. opt.signDisplay = 'never';
  737. break;
  738. case 'sign-accounting':
  739. opt.currencySign = 'accounting';
  740. break;
  741. case 'sign-accounting-always':
  742. opt.currencySign = 'accounting';
  743. opt.signDisplay = 'always';
  744. break;
  745. case 'sign-accounting-except-zero':
  746. opt.currencySign = 'accounting';
  747. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  748. // @ts-ignore https://github.com/microsoft/TypeScript/issues/46712
  749. opt.signDisplay = 'exceptZero';
  750. break;
  751. }
  752. if (decimal === 'decimal-always')
  753. fail(decimal);
  754. if (roundingMode)
  755. fail(roundingMode);
  756. return opt;
  757. }
  758. function parseAffixToken(src, pos, onError) {
  759. const char = src[pos];
  760. switch (char) {
  761. case '%':
  762. return { char: '%', style: 'percent', width: 1 };
  763. case '‰':
  764. return { char: '%', style: 'permille', width: 1 };
  765. case '¤': {
  766. let width = 1;
  767. while (src[++pos] === '¤')
  768. ++width;
  769. switch (width) {
  770. case 1:
  771. return { char, currency: 'default', width };
  772. case 2:
  773. return { char, currency: 'iso-code', width };
  774. case 3:
  775. return { char, currency: 'full-name', width };
  776. case 5:
  777. return { char, currency: 'narrow', width };
  778. default: {
  779. const msg = `Invalid number (${width}) of ¤ chars in pattern`;
  780. onError(new PatternError('¤', msg));
  781. return null;
  782. }
  783. }
  784. }
  785. case '*': {
  786. const pad = src[pos + 1];
  787. if (pad)
  788. return { char, pad, width: 2 };
  789. break;
  790. }
  791. case '+':
  792. case '-':
  793. return { char, width: 1 };
  794. case "'": {
  795. let str = src[++pos];
  796. let width = 2;
  797. if (str === "'")
  798. return { char, str, width };
  799. while (true) {
  800. const next = src[++pos];
  801. ++width;
  802. if (next === undefined) {
  803. const msg = `Unterminated quoted literal in pattern: ${str}`;
  804. onError(new PatternError("'", msg));
  805. return { char, str, width };
  806. }
  807. else if (next === "'") {
  808. if (src[++pos] !== "'")
  809. return { char, str, width };
  810. else
  811. ++width;
  812. }
  813. str += next;
  814. }
  815. }
  816. }
  817. return null;
  818. }
  819. const isDigit = (char) => char >= '0' && char <= '9';
  820. function parseNumberToken(src, pos) {
  821. const char = src[pos];
  822. if (isDigit(char)) {
  823. let digits = char;
  824. while (true) {
  825. const next = src[++pos];
  826. if (isDigit(next))
  827. digits += next;
  828. else
  829. return { char: '0', digits, width: digits.length };
  830. }
  831. }
  832. switch (char) {
  833. case '#': {
  834. let width = 1;
  835. while (src[++pos] === '#')
  836. ++width;
  837. return { char, width };
  838. }
  839. case '@': {
  840. let min = 1;
  841. while (src[++pos] === '@')
  842. ++min;
  843. let width = min;
  844. pos -= 1;
  845. while (src[++pos] === '#')
  846. ++width;
  847. return { char, min, width };
  848. }
  849. case 'E': {
  850. const plus = src[pos + 1] === '+';
  851. if (plus)
  852. ++pos;
  853. let expDigits = 0;
  854. while (src[++pos] === '0')
  855. ++expDigits;
  856. const width = (plus ? 2 : 1) + expDigits;
  857. if (expDigits)
  858. return { char, expDigits, plus, width };
  859. else
  860. break;
  861. }
  862. case '.':
  863. case ',':
  864. return { char, width: 1 };
  865. }
  866. return null;
  867. }
  868. function parseSubpattern(src, pos, onError) {
  869. let State;
  870. (function (State) {
  871. State[State["Prefix"] = 0] = "Prefix";
  872. State[State["Number"] = 1] = "Number";
  873. State[State["Suffix"] = 2] = "Suffix";
  874. })(State || (State = {}));
  875. const prefix = [];
  876. const number = [];
  877. const suffix = [];
  878. let state = State.Prefix;
  879. let str = '';
  880. while (pos < src.length) {
  881. const char = src[pos];
  882. if (char === ';') {
  883. pos += 1;
  884. break;
  885. }
  886. switch (state) {
  887. case State.Prefix: {
  888. const token = parseAffixToken(src, pos, onError);
  889. if (token) {
  890. if (str) {
  891. prefix.push({ char: "'", str, width: str.length });
  892. str = '';
  893. }
  894. prefix.push(token);
  895. pos += token.width;
  896. }
  897. else {
  898. const token = parseNumberToken(src, pos);
  899. if (token) {
  900. if (str) {
  901. prefix.push({ char: "'", str, width: str.length });
  902. str = '';
  903. }
  904. state = State.Number;
  905. number.push(token);
  906. pos += token.width;
  907. }
  908. else {
  909. str += char;
  910. pos += 1;
  911. }
  912. }
  913. break;
  914. }
  915. case State.Number: {
  916. const token = parseNumberToken(src, pos);
  917. if (token) {
  918. number.push(token);
  919. pos += token.width;
  920. }
  921. else {
  922. state = State.Suffix;
  923. }
  924. break;
  925. }
  926. case State.Suffix: {
  927. const token = parseAffixToken(src, pos, onError);
  928. if (token) {
  929. if (str) {
  930. suffix.push({ char: "'", str, width: str.length });
  931. str = '';
  932. }
  933. suffix.push(token);
  934. pos += token.width;
  935. }
  936. else {
  937. str += char;
  938. pos += 1;
  939. }
  940. break;
  941. }
  942. }
  943. }
  944. if (str)
  945. suffix.push({ char: "'", str, width: str.length });
  946. return { pattern: { prefix, number, suffix }, pos };
  947. }
  948. function parseTokens(src, onError) {
  949. const { pattern, pos } = parseSubpattern(src, 0, onError);
  950. if (pos < src.length) {
  951. const { pattern: negative } = parseSubpattern(src, pos, onError);
  952. return { tokens: pattern, negative };
  953. }
  954. return { tokens: pattern };
  955. }
  956. function parseNumberAsSkeleton(tokens, onError) {
  957. const res = {};
  958. let hasGroups = false;
  959. let hasExponent = false;
  960. let intOptional = 0;
  961. let intDigits = '';
  962. let decimalPos = -1;
  963. let fracDigits = '';
  964. let fracOptional = 0;
  965. for (let pos = 0; pos < tokens.length; ++pos) {
  966. const token = tokens[pos];
  967. switch (token.char) {
  968. case '#': {
  969. if (decimalPos === -1) {
  970. if (intDigits) {
  971. const msg = 'Pattern has # after integer digits';
  972. onError(new PatternError('#', msg));
  973. }
  974. intOptional += token.width;
  975. }
  976. else {
  977. fracOptional += token.width;
  978. }
  979. break;
  980. }
  981. case '0': {
  982. if (decimalPos === -1) {
  983. intDigits += token.digits;
  984. }
  985. else {
  986. if (fracOptional) {
  987. const msg = 'Pattern has digits after # in fraction';
  988. onError(new PatternError('0', msg));
  989. }
  990. fracDigits += token.digits;
  991. }
  992. break;
  993. }
  994. case '@': {
  995. if (res.precision)
  996. onError(new MaskedValueError('precision', res.precision));
  997. res.precision = {
  998. style: 'precision-fraction',
  999. minSignificant: token.min,
  1000. maxSignificant: token.width
  1001. };
  1002. break;
  1003. }
  1004. case ',':
  1005. hasGroups = true;
  1006. break;
  1007. case '.':
  1008. if (decimalPos === 1) {
  1009. const msg = 'Pattern has more than one decimal separator';
  1010. onError(new PatternError('.', msg));
  1011. }
  1012. decimalPos = pos;
  1013. break;
  1014. case 'E': {
  1015. if (hasExponent)
  1016. onError(new MaskedValueError('exponent', res.notation));
  1017. if (hasGroups) {
  1018. const msg = 'Exponential patterns may not contain grouping separators';
  1019. onError(new PatternError('E', msg));
  1020. }
  1021. res.notation = { style: 'scientific' };
  1022. if (token.expDigits > 1)
  1023. res.notation.expDigits = token.expDigits;
  1024. if (token.plus)
  1025. res.notation.expSign = 'sign-always';
  1026. hasExponent = true;
  1027. }
  1028. }
  1029. }
  1030. // imprecise mapping due to paradigm differences
  1031. if (hasGroups)
  1032. res.group = 'group-auto';
  1033. else if (intOptional + intDigits.length > 3)
  1034. res.group = 'group-off';
  1035. const increment = Number(`${intDigits || '0'}.${fracDigits}`);
  1036. if (increment)
  1037. res.precision = { style: 'precision-increment', increment };
  1038. if (!hasExponent) {
  1039. if (intDigits.length > 1)
  1040. res.integerWidth = { min: intDigits.length };
  1041. if (!res.precision && (fracDigits.length || fracOptional)) {
  1042. res.precision = {
  1043. style: 'precision-fraction',
  1044. minFraction: fracDigits.length,
  1045. maxFraction: fracDigits.length + fracOptional
  1046. };
  1047. }
  1048. }
  1049. else {
  1050. if (!res.precision || increment) {
  1051. res.integerWidth = intOptional
  1052. ? { min: 1, max: intOptional + intDigits.length }
  1053. : { min: Math.max(1, intDigits.length) };
  1054. }
  1055. if (res.precision) {
  1056. if (!increment)
  1057. res.integerWidth = { min: 1, max: 1 };
  1058. }
  1059. else {
  1060. const dc = intDigits.length + fracDigits.length;
  1061. if (decimalPos === -1) {
  1062. if (dc > 0)
  1063. res.precision = { style: 'precision-fraction', maxSignificant: dc };
  1064. }
  1065. else {
  1066. res.precision = {
  1067. style: 'precision-fraction',
  1068. maxSignificant: Math.max(1, dc) + fracOptional
  1069. };
  1070. if (dc > 1)
  1071. res.precision.minSignificant = dc;
  1072. }
  1073. }
  1074. }
  1075. return res;
  1076. }
  1077. function handleAffix(affixTokens, res, currency, onError, isPrefix) {
  1078. let inFmt = false;
  1079. let str = '';
  1080. for (const token of affixTokens) {
  1081. switch (token.char) {
  1082. case '%':
  1083. res.unit = { style: token.style };
  1084. if (isPrefix)
  1085. inFmt = true;
  1086. else
  1087. str = '';
  1088. break;
  1089. case '¤':
  1090. if (!currency) {
  1091. const msg = `The ¤ pattern requires a currency`;
  1092. onError(new PatternError('¤', msg));
  1093. break;
  1094. }
  1095. res.unit = { style: 'currency', currency };
  1096. switch (token.currency) {
  1097. case 'iso-code':
  1098. res.unitWidth = 'unit-width-iso-code';
  1099. break;
  1100. case 'full-name':
  1101. res.unitWidth = 'unit-width-full-name';
  1102. break;
  1103. case 'narrow':
  1104. res.unitWidth = 'unit-width-narrow';
  1105. break;
  1106. }
  1107. if (isPrefix)
  1108. inFmt = true;
  1109. else
  1110. str = '';
  1111. break;
  1112. case '*':
  1113. // TODO
  1114. break;
  1115. case '+':
  1116. if (!inFmt)
  1117. str += '+';
  1118. break;
  1119. case "'":
  1120. if (!inFmt)
  1121. str += token.str;
  1122. break;
  1123. }
  1124. }
  1125. return str;
  1126. }
  1127. function getNegativeAffix(affixTokens, isPrefix) {
  1128. let inFmt = false;
  1129. let str = '';
  1130. for (const token of affixTokens) {
  1131. switch (token.char) {
  1132. case '%':
  1133. case '¤':
  1134. if (isPrefix)
  1135. inFmt = true;
  1136. else
  1137. str = '';
  1138. break;
  1139. case '-':
  1140. if (!inFmt)
  1141. str += '-';
  1142. break;
  1143. case "'":
  1144. if (!inFmt)
  1145. str += token.str;
  1146. break;
  1147. }
  1148. }
  1149. return str;
  1150. }
  1151. /**
  1152. * Parse an {@link
  1153. * http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns |
  1154. * ICU NumberFormatter pattern} string into a {@link Skeleton} structure.
  1155. *
  1156. * @public
  1157. * @param src - The pattern string
  1158. * @param currency - If the pattern includes ¤ tokens, their skeleton
  1159. * representation requires a three-letter currency code.
  1160. * @param onError - Called when the parser encounters a syntax error. The
  1161. * function will still return a {@link Skeleton}, but it will be incomplete
  1162. * and/or inaccurate. If not defined, the error will be thrown instead.
  1163. *
  1164. * @remarks
  1165. * Unlike the skeleton parser, the pattern parser is not able to return partial
  1166. * results on error, and will instead throw. Output padding is not supported.
  1167. *
  1168. * @example
  1169. * ```js
  1170. * import { parseNumberPattern } from '@messageformat/number-skeleton'
  1171. *
  1172. * parseNumberPattern('#,##0.00 ¤', 'EUR', console.error)
  1173. * // {
  1174. * // group: 'group-auto',
  1175. * // precision: {
  1176. * // style: 'precision-fraction',
  1177. * // minFraction: 2,
  1178. * // maxFraction: 2
  1179. * // },
  1180. * // unit: { style: 'currency', currency: 'EUR' }
  1181. * // }
  1182. * ```
  1183. */
  1184. function parseNumberPattern(src, currency, onError = error => {
  1185. throw error;
  1186. }) {
  1187. const { tokens, negative } = parseTokens(src, onError);
  1188. const res = parseNumberAsSkeleton(tokens.number, onError);
  1189. const prefix = handleAffix(tokens.prefix, res, currency, onError, true);
  1190. const suffix = handleAffix(tokens.suffix, res, currency, onError, false);
  1191. if (negative) {
  1192. const negPrefix = getNegativeAffix(negative.prefix, true);
  1193. const negSuffix = getNegativeAffix(negative.suffix, false);
  1194. res.affix = { pos: [prefix, suffix], neg: [negPrefix, negSuffix] };
  1195. res.sign = 'sign-never';
  1196. }
  1197. else if (prefix || suffix) {
  1198. res.affix = { pos: [prefix, suffix] };
  1199. }
  1200. return res;
  1201. }
  1202. /** @internal */
  1203. function isNumberingSystem(ns) {
  1204. const systems = [
  1205. 'arab',
  1206. 'arabext',
  1207. 'bali',
  1208. 'beng',
  1209. 'deva',
  1210. 'fullwide',
  1211. 'gujr',
  1212. 'guru',
  1213. 'hanidec',
  1214. 'khmr',
  1215. 'knda',
  1216. 'laoo',
  1217. 'latn',
  1218. 'limb',
  1219. 'mlym',
  1220. 'mong',
  1221. 'mymr',
  1222. 'orya',
  1223. 'tamldec',
  1224. 'telu',
  1225. 'thai',
  1226. 'tibt'
  1227. ];
  1228. return systems.indexOf(ns) !== -1;
  1229. }
  1230. // FIXME: subtype is not checked
  1231. /** @internal */
  1232. function isUnit(unit) {
  1233. const types = [
  1234. 'acceleration',
  1235. 'angle',
  1236. 'area',
  1237. 'concentr',
  1238. 'consumption',
  1239. 'digital',
  1240. 'duration',
  1241. 'electric',
  1242. 'energy',
  1243. 'force',
  1244. 'frequency',
  1245. 'graphics',
  1246. 'length',
  1247. 'light',
  1248. 'mass',
  1249. 'power',
  1250. 'pressure',
  1251. 'speed',
  1252. 'temperature',
  1253. 'torque',
  1254. 'volume'
  1255. ];
  1256. const [type] = unit.split('-', 1);
  1257. return types.indexOf(type) !== -1;
  1258. }
  1259. const maxOptions = {
  1260. 'compact-short': 0,
  1261. 'compact-long': 0,
  1262. 'notation-simple': 0,
  1263. scientific: 2,
  1264. engineering: 2,
  1265. percent: 0,
  1266. permille: 0,
  1267. 'base-unit': 0,
  1268. currency: 1,
  1269. 'measure-unit': 1,
  1270. 'per-measure-unit': 1,
  1271. 'unit-width-narrow': 0,
  1272. 'unit-width-short': 0,
  1273. 'unit-width-full-name': 0,
  1274. 'unit-width-iso-code': 0,
  1275. 'unit-width-hidden': 0,
  1276. 'precision-integer': 0,
  1277. 'precision-unlimited': 0,
  1278. 'precision-currency-standard': 1,
  1279. 'precision-currency-cash': 0,
  1280. 'precision-increment': 1,
  1281. 'rounding-mode-ceiling': 0,
  1282. 'rounding-mode-floor': 0,
  1283. 'rounding-mode-down': 0,
  1284. 'rounding-mode-up': 0,
  1285. 'rounding-mode-half-even': 0,
  1286. 'rounding-mode-half-down': 0,
  1287. 'rounding-mode-half-up': 0,
  1288. 'rounding-mode-unnecessary': 0,
  1289. 'integer-width': 1,
  1290. scale: 1,
  1291. 'group-off': 0,
  1292. 'group-min2': 0,
  1293. 'group-auto': 0,
  1294. 'group-on-aligned': 0,
  1295. 'group-thousands': 0,
  1296. latin: 0,
  1297. 'numbering-system': 1,
  1298. 'sign-auto': 0,
  1299. 'sign-always': 0,
  1300. 'sign-never': 0,
  1301. 'sign-accounting': 0,
  1302. 'sign-accounting-always': 0,
  1303. 'sign-except-zero': 0,
  1304. 'sign-accounting-except-zero': 0,
  1305. 'decimal-auto': 0,
  1306. 'decimal-always': 0
  1307. };
  1308. const minOptions = {
  1309. currency: 1,
  1310. 'integer-width': 1,
  1311. 'measure-unit': 1,
  1312. 'numbering-system': 1,
  1313. 'per-measure-unit': 1,
  1314. 'precision-increment': 1,
  1315. scale: 1
  1316. };
  1317. function hasMaxOption(stem) {
  1318. return stem in maxOptions;
  1319. }
  1320. function hasMinOption(stem) {
  1321. return stem in minOptions;
  1322. }
  1323. /** @internal */
  1324. function validOptions(stem, options, onError) {
  1325. if (hasMaxOption(stem)) {
  1326. const maxOpt = maxOptions[stem];
  1327. if (options.length > maxOpt) {
  1328. if (maxOpt === 0) {
  1329. for (const opt of options)
  1330. onError(new BadOptionError(stem, opt));
  1331. }
  1332. else {
  1333. onError(new TooManyOptionsError(stem, options, maxOpt));
  1334. }
  1335. return false;
  1336. }
  1337. else if (hasMinOption(stem) && options.length < minOptions[stem]) {
  1338. onError(new MissingOptionError(stem));
  1339. return false;
  1340. }
  1341. }
  1342. return true;
  1343. }
  1344. function parseBlueprintDigits(src, style) {
  1345. const re = style === 'fraction' ? /^\.(0*)(\+|#*)$/ : /^(@+)(\+|#*)$/;
  1346. const match = src && src.match(re);
  1347. if (match) {
  1348. const min = match[1].length;
  1349. switch (match[2].charAt(0)) {
  1350. case '':
  1351. return { min, max: min };
  1352. case '+':
  1353. return { min, max: null };
  1354. case '#': {
  1355. return { min, max: min + match[2].length };
  1356. }
  1357. }
  1358. }
  1359. return null;
  1360. }
  1361. function parsePrecisionBlueprint(stem, options, onError) {
  1362. const fd = parseBlueprintDigits(stem, 'fraction');
  1363. if (fd) {
  1364. if (options.length > 1)
  1365. onError(new TooManyOptionsError(stem, options, 1));
  1366. const res = {
  1367. style: 'precision-fraction',
  1368. source: stem,
  1369. minFraction: fd.min
  1370. };
  1371. if (fd.max != null)
  1372. res.maxFraction = fd.max;
  1373. const option = options[0];
  1374. const sd = parseBlueprintDigits(option, 'significant');
  1375. if (sd) {
  1376. res.source = `${stem}/${option}`;
  1377. res.minSignificant = sd.min;
  1378. if (sd.max != null)
  1379. res.maxSignificant = sd.max;
  1380. }
  1381. else if (option)
  1382. onError(new BadOptionError(stem, option));
  1383. return res;
  1384. }
  1385. const sd = parseBlueprintDigits(stem, 'significant');
  1386. if (sd) {
  1387. for (const opt of options)
  1388. onError(new BadOptionError(stem, opt));
  1389. const res = {
  1390. style: 'precision-fraction',
  1391. source: stem,
  1392. minSignificant: sd.min
  1393. };
  1394. if (sd.max != null)
  1395. res.maxSignificant = sd.max;
  1396. return res;
  1397. }
  1398. return null;
  1399. }
  1400. /** @internal */
  1401. class TokenParser {
  1402. constructor(onError) {
  1403. this.skeleton = {};
  1404. this.onError = onError;
  1405. }
  1406. badOption(stem, opt) {
  1407. this.onError(new BadOptionError(stem, opt));
  1408. }
  1409. assertEmpty(key) {
  1410. const prev = this.skeleton[key];
  1411. if (prev)
  1412. this.onError(new MaskedValueError(key, prev));
  1413. }
  1414. parseToken(stem, options) {
  1415. if (!validOptions(stem, options, this.onError))
  1416. return;
  1417. const option = options[0];
  1418. const res = this.skeleton;
  1419. switch (stem) {
  1420. // notation
  1421. case 'compact-short':
  1422. case 'compact-long':
  1423. case 'notation-simple':
  1424. this.assertEmpty('notation');
  1425. res.notation = { style: stem };
  1426. break;
  1427. case 'scientific':
  1428. case 'engineering': {
  1429. let expDigits = null;
  1430. let expSign = undefined;
  1431. for (const opt of options) {
  1432. switch (opt) {
  1433. case 'sign-auto':
  1434. case 'sign-always':
  1435. case 'sign-never':
  1436. case 'sign-accounting':
  1437. case 'sign-accounting-always':
  1438. case 'sign-except-zero':
  1439. case 'sign-accounting-except-zero':
  1440. expSign = opt;
  1441. break;
  1442. default:
  1443. if (/^\+e+$/.test(opt))
  1444. expDigits = opt.length - 1;
  1445. else {
  1446. this.badOption(stem, opt);
  1447. }
  1448. }
  1449. }
  1450. this.assertEmpty('notation');
  1451. const source = options.join('/');
  1452. res.notation =
  1453. expDigits && expSign
  1454. ? { style: stem, source, expDigits, expSign }
  1455. : expDigits
  1456. ? { style: stem, source, expDigits }
  1457. : expSign
  1458. ? { style: stem, source, expSign }
  1459. : { style: stem, source };
  1460. break;
  1461. }
  1462. // unit
  1463. case 'percent':
  1464. case 'permille':
  1465. case 'base-unit':
  1466. this.assertEmpty('unit');
  1467. res.unit = { style: stem };
  1468. break;
  1469. case 'currency':
  1470. if (/^[A-Z]{3}$/.test(option)) {
  1471. this.assertEmpty('unit');
  1472. res.unit = { style: stem, currency: option };
  1473. }
  1474. else
  1475. this.badOption(stem, option);
  1476. break;
  1477. case 'measure-unit': {
  1478. if (isUnit(option)) {
  1479. this.assertEmpty('unit');
  1480. res.unit = { style: stem, unit: option };
  1481. }
  1482. else
  1483. this.badOption(stem, option);
  1484. break;
  1485. }
  1486. // unitPer
  1487. case 'per-measure-unit': {
  1488. if (isUnit(option)) {
  1489. this.assertEmpty('unitPer');
  1490. res.unitPer = option;
  1491. }
  1492. else
  1493. this.badOption(stem, option);
  1494. break;
  1495. }
  1496. // unitWidth
  1497. case 'unit-width-narrow':
  1498. case 'unit-width-short':
  1499. case 'unit-width-full-name':
  1500. case 'unit-width-iso-code':
  1501. case 'unit-width-hidden':
  1502. this.assertEmpty('unitWidth');
  1503. res.unitWidth = stem;
  1504. break;
  1505. // precision
  1506. case 'precision-integer':
  1507. case 'precision-unlimited':
  1508. case 'precision-currency-cash':
  1509. this.assertEmpty('precision');
  1510. res.precision = { style: stem };
  1511. break;
  1512. case 'precision-currency-standard':
  1513. this.assertEmpty('precision');
  1514. if (option === 'w') {
  1515. res.precision = { style: stem, trailingZero: 'stripIfInteger' };
  1516. }
  1517. else {
  1518. res.precision = { style: stem };
  1519. }
  1520. break;
  1521. case 'precision-increment': {
  1522. const increment = Number(option);
  1523. if (increment > 0) {
  1524. this.assertEmpty('precision');
  1525. res.precision = { style: stem, increment };
  1526. }
  1527. else
  1528. this.badOption(stem, option);
  1529. break;
  1530. }
  1531. // roundingMode
  1532. case 'rounding-mode-ceiling':
  1533. case 'rounding-mode-floor':
  1534. case 'rounding-mode-down':
  1535. case 'rounding-mode-up':
  1536. case 'rounding-mode-half-even':
  1537. case 'rounding-mode-half-odd':
  1538. case 'rounding-mode-half-ceiling':
  1539. case 'rounding-mode-half-floor':
  1540. case 'rounding-mode-half-down':
  1541. case 'rounding-mode-half-up':
  1542. case 'rounding-mode-unnecessary':
  1543. this.assertEmpty('roundingMode');
  1544. res.roundingMode = stem;
  1545. break;
  1546. // integerWidth
  1547. case 'integer-width': {
  1548. if (/^\+0*$/.test(option)) {
  1549. this.assertEmpty('integerWidth');
  1550. res.integerWidth = { source: option, min: option.length - 1 };
  1551. }
  1552. else {
  1553. const m = option.match(/^#*(0*)$/);
  1554. if (m) {
  1555. this.assertEmpty('integerWidth');
  1556. res.integerWidth = {
  1557. source: option,
  1558. min: m[1].length,
  1559. max: m[0].length
  1560. };
  1561. }
  1562. else
  1563. this.badOption(stem, option);
  1564. }
  1565. break;
  1566. }
  1567. // scale
  1568. case 'scale': {
  1569. const scale = Number(option);
  1570. if (scale > 0) {
  1571. this.assertEmpty('scale');
  1572. res.scale = scale;
  1573. }
  1574. else
  1575. this.badOption(stem, option);
  1576. break;
  1577. }
  1578. // group
  1579. case 'group-off':
  1580. case 'group-min2':
  1581. case 'group-auto':
  1582. case 'group-on-aligned':
  1583. case 'group-thousands':
  1584. this.assertEmpty('group');
  1585. res.group = stem;
  1586. break;
  1587. // numberingSystem
  1588. case 'latin':
  1589. this.assertEmpty('numberingSystem');
  1590. res.numberingSystem = 'latn';
  1591. break;
  1592. case 'numbering-system': {
  1593. if (isNumberingSystem(option)) {
  1594. this.assertEmpty('numberingSystem');
  1595. res.numberingSystem = option;
  1596. }
  1597. else
  1598. this.badOption(stem, option);
  1599. break;
  1600. }
  1601. // sign
  1602. case 'sign-auto':
  1603. case 'sign-always':
  1604. case 'sign-never':
  1605. case 'sign-accounting':
  1606. case 'sign-accounting-always':
  1607. case 'sign-except-zero':
  1608. case 'sign-accounting-except-zero':
  1609. this.assertEmpty('sign');
  1610. res.sign = stem;
  1611. break;
  1612. // decimal
  1613. case 'decimal-auto':
  1614. case 'decimal-always':
  1615. this.assertEmpty('decimal');
  1616. res.decimal = stem;
  1617. break;
  1618. // precision blueprint
  1619. default: {
  1620. const precision = parsePrecisionBlueprint(stem, options, this.onError);
  1621. if (precision) {
  1622. this.assertEmpty('precision');
  1623. res.precision = precision;
  1624. }
  1625. else {
  1626. this.onError(new BadStemError(stem));
  1627. }
  1628. }
  1629. }
  1630. }
  1631. }
  1632. /**
  1633. * Parse an {@link
  1634. * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md
  1635. * | ICU NumberFormatter skeleton} string into a {@link Skeleton} structure.
  1636. *
  1637. * @public
  1638. * @param src - The skeleton string
  1639. * @param onError - Called when the parser encounters a syntax error. The
  1640. * function will still return a {@link Skeleton}, but it may not contain
  1641. * information for all tokens. If not defined, the error will be thrown
  1642. * instead.
  1643. *
  1644. * @example
  1645. * ```js
  1646. * import { parseNumberSkeleton } from '@messageformat/number-skeleton'
  1647. *
  1648. * parseNumberSkeleton('compact-short currency/GBP', console.error)
  1649. * // {
  1650. * // notation: { style: 'compact-short' },
  1651. * // unit: { style: 'currency', currency: 'GBP' }
  1652. * // }
  1653. * ```
  1654. */
  1655. function parseNumberSkeleton(src, onError = error => {
  1656. throw error;
  1657. }) {
  1658. const tokens = [];
  1659. for (const part of src.split(' ')) {
  1660. if (part) {
  1661. const options = part.split('/');
  1662. const stem = options.shift() || '';
  1663. tokens.push({ stem, options });
  1664. }
  1665. }
  1666. const parser = new TokenParser(onError);
  1667. for (const { stem, options } of tokens) {
  1668. parser.parseToken(stem, options);
  1669. }
  1670. return parser.skeleton;
  1671. }
  1672. /**
  1673. * Returns a number formatter function for the given locales and number skeleton
  1674. *
  1675. * @remarks
  1676. * Uses `Intl.NumberFormat` (ES2020) internally.
  1677. *
  1678. * @public
  1679. * @param locales - One or more valid BCP 47 language tags, e.g. `fr` or `en-CA`
  1680. * @param skeleton - An ICU NumberFormatter pattern or `::`-prefixed skeleton
  1681. * string, or a parsed `Skeleton` structure
  1682. * @param currency - If `skeleton` is a pattern string that includes ¤ tokens,
  1683. * their skeleton representation requires a three-letter currency code.
  1684. * @param onError - If defined, will be called separately for each encountered
  1685. * parsing error and unsupported feature.
  1686. * @example
  1687. * ```js
  1688. * import { getNumberFormatter } from '@messageformat/number-skeleton'
  1689. *
  1690. * let src = ':: currency/CAD unit-width-narrow'
  1691. * let fmt = getNumberFormatter('en-CA', src, console.error)
  1692. * fmt(42) // '$42.00'
  1693. *
  1694. * src = '::percent scale/100'
  1695. * fmt = getNumberFormatter('en', src, console.error)
  1696. * fmt(0.3) // '30%'
  1697. * ```
  1698. */
  1699. function getNumberFormatter(locales, skeleton, currency, onError) {
  1700. if (typeof skeleton === 'string') {
  1701. skeleton =
  1702. skeleton.indexOf('::') === 0
  1703. ? parseNumberSkeleton(skeleton.slice(2), onError)
  1704. : parseNumberPattern(skeleton, currency, onError);
  1705. }
  1706. const lc = getNumberFormatLocales(locales, skeleton);
  1707. const opt = getNumberFormatOptions(skeleton, onError);
  1708. const mod = getNumberFormatModifier(skeleton);
  1709. const nf = new Intl.NumberFormat(lc, opt);
  1710. if (skeleton.affix) {
  1711. const [p0, p1] = skeleton.affix.pos;
  1712. const [n0, n1] = skeleton.affix.neg || ['', ''];
  1713. return (value) => {
  1714. const n = nf.format(mod(value));
  1715. return value < 0 ? `${n0}${n}${n1}` : `${p0}${n}${p1}`;
  1716. };
  1717. }
  1718. return (value) => nf.format(mod(value));
  1719. }
  1720. /**
  1721. * Returns a string of JavaScript source that evaluates to a number formatter
  1722. * function with the same `(value: number) => string` signature as the function
  1723. * returned by {@link getNumberFormatter}.
  1724. *
  1725. * @remarks
  1726. * The returned function will memoize an `Intl.NumberFormat` instance.
  1727. *
  1728. * @public
  1729. * @param locales - One or more valid BCP 47 language tags, e.g. `fr` or `en-CA`
  1730. * @param skeleton - An ICU NumberFormatter pattern or `::`-prefixed skeleton
  1731. * string, or a parsed `Skeleton` structure
  1732. * @param currency - If `skeleton` is a pattern string that includes ¤ tokens,
  1733. * their skeleton representation requires a three-letter currency code.
  1734. * @param onError - If defined, will be called separately for each encountered
  1735. * parsing error and unsupported feature.
  1736. * @example
  1737. * ```js
  1738. * import { getNumberFormatterSource } from '@messageformat/number-skeleton'
  1739. *
  1740. * getNumberFormatterSource('en', '::percent', console.error)
  1741. * // '(function() {\n' +
  1742. * // ' var opt = {"style":"percent"};\n' +
  1743. * // ' var nf = new Intl.NumberFormat(["en"], opt);\n' +
  1744. * // ' var mod = function(n) { return n * 0.01; };\n' +
  1745. * // ' return function(value) { return nf.format(mod(value)); }\n' +
  1746. * // '})()'
  1747. *
  1748. * const src = getNumberFormatterSource('en-CA', ':: currency/CAD unit-width-narrow', console.error)
  1749. * // '(function() {\n' +
  1750. * // ' var opt = {"style":"currency","currency":"CAD","currencyDisplay":"narrowSymbol","unitDisplay":"narrow"};\n' +
  1751. * // ' var nf = new Intl.NumberFormat(["en-CA"], opt);\n'
  1752. * // ' return function(value) { return nf.format(value); }\n' +
  1753. * // '})()'
  1754. * const fmt = new Function(`return ${src}`)()
  1755. * fmt(42) // '$42.00'
  1756. * ```
  1757. */
  1758. function getNumberFormatterSource(locales, skeleton, currency, onError) {
  1759. if (typeof skeleton === 'string') {
  1760. skeleton =
  1761. skeleton.indexOf('::') === 0
  1762. ? parseNumberSkeleton(skeleton.slice(2), onError)
  1763. : parseNumberPattern(skeleton, currency, onError);
  1764. }
  1765. const lc = getNumberFormatLocales(locales, skeleton);
  1766. const opt = getNumberFormatOptions(skeleton, onError);
  1767. const modSrc = getNumberFormatModifierSource(skeleton);
  1768. const lines = [
  1769. `(function() {`,
  1770. `var opt = ${JSON.stringify(opt)};`,
  1771. `var nf = new Intl.NumberFormat(${JSON.stringify(lc)}, opt);`
  1772. ];
  1773. let res = 'nf.format(value)';
  1774. if (modSrc) {
  1775. lines.push(`var mod = ${modSrc};`);
  1776. res = 'nf.format(mod(value))';
  1777. }
  1778. if (skeleton.affix) {
  1779. const [p0, p1] = skeleton.affix.pos.map(s => JSON.stringify(s));
  1780. if (skeleton.affix.neg) {
  1781. const [n0, n1] = skeleton.affix.neg.map(s => JSON.stringify(s));
  1782. res = `value < 0 ? ${n0} + ${res} + ${n1} : ${p0} + ${res} + ${p1}`;
  1783. }
  1784. else {
  1785. res = `${p0} + ${res} + ${p1}`;
  1786. }
  1787. }
  1788. lines.push(`return function(value) { return ${res}; }`);
  1789. return lines.join('\n ') + '\n})()';
  1790. }
  1791. const rtlLanguages = [
  1792. 'ar',
  1793. 'ckb',
  1794. 'fa',
  1795. 'he',
  1796. 'ks($|[^bfh])',
  1797. 'lrc',
  1798. 'mzn',
  1799. 'pa-Arab',
  1800. 'ps',
  1801. 'ug',
  1802. 'ur',
  1803. 'uz-Arab',
  1804. 'yi'
  1805. ];
  1806. const rtlRegExp = new RegExp('^' + rtlLanguages.join('|^'));
  1807. function biDiMarkText(text, locale) {
  1808. const isLocaleRTL = rtlRegExp.test(locale);
  1809. const mark = JSON.stringify(isLocaleRTL ? '\u200F' : '\u200E');
  1810. return `${mark} + ${text} + ${mark}`;
  1811. }
  1812. const RUNTIME_MODULE = '@messageformat/runtime';
  1813. const CARDINAL_MODULE = '@messageformat/runtime/lib/cardinals';
  1814. const PLURAL_MODULE = '@messageformat/runtime/lib/plurals';
  1815. const FORMATTER_MODULE = '@messageformat/runtime/lib/formatters';
  1816. class Compiler {
  1817. constructor(options) {
  1818. this.arguments = [];
  1819. this.runtime = {};
  1820. this.options = options;
  1821. }
  1822. compile(src, plural, plurals) {
  1823. const { localeCodeFromKey, requireAllArguments, strict, strictPluralKeys } = this.options;
  1824. if (typeof src === 'object') {
  1825. const result = {};
  1826. for (const key of Object.keys(src)) {
  1827. const lc = localeCodeFromKey ? localeCodeFromKey(key) : key;
  1828. const pl = (plurals && lc && plurals[lc]) || plural;
  1829. result[key] = this.compile(src[key], pl, plurals);
  1830. }
  1831. return result;
  1832. }
  1833. this.plural = plural;
  1834. const parserOptions = {
  1835. cardinal: plural.cardinals,
  1836. ordinal: plural.ordinals,
  1837. strict,
  1838. strictPluralKeys
  1839. };
  1840. this.arguments = [];
  1841. const r = parser.parse(src, parserOptions).map(token => this.token(token, null));
  1842. const hasArgs = this.arguments.length > 0;
  1843. const res = this.concatenate(r, true);
  1844. if (requireAllArguments && hasArgs) {
  1845. this.setRuntimeFn('reqArgs');
  1846. const reqArgs = JSON.stringify(this.arguments);
  1847. return `(d) => { reqArgs(${reqArgs}, d); return ${res}; }`;
  1848. }
  1849. return `(${hasArgs ? 'd' : ''}) => ${res}`;
  1850. }
  1851. cases(token, pluralToken) {
  1852. let needOther = true;
  1853. const r = token.cases.map(({ key, tokens }) => {
  1854. if (key === 'other')
  1855. needOther = false;
  1856. const s = tokens.map(tok => this.token(tok, pluralToken));
  1857. return `${safeIdentifier.property(null, key.replace(/^=/, ''))}: ${this.concatenate(s, false)}`;
  1858. });
  1859. if (needOther) {
  1860. const { type } = token;
  1861. const { cardinals, ordinals } = this.plural;
  1862. if (type === 'select' ||
  1863. (type === 'plural' && cardinals.includes('other')) ||
  1864. (type === 'selectordinal' && ordinals.includes('other')))
  1865. throw new Error(`No 'other' form found in ${JSON.stringify(token)}`);
  1866. }
  1867. return `{ ${r.join(', ')} }`;
  1868. }
  1869. concatenate(tokens, root) {
  1870. const asValues = this.options.returnType === 'values';
  1871. return asValues && (root || tokens.length > 1)
  1872. ? '[' + tokens.join(', ') + ']'
  1873. : tokens.join(' + ') || '""';
  1874. }
  1875. token(token, pluralToken) {
  1876. if (token.type === 'content')
  1877. return JSON.stringify(token.value);
  1878. const { id, lc } = this.plural;
  1879. let args, fn;
  1880. if ('arg' in token) {
  1881. this.arguments.push(token.arg);
  1882. args = [safeIdentifier.property('d', token.arg)];
  1883. }
  1884. else
  1885. args = [];
  1886. switch (token.type) {
  1887. case 'argument':
  1888. return this.options.biDiSupport
  1889. ? biDiMarkText(String(args[0]), lc)
  1890. : String(args[0]);
  1891. case 'select':
  1892. fn = 'select';
  1893. if (pluralToken && this.options.strict)
  1894. pluralToken = null;
  1895. args.push(this.cases(token, pluralToken));
  1896. this.setRuntimeFn('select');
  1897. break;
  1898. case 'selectordinal':
  1899. fn = 'plural';
  1900. args.push(token.pluralOffset || 0, id, this.cases(token, token), 1);
  1901. this.setLocale(id, true);
  1902. this.setRuntimeFn('plural');
  1903. break;
  1904. case 'plural':
  1905. fn = 'plural';
  1906. args.push(token.pluralOffset || 0, id, this.cases(token, token));
  1907. this.setLocale(id, false);
  1908. this.setRuntimeFn('plural');
  1909. break;
  1910. case 'function':
  1911. if (!this.options.customFormatters[token.key]) {
  1912. if (token.key === 'date') {
  1913. fn = this.setDateFormatter(token, args, pluralToken);
  1914. break;
  1915. }
  1916. else if (token.key === 'number') {
  1917. fn = this.setNumberFormatter(token, args, pluralToken);
  1918. break;
  1919. }
  1920. }
  1921. args.push(JSON.stringify(this.plural.locale));
  1922. if (token.param) {
  1923. if (pluralToken && this.options.strict)
  1924. pluralToken = null;
  1925. const arg = this.getFormatterArg(token, pluralToken);
  1926. if (arg)
  1927. args.push(arg);
  1928. }
  1929. fn = token.key;
  1930. this.setFormatter(fn);
  1931. break;
  1932. case 'octothorpe':
  1933. if (!pluralToken)
  1934. return '"#"';
  1935. args = [
  1936. JSON.stringify(this.plural.locale),
  1937. safeIdentifier.property('d', pluralToken.arg),
  1938. pluralToken.pluralOffset || 0
  1939. ];
  1940. if (this.options.strict) {
  1941. fn = 'strictNumber';
  1942. args.push(JSON.stringify(pluralToken.arg));
  1943. this.setRuntimeFn('strictNumber');
  1944. }
  1945. else {
  1946. fn = 'number';
  1947. this.setRuntimeFn('number');
  1948. }
  1949. break;
  1950. }
  1951. if (!fn)
  1952. throw new Error('Parser error for token ' + JSON.stringify(token));
  1953. return `${fn}(${args.join(', ')})`;
  1954. }
  1955. runtimeIncludes(key, type) {
  1956. if (safeIdentifier.identifier(key) !== key)
  1957. throw new SyntaxError(`Reserved word used as ${type} identifier: ${key}`);
  1958. const prev = this.runtime[key];
  1959. if (!prev || prev.type === type)
  1960. return prev;
  1961. throw new TypeError(`Cannot override ${prev.type} runtime function as ${type}: ${key}`);
  1962. }
  1963. setLocale(key, ord) {
  1964. const prev = this.runtimeIncludes(key, 'locale');
  1965. const { getCardinal, getPlural, isDefault } = this.plural;
  1966. let pf, module, toString;
  1967. if (!ord && isDefault && getCardinal) {
  1968. if (prev)
  1969. return;
  1970. pf = (n) => getCardinal(n);
  1971. module = CARDINAL_MODULE;
  1972. toString = () => String(getCardinal);
  1973. }
  1974. else {
  1975. if (prev && (!isDefault || prev.module === PLURAL_MODULE))
  1976. return;
  1977. pf = (n, ord) => getPlural(n, ord);
  1978. module = isDefault ? PLURAL_MODULE : getPlural.module || null;
  1979. toString = () => String(getPlural);
  1980. }
  1981. this.runtime[key] = Object.assign(pf, {
  1982. id: key,
  1983. module,
  1984. toString,
  1985. type: 'locale'
  1986. });
  1987. }
  1988. setRuntimeFn(key) {
  1989. if (this.runtimeIncludes(key, 'runtime'))
  1990. return;
  1991. this.runtime[key] = Object.assign(Runtime__namespace[key], {
  1992. id: key,
  1993. module: RUNTIME_MODULE,
  1994. type: 'runtime'
  1995. });
  1996. }
  1997. getFormatterArg({ key, param }, pluralToken) {
  1998. const fmt = this.options.customFormatters[key] ||
  1999. (isFormatterKey(key) && Formatters__namespace[key]);
  2000. if (!fmt || !param)
  2001. return null;
  2002. const argShape = ('arg' in fmt && fmt.arg) || 'string';
  2003. if (argShape === 'options') {
  2004. let value = '';
  2005. for (const tok of param) {
  2006. if (tok.type === 'content')
  2007. value += tok.value;
  2008. else
  2009. throw new SyntaxError(`Expected literal options for ${key} formatter`);
  2010. }
  2011. const options = {};
  2012. for (const pair of value.split(',')) {
  2013. const keyEnd = pair.indexOf(':');
  2014. if (keyEnd === -1)
  2015. options[pair.trim()] = null;
  2016. else {
  2017. const k = pair.substring(0, keyEnd).trim();
  2018. const v = pair.substring(keyEnd + 1).trim();
  2019. if (v === 'true')
  2020. options[k] = true;
  2021. else if (v === 'false')
  2022. options[k] = false;
  2023. else if (v === 'null')
  2024. options[k] = null;
  2025. else {
  2026. const n = Number(v);
  2027. options[k] = Number.isFinite(n) ? n : v;
  2028. }
  2029. }
  2030. }
  2031. return JSON.stringify(options);
  2032. }
  2033. else {
  2034. const parts = param.map(tok => this.token(tok, pluralToken));
  2035. if (argShape === 'raw')
  2036. return `[${parts.join(', ')}]`;
  2037. const s = parts.join(' + ');
  2038. return s ? `(${s}).trim()` : '""';
  2039. }
  2040. }
  2041. setFormatter(key) {
  2042. if (this.runtimeIncludes(key, 'formatter'))
  2043. return;
  2044. let cf = this.options.customFormatters[key];
  2045. if (cf) {
  2046. if (typeof cf === 'function')
  2047. cf = { formatter: cf };
  2048. this.runtime[key] = Object.assign(cf.formatter, { type: 'formatter' }, 'module' in cf && cf.module && cf.id
  2049. ? { id: safeIdentifier.identifier(cf.id), module: cf.module }
  2050. : { id: null, module: null });
  2051. }
  2052. else if (isFormatterKey(key)) {
  2053. this.runtime[key] = Object.assign(Formatters__namespace[key], { type: 'formatter' }, { id: key, module: FORMATTER_MODULE });
  2054. }
  2055. else {
  2056. throw new Error(`Formatting function not found: ${key}`);
  2057. }
  2058. }
  2059. setDateFormatter({ param }, args, plural) {
  2060. const { locale } = this.plural;
  2061. const argStyle = param && param.length === 1 && param[0];
  2062. if (argStyle &&
  2063. argStyle.type === 'content' &&
  2064. /^\s*::/.test(argStyle.value)) {
  2065. const argSkeletonText = argStyle.value.trim().substr(2);
  2066. const key = safeIdentifier.identifier(`date_${locale}_${argSkeletonText}`, true);
  2067. if (!this.runtimeIncludes(key, 'formatter')) {
  2068. const fmt = getDateFormatter(locale, argSkeletonText);
  2069. this.runtime[key] = Object.assign(fmt, {
  2070. id: key,
  2071. module: null,
  2072. toString: () => getDateFormatterSource(locale, argSkeletonText),
  2073. type: 'formatter'
  2074. });
  2075. }
  2076. return key;
  2077. }
  2078. args.push(JSON.stringify(locale));
  2079. if (param && param.length > 0) {
  2080. if (plural && this.options.strict)
  2081. plural = null;
  2082. const s = param.map(tok => this.token(tok, plural));
  2083. args.push('(' + (s.join(' + ') || '""') + ').trim()');
  2084. }
  2085. this.setFormatter('date');
  2086. return 'date';
  2087. }
  2088. setNumberFormatter({ param }, args, plural) {
  2089. const { locale } = this.plural;
  2090. if (!param || param.length === 0) {
  2091. args.unshift(JSON.stringify(locale));
  2092. args.push('0');
  2093. this.setRuntimeFn('number');
  2094. return 'number';
  2095. }
  2096. args.push(JSON.stringify(locale));
  2097. if (param.length === 1 && param[0].type === 'content') {
  2098. const fmtArg = param[0].value.trim();
  2099. switch (fmtArg) {
  2100. case 'currency':
  2101. args.push(JSON.stringify(this.options.currency));
  2102. this.setFormatter('numberCurrency');
  2103. return 'numberCurrency';
  2104. case 'integer':
  2105. this.setFormatter('numberInteger');
  2106. return 'numberInteger';
  2107. case 'percent':
  2108. this.setFormatter('numberPercent');
  2109. return 'numberPercent';
  2110. }
  2111. const cm = fmtArg.match(/^currency:([A-Z]+)$/);
  2112. if (cm) {
  2113. args.push(JSON.stringify(cm[1]));
  2114. this.setFormatter('numberCurrency');
  2115. return 'numberCurrency';
  2116. }
  2117. const key = safeIdentifier.identifier(`number_${locale}_${fmtArg}`, true);
  2118. if (!this.runtimeIncludes(key, 'formatter')) {
  2119. const { currency } = this.options;
  2120. const fmt = getNumberFormatter(locale, fmtArg, currency);
  2121. this.runtime[key] = Object.assign(fmt, {
  2122. id: null,
  2123. module: null,
  2124. toString: () => getNumberFormatterSource(locale, fmtArg, currency),
  2125. type: 'formatter'
  2126. });
  2127. }
  2128. return key;
  2129. }
  2130. if (plural && this.options.strict)
  2131. plural = null;
  2132. const s = param.map(tok => this.token(tok, plural));
  2133. args.push('(' + (s.join(' + ') || '""') + ').trim()');
  2134. args.push(JSON.stringify(this.options.currency));
  2135. this.setFormatter('numberFmt');
  2136. return 'numberFmt';
  2137. }
  2138. }
  2139. function isFormatterKey(key) {
  2140. return key in Formatters__namespace;
  2141. }
  2142. module.exports = Compiler;