@teambit/workspace 0.0.751 → 0.0.752

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.
@@ -25,8 +25,8 @@ export declare class WatchCommand implements Command {
25
25
  onAll: (event: string, path: string) => void;
26
26
  onStart: () => void;
27
27
  onReady: (workspace: any, watchPathsSortByComponent: any, verbose: any) => void;
28
- onChange: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration: any) => void;
29
- onAdd: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration: any) => void;
28
+ onChange: (filePaths: string[], buildResults: OnComponentEventResult[], verbose: boolean, duration: any, failureMsg?: string | undefined) => void;
29
+ onAdd: (filePaths: string[], buildResults: OnComponentEventResult[], verbose: boolean, duration: any, failureMsg?: string | undefined) => void;
30
30
  onUnlink: (p: any) => void;
31
31
  onError: (err: any) => void;
32
32
  };
@@ -99,22 +99,32 @@ class WatchCommand {
99
99
 
100
100
  this.logger.console(_chalk().default.yellow(`Watching for component changes in workspace ${workspace.config.name} (${(0, _moment().default)().format('HH:mm:ss')})...\n`));
101
101
  },
102
- onChange: (filePath, buildResults, verbose, duration) => {
102
+ onChange: (filePaths, buildResults, verbose, duration, failureMsg) => {
103
+ const files = filePaths.join(', ');
103
104
  clearOutdatedData();
104
105
 
105
106
  if (!buildResults.length) {
106
- this.logger.console(`The file ${filePath} has been changed, but nothing to compile.\n\n`);
107
+ failureMsg = failureMsg || `The files ${files} have been changed, but nothing to compile`;
108
+ this.logger.console(`${failureMsg}\n\n`);
107
109
  return;
108
110
  }
109
111
 
110
- this.logger.console(`The file ${filePath} has been changed.\n\n`);
112
+ this.logger.console(`The file(s) ${files} have been changed.\n\n`);
111
113
  this.logger.console((0, _outputFormatter().formatCompileResults)(buildResults, verbose));
112
114
  this.logger.console(`Finished. (${duration}ms)`);
113
115
  this.logger.console(_chalk().default.yellow(`Watching for component changes (${(0, _moment().default)().format('HH:mm:ss')})...`));
114
116
  },
115
- onAdd: (filePath, buildResults, verbose, duration) => {
117
+ onAdd: (filePaths, buildResults, verbose, duration, failureMsg) => {
118
+ const files = filePaths.join(', ');
116
119
  clearOutdatedData();
117
- this.logger.console(`The file ${filePath} has been added.\n\n`);
120
+
121
+ if (!buildResults.length) {
122
+ failureMsg = failureMsg || `The files ${files} have been added, but nothing to compile`;
123
+ this.logger.console(`${failureMsg}\n\n`);
124
+ return;
125
+ }
126
+
127
+ this.logger.console(`The file(s) ${filePaths} have been added.\n\n`);
118
128
  this.logger.console((0, _outputFormatter().formatCompileResults)(buildResults, verbose));
119
129
  this.logger.console(`Finished. (${duration}ms)`);
120
130
  this.logger.console(_chalk().default.yellow(`Watching for component changes (${(0, _moment().default)().format('HH:mm:ss')})...`));
@@ -1 +1 @@
1
- {"version":3,"names":["WatchCommand","constructor","pubsub","logger","watcher","onAll","event","path","console","onStart","onReady","workspace","watchPathsSortByComponent","verbose","clearOutdatedData","formatWatchPathsSortByComponent","chalk","yellow","config","name","moment","format","onChange","filePath","buildResults","duration","length","formatCompileResults","onAdd","onUnlink","p","onError","err","type","CompilerErrorEvent","TYPE","data","error","registerToEvents","sub","CompilerAspect","id","eventsListener","report","cliArgs","watchCmdOpts","checkTypes","getCheckTypesEnum","undefined","CheckTypes","None","EntireProject","ChangedFile","Error","watchOpts","msgs","preCompile","skipPreCompilation","spawnTSServer","Boolean","watchAll","process","stdout","write"],"sources":["watch.cmd.tsx"],"sourcesContent":["import chalk from 'chalk';\nimport moment from 'moment';\nimport { Command, CommandOptions } from '@teambit/cli';\nimport type { Logger } from '@teambit/logger';\nimport type { BitBaseEvent, PubsubMain } from '@teambit/pubsub';\n\n// import IDs and events\nimport { CompilerAspect, CompilerErrorEvent } from '@teambit/compiler';\n\nimport { Watcher, WatchOptions } from './watcher';\nimport { formatCompileResults, formatWatchPathsSortByComponent } from './output-formatter';\nimport { OnComponentEventResult } from '../on-component-events';\nimport { CheckTypes } from './check-types';\n\nexport type WatchCmdOpts = {\n verbose?: boolean;\n skipPreCompilation?: boolean;\n checkTypes?: string | boolean;\n};\n\nexport class WatchCommand implements Command {\n msgs = {\n onAll: (event: string, path: string) => this.logger.console(`Event: \"${event}\". Path: ${path}`),\n onStart: () => {},\n onReady: (workspace, watchPathsSortByComponent, verbose) => {\n clearOutdatedData();\n if (verbose) {\n this.logger.console(formatWatchPathsSortByComponent(watchPathsSortByComponent));\n }\n this.logger.console(\n chalk.yellow(\n `Watching for component changes in workspace ${workspace.config.name} (${moment().format('HH:mm:ss')})...\\n`\n )\n );\n },\n onChange: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration) => {\n clearOutdatedData();\n if (!buildResults.length) {\n this.logger.console(`The file ${filePath} has been changed, but nothing to compile.\\n\\n`);\n return;\n }\n this.logger.console(`The file ${filePath} has been changed.\\n\\n`);\n this.logger.console(formatCompileResults(buildResults, verbose));\n this.logger.console(`Finished. (${duration}ms)`);\n this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));\n },\n onAdd: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration) => {\n clearOutdatedData();\n this.logger.console(`The file ${filePath} has been added.\\n\\n`);\n this.logger.console(formatCompileResults(buildResults, verbose));\n this.logger.console(`Finished. (${duration}ms)`);\n this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));\n },\n onUnlink: (p) => {\n this.logger.console(`file ${p} has been removed`);\n },\n onError: (err) => {\n this.logger.console(`Watcher error ${err}`);\n },\n };\n\n name = 'watch';\n description = 'watch a set of components';\n alias = '';\n group = 'development';\n shortDescription = '';\n options = [\n ['v', 'verbose', 'showing npm verbose output for inspection and prints stack trace'],\n ['', 'skip-pre-compilation', 'skip the compilation step before starting to watch'],\n [\n 't',\n 'check-types [string]',\n 'EXPERIMENTAL. show errors/warnings for types. options are [file, project] to investigate only changed file or entire project. defaults to project',\n ],\n ] as CommandOptions;\n\n constructor(\n /**\n * logger extension.\n */\n private pubsub: PubsubMain,\n\n /**\n * logger extension.\n */\n private logger: Logger,\n\n /**\n * watcher extension.\n */\n private watcher: Watcher\n ) {\n this.registerToEvents();\n }\n\n private registerToEvents() {\n this.pubsub.sub(CompilerAspect.id, this.eventsListener);\n }\n\n private eventsListener = (event: BitBaseEvent<any>) => {\n switch (event.type) {\n case CompilerErrorEvent.TYPE:\n this.logger.console(`Watcher error ${event.data.error}, 'error'`);\n break;\n default:\n }\n };\n\n async report(cliArgs: [], watchCmdOpts: WatchCmdOpts) {\n const { verbose, checkTypes } = watchCmdOpts;\n const getCheckTypesEnum = () => {\n switch (checkTypes) {\n case undefined:\n case false:\n return CheckTypes.None;\n case 'project':\n case true: // project is the default\n return CheckTypes.EntireProject;\n case 'file':\n return CheckTypes.ChangedFile;\n default:\n throw new Error(`check-types can be either \"file\" or \"project\". got \"${checkTypes}\"`);\n }\n };\n const watchOpts: WatchOptions = {\n msgs: this.msgs,\n verbose,\n preCompile: !watchCmdOpts.skipPreCompilation,\n spawnTSServer: Boolean(checkTypes), // if check-types is enabled, it must spawn the tsserver.\n checkTypes: getCheckTypesEnum(),\n };\n await this.watcher.watchAll(watchOpts);\n return 'watcher terminated';\n }\n}\n\n/**\n * with console.clear() all history is deleted from the console. this function preserver the history.\n */\nfunction clearOutdatedData() {\n process.stdout.write('\\x1Bc');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AANA;AAcO,MAAMA,YAAN,CAAsC;EAwD3CC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,MATC;EAWT;AACJ;AACA;EACYC,OAdC,EAeT;IAAA,KAXQF,MAWR,GAX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gB,GAAG;IACzB,KAAKpC,MAAL,CAAYqC,GAAZ,CAAgBC,0BAAA,CAAeC,EAA/B,EAAmC,KAAKC,cAAxC;EACD;;EAWW,MAANC,MAAM,CAACC,OAAD,EAAcC,YAAd,EAA0C;IACpD,MAAM;MAAEhC,OAAF;MAAWiC;IAAX,IAA0BD,YAAhC;;IACA,MAAME,iBAAiB,GAAG,MAAM;MAC9B,QAAQD,UAAR;QACE,KAAKE,SAAL;QACA,KAAK,KAAL;UACE,OAAOC,wBAAA,CAAWC,IAAlB;;QACF,KAAK,SAAL;QACA,KAAK,IAAL;UAAW;UACT,OAAOD,wBAAA,CAAWE,aAAlB;;QACF,KAAK,MAAL;UACE,OAAOF,wBAAA,CAAWG,WAAlB;;QACF;UACE,MAAM,IAAIC,KAAJ,CAAW,uDAAsDP,UAAW,GAA5E,CAAN;MAVJ;IAYD,CAbD;;IAcA,MAAMQ,SAAuB,GAAG;MAC9BC,IAAI,EAAE,KAAKA,IADmB;MAE9B1C,OAF8B;MAG9B2C,UAAU,EAAE,CAACX,YAAY,CAACY,kBAHI;MAI9BC,aAAa,EAAEC,OAAO,CAACb,UAAD,CAJQ;MAIM;MACpCA,UAAU,EAAEC,iBAAiB;IALC,CAAhC;IAOA,MAAM,KAAK3C,OAAL,CAAawD,QAAb,CAAsBN,SAAtB,CAAN;IACA,OAAO,oBAAP;EACD;;AAjH0C;AAoH7C;AACA;AACA;;;;;AACA,SAASxC,iBAAT,GAA6B;EAC3B+C,OAAO,CAACC,MAAR,CAAeC,KAAf,CAAqB,OAArB;AACD"}
1
+ {"version":3,"names":["WatchCommand","constructor","pubsub","logger","watcher","onAll","event","path","console","onStart","onReady","workspace","watchPathsSortByComponent","verbose","clearOutdatedData","formatWatchPathsSortByComponent","chalk","yellow","config","name","moment","format","onChange","filePaths","buildResults","duration","failureMsg","files","join","length","formatCompileResults","onAdd","onUnlink","p","onError","err","type","CompilerErrorEvent","TYPE","data","error","registerToEvents","sub","CompilerAspect","id","eventsListener","report","cliArgs","watchCmdOpts","checkTypes","getCheckTypesEnum","undefined","CheckTypes","None","EntireProject","ChangedFile","Error","watchOpts","msgs","preCompile","skipPreCompilation","spawnTSServer","Boolean","watchAll","process","stdout","write"],"sources":["watch.cmd.tsx"],"sourcesContent":["import chalk from 'chalk';\nimport moment from 'moment';\nimport { Command, CommandOptions } from '@teambit/cli';\nimport type { Logger } from '@teambit/logger';\nimport type { BitBaseEvent, PubsubMain } from '@teambit/pubsub';\n\n// import IDs and events\nimport { CompilerAspect, CompilerErrorEvent } from '@teambit/compiler';\n\nimport { Watcher, WatchOptions } from './watcher';\nimport { formatCompileResults, formatWatchPathsSortByComponent } from './output-formatter';\nimport { OnComponentEventResult } from '../on-component-events';\nimport { CheckTypes } from './check-types';\n\nexport type WatchCmdOpts = {\n verbose?: boolean;\n skipPreCompilation?: boolean;\n checkTypes?: string | boolean;\n};\n\nexport class WatchCommand implements Command {\n msgs = {\n onAll: (event: string, path: string) => this.logger.console(`Event: \"${event}\". Path: ${path}`),\n onStart: () => {},\n onReady: (workspace, watchPathsSortByComponent, verbose) => {\n clearOutdatedData();\n if (verbose) {\n this.logger.console(formatWatchPathsSortByComponent(watchPathsSortByComponent));\n }\n this.logger.console(\n chalk.yellow(\n `Watching for component changes in workspace ${workspace.config.name} (${moment().format('HH:mm:ss')})...\\n`\n )\n );\n },\n onChange: (\n filePaths: string[],\n buildResults: OnComponentEventResult[],\n verbose: boolean,\n duration,\n failureMsg?: string\n ) => {\n const files = filePaths.join(', ');\n clearOutdatedData();\n if (!buildResults.length) {\n failureMsg = failureMsg || `The files ${files} have been changed, but nothing to compile`;\n this.logger.console(`${failureMsg}\\n\\n`);\n return;\n }\n this.logger.console(`The file(s) ${files} have been changed.\\n\\n`);\n this.logger.console(formatCompileResults(buildResults, verbose));\n this.logger.console(`Finished. (${duration}ms)`);\n this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));\n },\n onAdd: (\n filePaths: string[],\n buildResults: OnComponentEventResult[],\n verbose: boolean,\n duration,\n failureMsg?: string\n ) => {\n const files = filePaths.join(', ');\n clearOutdatedData();\n if (!buildResults.length) {\n failureMsg = failureMsg || `The files ${files} have been added, but nothing to compile`;\n this.logger.console(`${failureMsg}\\n\\n`);\n return;\n }\n this.logger.console(`The file(s) ${filePaths} have been added.\\n\\n`);\n this.logger.console(formatCompileResults(buildResults, verbose));\n this.logger.console(`Finished. (${duration}ms)`);\n this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));\n },\n onUnlink: (p) => {\n this.logger.console(`file ${p} has been removed`);\n },\n onError: (err) => {\n this.logger.console(`Watcher error ${err}`);\n },\n };\n\n name = 'watch';\n description = 'watch a set of components';\n alias = '';\n group = 'development';\n shortDescription = '';\n options = [\n ['v', 'verbose', 'showing npm verbose output for inspection and prints stack trace'],\n ['', 'skip-pre-compilation', 'skip the compilation step before starting to watch'],\n [\n 't',\n 'check-types [string]',\n 'EXPERIMENTAL. show errors/warnings for types. options are [file, project] to investigate only changed file or entire project. defaults to project',\n ],\n ] as CommandOptions;\n\n constructor(\n /**\n * logger extension.\n */\n private pubsub: PubsubMain,\n\n /**\n * logger extension.\n */\n private logger: Logger,\n\n /**\n * watcher extension.\n */\n private watcher: Watcher\n ) {\n this.registerToEvents();\n }\n\n private registerToEvents() {\n this.pubsub.sub(CompilerAspect.id, this.eventsListener);\n }\n\n private eventsListener = (event: BitBaseEvent<any>) => {\n switch (event.type) {\n case CompilerErrorEvent.TYPE:\n this.logger.console(`Watcher error ${event.data.error}, 'error'`);\n break;\n default:\n }\n };\n\n async report(cliArgs: [], watchCmdOpts: WatchCmdOpts) {\n const { verbose, checkTypes } = watchCmdOpts;\n const getCheckTypesEnum = () => {\n switch (checkTypes) {\n case undefined:\n case false:\n return CheckTypes.None;\n case 'project':\n case true: // project is the default\n return CheckTypes.EntireProject;\n case 'file':\n return CheckTypes.ChangedFile;\n default:\n throw new Error(`check-types can be either \"file\" or \"project\". got \"${checkTypes}\"`);\n }\n };\n const watchOpts: WatchOptions = {\n msgs: this.msgs,\n verbose,\n preCompile: !watchCmdOpts.skipPreCompilation,\n spawnTSServer: Boolean(checkTypes), // if check-types is enabled, it must spawn the tsserver.\n checkTypes: getCheckTypesEnum(),\n };\n await this.watcher.watchAll(watchOpts);\n return 'watcher terminated';\n }\n}\n\n/**\n * with console.clear() all history is deleted from the console. this function preserver the history.\n */\nfunction clearOutdatedData() {\n process.stdout.write('\\x1Bc');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AANA;AAcO,MAAMA,YAAN,CAAsC;EA4E3CC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,MATC;EAWT;AACJ;AACA;EACYC,OAdC,EAeT;IAAA,KAXQF,MAWR,GAXQA,MAWR;IAAA,KANQC,MAMR,GANQA,MAMR;IAAA,KADQC,OACR,GADQA,OACR;IAAA,8CA1FK;MACLC,KAAK,EAAE,CAACC,KAAD,EAAgBC,IAAhB,KAAiC,KAAKJ,MAAL,CAAYK,OAAZ,CAAqB,WAAUF,KAAM,YAAWC,IAAK,EAArD,CADnC;MAELE,OAAO,EAAE,MAAM,CAAE,CAFZ;MAGLC,OAAO,EAAE,CAACC,SAAD,EAAYC,yBAAZ,EAAuCC,OAAvC,KAAmD;QAC1DC,iBAAiB;;QACjB,IAAID,OAAJ,EAAa;UACX,KAAKV,MAAL,CAAYK,OAAZ,CAAoB,IAAAO,kDAAA,EAAgCH,yBAAhC,CAApB;QACD;;QACD,KAAKT,MAAL,CAAYK,OAAZ,CACEQ,gBAAA,CAAMC,MAAN,CACG,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ACpD,MAAM;MAAEnC,OAAF;MAAWoC;IAAX,IAA0BD,YAAhC;;IACA,MAAME,iBAAiB,GAAG,MAAM;MAC9B,QAAQD,UAAR;QACE,KAAKE,SAAL;QACA,KAAK,KAAL;UACE,OAAOC,wBAAA,CAAWC,IAAlB;;QACF,KAAK,SAAL;QACA,KAAK,IAAL;UAAW;UACT,OAAOD,wBAAA,CAAWE,aAAlB;;QACF,KAAK,MAAL;UACE,OAAOF,wBAAA,CAAWG,WAAlB;;QACF;UACE,MAAM,IAAIC,KAAJ,CAAW,uDAAsDP,UAAW,GAA5E,CAAN;MAVJ;IAYD,CAbD;;IAcA,MAAMQ,SAAuB,GAAG;MAC9BC,IAAI,EAAE,KAAKA,IADmB;MAE9B7C,OAF8B;MAG9B8C,UAAU,EAAE,CAACX,YAAY,CAACY,kBAHI;MAI9BC,aAAa,EAAEC,OAAO,CAACb,UAAD,CAJQ;MAIM;MACpCA,UAAU,EAAEC,iBAAiB;IALC,CAAhC;IAOA,MAAM,KAAK9C,OAAL,CAAa2D,QAAb,CAAsBN,SAAtB,CAAN;IACA,OAAO,oBAAP;EACD;;AArI0C;AAwI7C;AACA;AACA;;;;;AACA,SAAS3C,iBAAT,GAA6B;EAC3BkD,OAAO,CAACC,MAAR,CAAeC,KAAf,CAAqB,OAArB;AACD"}
@@ -37,12 +37,37 @@ export declare class Watcher {
37
37
  private verbose;
38
38
  private multipleWatchers;
39
39
  private fsWatcher;
40
+ private changedFilesPerComponent;
40
41
  constructor(workspace: Workspace, pubsub: PubsubMain, trackDirs?: {
41
42
  [dir: PathLinux]: ComponentID;
42
43
  }, verbose?: boolean, multipleWatchers?: WatcherProcessData[]);
43
44
  get consumer(): Consumer;
44
45
  watchAll(opts: WatchOptions): Promise<unknown>;
46
+ /**
47
+ * some actions trigger multiple files changes at (almost) the same time. e.g. "git pull".
48
+ * this causes some performance and instability issues. a debouncing mechanism was implemented to help with this.
49
+ * the way how it works is that the first file of the same component starts the execution with a delay (e.g. 200ms).
50
+ * if, in the meanwhile, another file of the same component was changed, it won't start a new execution, instead,
51
+ * it'll only add the file to `this.changedFilesPerComponent` prop.
52
+ * once the execution starts, it'll delete this component-id from the `this.changedFilesPerComponent` array,
53
+ * indicating the next file-change to start a new execution.
54
+ *
55
+ * implementation wise, `lodash.debounce` doesn't help here, because:
56
+ * A) it doesn't return the results, unless "leading" option is true. here, it must be false, otherwise, it'll start
57
+ * the execution immediately.
58
+ * B) it debounces the method regardless the param passes to it. so it'll disregard the component-id and will delay
59
+ * other components undesirably.
60
+ *
61
+ */
45
62
  private handleChange;
63
+ private sleep;
64
+ /**
65
+ * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
66
+ * entire cache is invalidated and the consumer is reloaded.
67
+ * when a file just changed, no need to reload the consumer, it is enough to just delete the
68
+ * component from the cache (both, workspace and consumer)
69
+ */
70
+ private triggerCompChanges;
46
71
  /**
47
72
  * if .bitmap changed, it's possible that a new component has been added. trigger onComponentAdd.
48
73
  */
@@ -52,15 +77,9 @@ export declare class Watcher {
52
77
  private creatOnComponentRemovedEvent;
53
78
  private creatOnComponentChangeEvent;
54
79
  private creatOnComponentAddEvent;
55
- private completeWatch;
56
80
  private isComponentWatchedExternally;
57
- /**
58
- * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
59
- * entire cache is invalidated and the consumer is reloaded.
60
- * when a file just changed, no need to reload the consumer, it is enough to just delete the
61
- * component from the cache (both, workspace and consumer)
62
- */
63
- private getComponentIdAndClearItsCache;
81
+ private getComponentIdByPath;
82
+ private getRelativePathLinux;
64
83
  private findTrackDirByFilePathRecursively;
65
84
  private createWatcher;
66
85
  setTrackDirs(): Promise<void>;
@@ -149,6 +149,8 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (O
149
149
 
150
150
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2().default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
151
151
 
152
+ const DEBOUNCE_WAIT_MS = 100;
153
+
152
154
  class Watcher {
153
155
  constructor(workspace, pubsub, trackDirs = {}, verbose = false, multipleWatchers = []) {
154
156
  this.workspace = workspace;
@@ -157,6 +159,7 @@ class Watcher {
157
159
  this.verbose = verbose;
158
160
  this.multipleWatchers = multipleWatchers;
159
161
  (0, _defineProperty2().default)(this, "fsWatcher", void 0);
162
+ (0, _defineProperty2().default)(this, "changedFilesPerComponent", {});
160
163
  }
161
164
 
162
165
  get consumer() {
@@ -188,16 +191,36 @@ class Watcher {
188
191
 
189
192
  watcher.on('change', async filePath => {
190
193
  const startTime = new Date().getTime();
191
- const buildResults = (await this.handleChange(filePath, opts === null || opts === void 0 ? void 0 : opts.initiator)) || [];
194
+ const {
195
+ files,
196
+ results,
197
+ debounced,
198
+ failureMsg
199
+ } = await this.handleChange(filePath, opts === null || opts === void 0 ? void 0 : opts.initiator);
200
+
201
+ if (debounced) {
202
+ return;
203
+ }
204
+
192
205
  const duration = new Date().getTime() - startTime;
193
- msgs === null || msgs === void 0 ? void 0 : msgs.onChange(filePath, buildResults, this.verbose, duration);
206
+ msgs === null || msgs === void 0 ? void 0 : msgs.onChange(files, results, this.verbose, duration, failureMsg);
194
207
  }); // eslint-disable-next-line @typescript-eslint/no-misused-promises
195
208
 
196
209
  watcher.on('add', async filePath => {
197
210
  const startTime = new Date().getTime();
198
- const buildResults = (await this.handleChange(filePath)) || [];
211
+ const {
212
+ files,
213
+ results,
214
+ debounced,
215
+ failureMsg
216
+ } = await this.handleChange(filePath, opts === null || opts === void 0 ? void 0 : opts.initiator);
217
+
218
+ if (debounced) {
219
+ return;
220
+ }
221
+
199
222
  const duration = new Date().getTime() - startTime;
200
- msgs === null || msgs === void 0 ? void 0 : msgs.onAdd(filePath, buildResults, this.verbose, duration);
223
+ msgs === null || msgs === void 0 ? void 0 : msgs.onAdd(files, results, this.verbose, duration, failureMsg);
201
224
  }); // eslint-disable-next-line @typescript-eslint/no-misused-promises
202
225
 
203
226
  watcher.on('unlink', async p => {
@@ -210,26 +233,80 @@ class Watcher {
210
233
  });
211
234
  });
212
235
  }
236
+ /**
237
+ * some actions trigger multiple files changes at (almost) the same time. e.g. "git pull".
238
+ * this causes some performance and instability issues. a debouncing mechanism was implemented to help with this.
239
+ * the way how it works is that the first file of the same component starts the execution with a delay (e.g. 200ms).
240
+ * if, in the meanwhile, another file of the same component was changed, it won't start a new execution, instead,
241
+ * it'll only add the file to `this.changedFilesPerComponent` prop.
242
+ * once the execution starts, it'll delete this component-id from the `this.changedFilesPerComponent` array,
243
+ * indicating the next file-change to start a new execution.
244
+ *
245
+ * implementation wise, `lodash.debounce` doesn't help here, because:
246
+ * A) it doesn't return the results, unless "leading" option is true. here, it must be false, otherwise, it'll start
247
+ * the execution immediately.
248
+ * B) it debounces the method regardless the param passes to it. so it'll disregard the component-id and will delay
249
+ * other components undesirably.
250
+ *
251
+ */
252
+
213
253
 
214
254
  async handleChange(filePath, initiator) {
215
255
  try {
216
256
  if (filePath.endsWith(_constants().BIT_MAP)) {
217
257
  const buildResults = await this.handleBitmapChanges();
218
- this.completeWatch();
219
- return buildResults;
258
+
259
+ _loader().default.stop();
260
+
261
+ return {
262
+ results: buildResults,
263
+ files: [filePath]
264
+ };
220
265
  }
221
266
 
222
- const componentId = await this.getComponentIdAndClearItsCache(filePath);
267
+ const componentId = this.getComponentIdByPath(filePath);
223
268
 
224
269
  if (!componentId) {
225
- _logger().default.debug(`file ${filePath} is not part of any component, ignoring it`);
270
+ const failureMsg = `file ${filePath} is not part of any component, ignoring it`;
271
+
272
+ _logger().default.debug(failureMsg);
273
+
274
+ _loader().default.stop();
275
+
276
+ return {
277
+ results: [],
278
+ files: [filePath],
279
+ failureMsg
280
+ };
281
+ }
282
+
283
+ const compIdStr = componentId.toString();
226
284
 
227
- return this.completeWatch();
285
+ if (this.changedFilesPerComponent[compIdStr]) {
286
+ this.changedFilesPerComponent[compIdStr].push(filePath);
287
+
288
+ _loader().default.stop();
289
+
290
+ return {
291
+ results: [],
292
+ debounced: true
293
+ };
228
294
  }
229
295
 
230
- const buildResults = await this.executeWatchOperationsOnComponent(componentId, [filePath], true, initiator);
231
- this.completeWatch();
232
- return buildResults;
296
+ this.changedFilesPerComponent[compIdStr] = [filePath];
297
+ await this.sleep(DEBOUNCE_WAIT_MS);
298
+ const files = this.changedFilesPerComponent[compIdStr];
299
+ delete this.changedFilesPerComponent[compIdStr];
300
+ const buildResults = await this.triggerCompChanges(componentId, files, initiator);
301
+ const failureMsg = buildResults.length ? undefined : `files ${files.join(', ')} are inside the component ${compIdStr} but configured to be ignored`;
302
+
303
+ _loader().default.stop();
304
+
305
+ return {
306
+ results: buildResults,
307
+ files,
308
+ failureMsg
309
+ };
233
310
  } catch (err) {
234
311
  const msg = `watcher found an error while handling ${filePath}`;
235
312
 
@@ -237,8 +314,48 @@ class Watcher {
237
314
 
238
315
  _logger().default.console(`${msg}, ${err.message}`);
239
316
 
317
+ _loader().default.stop();
318
+
319
+ return {
320
+ results: [],
321
+ files: [filePath],
322
+ failureMsg: err.message
323
+ };
324
+ }
325
+ }
326
+
327
+ async sleep(ms) {
328
+ return new Promise(resolve => setTimeout(resolve, ms));
329
+ }
330
+ /**
331
+ * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
332
+ * entire cache is invalidated and the consumer is reloaded.
333
+ * when a file just changed, no need to reload the consumer, it is enough to just delete the
334
+ * component from the cache (both, workspace and consumer)
335
+ */
336
+
337
+
338
+ async triggerCompChanges(componentId, files, initiator) {
339
+ this.workspace.clearComponentCache(componentId);
340
+ const component = await this.workspace.get(componentId);
341
+ const componentMap = component.state._consumer.componentMap;
342
+ const compFiles = files.filter(filePath => {
343
+ const relativeFile = this.getRelativePathLinux(filePath);
344
+ const isCompFile = Boolean(componentMap.getFilesRelativeToConsumer().find(p => p === relativeFile));
345
+
346
+ if (!isCompFile) {
347
+ _logger().default.debug(`file ${filePath} is inside the component ${componentId.toString()} but configured to be ignored`);
348
+ }
349
+
350
+ return isCompFile;
351
+ });
352
+
353
+ if (!compFiles.length) {
240
354
  return [];
241
355
  }
356
+
357
+ const buildResults = await this.executeWatchOperationsOnComponent(componentId, compFiles, true, initiator);
358
+ return buildResults;
242
359
  }
243
360
  /**
244
361
  * if .bitmap changed, it's possible that a new component has been added. trigger onComponentAdd.
@@ -309,13 +426,7 @@ class Watcher {
309
426
  return [];
310
427
  }
311
428
 
312
- if (buildResults && buildResults.length) {
313
- return buildResults;
314
- }
315
-
316
- _logger().default.console(`${idStr} doesn't have a compiler, nothing to build`);
317
-
318
- return [];
429
+ return buildResults;
319
430
  }
320
431
 
321
432
  creatOnComponentRemovedEvent(idStr) {
@@ -330,12 +441,6 @@ class Watcher {
330
441
  return new (_events().OnComponentAddEvent)(Date.now(), idStr, hook);
331
442
  }
332
443
 
333
- completeWatch() {
334
- _loader().default.stop();
335
-
336
- return [];
337
- }
338
-
339
444
  isComponentWatchedExternally(componentId) {
340
445
  const watcherData = this.multipleWatchers.find(m => m.componentIds.find(id => id.isEqual(componentId._legacy)));
341
446
 
@@ -347,16 +452,9 @@ class Watcher {
347
452
 
348
453
  return false;
349
454
  }
350
- /**
351
- * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
352
- * entire cache is invalidated and the consumer is reloaded.
353
- * when a file just changed, no need to reload the consumer, it is enough to just delete the
354
- * component from the cache (both, workspace and consumer)
355
- */
356
455
 
357
-
358
- async getComponentIdAndClearItsCache(filePath) {
359
- const relativeFile = (0, _utils().pathNormalizeToLinux)(this.consumer.getPathRelativeToConsumer(filePath));
456
+ getComponentIdByPath(filePath) {
457
+ const relativeFile = this.getRelativePathLinux(filePath);
360
458
  const trackDir = this.findTrackDirByFilePathRecursively(relativeFile);
361
459
 
362
460
  if (!trackDir) {
@@ -365,17 +463,11 @@ class Watcher {
365
463
  return null;
366
464
  }
367
465
 
368
- const componentId = this.trackDirs[trackDir];
369
- this.workspace.clearComponentCache(componentId);
370
- const component = await this.workspace.get(componentId);
371
- const componentMap = component.state._consumer.componentMap;
372
-
373
- if (componentMap.getFilesRelativeToConsumer().find(p => p === relativeFile)) {
374
- return componentId;
375
- } // the file is inside the component dir but it's ignored. (e.g. it's in IGNORE_LIST)
376
-
466
+ return this.trackDirs[trackDir];
467
+ }
377
468
 
378
- return null;
469
+ getRelativePathLinux(filePath) {
470
+ return (0, _utils().pathNormalizeToLinux)(this.consumer.getPathRelativeToConsumer(filePath));
379
471
  }
380
472
 
381
473
  findTrackDirByFilePathRecursively(filePath) {
@@ -1 +1 @@
1
- {"version":3,"names":["Watcher","constructor","workspace","pubsub","trackDirs","verbose","multipleWatchers","consumer","watchAll","opts","msgs","watchOpts","pathsToWatch","getPathsToWatch","componentIds","Object","values","triggerOnPreWatch","createWatcher","watcher","fsWatcher","onStart","Promise","resolve","reject","process","env","BIT_LOG","onAll","on","onReady","filePath","startTime","Date","getTime","buildResults","handleChange","initiator","duration","onChange","onAdd","p","onUnlink","err","onError","endsWith","BIT_MAP","handleBitmapChanges","completeWatch","componentId","getComponentIdAndClearItsCache","logger","debug","executeWatchOperationsOnComponent","msg","error","console","message","previewsTrackDirs","_reloadConsumer","setTrackDirs","newDirs","difference","keys","removedDirs","results","length","add","addResults","mapSeries","dir","push","flat","unwatch","executeWatchOperationsOnRemove","chalk","bold","toString","pub","WorkspaceAspect","id","creatOnComponentRemovedEvent","triggerOnComponentRemove","files","isChange","isComponentWatchedExternally","get","idStr","creatOnComponentChangeEvent","creatOnComponentAddEvent","triggerOnComponentChange","triggerOnComponentAdd","OnComponentRemovedEvent","now","hook","OnComponentChangeEvent","OnComponentAddEvent","loader","stop","watcherData","find","m","isEqual","_legacy","compilerId","relativeFile","pathNormalizeToLinux","getPathRelativeToConsumer","trackDir","findTrackDirByFilePathRecursively","clearComponentCache","component","componentMap","state","_consumer","getFilesRelativeToConsumer","parentDir","dirname","chokidar","watch","ignoreInitial","ignored","path","includes","sep","persistent","useFsEvents","componentsFromBitMap","bitMap","getAllComponents","COMPONENT_ORIGINS","AUTHORED","IMPORTED","all","map","bitId","getTrackDir","Error","resolveComponentId","paths","pathsAbsolute","toAbsolutePath"],"sources":["watcher.ts"],"sourcesContent":["import { PubsubMain } from '@teambit/pubsub';\nimport { dirname, sep } from 'path';\nimport { difference } from 'lodash';\nimport { ComponentID } from '@teambit/component';\nimport { BitId } from '@teambit/legacy-bit-id';\nimport loader from '@teambit/legacy/dist/cli/loader';\nimport { BIT_MAP, COMPONENT_ORIGINS } from '@teambit/legacy/dist/constants';\nimport { Consumer } from '@teambit/legacy/dist/consumer';\nimport logger from '@teambit/legacy/dist/logger/logger';\nimport { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';\nimport mapSeries from 'p-map-series';\nimport chalk from 'chalk';\nimport { ChildProcess } from 'child_process';\nimport chokidar, { FSWatcher } from 'chokidar';\nimport ComponentMap from '@teambit/legacy/dist/consumer/bit-map/component-map';\nimport { PathLinux, PathOsBasedAbsolute } from '@teambit/legacy/dist/utils/path';\nimport { CompilationInitiator } from '@teambit/compiler';\nimport { WorkspaceAspect } from '../';\nimport { OnComponentChangeEvent, OnComponentAddEvent, OnComponentRemovedEvent } from '../events';\nimport { Workspace } from '../workspace';\nimport { OnComponentEventResult } from '../on-component-events';\nimport { CheckTypes } from './check-types';\n\nexport type WatcherProcessData = { watchProcess: ChildProcess; compilerId: BitId; componentIds: BitId[] };\n\nexport type EventMessages = {\n onAll: Function;\n onStart: Function;\n onReady: Function;\n onChange: Function;\n onAdd: Function;\n onUnlink: Function;\n onError: Function;\n};\n\nexport type WatchOptions = {\n msgs?: EventMessages;\n initiator?: CompilationInitiator;\n verbose?: boolean; // print watch events to the console. (also ts-server events if spawnTSServer is true)\n spawnTSServer?: boolean; // needed for check types and extract API/docs.\n checkTypes?: CheckTypes; // if enabled, the spawnTSServer becomes true.\n preCompile?: boolean; // whether compile all components before start watching\n};\n\nexport class Watcher {\n private fsWatcher: FSWatcher;\n constructor(\n private workspace: Workspace,\n private pubsub: PubsubMain,\n private trackDirs: { [dir: PathLinux]: ComponentID } = {},\n private verbose = false,\n private multipleWatchers: WatcherProcessData[] = []\n ) {}\n\n get consumer(): Consumer {\n return this.workspace.consumer;\n }\n\n async watchAll(opts: WatchOptions) {\n const { msgs, ...watchOpts } = opts;\n // TODO: run build in the beginning of process (it's work like this in other envs)\n const pathsToWatch = await this.getPathsToWatch();\n const componentIds = Object.values(this.trackDirs);\n await this.workspace.triggerOnPreWatch(componentIds, watchOpts);\n await this.createWatcher(pathsToWatch);\n const watcher = this.fsWatcher;\n msgs?.onStart(this.workspace);\n\n return new Promise((resolve, reject) => {\n // prefix your command with \"BIT_LOG=*\" to see all watch events\n if (process.env.BIT_LOG) {\n // @ts-ignore\n if (msgs?.onAll) watcher.on('all', msgs?.onAll);\n }\n watcher.on('ready', () => {\n msgs?.onReady(this.workspace, this.trackDirs, this.verbose);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('change', async (filePath) => {\n const startTime = new Date().getTime();\n const buildResults = (await this.handleChange(filePath, opts?.initiator)) || [];\n const duration = new Date().getTime() - startTime;\n msgs?.onChange(filePath, buildResults, this.verbose, duration);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('add', async (filePath) => {\n const startTime = new Date().getTime();\n const buildResults = (await this.handleChange(filePath)) || [];\n const duration = new Date().getTime() - startTime;\n msgs?.onAdd(filePath, buildResults, this.verbose, duration);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('unlink', async (p) => {\n msgs?.onUnlink(p);\n await this.handleChange(p);\n });\n watcher.on('error', (err) => {\n msgs?.onError(err);\n reject(err);\n });\n });\n }\n\n private async handleChange(filePath: string, initiator?: CompilationInitiator): Promise<OnComponentEventResult[]> {\n try {\n if (filePath.endsWith(BIT_MAP)) {\n const buildResults = await this.handleBitmapChanges();\n this.completeWatch();\n return buildResults;\n }\n const componentId = await this.getComponentIdAndClearItsCache(filePath);\n if (!componentId) {\n logger.debug(`file ${filePath} is not part of any component, ignoring it`);\n return this.completeWatch();\n }\n\n const buildResults = await this.executeWatchOperationsOnComponent(componentId, [filePath], true, initiator);\n this.completeWatch();\n return buildResults;\n } catch (err: any) {\n const msg = `watcher found an error while handling ${filePath}`;\n logger.error(msg, err);\n logger.console(`${msg}, ${err.message}`);\n return [];\n }\n }\n\n /**\n * if .bitmap changed, it's possible that a new component has been added. trigger onComponentAdd.\n */\n private async handleBitmapChanges(): Promise<OnComponentEventResult[]> {\n const previewsTrackDirs = { ...this.trackDirs };\n await this.workspace._reloadConsumer();\n await this.setTrackDirs();\n const newDirs: string[] = difference(Object.keys(this.trackDirs), Object.keys(previewsTrackDirs));\n const removedDirs: string[] = difference(Object.keys(previewsTrackDirs), Object.keys(this.trackDirs));\n const results: OnComponentEventResult[] = [];\n if (newDirs.length) {\n this.fsWatcher.add(newDirs);\n const addResults = await mapSeries(newDirs, async (dir) =>\n this.executeWatchOperationsOnComponent(this.trackDirs[dir], [], false)\n );\n results.push(...addResults.flat());\n }\n if (removedDirs.length) {\n await this.fsWatcher.unwatch(removedDirs);\n await mapSeries(removedDirs, (dir) => this.executeWatchOperationsOnRemove(previewsTrackDirs[dir]));\n }\n return results;\n }\n\n private async executeWatchOperationsOnRemove(componentId: ComponentID) {\n logger.debug(`running OnComponentRemove hook for ${chalk.bold(componentId.toString())}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentRemovedEvent(componentId.toString()));\n await this.workspace.triggerOnComponentRemove(componentId);\n }\n\n private async executeWatchOperationsOnComponent(\n componentId: ComponentID,\n files: string[],\n isChange = true,\n initiator?: CompilationInitiator\n ): Promise<OnComponentEventResult[]> {\n if (this.isComponentWatchedExternally(componentId)) {\n // update capsule, once done, it automatically triggers the external watcher\n await this.workspace.get(componentId);\n return [];\n }\n const idStr = componentId.toString();\n\n if (isChange) {\n logger.debug(`running OnComponentChange hook for ${chalk.bold(idStr)}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentChangeEvent(idStr, 'OnComponentChange'));\n } else {\n logger.debug(`running OnComponentAdd hook for ${chalk.bold(idStr)}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentAddEvent(idStr, 'OnComponentAdd'));\n }\n\n let buildResults: OnComponentEventResult[];\n try {\n buildResults = isChange\n ? await this.workspace.triggerOnComponentChange(componentId, files, initiator)\n : await this.workspace.triggerOnComponentAdd(componentId);\n } catch (err: any) {\n // do not exit the watch process on errors, just print them\n const msg = `found an issue during onComponentChange or onComponentAdd hooks`;\n logger.error(msg, err);\n logger.console(`\\n${msg}: ${err.message || err}`);\n return [];\n }\n if (buildResults && buildResults.length) {\n return buildResults;\n }\n logger.console(`${idStr} doesn't have a compiler, nothing to build`);\n return [];\n }\n\n private creatOnComponentRemovedEvent(idStr) {\n return new OnComponentRemovedEvent(Date.now(), idStr);\n }\n\n private creatOnComponentChangeEvent(idStr, hook) {\n return new OnComponentChangeEvent(Date.now(), idStr, hook);\n }\n\n private creatOnComponentAddEvent(idStr, hook) {\n return new OnComponentAddEvent(Date.now(), idStr, hook);\n }\n\n private completeWatch() {\n loader.stop();\n return [];\n }\n\n private isComponentWatchedExternally(componentId: ComponentID) {\n const watcherData = this.multipleWatchers.find((m) => m.componentIds.find((id) => id.isEqual(componentId._legacy)));\n if (watcherData) {\n logger.debug(`${componentId.toString()} is watched by ${watcherData.compilerId.toString()}`);\n return true;\n }\n return false;\n }\n\n /**\n * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the\n * entire cache is invalidated and the consumer is reloaded.\n * when a file just changed, no need to reload the consumer, it is enough to just delete the\n * component from the cache (both, workspace and consumer)\n */\n private async getComponentIdAndClearItsCache(filePath: string): Promise<ComponentID | null> {\n const relativeFile = pathNormalizeToLinux(this.consumer.getPathRelativeToConsumer(filePath));\n const trackDir = this.findTrackDirByFilePathRecursively(relativeFile);\n if (!trackDir) {\n // the file is not part of any component. If it was a new component, or a new file of\n // existing component, then, handleBitmapChanges() should deal with it.\n return null;\n }\n const componentId = this.trackDirs[trackDir];\n this.workspace.clearComponentCache(componentId);\n const component = await this.workspace.get(componentId);\n const componentMap: ComponentMap = component.state._consumer.componentMap;\n if (componentMap.getFilesRelativeToConsumer().find((p) => p === relativeFile)) {\n return componentId;\n }\n // the file is inside the component dir but it's ignored. (e.g. it's in IGNORE_LIST)\n return null;\n }\n\n private findTrackDirByFilePathRecursively(filePath: string): string | null {\n if (this.trackDirs[filePath]) return filePath;\n const parentDir = dirname(filePath);\n if (parentDir === filePath) return null;\n return this.findTrackDirByFilePathRecursively(parentDir);\n }\n\n private async createWatcher(pathsToWatch: string[]) {\n this.fsWatcher = chokidar.watch(pathsToWatch, {\n ignoreInitial: true,\n // Using the function way since the regular way not working as expected\n // It might be solved when upgrading to chokidar > 3.0.0\n // See:\n // https://github.com/paulmillr/chokidar/issues/773\n // https://github.com/paulmillr/chokidar/issues/492\n // https://github.com/paulmillr/chokidar/issues/724\n ignored: (path) => {\n // Ignore package.json temporarily since it cerates endless loop since it's re-written after each build\n if (path.includes(`${sep}node_modules${sep}`) || path.includes(`${sep}package.json`)) {\n return true;\n }\n return false;\n },\n persistent: true,\n useFsEvents: false,\n });\n }\n\n async setTrackDirs() {\n this.trackDirs = {};\n const componentsFromBitMap = this.consumer.bitMap.getAllComponents([\n COMPONENT_ORIGINS.AUTHORED,\n COMPONENT_ORIGINS.IMPORTED,\n ]);\n await Promise.all(\n componentsFromBitMap.map(async (componentMap) => {\n const bitId = componentMap.id;\n const trackDir = componentMap.getTrackDir();\n if (!trackDir) throw new Error(`${bitId.toString()} has no rootDir, which is invalid in Harmony`);\n const componentId = await this.workspace.resolveComponentId(bitId);\n this.trackDirs[trackDir] = componentId;\n })\n );\n }\n\n private async getPathsToWatch(): Promise<PathOsBasedAbsolute[]> {\n await this.setTrackDirs();\n const paths = [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,CAA7B;IAIA,MAAM9G,OAAO,CAAC+G,GAAR,CACJN,oBAAoB,CAACO,GAArB,CAAyB,MAAOtB,YAAP,IAAwB;MAC/C,MAAMuB,KAAK,GAAGvB,YAAY,CAAChC,EAA3B;MACA,MAAM4B,QAAQ,GAAGI,YAAY,CAACwB,WAAb,EAAjB;MACA,IAAI,CAAC5B,QAAL,EAAe,MAAM,IAAI6B,KAAJ,CAAW,GAAEF,KAAK,CAAC1D,QAAN,EAAiB,8CAA9B,CAAN;MACf,MAAM5B,WAAW,GAAG,MAAM,KAAK/C,SAAL,CAAewI,kBAAf,CAAkCH,KAAlC,CAA1B;MACA,KAAKnI,SAAL,CAAewG,QAAf,IAA2B3D,WAA3B;IACD,CAND,CADI,CAAN;EASD;;EAE4B,MAAfpC,eAAe,GAAmC;IAC9D,MAAM,KAAK+C,YAAL,EAAN;IACA,MAAM+E,KAAK,GAAG,CAAC,GAAG5H,MAAM,CAACgD,IAAP,CAAY,KAAK3D,SAAjB,CAAJ,EAAiC0C,oBAAjC,CAAd;IACA,MAAM8F,aAAa,GAAGD,KAAK,CAACL,GAAN,CAAWhE,GAAD,IAAS,KAAK/D,QAAL,CAAcsI,cAAd,CAA6BvE,GAA7B,CAAnB,CAAtB;IACA,OAAOsE,aAAP;EACD;;AA9PkB"}
1
+ {"version":3,"names":["DEBOUNCE_WAIT_MS","Watcher","constructor","workspace","pubsub","trackDirs","verbose","multipleWatchers","consumer","watchAll","opts","msgs","watchOpts","pathsToWatch","getPathsToWatch","componentIds","Object","values","triggerOnPreWatch","createWatcher","watcher","fsWatcher","onStart","Promise","resolve","reject","process","env","BIT_LOG","onAll","on","onReady","filePath","startTime","Date","getTime","files","results","debounced","failureMsg","handleChange","initiator","duration","onChange","onAdd","p","onUnlink","err","onError","endsWith","BIT_MAP","buildResults","handleBitmapChanges","loader","stop","componentId","getComponentIdByPath","logger","debug","compIdStr","toString","changedFilesPerComponent","push","sleep","triggerCompChanges","length","undefined","join","msg","error","console","message","ms","setTimeout","clearComponentCache","component","get","componentMap","state","_consumer","compFiles","filter","relativeFile","getRelativePathLinux","isCompFile","Boolean","getFilesRelativeToConsumer","find","executeWatchOperationsOnComponent","previewsTrackDirs","_reloadConsumer","setTrackDirs","newDirs","difference","keys","removedDirs","add","addResults","mapSeries","dir","flat","unwatch","executeWatchOperationsOnRemove","chalk","bold","pub","WorkspaceAspect","id","creatOnComponentRemovedEvent","triggerOnComponentRemove","isChange","isComponentWatchedExternally","idStr","creatOnComponentChangeEvent","creatOnComponentAddEvent","triggerOnComponentChange","triggerOnComponentAdd","OnComponentRemovedEvent","now","hook","OnComponentChangeEvent","OnComponentAddEvent","watcherData","m","isEqual","_legacy","compilerId","trackDir","findTrackDirByFilePathRecursively","pathNormalizeToLinux","getPathRelativeToConsumer","parentDir","dirname","chokidar","watch","ignoreInitial","ignored","path","includes","sep","persistent","useFsEvents","componentsFromBitMap","bitMap","getAllComponents","COMPONENT_ORIGINS","AUTHORED","IMPORTED","all","map","bitId","getTrackDir","Error","resolveComponentId","paths","pathsAbsolute","toAbsolutePath"],"sources":["watcher.ts"],"sourcesContent":["import { PubsubMain } from '@teambit/pubsub';\nimport { dirname, sep } from 'path';\nimport { difference } from 'lodash';\nimport { ComponentID } from '@teambit/component';\nimport { BitId } from '@teambit/legacy-bit-id';\nimport loader from '@teambit/legacy/dist/cli/loader';\nimport { BIT_MAP, COMPONENT_ORIGINS } from '@teambit/legacy/dist/constants';\nimport { Consumer } from '@teambit/legacy/dist/consumer';\nimport logger from '@teambit/legacy/dist/logger/logger';\nimport { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';\nimport mapSeries from 'p-map-series';\nimport chalk from 'chalk';\nimport { ChildProcess } from 'child_process';\nimport chokidar, { FSWatcher } from 'chokidar';\nimport ComponentMap from '@teambit/legacy/dist/consumer/bit-map/component-map';\nimport { PathLinux, PathOsBasedAbsolute } from '@teambit/legacy/dist/utils/path';\nimport { CompilationInitiator } from '@teambit/compiler';\nimport { WorkspaceAspect } from '../';\nimport { OnComponentChangeEvent, OnComponentAddEvent, OnComponentRemovedEvent } from '../events';\nimport { Workspace } from '../workspace';\nimport { OnComponentEventResult } from '../on-component-events';\nimport { CheckTypes } from './check-types';\n\nexport type WatcherProcessData = { watchProcess: ChildProcess; compilerId: BitId; componentIds: BitId[] };\n\nexport type EventMessages = {\n onAll: Function;\n onStart: Function;\n onReady: Function;\n onChange: Function;\n onAdd: Function;\n onUnlink: Function;\n onError: Function;\n};\n\nexport type WatchOptions = {\n msgs?: EventMessages;\n initiator?: CompilationInitiator;\n verbose?: boolean; // print watch events to the console. (also ts-server events if spawnTSServer is true)\n spawnTSServer?: boolean; // needed for check types and extract API/docs.\n checkTypes?: CheckTypes; // if enabled, the spawnTSServer becomes true.\n preCompile?: boolean; // whether compile all components before start watching\n};\n\nconst DEBOUNCE_WAIT_MS = 100;\n\nexport class Watcher {\n private fsWatcher: FSWatcher;\n private changedFilesPerComponent: { [componentId: string]: string[] } = {};\n constructor(\n private workspace: Workspace,\n private pubsub: PubsubMain,\n private trackDirs: { [dir: PathLinux]: ComponentID } = {},\n private verbose = false,\n private multipleWatchers: WatcherProcessData[] = []\n ) {}\n\n get consumer(): Consumer {\n return this.workspace.consumer;\n }\n\n async watchAll(opts: WatchOptions) {\n const { msgs, ...watchOpts } = opts;\n // TODO: run build in the beginning of process (it's work like this in other envs)\n const pathsToWatch = await this.getPathsToWatch();\n const componentIds = Object.values(this.trackDirs);\n await this.workspace.triggerOnPreWatch(componentIds, watchOpts);\n await this.createWatcher(pathsToWatch);\n const watcher = this.fsWatcher;\n msgs?.onStart(this.workspace);\n\n return new Promise((resolve, reject) => {\n // prefix your command with \"BIT_LOG=*\" to see all watch events\n if (process.env.BIT_LOG) {\n // @ts-ignore\n if (msgs?.onAll) watcher.on('all', msgs?.onAll);\n }\n watcher.on('ready', () => {\n msgs?.onReady(this.workspace, this.trackDirs, this.verbose);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('change', async (filePath) => {\n const startTime = new Date().getTime();\n const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);\n if (debounced) {\n return;\n }\n const duration = new Date().getTime() - startTime;\n msgs?.onChange(files, results, this.verbose, duration, failureMsg);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('add', async (filePath) => {\n const startTime = new Date().getTime();\n const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);\n if (debounced) {\n return;\n }\n const duration = new Date().getTime() - startTime;\n msgs?.onAdd(files, results, this.verbose, duration, failureMsg);\n });\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n watcher.on('unlink', async (p) => {\n msgs?.onUnlink(p);\n await this.handleChange(p);\n });\n watcher.on('error', (err) => {\n msgs?.onError(err);\n reject(err);\n });\n });\n }\n\n /**\n * some actions trigger multiple files changes at (almost) the same time. e.g. \"git pull\".\n * this causes some performance and instability issues. a debouncing mechanism was implemented to help with this.\n * the way how it works is that the first file of the same component starts the execution with a delay (e.g. 200ms).\n * if, in the meanwhile, another file of the same component was changed, it won't start a new execution, instead,\n * it'll only add the file to `this.changedFilesPerComponent` prop.\n * once the execution starts, it'll delete this component-id from the `this.changedFilesPerComponent` array,\n * indicating the next file-change to start a new execution.\n *\n * implementation wise, `lodash.debounce` doesn't help here, because:\n * A) it doesn't return the results, unless \"leading\" option is true. here, it must be false, otherwise, it'll start\n * the execution immediately.\n * B) it debounces the method regardless the param passes to it. so it'll disregard the component-id and will delay\n * other components undesirably.\n *\n */\n private async handleChange(\n filePath: string,\n initiator?: CompilationInitiator\n ): Promise<{\n results: OnComponentEventResult[];\n files?: string[];\n failureMsg?: string;\n debounced?: boolean;\n }> {\n try {\n if (filePath.endsWith(BIT_MAP)) {\n const buildResults = await this.handleBitmapChanges();\n loader.stop();\n return { results: buildResults, files: [filePath] };\n }\n const componentId = this.getComponentIdByPath(filePath);\n if (!componentId) {\n const failureMsg = `file ${filePath} is not part of any component, ignoring it`;\n logger.debug(failureMsg);\n loader.stop();\n return { results: [], files: [filePath], failureMsg };\n }\n\n const compIdStr = componentId.toString();\n if (this.changedFilesPerComponent[compIdStr]) {\n this.changedFilesPerComponent[compIdStr].push(filePath);\n loader.stop();\n return { results: [], debounced: true };\n }\n this.changedFilesPerComponent[compIdStr] = [filePath];\n await this.sleep(DEBOUNCE_WAIT_MS);\n const files = this.changedFilesPerComponent[compIdStr];\n delete this.changedFilesPerComponent[compIdStr];\n\n const buildResults = await this.triggerCompChanges(componentId, files, initiator);\n const failureMsg = buildResults.length\n ? undefined\n : `files ${files.join(', ')} are inside the component ${compIdStr} but configured to be ignored`;\n loader.stop();\n return { results: buildResults, files, failureMsg };\n } catch (err: any) {\n const msg = `watcher found an error while handling ${filePath}`;\n logger.error(msg, err);\n logger.console(`${msg}, ${err.message}`);\n loader.stop();\n return { results: [], files: [filePath], failureMsg: err.message };\n }\n }\n\n private async sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the\n * entire cache is invalidated and the consumer is reloaded.\n * when a file just changed, no need to reload the consumer, it is enough to just delete the\n * component from the cache (both, workspace and consumer)\n */\n private async triggerCompChanges(\n componentId: ComponentID,\n files: string[],\n initiator?: CompilationInitiator\n ): Promise<OnComponentEventResult[]> {\n this.workspace.clearComponentCache(componentId);\n const component = await this.workspace.get(componentId);\n const componentMap: ComponentMap = component.state._consumer.componentMap;\n const compFiles = files.filter((filePath) => {\n const relativeFile = this.getRelativePathLinux(filePath);\n const isCompFile = Boolean(componentMap.getFilesRelativeToConsumer().find((p) => p === relativeFile));\n if (!isCompFile) {\n logger.debug(`file ${filePath} is inside the component ${componentId.toString()} but configured to be ignored`);\n }\n return isCompFile;\n });\n if (!compFiles.length) {\n return [];\n }\n const buildResults = await this.executeWatchOperationsOnComponent(componentId, compFiles, true, initiator);\n return buildResults;\n }\n\n /**\n * if .bitmap changed, it's possible that a new component has been added. trigger onComponentAdd.\n */\n private async handleBitmapChanges(): Promise<OnComponentEventResult[]> {\n const previewsTrackDirs = { ...this.trackDirs };\n await this.workspace._reloadConsumer();\n await this.setTrackDirs();\n const newDirs: string[] = difference(Object.keys(this.trackDirs), Object.keys(previewsTrackDirs));\n const removedDirs: string[] = difference(Object.keys(previewsTrackDirs), Object.keys(this.trackDirs));\n const results: OnComponentEventResult[] = [];\n if (newDirs.length) {\n this.fsWatcher.add(newDirs);\n const addResults = await mapSeries(newDirs, async (dir) =>\n this.executeWatchOperationsOnComponent(this.trackDirs[dir], [], false)\n );\n results.push(...addResults.flat());\n }\n if (removedDirs.length) {\n await this.fsWatcher.unwatch(removedDirs);\n await mapSeries(removedDirs, (dir) => this.executeWatchOperationsOnRemove(previewsTrackDirs[dir]));\n }\n return results;\n }\n\n private async executeWatchOperationsOnRemove(componentId: ComponentID) {\n logger.debug(`running OnComponentRemove hook for ${chalk.bold(componentId.toString())}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentRemovedEvent(componentId.toString()));\n await this.workspace.triggerOnComponentRemove(componentId);\n }\n\n private async executeWatchOperationsOnComponent(\n componentId: ComponentID,\n files: string[],\n isChange = true,\n initiator?: CompilationInitiator\n ): Promise<OnComponentEventResult[]> {\n if (this.isComponentWatchedExternally(componentId)) {\n // update capsule, once done, it automatically triggers the external watcher\n await this.workspace.get(componentId);\n return [];\n }\n const idStr = componentId.toString();\n\n if (isChange) {\n logger.debug(`running OnComponentChange hook for ${chalk.bold(idStr)}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentChangeEvent(idStr, 'OnComponentChange'));\n } else {\n logger.debug(`running OnComponentAdd hook for ${chalk.bold(idStr)}`);\n this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentAddEvent(idStr, 'OnComponentAdd'));\n }\n\n let buildResults: OnComponentEventResult[];\n try {\n buildResults = isChange\n ? await this.workspace.triggerOnComponentChange(componentId, files, initiator)\n : await this.workspace.triggerOnComponentAdd(componentId);\n } catch (err: any) {\n // do not exit the watch process on errors, just print them\n const msg = `found an issue during onComponentChange or onComponentAdd hooks`;\n logger.error(msg, err);\n logger.console(`\\n${msg}: ${err.message || err}`);\n return [];\n }\n return buildResults;\n }\n\n private creatOnComponentRemovedEvent(idStr) {\n return new OnComponentRemovedEvent(Date.now(), idStr);\n }\n\n private creatOnComponentChangeEvent(idStr, hook) {\n return new OnComponentChangeEvent(Date.now(), idStr, hook);\n }\n\n private creatOnComponentAddEvent(idStr, hook) {\n return new OnComponentAddEvent(Date.now(), idStr, hook);\n }\n\n private isComponentWatchedExternally(componentId: ComponentID) {\n const watcherData = this.multipleWatchers.find((m) => m.componentIds.find((id) => id.isEqual(componentId._legacy)));\n if (watcherData) {\n logger.debug(`${componentId.toString()} is watched by ${watcherData.compilerId.toString()}`);\n return true;\n }\n return false;\n }\n\n private getComponentIdByPath(filePath: string): ComponentID | null {\n const relativeFile = this.getRelativePathLinux(filePath);\n const trackDir = this.findTrackDirByFilePathRecursively(relativeFile);\n if (!trackDir) {\n // the file is not part of any component. If it was a new component, or a new file of\n // existing component, then, handleBitmapChanges() should deal with it.\n return null;\n }\n return this.trackDirs[trackDir];\n }\n\n private getRelativePathLinux(filePath: string) {\n return pathNormalizeToLinux(this.consumer.getPathRelativeToConsumer(filePath));\n }\n\n private findTrackDirByFilePathRecursively(filePath: string): string | null {\n if (this.trackDirs[filePath]) return filePath;\n const parentDir = dirname(filePath);\n if (parentDir === filePath) return null;\n return this.findTrackDirByFilePathRecursively(parentDir);\n }\n\n private async createWatcher(pathsToWatch: string[]) {\n this.fsWatcher = chokidar.watch(pathsToWatch, {\n ignoreInitial: true,\n // Using the function way since the regular way not working as expected\n // It might be solved when upgrading to chokidar > 3.0.0\n // See:\n // https://github.com/paulmillr/chokidar/issues/773\n // https://github.com/paulmillr/chokidar/issues/492\n // https://github.com/paulmillr/chokidar/issues/724\n ignored: (path) => {\n // Ignore package.json temporarily since it cerates endless loop since it's re-written after each build\n if (path.includes(`${sep}node_modules${sep}`) || path.includes(`${sep}package.json`)) {\n return true;\n }\n return false;\n },\n persistent: true,\n useFsEvents: false,\n });\n }\n\n async setTrackDirs() {\n this.trackDirs = {};\n const componentsFromBitMap = this.consumer.bitMap.getAllComponents([\n COMPONENT_ORIGINS.AUTHORED,\n COMPONENT_ORIGINS.IMPORTED,\n ]);\n await Promise.all(\n componentsFromBitMap.map(async (componentMap) => {\n const bitId = componentMap.id;\n const trackDir = componentMap.getTrackDir();\n if (!trackDir) throw new Error(`${bitId.toString()} has no rootDir, which is invalid in Harmony`);\n const componentId = await this.workspace.resolveComponentId(bitId);\n this.trackDirs[trackDir] = componentId;\n })\n );\n }\n\n private async getPathsToWatch(): Promise<PathOsBasedAbsolute[]> {\n await this.setTrackDirs();\n const paths = [...Object.keys(this.trackDirs), BIT_MAP];\n const pathsAbsolute = paths.map((dir) => this.consumer.toAbsolutePath(dir));\n return pathsAbsolute;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;;;;;AA0BA,MAAMA,gBAAgB,GAAG,GAAzB;;AAEO,MAAMC,OAAN,CAAc;EAGnBC,WAAW,CACDC,SADC,EAEDC,MAFC,EAGDC,SAA4C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CAAC6H,GAAR,CACJN,oBAAoB,CAACO,GAArB,CAAyB,MAAOxE,YAAP,IAAwB;MAC/C,MAAMyE,KAAK,GAAGzE,YAAY,CAAC8B,EAA3B;MACA,MAAMoB,QAAQ,GAAGlD,YAAY,CAAC0E,WAAb,EAAjB;MACA,IAAI,CAACxB,QAAL,EAAe,MAAM,IAAIyB,KAAJ,CAAW,GAAEF,KAAK,CAAC1F,QAAN,EAAiB,8CAA9B,CAAN;MACf,MAAML,WAAW,GAAG,MAAM,KAAKpD,SAAL,CAAesJ,kBAAf,CAAkCH,KAAlC,CAA1B;MACA,KAAKjJ,SAAL,CAAe0H,QAAf,IAA2BxE,WAA3B;IACD,CAND,CADI,CAAN;EASD;;EAE4B,MAAfzC,eAAe,GAAmC;IAC9D,MAAM,KAAK6E,YAAL,EAAN;IACA,MAAM+D,KAAK,GAAG,CAAC,GAAG1I,MAAM,CAAC8E,IAAP,CAAY,KAAKzF,SAAjB,CAAJ,EAAiC6C,oBAAjC,CAAd;IACA,MAAMyG,aAAa,GAAGD,KAAK,CAACL,GAAN,CAAWlD,GAAD,IAAS,KAAK3F,QAAL,CAAcoJ,cAAd,CAA6BzD,GAA7B,CAAnB,CAAtB;IACA,OAAOwD,aAAP;EACD;;AA5TkB"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/workspace",
3
- "version": "0.0.751",
3
+ "version": "0.0.752",
4
4
  "homepage": "https://bit.dev/teambit/workspace/workspace",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.workspace",
8
8
  "name": "workspace",
9
- "version": "0.0.751"
9
+ "version": "0.0.752"
10
10
  },
11
11
  "dependencies": {
12
12
  "lodash": "4.17.21",
@@ -40,37 +40,37 @@
40
40
  "@teambit/component-id": "0.0.402",
41
41
  "@teambit/legacy-bit-id": "0.0.399",
42
42
  "@teambit/logger": "0.0.589",
43
- "@teambit/scope": "0.0.751",
43
+ "@teambit/scope": "0.0.752",
44
44
  "@teambit/cli": "0.0.496",
45
- "@teambit/isolator": "0.0.751",
46
- "@teambit/component-tree": "0.0.539",
45
+ "@teambit/isolator": "0.0.752",
46
+ "@teambit/component-tree": "0.0.540",
47
47
  "@teambit/component.ui.component-status-resolver": "0.0.492",
48
48
  "@teambit/lanes.ui.lanes": "0.0.63",
49
49
  "@teambit/harmony.modules.resolved-component": "0.0.484",
50
- "@teambit/dependency-resolver": "0.0.751",
51
- "@teambit/compiler": "0.0.751",
52
- "@teambit/component": "0.0.751",
53
- "@teambit/graphql": "0.0.751",
54
- "@teambit/aspect-loader": "0.0.751",
55
- "@teambit/bundler": "0.0.751",
50
+ "@teambit/dependency-resolver": "0.0.752",
51
+ "@teambit/compiler": "0.0.752",
52
+ "@teambit/component": "0.0.752",
53
+ "@teambit/graphql": "0.0.752",
54
+ "@teambit/aspect-loader": "0.0.752",
55
+ "@teambit/bundler": "0.0.752",
56
56
  "@teambit/community": "0.0.44",
57
- "@teambit/envs": "0.0.751",
58
- "@teambit/pubsub": "0.0.751",
59
- "@teambit/ui": "0.0.751",
57
+ "@teambit/envs": "0.0.752",
58
+ "@teambit/pubsub": "0.0.752",
59
+ "@teambit/ui": "0.0.752",
60
60
  "@teambit/variants": "0.0.592",
61
61
  "@teambit/component-issues": "0.0.53",
62
62
  "@teambit/config": "0.0.509",
63
63
  "@teambit/harmony.modules.requireable-component": "0.0.484",
64
- "@teambit/importer": "0.0.180",
64
+ "@teambit/importer": "0.0.181",
65
65
  "@teambit/lane-id": "0.0.15",
66
66
  "@teambit/workspace.modules.match-pattern": "0.0.489",
67
67
  "@teambit/component.ui.component-drawer": "0.0.42",
68
68
  "@teambit/design.ui.tree": "0.0.5",
69
69
  "@teambit/ui-foundation.ui.side-bar": "0.0.560",
70
- "@teambit/command-bar": "0.0.751",
70
+ "@teambit/command-bar": "0.0.752",
71
71
  "@teambit/component.ui.component-filters": "0.0.5",
72
- "@teambit/graph": "0.0.751",
73
- "@teambit/sidebar": "0.0.751",
72
+ "@teambit/graph": "0.0.752",
73
+ "@teambit/sidebar": "0.0.752",
74
74
  "@teambit/ui-foundation.ui.main-dropdown": "0.0.487",
75
75
  "@teambit/ui-foundation.ui.menu": "0.0.487",
76
76
  "@teambit/ui-foundation.ui.react-router.slot-router": "0.0.490",
@@ -78,7 +78,7 @@
78
78
  "@teambit/toolbox.time.time-format": "0.0.483",
79
79
  "@teambit/ui-foundation.ui.hooks.use-data-query": "0.0.487",
80
80
  "@teambit/component-descriptor": "0.0.58",
81
- "@teambit/deprecation": "0.0.751",
81
+ "@teambit/deprecation": "0.0.752",
82
82
  "@teambit/ui-foundation.ui.constants.z-indexes": "0.0.487",
83
83
  "@teambit/ui-foundation.ui.buttons.collapser": "0.0.194",
84
84
  "@teambit/ui-foundation.ui.corner": "0.0.498",
@@ -1,2 +1,2 @@
1
- export const compositions = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.workspace_workspace@0.0.751/dist/workspace.composition.js')]
2
- export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.workspace_workspace@0.0.751/dist/workspace.docs.mdx')]
1
+ export const compositions = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.workspace_workspace@0.0.752/dist/workspace.composition.js')]
2
+ export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.workspace_workspace@0.0.752/dist/workspace.docs.mdx')]
@@ -33,20 +33,40 @@ export class WatchCommand implements Command {
33
33
  )
34
34
  );
35
35
  },
36
- onChange: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration) => {
36
+ onChange: (
37
+ filePaths: string[],
38
+ buildResults: OnComponentEventResult[],
39
+ verbose: boolean,
40
+ duration,
41
+ failureMsg?: string
42
+ ) => {
43
+ const files = filePaths.join(', ');
37
44
  clearOutdatedData();
38
45
  if (!buildResults.length) {
39
- this.logger.console(`The file ${filePath} has been changed, but nothing to compile.\n\n`);
46
+ failureMsg = failureMsg || `The files ${files} have been changed, but nothing to compile`;
47
+ this.logger.console(`${failureMsg}\n\n`);
40
48
  return;
41
49
  }
42
- this.logger.console(`The file ${filePath} has been changed.\n\n`);
50
+ this.logger.console(`The file(s) ${files} have been changed.\n\n`);
43
51
  this.logger.console(formatCompileResults(buildResults, verbose));
44
52
  this.logger.console(`Finished. (${duration}ms)`);
45
53
  this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));
46
54
  },
47
- onAdd: (filePath: string, buildResults: OnComponentEventResult[], verbose: boolean, duration) => {
55
+ onAdd: (
56
+ filePaths: string[],
57
+ buildResults: OnComponentEventResult[],
58
+ verbose: boolean,
59
+ duration,
60
+ failureMsg?: string
61
+ ) => {
62
+ const files = filePaths.join(', ');
48
63
  clearOutdatedData();
49
- this.logger.console(`The file ${filePath} has been added.\n\n`);
64
+ if (!buildResults.length) {
65
+ failureMsg = failureMsg || `The files ${files} have been added, but nothing to compile`;
66
+ this.logger.console(`${failureMsg}\n\n`);
67
+ return;
68
+ }
69
+ this.logger.console(`The file(s) ${filePaths} have been added.\n\n`);
50
70
  this.logger.console(formatCompileResults(buildResults, verbose));
51
71
  this.logger.console(`Finished. (${duration}ms)`);
52
72
  this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));
package/watch/watcher.ts CHANGED
@@ -42,8 +42,11 @@ export type WatchOptions = {
42
42
  preCompile?: boolean; // whether compile all components before start watching
43
43
  };
44
44
 
45
+ const DEBOUNCE_WAIT_MS = 100;
46
+
45
47
  export class Watcher {
46
48
  private fsWatcher: FSWatcher;
49
+ private changedFilesPerComponent: { [componentId: string]: string[] } = {};
47
50
  constructor(
48
51
  private workspace: Workspace,
49
52
  private pubsub: PubsubMain,
@@ -78,16 +81,22 @@ export class Watcher {
78
81
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
79
82
  watcher.on('change', async (filePath) => {
80
83
  const startTime = new Date().getTime();
81
- const buildResults = (await this.handleChange(filePath, opts?.initiator)) || [];
84
+ const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);
85
+ if (debounced) {
86
+ return;
87
+ }
82
88
  const duration = new Date().getTime() - startTime;
83
- msgs?.onChange(filePath, buildResults, this.verbose, duration);
89
+ msgs?.onChange(files, results, this.verbose, duration, failureMsg);
84
90
  });
85
91
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
86
92
  watcher.on('add', async (filePath) => {
87
93
  const startTime = new Date().getTime();
88
- const buildResults = (await this.handleChange(filePath)) || [];
94
+ const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);
95
+ if (debounced) {
96
+ return;
97
+ }
89
98
  const duration = new Date().getTime() - startTime;
90
- msgs?.onAdd(filePath, buildResults, this.verbose, duration);
99
+ msgs?.onAdd(files, results, this.verbose, duration, failureMsg);
91
100
  });
92
101
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
93
102
  watcher.on('unlink', async (p) => {
@@ -101,28 +110,102 @@ export class Watcher {
101
110
  });
102
111
  }
103
112
 
104
- private async handleChange(filePath: string, initiator?: CompilationInitiator): Promise<OnComponentEventResult[]> {
113
+ /**
114
+ * some actions trigger multiple files changes at (almost) the same time. e.g. "git pull".
115
+ * this causes some performance and instability issues. a debouncing mechanism was implemented to help with this.
116
+ * the way how it works is that the first file of the same component starts the execution with a delay (e.g. 200ms).
117
+ * if, in the meanwhile, another file of the same component was changed, it won't start a new execution, instead,
118
+ * it'll only add the file to `this.changedFilesPerComponent` prop.
119
+ * once the execution starts, it'll delete this component-id from the `this.changedFilesPerComponent` array,
120
+ * indicating the next file-change to start a new execution.
121
+ *
122
+ * implementation wise, `lodash.debounce` doesn't help here, because:
123
+ * A) it doesn't return the results, unless "leading" option is true. here, it must be false, otherwise, it'll start
124
+ * the execution immediately.
125
+ * B) it debounces the method regardless the param passes to it. so it'll disregard the component-id and will delay
126
+ * other components undesirably.
127
+ *
128
+ */
129
+ private async handleChange(
130
+ filePath: string,
131
+ initiator?: CompilationInitiator
132
+ ): Promise<{
133
+ results: OnComponentEventResult[];
134
+ files?: string[];
135
+ failureMsg?: string;
136
+ debounced?: boolean;
137
+ }> {
105
138
  try {
106
139
  if (filePath.endsWith(BIT_MAP)) {
107
140
  const buildResults = await this.handleBitmapChanges();
108
- this.completeWatch();
109
- return buildResults;
141
+ loader.stop();
142
+ return { results: buildResults, files: [filePath] };
110
143
  }
111
- const componentId = await this.getComponentIdAndClearItsCache(filePath);
144
+ const componentId = this.getComponentIdByPath(filePath);
112
145
  if (!componentId) {
113
- logger.debug(`file ${filePath} is not part of any component, ignoring it`);
114
- return this.completeWatch();
146
+ const failureMsg = `file ${filePath} is not part of any component, ignoring it`;
147
+ logger.debug(failureMsg);
148
+ loader.stop();
149
+ return { results: [], files: [filePath], failureMsg };
115
150
  }
116
151
 
117
- const buildResults = await this.executeWatchOperationsOnComponent(componentId, [filePath], true, initiator);
118
- this.completeWatch();
119
- return buildResults;
152
+ const compIdStr = componentId.toString();
153
+ if (this.changedFilesPerComponent[compIdStr]) {
154
+ this.changedFilesPerComponent[compIdStr].push(filePath);
155
+ loader.stop();
156
+ return { results: [], debounced: true };
157
+ }
158
+ this.changedFilesPerComponent[compIdStr] = [filePath];
159
+ await this.sleep(DEBOUNCE_WAIT_MS);
160
+ const files = this.changedFilesPerComponent[compIdStr];
161
+ delete this.changedFilesPerComponent[compIdStr];
162
+
163
+ const buildResults = await this.triggerCompChanges(componentId, files, initiator);
164
+ const failureMsg = buildResults.length
165
+ ? undefined
166
+ : `files ${files.join(', ')} are inside the component ${compIdStr} but configured to be ignored`;
167
+ loader.stop();
168
+ return { results: buildResults, files, failureMsg };
120
169
  } catch (err: any) {
121
170
  const msg = `watcher found an error while handling ${filePath}`;
122
171
  logger.error(msg, err);
123
172
  logger.console(`${msg}, ${err.message}`);
173
+ loader.stop();
174
+ return { results: [], files: [filePath], failureMsg: err.message };
175
+ }
176
+ }
177
+
178
+ private async sleep(ms: number) {
179
+ return new Promise((resolve) => setTimeout(resolve, ms));
180
+ }
181
+
182
+ /**
183
+ * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
184
+ * entire cache is invalidated and the consumer is reloaded.
185
+ * when a file just changed, no need to reload the consumer, it is enough to just delete the
186
+ * component from the cache (both, workspace and consumer)
187
+ */
188
+ private async triggerCompChanges(
189
+ componentId: ComponentID,
190
+ files: string[],
191
+ initiator?: CompilationInitiator
192
+ ): Promise<OnComponentEventResult[]> {
193
+ this.workspace.clearComponentCache(componentId);
194
+ const component = await this.workspace.get(componentId);
195
+ const componentMap: ComponentMap = component.state._consumer.componentMap;
196
+ const compFiles = files.filter((filePath) => {
197
+ const relativeFile = this.getRelativePathLinux(filePath);
198
+ const isCompFile = Boolean(componentMap.getFilesRelativeToConsumer().find((p) => p === relativeFile));
199
+ if (!isCompFile) {
200
+ logger.debug(`file ${filePath} is inside the component ${componentId.toString()} but configured to be ignored`);
201
+ }
202
+ return isCompFile;
203
+ });
204
+ if (!compFiles.length) {
124
205
  return [];
125
206
  }
207
+ const buildResults = await this.executeWatchOperationsOnComponent(componentId, compFiles, true, initiator);
208
+ return buildResults;
126
209
  }
127
210
 
128
211
  /**
@@ -188,11 +271,7 @@ export class Watcher {
188
271
  logger.console(`\n${msg}: ${err.message || err}`);
189
272
  return [];
190
273
  }
191
- if (buildResults && buildResults.length) {
192
- return buildResults;
193
- }
194
- logger.console(`${idStr} doesn't have a compiler, nothing to build`);
195
- return [];
274
+ return buildResults;
196
275
  }
197
276
 
198
277
  private creatOnComponentRemovedEvent(idStr) {
@@ -207,11 +286,6 @@ export class Watcher {
207
286
  return new OnComponentAddEvent(Date.now(), idStr, hook);
208
287
  }
209
288
 
210
- private completeWatch() {
211
- loader.stop();
212
- return [];
213
- }
214
-
215
289
  private isComponentWatchedExternally(componentId: ComponentID) {
216
290
  const watcherData = this.multipleWatchers.find((m) => m.componentIds.find((id) => id.isEqual(componentId._legacy)));
217
291
  if (watcherData) {
@@ -221,29 +295,19 @@ export class Watcher {
221
295
  return false;
222
296
  }
223
297
 
224
- /**
225
- * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
226
- * entire cache is invalidated and the consumer is reloaded.
227
- * when a file just changed, no need to reload the consumer, it is enough to just delete the
228
- * component from the cache (both, workspace and consumer)
229
- */
230
- private async getComponentIdAndClearItsCache(filePath: string): Promise<ComponentID | null> {
231
- const relativeFile = pathNormalizeToLinux(this.consumer.getPathRelativeToConsumer(filePath));
298
+ private getComponentIdByPath(filePath: string): ComponentID | null {
299
+ const relativeFile = this.getRelativePathLinux(filePath);
232
300
  const trackDir = this.findTrackDirByFilePathRecursively(relativeFile);
233
301
  if (!trackDir) {
234
302
  // the file is not part of any component. If it was a new component, or a new file of
235
303
  // existing component, then, handleBitmapChanges() should deal with it.
236
304
  return null;
237
305
  }
238
- const componentId = this.trackDirs[trackDir];
239
- this.workspace.clearComponentCache(componentId);
240
- const component = await this.workspace.get(componentId);
241
- const componentMap: ComponentMap = component.state._consumer.componentMap;
242
- if (componentMap.getFilesRelativeToConsumer().find((p) => p === relativeFile)) {
243
- return componentId;
244
- }
245
- // the file is inside the component dir but it's ignored. (e.g. it's in IGNORE_LIST)
246
- return null;
306
+ return this.trackDirs[trackDir];
307
+ }
308
+
309
+ private getRelativePathLinux(filePath: string) {
310
+ return pathNormalizeToLinux(this.consumer.getPathRelativeToConsumer(filePath));
247
311
  }
248
312
 
249
313
  private findTrackDirByFilePathRecursively(filePath: string): string | null {