@teambit/workspace 0.0.987 → 0.0.989

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 (38) hide show
  1. package/dist/index.d.ts +0 -2
  2. package/dist/index.js +0 -14
  3. package/dist/index.js.map +1 -1
  4. package/dist/{preview-1676570198614.js → preview-1676777489824.js} +2 -2
  5. package/dist/workspace.d.ts +4 -11
  6. package/dist/workspace.js +8 -29
  7. package/dist/workspace.js.map +1 -1
  8. package/dist/workspace.main.runtime.d.ts +3 -3
  9. package/dist/workspace.main.runtime.js +1 -1
  10. package/dist/workspace.main.runtime.js.map +1 -1
  11. package/dist/workspace.provider.d.ts +3 -7
  12. package/dist/workspace.provider.js +3 -18
  13. package/dist/workspace.provider.js.map +1 -1
  14. package/package-tar/teambit-workspace-0.0.989.tgz +0 -0
  15. package/package.json +38 -41
  16. package/dist/watch/REFACTOR_GUIDE.md +0 -12
  17. package/dist/watch/check-types.d.ts +0 -5
  18. package/dist/watch/check-types.js +0 -15
  19. package/dist/watch/check-types.js.map +0 -1
  20. package/dist/watch/output-formatter.d.ts +0 -9
  21. package/dist/watch/output-formatter.js +0 -54
  22. package/dist/watch/output-formatter.js.map +0 -1
  23. package/dist/watch/watch-queue.d.ts +0 -8
  24. package/dist/watch/watch-queue.js +0 -44
  25. package/dist/watch/watch-queue.js.map +0 -1
  26. package/dist/watch/watch.cmd.d.ts +0 -55
  27. package/dist/watch/watch.cmd.js +0 -173
  28. package/dist/watch/watch.cmd.js.map +0 -1
  29. package/dist/watch/watcher.d.ts +0 -108
  30. package/dist/watch/watcher.js +0 -461
  31. package/dist/watch/watcher.js.map +0 -1
  32. package/package-tar/teambit-workspace-0.0.987.tgz +0 -0
  33. package/watch/REFACTOR_GUIDE.md +0 -12
  34. package/watch/check-types.ts +0 -5
  35. package/watch/output-formatter.ts +0 -50
  36. package/watch/watch-queue.ts +0 -17
  37. package/watch/watch.cmd.tsx +0 -162
  38. package/watch/watcher.ts +0 -409
