Prepare i18n, load translations from plugins and book

@param {Output}
@return {Promise<Output>}
518636
function prepareI18n(output) {
    var state = output.getState();
    var i18n = state.getI18n();
    var searchPaths = listSearchPaths(output);

    searchPaths
        .reverse()
        .forEach(function(searchPath) {
            var i18nRoot = path.resolve(searchPath, '_i18n');

            if (!fs.existsSync(i18nRoot)) return;
            i18n.load(i18nRoot);
        });

    return Promise(output);
}
507973
function generatePage(output, page) {
    var book = output.getBook();
    var engine = createTemplateEngine(output);

    return timing.measure(
        'page.generate',
        Promise(page)
        .then(function(resultPage) {
            var file = resultPage.getFile();
            var filePath = file.getPath();
            var parser = file.getParser();
            var context = JSONUtils.encodeOutputWithPage(output, resultPage);

            if (!parser) {
                return Promise.reject(error.FileNotParsableError({
                    filename: filePath
                }));
            }

            // Call hook "page:before"
            return callPageHook('page:before', output, resultPage)

            // Escape code blocks with raw tags
            .then(function(currentPage) {
                return parser.preparePage(currentPage.getContent());
            })

            // Render templating syntax
            .then(function(content) {
                var absoluteFilePath = path.join(book.getContentRoot(), filePath);
                return Templating.render(engine, absoluteFilePath, content, context);
            })

            .then(function(output) {
                var content = output.getContent();

                return parser.parsePage(content)
                .then(function(result) {
                    return output.setContent(result.content);
                });
            })

            // Post processing for templating syntax
            .then(function(output) {
                return Templating.postRender(engine, output);
            })

            // Return new page
            .then(function(content) {
                return resultPage.set('content', content);
            })

            // Call final hook
            .then(function(currentPage) {
                return callPageHook('page', output, currentPage);
            });
        })
    );
}
182034
function(onProgress) {
        const errorHandler = function(err) {
            if(err instanceof Error) {
                return Promise.reject(err);
            } else {
                return Promise.resolve();
            }
        };

        // TRICKY: the language catalogs are dependent so we must run them in order
        return updateCatalog('langnames', onProgress)
            .catch(errorHandler)
            .then(function(response) {
                return updateCatalog('temp-langnames', onProgress);
            })
            .catch(errorHandler)
            .then(function(response) {
                return updateCatalog('approved-temp-langnames', onProgress);
            })
            .catch(errorHandler)
            .then(function(response) {
                return updateCatalog('new-language-questions', onProgress)
            })
            .catch(errorHandler)
            .then(function() {
                return Promise.resolve();
            });
    }
903191
def i18n(ctx, update=False):
    ''''''
    header('')

    info('Extract Python strings')
    lrun('python setup.py extract_messages')

    # Fix crowdin requiring Language with `2-digit` iso code in potfile
    # to produce 2-digit iso code pofile
    # Opening the catalog also allows to set extra metadata
    potfile = join(ROOT, 'udata', 'translations', '{}.pot'.format(I18N_DOMAIN))
    with open(potfile, 'rb') as infile:
        catalog = read_po(infile, 'en')
    catalog.copyright_holder = 'Open Data Team'
    catalog.msgid_bugs_address = 'i18n@opendata.team'
    catalog.language_team = 'Open Data Team <i18n@opendata.team>'
    catalog.last_translator = 'Open Data Team <i18n@opendata.team>'
    catalog.revision_date = datetime.now(LOCALTZ)
    with open(potfile, 'wb') as outfile:
        write_po(outfile, catalog, width=80)

    if update:
        lrun('python setup.py update_catalog')

    info('Extract JavaScript strings')
    keys = set()
    catalog = {}
    catalog_filename = join(ROOT, 'js', 'locales',
                            '{}.en.json'.format(I18N_DOMAIN))
    if exists(catalog_filename):
        with codecs.open(catalog_filename, encoding='utf8') as f:
            catalog = json.load(f)

    globs = '*.js', '*.vue', '*.hbs'
    regexps = [
        re.compile(r'(?:|\.|\s|\{)_\(\s*(?:"|\')(.*?)(?:"|\')\s*(?:\)|,)'),  # JS _('trad')
        re.compile(r'v-i18n="(.*?)"'),  # Vue.js directive v-i18n="trad"
        re.compile(r'"\{\{\{?\s*\'(.*?)\'\s*\|\s*i18n\}\}\}?"'),  # Vue.js filter {{ 'trad'|i18n }}
        re.compile(r'{{_\s*"(.*?)"\s*}}'),  # Handlebars {{_ "trad" }}
        re.compile(r'{{_\s*\'(.*?)\'\s*}}'),  # Handlebars {{_ 'trad' }}
        re.compile(r'\:[a-z0-9_\-]+="\s*_\(\'(.*?)\'\)\s*"'),  # Vue.js binding :prop="_('trad')"
    ]

    for directory, _, _ in os.walk(join(ROOT, 'js')):
        glob_patterns = (iglob(join(directory, g)) for g in globs)
        for filename in itertools.chain(*glob_patterns):
            print('Extracting messages from {0}'.format(green(filename)))
            content = codecs.open(filename, encoding='utf8').read()
            for regexp in regexps:
                for match in regexp.finditer(content):
                    key = match.group(1)
                    key = key.replace('\\n', '\n')
                    keys.add(key)
                    if key not in catalog:
                        catalog[key] = key

    # Remove old/not found translations
    for key in catalog.keys():
        if key not in keys:
            del catalog[key]

    with codecs.open(catalog_filename, 'w', encoding='utf8') as f:
        json.dump(catalog, f, sort_keys=True, indent=4, ensure_ascii=False,
                  encoding='utf8', separators=(',', ': '))
