alloy 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.github/workflows/cla.yaml +1 -1
  2. package/Alloy/alloy.js +7 -4
  3. package/Alloy/builtins/social.js +1 -1
  4. package/Alloy/builtins/string.js +1 -4
  5. package/Alloy/commands/compile/Orphanage.js +1 -2
  6. package/Alloy/commands/compile/README.md +1 -1
  7. package/Alloy/commands/compile/ast/builtins-plugin.js +1 -1
  8. package/Alloy/commands/compile/ast/controller.js +52 -27
  9. package/Alloy/commands/compile/compilerUtils.js +24 -11
  10. package/Alloy/commands/compile/index.js +211 -62
  11. package/Alloy/commands/compile/parsers/Alloy.Abstract._BackboneClass.js +3 -2
  12. package/Alloy/commands/compile/parsers/Alloy.Require.js +10 -4
  13. package/Alloy/commands/compile/parsers/Ti.UI.ActivityIndicator.js +9 -0
  14. package/Alloy/commands/compile/parsers/Ti.UI.Column.js +9 -0
  15. package/Alloy/commands/compile/parsers/Ti.UI.MaskedImage.js +9 -0
  16. package/Alloy/commands/compile/parsers/Ti.UI.Notification.js +9 -0
  17. package/Alloy/commands/compile/parsers/Ti.UI.ProgressBar.js +9 -0
  18. package/Alloy/commands/compile/parsers/Ti.UI.RefreshControl.js +9 -0
  19. package/Alloy/commands/compile/parsers/Ti.UI.Row.js +9 -0
  20. package/Alloy/commands/compile/parsers/Ti.UI.SearchBar.js +9 -0
  21. package/Alloy/commands/compile/parsers/Ti.UI.Shortcut.js +9 -0
  22. package/Alloy/commands/compile/parsers/Ti.UI.ShortcutItem.js +9 -0
  23. package/Alloy/commands/compile/sourceMapper.js +0 -16
  24. package/Alloy/commands/compile/styler.js +101 -58
  25. package/Alloy/commands/db/index.js +76 -0
  26. package/Alloy/commands/generate/targets/jmk.js +1 -1
  27. package/Alloy/commands/generate/targets/style.js +1 -1
  28. package/Alloy/commands/generate/targets/widget.js +2 -2
  29. package/Alloy/commands/new/index.js +1 -1
  30. package/Alloy/commands/purgetss/index.js +5 -0
  31. package/Alloy/common/constants.js +2 -11
  32. package/Alloy/lib/alloy/sync/localStorage.js +0 -8
  33. package/Alloy/lib/alloy/sync/sql.js +12 -9
  34. package/Alloy/plugin/plugin.py +1 -123
  35. package/Alloy/template/lib/alloy.js +7 -8
  36. package/Alloy/tiapp.js +18 -0
  37. package/CHANGELOG.md +6 -0
  38. package/README.md +4 -0
  39. package/package.json +1 -1
  40. package/platforms/windows/index.js +0 -4
  41. package/samples/apps/advanced/complex_styling/config.json +1 -4
  42. package/samples/apps/advanced/custom_tss_queries/styles/index.tss +0 -6
  43. package/samples/apps/advanced/device_query/specs/index.js +1 -12
  44. package/samples/apps/advanced/device_query/styles/index.tss +0 -12
  45. package/samples/apps/advanced/form_factor/views/index.xml +1 -7
  46. package/samples/apps/advanced/inheritance/controllers/index.js +4 -8
  47. package/samples/apps/advanced/inheritance/specs/baseDialog.js +2 -2
  48. package/samples/apps/advanced/master_detail/specs/row.js +3 -3
  49. package/samples/apps/advanced/proxy_property_requires/widgets/com.foo.widget/views/section.xml +3 -3
  50. package/samples/apps/advanced/proxy_property_requires/widgets/com.foo.widget/widget.json +2 -2
  51. package/samples/apps/advanced/require_children/widgets/alloy.container/widget.json +2 -2
  52. package/samples/apps/advanced/themes/specs/dialog.js +1 -18
  53. package/samples/apps/advanced/themes/specs/index.js +1 -45
  54. package/samples/apps/advanced/theming_widgets/widgets/starrating/widget.json +2 -2
  55. package/samples/apps/basics/builtins/specs/index.js +2 -2
  56. package/samples/apps/basics/config_json/config.json +1 -4
  57. package/samples/apps/basics/global_style/specs/item.js +2 -2
  58. package/samples/apps/basics/simple/specs/index.js +2 -2
  59. package/samples/apps/models/binding_tableview/controllers/tab_1.js +2 -2
  60. package/samples/apps/models/binding_tableview/controllers/tab_2.js +2 -2
  61. package/samples/apps/models/binding_tableview/controllers/tab_3.js +2 -2
  62. package/samples/apps/models/binding_tableview/controllers/tab_4.js +2 -2
  63. package/samples/apps/ui/buttonbar/views/index.xml +1 -1
  64. package/samples/apps/ui/switch/views/index.xml +2 -2
  65. package/samples/apps/widgets/basic/widgets/com.foo.widget/widget.json +2 -2
  66. package/samples/apps/widgets/complex/widgets/com.appcelerator.loading/widget.json +1 -1
  67. package/samples/apps/widgets/complex/widgets/com.testing.searchForBooks/widget.json +1 -1
  68. package/samples/apps/widgets/models/widgets/alloy.datatable/widget.json +1 -1
  69. package/samples/apps/widgets/wpath/widgets/com.test.hellobutton/widget.json +1 -1
  70. package/test/specs/new.js +0 -2
  71. package/test/specs/optimizer.js +0 -2
  72. package/test/specs/purgetss.js +74 -0
  73. package/test/specs/require.js +94 -0
  74. package/test/specs/styler.js +271 -0