@@ -1,162 +0,0 @@
1
- import chalk from 'chalk';
2
- import moment from 'moment';
3
- import { Command, CommandOptions } from '@teambit/cli';
4
- import type { Logger } from '@teambit/logger';
5
- import type { BitBaseEvent, PubsubMain } from '@teambit/pubsub';
6
-
7
- // import IDs and events
8
- import { CompilerAspect, CompilerErrorEvent } from '@teambit/compiler';
9
-
10
- import { Watcher, WatchOptions } from './watcher';
11
- import { formatCompileResults, formatWatchPathsSortByComponent } from './output-formatter';
12
- import { OnComponentEventResult } from '../on-component-events';
13
- import { CheckTypes } from './check-types';
14
-
15
- export type WatchCmdOpts = {
16
- verbose?: boolean;
17
- skipPreCompilation?: boolean;
18
- checkTypes?: string | boolean;
19
- };
20
-
21
- export class WatchCommand implements Command {
22
- msgs = {
23
- onAll: (event: string, path: string) => this.logger.console(`Event: "${event}". Path: ${path}`),
24
- onStart: () => {},
25
- onReady: (workspace, watchPathsSortByComponent, verbose) => {
26
- clearOutdatedData();
27
- if (verbose) {
28
- this.logger.console(formatWatchPathsSortByComponent(watchPathsSortByComponent));
29
- }
30
- this.logger.console(
31
- chalk.yellow(
32
- `Watching for component changes in workspace ${workspace.config.name} (${moment().format('HH:mm:ss')})...\n`
33
- )
34
- );
35
- },
36
- onChange: (
37
- filePaths: string[],
38
- buildResults: OnComponentEventResult[],
39
- verbose: boolean,
40
- duration,
41
- failureMsg?: string
42
- ) => {
43
- const files = filePaths.join(', ');
44
- // clearOutdatedData();
45
- if (!buildResults.length) {
46
- failureMsg = failureMsg || `The files ${files} have been changed, but nothing to compile`;
47
- this.logger.console(`${failureMsg}\n\n`);
48
- return;
49
- }
50
- this.logger.console(`The file(s) ${files} have been changed.\n\n`);
51
- this.logger.console(formatCompileResults(buildResults, verbose));
52
- this.logger.console(`Finished. (${duration}ms)`);
53
- this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));
54
- },
55
- onAdd: (
56
- filePaths: string[],
57
- buildResults: OnComponentEventResult[],
58
- verbose: boolean,
59
- duration,
60
- failureMsg?: string
61
- ) => {
62
- const files = filePaths.join(', ');
63
- // clearOutdatedData();
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`);
70
- this.logger.console(formatCompileResults(buildResults, verbose));
71
- this.logger.console(`Finished. (${duration}ms)`);
72
- this.logger.console(chalk.yellow(`Watching for component changes (${moment().format('HH:mm:ss')})...`));
73
- },
74
- onUnlink: (p) => {
75
- this.logger.console(`file ${p} has been removed`);
76
- },
77
- onError: (err) => {
78
- this.logger.console(`Watcher error ${err}`);
79
- },
80
- };
81
-
82
- name = 'watch';
83
- description = 'automatically recompile modified components (on save)';
84
- helpUrl = 'reference/compiling/compiler-overview';
85
- alias = '';
86
- group = 'development';
87
- options = [
88
- ['v', 'verbose', 'show npm verbose output for inspection and print the stack trace'],
89
- ['', 'skip-pre-compilation', 'skip the compilation step before starting to watch'],
90
- [
91
- 't',
92
- 'check-types [string]',
93
- 'EXPERIMENTAL. show errors/warnings for types. options are [file, project] to investigate only changed file or entire project. defaults to project',
94
- ],
95
- ] as CommandOptions;
96
-
97
- constructor(
98
- /**
99
- * logger extension.
100
- */
101
- private pubsub: PubsubMain,
102
-
103
- /**
104
- * logger extension.
105
- */
106
- private logger: Logger,
107
-
108
- /**
109
- * watcher extension.
110
- */
111
- private watcher: Watcher
112
- ) {
113
- this.registerToEvents();
114
- }
115
-
116
- private registerToEvents() {
117
- this.pubsub.sub(CompilerAspect.id, this.eventsListener);
118
- }
119
-
120
- private eventsListener = (event: BitBaseEvent<any>) => {
121
- switch (event.type) {
122
- case CompilerErrorEvent.TYPE:
123
- this.logger.console(`Watcher error ${event.data.error}, 'error'`);
124
- break;
125
- default:
126
- }
127
- };
128
-
129
- async report(cliArgs: [], watchCmdOpts: WatchCmdOpts) {
130
- const { verbose, checkTypes } = watchCmdOpts;
131
- const getCheckTypesEnum = () => {
132
- switch (checkTypes) {
133
- case undefined:
134
- case false:
135
- return CheckTypes.None;
136
- case 'project':
137
- case true: // project is the default
138
- return CheckTypes.EntireProject;
139
- case 'file':
140
- return CheckTypes.ChangedFile;
141
- default:
142
- throw new Error(`check-types can be either "file" or "project". got "${checkTypes}"`);
143
- }
144
- };
145
- const watchOpts: WatchOptions = {
146
- msgs: this.msgs,
147
- verbose,
148
- preCompile: !watchCmdOpts.skipPreCompilation,
149
- spawnTSServer: Boolean(checkTypes), // if check-types is enabled, it must spawn the tsserver.
150
- checkTypes: getCheckTypesEnum(),
151
- };
152
- await this.watcher.watchAll(watchOpts);
153
- return 'watcher terminated';
154
- }
155
- }
156
-
157
- /**
158
- * with console.clear() all history is deleted from the console. this function preserver the history.
159
- */
160
- function clearOutdatedData() {
161
- process.stdout.write('\x1Bc');
162
- }
package/watch/watcher.ts DELETED
@@ -1,409 +0,0 @@
1
- import { PubsubMain } from '@teambit/pubsub';
2
- import { dirname, sep } from 'path';
3
- import { difference } from 'lodash';
4
- import { ComponentID } from '@teambit/component';
5
- import { BitId } from '@teambit/legacy-bit-id';
6
- import loader from '@teambit/legacy/dist/cli/loader';
7
- import { BIT_MAP } from '@teambit/legacy/dist/constants';
8
- import { Consumer } from '@teambit/legacy/dist/consumer';
9
- import logger from '@teambit/legacy/dist/logger/logger';
10
- import { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';
11
- import mapSeries from 'p-map-series';
12
- import chalk from 'chalk';
13
- import { ChildProcess } from 'child_process';
14
- import chokidar, { FSWatcher } from 'chokidar';
15
- import ComponentMap from '@teambit/legacy/dist/consumer/bit-map/component-map';
16
- import { PathLinux, PathOsBasedAbsolute } from '@teambit/legacy/dist/utils/path';
17
- import { CompilationInitiator } from '@teambit/compiler';
18
- import { WorkspaceAspect } from '../';
19
- import { OnComponentChangeEvent, OnComponentAddEvent, OnComponentRemovedEvent } from '../events';
20
- import { Workspace } from '../workspace';
21
- import { OnComponentEventResult } from '../on-component-events';
22
- import { CheckTypes } from './check-types';
23
- import { WatchQueue } from './watch-queue';
24
-
25
- export type WatcherProcessData = { watchProcess: ChildProcess; compilerId: BitId; componentIds: BitId[] };
26
-
27
- export type EventMessages = {
28
- onAll: Function;
29
- onStart: Function;
30
- onReady: Function;
31
- onChange: Function;
32
- onAdd: Function;
33
- onUnlink: Function;
34
- onError: Function;
35
- };
36
-
37
- export type WatchOptions = {
38
- msgs?: EventMessages;
39
- initiator?: CompilationInitiator;
40
- verbose?: boolean; // print watch events to the console. (also ts-server events if spawnTSServer is true)
41
- spawnTSServer?: boolean; // needed for check types and extract API/docs.
42
- checkTypes?: CheckTypes; // if enabled, the spawnTSServer becomes true.
43
- preCompile?: boolean; // whether compile all components before start watching
44
- };
45
-
46
- const DEBOUNCE_WAIT_MS = 100;
47
-
48
- export class Watcher {
49
- private fsWatcher: FSWatcher;
50
- private changedFilesPerComponent: { [componentId: string]: string[] } = {};
51
- private watchQueue = new WatchQueue();
52
- private bitMapChangesInProgress = false;
53
- constructor(
54
- private workspace: Workspace,
55
- private pubsub: PubsubMain,
56
- private trackDirs: { [dir: PathLinux]: ComponentID } = {},
57
- private verbose = false,
58
- private multipleWatchers: WatcherProcessData[] = []
59
- ) {}
60
-
61
- get consumer(): Consumer {
62
- return this.workspace.consumer;
63
- }
64
-
65
- async watchAll(opts: WatchOptions) {
66
- const { msgs, ...watchOpts } = opts;
67
- // TODO: run build in the beginning of process (it's work like this in other envs)
68
- const pathsToWatch = await this.getPathsToWatch();
69
- const componentIds = Object.values(this.trackDirs);
70
- await this.workspace.triggerOnPreWatch(componentIds, watchOpts);
71
- await this.createWatcher(pathsToWatch);
72
- const watcher = this.fsWatcher;
73
- msgs?.onStart(this.workspace);
74
-
75
- return new Promise((resolve, reject) => {
76
- // prefix your command with "BIT_LOG=*" to see all watch events
77
- if (process.env.BIT_LOG) {
78
- // @ts-ignore
79
- if (msgs?.onAll) watcher.on('all', msgs?.onAll);
80
- }
81
- watcher.on('ready', () => {
82
- msgs?.onReady(this.workspace, this.trackDirs, this.verbose);
83
- });
84
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
85
- watcher.on('change', async (filePath) => {
86
- const startTime = new Date().getTime();
87
- const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);
88
- if (debounced) {
89
- return;
90
- }
91
- const duration = new Date().getTime() - startTime;
92
- msgs?.onChange(files, results, this.verbose, duration, failureMsg);
93
- });
94
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
95
- watcher.on('add', async (filePath) => {
96
- const startTime = new Date().getTime();
97
- const { files, results, debounced, failureMsg } = await this.handleChange(filePath, opts?.initiator);
98
- if (debounced) {
99
- return;
100
- }
101
- const duration = new Date().getTime() - startTime;
102
- msgs?.onAdd(files, results, this.verbose, duration, failureMsg);
103
- });
104
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
105
- watcher.on('unlink', async (p) => {
106
- msgs?.onUnlink(p);
107
- await this.handleChange(p);
108
- });
109
- watcher.on('error', (err) => {
110
- msgs?.onError(err);
111
- reject(err);
112
- });
113
- });
114
- }
115
-
116
- /**
117
- * *** DEBOUNCING ***
118
- * some actions trigger multiple files changes at (almost) the same time. e.g. "git pull".
119
- * this causes some performance and instability issues. a debouncing mechanism was implemented to help with this.
120
- * the way how it works is that the first file of the same component starts the execution with a delay (e.g. 200ms).
121
- * if, in the meanwhile, another file of the same component was changed, it won't start a new execution, instead,
122
- * it'll only add the file to `this.changedFilesPerComponent` prop.
123
- * once the execution starts, it'll delete this component-id from the `this.changedFilesPerComponent` array,
124
- * indicating the next file-change to start a new execution.
125
- *
126
- * implementation wise, `lodash.debounce` doesn't help here, because:
127
- * A) it doesn't return the results, unless "leading" option is true. here, it must be false, otherwise, it'll start
128
- * the execution immediately.
129
- * B) it debounces the method regardless the param passes to it. so it'll disregard the component-id and will delay
130
- * other components undesirably.
131
- *
132
- * *** QUEUE ***
133
- * the debouncing helps to not execute the same component multiple times concurrently. however, multiple components
134
- * and .bitmap changes execution can still be processed concurrently.
135
- * the following example explains why this is an issue.
136
- * compA is changed in the .bitmap file from version 0.0.1 to 0.0.2. its files were changed as well.
137
- * all these changes get pulled at the same time by "git pull", as a result, the execution of compA and the .bitmap
138
- * happen at the same time.
139
- * during the execution of compA, the component id is parsed as compA@0.0.1, later, it asks for the Workspace for this
140
- * id. while the workspace is looking for this id, the .bitmap execution reloaded the consumer and changed all versions.
141
- * after this change, the workspace doesn't have this id anymore, which will trigger an error.
142
- * to ensure this won't happen, we keep a flag to indicate whether the .bitmap execution is running, and if so, all
143
- * other executions are paused until the queue is empty (this is done by awaiting for queue.onIdle).
144
- * once the queue is empty, we know the .bitmap process was done and the workspace has all new ids.
145
- * in the example above, at this stage, the id will be resolved to compA@0.0.2.
146
- * one more thing, the queue is configured to have concurrency of 1. to make sure two components are not processed at
147
- * the same time. (the same way is done when loading all components from the filesystem/scope).
148
- * this way we can also ensure that if compA was started before the .bitmap execution, it will complete before the
149
- * .bitmap execution starts.
150
- */
151
- private async handleChange(
152
- filePath: string,
153
- initiator?: CompilationInitiator
154
- ): Promise<{
155
- results: OnComponentEventResult[];
156
- files?: string[];
157
- failureMsg?: string;
158
- debounced?: boolean;
159
- }> {
160
- try {
161
- if (filePath.endsWith(BIT_MAP)) {
162
- this.bitMapChangesInProgress = true;
163
- const buildResults = await this.watchQueue.add(() => this.handleBitmapChanges());
164
- this.bitMapChangesInProgress = false;
165
- loader.stop();
166
- return { results: buildResults, files: [filePath] };
167
- }
168
- if (this.bitMapChangesInProgress) {
169
- await this.watchQueue.onIdle();
170
- }
171
- const componentId = this.getComponentIdByPath(filePath);
172
- if (!componentId) {
173
- const failureMsg = `file ${filePath} is not part of any component, ignoring it`;
174
- logger.debug(failureMsg);
175
- loader.stop();
176
- return { results: [], files: [filePath], failureMsg };
177
- }
178
- const compIdStr = componentId.toString();
179
- if (this.changedFilesPerComponent[compIdStr]) {
180
- this.changedFilesPerComponent[compIdStr].push(filePath);
181
- loader.stop();
182
- return { results: [], debounced: true };
183
- }
184
- this.changedFilesPerComponent[compIdStr] = [filePath];
185
- await this.sleep(DEBOUNCE_WAIT_MS);
186
- const files = this.changedFilesPerComponent[compIdStr];
187
- delete this.changedFilesPerComponent[compIdStr];
188
-
189
- const buildResults = await this.watchQueue.add(() => this.triggerCompChanges(componentId, files, initiator));
190
- const failureMsg = buildResults.length
191
- ? undefined
192
- : `files ${files.join(', ')} are inside the component ${compIdStr} but configured to be ignored`;
193
- loader.stop();
194
- return { results: buildResults, files, failureMsg };
195
- } catch (err: any) {
196
- const msg = `watcher found an error while handling ${filePath}`;
197
- logger.error(msg, err);
198
- logger.console(`${msg}, ${err.message}`);
199
- loader.stop();
200
- return { results: [], files: [filePath], failureMsg: err.message };
201
- }
202
- }
203
-
204
- private async sleep(ms: number) {
205
- return new Promise((resolve) => setTimeout(resolve, ms));
206
- }
207
-
208
- /**
209
- * if a file was added/remove, once the component is loaded, it changes .bitmap, and then the
210
- * entire cache is invalidated and the consumer is reloaded.
211
- * when a file just changed, no need to reload the consumer, it is enough to just delete the
212
- * component from the cache (both, workspace and consumer)
213
- */
214
- private async triggerCompChanges(
215
- componentId: ComponentID,
216
- files: string[],
217
- initiator?: CompilationInitiator
218
- ): Promise<OnComponentEventResult[]> {
219
- let updatedComponentId: ComponentID | undefined = componentId;
220
- if (!(await this.workspace.hasId(componentId))) {
221
- // bitmap has changed meanwhile, which triggered `handleBitmapChanges`, which re-loaded consumer and updated versions
222
- // so the original componentId might not be in the workspace now, and we need to find the updated one
223
- const ids = await this.workspace.listIds();
224
- updatedComponentId = ids.find((id) => id.isEqual(componentId, { ignoreVersion: true }));
225
- if (!updatedComponentId) {
226
- logger.debug(`triggerCompChanges, the component ${componentId.toString()} was probably removed from .bitmap`);
227
- return [];
228
- }
229
- }
230
- this.workspace.clearComponentCache(updatedComponentId);
231
- const component = await this.workspace.get(updatedComponentId);
232
- const componentMap: ComponentMap = component.state._consumer.componentMap;
233
- if (!componentMap) {
234
- throw new Error(
235
- `unable to find componentMap for ${updatedComponentId.toString()}, make sure this component is in .bitmap`
236
- );
237
- }
238
- const compFiles = files.filter((filePath) => {
239
- const relativeFile = this.getRelativePathLinux(filePath);
240
- const isCompFile = Boolean(componentMap.getFilesRelativeToConsumer().find((p) => p === relativeFile));
241
- return isCompFile;
242
- });
243
- if (!compFiles.length) {
244
- logger.debug(
245
- `the following files are part of the component ${componentId.toStringWithoutVersion()} but configured to be ignored:\n${files.join(
246
- '\n'
247
- )}'`
248
- );
249
- return [];
250
- }
251
- const buildResults = await this.executeWatchOperationsOnComponent(updatedComponentId, compFiles, true, initiator);
252
- return buildResults;
253
- }
254
-
255
- /**
256
- * if .bitmap changed, it's possible that a new component has been added. trigger onComponentAdd.
257
- */
258
- private async handleBitmapChanges(): Promise<OnComponentEventResult[]> {
259
- const previewsTrackDirs = { ...this.trackDirs };
260
- await this.workspace._reloadConsumer();
261
- await this.setTrackDirs();
262
- const newDirs: string[] = difference(Object.keys(this.trackDirs), Object.keys(previewsTrackDirs));
263
- const removedDirs: string[] = difference(Object.keys(previewsTrackDirs), Object.keys(this.trackDirs));
264
- const results: OnComponentEventResult[] = [];
265
- if (newDirs.length) {
266
- this.fsWatcher.add(newDirs);
267
- const addResults = await mapSeries(newDirs, async (dir) =>
268
- this.executeWatchOperationsOnComponent(this.trackDirs[dir], [], false)
269
- );
270
- results.push(...addResults.flat());
271
- await this.workspace.triggerOnMultipleComponentsAdd();
272
- }
273
- if (removedDirs.length) {
274
- await this.fsWatcher.unwatch(removedDirs);
275
- await mapSeries(removedDirs, (dir) => this.executeWatchOperationsOnRemove(previewsTrackDirs[dir]));
276
- }
277
- return results;
278
- }
279
-
280
- private async executeWatchOperationsOnRemove(componentId: ComponentID) {
281
- logger.debug(`running OnComponentRemove hook for ${chalk.bold(componentId.toString())}`);
282
- this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentRemovedEvent(componentId.toString()));
283
- await this.workspace.triggerOnComponentRemove(componentId);
284
- }
285
-
286
- private async executeWatchOperationsOnComponent(
287
- componentId: ComponentID,
288
- files: string[],
289
- isChange = true,
290
- initiator?: CompilationInitiator
291
- ): Promise<OnComponentEventResult[]> {
292
- if (this.isComponentWatchedExternally(componentId)) {
293
- // update capsule, once done, it automatically triggers the external watcher
294
- await this.workspace.get(componentId);
295
- return [];
296
- }
297
- const idStr = componentId.toString();
298
-
299
- if (isChange) {
300
- logger.debug(`running OnComponentChange hook for ${chalk.bold(idStr)}`);
301
- this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentChangeEvent(idStr, 'OnComponentChange'));
302
- } else {
303
- logger.debug(`running OnComponentAdd hook for ${chalk.bold(idStr)}`);
304
- this.pubsub.pub(WorkspaceAspect.id, this.creatOnComponentAddEvent(idStr, 'OnComponentAdd'));
305
- }
306
-
307
- // the try/catch is probably not needed here because this gets called by `handleChange()` which already has a try/catch
308
- // I left it here commented out for now just in case, but it should be removed as soon as we're more confident
309
-
310
- // let buildResults: OnComponentEventResult[];
311
- // try {
312
- const buildResults = isChange
313
- ? await this.workspace.triggerOnComponentChange(componentId, files, initiator)
314
- : await this.workspace.triggerOnComponentAdd(componentId);
315
- // } catch (err: any) {
316
- // // do not exit the watch process on errors, just print them
317
- // const msg = `found an issue during onComponentChange or onComponentAdd hooks for ${idStr}`;
318
- // logger.error(msg, err);
319
- // logger.console(`\n${msg}: ${err.message || err}`);
320
- // return [];
321
- // }
322
- return buildResults;
323
- }
324
-
325
- private creatOnComponentRemovedEvent(idStr) {
326
- return new OnComponentRemovedEvent(Date.now(), idStr);
327
- }
328
-
329
- private creatOnComponentChangeEvent(idStr, hook) {
330
- return new OnComponentChangeEvent(Date.now(), idStr, hook);
331
- }
332
-
333
- private creatOnComponentAddEvent(idStr, hook) {
334
- return new OnComponentAddEvent(Date.now(), idStr, hook);
335
- }
336
-
337
- private isComponentWatchedExternally(componentId: ComponentID) {
338
- const watcherData = this.multipleWatchers.find((m) => m.componentIds.find((id) => id.isEqual(componentId._legacy)));
339
- if (watcherData) {
340
- logger.debug(`${componentId.toString()} is watched by ${watcherData.compilerId.toString()}`);
341
- return true;
342
- }
343
- return false;
344
- }
345
-
346
- private getComponentIdByPath(filePath: string): ComponentID | null {
347
- const relativeFile = this.getRelativePathLinux(filePath);
348
- const trackDir = this.findTrackDirByFilePathRecursively(relativeFile);
349
- if (!trackDir) {
350
- // the file is not part of any component. If it was a new component, or a new file of
351
- // existing component, then, handleBitmapChanges() should deal with it.
352
- return null;
353
- }
354
- return this.trackDirs[trackDir];
355
- }
356
-
357
- private getRelativePathLinux(filePath: string) {
358
- return pathNormalizeToLinux(this.consumer.getPathRelativeToConsumer(filePath));
359
- }
360
-
361
- private findTrackDirByFilePathRecursively(filePath: string): string | null {
362
- if (this.trackDirs[filePath]) return filePath;
363
- const parentDir = dirname(filePath);
364
- if (parentDir === filePath) return null;
365
- return this.findTrackDirByFilePathRecursively(parentDir);
366
- }
367
-
368
- private async createWatcher(pathsToWatch: string[]) {
369
- this.fsWatcher = chokidar.watch(pathsToWatch, {
370
- ignoreInitial: true,
371
- // Using the function way since the regular way not working as expected
372
- // It might be solved when upgrading to chokidar > 3.0.0
373
- // See:
374
- // https://github.com/paulmillr/chokidar/issues/773
375
- // https://github.com/paulmillr/chokidar/issues/492
376
- // https://github.com/paulmillr/chokidar/issues/724
377
- ignored: (path) => {
378
- // Ignore package.json temporarily since it cerates endless loop since it's re-written after each build
379
- if (path.includes(`${sep}node_modules${sep}`) || path.includes(`${sep}package.json`)) {
380
- return true;
381
- }
382
- return false;
383
- },
384
- persistent: true,
385
- useFsEvents: false,
386
- });
387
- }
388
-
389
- async setTrackDirs() {
390
- this.trackDirs = {};
391
- const componentsFromBitMap = this.consumer.bitMap.getAllComponents();
392
- await Promise.all(
393
- componentsFromBitMap.map(async (componentMap) => {
394
- const bitId = componentMap.id;
395
- const rootDir = componentMap.getRootDir();
396
- if (!rootDir) throw new Error(`${bitId.toString()} has no rootDir, which is invalid in Harmony`);
397
- const componentId = await this.workspace.resolveComponentId(bitId);
398
- this.trackDirs[rootDir] = componentId;
399
- })
400
- );
401
- }
402
-
403
- private async getPathsToWatch(): Promise<PathOsBasedAbsolute[]> {
404
- await this.setTrackDirs();
405
- const paths = [...Object.keys(this.trackDirs), BIT_MAP];
406
- const pathsAbsolute = paths.map((dir) => this.consumer.toAbsolutePath(dir));
407
- return pathsAbsolute;
408
- }
409
- }