109483
function translate(id, filename, buffer, options, next) {
	var ext = (filename.match(extexp) || [])[1] || '',
		encoding = options.encoding || exports.defaults.encoding,
		trans = options.translate, js, nowrap;

	// make a list of what not to wrap
	nowrap = options.nowrap || exports.defaults.nowrap;
	nowrap = [ 'define', 'define.min', 'define.shim' ].concat(nowrap);
	// should this code get wrapped with a define?
	nowrap = nowrap.some(function(no) {
		return no.test ? no.test(id) : (no === id);
	});

	// convert commonjs to amd
	function wrap(err, js) {
		if (err) { return next(err); }

		var deps = exports.dependencies(id, js), params = [], undef = '';

		// make sure require, exports, and module are properly passed into the factory
		if (/\brequire\b/.test(js)) { params.push('require'); }
		if (/\bexports\b/.test(js)) { params.push('exports'); }
		if (/\bmodule\b/.test(js)) { params.push('module'); }

		// make sure code follows the `exports` path instead of `define` path once wrapped
		if (/\bdefine\.amd\b/.test(js)) { undef = 'var define;'; }

		if (deps.length) {
			deps = ',' + JSON.stringify(params.concat(deps));
		} else if (params.length) {
			params = [ 'require', 'exports', 'module' ];
		}

		js = 'define(' + JSON.stringify(id) + deps + ',function(' + params + ')' +
				'{' + js + '\n' + undef + '}' + // rely on hoisting for define
			');\n';
		next(null, js);
	}

	// find the translate function
	trans = trans && (trans[filename] || trans[id] || trans[ext]);
	if (trans) { // user configured translation
		return trans(
			{ id:id, filename:filename, buffer:buffer },
			options, (nowrap ? next : wrap)
		);
	}

	js = buffer.toString(encoding);

	// handle javascript files
	if ('js' === ext) {
		return (nowrap ? next : wrap)(null, js);
	}

	// handle non-javascript files
	if ('json' !== ext) { js = JSON.stringify(js); } // export file as json string
	if (nowrap) { return next(null, 'return ' + js); }
	return next(null, 'define(' + JSON.stringify(id) + ',' + js + ');\n');
}
1157887
function (language, filename, async) {
  //Enable async
  async = async || false;
  //Try get language file
  try {
    //Define language path
    var languagePath = path.join(config.path, language, filename);
    var exists = fs.existsSync(languagePath);
    if (exists) {
      if (async) {
        //Return Json Data
        fs.readFile(languagePath, 'utf-8', function (err, data) {
          if (err) {throw err;}
          config.data = JSON.parse(data);
          emitter.emit('livi18n/loaded');
        });
      } else {
        //Return Json Data
        return JSON.parse(fs.readFileSync(languagePath, 'utf-8'));
      }
    } else {
      console.error(_name + ': Could not find the language file in ' + languagePath);
    }
  } catch (e) {
    console.error(_name + ': Could not find the language file in ' + languagePath);
  }
}
1076968
function(file) {
        var self = this;

        return new Promise(function(resolve) {
            fs.readFileAsync(file, 'utf-8')
                .then(function(content) {
                    return self._parseFile(file, content);
                })
                .then(function(ast) {
                    return self._getConfig(file, ast);
                })
                .then(function(config) {
                    self._modules = self._modules.concat(config);

                    resolve(config);
                });
        });
    }