@@ -8,6 +8,6 @@ jobs:
8
8
  name: Verify contributor
9
9
 
10
10
  steps:
11
- - uses: tidev/tidev-cla-action@v2
11
+ - uses: tidev/tidev-cla-action@v3
12
12
  with:
13
13
  repo-token: ${{ secrets.GITHUB_TOKEN }}
package/Alloy/alloy.js CHANGED
@@ -14,8 +14,7 @@ var program = require('commander'),
14
14
  fs = require('fs'),
15
15
  CONST = require('./common/constants');
16
16
 
17
- // patch to remove the warning in node >=0.8
18
- path.existsSync = fs.existsSync || path.existsSync;
17
+
19
18
 
20
19
  // avoid io issues on Windows in nodejs 0.10.X: https://github.com/joyent/node/issues/3584
21
20
  if (process.env.ALLOY_TESTS && /^win/i.test(os.platform())) {
@@ -77,10 +76,14 @@ program.command('remove <source>')
77
76
  .description('remove the controller, view, and style files at <source>');
78
77
 
79
78
  program.command('purgetss')
80
- .description('Create a clean app.tss file with only the classes used in your XML Files.\nYour original classes will be backed up in _app.tss')
79
+ .description('Deprecated: run `purgetss` directly; see `purgetss --help`.\nCreate a clean app.tss file with only the classes used in your XML Files.\nYour original classes will be backed up in _app.tss')
81
80
  .option('--modules', 'Copy or generate the corresponding CommonJS module into `./app/lib/` folder.')
82
81
  .option('--vendor <arguments>', 'Use any of the following arguments to copy specific vendors: fa = Font Awesome, md = Material Design or f7 = Framework7 Icons');
83
82
 
83
+ program.command('db')
84
+ .description('Fetches the default alloy database (_alloy_) from the device')
85
+ .option('get', 'Downloads the _alloy_ database to your app folder');
86
+
84
87
  program.command('info [type]', { hidden: true });
85
88
 
86
89
  program.command('debugger', { hidden: true });
@@ -144,7 +147,7 @@ function getCommands() {
144
147
  try {
145
148
  var commandsPath = path.join(__dirname, 'commands');
146
149
  return _.filter(fs.readdirSync(commandsPath), function(file) {
147
- return path.existsSync(path.join(commandsPath, file, 'index.js'));
150
+ return fs.existsSync(path.join(commandsPath, file, 'index.js'));
148
151
  });
149
152
  } catch (e) {
150
153
  U.die('Error getting command list', e);
@@ -157,7 +157,7 @@ OAuth == null && (OAuth = {}), OAuth.setProperties = function(into, from) {
157
157
  if (s == null) return '';
158
158
  if (s instanceof Array) {
159
159
  var e = '';
160
- for (var i = 0; i < s.length; ++s) e != '' && (e += '&'), e += OAuth.percentEncode(s[i]);
160
+ for (var i = 0; i < s.length; ++i) e != '' && (e += '&'), e += OAuth.percentEncode(s[i]);
161
161
  return e;
162
162
  }
163
163
  return s = encodeURIComponent(s), s = s.replace(/\!/g, '%21'), s = s.replace(/\*/g, '%2A'), s = s.replace(/\'/g, '%27'), s = s.replace(/\(/g, '%28'), s = s.replace(/\)/g, '%29'), s;
@@ -64,10 +64,7 @@ exports.lcfirst = function (text) {
64
64
  * @param {String} amount Amount to format.
65
65
  * @return {String} Amount formatted as a currency value.
66
66
  */
67
- exports.formatCurrency = !(OS_MOBILEWEB) ? String.formatCurrency : function (amount) {
68
- var num = isNaN(amount) || amount === '' || amount === null ? 0.00 : amount;
69
- return '$' + parseFloat(num).toFixed(2);
70
- };
67
+ exports.formatCurrency = String.formatCurrency;
71
68
 
72
69
 
73
70
  /**
@@ -277,8 +277,7 @@ function isException(file, exceptions) {
277
277
  // handle folder wildcards
278
278
  if (ex.charAt(ex.length - 1) === '*') {
279
279
  for (var j = 0; j < exs.length; j++) {
280
- var newEx = exs[i].substr(0, exs[i].length - 2);
281
-
280
+ var newEx = exs[j].substr(0, exs[j].length - 2);
282
281
  // see if the file starts with the wildcard
283
282
  if (file.length >= newEx.length && file.substr(0, newEx.length) === newEx) {
284
283
  return true;
@@ -2,7 +2,7 @@ Files related to the `alloy compile` command:
2
2
 
3
3
  * ast - optimizer, compressor, and related AST scripts
4
4
  * parsers - parsers for specific UI components
5
- * BuildLog.js - generates the build/alloy/build.json file which is used to track files that could be reused by subsequent compile operations
5
+ * BuildLog.js - generates the build/alloy/build.json file which is used to track files that could be reused by subsequent compile operations, including a per-platform hash of every generated controller and runtime style so unchanged components are skipped on the next compile
6
6
  * CompilerMakeFile.js - class used during JMK processing
7
7
  * compilerUtils.js - utility functions used by the compiler, such as validation of nodes, getting parser arguments, etc. But this script also defines the main code generating functions: CU.generateNode and CU.generateNodeExtended which are used in processing nearly every XML tag.
8
8
  * index.js - main entry point for the alloy compiler
@@ -21,7 +21,7 @@ function appendExtension(file, extension) {
21
21
  }
22
22
 
23
23
  function loadBuiltin(source, name, dest) {
24
- if (!path.existsSync(source)) {
24
+ if (!fs.existsSync(source)) {
25
25
  return;
26
26
  }
27
27
 
@@ -13,13 +13,22 @@ let GENCODE_OPTIONS = {
13
13
  exports.processController = function(code, file, isProduction = false) {
14
14
  var baseController = '',
15
15
  moduleCodes = '',
16
- newCode = '',
17
- exportSpecifiers = [];
16
+ newCode = '';
18
17
 
19
18
  if (isProduction) {
20
19
  GENCODE_OPTIONS.retainLines = false;
21
20
  }
22
21
 
22
+ function buildExportAssignment(exportedName, localName) {
23
+ return types.expressionStatement(
24
+ types.assignmentExpression(
25
+ '=',
26
+ types.memberExpression(types.identifier('exports'), types.identifier(exportedName)),
27
+ types.identifier(localName)
28
+ )
29
+ );
30
+ }
31
+
23
32
  try {
24
33
  var ast = babylon.parse(code, { sourceFilename: file, sourceType: 'unambiguous' });
25
34
 
@@ -55,38 +64,54 @@ exports.processController = function(code, file, isProduction = false) {
55
64
 
56
65
  ExportNamedDeclaration: function(path) {
57
66
  var node = path.node;
58
- var specifiers = node.specifiers;
59
- if (specifiers && specifiers.length !== 0) {
60
- specifiers.forEach(function (specifier) {
61
- if (specifier.local && specifier.local.name) {
62
- exportSpecifiers.push(specifier.local.name);
67
+
68
+ // Re-exports from another module (e.g. `export { foo } from './bar'`) are true
69
+ // module-level constructs — hoist them out of the controller body.
70
+ if (node.source) {
71
+ moduleCodes += generate(node, GENCODE_OPTIONS).code;
72
+ path.remove();
73
+ return;
74
+ }
75
+
76
+ // `export function show() {}`, `export const show = ...`, `export class X {}`
77
+ if (node.declaration) {
78
+ var decl = node.declaration;
79
+ var replacements = [decl];
80
+ if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
81
+ if (decl.id && decl.id.name) {
82
+ replacements.push(buildExportAssignment(decl.id.name, decl.id.name));
63
83
  }
64
- });
84
+ } else if (decl.type === 'VariableDeclaration') {
85
+ decl.declarations.forEach(function (d) {
86
+ if (d.id && d.id.name) {
87
+ replacements.push(buildExportAssignment(d.id.name, d.id.name));
88
+ }
89
+ });
90
+ }
91
+ path.replaceWithMultiple(replacements);
92
+ return;
93
+ }
94
+
95
+ // `export { show }` or `export { show as displayShow }` — locally declared
96
+ // bindings get attached to the controller's local `exports` object.
97
+ if (node.specifiers && node.specifiers.length !== 0) {
98
+ var assignments = node.specifiers
99
+ .filter(function (specifier) { return specifier.local && specifier.local.name; })
100
+ .map(function (specifier) {
101
+ var localName = specifier.local.name;
102
+ var exportedName = (specifier.exported && specifier.exported.name) || localName;
103
+ return buildExportAssignment(exportedName, localName);
104
+ });
105
+ path.replaceWithMultiple(assignments);
106
+ return;
65
107
  }
108
+
109
+ // Fallback: leave as-is at module level.
66
110
  moduleCodes += generate(node, GENCODE_OPTIONS).code;
67
111
  path.remove();
68
112
  }
69
113
  }, path.scope);
70
114
 
71
- if (exportSpecifiers.length > 0) {
72
- traverse(ast, {
73
- enter: function(path) {
74
- var node = path.node,
75
- name;
76
- if (node.type === 'VariableDeclaration') {
77
- name = node.declarations[0].id.name;
78
- } else if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') {
79
- name = node.id.name;
80
- }
81
-
82
- if (exportSpecifiers.indexOf(name) !== -1) {
83
- moduleCodes += generate(node, GENCODE_OPTIONS).code;
84
- path.remove();
85
- }
86
- }
87
- });
88
- }
89
-
90
115
  newCode = generate(ast, GENCODE_OPTIONS).code;
91
116
  } catch (e) {
92
117
  U.dieWithCodeFrame('Error generating AST for "' + file + '". Unexpected token at line ' + e.loc.line + ' column ' + e.loc.column, e.loc, code);
@@ -21,7 +21,14 @@ var alloyRoot = path.join(__dirname, '..', '..'),
21
21
  alloyUniqueIdPrefix = '__alloyId',
22
22
  alloyUniqueIdCounter = 0,
23
23
  JSON_NULL = JSON.parse('null'),
24
- compilerConfig;
24
+ compilerConfig,
25
+ parserFileNames;
26
+
27
+ // cache parsers directory listing (avoid readdirSync per element)
28
+ (function initParserCache() {
29
+ var parsersDir = path.join(alloyRoot, 'commands', 'compile', 'parsers');
30
+ parserFileNames = fs.readdirSync(parsersDir);
31
+ })();
25
32
 
26
33
  ///////////////////////////////
27
34
  ////////// constants //////////
@@ -93,6 +100,13 @@ exports.generateUniqueId = function() {
93
100
  return alloyUniqueIdPrefix + alloyUniqueIdCounter++;
94
101
  };
95
102
 
103
+ // Generated ids only have to be unique inside one component, so the counter
104
+ // restarts for every component. That keeps the generated code of a component
105
+ // the same no matter which components were generated (or cached) before it.
106
+ exports.resetUniqueId = function() {
107
+ alloyUniqueIdCounter = 0;
108
+ };
109
+
96
110
  exports.getNodeFullname = function(node) {
97
111
  var name = node.nodeName,
98
112
  ns = node.getAttribute('ns') || CONST.IMPLICIT_NAMESPACES[name] || CONST.NAMESPACE_DEFAULT,
@@ -334,9 +348,8 @@ exports.generateNode = function(node, state, defaultId, isTopLevel, isModelOrCol
334
348
  }
335
349
 
336
350
  // Determine which parser to use for this node
337
- var parsersDir = path.join(alloyRoot, 'commands', 'compile', 'parsers');
338
351
  var parserRequire = 'default';
339
- if (_.includes(fs.readdirSync(parsersDir), args.fullname + '.js')) {
352
+ if (_.includes(parserFileNames, args.fullname + '.js')) {
340
353
  parserRequire = args.fullname + '.js';
341
354
  }
342
355
 
@@ -610,7 +623,7 @@ exports.copyWidgetResources = function(resources, resourceDir, widgetId, opts) {
610
623
  }
611
624
 
612
625
  _.each(resources, function(dir) {
613
- if (!path.existsSync(dir)) { return; }
626
+ if (!fs.existsSync(dir)) { return; }
614
627
  logger.trace('WIDGET_SRC=' + path.relative(compilerConfig.dir.project, dir));
615
628
  var files = walkSync(dir);
616
629
  _.each(files, function(file) {
@@ -633,7 +646,7 @@ exports.copyWidgetResources = function(resources, resourceDir, widgetId, opts) {
633
646
 
634
647
  var destDir = path.join(resourceDir, dirname, widgetId);
635
648
  var dest = path.join(destDir, path.basename(file));
636
- if (!path.existsSync(destDir)) {
649
+ if (!fs.existsSync(destDir)) {
637
650
  fs.mkdirpSync(destDir);
638
651
  }
639
652
 
@@ -676,11 +689,11 @@ exports.copyWidgetResources = function(resources, resourceDir, widgetId, opts) {
676
689
  fs.copySync(widgetAssetSourceDir, widgetAssetTargetDir, {preserveTimestamps: true});
677
690
  }
678
691
  // platform-specific assets from the widget must override those of the theme
679
- if (platform && path.existsSync(path.join(resources[0], platform))) {
692
+ if (platform && fs.existsSync(path.join(resources[0], platform))) {
680
693
  fs.copySync(path.join(resources[0], platform), widgetAssetTargetDir, {preserveTimestamps: true});
681
694
  }
682
695
  // however platform-specific theme assets must override the platform assets from the widget
683
- if (platform && path.existsSync(path.join(widgetAssetSourceDir, platform))) {
696
+ if (platform && fs.existsSync(path.join(widgetAssetSourceDir, platform))) {
684
697
  logger.trace('Processing platform-specific theme assets for the ' + widgetId + ' widget');
685
698
  widgetAssetSourceDir = path.join(widgetAssetSourceDir, platform);
686
699
  fs.copySync(widgetAssetSourceDir, widgetAssetTargetDir, {preserveTimestamps: true});
@@ -691,7 +704,7 @@ exports.copyWidgetResources = function(resources, resourceDir, widgetId, opts) {
691
704
  var files = walkSync(widgetAssetTargetDir);
692
705
  _.each(files, function(file) {
693
706
  var source = path.join(widgetAssetTargetDir, file);
694
- if (path.existsSync(source) && fs.statSync(source).isDirectory()) {
707
+ if (fs.existsSync(source) && fs.statSync(source).isDirectory()) {
695
708
  fs.removeSync(source);
696
709
  }
697
710
  });
@@ -855,14 +868,14 @@ function generateConfig(obj) {
855
868
  var resourcesCfg = path.join(resourcesBase, 'CFG.js');
856
869
 
857
870
  // parse config.json, if it exists
858
- if (path.existsSync(appCfg)) {
871
+ if (fs.existsSync(appCfg)) {
859
872
  o = exports.parseConfig(appCfg, alloyConfig, o);
860
873
 
861
874
  if (o.theme) {
862
875
  var themeCfg = path.join(obj.dir.home, 'themes', o.theme, 'config.' + CONST.FILE_EXT.CONFIG);
863
876
 
864
877
  // parse theme config.json, if it exists
865
- if (path.existsSync(themeCfg)) {
878
+ if (fs.existsSync(themeCfg)) {
866
879
  o = exports.parseConfig(themeCfg, alloyConfig, o);
867
880
  }
868
881
  }
@@ -944,7 +957,7 @@ exports.loadController = function(file) {
944
957
 
945
958
  // Read the controller file
946
959
  try {
947
- if (!path.existsSync(file)) {
960
+ if (!fs.existsSync(file)) {
948
961
  return code;
949
962
  }
950
963
  contents = fs.readFileSync(file, 'utf8');
@@ -42,7 +42,24 @@ var times = {
42
42
  };
43
43
 
44
44
  var fileRestrictionUpdatedFiles = [],
45
- restrictionSkipOptimize = false;
45
+ restrictionSkipOptimize = false,
46
+ templateCache = {};
47
+
48
+ // Generated controllers and runtime styles are cached across compiles in the
49
+ // build log, keyed by a hash of everything that feeds into them. See
50
+ // createComponentCacheBase() and componentCacheHash().
51
+ var componentCache = {},
52
+ componentCacheBase = '',
53
+ componentCacheSeen = {},
54
+ componentViewDirs = [],
55
+ allViewsHash = null;
56
+
57
+ function getCompiledTemplate(name) {
58
+ if (!templateCache[name]) {
59
+ templateCache[name] = _.template(fs.readFileSync(path.join(alloyRoot, 'template', name), 'utf8'));
60
+ }
61
+ return templateCache[name];
62
+ }
46
63
 
47
64
  //////////////////////////////////////
48
65
  ////////// command function //////////
@@ -168,6 +185,12 @@ module.exports = function(args, program) {
168
185
  // track whether deploy type has changed since previous build
169
186
  buildLog.data.deploytypeChanged = buildLog.data.deploytype !== alloyConfig.deploytype;
170
187
  buildLog.data.deploytype = alloyConfig.deploytype;
188
+
189
+ // generated components are tracked per platform, since each platform
190
+ // writes into its own Resources folder
191
+ buildLog.data[buildPlatform] || (buildLog.data[buildPlatform] = {});
192
+ componentCache = buildLog.data[buildPlatform].components || (buildLog.data[buildPlatform].components = {});
193
+ componentCacheSeen = {};
171
194
  logger.debug('');
172
195
 
173
196
  // wipe the controllers, models, and widgets
@@ -425,6 +448,9 @@ module.exports = function(args, program) {
425
448
  // don't process XML/controller files inside .svn folders (ALOY-839)
426
449
  var excludeRegex = new RegExp('(?:^|[\\/\\\\])(?:' + CONST.EXCLUDED_FILES.join('|') + ')(?:$|[\\/\\\\])');
427
450
 
451
+ // everything that is shared by all components and can change their output
452
+ componentCacheBase = createComponentCacheBase(widgetDirs, paths);
453
+
428
454
  // Process all views/controllers and generate their runtime
429
455
  // commonjs modules and source maps.
430
456
  var tracker = {};
@@ -472,6 +498,16 @@ module.exports = function(args, program) {
472
498
  });
473
499
  }
474
500
  });
501
+
502
+ // forget components whose sources are gone. Orphanage already removed
503
+ // their generated files, so their entries could never be used again.
504
+ if (restrictionPath === null) {
505
+ _.each(_.keys(componentCache), function(id) {
506
+ if (!componentCacheSeen[id]) {
507
+ delete componentCache[id];
508
+ }
509
+ });
510
+ }
475
511
  logger.info('');
476
512
 
477
513
  generateAppJs(paths, compileConfig, restrictionPath, compilerMakeFile);
@@ -605,7 +641,7 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
605
641
  Widget: !manifest ? '' : 'var ' + CONST.WIDGET_OBJECT +
606
642
  " = new (require('/alloy/widget'))('" + manifest.id + "');this.__widgetId='" +
607
643
  manifest.id + "';",
608
- WPATH: !manifest ? '' : _.template(fs.readFileSync(path.join(alloyRoot, 'template', 'wpath.js'), 'utf8'))({ WIDGETID: manifest.id }),
644
+ WPATH: !manifest ? '' : getCompiledTemplate('wpath.js')({ WIDGETID: manifest.id }),
609
645
  __MAPMARKER_CONTROLLER_CODE__: '',
610
646
  ES6Mod: ''
611
647
  },
@@ -619,6 +655,11 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
619
655
  styler.bindingsMap = {};
620
656
  CU.destroyCode = '';
621
657
  CU.postCode = '';
658
+ // form factor data functions belong to the component that declared them,
659
+ // they must not leak into the components generated afterwards
660
+ CU.dataFunctionNames = {};
661
+ CU.resetUniqueId();
662
+ styler.resetStyleOrder();
622
663
  CU[CONST.AUTOSTYLE_PROPERTY] = compileConfig[CONST.AUTOSTYLE_PROPERTY];
623
664
  CU.currentManifest = manifest;
624
665
  CU.currentDefaultId = viewName;
@@ -661,6 +702,62 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
661
702
  files[fileType] = path.join(files[fileType], viewName + '.js');
662
703
  });
663
704
 
705
+ // prep the controller paths based on whether it's an app
706
+ // controller or widget controller
707
+ var targetFilepath = path.join(compileConfig.dir.resources, titaniumFolder,
708
+ path.relative(compileConfig.dir.resources, files.COMPONENT));
709
+ var runtimeStylePath = path.join(compileConfig.dir.resources, titaniumFolder,
710
+ path.relative(compileConfig.dir.resources, files.RUNTIME_STYLE));
711
+ if (manifest) {
712
+ fs.mkdirpSync(
713
+ path.join(compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET,
714
+ manifest.id, widgetDir)
715
+ );
716
+ fs.mkdirpSync(
717
+ path.join(compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET,
718
+ manifest.id, widgetStyleDir)
719
+ );
720
+
721
+ // [ALOY-967] merge "i18n" dir in widget folder
722
+ CU.mergeI18N(path.join(dir, 'i18n'), path.join(compileConfig.dir.project, 'i18n'), { override: false });
723
+ widgetIds.push(manifest.id);
724
+
725
+ CU.copyWidgetResources(
726
+ [path.join(dir, CONST.DIR.ASSETS), path.join(dir, CONST.DIR.LIB)],
727
+ path.join(compileConfig.dir.resources, titaniumFolder),
728
+ manifest.id,
729
+ {
730
+ filter: new RegExp('^(?:' + otherPlatforms.join('|') + ')[\\/\\\\]'),
731
+ exceptions: otherPlatforms,
732
+ titaniumFolder: titaniumFolder,
733
+ theme: theme
734
+ }
735
+ );
736
+ targetFilepath = path.join(
737
+ compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET, manifest.id,
738
+ widgetDir, viewName + '.js'
739
+ );
740
+ runtimeStylePath = path.join(
741
+ compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET, manifest.id,
742
+ widgetStyleDir, viewName + '.js'
743
+ );
744
+ }
745
+
746
+ // theme styles that override the component's own, if a theme is active
747
+ var themeStyleFiles = getThemeStyleFiles(dirname, viewName, manifest);
748
+
749
+ // Reuse the generated files from the previous compile when every input
750
+ // that feeds into them is unchanged. This is what makes rebuilds fast.
751
+ var cacheId = path.relative(compileConfig.dir.resources, targetFilepath).replace(/\\/g, '/');
752
+ var cacheHash = componentCacheHash(files, themeStyleFiles, manifest ? path.join(dir, 'widget.json') : null);
753
+ componentCacheSeen[cacheId] = true;
754
+ if (componentCache[cacheId] === cacheHash && generatedFilesExist(targetFilepath, runtimeStylePath)) {
755
+ logger.info(' cached: "' + path.relative(compileConfig.dir.project, targetFilepath) + '"');
756
+ restrictionSkipOptimize = (fileRestriction !== null);
757
+ return;
758
+ }
759
+ delete componentCache[cacheId];
760
+
664
761
  // we are processing a view, not just a controller
665
762
  if (!noView) {
666
763
  // validate view
@@ -687,22 +784,11 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
687
784
  });
688
785
  }
689
786
 
690
- if (theme) {
787
+ if (themeStyleFiles) {
691
788
  // if a theme is applied, override TSS definitions with those defined in the theme
692
- var themeStylesDir, theStyle, themeStylesFile, psThemeStylesFile;
693
- if (!manifest) {
694
- // theming a "normal" controller
695
- themeStylesDir = path.join(compileConfig.dir.themes, theme, 'styles');
696
- theStyle = dirname ? path.join(dirname, viewName + '.tss') : viewName + '.tss';
697
- themeStylesFile = path.join(themeStylesDir, theStyle);
698
- psThemeStylesFile = path.join(themeStylesDir, buildPlatform, theStyle);
699
- } else {
700
- // theming a widget
701
- themeStylesDir = path.join(compileConfig.dir.themes, theme, 'widgets', manifest.id, 'styles');
702
- theStyle = dirname ? path.join(dirname, viewName + '.tss') : viewName + '.tss';
703
- themeStylesFile = path.join(themeStylesDir, theStyle);
704
- psThemeStylesFile = path.join(themeStylesDir, buildPlatform, theStyle);
705
- }
789
+ var theStyle = themeStyleFiles.name,
790
+ themeStylesFile = themeStyleFiles.base,
791
+ psThemeStylesFile = themeStyleFiles.platform;
706
792
 
707
793
  if (fs.existsSync(themeStylesFile)) {
708
794
  // load theme-specific styles, overriding default definitions
@@ -812,8 +898,10 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
812
898
 
813
899
  // process the UI nodes
814
900
  _.each(rootChildren, function(node, i) {
815
- // should we use the default id?
816
- var defaultId = CU.isNodeForCurrentPlatform(node) ? viewName : undefined;
901
+ // should we use the default id? Not when the view's name is a reserved word (such
902
+ // as delete.xml): that is not a valid id, so the element gets a generated one.
903
+ var defaultId = CU.isNodeForCurrentPlatform(node) && !_.includes(CONST.JS_RESERVED_ALL, viewName) ?
904
+ viewName : undefined;
817
905
 
818
906
  // generate the code for this node
819
907
  var fullname = CU.getNodeFullname(node);
@@ -893,48 +981,7 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
893
981
  // create generated controller module code for this view/controller or widget
894
982
  var controllerCode = template.__MAPMARKER_CONTROLLER_CODE__;
895
983
  delete template.__MAPMARKER_CONTROLLER_CODE__;
896
- var code = _.template(fs.readFileSync(path.join(compileConfig.dir.template, 'component.js'), 'utf8'))(template);
897
-
898
- // prep the controller paths based on whether it's an app
899
- // controller or widget controller
900
- var targetFilepath = path.join(compileConfig.dir.resources, titaniumFolder,
901
- path.relative(compileConfig.dir.resources, files.COMPONENT));
902
- var runtimeStylePath = path.join(compileConfig.dir.resources, titaniumFolder,
903
- path.relative(compileConfig.dir.resources, files.RUNTIME_STYLE));
904
- if (manifest) {
905
- fs.mkdirpSync(
906
- path.join(compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET,
907
- manifest.id, widgetDir)
908
- );
909
- fs.mkdirpSync(
910
- path.join(compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET,
911
- manifest.id, widgetStyleDir)
912
- );
913
-
914
- // [ALOY-967] merge "i18n" dir in widget folder
915
- CU.mergeI18N(path.join(dir, 'i18n'), path.join(compileConfig.dir.project, 'i18n'), { override: false });
916
- widgetIds.push(manifest.id);
917
-
918
- CU.copyWidgetResources(
919
- [path.join(dir, CONST.DIR.ASSETS), path.join(dir, CONST.DIR.LIB)],
920
- path.join(compileConfig.dir.resources, titaniumFolder),
921
- manifest.id,
922
- {
923
- filter: new RegExp('^(?:' + otherPlatforms.join('|') + ')[\\/\\\\]'),
924
- exceptions: otherPlatforms,
925
- titaniumFolder: titaniumFolder,
926
- theme: theme
927
- }
928
- );
929
- targetFilepath = path.join(
930
- compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET, manifest.id,
931
- widgetDir, viewName + '.js'
932
- );
933
- runtimeStylePath = path.join(
934
- compileConfig.dir.resources, titaniumFolder, 'alloy', CONST.DIR.WIDGET, manifest.id,
935
- widgetStyleDir, viewName + '.js'
936
- );
937
- }
984
+ var code = getCompiledTemplate('component.js')(template);
938
985
 
939
986
  // generate the code and source map for the current controller
940
987
  sourceMapper.generateCodeAndSourceMap({
@@ -1010,10 +1057,112 @@ function parseAlloyComponent(view, dir, manifest, noView, fileRestriction) {
1010
1057
  // write out the pre-processed styles to runtime module files
1011
1058
  var styleCode = 'module.exports = [' + processedStyles.join(',') + '];';
1012
1059
  if (manifest) {
1013
- styleCode += _.template(fs.readFileSync(path.join(alloyRoot, 'template', 'wpath.js'), 'utf8'))({ WIDGETID: manifest.id });
1060
+ styleCode += getCompiledTemplate('wpath.js')({ WIDGETID: manifest.id });
1014
1061
  }
1015
1062
  fs.mkdirpSync(path.dirname(runtimeStylePath));
1016
1063
  fs.writeFileSync(runtimeStylePath, styleCode);
1064
+
1065
+ // remember what was generated so the next compile can skip it
1066
+ componentCache[cacheId] = cacheHash;
1067
+ }
1068
+
1069
+ // Everything shared by all components that changes their generated output.
1070
+ // Combined with the per-component inputs in componentCacheHash().
1071
+ function createComponentCacheBase(widgetDirs, paths) {
1072
+ componentViewDirs = _.map(widgetDirs, function(collection) {
1073
+ return path.join(collection.dir, CONST.DIR.VIEW);
1074
+ });
1075
+ allViewsHash = null;
1076
+
1077
+ return JSON.stringify({
1078
+ version: require('../../../package.json').version,
1079
+ platform: buildPlatform,
1080
+ deploytype: compileConfig.alloyConfig.deploytype,
1081
+ theme: theme || '',
1082
+ cfgHash: buildLog.data.cfgHash,
1083
+ globalStyleHash: buildLog.data.globalStyleCacheHash,
1084
+ sourcemap: compileConfig.sourcemap,
1085
+ autoStyle: compileConfig[CONST.AUTOSTYLE_PROPERTY],
1086
+ backbone: compileConfig.backbone,
1087
+ adapters: compileConfig.adapters,
1088
+ models: CU.models.slice().sort(),
1089
+ jmk: U.createHash(path.join(paths.app, 'alloy.jmk'))
1090
+ });
1091
+ }
1092
+
1093
+ // Hash of the contents of every file a single component is generated from.
1094
+ // Missing files hash as empty, so one appearing later changes the hash, and
1095
+ // the paths are part of it, so a platform-specific file taking over does too.
1096
+ function componentCacheHash(files, themeStyleFiles, manifestFile) {
1097
+ var inputs = [files.VIEW, files.CONTROLLER];
1098
+ _.each([].concat(files.STYLE || []), function(style) {
1099
+ inputs.push(style.file || style);
1100
+ });
1101
+ if (themeStyleFiles) {
1102
+ inputs.push(themeStyleFiles.base, themeStyleFiles.platform);
1103
+ }
1104
+ if (manifestFile) {
1105
+ inputs.push(manifestFile);
1106
+ }
1107
+
1108
+ // Parsers expand <Require> and <Widget> and generate different code
1109
+ // depending on what the referenced view contains, so a component that
1110
+ // uses them also depends on the other views.
1111
+ var dependsOnViews = files.VIEW && fs.existsSync(files.VIEW) &&
1112
+ /<(?:Require|Widget)[\s\/>]/.test(fs.readFileSync(files.VIEW, 'utf8'));
1113
+
1114
+ return U.createHashFromString(componentCacheBase + '\n' + U.createHash(_.compact(inputs)) +
1115
+ (dependsOnViews ? '\n' + getAllViewsHash() : ''));
1116
+ }
1117
+
1118
+ // Hash of the paths and contents of every view in the app and its widgets,
1119
+ // computed at most once per compile.
1120
+ function getAllViewsHash() {
1121
+ if (allViewsHash === null) {
1122
+ var views = [];
1123
+ _.each(componentViewDirs, function(dir) {
1124
+ if (fs.existsSync(dir)) {
1125
+ _.each(walkSync(dir), function(f) {
1126
+ if (viewRegex.test(f)) {
1127
+ views.push(path.join(dir, f));
1128
+ }
1129
+ });
1130
+ }
1131
+ });
1132
+ allViewsHash = U.createHash(views.sort());
1133
+ }
1134
+ return allViewsHash;
1135
+ }
1136
+
1137
+ // Theme TSS files for a component. Returns null when no theme is active.
1138
+ function getThemeStyleFiles(dirname, viewName, manifest) {
1139
+ if (!theme) {
1140
+ return null;
1141
+ }
1142
+ var themeStylesDir = manifest ?
1143
+ path.join(compileConfig.dir.themes, theme, 'widgets', manifest.id, 'styles') :
1144
+ path.join(compileConfig.dir.themes, theme, 'styles');
1145
+ var name = dirname ? path.join(dirname, viewName + '.tss') : viewName + '.tss';
1146
+ return {
1147
+ name: name,
1148
+ base: path.join(themeStylesDir, name),
1149
+ platform: path.join(themeStylesDir, buildPlatform, name)
1150
+ };
1151
+ }
1152
+
1153
+ // A cache entry is only usable while the files it describes are still there.
1154
+ function generatedFilesExist(targetFilepath, runtimeStylePath) {
1155
+ if (!fs.existsSync(targetFilepath) || !fs.existsSync(runtimeStylePath)) {
1156
+ return false;
1157
+ }
1158
+ if (compileConfig.sourcemap !== false) {
1159
+ var mapFile = path.join(compileConfig.dir.project, CONST.DIR.MAP,
1160
+ path.relative(compileConfig.dir.project, targetFilepath)) + '.' + CONST.FILE_EXT.MAP;
1161
+ if (!fs.existsSync(mapFile)) {
1162
+ return false;
1163
+ }
1164
+ }
1165
+ return true;
1017
1166
  }
1018
1167
 
1019
1168
  function findModelMigrations(name, inDir) {