Best JavaScript code snippet using devicefarmer-stf
i18n.js
Source:i18n.js
1define(["./_base/kernel", "require", "./has", "./_base/array", "./_base/config", "./_base/lang", "./has!host-browser?./_base/xhr", "./json", "module"],2 function(dojo, require, has, array, config, lang, xhr, json, module){3 // module:4 // dojo/i18n5 has.add("dojo-preload-i18n-Api",6 // if true, define the preload localizations machinery7 18 );9 has.add("dojo-v1x-i18n-Api",10 // if true, define the v1.x i18n functions11 112 );13 var14 thisModule = dojo.i18n =15 {16 // summary:17 // This module implements the dojo/i18n! plugin and the v1.6- i18n API18 // description:19 // We choose to include our own plugin to leverage functionality already contained in dojo20 // and thereby reduce the size of the plugin compared to various loader implementations. Also, this21 // allows foreign AMD loaders to be used without their plugins.22 },23 nlsRe =24 // regexp for reconstructing the master bundle name from parts of the regexp match25 // nlsRe.exec("foo/bar/baz/nls/en-ca/foo") gives:26 // ["foo/bar/baz/nls/en-ca/foo", "foo/bar/baz/nls/", "/", "/", "en-ca", "foo"]27 // nlsRe.exec("foo/bar/baz/nls/foo") gives:28 // ["foo/bar/baz/nls/foo", "foo/bar/baz/nls/", "/", "/", "foo", ""]29 // so, if match[5] is blank, it means this is the top bundle definition.30 // courtesy of http://requirejs.org31 /(^.*(^|\/)nls)(\/|$)([^\/]*)\/?([^\/]*)/,32 getAvailableLocales = function(33 root,34 locale,35 bundlePath,36 bundleName37 ){38 // summary:39 // return a vector of module ids containing all available locales with respect to the target locale40 // For example, assuming:41 //42 // - the root bundle indicates specific bundles for "fr" and "fr-ca",43 // - bundlePath is "myPackage/nls"44 // - bundleName is "myBundle"45 //46 // Then a locale argument of "fr-ca" would return47 //48 // ["myPackage/nls/myBundle", "myPackage/nls/fr/myBundle", "myPackage/nls/fr-ca/myBundle"]49 //50 // Notice that bundles are returned least-specific to most-specific, starting with the root.51 //52 // If root===false indicates we're working with a pre-AMD i18n bundle that doesn't tell about the available locales;53 // therefore, assume everything is available and get 404 errors that indicate a particular localization is not available54 for(var result = [bundlePath + bundleName], localeParts = locale.split("-"), current = "", i = 0; i<localeParts.length; i++){55 current += (current ? "-" : "") + localeParts[i];56 if(!root || root[current]){57 result.push(bundlePath + current + "/" + bundleName);58 result.specificity = current;59 }60 }61 return result;62 },63 cache = {},64 getBundleName = function(moduleName, bundleName, locale){65 locale = locale ? locale.toLowerCase() : dojo.locale;66 moduleName = moduleName.replace(/\./g, "/");67 bundleName = bundleName.replace(/\./g, "/");68 return (/root/i.test(locale)) ?69 (moduleName + "/nls/" + bundleName) :70 (moduleName + "/nls/" + locale + "/" + bundleName);71 },72 getL10nName = dojo.getL10nName = function(moduleName, bundleName, locale){73 return moduleName = module.id + "!" + getBundleName(moduleName, bundleName, locale);74 },75 doLoad = function(require, bundlePathAndName, bundlePath, bundleName, locale, load){76 // summary:77 // get the root bundle which instructs which other bundles are required to construct the localized bundle78 require([bundlePathAndName], function(root){79 var current = lang.clone(root.root || root.ROOT),// 1.6 built bundle defined ROOT80 availableLocales = getAvailableLocales(!root._v1x && root, locale, bundlePath, bundleName);81 require(availableLocales, function(){82 for (var i = 1; i<availableLocales.length; i++){83 current = lang.mixin(lang.clone(current), arguments[i]);84 }85 // target may not have been resolve (e.g., maybe only "fr" exists when "fr-ca" was requested)86 var target = bundlePathAndName + "/" + locale;87 cache[target] = current;88 current.$locale = availableLocales.specificity;89 load();90 });91 });92 },93 normalize = function(id, toAbsMid){94 // summary:95 // id may be relative.96 // preload has form `*preload*<path>/nls/<module>*<flattened locales>` and97 // therefore never looks like a relative98 return /^\./.test(id) ? toAbsMid(id) : id;99 },100 getLocalesToLoad = function(targetLocale){101 var list = config.extraLocale || [];102 list = lang.isArray(list) ? list : [list];103 list.push(targetLocale);104 return list;105 },106 load = function(id, require, load){107 // summary:108 // id is in one of the following formats109 //110 // 1. <path>/nls/<bundle>111 // => load the bundle, localized to config.locale; load all bundles localized to112 // config.extraLocale (if any); return the loaded bundle localized to config.locale.113 //114 // 2. <path>/nls/<locale>/<bundle>115 // => load then return the bundle localized to <locale>116 //117 // 3. *preload*<path>/nls/<module>*<JSON array of available locales>118 // => for config.locale and all config.extraLocale, load all bundles found119 // in the best-matching bundle rollup. A value of 1 is returned, which120 // is meaningless other than to say the plugin is executing the requested121 // preloads122 //123 // In cases 1 and 2, <path> is always normalized to an absolute module id upon entry; see124 // normalize. In case 3, it <path> is assumed to be absolute; this is arranged by the builder.125 //126 // To load a bundle means to insert the bundle into the plugin's cache and publish the bundle127 // value to the loader. Given <path>, <bundle>, and a particular <locale>, the cache key128 //129 // <path>/nls/<bundle>/<locale>130 //131 // will hold the value. Similarly, then plugin will publish this value to the loader by132 //133 // define("<path>/nls/<bundle>/<locale>", <bundle-value>);134 //135 // Given this algorithm, other machinery can provide fast load paths be preplacing136 // values in the plugin's cache, which is public. When a load is demanded the137 // cache is inspected before starting any loading. Explicitly placing values in the plugin138 // cache is an advanced/experimental feature that should not be needed; use at your own risk.139 //140 // For the normal AMD algorithm, the root bundle is loaded first, which instructs the141 // plugin what additional localized bundles are required for a particular locale. These142 // additional locales are loaded and a mix of the root and each progressively-specific143 // locale is returned. For example:144 //145 // 1. The client demands "dojo/i18n!some/path/nls/someBundle146 //147 // 2. The loader demands load(some/path/nls/someBundle)148 //149 // 3. This plugin require's "some/path/nls/someBundle", which is the root bundle.150 //151 // 4. Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations152 // are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin153 // requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"154 //155 // 5. Upon receiving all required bundles, the plugin constructs the value of the bundle156 // ab-cd-ef as...157 //158 // mixin(mixin(mixin({}, require("some/path/nls/someBundle"),159 // require("some/path/nls/ab/someBundle")),160 // require("some/path/nls/ab-cd-ef/someBundle"));161 //162 // This value is inserted into the cache and published to the loader at the163 // key/module-id some/path/nls/someBundle/ab-cd-ef.164 //165 // The special preload signature (case 3) instructs the plugin to stop servicing all normal requests166 // (further preload requests will be serviced) until all ongoing preloading has completed.167 //168 // The preload signature instructs the plugin that a special rollup module is available that contains169 // one or more flattened, localized bundles. The JSON array of available locales indicates which locales170 // are available. Here is an example:171 //172 // *preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]173 //174 // This indicates the following rollup modules are available:175 //176 // some/path/nls/someModule_ROOT177 // some/path/nls/someModule_ab178 // some/path/nls/someModule_ab-cd-ef179 //180 // Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash.181 // For example, assume someModule contained the bundles some/bundle/path/someBundle and182 // some/bundle/path/someOtherBundle, then some/path/nls/someModule_ab would be expressed as follows:183 //184 // define({185 // some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,186 // some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,187 // });188 //189 // E.g., given this design, preloading for locale=="ab" can execute the following algorithm:190 //191 // require(["some/path/nls/someModule_ab"], function(rollup){192 // for(var p in rollup){193 // var id = p + "/ab",194 // cache[id] = rollup[p];195 // define(id, rollup[p]);196 // }197 // });198 //199 // Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and200 // load accordingly.201 //202 // The builder will write such rollups for every layer if a non-empty localeList profile property is203 // provided. Further, the builder will include the following cache entry in the cache associated with204 // any layer.205 //206 // "*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}207 //208 // The *now special cache module instructs the loader to apply the provided function to context-require209 // with respect to the particular layer being defined. This causes the plugin to hold all normal service210 // requests until all preloading is complete.211 //212 // Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case213 // where the target locale has a single segment and a layer depends on a single bundle:214 //215 // Without Preloads:216 //217 // 1. Layer loads root bundle.218 // 2. bundle is demanded; plugin loads single localized bundle.219 //220 // With Preloads:221 //222 // 1. Layer causes preloading of target bundle.223 // 2. bundle is demanded; service is delayed until preloading complete; bundle is returned.224 //225 // In each case a single transaction is required to load the target bundle. In cases where multiple bundles226 // are required and/or the locale has multiple segments, preloads still requires a single transaction whereas227 // the normal path requires an additional transaction for each additional bundle/locale-segment. However all228 // of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading229 // algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.230 var match = nlsRe.exec(id),231 bundlePath = match[1] + "/",232 bundleName = match[5] || match[4],233 bundlePathAndName = bundlePath + bundleName,234 localeSpecified = (match[5] && match[4]),235 targetLocale = localeSpecified || dojo.locale || "",236 loadTarget = bundlePathAndName + "/" + targetLocale,237 loadList = localeSpecified ? [targetLocale] : getLocalesToLoad(targetLocale),238 remaining = loadList.length,239 finish = function(){240 if(!--remaining){241 load(lang.delegate(cache[loadTarget]));242 }243 },244 split = id.split("*"),245 preloadDemand = split[1] == "preload";246 if(has("dojo-preload-i18n-Api")){247 if(preloadDemand){248 if(!cache[id]){249 // use cache[id] to prevent multiple preloads of the same preload; this shouldn't happen, but250 // who knows what over-aggressive human optimizers may attempt251 cache[id] = 1;252 preloadL10n(split[2], json.parse(split[3]), 1, require);253 }254 // don't stall the loader!255 load(1);256 }257 if(preloadDemand || (waitForPreloads(id, require, load) && !cache[loadTarget])){258 return;259 }260 }261 else if (preloadDemand) {262 // If a build is created with nls resources and 'dojo-preload-i18n-Api' has not been set to false,263 // the built file will include a preload in the cache (which looks about like so:)264 // '*now':function(r){r(['dojo/i18n!*preload*dojo/nls/dojo*["ar","ca","cs","da","de","el","en-gb","en-us","es-es","fi-fi","fr-fr","he-il","hu","it-it","ja-jp","ko-kr","nl-nl","nb","pl","pt-br","pt-pt","ru","sk","sl","sv","th","tr","zh-tw","zh-cn","ROOT"]']);}265 // If the consumer of the build sets 'dojo-preload-i18n-Api' to false in the Dojo config, the cached266 // preload will not be parsed and will result in an attempt to call 'require' passing it the unparsed267 // preload, which is not a valid module id.268 // In this case we should skip this request.269 load(1);270 return;271 }272 array.forEach(loadList, function(locale){273 var target = bundlePathAndName + "/" + locale;274 if(has("dojo-preload-i18n-Api")){275 checkForLegacyModules(target);276 }277 if(!cache[target]){278 doLoad(require, bundlePathAndName, bundlePath, bundleName, locale, finish);279 }else{280 finish();281 }282 });283 };284 if(has("dojo-preload-i18n-Api") || has("dojo-v1x-i18n-Api")){285 var normalizeLocale = thisModule.normalizeLocale = function(locale){286 var result = locale ? locale.toLowerCase() : dojo.locale;287 return result == "root" ? "ROOT" : result;288 },289 isXd = function(mid, contextRequire){290 return (has("dojo-sync-loader") && has("dojo-v1x-i18n-Api")) ?291 contextRequire.isXdUrl(require.toUrl(mid + ".js")) :292 true;293 },294 preloading = 0,295 preloadWaitQueue = [],296 preloadL10n = thisModule._preloadLocalizations = function(/*String*/bundlePrefix, /*Array*/localesGenerated, /*boolean?*/ guaranteedAmdFormat, /*function?*/ contextRequire){297 // summary:298 // Load available flattened resource bundles associated with a particular module for dojo/locale and all dojo/config.extraLocale (if any)299 // description:300 // Only called by built layer files. The entire locale hierarchy is loaded. For example,301 // if locale=="ab-cd", then ROOT, "ab", and "ab-cd" are loaded. This is different than v1.6-302 // in that the v1.6- would only load ab-cd...which was *always* flattened.303 //304 // If guaranteedAmdFormat is true, then the module can be loaded with require thereby circumventing the detection algorithm305 // and the extra possible extra transaction.306 // If this function is called from legacy code, then guaranteedAmdFormat and contextRequire will be undefined. Since the function307 // needs a require in order to resolve module ids, fall back to the context-require associated with this dojo/i18n module, which308 // itself may have been mapped.309 contextRequire = contextRequire || require;310 function doRequire(mid, callback){311 if(isXd(mid, contextRequire) || guaranteedAmdFormat){312 contextRequire([mid], callback);313 }else{314 syncRequire([mid], callback, contextRequire);315 }316 }317 function forEachLocale(locale, func){318 // given locale= "ab-cd-ef", calls func on "ab-cd-ef", "ab-cd", "ab", "ROOT"; stops calling the first time func returns truthy319 var parts = locale.split("-");320 while(parts.length){321 if(func(parts.join("-"))){322 return;323 }324 parts.pop();325 }326 func("ROOT");327 }328 function preloadingAddLock(){329 preloading++;330 }331 function preloadingRelLock(){332 --preloading;333 while(!preloading && preloadWaitQueue.length){334 load.apply(null, preloadWaitQueue.shift());335 }336 }337 function cacheId(path, name, loc, require){338 // path is assumed to have a trailing "/"339 return require.toAbsMid(path + name + "/" + loc)340 }341 function preload(locale){342 locale = normalizeLocale(locale);343 forEachLocale(locale, function(loc){344 if(array.indexOf(localesGenerated, loc) >= 0){345 var mid = bundlePrefix.replace(/\./g, "/") + "_" + loc;346 preloadingAddLock();347 doRequire(mid, function(rollup){348 for(var p in rollup){349 var bundle = rollup[p],350 match = p.match(/(.+)\/([^\/]+)$/),351 bundleName, bundlePath;352 353 // If there is no match, the bundle is not a regular bundle from an AMD layer.354 if (!match){continue;}355 bundleName = match[2];356 bundlePath = match[1] + "/";357 // backcompat358 if(!bundle._localized){continue;}359 var localized;360 if(loc === "ROOT"){361 var root = localized = bundle._localized;362 delete bundle._localized;363 root.root = bundle;364 cache[require.toAbsMid(p)] = root;365 }else{366 localized = bundle._localized;367 cache[cacheId(bundlePath, bundleName, loc, require)] = bundle;368 }369 if(loc !== locale){370 // capture some locale variables371 function improveBundle(bundlePath, bundleName, bundle, localized){372 // locale was not flattened and we've fallen back to a less-specific locale that was flattened373 // for example, we had a flattened 'fr', a 'fr-ca' is available for at least this bundle, and374 // locale==='fr-ca'; therefore, we must improve the bundle as retrieved from the rollup by375 // manually loading the fr-ca version of the bundle and mixing this into the already-retrieved 'fr'376 // version of the bundle.377 //378 // Remember, different bundles may have different sets of locales available.379 //380 // we are really falling back on the regular algorithm here, but--hopefully--starting with most381 // of the required bundles already on board as given by the rollup and we need to "manually" load382 // only one locale from a few bundles...or even better...we won't find anything better to load.383 // This algorithm ensures there is nothing better to load even when we can only load a less-specific rollup.384 //385 // note: this feature is only available in async mode386 // inspect the loaded bundle that came from the rollup to see if something better is available387 // for any bundle in a rollup, more-specific available locales are given at localized.388 var requiredBundles = [],389 cacheIds = [];390 forEachLocale(locale, function(loc){391 if(localized[loc]){392 requiredBundles.push(require.toAbsMid(bundlePath + loc + "/" + bundleName));393 cacheIds.push(cacheId(bundlePath, bundleName, loc, require));394 }395 });396 if(requiredBundles.length){397 preloadingAddLock();398 contextRequire(requiredBundles, function(){399 // requiredBundles was constructed by forEachLocale so it contains locales from 400 // less specific to most specific. 401 // the loop starts with the most specific locale, the last one.402 for(var i = requiredBundles.length - 1; i >= 0 ; i--){403 bundle = lang.mixin(lang.clone(bundle), arguments[i]);404 cache[cacheIds[i]] = bundle;405 }406 // this is the best possible (maybe a perfect match, maybe not), accept it407 cache[cacheId(bundlePath, bundleName, locale, require)] = lang.clone(bundle);408 preloadingRelLock();409 });410 }else{411 // this is the best possible (definitely not a perfect match), accept it412 cache[cacheId(bundlePath, bundleName, locale, require)] = bundle;413 }414 }415 improveBundle(bundlePath, bundleName, bundle, localized);416 }417 }418 preloadingRelLock();419 });420 return true;421 }422 return false;423 });424 }425 preload();426 array.forEach(dojo.config.extraLocale, preload);427 },428 waitForPreloads = function(id, require, load){429 if(preloading){430 preloadWaitQueue.push([id, require, load]);431 }432 return preloading;433 },434 checkForLegacyModules = function()435 {};436 }437 if(has("dojo-v1x-i18n-Api")){438 // this code path assumes the dojo loader and won't work with a standard AMD loader439 var amdValue = {},440 evalBundle,441 syncRequire = function(deps, callback, require){442 var results = [];443 array.forEach(deps, function(mid){444 var url = require.toUrl(mid + ".js");445 function load(text){446 if (!evalBundle) {447 // use the function ctor to keep the minifiers away (also come close to global scope, but this is secondary)448 evalBundle = new Function(449 "__bundle", // the bundle to evalutate450 "__checkForLegacyModules", // a function that checks if __bundle defined __mid in the global space451 "__mid", // the mid that __bundle is intended to define452 "__amdValue",453 // returns one of:454 // 1 => the bundle was an AMD bundle455 // a legacy bundle object that is the value of __mid456 // instance of Error => could not figure out how to evaluate bundle457 // used to detect when __bundle calls define458 "var define = function(mid, factory){define.called = 1; __amdValue.result = factory || mid;},"459 + " require = function(){define.called = 1;};"460 + "try{"461 + "define.called = 0;"462 + "eval(__bundle);"463 + "if(define.called==1)"464 // bundle called define; therefore signal it's an AMD bundle465 + "return __amdValue;"466 + "if((__checkForLegacyModules = __checkForLegacyModules(__mid)))"467 // bundle was probably a v1.6- built NLS flattened NLS bundle that defined __mid in the global space468 + "return __checkForLegacyModules;"469 + "}catch(e){}"470 // evaulating the bundle was *neither* an AMD *nor* a legacy flattened bundle471 // either way, re-eval *after* surrounding with parentheses472 + "try{"473 + "return eval('('+__bundle+')');"474 + "}catch(e){"475 + "return e;"476 + "}"477 );478 }479 var result = evalBundle(text, checkForLegacyModules, mid, amdValue);480 if(result===amdValue){481 // the bundle was an AMD module; re-inject it through the normal AMD path482 // we gotta do this since it could be an anonymous module and simply evaluating483 // the text here won't provide the loader with the context to know what484 // module is being defined()'d. With browser caching, this should be free; further485 // this entire code path can be circumvented by using the AMD format to begin with486 results.push(cache[url] = amdValue.result);487 }else{488 if(result instanceof Error){489 console.error("failed to evaluate i18n bundle; url=" + url, result);490 result = {};491 }492 // nls/<locale>/<bundle-name> indicates not the root.493 results.push(cache[url] = (/nls\/[^\/]+\/[^\/]+$/.test(url) ? result : {root:result, _v1x:1}));494 }495 }496 if(cache[url]){497 results.push(cache[url]);498 }else{499 var bundle = require.syncLoadNls(mid);500 // need to check for legacy module here because there might be a legacy module for a501 // less specific locale (which was not looked up during the first checkForLegacyModules502 // call in load()).503 // Also need to reverse the locale and the module name in the mid because syncRequire504 // deps parameters uses the AMD style package/nls/locale/module while legacy code uses505 // package/nls/module/locale.506 if(!bundle){507 bundle = checkForLegacyModules(mid.replace(/nls\/([^\/]*)\/([^\/]*)$/, "nls/$2/$1"));508 }509 if(bundle){510 results.push(bundle);511 }else{512 if(!xhr){513 try{514 require.getText(url, true, load);515 }catch(e){516 results.push(cache[url] = {});517 }518 }else{519 xhr.get({520 url:url,521 sync:true,522 load:load,523 error:function(){524 results.push(cache[url] = {});525 }526 });527 }528 }529 }530 });531 callback && callback.apply(null, results);532 };533 checkForLegacyModules = function(target){534 // legacy code may have already loaded [e.g] the raw bundle x/y/z at x.y.z; when true, push into the cache535 for(var result, names = target.split("/"), object = dojo.global[names[0]], i = 1; object && i<names.length-1; object = object[names[i++]]){}536 if(object){537 result = object[names[i]];538 if(!result){539 // fallback for incorrect bundle build of 1.6540 result = object[names[i].replace(/-/g,"_")];541 }542 if(result){543 cache[target] = result;544 }545 }546 return result;547 };548 thisModule.getLocalization = function(moduleName, bundleName, locale){549 var result,550 l10nName = getBundleName(moduleName, bundleName, locale);551 load(552 l10nName,553 // isXd() and syncRequire() need a context-require in order to resolve the mid with respect to a reference module.554 // Since this legacy function does not have the concept of a reference module, resolve with respect to this555 // dojo/i18n module, which, itself may have been mapped.556 (!isXd(l10nName, require) ? function(deps, callback){ syncRequire(deps, callback, require); } : require),557 function(result_){ result = result_; }558 );559 return result;560 };561 }562 return lang.mixin(thisModule, {563 dynamic:true,564 normalize:normalize,565 load:load,566 cache:cache,567 getL10nName: getL10nName568 });...
i18n.js.uncompressed.js
Source:i18n.js.uncompressed.js
1define("dojo/i18n", ["./_base/kernel", "require", "./has", "./_base/array", "./_base/config", "./_base/lang", "./_base/xhr", "./json", "module"],2 function(dojo, require, has, array, config, lang, xhr, json, module){3 // module:4 // dojo/i18n5 has.add("dojo-preload-i18n-Api",6 // if true, define the preload localizations machinery7 18 );9 1 || has.add("dojo-v1x-i18n-Api",10 // if true, define the v1.x i18n functions11 112 );13 var14 thisModule = dojo.i18n =15 {16 // summary:17 // This module implements the dojo/i18n! plugin and the v1.6- i18n API18 // description:19 // We choose to include our own plugin to leverage functionality already contained in dojo20 // and thereby reduce the size of the plugin compared to various loader implementations. Also, this21 // allows foreign AMD loaders to be used without their plugins.22 },23 nlsRe =24 // regexp for reconstructing the master bundle name from parts of the regexp match25 // nlsRe.exec("foo/bar/baz/nls/en-ca/foo") gives:26 // ["foo/bar/baz/nls/en-ca/foo", "foo/bar/baz/nls/", "/", "/", "en-ca", "foo"]27 // nlsRe.exec("foo/bar/baz/nls/foo") gives:28 // ["foo/bar/baz/nls/foo", "foo/bar/baz/nls/", "/", "/", "foo", ""]29 // so, if match[5] is blank, it means this is the top bundle definition.30 // courtesy of http://requirejs.org31 /(^.*(^|\/)nls)(\/|$)([^\/]*)\/?([^\/]*)/,32 getAvailableLocales = function(33 root,34 locale,35 bundlePath,36 bundleName37 ){38 // summary:39 // return a vector of module ids containing all available locales with respect to the target locale40 // For example, assuming:41 //42 // - the root bundle indicates specific bundles for "fr" and "fr-ca",43 // - bundlePath is "myPackage/nls"44 // - bundleName is "myBundle"45 //46 // Then a locale argument of "fr-ca" would return47 //48 // ["myPackage/nls/myBundle", "myPackage/nls/fr/myBundle", "myPackage/nls/fr-ca/myBundle"]49 //50 // Notice that bundles are returned least-specific to most-specific, starting with the root.51 //52 // If root===false indicates we're working with a pre-AMD i18n bundle that doesn't tell about the available locales;53 // therefore, assume everything is available and get 404 errors that indicate a particular localization is not available54 for(var result = [bundlePath + bundleName], localeParts = locale.split("-"), current = "", i = 0; i<localeParts.length; i++){55 current += (current ? "-" : "") + localeParts[i];56 if(!root || root[current]){57 result.push(bundlePath + current + "/" + bundleName);58 result.specificity = current;59 }60 }61 return result;62 },63 cache = {},64 getBundleName = function(moduleName, bundleName, locale){65 locale = locale ? locale.toLowerCase() : dojo.locale;66 moduleName = moduleName.replace(/\./g, "/");67 bundleName = bundleName.replace(/\./g, "/");68 return (/root/i.test(locale)) ?69 (moduleName + "/nls/" + bundleName) :70 (moduleName + "/nls/" + locale + "/" + bundleName);71 },72 getL10nName = dojo.getL10nName = function(moduleName, bundleName, locale){73 return moduleName = module.id + "!" + getBundleName(moduleName, bundleName, locale);74 },75 doLoad = function(require, bundlePathAndName, bundlePath, bundleName, locale, load){76 // summary:77 // get the root bundle which instructs which other bundles are required to construct the localized bundle78 require([bundlePathAndName], function(root){79 var current = lang.clone(root.root || root.ROOT),// 1.6 built bundle defined ROOT80 availableLocales = getAvailableLocales(!root._v1x && root, locale, bundlePath, bundleName);81 require(availableLocales, function(){82 for (var i = 1; i<availableLocales.length; i++){83 current = lang.mixin(lang.clone(current), arguments[i]);84 }85 // target may not have been resolve (e.g., maybe only "fr" exists when "fr-ca" was requested)86 var target = bundlePathAndName + "/" + locale;87 cache[target] = current;88 current.$locale = availableLocales.specificity;89 load();90 });91 });92 },93 normalize = function(id, toAbsMid){94 // summary:95 // id may be relative.96 // preload has form `*preload*<path>/nls/<module>*<flattened locales>` and97 // therefore never looks like a relative98 return /^\./.test(id) ? toAbsMid(id) : id;99 },100 getLocalesToLoad = function(targetLocale){101 var list = config.extraLocale || [];102 list = lang.isArray(list) ? list : [list];103 list.push(targetLocale);104 return list;105 },106 load = function(id, require, load){107 // summary:108 // id is in one of the following formats109 //110 // 1. <path>/nls/<bundle>111 // => load the bundle, localized to config.locale; load all bundles localized to112 // config.extraLocale (if any); return the loaded bundle localized to config.locale.113 //114 // 2. <path>/nls/<locale>/<bundle>115 // => load then return the bundle localized to <locale>116 //117 // 3. *preload*<path>/nls/<module>*<JSON array of available locales>118 // => for config.locale and all config.extraLocale, load all bundles found119 // in the best-matching bundle rollup. A value of 1 is returned, which120 // is meaningless other than to say the plugin is executing the requested121 // preloads122 //123 // In cases 1 and 2, <path> is always normalized to an absolute module id upon entry; see124 // normalize. In case 3, it <path> is assumed to be absolute; this is arranged by the builder.125 //126 // To load a bundle means to insert the bundle into the plugin's cache and publish the bundle127 // value to the loader. Given <path>, <bundle>, and a particular <locale>, the cache key128 //129 // <path>/nls/<bundle>/<locale>130 //131 // will hold the value. Similarly, then plugin will publish this value to the loader by132 //133 // define("<path>/nls/<bundle>/<locale>", <bundle-value>);134 //135 // Given this algorithm, other machinery can provide fast load paths be preplacing136 // values in the plugin's cache, which is public. When a load is demanded the137 // cache is inspected before starting any loading. Explicitly placing values in the plugin138 // cache is an advanced/experimental feature that should not be needed; use at your own risk.139 //140 // For the normal AMD algorithm, the root bundle is loaded first, which instructs the141 // plugin what additional localized bundles are required for a particular locale. These142 // additional locales are loaded and a mix of the root and each progressively-specific143 // locale is returned. For example:144 //145 // 1. The client demands "dojo/i18n!some/path/nls/someBundle146 //147 // 2. The loader demands load(some/path/nls/someBundle)148 //149 // 3. This plugin require's "some/path/nls/someBundle", which is the root bundle.150 //151 // 4. Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations152 // are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin153 // requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"154 //155 // 5. Upon receiving all required bundles, the plugin constructs the value of the bundle156 // ab-cd-ef as...157 //158 // mixin(mixin(mixin({}, require("some/path/nls/someBundle"),159 // require("some/path/nls/ab/someBundle")),160 // require("some/path/nls/ab-cd-ef/someBundle"));161 //162 // This value is inserted into the cache and published to the loader at the163 // key/module-id some/path/nls/someBundle/ab-cd-ef.164 //165 // The special preload signature (case 3) instructs the plugin to stop servicing all normal requests166 // (further preload requests will be serviced) until all ongoing preloading has completed.167 //168 // The preload signature instructs the plugin that a special rollup module is available that contains169 // one or more flattened, localized bundles. The JSON array of available locales indicates which locales170 // are available. Here is an example:171 //172 // *preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]173 //174 // This indicates the following rollup modules are available:175 //176 // some/path/nls/someModule_ROOT177 // some/path/nls/someModule_ab178 // some/path/nls/someModule_ab-cd-ef179 //180 // Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash.181 // For example, assume someModule contained the bundles some/bundle/path/someBundle and182 // some/bundle/path/someOtherBundle, then some/path/nls/someModule_ab would be expressed as follows:183 //184 // define({185 // some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,186 // some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,187 // });188 //189 // E.g., given this design, preloading for locale=="ab" can execute the following algorithm:190 //191 // require(["some/path/nls/someModule_ab"], function(rollup){192 // for(var p in rollup){193 // var id = p + "/ab",194 // cache[id] = rollup[p];195 // define(id, rollup[p]);196 // }197 // });198 //199 // Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and200 // load accordingly.201 //202 // The builder will write such rollups for every layer if a non-empty localeList profile property is203 // provided. Further, the builder will include the following cache entry in the cache associated with204 // any layer.205 //206 // "*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}207 //208 // The *now special cache module instructs the loader to apply the provided function to context-require209 // with respect to the particular layer being defined. This causes the plugin to hold all normal service210 // requests until all preloading is complete.211 //212 // Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case213 // where the target locale has a single segment and a layer depends on a single bundle:214 //215 // Without Preloads:216 //217 // 1. Layer loads root bundle.218 // 2. bundle is demanded; plugin loads single localized bundle.219 //220 // With Preloads:221 //222 // 1. Layer causes preloading of target bundle.223 // 2. bundle is demanded; service is delayed until preloading complete; bundle is returned.224 //225 // In each case a single transaction is required to load the target bundle. In cases where multiple bundles226 // are required and/or the locale has multiple segments, preloads still requires a single transaction whereas227 // the normal path requires an additional transaction for each additional bundle/locale-segment. However all228 // of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading229 // algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.230 var match = nlsRe.exec(id),231 bundlePath = match[1] + "/",232 bundleName = match[5] || match[4],233 bundlePathAndName = bundlePath + bundleName,234 localeSpecified = (match[5] && match[4]),235 targetLocale = localeSpecified || dojo.locale || "",236 loadTarget = bundlePathAndName + "/" + targetLocale,237 loadList = localeSpecified ? [targetLocale] : getLocalesToLoad(targetLocale),238 remaining = loadList.length,239 finish = function(){240 if(!--remaining){241 load(lang.delegate(cache[loadTarget]));242 }243 },244 split = id.split("*"),245 preloadDemand = split[1] == "preload";246 if(has("dojo-preload-i18n-Api")){247 if(preloadDemand){248 if(!cache[id]){249 // use cache[id] to prevent multiple preloads of the same preload; this shouldn't happen, but250 // who knows what over-aggressive human optimizers may attempt251 cache[id] = 1;252 preloadL10n(split[2], json.parse(split[3]), 1, require);253 }254 // don't stall the loader!255 load(1);256 }257 if(preloadDemand || (waitForPreloads(id, require, load) && !cache[loadTarget])){258 return;259 }260 }261 else if (preloadDemand) {262 // If a build is created with nls resources and 'dojo-preload-i18n-Api' has not been set to false,263 // the built file will include a preload in the cache (which looks about like so:)264 // '*now':function(r){r(['dojo/i18n!*preload*dojo/nls/dojo*["ar","ca","cs","da","de","el","en-gb","en-us","es-es","fi-fi","fr-fr","he-il","hu","it-it","ja-jp","ko-kr","nl-nl","nb","pl","pt-br","pt-pt","ru","sk","sl","sv","th","tr","zh-tw","zh-cn","ROOT"]']);}265 // If the consumer of the build sets 'dojo-preload-i18n-Api' to false in the Dojo config, the cached266 // preload will not be parsed and will result in an attempt to call 'require' passing it the unparsed267 // preload, which is not a valid module id.268 // In this case we should skip this request.269 load(1);270 return;271 }272 array.forEach(loadList, function(locale){273 var target = bundlePathAndName + "/" + locale;274 if(has("dojo-preload-i18n-Api")){275 checkForLegacyModules(target);276 }277 if(!cache[target]){278 doLoad(require, bundlePathAndName, bundlePath, bundleName, locale, finish);279 }else{280 finish();281 }282 });283 };284 if(has("dojo-preload-i18n-Api") || 1 ){285 var normalizeLocale = thisModule.normalizeLocale = function(locale){286 var result = locale ? locale.toLowerCase() : dojo.locale;287 return result == "root" ? "ROOT" : result;288 },289 isXd = function(mid, contextRequire){290 return ( 1 && 1 ) ?291 contextRequire.isXdUrl(require.toUrl(mid + ".js")) :292 true;293 },294 preloading = 0,295 preloadWaitQueue = [],296 preloadL10n = thisModule._preloadLocalizations = function(/*String*/bundlePrefix, /*Array*/localesGenerated, /*boolean?*/ guaranteedAmdFormat, /*function?*/ contextRequire){297 // summary:298 // Load available flattened resource bundles associated with a particular module for dojo/locale and all dojo/config.extraLocale (if any)299 // description:300 // Only called by built layer files. The entire locale hierarchy is loaded. For example,301 // if locale=="ab-cd", then ROOT, "ab", and "ab-cd" are loaded. This is different than v1.6-302 // in that the v1.6- would only load ab-cd...which was *always* flattened.303 //304 // If guaranteedAmdFormat is true, then the module can be loaded with require thereby circumventing the detection algorithm305 // and the extra possible extra transaction.306 // If this function is called from legacy code, then guaranteedAmdFormat and contextRequire will be undefined. Since the function307 // needs a require in order to resolve module ids, fall back to the context-require associated with this dojo/i18n module, which308 // itself may have been mapped.309 contextRequire = contextRequire || require;310 function doRequire(mid, callback){311 if(isXd(mid, contextRequire) || guaranteedAmdFormat){312 contextRequire([mid], callback);313 }else{314 syncRequire([mid], callback, contextRequire);315 }316 }317 function forEachLocale(locale, func){318 // given locale= "ab-cd-ef", calls func on "ab-cd-ef", "ab-cd", "ab", "ROOT"; stops calling the first time func returns truthy319 var parts = locale.split("-");320 while(parts.length){321 if(func(parts.join("-"))){322 return;323 }324 parts.pop();325 }326 func("ROOT");327 }328 function preloadingAddLock(){329 preloading++;330 }331 function preloadingRelLock(){332 --preloading;333 while(!preloading && preloadWaitQueue.length){334 load.apply(null, preloadWaitQueue.shift());335 }336 }337 function cacheId(path, name, loc, require){338 // path is assumed to have a trailing "/"339 return require.toAbsMid(path + name + "/" + loc)340 }341 function preload(locale){342 locale = normalizeLocale(locale);343 forEachLocale(locale, function(loc){344 if(array.indexOf(localesGenerated, loc) >= 0){345 var mid = bundlePrefix.replace(/\./g, "/") + "_" + loc;346 preloadingAddLock();347 doRequire(mid, function(rollup){348 for(var p in rollup){349 var bundle = rollup[p],350 match = p.match(/(.+)\/([^\/]+)$/),351 bundleName, bundlePath;352 353 // If there is no match, the bundle is not a regular bundle from an AMD layer.354 if (!match){continue;}355 bundleName = match[2];356 bundlePath = match[1] + "/";357 // backcompat358 if(!bundle._localized){continue;}359 var localized;360 if(loc === "ROOT"){361 var root = localized = bundle._localized;362 delete bundle._localized;363 root.root = bundle;364 cache[require.toAbsMid(p)] = root;365 }else{366 localized = bundle._localized;367 cache[cacheId(bundlePath, bundleName, loc, require)] = bundle;368 }369 if(loc !== locale){370 // capture some locale variables371 function improveBundle(bundlePath, bundleName, bundle, localized){372 // locale was not flattened and we've fallen back to a less-specific locale that was flattened373 // for example, we had a flattened 'fr', a 'fr-ca' is available for at least this bundle, and374 // locale==='fr-ca'; therefore, we must improve the bundle as retrieved from the rollup by375 // manually loading the fr-ca version of the bundle and mixing this into the already-retrieved 'fr'376 // version of the bundle.377 //378 // Remember, different bundles may have different sets of locales available.379 //380 // we are really falling back on the regular algorithm here, but--hopefully--starting with most381 // of the required bundles already on board as given by the rollup and we need to "manually" load382 // only one locale from a few bundles...or even better...we won't find anything better to load.383 // This algorithm ensures there is nothing better to load even when we can only load a less-specific rollup.384 //385 // note: this feature is only available in async mode386 // inspect the loaded bundle that came from the rollup to see if something better is available387 // for any bundle in a rollup, more-specific available locales are given at localized.388 var requiredBundles = [],389 cacheIds = [];390 forEachLocale(locale, function(loc){391 if(localized[loc]){392 requiredBundles.push(require.toAbsMid(bundlePath + loc + "/" + bundleName));393 cacheIds.push(cacheId(bundlePath, bundleName, loc, require));394 }395 });396 if(requiredBundles.length){397 preloadingAddLock();398 contextRequire(requiredBundles, function(){399 // requiredBundles was constructed by forEachLocale so it contains locales from 400 // less specific to most specific. 401 // the loop starts with the most specific locale, the last one.402 for(var i = requiredBundles.length - 1; i >= 0 ; i--){403 bundle = lang.mixin(lang.clone(bundle), arguments[i]);404 cache[cacheIds[i]] = bundle;405 }406 // this is the best possible (maybe a perfect match, maybe not), accept it407 cache[cacheId(bundlePath, bundleName, locale, require)] = lang.clone(bundle);408 preloadingRelLock();409 });410 }else{411 // this is the best possible (definitely not a perfect match), accept it412 cache[cacheId(bundlePath, bundleName, locale, require)] = bundle;413 }414 }415 improveBundle(bundlePath, bundleName, bundle, localized);416 }417 }418 preloadingRelLock();419 });420 return true;421 }422 return false;423 });424 }425 preload();426 array.forEach(dojo.config.extraLocale, preload);427 },428 waitForPreloads = function(id, require, load){429 if(preloading){430 preloadWaitQueue.push([id, require, load]);431 }432 return preloading;433 },434 checkForLegacyModules = function()435 {};436 }437 if( 1 ){438 // this code path assumes the dojo loader and won't work with a standard AMD loader439 var amdValue = {},440 evalBundle,441 syncRequire = function(deps, callback, require){442 var results = [];443 array.forEach(deps, function(mid){444 var url = require.toUrl(mid + ".js");445 function load(text){446 if (!evalBundle) {447 // use the function ctor to keep the minifiers away (also come close to global scope, but this is secondary)448 evalBundle = new Function(449 "__bundle", // the bundle to evalutate450 "__checkForLegacyModules", // a function that checks if __bundle defined __mid in the global space451 "__mid", // the mid that __bundle is intended to define452 "__amdValue",453 // returns one of:454 // 1 => the bundle was an AMD bundle455 // a legacy bundle object that is the value of __mid456 // instance of Error => could not figure out how to evaluate bundle457 // used to detect when __bundle calls define458 "var define = function(mid, factory){define.called = 1; __amdValue.result = factory || mid;},"459 + " require = function(){define.called = 1;};"460 + "try{"461 + "define.called = 0;"462 + "eval(__bundle);"463 + "if(define.called==1)"464 // bundle called define; therefore signal it's an AMD bundle465 + "return __amdValue;"466 + "if((__checkForLegacyModules = __checkForLegacyModules(__mid)))"467 // bundle was probably a v1.6- built NLS flattened NLS bundle that defined __mid in the global space468 + "return __checkForLegacyModules;"469 + "}catch(e){}"470 // evaulating the bundle was *neither* an AMD *nor* a legacy flattened bundle471 // either way, re-eval *after* surrounding with parentheses472 + "try{"473 + "return eval('('+__bundle+')');"474 + "}catch(e){"475 + "return e;"476 + "}"477 );478 }479 var result = evalBundle(text, checkForLegacyModules, mid, amdValue);480 if(result===amdValue){481 // the bundle was an AMD module; re-inject it through the normal AMD path482 // we gotta do this since it could be an anonymous module and simply evaluating483 // the text here won't provide the loader with the context to know what484 // module is being defined()'d. With browser caching, this should be free; further485 // this entire code path can be circumvented by using the AMD format to begin with486 results.push(cache[url] = amdValue.result);487 }else{488 if(result instanceof Error){489 console.error("failed to evaluate i18n bundle; url=" + url, result);490 result = {};491 }492 // nls/<locale>/<bundle-name> indicates not the root.493 results.push(cache[url] = (/nls\/[^\/]+\/[^\/]+$/.test(url) ? result : {root:result, _v1x:1}));494 }495 }496 if(cache[url]){497 results.push(cache[url]);498 }else{499 var bundle = require.syncLoadNls(mid);500 // need to check for legacy module here because there might be a legacy module for a501 // less specific locale (which was not looked up during the first checkForLegacyModules502 // call in load()).503 // Also need to reverse the locale and the module name in the mid because syncRequire504 // deps parameters uses the AMD style package/nls/locale/module while legacy code uses505 // package/nls/module/locale.506 if(!bundle){507 bundle = checkForLegacyModules(mid.replace(/nls\/([^\/]*)\/([^\/]*)$/, "nls/$2/$1"));508 }509 if(bundle){510 results.push(bundle);511 }else{512 if(!xhr){513 try{514 require.getText(url, true, load);515 }catch(e){516 results.push(cache[url] = {});517 }518 }else{519 xhr.get({520 url:url,521 sync:true,522 load:load,523 error:function(){524 results.push(cache[url] = {});525 }526 });527 }528 }529 }530 });531 callback && callback.apply(null, results);532 };533 checkForLegacyModules = function(target){534 // legacy code may have already loaded [e.g] the raw bundle x/y/z at x.y.z; when true, push into the cache535 for(var result, names = target.split("/"), object = dojo.global[names[0]], i = 1; object && i<names.length-1; object = object[names[i++]]){}536 if(object){537 result = object[names[i]];538 if(!result){539 // fallback for incorrect bundle build of 1.6540 result = object[names[i].replace(/-/g,"_")];541 }542 if(result){543 cache[target] = result;544 }545 }546 return result;547 };548 thisModule.getLocalization = function(moduleName, bundleName, locale){549 var result,550 l10nName = getBundleName(moduleName, bundleName, locale);551 load(552 l10nName,553 // isXd() and syncRequire() need a context-require in order to resolve the mid with respect to a reference module.554 // Since this legacy function does not have the concept of a reference module, resolve with respect to this555 // dojo/i18n module, which, itself may have been mapped.556 (!isXd(l10nName, require) ? function(deps, callback){ syncRequire(deps, callback, require); } : require),557 function(result_){ result = result_; }558 );559 return result;560 };561 }562 return lang.mixin(thisModule, {563 dynamic:true,564 normalize:normalize,565 load:load,566 cache:cache,567 getL10nName: getL10nName568 });...
build.js
Source:build.js
1'use strict';2const {rollup} = require('rollup');3const babel = require('rollup-plugin-babel');4const closure = require('./plugins/closure-plugin');5const commonjs = require('rollup-plugin-commonjs');6const prettier = require('rollup-plugin-prettier');7const replace = require('rollup-plugin-replace');8const stripBanner = require('rollup-plugin-strip-banner');9const chalk = require('chalk');10const path = require('path');11const resolve = require('rollup-plugin-node-resolve');12const fs = require('fs');13const argv = require('minimist')(process.argv.slice(2));14const Modules = require('./modules');15const Bundles = require('./bundles');16const Stats = require('./stats');17const Sync = require('./sync');18const sizes = require('./plugins/sizes-plugin');19const useForks = require('./plugins/use-forks-plugin');20const stripUnusedImports = require('./plugins/strip-unused-imports');21const extractErrorCodes = require('../error-codes/extract-errors');22const Packaging = require('./packaging');23const {asyncCopyTo, asyncRimRaf} = require('./utils');24const codeFrame = require('babel-code-frame');25const Wrappers = require('./wrappers');26// Errors in promises should be fatal.27let loggedErrors = new Set();28process.on('unhandledRejection', err => {29 if (loggedErrors.has(err)) {30 // No need to print it twice.31 process.exit(1);32 }33 throw err;34});35const {36 UMD_DEV,37 UMD_PROD,38 UMD_PROFILING,39 NODE_DEV,40 NODE_PROD,41 NODE_PROFILING,42 FB_WWW_DEV,43 FB_WWW_PROD,44 FB_WWW_PROFILING,45 RN_OSS_DEV,46 RN_OSS_PROD,47 RN_OSS_PROFILING,48 RN_FB_DEV,49 RN_FB_PROD,50 RN_FB_PROFILING,51} = Bundles.bundleTypes;52function parseRequestedNames(names, toCase) {53 let result = [];54 for (let i = 0; i < names.length; i++) {55 let splitNames = names[i].split(',');56 for (let j = 0; j < splitNames.length; j++) {57 let name = splitNames[j].trim();58 if (!name) {59 continue;60 }61 if (toCase === 'uppercase') {62 name = name.toUpperCase();63 } else if (toCase === 'lowercase') {64 name = name.toLowerCase();65 }66 result.push(name);67 }68 }69 return result;70}71const requestedBundleTypes = argv.type72 ? parseRequestedNames([argv.type], 'uppercase')73 : [];74const requestedBundleNames = parseRequestedNames(argv._, 'lowercase');75const forcePrettyOutput = argv.pretty;76const syncFBSourcePath = argv['sync-fbsource'];77const syncWWWPath = argv['sync-www'];78const shouldExtractErrors = argv['extract-errors'];79const errorCodeOpts = {80 errorMapFilePath: 'scripts/error-codes/codes.json',81};82const closureOptions = {83 compilation_level: 'SIMPLE',84 language_in: 'ECMASCRIPT5_STRICT',85 language_out: 'ECMASCRIPT5_STRICT',86 env: 'CUSTOM',87 warning_level: 'QUIET',88 apply_input_source_maps: false,89 use_types_for_optimization: false,90 process_common_js_modules: false,91 rewrite_polyfills: false,92};93function getBabelConfig(updateBabelOptions, bundleType, filename) {94 let options = {95 exclude: '/**/node_modules/**',96 presets: [],97 plugins: [],98 };99 if (updateBabelOptions) {100 options = updateBabelOptions(options);101 }102 switch (bundleType) {103 case FB_WWW_DEV:104 case FB_WWW_PROD:105 case FB_WWW_PROFILING:106 return Object.assign({}, options, {107 plugins: options.plugins.concat([108 // Minify invariant messages109 require('../error-codes/minify-error-messages'),110 // Wrap warning() calls in a __DEV__ check so they are stripped from production.111 require('../babel/wrap-warning-with-env-check'),112 ]),113 });114 case RN_OSS_DEV:115 case RN_OSS_PROD:116 case RN_OSS_PROFILING:117 case RN_FB_DEV:118 case RN_FB_PROD:119 case RN_FB_PROFILING:120 return Object.assign({}, options, {121 plugins: options.plugins.concat([122 // Wrap warning() calls in a __DEV__ check so they are stripped from production.123 require('../babel/wrap-warning-with-env-check'),124 ]),125 });126 case UMD_DEV:127 case UMD_PROD:128 case UMD_PROFILING:129 case NODE_DEV:130 case NODE_PROD:131 case NODE_PROFILING:132 return Object.assign({}, options, {133 plugins: options.plugins.concat([134 // Use object-assign polyfill in open source135 path.resolve('./scripts/babel/transform-object-assign-require'),136 // Minify invariant messages137 require('../error-codes/minify-error-messages'),138 // Wrap warning() calls in a __DEV__ check so they are stripped from production.139 require('../babel/wrap-warning-with-env-check'),140 ]),141 });142 default:143 return options;144 }145}146function getRollupOutputOptions(147 outputPath,148 format,149 globals,150 globalName,151 bundleType152) {153 const isProduction = isProductionBundleType(bundleType);154 return Object.assign(155 {},156 {157 file: outputPath,158 format,159 globals,160 freeze: !isProduction,161 interop: false,162 name: globalName,163 sourcemap: false,164 }165 );166}167function getFormat(bundleType) {168 switch (bundleType) {169 case UMD_DEV:170 case UMD_PROD:171 case UMD_PROFILING:172 return `umd`;173 case NODE_DEV:174 case NODE_PROD:175 case NODE_PROFILING:176 case FB_WWW_DEV:177 case FB_WWW_PROD:178 case FB_WWW_PROFILING:179 case RN_OSS_DEV:180 case RN_OSS_PROD:181 case RN_OSS_PROFILING:182 case RN_FB_DEV:183 case RN_FB_PROD:184 case RN_FB_PROFILING:185 return `cjs`;186 }187}188function getFilename(name, globalName, bundleType) {189 // we do this to replace / to -, for react-dom/server190 name = name.replace('/', '-');191 switch (bundleType) {192 case UMD_DEV:193 return `${name}.development.js`;194 case UMD_PROD:195 return `${name}.production.min.js`;196 case UMD_PROFILING:197 return `${name}.profiling.min.js`;198 case NODE_DEV:199 return `${name}.development.js`;200 case NODE_PROD:201 return `${name}.production.min.js`;202 case NODE_PROFILING:203 return `${name}.profiling.min.js`;204 case FB_WWW_DEV:205 case RN_OSS_DEV:206 case RN_FB_DEV:207 return `${globalName}-dev.js`;208 case FB_WWW_PROD:209 case RN_OSS_PROD:210 case RN_FB_PROD:211 return `${globalName}-prod.js`;212 case FB_WWW_PROFILING:213 case RN_FB_PROFILING:214 case RN_OSS_PROFILING:215 return `${globalName}-profiling.js`;216 }217}218function isProductionBundleType(bundleType) {219 switch (bundleType) {220 case UMD_DEV:221 case NODE_DEV:222 case FB_WWW_DEV:223 case RN_OSS_DEV:224 case RN_FB_DEV:225 return false;226 case UMD_PROD:227 case NODE_PROD:228 case UMD_PROFILING:229 case NODE_PROFILING:230 case FB_WWW_PROD:231 case FB_WWW_PROFILING:232 case RN_OSS_PROD:233 case RN_OSS_PROFILING:234 case RN_FB_PROD:235 case RN_FB_PROFILING:236 return true;237 default:238 throw new Error(`Unknown type: ${bundleType}`);239 }240}241function isProfilingBundleType(bundleType) {242 switch (bundleType) {243 case FB_WWW_DEV:244 case FB_WWW_PROD:245 case NODE_DEV:246 case NODE_PROD:247 case RN_FB_DEV:248 case RN_FB_PROD:249 case RN_OSS_DEV:250 case RN_OSS_PROD:251 case UMD_DEV:252 case UMD_PROD:253 return false;254 case FB_WWW_PROFILING:255 case NODE_PROFILING:256 case RN_FB_PROFILING:257 case RN_OSS_PROFILING:258 case UMD_PROFILING:259 return true;260 default:261 throw new Error(`Unknown type: ${bundleType}`);262 }263}264function forbidFBJSImports() {265 return {266 name: 'forbidFBJSImports',267 resolveId(importee, importer) {268 if (/^fbjs\//.test(importee)) {269 throw new Error(270 `Don't import ${importee} (found in ${importer}). ` +271 `Use the utilities in packages/shared/ instead.`272 );273 }274 },275 };276}277function getPlugins(278 entry,279 externals,280 updateBabelOptions,281 filename,282 packageName,283 bundleType,284 globalName,285 moduleType,286 pureExternalModules287) {288 const findAndRecordErrorCodes = extractErrorCodes(errorCodeOpts);289 const forks = Modules.getForks(bundleType, entry, moduleType);290 const isProduction = isProductionBundleType(bundleType);291 const isProfiling = isProfilingBundleType(bundleType);292 const isUMDBundle =293 bundleType === UMD_DEV ||294 bundleType === UMD_PROD ||295 bundleType === UMD_PROFILING;296 const isFBBundle =297 bundleType === FB_WWW_DEV ||298 bundleType === FB_WWW_PROD ||299 bundleType === FB_WWW_PROFILING;300 const isRNBundle =301 bundleType === RN_OSS_DEV ||302 bundleType === RN_OSS_PROD ||303 bundleType === RN_OSS_PROFILING ||304 bundleType === RN_FB_DEV ||305 bundleType === RN_FB_PROD ||306 bundleType === RN_FB_PROFILING;307 const shouldStayReadable = isFBBundle || isRNBundle || forcePrettyOutput;308 return [309 // Extract error codes from invariant() messages into a file.310 shouldExtractErrors && {311 transform(source) {312 findAndRecordErrorCodes(source);313 return source;314 },315 },316 // Shim any modules that need forking in this environment.317 useForks(forks),318 // Ensure we don't try to bundle any fbjs modules.319 forbidFBJSImports(),320 // Use Node resolution mechanism.321 resolve({322 skip: externals,323 }),324 // Remove license headers from individual modules325 stripBanner({326 exclude: 'node_modules/**/*',327 }),328 // Compile to ES5.329 babel(getBabelConfig(updateBabelOptions, bundleType)),330 // Remove 'use strict' from individual source files.331 {332 transform(source) {333 return source.replace(/['"]use strict['"']/g, '');334 },335 },336 // Turn __DEV__ and process.env checks into constants.337 replace({338 __DEV__: isProduction ? 'false' : 'true',339 __PROFILE__: isProfiling || !isProduction ? 'true' : 'false',340 __UMD__: isUMDBundle ? 'true' : 'false',341 'process.env.NODE_ENV': isProduction ? "'production'" : "'development'",342 }),343 // We still need CommonJS for external deps like object-assign.344 commonjs(),345 // Apply dead code elimination and/or minification.346 isProduction &&347 closure(348 Object.assign({}, closureOptions, {349 // Don't let it create global variables in the browser.350 // https://github.com/facebook/react/issues/10909351 assume_function_wrapper: !isUMDBundle,352 // Works because `google-closure-compiler-js` is forked in Yarn lockfile.353 // We can remove this if GCC merges my PR:354 // https://github.com/google/closure-compiler/pull/2707355 // and then the compiled version is released via `google-closure-compiler-js`.356 renaming: !shouldStayReadable,357 })358 ),359 // HACK to work around the fact that Rollup isn't removing unused, pure-module imports.360 // Note that this plugin must be called after closure applies DCE.361 isProduction && stripUnusedImports(pureExternalModules),362 // Add the whitespace back if necessary.363 shouldStayReadable && prettier({parser: 'babylon'}),364 // License and haste headers, top-level `if` blocks.365 {366 transformBundle(source) {367 return Wrappers.wrapBundle(368 source,369 bundleType,370 globalName,371 filename,372 moduleType373 );374 },375 },376 // Record bundle size.377 sizes({378 getSize: (size, gzip) => {379 const currentSizes = Stats.currentBuildResults.bundleSizes;380 const recordIndex = currentSizes.findIndex(381 record =>382 record.filename === filename && record.bundleType === bundleType383 );384 const index = recordIndex !== -1 ? recordIndex : currentSizes.length;385 currentSizes[index] = {386 filename,387 bundleType,388 packageName,389 size,390 gzip,391 };392 },393 }),394 ].filter(Boolean);395}396function shouldSkipBundle(bundle, bundleType) {397 const shouldSkipBundleType = bundle.bundleTypes.indexOf(bundleType) === -1;398 if (shouldSkipBundleType) {399 return true;400 }401 if (requestedBundleTypes.length > 0) {402 const isAskingForDifferentType = requestedBundleTypes.every(403 requestedType => bundleType.indexOf(requestedType) === -1404 );405 if (isAskingForDifferentType) {406 return true;407 }408 }409 if (requestedBundleNames.length > 0) {410 const isAskingForDifferentNames = requestedBundleNames.every(411 // If the name ends with `something/index` we only match if the412 // entry ends in something. Such as `react-dom/index` only matches413 // `react-dom` but not `react-dom/server`. Everything else is fuzzy414 // search.415 requestedName =>416 (bundle.entry + '/index.js').indexOf(requestedName) === -1417 );418 if (isAskingForDifferentNames) {419 return true;420 }421 }422 return false;423}424async function createBundle(bundle, bundleType) {425 if (shouldSkipBundle(bundle, bundleType)) {426 return;427 }428 const filename = getFilename(bundle.entry, bundle.global, bundleType);429 const logKey =430 chalk.white.bold(filename) + chalk.dim(` (${bundleType.toLowerCase()})`);431 const format = getFormat(bundleType);432 const packageName = Packaging.getPackageName(bundle.entry);433 let resolvedEntry = require.resolve(bundle.entry);434 if (435 bundleType === FB_WWW_DEV ||436 bundleType === FB_WWW_PROD ||437 bundleType === FB_WWW_PROFILING438 ) {439 const resolvedFBEntry = resolvedEntry.replace('.js', '.fb.js');440 if (fs.existsSync(resolvedFBEntry)) {441 resolvedEntry = resolvedFBEntry;442 }443 }444 const shouldBundleDependencies =445 bundleType === UMD_DEV ||446 bundleType === UMD_PROD ||447 bundleType === UMD_PROFILING;448 const peerGlobals = Modules.getPeerGlobals(bundle.externals, bundleType);449 let externals = Object.keys(peerGlobals);450 if (!shouldBundleDependencies) {451 const deps = Modules.getDependencies(bundleType, bundle.entry);452 externals = externals.concat(deps);453 }454 const importSideEffects = Modules.getImportSideEffects();455 const pureExternalModules = Object.keys(importSideEffects).filter(456 module => !importSideEffects[module]457 );458 const rollupConfig = {459 input: resolvedEntry,460 treeshake: {461 pureExternalModules,462 },463 external(id) {464 const containsThisModule = pkg => id === pkg || id.startsWith(pkg + '/');465 const isProvidedByDependency = externals.some(containsThisModule);466 if (!shouldBundleDependencies && isProvidedByDependency) {467 return true;468 }469 return !!peerGlobals[id];470 },471 onwarn: handleRollupWarning,472 plugins: getPlugins(473 bundle.entry,474 externals,475 bundle.babel,476 filename,477 packageName,478 bundleType,479 bundle.global,480 bundle.moduleType,481 pureExternalModules482 ),483 // We can't use getters in www.484 legacy:485 bundleType === FB_WWW_DEV ||486 bundleType === FB_WWW_PROD ||487 bundleType === FB_WWW_PROFILING,488 };489 const [mainOutputPath, ...otherOutputPaths] = Packaging.getBundleOutputPaths(490 bundleType,491 filename,492 packageName493 );494 const rollupOutputOptions = getRollupOutputOptions(495 mainOutputPath,496 format,497 peerGlobals,498 bundle.global,499 bundleType500 );501 console.log(`${chalk.bgYellow.black(' BUILDING ')} ${logKey}`);502 try {503 const result = await rollup(rollupConfig);504 await result.write(rollupOutputOptions);505 } catch (error) {506 console.log(`${chalk.bgRed.black(' OH NOES! ')} ${logKey}\n`);507 handleRollupError(error);508 throw error;509 }510 for (let i = 0; i < otherOutputPaths.length; i++) {511 await asyncCopyTo(mainOutputPath, otherOutputPaths[i]);512 }513 console.log(`${chalk.bgGreen.black(' COMPLETE ')} ${logKey}\n`);514}515function handleRollupWarning(warning) {516 if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {517 const match = warning.message.match(/external module '([^']+)'/);518 if (!match || typeof match[1] !== 'string') {519 throw new Error(520 'Could not parse a Rollup warning. ' + 'Fix this method.'521 );522 }523 const importSideEffects = Modules.getImportSideEffects();524 const externalModule = match[1];525 if (typeof importSideEffects[externalModule] !== 'boolean') {526 throw new Error(527 'An external module "' +528 externalModule +529 '" is used in a DEV-only code path ' +530 'but we do not know if it is safe to omit an unused require() to it in production. ' +531 'Please add it to the `importSideEffects` list in `scripts/rollup/modules.js`.'532 );533 }534 // Don't warn. We will remove side effectless require() in a later pass.535 return;536 }537 if (typeof warning.code === 'string') {538 // This is a warning coming from Rollup itself.539 // These tend to be important (e.g. clashes in namespaced exports)540 // so we'll fail the build on any of them.541 console.error();542 console.error(warning.message || warning);543 console.error();544 process.exit(1);545 } else {546 // The warning is from one of the plugins.547 // Maybe it's not important, so just print it.548 console.warn(warning.message || warning);549 }550}551function handleRollupError(error) {552 loggedErrors.add(error);553 if (!error.code) {554 console.error(error);555 return;556 }557 console.error(558 `\x1b[31m-- ${error.code}${error.plugin ? ` (${error.plugin})` : ''} --`559 );560 console.error(error.stack);561 if (error.loc && error.loc.file) {562 const {file, line, column} = error.loc;563 // This looks like an error from Rollup, e.g. missing export.564 // We'll use the accurate line numbers provided by Rollup but565 // use Babel code frame because it looks nicer.566 const rawLines = fs.readFileSync(file, 'utf-8');567 // column + 1 is required due to rollup counting column start position from 0568 // whereas babel-code-frame counts from 1569 const frame = codeFrame(rawLines, line, column + 1, {570 highlightCode: true,571 });572 console.error(frame);573 } else if (error.codeFrame) {574 // This looks like an error from a plugin (e.g. Babel).575 // In this case we'll resort to displaying the provided code frame576 // because we can't be sure the reported location is accurate.577 console.error(error.codeFrame);578 }579}580async function buildEverything() {581 await asyncRimRaf('build');582 // Run them serially for better console output583 // and to avoid any potential race conditions.584 // eslint-disable-next-line no-for-of-loops/no-for-of-loops585 for (const bundle of Bundles.bundles) {586 await createBundle(bundle, UMD_DEV);587 await createBundle(bundle, UMD_PROD);588 await createBundle(bundle, UMD_PROFILING);589 await createBundle(bundle, NODE_DEV);590 await createBundle(bundle, NODE_PROD);591 await createBundle(bundle, NODE_PROFILING);592 await createBundle(bundle, FB_WWW_DEV);593 await createBundle(bundle, FB_WWW_PROD);594 await createBundle(bundle, FB_WWW_PROFILING);595 await createBundle(bundle, RN_OSS_DEV);596 await createBundle(bundle, RN_OSS_PROD);597 await createBundle(bundle, RN_OSS_PROFILING);598 await createBundle(bundle, RN_FB_DEV);599 await createBundle(bundle, RN_FB_PROD);600 await createBundle(bundle, RN_FB_PROFILING);601 }602 await Packaging.copyAllShims();603 await Packaging.prepareNpmPackages();604 if (syncFBSourcePath) {605 await Sync.syncReactNative(syncFBSourcePath);606 } else if (syncWWWPath) {607 await Sync.syncReactDom('build/facebook-www', syncWWWPath);608 }609 console.log(Stats.printResults());610 if (!forcePrettyOutput) {611 Stats.saveResults();612 }613 if (shouldExtractErrors) {614 console.warn(615 '\nWarning: this build was created with --extract-errors enabled.\n' +616 'this will result in extremely slow builds and should only be\n' +617 'used when the error map needs to be rebuilt.\n'618 );619 }620}...
alias.js
Source:alias.js
1/**2 * There are basically two kinds of alias in CLDR:3 * 1. locale alias e.g.4 * in xml, <alias source="locale" path="......"/>,5 * in gernated JSON bunle, xxxx@localeAlias:{'target':'xxx', 'bundle':'xxxx'}6 * 2. other locale alias e.g.7 * in xml, currently only like <alias source="fr" path="//ldml"/>8 * #1 is supported by this 'alias.js',9 * #2 is covered by 'specialLocale.js' and may need enhancement for future CLDR versions.10 */11djConfig={baseUrl: "../../../dojo/", paths: {"dojo/_base/xhr": "../util/buildscripts/cldr/xhr"}};12load("../../../dojo/dojo.js");13load("../jslib/logger.js");14load("../jslib/fileUtil.js");15load("cldrUtil.js");16dojo.require("dojo.i18n");17var dir/*String*/ = arguments[0];// ${dojo}/dojo/cldr/nls18var logDir = arguments[1];19var logStr = "";20//Add new bundles to the list so that they will be aliased according to the ldml spec.21var BUNDLES = ['gregorian','hebrew','islamic','islamic-civil','buddhist','persian'];22var LOCALE_ALIAS_MARK = '@localeAlias';23var LOCALE_ALIAS_SOURCE_PROPERTY = 'source';24var LOCALE_ALIAS_TARGET_PROPERTY = 'target';25var LOCALE_ALIAS_TARGET_BUNDLE = 'bundle';26var localeAliasPaths = [];/**/27var records = {};/*{property : boolean}, record whether a property has been calculated for alias path*/28var updated = false;29print('alias.js...');30for(var i = 0; i < BUNDLES.length; i++){31 var regExp = new RegExp('\/' + BUNDLES[i] + '\.js$'); //e.g. new RegExp('\/gregorian\.js$')32 var fileList = fileUtil.getFilteredFileList(dir, regExp, true);33 34 for(var j = 0; j < fileList.length; j++){35 var jsFileName = new String(fileList[j]); //Java String36 var jsFilePath = jsFileName.split("/");37 var locale = jsFilePath[jsFilePath.length-2];38 if(locale=="nls"){continue;} // no need for root bundle39 try{40// dojo.i18n._requireLocalization('dojo.cldr', BUNDLES[i], locale); //declare bundle41 var bundle = dojo.i18n.getLocalization('dojo.cldr', BUNDLES[i], locale); //get bundle42 var nativeSrcBundle = getNativeBundle(jsFileName);//bundle not flattened43 }catch(e){/*logStr += "alias: an exception occurred: "+e;/* simply ignore if no bundle found*/}44 45 if(!bundle) continue;46 47 updated = false;48 //logStr += locale + ":" + BUNDLES[i] + "=========================================================================\n";49 50 _calculateAliasPath(bundle, BUNDLES[i]);51 //logStr += "all alias paths=" + dojo.toJson(localeAliasPaths) + "\n";52 53 _processLocaleAlias(localeAliasPaths, bundle, nativeSrcBundle,locale);54 55 if(updated){56 fileUtil.saveUtf8File(jsFileName, "(" + dojo.toJson(nativeSrcBundle, true) + ")");57 }58 //logStr += '\n';59 }60 cleanLocaleAlias(fileList);61}62//fileUtil.saveUtf8File(logDir + '/alias.log',logStr+'\n');63//print('CLDR finished, please refer to logs at ' + logDir + ' for more details.');64function _calculateAliasPath(bundle, name/*String*/){65 for(p in bundle){66 var index = p.indexOf(LOCALE_ALIAS_MARK);67 if(index >= 0 /*p like 'xxx@localeAlias6'*/){68 var localeAliasSource/*String*/ = p.substring(0,index);69 if(records[localeAliasSource]/*calculated*/){70 //logStr += p + " has been calculated, ignored\n"71 continue;72 }73 74 var path = [];75 var aliasIndex = new Number(p.substring(index + LOCALE_ALIAS_MARK.length));76 //logStr += "aliasIndex for " + p + " is " + aliasIndex + "\n";77 var i = aliasIndex;78 while(bundle[localeAliasSource + LOCALE_ALIAS_MARK + (--i)]){}79 80 var src = localeAliasSource;81 while(bundle[localeAliasSource + LOCALE_ALIAS_MARK + (++i)]){82 var mapping = {};83 mapping[LOCALE_ALIAS_SOURCE_PROPERTY] = src;84 mapping[LOCALE_ALIAS_TARGET_PROPERTY] = bundle[localeAliasSource + LOCALE_ALIAS_MARK + i][LOCALE_ALIAS_TARGET_PROPERTY];85 mapping[LOCALE_ALIAS_TARGET_BUNDLE] = bundle[localeAliasSource + LOCALE_ALIAS_MARK + i][LOCALE_ALIAS_TARGET_BUNDLE];86 //whether aliased to the bundle itself87 mapping.inSelf = mapping[LOCALE_ALIAS_TARGET_BUNDLE] === name;88 path.push(mapping);89 records[src] = true;90 src = bundle[localeAliasSource + LOCALE_ALIAS_MARK + i][LOCALE_ALIAS_TARGET_PROPERTY];91 }92 path = path.reverse();93 //logStr += "alias path calucated for " + localeAliasSource + "=" + dojo.toJson(path) + "\n";94 localeAliasPaths.push(path);95 }96 }97}98function _processLocaleAlias(localeAliasPaths/*Array*/, bundle/*JSON Obj*/, nativeSrcBundle/*JSON Obj*/,locale/*String*/){99 // summary:100 // Update all properties as defined by 'locale' alias mapping101 // E.g.'months-format-abbr@localeAlias6':{'target':"months-format-wide", 'bundle':"gregorian"},102 // means the array values of 'months-format-abbr' in current bundle should be103 // merged with(inherit or overwrite) that of 'months-format-wide' in 'gregorian' bundle104 //105 // Note: Currently no bundle recognition, always assume 'gregorian'.106 var processed = {};107 for(var i = 0; i < localeAliasPaths.length; i++){108 var path = localeAliasPaths[i];109 for(var j = 0; j < path.length; j++){110 var mapping = path[j];111 if(mapping.inSelf && mapping[LOCALE_ALIAS_SOURCE_PROPERTY] != mapping[LOCALE_ALIAS_TARGET_PROPERTY]112 && bundle[mapping[LOCALE_ALIAS_TARGET_PROPERTY]]/*target existed*/){113 //e.g. {'source':'months-format-abbr','target':"months-format-wide",'bundle':"gregorian"},114 //currently source and target bundles are the same - gregorian115 if(processed[mapping[LOCALE_ALIAS_SOURCE_PROPERTY]]){/*haven't been processed*/116 //logStr += "!" + mapping[LOCALE_ALIAS_SOURCE_PROPERTY] +" has been processed for alias, escaped\n";117 continue;118 }119 _updateLocaleAlias(bundle, mapping[LOCALE_ALIAS_SOURCE_PROPERTY], bundle,120 mapping[LOCALE_ALIAS_TARGET_PROPERTY], nativeSrcBundle);121 processed[mapping[LOCALE_ALIAS_SOURCE_PROPERTY]] = true;122 }else if(!mapping.inSelf){123 //For other non-gregorian calendars. e.g. "hebrew" etc.124 //Get the bundle according to the locale.125 var targetBundle = dojo.i18n.getLocalization('dojo.cldr', mapping[LOCALE_ALIAS_TARGET_BUNDLE], locale);126 if(processed[mapping[LOCALE_ALIAS_SOURCE_PROPERTY]]){//If being processed, continue;127 continue;128 }129 _updateNoneGregAlias(bundle, mapping[LOCALE_ALIAS_SOURCE_PROPERTY], targetBundle,130 mapping[LOCALE_ALIAS_TARGET_PROPERTY], nativeSrcBundle);131 processed[mapping[LOCALE_ALIAS_SOURCE_PROPERTY]] = true;132 }133 }134 }135}136/*137* This function will flatten the source bundle for non-gregorian ones by searching in the bundle files generated from the ldml spec which have terms like:138* "'months-standAlone-abbr@localeAlias131':{'target':"months-format-abbr",'bundle':"hebrew"},".139* Parameters:140* sourceBundle: The bundles which need to be aliased.141* aliasSource: The source mark string. 'months-standAlone-abbr' for example.142* targetBundle: The aliased bundle. 'hebrew' for example.143* aliasTarget: The target mark string. 'months-format-abbr' for example.144* nativeSrcBundle: The final flattened bundle file.145* According to the dojo way of fetching resource bundle, this function will firstly check the bundle under the appointed146* locale. If the wanted calendar bundle is not under the locale, the root calendar bundle will be fetched. If the non-gregorian147* bundle in the root can not be found, dojo will finally get the root gregorian bundle.148*/149function _updateNoneGregAlias(sourceBundle/*JSON Obj*/, aliasSource/*String*/, targetBundle/*JSON Obj*/, aliasTarget/*String*/, nativeSrcBundle/*JSON Obj*/){150 for (var sKey in sourceBundle) {151 var target = targetBundle[sKey],152 source = sourceBundle[sKey],153 nativeSrc = nativeSrcBundle[sKey];154 if (sKey.indexOf(aliasSource) == 0 && !nativeSrc && target && !compare(source, target)) {155 nativeSrcBundle[sKey] = target;156 sourceBundle[sKey] = target;157 updated = true;158 } else {159 if (sKey.indexOf(aliasSource) == 0 && nativeSrc && dojo.isArray(source) && dojo.isArray(target)) {160 for (var i = 0; i < source.length; i++) {161 if (source[i] === undefined) {162 source[i] = target[i];163 updated = true;164 }165 }166 if (source.length < target.length) {167 source = sourceBundle[sKey] = source.concat(target.slice(source.length));168 updated = true;169 }170 if (updated) {171 nativeSrcBundle[sKey] = source;172 }173 }174 }175 }176}177function _updateLocaleAlias(sourceBundle/*JSON Obj*/,aliasSource/*String*/, targetBundle/*JSON Obj*/,178 aliasTarget/*String*/, nativeSrcBundle/*JSON Obj*/){179 //single property180 if(!nativeSrcBundle[aliasSource] && nativeSrcBundle[aliasTarget]//no this property in current locale181 && !compare(sourceBundle[aliasSource], targetBundle[aliasTarget])){182 // then should inherit from alias target (as defined by 'locale' alias)183 //logStr += '1 '+aliasSource + "=" + sourceBundle[aliasSource] + " is replaced with " + aliasTarget + "=" + targetBundle[aliasTarget]+'\n';184 //sourceBundle[aliasSource] = targetBundle[aliasTarget];185 nativeSrcBundle[aliasSource] = targetBundle[aliasTarget];186 sourceBundle[aliasSource] = nativeSrcBundle[aliasSource];187 updated = true;188 }else if(nativeSrcBundle[aliasSource] && dojo.isArray(sourceBundle[aliasSource])189 && dojo.isArray(targetBundle[aliasTarget])){190 if(sourceBundle[aliasSource].length > targetBundle[aliasTarget].length){191 //logStr +="Error:" + aliasSource + ".length > " + aliasTarget + ".length \n";192 }193 //array property, see if need inherit194 for(var i = 0; i < sourceBundle[aliasSource].length; i++){195 if(sourceBundle[aliasSource][i] == undefined){//need inherit196 //logStr += '2 ' + aliasSource + "["+i+"]=" +sourceBundle[aliasSource][i]+" is replaced with " + aliasTarget+"["+i+"]="+targetBundle[aliasTarget][i]+'\n';197 sourceBundle[aliasSource][i] = targetBundle[aliasTarget][i];198 updated = true;199 }// otherwise no change and use current value200 }201 if(sourceBundle[aliasSource].length < targetBundle[aliasTarget].length){202 //logStr +='3 ' + aliasSource +' from ' + sourceBundle[aliasSource].length +' to '203 // + (targetBundle[aliasTarget].length-1) + ' are copied from '204 // +aliasTarget + '='+ targetBundle[aliasTarget] +'\n';205 sourceBundle[aliasSource] = sourceBundle[aliasSource].concat(206 targetBundle[aliasTarget].slice(sourceBundle[aliasSource].length));207 updated = true;208 }209 if(updated){210 nativeSrcBundle[aliasSource] = sourceBundle[aliasSource];211 }212 }213}214function cleanLocaleAlias(fileList/*Array*/){215 for(var i = 0; i < fileList.length; i++){216 var fileName = new String(fileList[i]); //Java String217 try{218 var bundle = getNativeBundle(fileName);//bundle not flattened219 }catch(e){print(e);/* simply ignore if no bundle found*/}220 221 var newBundle = {};222 var needUpdate = false;223 for(p in bundle){224 if(p.indexOf(LOCALE_ALIAS_MARK) < 0){225 newBundle[p] = bundle[p];226 }else{227 needUpdate = true;228 }229 }230 if(needUpdate){231 fileUtil.saveUtf8File(fileName, "(" + dojo.toJson(newBundle, true) + ")");232 //logStr += "cleaned @localAlias for " + fileName + "\n";233 }234 }...
add-to-cart-bundle.js
Source:add-to-cart-bundle.js
...14 $( '.bundle_form_' + bundle_id + ' .bundle_wrap' ).find('input[name="variation_id['+ bundled_item_id +']"]').val( variation.variation_id ).change();15 for ( attribute in variation.attributes ) {16 $( '.bundle_form_' + bundle_id + ' .bundle_wrap' ).find('input[name="' + attribute + '['+ bundled_item_id +']"]').val( $(this).find('.attribute-options select[name="' + attribute + '"]').val() );17 }18 attempt_show_bundle( bundle_id );19 } )20 .on( 'woocommerce_update_variation_values', function() {21 var bundle_id = $(this).attr('data-bundle-id');22 var bundled_item_id = $(this).attr('data-bundled-item-id');23 $(this).find( '.bundled_item_wrap input[name="variation_id"]').each(function(){24 if ( $(this).val() == '' ) {25 $( '.bundle_form_' + bundle_id + ' .bundle_wrap' ).find('input[name="variation_id['+ bundled_item_id +']"]').val('');26 $( '.bundle_form_' + bundle_id + ' .bundle_wrap' ).slideUp('200');27 }28 });29 } );30 function attempt_show_bundle( bundle_id ) {31 var all_set = true;32 $('#product-' + bundle_id + ' .variations select').each(function(){33 if ($(this).val().length == 0) {34 all_set = false;35 }36 });37 if (all_set) {38 var bundle_price_data = window[ "bundle_price_data_" + bundle_id ];39 var bundled_item_quantities = window[ "bundled_item_quantities_" + bundle_id ];40 if ( (bundle_price_data['per_product_pricing'] == false) && (bundle_price_data['total'] == -1) ) return;41 if ( bundle_price_data['per_product_pricing'] == true ) {42 bundle_price_data['total'] = 0;43 bundle_price_data['regular_total'] = 0;44 for ( prod_id in bundle_price_data['prices'] ) {45 bundle_price_data['total'] += bundle_price_data['prices'][prod_id] * bundled_item_quantities[prod_id];46 bundle_price_data['regular_total'] += bundle_price_data['regular_prices'][prod_id] * bundled_item_quantities[prod_id];47 }48 }49 if ( bundle_price_data['total'] == 0 )50 $('.bundle_form_' + bundle_id + ' .bundle_price').html('<p class="price"><span class="total">' + bundle_price_data['total_description'] + '</span>'+ bundle_price_data['free'] +'</p>');51 else {52 var sales_price = number_format ( bundle_price_data['total'], bundle_price_data['woocommerce_price_num_decimals'], bundle_price_data['woocommerce_price_decimal_sep'], bundle_price_data['woocommerce_price_thousand_sep'] );53 var regular_price = number_format ( bundle_price_data['regular_total'], bundle_price_data['woocommerce_price_num_decimals'], bundle_price_data['woocommerce_price_decimal_sep'], bundle_price_data['woocommerce_price_thousand_sep'] );54 var remove = bundle_price_data['woocommerce_price_decimal_sep'];55 if ( bundle_price_data['woocommerce_price_trim_zeros'] == 'yes' && bundle_price_data['woocommerce_price_num_decimals'] > 0 ) {56 for (var i = 0; i < bundle_price_data['woocommerce_price_num_decimals']; i++) { remove = remove + '0'; }57 sales_price = sales_price.replace(remove, '');58 regular_price = regular_price.replace(remove, '');59 }60 var sales_price_format = '';61 var regular_price_format = '';62 if ( bundle_price_data['woocommerce_currency_pos'] == 'left' ) {63 sales_price_format = '<span class="amount">' + bundle_price_data['currency_symbol'] + sales_price + '</span>';64 regular_price_format = '<span class="amount">' + bundle_price_data['currency_symbol'] + regular_price + '</span>'; }65 else if ( bundle_price_data['woocommerce_currency_pos'] == 'right' ) {66 sales_price_format = '<span class="amount">' + sales_price + bundle_price_data['currency_symbol'] + '</span>';67 regular_price_format = '<span class="amount">' + regular_price + bundle_price_data['currency_symbol'] + '</span>'; }68 else if ( bundle_price_data['woocommerce_currency_pos'] == 'left_space' ) {69 sales_price_format = '<span class="amount">' + bundle_price_data['currency_symbol'] + ' ' + sales_price + '</span>';70 regular_price_format = '<span class="amount">' + bundle_price_data['currency_symbol'] + ' ' + regular_price + '</span>'; }71 else if ( bundle_price_data['woocommerce_currency_pos'] == 'right_space' ) {72 sales_price_format = '<span class="amount">' + sales_price + ' ' + bundle_price_data['currency_symbol'] + '</span>';73 regular_price_format = '<span class="amount">' + regular_price + ' ' + bundle_price_data['currency_symbol'] + '</span>'; }74 if ( bundle_price_data['regular_total'] > bundle_price_data['total'] ) {75 $('.bundle_form_' + bundle_id + ' .bundle_price').html('<p class="price"><span class="total">' + bundle_price_data['total_description'] + '</span><del>' + regular_price_format +'</del> <ins>'+ sales_price_format +'</ins></p>');76 } else {77 $('.bundle_form_' + bundle_id + ' .bundle_price').html('<p class="price"><span class="total">' + bundle_price_data['total_description'] + '</span>'+ sales_price_format +'</p>');78 }79 }80 // reset bundle stock status81 $('.bundle_form_' + bundle_id + ' .bundle_wrap p.stock').replaceWith( bundle_stock_status[bundle_id] );82 // set bundle stock status as out of stock if any selected variation is out of stock83 $('#product-' + bundle_id + ' .variations_form').each(function(){84 if ( $(this).find('.variations').length > 0 ) {85 var $item_stock_p = $(this).find('p.stock');86 if ( $item_stock_p.hasClass('out-of-stock') ) {87 if ( $('.bundle_form_' + bundle_id + ' .bundle_wrap p.stock').length > 0 ) {88 $('.bundle_form_' + bundle_id + ' .bundle_wrap p.stock').replaceWith( $item_stock_p.clone() );89 } else {90 $('.bundle_form_' + bundle_id + ' .bundle_wrap .bundle_price').after( $item_stock_p.clone() );91 }92 }93 }94 });95 $('.bundle_form_' + bundle_id + ' .bundle_wrap').slideDown('200').trigger('show_bundle');96 }97 }98 function check_all_simple( bundle_id ) {99 var bundle_price_data = window[ "bundle_price_data_" + bundle_id ];100 var bundle_variations = window[ "bundle_variations_" + bundle_id ];101 if ( typeof bundle_price_data == 'undefined' ) { return false; }102 if ( bundle_price_data['prices'].length < 1 ) { return false; }103 if ( $( '.bundle_form_' + bundle_id + ' input[value="variable"]' ).length > 0 ) {104 return false;105 }106 return true;107 }108 /**109 * Initial states and loading110 */111 var bundle_stock_status = [];112 $('.bundle_form').each( function() {113 var bundle_id = $(this).attr('data-bundle-id');114 if ( $(this).find('.bundle_wrap p.stock').length > 0 )115 bundle_stock_status[bundle_id] = $(this).find('.bundle_wrap p.stock').clone().wrap('<p>').parent().html();116 $('#product-' + bundle_id + ' .variations select').change();117 if ( check_all_simple( bundle_id ) )118 attempt_show_bundle( bundle_id );119 });120 /**121 * Helper functions for variations122 */123 function number_format( number, decimals, dec_point, thousands_sep ) {124 var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;125 var d = dec_point == undefined ? "," : dec_point;126 var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";127 var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;128 return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");129 }...
ResourceBundle.js
Source:ResourceBundle.js
1Clazz.load(null,"java.util.ResourceBundle",["java.lang.NullPointerException","java.util.Enumeration","$.MissingResourceException","net.sf.j2s.ajax.HttpRequest"],function(){2c$=Clazz.decorateAsClass(function(){3this.parent=null;4this.locale=null;5this.bundleName=null;6Clazz.instantialize(this,arguments);7},java.util,"ResourceBundle");8Clazz.makeConstructor(c$,9function(){10});11Clazz.defineMethod(c$,"getString",12function(key){13return this.getObject(key);14},"~S");15Clazz.defineMethod(c$,"getStringArray",16function(key){17return this.getObject(key);18},"~S");19Clazz.defineMethod(c$,"getObject",20function(key){21var obj=this.handleGetObject(key);22if(obj==null){23if(this.parent!=null){24obj=this.parent.getObject(key);25}if(obj==null)throw new java.util.MissingResourceException("Can't find resource for bundle "+this.getClass().getName()+", key "+key,this.getClass().getName(),key);26}return obj;27},"~S");28Clazz.defineMethod(c$,"getLocale",29function(){30return this.locale;31});32Clazz.defineMethod(c$,"setParent",33function(parent){34this.parent=parent;35},"java.util.ResourceBundle");36c$.getBundle=Clazz.defineMethod(c$,"getBundle",37function(baseName){38return java.util.ResourceBundle.getBundleImpl(baseName,null,null);39},"~S");40c$.getBundle=Clazz.defineMethod(c$,"getBundle",41function(baseName,locale){42return java.util.ResourceBundle.getBundleImpl(baseName,locale,null);43},"~S,java.util.Locale");44c$.getBundle=Clazz.defineMethod(c$,"getBundle",45function(baseName,locale,loader){46if(loader==null){47throw new NullPointerException();48}return java.util.ResourceBundle.getBundleImpl(baseName,locale,loader);49},"~S,java.util.Locale,ClassLoader");50c$.getBundleImpl=Clazz.defineMethod(c$,"getBundleImpl",51($fz=function(baseName,locale,loader){52if(baseName==null){53throw new NullPointerException();54}for(var i=0;i<java.util.ResourceBundle.caches.length;i++){55if(java.util.ResourceBundle.caches[i].bundleName===baseName){56return java.util.ResourceBundle.caches[i];57}}58var bundle=new java.util.ResourceBundle.TextResourceBundle(baseName);59java.util.ResourceBundle.caches[java.util.ResourceBundle.caches.length]=bundle;60return bundle;61},$fz.isPrivate=true,$fz),"~S,java.util.Locale,ClassLoader");62c$.registerBundle=Clazz.defineMethod(c$,"registerBundle",63function(baseName,content){64for(var i=0;i<java.util.ResourceBundle.caches.length;i++){65if(java.util.ResourceBundle.caches[i].bundleName===baseName){66return;67}}68java.util.ResourceBundle.caches[java.util.ResourceBundle.caches.length]=new java.util.ResourceBundle.TextResourceBundle(baseName,content);69},"~S,~S");70Clazz.pu$h(self.c$);71c$=Clazz.decorateAsClass(function(){72this.map=null;73this.keys=null;74this.content=null;75this.initialized=false;76Clazz.instantialize(this,arguments);77},java.util.ResourceBundle,"TextResourceBundle",java.util.ResourceBundle);78Clazz.prepareFields(c$,function(){79this.map=new Array(0);80this.keys=new Array(0);81});82Clazz.makeConstructor(c$,83function(a){84Clazz.superConstructor(this,java.util.ResourceBundle.TextResourceBundle,[]);85this.bundleName=a;86},"~S");87Clazz.makeConstructor(c$,88function(a,b){89Clazz.superConstructor(this,java.util.ResourceBundle.TextResourceBundle,[]);90this.bundleName=a;91this.content=b;92},"~S,~S");93Clazz.defineMethod(c$,"evalString",94function(a){95var r=new Array();96var b=false;97var x=0;98for(var i=0;i<a.length;i++){99var c=a.charAt(i);100if(b){101if(c=='f') r[r.length] = '\f';102else if(c=='t') r[r.length] = '\t';103else if(c=='r') r[r.length] = '\r';104else if(c=='n') r[r.length] = '\n';105else if(c=='\'') r[r.length] = '\'';106else if(c=='\"') r[r.length] = '\"';107else if(c=='\\') r[r.length] = '\\';108else if(c=='u'){109r[r.length]=eval("\"\\u"+a.substring(i+1,i+5)+"\"");110i+=4;111}112x=i+1;113b=false;114}else if(c=='\\'){115if(x!=i){116r[r.length]=a.substring(x,i);117}118b=true;119}120}121if(!b){122r[r.length]=a.substring(x,a.length);123}124return r.join('');125},"~S");126Clazz.defineMethod(c$,"initBundle",127($fz=function(){128if(this.initialized){129return;130}this.initialized=true;131var a=null;132var b=this.bundleName;133if(this.content==null){134var n=b.replace(/\./g,'/')+".properties";135var p=Clazz.binaryFolders;136if(p==null){137p=["bin","","j2slib"];138}139var r=new net.sf.j2s.ajax.HttpRequest();140var x=0;141while(a==null&&x<p.length){142var q=p[x];143if(q.length>0&&q.lastIndexOf("/")!=q.length-1){144q+="/";145}146try{147r.open("GET",q+n,false);148r.send();149a=r.getResponseText();150}catch(e){151r=new net.sf.j2s.ajax.HttpRequest();152}153x++;154}155}if(this.content==null){156this.content=a;157}if(this.content==null){158return;159}var c=this.content.$plit("\n");160for(var d=0;d<c.length;d++){161var e=c[d].trim();162if(!e.startsWith("#")){163var f=e.indexOf('=');164if(f!=-1){165var g=e.substring(0,f).trim();166var h=e.substring(f+1).trim();167if(h.indexOf('\\')!=-1){168h=this.evalString(h);169}var i=this.map;170var j=this.keys;171{172if(i[g]==null){173j[j.length]=g;174}175i[g]=h;176}}}}177},$fz.isPrivate=true,$fz));178Clazz.overrideMethod(c$,"getKeys",179function(){180return((Clazz.isClassDefined("java.util.ResourceBundle$TextResourceBundle$1")?0:java.util.ResourceBundle.TextResourceBundle.$ResourceBundle$TextResourceBundle$1$()),Clazz.innerTypeInstance(java.util.ResourceBundle$TextResourceBundle$1,this,null));181});182Clazz.overrideMethod(c$,"handleGetObject",183function(a){184if(!this.initialized){185this.initBundle();186}var b=this.map;187{188return b[a];189}return b;190},"~S");191c$.$ResourceBundle$TextResourceBundle$1$=function(){192Clazz.pu$h(self.c$);193c$=Clazz.decorateAsClass(function(){194Clazz.prepareCallback(this,arguments);195this.index=-1;196Clazz.instantialize(this,arguments);197},java.util,"ResourceBundle$TextResourceBundle$1",null,java.util.Enumeration);198Clazz.overrideMethod(c$,"nextElement",199function(){200this.index++;201return this.b$["java.util.ResourceBundle.TextResourceBundle"].keys[this.index];202});203Clazz.overrideMethod(c$,"hasMoreElements",204function(){205return this.index<this.b$["java.util.ResourceBundle.TextResourceBundle"].keys.length-1;206});207c$=Clazz.p0p();208};209c$=Clazz.p0p();210c$.caches=c$.prototype.caches=new Array(0);
...
legacyModule.js
Source:legacyModule.js
1dojo.provide("i18nTest.legacyModule");2dojo.requireLocalization("i18nTest", "amdBundle");3dojo.requireLocalization("i18nTest", "legacyBundle");4i18nTest.legacyModule = function(){5 var legacyBundle = dojo.i18n.getLocalization("i18nTest", "legacyBundle"),6 amdBundle = dojo.i18n.getLocalization("i18nTest", "amdBundle"),7 result = [];8 if(amdBundle.rootValueOnly!="rootValueOnly"){9 result.push('amdBundle.rootValueOnly!="rootValueOnly"');10 }11 switch(dojo.locale){12 case "ab":13 case "ab-cd":14 if(amdBundle.amdBundle!="amdBundle-ab"){15 result.push('amdBundle.amdBundle!="amdBundle-ab"');16 }17 if(amdBundle.abValueOnly!="abValueOnly"){18 result.push('amdBundle.abValueOnly!="abValueOnly"');19 }20 break;21 case "ab-cd-ef":22 if(amdBundle.amdBundle!="amdBundle-ab-cd-ef"){23 result.push('amdBundle.amdBundle!="amdBundle-ab-cd-ef"');24 }25 if(amdBundle.abValueOnly!="abValueOnly"){26 result.push('amdBundle.abValueOnly!="abValueOnly"');27 }28 if(amdBundle.abCdEfValueOnly!="abCdEfValueOnly"){29 result.push('amdBundle.abCdEfValueOnly!="abCdEfValueOnly"');30 }31 break;32 default:33 if(amdBundle.amdBundle!="amdBundle"){34 result.push('amdBundle.amdBundle!="amdBundle"');35 }36 }37 if(legacyBundle.rootValueOnly!="rootValueOnly"){38 result.push('legacyBundle.rootValueOnly!="rootValueOnly"');39 }40 switch(dojo.locale){41 case "ab":42 case "ab-cd":43 if(legacyBundle.legacyBundle!="legacyBundle-ab"){44 result.push('legacyBundle.legacyBundle!="legacyBundle-ab"');45 }46 if(legacyBundle.abValueOnly!="abValueOnly"){47 result.push('legacyBundle.abValueOnly!="abValueOnly"');48 }49 break;50 case "ab-cd-ef":51 if(legacyBundle.legacyBundle!="legacyBundle-ab-cd-ef"){52 result.push('legacyBundle.legacyBundle!="legacyBundle-ab-cd-ef"');53 }54 if(legacyBundle.abValueOnly!="abValueOnly"){55 result.push('legacyBundle.abValueOnly!="abValueOnly"');56 }57 if(legacyBundle.abCdEfValueOnly!="abCdEfValueOnly"){58 result.push('legacyBundle.abCdEfValueOnly!="abCdEfValueOnly"');59 }60 break;61 default:62 if(legacyBundle.legacyBundle!="legacyBundle"){63 result.push('legacyBundle.legacyBundle!="legacyBundle"');64 }65 }66 var i18n= require("dojo/i18n");67 for(var p in i18n._cache) console.log(p);68 return result.length==0 ? true : result.join(";");...
test_bug378839.js
Source:test_bug378839.js
1/* Tests getting properties from string bundles2 */3const name_file = "file";4const value_file = "File";5const name_loyal = "loyal";6const value_loyal = "\u5fe0\u5fc3"; // tests escaped Unicode7const name_trout = "trout";8const value_trout = "\u9cdf\u9b5a"; // tests UTF-89const name_edit = "edit";10const value_edit = "Edit"; // tests literal leading spaces are stripped11const name_view = "view";12const value_view = "View"; // tests literal trailing spaces are stripped13const name_go = "go";14const value_go = " Go"; // tests escaped leading spaces are not stripped15const name_message = "message";16const value_message = "Message "; // tests escaped trailing spaces are not stripped17const name_hello = "hello";18const var_hello = "World";19const value_hello = "Hello World"; // tests formatStringFromName with parameter20function run_test() {21 var StringBundle = 22 Components.classes["@mozilla.org/intl/stringbundle;1"]23 .getService(Components.interfaces.nsIStringBundleService);24 var ios = Components.classes["@mozilla.org/network/io-service;1"]25 .getService(Components.interfaces.nsIIOService);26 var bundleURI = ios.newFileURI(do_get_file("strres.properties"));27 var bundle = StringBundle.createBundle(bundleURI.spec);28 var bundle_file = bundle.GetStringFromName(name_file);29 do_check_eq(bundle_file, value_file);30 var bundle_loyal = bundle.GetStringFromName(name_loyal);31 do_check_eq(bundle_loyal, value_loyal);32 var bundle_trout = bundle.GetStringFromName(name_trout);33 do_check_eq(bundle_trout, value_trout);34 var bundle_edit = bundle.GetStringFromName(name_edit);35 do_check_eq(bundle_edit, value_edit);36 var bundle_view = bundle.GetStringFromName(name_view);37 do_check_eq(bundle_view, value_view);38 var bundle_go = bundle.GetStringFromName(name_go);39 do_check_eq(bundle_go, value_go);40 var bundle_message = bundle.GetStringFromName(name_message);41 do_check_eq(bundle_message, value_message);42 var bundle_hello = bundle.formatStringFromName(name_hello, [var_hello], 1);43 do_check_eq(bundle_hello, value_hello);44}...
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var bundle = stf.bundle;3var path = require('path');4var bundlePath = path.join(__dirname, 'test.bundle');5var bundleId = 'test.bundle';6var bundleVersion = '1.0.0';7bundle(bundlePath, bundleId, bundleVersion, function(err, result) {8 if (err) {9 console.log(err);10 } else {11 console.log(result);12 }13});14{15 {16 "source": "var a = 1;"17 },18 {19 "source": "var a = 2;"20 }21}22{23 {24 "source": "var a = 1;"25 },26 {27 "source": "var a = 2;"28 }29}30{31 {32 "source": "var a = 1;"33 },34 {35 "source": "var a = 2;"36 }37}38{39 {40 "source": "var a = 1;"41 },42 {43 "source": "var a = 2;"44 }45}46{
Using AI Code Generation
1var stf = require('devicefarmer-stf');2var stfClient = stf.createClient();3stfClient.bundle(function(err, data){4 console.log(data);5});6var stf = require('devicefarmer-stf');7var stfClient = stf.createClient();8stfClient.install(function(err, data){9 console.log(data);10});11var stf = require('devicefarmer-stf');12var stfClient = stf.createClient();13stfClient.restart(function(err, data){14 console.log(data);15});16var stf = require('devicefarmer-stf');17var stfClient = stf.createClient();18stfClient.uninstall(function(err, data){19 console.log(data);20});21var stf = require('devicefarmer-stf');22var stfClient = stf.createClient();23stfClient.list(function(err, data){24 console.log(data);25});26var stf = require('devicefarmer-stf');27var stfClient = stf.createClient();28stfClient.info(function(err, data){29 console.log(data);30});31var stf = require('devicefarmer-stf');32var stfClient = stf.createClient();33stfClient.logs(function(err, data){34 console.log(data);35});36var stf = require('devicefarmer-stf');37var stfClient = stf.createClient();38stfClient.screenshot(function(err, data){39 console.log(data);40});41var stf = require('devicefarmer-stf');42var stfClient = stf.createClient();43stfClient.screenrecord(function(err, data){44 console.log(data);45});
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var deviceInfo = device.getInfo();3var bundle = device.bundle(deviceInfo.serial, '/Users/username/Desktop/test.apk');4bundle.then(function (data) {5 console.log(data);6}).catch(function (err) {7 console.log(err);8});9var stf = require('devicefarmer-stf-client');10var deviceInfo = device.getInfo();11var install = device.install(deviceInfo.serial, '/Users/username/Desktop/test.apk');12install.then(function (data) {13 console.log(data);14}).catch(function (err) {15 console.log(err);16});17var stf = require('devicefarmer-stf-client');18var deviceInfo = device.getInfo();19var uninstall = device.uninstall(deviceInfo.serial, 'com.example.test');20uninstall.then(function (data) {21 console.log(data);22}).catch(function (err) {23 console.log(err);24});25var stf = require('devicefarmer-stf-client');26var deviceInfo = device.getInfo();27var start = device.start(deviceInfo.serial, 'com.example.test');28start.then(function (data) {29 console.log(data);30}).catch(function (err) {31 console.log(err);32});33var stf = require('devicefarmer-stf-client');34var deviceInfo = device.getInfo();35var stop = device.stop(deviceInfo.serial, 'com.example.test');36stop.then(function (data) {37 console.log(data);38}).catch(function (err) {39 console.log(err);40});41var stf = require('devicefarmer-stf-client');
Using AI Code Generation
1var client = require('devicefarmer-stf-client');2var bundle = device.bundle('bundleId');3bundle.install('path/to/bundle.ipa', function(err) {4 if(err) {5 console.error(err);6 } else {7 console.log('Bundle installed');8 }9});10bundle.uninstall(function(err) {11 if(err) {12 console.error(err);13 } else {14 console.log('Bundle uninstalled');15 }16});17var client = require('devicefarmer-stf-client');18var bundle = device.bundle('bundleId');19bundle.install('path/to/bundle.ipa', function(err) {20 if(err) {21 console.error(err);22 } else {23 console.log('Bundle installed');24 }25});26bundle.uninstall(function(err) {27 if(err) {28 console.error(err);29 } else {30 console.log('Bundle uninstalled');31 }32});33var client = require('devicefarmer-stf-client');34var bundle = device.bundle('bundleId');35bundle.install('path/to/bundle.ipa', function(err) {36 if(err) {37 console.error(err);38 } else {39 console.log('Bundle installed');40 }41});42bundle.uninstall(function(err) {43 if(err) {44 console.error(err);45 } else {46 console.log('Bundle uninstalled');47 }48});49var client = require('devicefarmer-stf-client');50var bundle = device.bundle('bundleId');51bundle.install('path/to/bundle.ipa', function(err) {52 if(err) {53 console.error(err);54 } else {55 console.log('Bundle installed');56 }57});58bundle.uninstall(function(err) {59 if(err) {60 console.error(err);61 } else {62 console.log('Bundle uninstalled');63 }64});
Using AI Code Generation
1const { STFClient } = require('devicefarmer-stf-client');2const client = new STFClient();3const device = await client.getDevice('device id');4const bundle = await device.bundle('bundle id');5await bundle.install();6await bundle.launch();7await bundle.uninstall();8await bundle.stop();9await bundle.restart();10await bundle.open('url');11await bundle.close();12await bundle.clear();13await bundle.clearData();14await bundle.clearCache();15await bundle.clearCookies();16await bundle.clearHistory();17await bundle.clearPasswords();18await bundle.clearFormData();19await bundle.clearGeoLocation();20await bundle.clearSearchHistory();21await bundle.clearSearchSuggestions();22await bundle.clearWebStorage();23await bundle.clearWebSQL();
Using AI Code Generation
1var client = require('devicefarmer-stf-client');2var device = client.device;3device.bundle('com.example.testapp', function(err, bundle) {4 console.log('bundle', bundle);5});6var client = require('devicefarmer-stf-client');7var device = client.device;8device.screenshot(function(err, screenshot) {9 console.log('screenshot', screenshot);10});11var client = require('devicefarmer-stf-client');12var device = client.device;13device.install('/path/to/my.apk', function(err, install) {14 console.log('install', install);15});16var client = require('devicefarmer-stf-client');17var device = client.device;18device.uninstall('com.example.testapp', function(err, uninstall) {19 console.log('uninstall', uninstall);20});21var client = require('devicefarmer-stf-client');22var device = client.device;23device.forward('tcp:8100', 'localabstract:webview_devtools_remote', function(err, forward) {24 console.log('forward', forward);25});26var client = require('devicefarmer-stf-client');27var device = client.device;28device.reverse('tcp:8100', 'localabstract:webview_devtools_remote', function(err, reverse) {29 console.log('reverse', reverse);30});31var client = require('devicefarmer-stf-client');32var device = client.device;33device.push('/path/to/my.file', '/path/to/my.file', function(err, push) {34 console.log('push', push);35});36var client = require('devicefarmer-stf-client');37var device = client.device;38device.pull('/path/to/my.file', '/path/to/my.file', function(err, pull) {39 console.log('pull', pull
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!