743652
function (request, response) {
      var locale = request.params.locale;
      var phrase = request.params.phrase;

      var result;
      if (request.query.plural) {
        var singular = phrase;
        var plural = request.query.plural;
        // Make sure the information is added to the catalog if it doesn't exist yet.
        var translated = vulpejs.i18n.__n({
          singular: singular,
          plural: plural,
          count: request.query.count,
          locale: locale,
        });
        // Retrieve the translation object from the catalog and return it.
        var catalog = vulpejs.i18n.getCatalog(locale);
        result = singular.split(configuration.objectNotation).reduce(function (object, index) {
          return object[index];
        }, catalog);
      } else {
        result = vulpejs.i18n.__({
          phrase: phrase,
          locale: locale,
        });
      }
      response.send(result);
    }
69821
function buildScripts() {
  return Promise.resolve()
    // Create the dist folder if it doesn't exist
    .then(() => {
      if(!FS.existsSync(Path.join(__dirname, 'dist'))) {
        return FS.mkdirAsync(Path.join(__dirname, 'dist'));
      }
    })

    // Generate minified scripts
    .then(() => new Promise((resolve, reject) => {
      let scripts = {
        'dropdowns.js': FS.readFileSync(Path.join(__dirname, 'source/js/dropdowns.js'), 'utf8'),
        'tabs.js': FS.readFileSync(Path.join(__dirname, 'source/js/tabs.js'), 'utf8')
      };

      let result = UglifyJS.minify(scripts, {
        output: {
          comments: /^!/
        }
      });
      if(result.error) {
        reject(result.error);
        return;
      }

      resolve(result.code);
    }))

    // Write minified scripts to dist
    .then((scripts) => {
      let file = Path.join(__dirname, 'dist/shoelace.js');

      // Update {{version}} in JS since it's not processed with Handlebars
      scripts = scripts.replace(/\{\{version\}\}/g, __version);

      // Output a message
      console.log(Chalk.green('JS processed: %s! 🐭'), Path.relative(__dirname, file));

      // Write output file
      return FS.writeFileAsync(file, scripts, 'utf8');
    });
}
240187
function prepareParams(msg, config) {
    var params = {},
      inputlang = config.inputlang ? config.inputlang : 'en',
      outputlang = config.outputlang ? config.outputlang : 'en';

    if (msg.piparams) {
      if (msg.piparams.inputlanguage &&
            -1 < VALID_INPUT_LANGUAGES.indexOf(msg.piparams.inputlanguage)) {
        inputlang = msg.piparams.inputlanguage;
      }
      if (msg.piparams.responselanguage &&
            -1 < VALID_RESPONSE_LANGUAGES.indexOf(msg.piparams.responselanguage)) {
        outputlang = msg.piparams.responselanguage;
      }
    }

    params = {
      content: msg.payload,
      consumption_preferences: config.consumption ? config.consumption : false,
      raw_scores: config.rawscores ? config.rawscores : false,
      headers: {
        'content-language': inputlang,
        'accept-language': outputlang,
        'accept': 'application/json'
      }
    };

    if ('string' === typeof msg.payload) {
      params.content_type = 'text/plain';
    } else {
      params.content_type = 'application/json';
    }

    return Promise.resolve(params);
  }
