Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. 'License'); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. /*
  18. this file is found by cordova-lib when you attempt to
  19. 'cordova platform add PATH' where path is this repo.
  20. */
  21. var shell = require('shelljs');
  22. var path = require('path');
  23. var fs = require('fs');
  24. var cdvcmn = require('cordova-common');
  25. var CordovaLogger = cdvcmn.CordovaLogger;
  26. var ConfigParser = cdvcmn.ConfigParser;
  27. var ActionStack = cdvcmn.ActionStack;
  28. var selfEvents = cdvcmn.events;
  29. var xmlHelpers = cdvcmn.xmlHelpers;
  30. var PlatformJson = cdvcmn.PlatformJson;
  31. var PlatformMunger = cdvcmn.ConfigChanges.PlatformMunger;
  32. var PluginInfoProvider = cdvcmn.PluginInfoProvider;
  33. var BrowserParser = require('./browser_parser');
  34. var PLATFORM_NAME = 'browser';
  35. function setupEvents (externalEventEmitter) {
  36. if (externalEventEmitter) {
  37. // This will make the platform internal events visible outside
  38. selfEvents.forwardEventsTo(externalEventEmitter);
  39. return externalEventEmitter;
  40. }
  41. // There is no logger if external emitter is not present,
  42. // so attach a console logger
  43. CordovaLogger.get().subscribe(selfEvents);
  44. return selfEvents;
  45. }
  46. function Api (platform, platformRootDir, events) {
  47. this.platform = platform || PLATFORM_NAME;
  48. // MyApp/platforms/browser
  49. this.root = path.resolve(__dirname, '..');
  50. this.events = setupEvents(events);
  51. this.parser = new BrowserParser(this.root);
  52. this._handler = require('./browser_handler');
  53. this.locations = {
  54. platformRootDir: platformRootDir,
  55. root: this.root,
  56. www: path.join(this.root, 'www'),
  57. res: path.join(this.root, 'res'),
  58. platformWww: path.join(this.root, 'platform_www'),
  59. configXml: path.join(this.root, 'config.xml'),
  60. defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),
  61. build: path.join(this.root, 'build'),
  62. // NOTE: Due to platformApi spec we need to return relative paths here
  63. cordovaJs: 'bin/templates/project/assets/www/cordova.js',
  64. cordovaJsSrc: 'cordova-js-src'
  65. };
  66. this._platformJson = PlatformJson.load(this.root, platform);
  67. this._pluginInfoProvider = new PluginInfoProvider();
  68. this._munger = new PlatformMunger(platform, this.root, this._platformJson, this._pluginInfoProvider);
  69. }
  70. Api.createPlatform = function (dest, config, options, events) {
  71. var creator = require('../../lib/create');
  72. events = setupEvents(events);
  73. var name = 'HelloCordova';
  74. var id = 'io.cordova.hellocordova';
  75. if (config) {
  76. name = config.name();
  77. id = config.packageName();
  78. }
  79. var result;
  80. try {
  81. // we create the project using our scripts in this platform
  82. result = creator.createProject(dest, id, name, options)
  83. .then(function () {
  84. // after platform is created we return Api instance based on new Api.js location
  85. // Api.js has been copied to the new project
  86. // This is required to correctly resolve paths in the future api calls
  87. var PlatformApi = require(path.resolve(dest, 'cordova/Api'));
  88. return new PlatformApi('browser', dest, events);
  89. });
  90. } catch (e) {
  91. events.emit('error', 'createPlatform is not callable from the browser project API.');
  92. throw (e);
  93. }
  94. return result;
  95. };
  96. Api.updatePlatform = function (dest, options, events) {
  97. // console.log("test-platform:Api:updatePlatform");
  98. // todo?: create projectInstance and fulfill promise with it.
  99. return Promise.resolve();
  100. };
  101. Api.prototype.getPlatformInfo = function () {
  102. // console.log("browser-platform:Api:getPlatformInfo");
  103. // return PlatformInfo object
  104. return {
  105. 'locations': this.locations,
  106. 'root': this.root,
  107. 'name': this.platform,
  108. 'version': { 'version': '1.0.0' }, // um, todo!
  109. 'projectConfig': this.config
  110. };
  111. };
  112. Api.prototype.prepare = function (cordovaProject, options) {
  113. // First cleanup current config and merge project's one into own
  114. var defaultConfigPath = path.join(this.locations.platformRootDir, 'cordova',
  115. 'defaults.xml');
  116. var ownConfigPath = this.locations.configXml;
  117. var sourceCfg = cordovaProject.projectConfig;
  118. // If defaults.xml is present, overwrite platform config.xml with it.
  119. // Otherwise save whatever is there as defaults so it can be
  120. // restored or copy project config into platform if none exists.
  121. if (fs.existsSync(defaultConfigPath)) {
  122. this.events.emit('verbose', 'Generating config.xml from defaults for platform "' + this.platform + '"');
  123. shell.cp('-f', defaultConfigPath, ownConfigPath);
  124. } else if (fs.existsSync(ownConfigPath)) {
  125. this.events.emit('verbose', 'Generating defaults.xml from own config.xml for platform "' + this.platform + '"');
  126. shell.cp('-f', ownConfigPath, defaultConfigPath);
  127. } else {
  128. this.events.emit('verbose', 'case 3"' + this.platform + '"');
  129. shell.cp('-f', sourceCfg.path, ownConfigPath);
  130. }
  131. // merge our configs
  132. this.config = new ConfigParser(ownConfigPath);
  133. xmlHelpers.mergeXml(cordovaProject.projectConfig.doc.getroot(),
  134. this.config.doc.getroot(),
  135. this.platform, true);
  136. this.config.write();
  137. // Update own www dir with project's www assets and plugins' assets and js-files
  138. this.parser.update_www(cordovaProject, options);
  139. // Copy or Create manifest.json
  140. // todo: move this to a manifest helper module
  141. // output path
  142. var manifestPath = path.join(this.locations.www, 'manifest.json');
  143. var srcManifestPath = path.join(cordovaProject.locations.www, 'manifest.json');
  144. if (fs.existsSync(srcManifestPath)) {
  145. // just blindly copy it to our output/www
  146. // todo: validate it? ensure all properties we expect exist?
  147. this.events.emit('verbose', 'copying ' + srcManifestPath + ' => ' + manifestPath);
  148. shell.cp('-f', srcManifestPath, manifestPath);
  149. } else {
  150. var manifestJson = {
  151. 'background_color': '#FFF',
  152. 'display': 'standalone'
  153. };
  154. if (this.config) {
  155. if (this.config.name()) {
  156. manifestJson.name = this.config.name();
  157. }
  158. if (this.config.shortName()) {
  159. manifestJson.short_name = this.config.shortName();
  160. }
  161. if (this.config.packageName()) {
  162. manifestJson.version = this.config.packageName();
  163. }
  164. if (this.config.description()) {
  165. manifestJson.description = this.config.description();
  166. }
  167. if (this.config.author()) {
  168. manifestJson.author = this.config.author();
  169. }
  170. // icons
  171. var icons = this.config.getStaticResources('browser', 'icon');
  172. var manifestIcons = icons.map(function (icon) {
  173. // given a tag like this :
  174. // <icon src="res/ios/icon.png" width="57" height="57" density="mdpi" />
  175. /* configParser returns icons that look like this :
  176. { src: 'res/ios/icon.png',
  177. target: undefined,
  178. density: 'mdpi',
  179. platform: null,
  180. width: 57,
  181. height: 57
  182. } ******/
  183. /* manifest expects them to be like this :
  184. { "src": "images/touch/icon-128x128.png",
  185. "type": "image/png",
  186. "sizes": "128x128"
  187. } ******/
  188. // ?Is it worth looking at file extentions?
  189. return { 'src': icon.src,
  190. 'type': 'image/png',
  191. 'sizes': (icon.width + 'x' + icon.height) };
  192. });
  193. manifestJson.icons = manifestIcons;
  194. // orientation
  195. // <preference name="Orientation" value="landscape" />
  196. var oriPref = this.config.getGlobalPreference('Orientation');
  197. if (oriPref) {
  198. // if it's a supported value, use it
  199. if (['landscape', 'portrait'].indexOf(oriPref) > -1) {
  200. manifestJson.orientation = oriPref;
  201. } else { // anything else maps to 'any'
  202. manifestJson.orientation = 'any';
  203. }
  204. }
  205. // get start_url
  206. var contentNode = this.config.doc.find('content') || { 'attrib': { 'src': 'index.html' } }; // sensible default
  207. manifestJson.start_url = contentNode.attrib.src;
  208. // now we get some values from start_url page ...
  209. var startUrlPath = path.join(cordovaProject.locations.www, manifestJson.start_url);
  210. if (fs.existsSync(startUrlPath)) {
  211. var contents = fs.readFileSync(startUrlPath, 'utf-8');
  212. // matches <meta name="theme-color" content="#FF0044">
  213. var themeColorRegex = /<meta(?=[^>]*name="theme-color")\s[^>]*content="([^>]*)"/i;
  214. var result = themeColorRegex.exec(contents);
  215. var themeColor;
  216. if (result && result.length >= 2) {
  217. themeColor = result[1];
  218. } else { // see if there is a preference in config.xml
  219. // <preference name="StatusBarBackgroundColor" value="#000000" />
  220. themeColor = this.config.getGlobalPreference('StatusBarBackgroundColor');
  221. }
  222. if (themeColor) {
  223. manifestJson.theme_color = themeColor;
  224. }
  225. }
  226. }
  227. fs.writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 2), 'utf8');
  228. }
  229. // update project according to config.xml changes.
  230. return this.parser.update_project(this.config, options);
  231. };
  232. Api.prototype.addPlugin = function (pluginInfo, installOptions) {
  233. // console.log(new Error().stack);
  234. if (!pluginInfo) {
  235. return Promise.reject(new Error('The parameter is incorrect. The first parameter ' +
  236. 'should be valid PluginInfo instance'));
  237. }
  238. installOptions = installOptions || {};
  239. installOptions.variables = installOptions.variables || {};
  240. // CB-10108 platformVersion option is required for proper plugin installation
  241. installOptions.platformVersion = installOptions.platformVersion ||
  242. this.getPlatformInfo().version;
  243. var self = this;
  244. var actions = new ActionStack();
  245. var projectFile = this._handler.parseProjectFile && this._handler.parseProjectFile(this.root);
  246. // gather all files needs to be handled during install
  247. pluginInfo.getFilesAndFrameworks(this.platform)
  248. .concat(pluginInfo.getAssets(this.platform))
  249. .concat(pluginInfo.getJsModules(this.platform))
  250. .forEach(function (item) {
  251. actions.push(actions.createAction(
  252. self._getInstaller(item.itemType),
  253. [item, pluginInfo.dir, pluginInfo.id, installOptions, projectFile],
  254. self._getUninstaller(item.itemType),
  255. [item, pluginInfo.dir, pluginInfo.id, installOptions, projectFile]));
  256. });
  257. // run through the action stack
  258. return actions.process(this.platform, this.root)
  259. .then(function () {
  260. if (projectFile) {
  261. projectFile.write();
  262. }
  263. // Add PACKAGE_NAME variable into vars
  264. if (!installOptions.variables.PACKAGE_NAME) {
  265. installOptions.variables.PACKAGE_NAME = self._handler.package_name(self.root);
  266. }
  267. self._munger
  268. // Ignore passed `is_top_level` option since platform itself doesn't know
  269. // anything about managing dependencies - it's responsibility of caller.
  270. .add_plugin_changes(pluginInfo, installOptions.variables, /* is_top_level= */true, /* should_increment= */true)
  271. .save_all();
  272. var targetDir = installOptions.usePlatformWww ?
  273. self.getPlatformInfo().locations.platformWww :
  274. self.getPlatformInfo().locations.www;
  275. self._addModulesInfo(pluginInfo, targetDir);
  276. });
  277. };
  278. Api.prototype.removePlugin = function (plugin, uninstallOptions) {
  279. // console.log("NotImplemented :: browser-platform:Api:removePlugin ",plugin, uninstallOptions);
  280. uninstallOptions = uninstallOptions || {};
  281. // CB-10108 platformVersion option is required for proper plugin installation
  282. uninstallOptions.platformVersion = uninstallOptions.platformVersion ||
  283. this.getPlatformInfo().version;
  284. var self = this;
  285. var actions = new ActionStack();
  286. var projectFile = this._handler.parseProjectFile && this._handler.parseProjectFile(this.root);
  287. // queue up plugin files
  288. plugin.getFilesAndFrameworks(this.platform)
  289. .concat(plugin.getAssets(this.platform))
  290. .concat(plugin.getJsModules(this.platform))
  291. .forEach(function (item) {
  292. actions.push(actions.createAction(
  293. self._getUninstaller(item.itemType), [item, plugin.dir, plugin.id, uninstallOptions, projectFile],
  294. self._getInstaller(item.itemType), [item, plugin.dir, plugin.id, uninstallOptions, projectFile]));
  295. });
  296. // run through the action stack
  297. return actions.process(this.platform, this.root)
  298. .then(function () {
  299. if (projectFile) {
  300. projectFile.write();
  301. }
  302. self._munger
  303. // Ignore passed `is_top_level` option since platform itself doesn't know
  304. // anything about managing dependencies - it's responsibility of caller.
  305. .remove_plugin_changes(plugin, /* is_top_level= */true)
  306. .save_all();
  307. var targetDir = uninstallOptions.usePlatformWww ?
  308. self.getPlatformInfo().locations.platformWww :
  309. self.getPlatformInfo().locations.www;
  310. self._removeModulesInfo(plugin, targetDir);
  311. // Remove stale plugin directory
  312. // TODO: this should be done by plugin files uninstaller
  313. shell.rm('-rf', path.resolve(self.root, 'Plugins', plugin.id));
  314. });
  315. };
  316. Api.prototype._getInstaller = function (type) {
  317. var self = this;
  318. return function (item, plugin_dir, plugin_id, options, project) {
  319. var installer = self._handler[type];
  320. if (!installer) {
  321. console.log('unrecognized type ' + type);
  322. } else {
  323. var wwwDest = options.usePlatformWww ?
  324. self.getPlatformInfo().locations.platformWww :
  325. self._handler.www_dir(self.root);
  326. if (type === 'asset') {
  327. installer.install(item, plugin_dir, wwwDest);
  328. } else if (type === 'js-module') {
  329. installer.install(item, plugin_dir, plugin_id, wwwDest);
  330. } else {
  331. installer.install(item, plugin_dir, self.root, plugin_id, options, project);
  332. }
  333. }
  334. };
  335. };
  336. Api.prototype._getUninstaller = function (type) {
  337. var self = this;
  338. return function (item, plugin_dir, plugin_id, options, project) {
  339. var installer = self._handler[type];
  340. if (!installer) {
  341. console.log('browser plugin uninstall: unrecognized type, skipping : ' + type);
  342. } else {
  343. var wwwDest = options.usePlatformWww ?
  344. self.getPlatformInfo().locations.platformWww :
  345. self._handler.www_dir(self.root);
  346. if (['asset', 'js-module'].indexOf(type) > -1) {
  347. return installer.uninstall(item, wwwDest, plugin_id);
  348. } else {
  349. return installer.uninstall(item, self.root, plugin_id, options, project);
  350. }
  351. }
  352. };
  353. };
  354. /**
  355. * Removes the specified modules from list of installed modules and updates
  356. * platform_json and cordova_plugins.js on disk.
  357. *
  358. * @param {PluginInfo} plugin PluginInfo instance for plugin, which modules
  359. * needs to be added.
  360. * @param {String} targetDir The directory, where updated cordova_plugins.js
  361. * should be written to.
  362. */
  363. Api.prototype._addModulesInfo = function (plugin, targetDir) {
  364. var installedModules = this._platformJson.root.modules || [];
  365. var installedPaths = installedModules.map(function (installedModule) {
  366. return installedModule.file;
  367. });
  368. var modulesToInstall = plugin.getJsModules(this.platform)
  369. .filter(function (moduleToInstall) {
  370. return installedPaths.indexOf(moduleToInstall.file) === -1;
  371. }).map(function (moduleToInstall) {
  372. var moduleName = plugin.id + '.' + (moduleToInstall.name || moduleToInstall.src.match(/([^\/]+)\.js/)[1]);
  373. var obj = {
  374. file: ['plugins', plugin.id, moduleToInstall.src].join('/'), /* eslint no-useless-escape : 0 */
  375. id: moduleName,
  376. pluginId: plugin.id
  377. };
  378. if (moduleToInstall.clobbers.length > 0) {
  379. obj.clobbers = moduleToInstall.clobbers.map(function (o) { return o.target; });
  380. }
  381. if (moduleToInstall.merges.length > 0) {
  382. obj.merges = moduleToInstall.merges.map(function (o) { return o.target; });
  383. }
  384. if (moduleToInstall.runs) {
  385. obj.runs = true;
  386. }
  387. return obj;
  388. });
  389. this._platformJson.root.modules = installedModules.concat(modulesToInstall);
  390. if (!this._platformJson.root.plugin_metadata) {
  391. this._platformJson.root.plugin_metadata = {};
  392. }
  393. this._platformJson.root.plugin_metadata[plugin.id] = plugin.version;
  394. this._writePluginModules(targetDir);
  395. this._platformJson.save();
  396. };
  397. /**
  398. * Fetches all installed modules, generates cordova_plugins contents and writes
  399. * it to file.
  400. *
  401. * @param {String} targetDir Directory, where write cordova_plugins.js to.
  402. * Ususally it is either <platform>/www or <platform>/platform_www
  403. * directories.
  404. */
  405. Api.prototype._writePluginModules = function (targetDir) {
  406. // Write out moduleObjects as JSON wrapped in a cordova module to cordova_plugins.js
  407. var final_contents = 'cordova.define(\'cordova/plugin_list\', function(require, exports, module) {\n';
  408. final_contents += 'module.exports = ' + JSON.stringify(this._platformJson.root.modules, null, ' ') + ';\n';
  409. final_contents += 'module.exports.metadata = \n';
  410. final_contents += '// TOP OF METADATA\n';
  411. final_contents += JSON.stringify(this._platformJson.root.plugin_metadata || {}, null, ' ') + '\n';
  412. final_contents += '// BOTTOM OF METADATA\n';
  413. final_contents += '});'; // Close cordova.define.
  414. shell.mkdir('-p', targetDir);
  415. fs.writeFileSync(path.join(targetDir, 'cordova_plugins.js'), final_contents, 'utf-8');
  416. };
  417. /**
  418. * Removes the specified modules from list of installed modules and updates
  419. * platform_json and cordova_plugins.js on disk.
  420. *
  421. * @param {PluginInfo} plugin PluginInfo instance for plugin, which modules
  422. * needs to be removed.
  423. * @param {String} targetDir The directory, where updated cordova_plugins.js
  424. * should be written to.
  425. */
  426. Api.prototype._removeModulesInfo = function (plugin, targetDir) {
  427. var installedModules = this._platformJson.root.modules || [];
  428. var modulesToRemove = plugin.getJsModules(this.platform)
  429. .map(function (jsModule) {
  430. return ['plugins', plugin.id, jsModule.src].join('/');
  431. });
  432. var updatedModules = installedModules
  433. .filter(function (installedModule) {
  434. return (modulesToRemove.indexOf(installedModule.file) === -1);
  435. });
  436. this._platformJson.root.modules = updatedModules;
  437. if (this._platformJson.root.plugin_metadata) {
  438. delete this._platformJson.root.plugin_metadata[plugin.id];
  439. }
  440. this._writePluginModules(targetDir);
  441. this._platformJson.save();
  442. };
  443. Api.prototype.build = function (buildOptions) {
  444. var self = this;
  445. return require('./lib/check_reqs').run()
  446. .then(function () {
  447. return require('./lib/build').run.call(self, buildOptions);
  448. });
  449. };
  450. Api.prototype.run = function (runOptions) {
  451. return require('./lib/run').run(runOptions);
  452. };
  453. Api.prototype.clean = function (cleanOptions) {
  454. return require('./lib/clean').run(cleanOptions);
  455. };
  456. Api.prototype.requirements = function () {
  457. return require('./lib/check_reqs').run();
  458. };
  459. module.exports = Api;