compile-module.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. var safeIdentifier = require('safe-identifier');
  3. var Compiler = require('./compiler');
  4. function stringifyRuntime(runtime) {
  5. const imports = {};
  6. const vars = {};
  7. for (const [name, fn] of Object.entries(runtime)) {
  8. if (fn.module) {
  9. const alias = fn.id && fn.id !== name ? `${fn.id} as ${name}` : name;
  10. const prev = imports[fn.module];
  11. imports[fn.module] = prev ? [...prev, alias] : [alias];
  12. }
  13. else {
  14. vars[name] = String(fn);
  15. }
  16. }
  17. const is = Object.entries(imports).map(([module, names]) => `import { ${names.sort().join(', ')} } from ${JSON.stringify(module)};`);
  18. const vs = Object.entries(vars).map(([id, value]) => new RegExp(`^function ${id}\\b`).test(value)
  19. ? value
  20. : `const ${id} = ${value};`);
  21. if (is.length > 0 && vs.length > 0)
  22. is.push('');
  23. return is.concat(vs).join('\n');
  24. }
  25. function stringifyObject(obj, level = 0) {
  26. if (typeof obj !== 'object')
  27. return obj;
  28. const indent = ' '.repeat(level);
  29. const o = Object.keys(obj).map(key => {
  30. const v = stringifyObject(obj[key], level + 1);
  31. return `\n${indent} ${safeIdentifier.property(null, key)}: ${v}`;
  32. });
  33. return `{${o.join(',')}\n${indent}}`;
  34. }
  35. function compileModule(messageformat, messages) {
  36. const { plurals } = messageformat;
  37. const cp = {};
  38. if (plurals.length > 1)
  39. for (const pl of plurals)
  40. cp[pl.lc] = cp[pl.locale] = pl;
  41. const compiler = new Compiler(messageformat.options);
  42. const msgObj = compiler.compile(messages, plurals[0], cp);
  43. const msgStr = stringifyObject(msgObj);
  44. const rtStr = stringifyRuntime(compiler.runtime);
  45. return `${rtStr}\nexport default ${msgStr}`;
  46. }
  47. module.exports = compileModule;