220849
function runEbookConvert(output) {
    var logger = output.getLogger();
    var options = output.getOptions();
    var format = options.get('format');
    var outputFolder = output.getRoot();

    if (!format) {
        return Promise(output);
    }

    return getConvertOptions(output)
    .then(function(options) {
        var cmd = [
            'ebook-convert',
            path.resolve(outputFolder, SUMMARY_FILE),
            path.resolve(outputFolder, 'index.' + format),
            command.optionsToShellArgs(options)
        ].join(' ');

        return command.exec(cmd)
        .progress(function(data) {
            logger.debug(data);
        })
        .fail(function(err) {
            if (err.code == 127) {
                throw error.RequireInstallError({
                    cmd: 'ebook-convert',
                    install: 'Install it from Calibre: https://calibre-ebook.com'
                });
            }

            throw error.EbookError(err);
        });
    })
    .thenResolve(output);
}
1166944
function Locales() {

    var _require = function(path) {
        var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
        if (cacheless) {
            try {
                delete require.cache[require.resolve(path)];
                return require(path)
            } catch (err) {
                throw err
            }

        } else {
            return require(path)
        }
    }

    /**
     * init
     *
     * return {array} regions collection
     * */
    var init  = function () {

        var dir         = __dirname + '/dist/region' // regions by language
            , files     = fs.readdirSync(dir)
            , i         = 0
            , key       = null
            , regions   = []
        ;

        for (var f = 0, len = files.length; f < len; ++f) {
            if ( ! /^\./.test(files[f]) || f == len-1 ) {
                key         = files[f].split(/\./)[0];
                regions[i]  = { lang: key, content: _require( dir + '/' + files[f] ) }
            }
        }


        return regions
    }
    

    return init()
}
288890
function loadLang() {
  var locale = getParam( 'lang' );
  pageInfo["layout"] = getParam( 'layout' );
  if ( locale == '' ) { locale = "EN"; }

  $.i18n( { locale: locale } );

  var langMap = 'i18n/'+locale+'.json';
    if( mode == "php"  &&  pageInfo["layout"] != '' ) {
      langMap = "svc/backend/i18n?locale="+locale+'&layout='+pageInfo["layout"];
      $.getJSON( langMap, 
          function( langMapDta ) {
            $.i18n().load( 
                langMapDta, 
                locale 
              ).done( 
                function(){ ajaxOngoing--; } 
              );
          }
      );
    } else {
      // do it static
      $.i18n().load( 
          langMap, 
          locale 
        ).done( 
          function(){ ajaxOngoing--; } 
        );      
    }

    $.extend( $.i18n.parser.emitter, {
      // Handle PONGVER keywords
      pongver: function () {
        //alert( "version" )
        return PONGVER;
      }
    } );

    /* hook vor init call back to define other i18n extends */
    if (typeof initI18n === "function") { 
        // safe to use the function
      initI18n();
    }
    
  pageInfo["lang"] = locale;
}
1278968
function Page() {
  const { t, i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  return (
    <div className="App">
      <div className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Welcome />
      </div>
      <div className="App-intro">
        <div>
          <button onClick={() => changeLanguage('de')}>de</button>
          <button onClick={() => changeLanguage('en')}>en</button>
        </div>
        <MyComponent />
      </div>
      <div>{t('description.part2')}</div>
    </div>
  );
}
714842
function(input, source) {
  var output = input.toString();

  if (source.path.match(/\.js$/)) {
    output = output.replace(/(["'](do not )?use strict[\"\'];)/,
        'define(function(require, exports, module) {\n\n$1');
    output += '\n\n});\n';
  }

  return output;
}
42463
function generateBundle(locale, messages, reactElements, options) {
  var builtContent;
  var onBuildWrite = options.onBuildWrite || defaultOnBuildWrite;
  options = options || {};

  init();

  assertLocale(locale);
  assertMessages(messages);
  assertReactElements(reactElements);

  // Load i18n content.
  loadCldr(locale);
  loadMessages(messages);

  // Set locale.
  Globalize.locale(locale);

  // Have react to render all passed components, therefore the formatters in
  // use will be created in Globalize.cache.
  _reactElements(reactElements).forEach(function(reactElement) {
    React.renderToString(reactElement);
   });

  // Compile all generated formatters.
  builtContent = GlobalizeCompiler(Globalize.cache);

  // Cleanup.
  Globalize.cache = {};

  return onBuildWrite(locale, builtContent);
}
757604
function decodeGlobal(output, result) {
    var book = output.getBook();
    var config = book.getConfig();

    // Update config
    config = decodeConfig(config, result.config);
    book = book.set('config', config);

    return output.set('book', book);
}