@teambit/workspace 1.0.105 → 1.0.106

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.
@@ -1,7 +1,9 @@
1
+ import pMap from 'p-map';
2
+ import { concurrentComponentsLimit } from '@teambit/legacy/dist/utils/concurrency';
1
3
  import { Component, ComponentFS, Config, InvalidComponent, State, TagMap } from '@teambit/component';
2
4
  import { ComponentID, ComponentIdList } from '@teambit/component-id';
3
5
  import mapSeries from 'p-map-series';
4
- import { compact, fromPairs, uniq } from 'lodash';
6
+ import { compact, fromPairs, groupBy, pick, uniq } from 'lodash';
5
7
  import ConsumerComponent from '@teambit/legacy/dist/consumer/component';
6
8
  import { MissingBitMapComponent } from '@teambit/legacy/dist/consumer/bit-map/exceptions';
7
9
  import { getLatestVersionNumber } from '@teambit/legacy/dist/utils';
@@ -10,41 +12,460 @@ import { ComponentNotFound } from '@teambit/legacy/dist/scope/exceptions';
10
12
  import { DependencyResolverAspect, DependencyResolverMain } from '@teambit/dependency-resolver';
11
13
  import { Logger } from '@teambit/logger';
12
14
  import { EnvsAspect, EnvsMain } from '@teambit/envs';
13
- import { ExtensionDataEntry } from '@teambit/legacy/dist/consumer/config';
15
+ import { ExtensionDataEntry, ExtensionDataList } from '@teambit/legacy/dist/consumer/config';
14
16
  import { getMaxSizeForComponents, InMemoryCache } from '@teambit/legacy/dist/cache/in-memory-cache';
17
+ import { AspectLoaderMain } from '@teambit/aspect-loader';
15
18
  import { createInMemoryCache } from '@teambit/legacy/dist/cache/cache-factory';
16
19
  import ComponentNotFoundInPath from '@teambit/legacy/dist/consumer/component/exceptions/component-not-found-in-path';
17
- import { ComponentLoadOptions } from '@teambit/legacy/dist/consumer/component/component-loader';
20
+ import { ComponentLoadOptions as LegacyComponentLoadOptions } from '@teambit/legacy/dist/consumer/component/component-loader';
18
21
  import { Workspace } from '../workspace';
19
22
  import { WorkspaceComponent } from './workspace-component';
20
23
  import { MergeConfigConflict } from '../exceptions/merge-config-conflict';
21
24
 
25
+ type GetManyRes = {
26
+ components: Component[];
27
+ invalidComponents: InvalidComponent[];
28
+ };
29
+
30
+ export type ComponentLoadOptions = LegacyComponentLoadOptions & {
31
+ loadExtensions?: boolean;
32
+ executeLoadSlot?: boolean;
33
+ idsToNotLoadAsAspects?: string[];
34
+ loadSeedersAsAspects?: boolean;
35
+ resolveExtensionsVersions?: boolean;
36
+ };
37
+
38
+ type LoadGroup = { workspaceIds: ComponentID[]; scopeIds: ComponentID[] } & LoadGroupMetadata;
39
+ type LoadGroupMetadata = {
40
+ core?: boolean;
41
+ aspects?: boolean;
42
+ seeders?: boolean;
43
+ };
44
+
45
+ type GetAndLoadSlotOpts = ComponentLoadOptions & LoadGroupMetadata;
46
+
47
+ type ComponentGetOneOptions = {
48
+ resolveIdVersion?: boolean;
49
+ };
50
+
51
+ type WorkspaceScopeIdsMap = {
52
+ scopeIds: Map<string, ComponentID>;
53
+ workspaceIds: Map<string, ComponentID>;
54
+ };
55
+
56
+ export type LoadCompAsAspectsOptions = {
57
+ /**
58
+ * In case the component we are loading is app, whether to load it as app (in a scope aspects capsule)
59
+ */
60
+ loadApps?: boolean;
61
+ /**
62
+ * In case the component we are loading is env, whether to load it as env (in a scope aspects capsule)
63
+ */
64
+ loadEnvs?: boolean;
65
+
66
+ /**
67
+ * In case the component we are loading is a regular aspect, whether to load it as aspect (in a scope aspects capsule)
68
+ */
69
+ loadAspects?: boolean;
70
+
71
+ idsToNotLoadAsAspects?: string[];
72
+
73
+ /**
74
+ * Are this core aspects
75
+ */
76
+ core?: boolean;
77
+
78
+ /**
79
+ * Are this aspects seeders of the load many operation
80
+ */
81
+ seeders?: boolean;
82
+ };
83
+
22
84
  export class WorkspaceComponentLoader {
23
85
  private componentsCache: InMemoryCache<Component>; // cache loaded components
86
+ /**
87
+ * Cache components that loaded from scope (especially for get many for perf improvements)
88
+ */
89
+ private scopeComponentsCache: InMemoryCache<Component>;
90
+ /**
91
+ * Cache extension list for components. used by get many for perf improvements.
92
+ * And to make sure we load extensions first.
93
+ */
94
+ private componentsExtensionsCache: InMemoryCache<{ extensions: ExtensionDataList; errors: Error[] | undefined }>;
95
+
96
+ private componentLoadedSelfAsAspects: InMemoryCache<boolean>; // cache loaded components
24
97
  constructor(
25
98
  private workspace: Workspace,
26
99
  private logger: Logger,
27
100
  private dependencyResolver: DependencyResolverMain,
28
- private envs: EnvsMain
101
+ private envs: EnvsMain,
102
+ private aspectLoader: AspectLoaderMain
29
103
  ) {
30
104
  this.componentsCache = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
105
+ this.scopeComponentsCache = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
106
+ this.componentsExtensionsCache = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
107
+ this.componentLoadedSelfAsAspects = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
31
108
  }
32
109
 
33
- async getMany(
34
- ids: Array<ComponentID>,
35
- loadOpts?: ComponentLoadOptions,
36
- throwOnFailure = true
37
- ): Promise<{
38
- components: Component[];
39
- invalidComponents: InvalidComponent[];
40
- }> {
110
+ async getMany(ids: Array<ComponentID>, loadOpts?: ComponentLoadOptions, throwOnFailure = true): Promise<GetManyRes> {
41
111
  const idsWithoutEmpty = compact(ids);
42
- const errors: { id: ComponentID; err: Error }[] = [];
112
+ this.logger.setStatusLine(`loading ${ids.length} component(s)`);
113
+ const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(
114
+ // We don't want to load extension or execute the load slot at this step
115
+ // we will do it later
116
+ // this important for better performance
117
+ // We don't want to resolveExtensionsVersions as with get many we call aspect merger merge before update dependencies
118
+ // so we will have the correct versions for extensions already and update them after will resolve wrong versions
119
+ // in some cases
120
+ { loadExtensions: false, executeLoadSlot: false, loadSeedersAsAspects: true, resolveExtensionsVersions: false },
121
+ loadOpts || {}
122
+ );
123
+
124
+ const loadOrCached: { idsToLoad: ComponentID[]; fromCache: Component[] } = { idsToLoad: [], fromCache: [] };
125
+ idsWithoutEmpty.forEach((id) => {
126
+ const componentFromCache = this.getFromCache(id, loadOptsWithDefaults);
127
+ if (componentFromCache) {
128
+ loadOrCached.fromCache.push(componentFromCache);
129
+ } else {
130
+ loadOrCached.idsToLoad.push(id);
131
+ }
132
+ }, loadOrCached);
133
+
134
+ const { components: loadedComponents, invalidComponents } = await this.getAndLoadSlotOrdered(
135
+ loadOrCached.idsToLoad || [],
136
+ loadOptsWithDefaults,
137
+ throwOnFailure
138
+ );
139
+
140
+ const components = [...loadedComponents, ...loadOrCached.fromCache];
141
+
142
+ // this.logger.clearStatusLine();
143
+ return { components, invalidComponents };
144
+ }
145
+
146
+ private async getAndLoadSlotOrdered(
147
+ ids: ComponentID[],
148
+ loadOpts: ComponentLoadOptions,
149
+ throwOnFailure = true
150
+ ): Promise<GetManyRes> {
151
+ if (!ids?.length) return { components: [], invalidComponents: [] };
152
+
153
+ const workspaceScopeIdsMap: WorkspaceScopeIdsMap = await this.groupAndUpdateIds(ids);
154
+
155
+ const groupsToHandle = await this.buildLoadGroups(workspaceScopeIdsMap);
156
+ const groupsRes = compact(
157
+ await mapSeries(groupsToHandle, async (group) => {
158
+ const { scopeIds, workspaceIds, aspects, core, seeders } = group;
159
+ if (!workspaceIds.length && !scopeIds.length) return undefined;
160
+ const res = await this.getAndLoadSlot(
161
+ workspaceIds,
162
+ scopeIds,
163
+ { ...loadOpts, core, seeders, aspects },
164
+ throwOnFailure
165
+ );
166
+ // We don't want to return components that were not asked originally (we do want to load them)
167
+ if (!group.seeders) return undefined;
168
+ return res;
169
+ })
170
+ );
171
+ const finalRes = groupsRes.reduce(
172
+ (acc, curr) => {
173
+ return {
174
+ components: [...acc.components, ...curr.components],
175
+ invalidComponents: [...acc.invalidComponents, ...curr.invalidComponents],
176
+ };
177
+ },
178
+ { components: [], invalidComponents: [] }
179
+ );
180
+ return finalRes;
181
+ }
182
+
183
+ private async buildLoadGroups(workspaceScopeIdsMap: WorkspaceScopeIdsMap): Promise<Array<LoadGroup>> {
184
+ const allIds = [...workspaceScopeIdsMap.workspaceIds.values(), ...workspaceScopeIdsMap.scopeIds.values()];
185
+ const groupedByIsCoreEnvs = groupBy(allIds, (id) => {
186
+ return this.envs.isCoreEnv(id.toStringWithoutVersion());
187
+ });
188
+ await this.populateScopeAndExtensionsCache(groupedByIsCoreEnvs.false || [], workspaceScopeIdsMap);
189
+ const allExtIds: Map<string, ComponentID> = new Map();
190
+ groupedByIsCoreEnvs.false.forEach((id) => {
191
+ const idStr = id.toString();
192
+ const fromCache = this.componentsExtensionsCache.get(idStr);
193
+ if (!fromCache || !fromCache.extensions) {
194
+ return;
195
+ }
196
+ fromCache.extensions.forEach((ext) => {
197
+ if (!allExtIds.has(ext.stringId) && ext.newExtensionId) {
198
+ allExtIds.set(ext.stringId, ext.newExtensionId);
199
+ }
200
+ });
201
+ });
202
+ const allExtCompIds = Array.from(allExtIds.values());
203
+ await this.populateScopeAndExtensionsCache(allExtCompIds || [], workspaceScopeIdsMap);
204
+
205
+ const allExtIdsStr = allExtCompIds.map((id) => id.toString());
206
+ const groupedByIsExtOfAnother = groupBy(groupedByIsCoreEnvs.false, (id) => {
207
+ return allExtIdsStr.includes(id.toString());
208
+ });
209
+ const extIdsFromTheList = (groupedByIsExtOfAnother.true || []).map((id) => id.toString());
210
+ const extsNotFromTheList: ComponentID[] = [];
211
+ for (const [, id] of allExtIds.entries()) {
212
+ if (!extIdsFromTheList.includes(id.toString())) {
213
+ extsNotFromTheList.push(id);
214
+ }
215
+ }
216
+
217
+ await this.groupAndUpdateIds(extsNotFromTheList, workspaceScopeIdsMap);
218
+
219
+ const layerdExtFromTheList = this.regroupExtIdsFromTheList(groupedByIsExtOfAnother.true);
220
+ const layerdExtGroups = layerdExtFromTheList.map((ids) => {
221
+ return {
222
+ ids,
223
+ core: false,
224
+ aspects: true,
225
+ seeders: true,
226
+ };
227
+ });
228
+
229
+ const groupsToHandle = [
230
+ // Always load first core envs
231
+ { ids: groupedByIsCoreEnvs.true || [], core: true, aspects: true, seeders: false },
232
+ { ids: extsNotFromTheList || [], core: false, aspects: true, seeders: false },
233
+ ...layerdExtGroups,
234
+ { ids: groupedByIsExtOfAnother.false || [], core: false, aspects: false, seeders: true },
235
+ ];
236
+ const groupsByWsScope = groupsToHandle.map((group) => {
237
+ const groupedByWsScope = groupBy(group.ids, (id) => {
238
+ return workspaceScopeIdsMap.workspaceIds.has(id.toString());
239
+ });
240
+ return {
241
+ workspaceIds: groupedByWsScope.true || [],
242
+ scopeIds: groupedByWsScope.false || [],
243
+ core: group.core,
244
+ aspects: group.aspects,
245
+ seeders: group.seeders,
246
+ };
247
+ });
248
+ return groupsByWsScope;
249
+ }
250
+
251
+ private regroupExtIdsFromTheList(ids: ComponentID[]): Array<ComponentID[]> {
252
+ // TODO: implement this function
253
+ // this should handle a case when you have:
254
+ // compA that has extA and that extA has extB
255
+ // in that case we now get the following group:
256
+ // ids: [extA, extB]
257
+ // while we need extB to be in a different group before extA
258
+ return [ids];
259
+ }
260
+
261
+ private async getAndLoadSlot(
262
+ workspaceIds: ComponentID[],
263
+ scopeIds: ComponentID[],
264
+ loadOpts: GetAndLoadSlotOpts,
265
+ throwOnFailure = true
266
+ ): Promise<GetManyRes> {
267
+ const { workspaceComponents, scopeComponents, invalidComponents } = await this.getComponentsWithoutLoadExtensions(
268
+ workspaceIds,
269
+ scopeIds,
270
+ loadOpts,
271
+ throwOnFailure
272
+ );
273
+
274
+ const components = workspaceComponents.concat(scopeComponents);
275
+
276
+ const allExtensions: ExtensionDataList[] = components.map((component) => {
277
+ return component.state._consumer.extensions;
278
+ });
279
+
280
+ // Ensure we won't load the same extension many times
281
+ // We don't want to ignore version here, as we do want to load different extensions with same id but different versions here
282
+ const mergedExtensions = ExtensionDataList.mergeConfigs(allExtensions, false);
283
+ await this.workspace.loadComponentsExtensions(mergedExtensions);
284
+ const withAspects = await pMap(components, (component) => this.executeLoadSlot(component), {
285
+ concurrency: concurrentComponentsLimit(),
286
+ });
287
+
288
+ // const withAspects = await Promise.all(
289
+ // components.map((component) => {
290
+ // return this.executeLoadSlot(component);
291
+ // })
292
+ // );
293
+ await this.warnAboutMisconfiguredEnvs(withAspects);
294
+ // It's important to load the workspace components as aspects here
295
+ // otherwise the envs from the workspace won't be loaded at time
296
+ // so we will get wrong dependencies from component who uses envs from the workspace
297
+ if (loadOpts.loadSeedersAsAspects) {
298
+ await this.loadCompsAsAspects(workspaceComponents.concat(scopeComponents), {
299
+ loadApps: true,
300
+ loadEnvs: true,
301
+ loadAspects: loadOpts.aspects,
302
+ core: loadOpts.core,
303
+ seeders: loadOpts.seeders,
304
+ idsToNotLoadAsAspects: loadOpts.idsToNotLoadAsAspects,
305
+ });
306
+ }
307
+
308
+ return { components: withAspects, invalidComponents };
309
+ }
310
+
311
+ // TODO: this is similar to scope.main.runtime loadCompAspects func, we should merge them.
312
+ async loadCompsAsAspects(
313
+ components: Component[],
314
+ opts: LoadCompAsAspectsOptions = { loadApps: true, loadEnvs: true, loadAspects: true }
315
+ ): Promise<void> {
316
+ const aspectIds: string[] = [];
317
+ components.forEach((component) => {
318
+ const firstTimeToLoad = this.componentLoadedSelfAsAspects.get(component.id.toString()) === undefined;
319
+ const excluded = opts.idsToNotLoadAsAspects?.includes(component.id.toString());
320
+ const isCore = this.aspectLoader.isCoreAspect(component.id.toStringWithoutVersion());
321
+ const alreadyLoaded = this.aspectLoader.isAspectLoaded(component.id.toString());
322
+ const skipLoading = excluded || isCore || alreadyLoaded || !firstTimeToLoad;
323
+
324
+ if (skipLoading) {
325
+ return;
326
+ }
327
+ const idStr = component.id.toString();
328
+ const appData = component.state.aspects.get('teambit.harmony/application');
329
+ if (opts.loadApps && appData?.data?.appName) {
330
+ aspectIds.push(idStr);
331
+ this.componentLoadedSelfAsAspects.set(idStr, true);
332
+ }
333
+ const envsData = component.state.aspects.get(EnvsAspect.id);
334
+ if (opts.loadEnvs && (envsData?.data?.services || envsData?.data?.self || envsData?.data?.type === 'env')) {
335
+ aspectIds.push(idStr);
336
+ this.componentLoadedSelfAsAspects.set(idStr, true);
337
+ }
338
+ if (opts.loadAspects && envsData?.data?.type === 'aspect') {
339
+ aspectIds.push(idStr);
340
+ this.componentLoadedSelfAsAspects.set(idStr, true);
341
+ }
342
+ });
343
+ if (!aspectIds.length) return;
344
+
345
+ try {
346
+ await this.workspace.loadAspects(aspectIds, true, 'self loading aspects', {});
347
+ } catch (err: any) {
348
+ this.logger.warn(`failed loading components as aspects for components ${aspectIds.join(', ')}`, err);
349
+ // we ignore that errors at the moment
350
+ }
351
+ }
352
+
353
+ private async populateScopeAndExtensionsCache(ids: ComponentID[], workspaceScopeIdsMap: WorkspaceScopeIdsMap) {
354
+ return mapSeries(ids, async (id) => {
355
+ const idStr = id.toString();
356
+ let componentFromScope;
357
+ if (!this.scopeComponentsCache.has(idStr)) {
358
+ try {
359
+ // Do not import automatically if it's missing, it will throw an error later
360
+ componentFromScope = await this.workspace.scope.get(id, undefined, false);
361
+ if (componentFromScope) {
362
+ this.scopeComponentsCache.set(idStr, componentFromScope);
363
+ }
364
+ // This is fine here, as it will be handled later in the process
365
+ } catch (err: any) {
366
+ const wsAspectLoader = this.workspace.getWorkspaceAspectsLoader();
367
+ wsAspectLoader.throwWsJsoncAspectNotFoundError(err);
368
+ this.logger.warn(`populateScopeAndExtensionsCache - failed loading component ${idStr} from scope`, err);
369
+ }
370
+ }
371
+ if (!this.componentsExtensionsCache.has(idStr) && workspaceScopeIdsMap.workspaceIds.has(idStr)) {
372
+ componentFromScope = componentFromScope || this.scopeComponentsCache.get(idStr);
373
+ const { extensions, errors } = await this.workspace.componentExtensions(id, componentFromScope, undefined, {
374
+ loadExtensions: false,
375
+ });
376
+ this.componentsExtensionsCache.set(idStr, { extensions, errors });
377
+ }
378
+ });
379
+ }
380
+
381
+ private async warnAboutMisconfiguredEnvs(components: Component[]) {
382
+ const allIds = uniq(components.map((component) => this.envs.getEnvId(component)));
383
+ return Promise.all(allIds.map((envId) => this.workspace.warnAboutMisconfiguredEnv(envId)));
384
+ }
385
+
386
+ private async groupAndUpdateIds(
387
+ ids: ComponentID[],
388
+ existingGroups?: WorkspaceScopeIdsMap
389
+ ): Promise<WorkspaceScopeIdsMap> {
390
+ const result: WorkspaceScopeIdsMap = existingGroups || {
391
+ scopeIds: new Map(),
392
+ workspaceIds: new Map(),
393
+ };
394
+
395
+ await Promise.all(
396
+ ids.map(async (componentId) => {
397
+ const inWs = await this.isInWsIncludeDeleted(componentId);
398
+
399
+ if (!inWs) {
400
+ result.scopeIds.set(componentId.toString(), componentId);
401
+ return undefined;
402
+ }
403
+ const resolvedVersions = this.resolveVersion(componentId);
404
+ result.workspaceIds.set(resolvedVersions.toString(), resolvedVersions);
405
+ return undefined;
406
+ })
407
+ );
408
+ return result;
409
+ }
410
+
411
+ private async isInWsIncludeDeleted(componentId: ComponentID): Promise<boolean> {
412
+ const nonDeletedWsIds = await this.workspace.listIds();
413
+ const deletedWsIds = await this.workspace.locallyDeletedIds();
414
+ const allWsIds = nonDeletedWsIds.concat(deletedWsIds);
415
+ const inWs = allWsIds.find((id) => id.isEqual(componentId, { ignoreVersion: !componentId.hasVersion() }));
416
+ return !!inWs;
417
+ }
418
+
419
+ private async getComponentsWithoutLoadExtensions(
420
+ workspaceIds: ComponentID[],
421
+ scopeIds: ComponentID[],
422
+ loadOpts: GetAndLoadSlotOpts,
423
+ throwOnFailure = true
424
+ ) {
43
425
  const invalidComponents: InvalidComponent[] = [];
44
- const longProcessLogger = this.logger.createLongProcessLogger('loading components', ids.length);
45
- const componentsP = mapSeries(idsWithoutEmpty, async (id: ComponentID) => {
46
- longProcessLogger.logProgress(id.toString());
47
- return this.get(id, undefined, undefined, undefined, loadOpts).catch((err) => {
426
+ const errors: { id: ComponentID; err: Error }[] = [];
427
+ const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(
428
+ // We don't want to load extension or execute the load slot at this step
429
+ // we will do it later
430
+ // this important for better performance
431
+ // We don't want to store deps in fs cache, as at this point extensions are not loaded yet
432
+ // so it might save a wrong deps into the cache
433
+ { loadExtensions: false, executeLoadSlot: false },
434
+ loadOpts || {}
435
+ );
436
+
437
+ const idsIndex = {};
438
+
439
+ workspaceIds.forEach((id) => {
440
+ idsIndex[id.toString()] = id;
441
+ });
442
+
443
+ const {
444
+ components: legacyComponents,
445
+ invalidComponents: legacyInvalidComponents,
446
+ removedComponents,
447
+ } = await this.workspace.consumer.loadComponents(
448
+ ComponentIdList.fromArray(workspaceIds),
449
+ false,
450
+ loadOptsWithDefaults
451
+ );
452
+ const allLegacyComponents = legacyComponents.concat(removedComponents);
453
+ legacyInvalidComponents.forEach((invalidComponent) => {
454
+ const entry = { id: idsIndex[invalidComponent.id.toString()], err: invalidComponent.error };
455
+ if (ConsumerComponent.isComponentInvalidByErrorType(invalidComponent.error)) {
456
+ if (throwOnFailure) throw invalidComponent.error;
457
+ invalidComponents.push(entry);
458
+ }
459
+ if (
460
+ this.isComponentNotExistsError(invalidComponent.error) ||
461
+ invalidComponent.error instanceof ComponentNotFoundInPath
462
+ ) {
463
+ errors.push(entry);
464
+ }
465
+ });
466
+
467
+ const getWithCatch = (id, legacyComponent) => {
468
+ return this.get(id, legacyComponent, undefined, undefined, loadOptsWithDefaults).catch((err) => {
48
469
  if (ConsumerComponent.isComponentInvalidByErrorType(err) && !throwOnFailure) {
49
470
  invalidComponents.push({
50
471
  id,
@@ -61,16 +482,54 @@ export class WorkspaceComponentLoader {
61
482
  }
62
483
  throw err;
63
484
  });
64
- });
65
- const components = await componentsP;
485
+ };
486
+
487
+ // await this.getConsumerComponent(id, loadOpts)
488
+ const componentsP = pMap(
489
+ allLegacyComponents,
490
+ (legacyComponent) => {
491
+ // const componentsP = Promise.all(
492
+ // allLegacyComponents.map(async (legacyComponent) => {
493
+ let id = idsIndex[legacyComponent.id.toString()];
494
+ if (!id) {
495
+ const withoutVersion = idsIndex[legacyComponent.id.toStringWithoutVersion()] || legacyComponent.id;
496
+ if (withoutVersion) {
497
+ id = withoutVersion.changeVersion(legacyComponent.id.version);
498
+ idsIndex[legacyComponent.id.toString()] = id;
499
+ }
500
+ }
501
+ return getWithCatch(id, legacyComponent);
502
+ },
503
+ {
504
+ concurrency: concurrentComponentsLimit(),
505
+ }
506
+ );
507
+
66
508
  errors.forEach((err) => {
67
509
  this.logger.console(`failed loading component ${err.id.toString()}, see full error in debug.log file`);
68
510
  this.logger.warn(`failed loading component ${err.id.toString()}`, err.err);
69
511
  });
70
- // remove errored components
71
- const filteredComponents: Component[] = compact(components);
72
- longProcessLogger.end();
73
- return { components: filteredComponents, invalidComponents };
512
+ const components: Component[] = compact(await componentsP);
513
+
514
+ // Here we need to load many, otherwise we will get wrong overrides dependencies data
515
+ // as when loading the next batch of components (next group) we won't have the envs loaded
516
+
517
+ try {
518
+ // We don't want to load envs as part of this step, they will be loaded later
519
+ const scopeComponents = await this.workspace.scope.loadMany(scopeIds, undefined, {
520
+ loadApps: false,
521
+ loadEnvs: false,
522
+ });
523
+ return {
524
+ workspaceComponents: components,
525
+ scopeComponents,
526
+ invalidComponents,
527
+ };
528
+ } catch (err) {
529
+ const wsAspectLoader = this.workspace.getWorkspaceAspectsLoader();
530
+ wsAspectLoader.throwWsJsoncAspectNotFoundError(err);
531
+ throw err;
532
+ }
74
533
  }
75
534
 
76
535
  async getInvalid(ids: Array<ComponentID>): Promise<InvalidComponent[]> {
@@ -100,24 +559,30 @@ export class WorkspaceComponentLoader {
100
559
  legacyComponent?: ConsumerComponent,
101
560
  useCache = true,
102
561
  storeInCache = true,
103
- loadOpts?: ComponentLoadOptions
562
+ loadOpts?: ComponentLoadOptions,
563
+ getOpts: ComponentGetOneOptions = { resolveIdVersion: true }
104
564
  ): Promise<Component> {
105
- const bitIdWithVersion: ComponentID = getLatestVersionNumber(
106
- this.workspace.consumer.bitmapIdsFromCurrentLaneIncludeRemoved,
107
- componentId
565
+ const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(
566
+ { loadExtensions: true, executeLoadSlot: true },
567
+ loadOpts || {}
108
568
  );
109
- const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
110
- const fromCache = this.getFromCache(id, loadOpts);
569
+ const id = getOpts?.resolveIdVersion ? this.resolveVersion(componentId) : componentId;
570
+ const fromCache = this.getFromCache(componentId, loadOptsWithDefaults);
111
571
  if (fromCache && useCache) {
112
572
  return fromCache;
113
573
  }
114
- const consumerComponent = legacyComponent || (await this.getConsumerComponent(id, loadOpts));
574
+ let consumerComponent = legacyComponent;
575
+ const inWs = await this.isInWsIncludeDeleted(componentId);
576
+ if (inWs && !consumerComponent) {
577
+ consumerComponent = await this.getConsumerComponent(id, loadOptsWithDefaults);
578
+ }
579
+
115
580
  // in case of out-of-sync, the id may changed during the load process
116
581
  const updatedId = consumerComponent ? consumerComponent.id : id;
117
- const component = await this.loadOne(updatedId, consumerComponent, loadOpts);
582
+ const component = await this.loadOne(updatedId, consumerComponent, loadOptsWithDefaults);
118
583
  if (storeInCache) {
119
584
  this.addMultipleEnvsIssueIfNeeded(component); // it's in storeInCache block, otherwise, it wasn't fully loaded
120
- this.saveInCache(component, loadOpts);
585
+ this.saveInCache(component, loadOptsWithDefaults);
121
586
  }
122
587
  return component;
123
588
  }
@@ -133,6 +598,15 @@ export class WorkspaceComponentLoader {
133
598
  }
134
599
  }
135
600
 
601
+ private resolveVersion(componentId: ComponentID): ComponentID {
602
+ const bitIdWithVersion: ComponentID = getLatestVersionNumber(
603
+ this.workspace.consumer.bitmapIdsFromCurrentLaneIncludeRemoved,
604
+ componentId
605
+ );
606
+ const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
607
+ return id;
608
+ }
609
+
136
610
  private addMultipleEnvsIssueIfNeeded(component: Component) {
137
611
  const envs = this.envs.getAllEnvsConfiguredOnComponent(component);
138
612
  const envIds = uniq(envs.map((env) => env.id));
@@ -144,7 +618,11 @@ export class WorkspaceComponentLoader {
144
618
 
145
619
  clearCache() {
146
620
  this.componentsCache.deleteAll();
621
+ this.scopeComponentsCache.deleteAll();
622
+ this.componentsExtensionsCache.deleteAll();
623
+ this.componentLoadedSelfAsAspects.deleteAll();
147
624
  }
625
+
148
626
  clearComponentCache(id: ComponentID) {
149
627
  const idStr = id.toString();
150
628
  for (const cacheKey of this.componentsCache.keys()) {
@@ -155,12 +633,22 @@ export class WorkspaceComponentLoader {
155
633
  }
156
634
 
157
635
  private async loadOne(id: ComponentID, consumerComponent?: ConsumerComponent, loadOpts?: ComponentLoadOptions) {
158
- const componentFromScope = await this.workspace.scope.get(id);
636
+ const idStr = id.toString();
637
+ const componentFromScope = this.scopeComponentsCache.has(idStr)
638
+ ? this.scopeComponentsCache.get(idStr)
639
+ : await this.workspace.scope.get(id);
159
640
  if (!consumerComponent) {
160
641
  if (!componentFromScope) throw new MissingBitMapComponent(id.toString());
161
642
  return componentFromScope;
162
643
  }
163
- const { extensions, errors } = await this.workspace.componentExtensions(id, componentFromScope);
644
+ const extErrorsFromCache = this.componentsExtensionsCache.has(idStr)
645
+ ? this.componentsExtensionsCache.get(idStr)
646
+ : undefined;
647
+ const { extensions, errors } =
648
+ extErrorsFromCache ||
649
+ (await this.workspace.componentExtensions(id, componentFromScope, undefined, {
650
+ loadExtensions: loadOpts?.loadExtensions,
651
+ }));
164
652
  if (errors?.some((err) => err instanceof MergeConfigConflict)) {
165
653
  consumerComponent.issues.getOrCreate(IssuesClasses.MergeConfigHasConflict).data = true;
166
654
  }
@@ -187,10 +675,17 @@ export class WorkspaceComponentLoader {
187
675
  componentFromScope.tags,
188
676
  this.workspace
189
677
  );
190
- const updatedComp = await this.executeLoadSlot(workspaceComponent, loadOpts);
191
- return updatedComp;
678
+ if (loadOpts?.executeLoadSlot) {
679
+ return this.executeLoadSlot(workspaceComponent, loadOpts);
680
+ }
681
+ // const updatedComp = await this.executeLoadSlot(workspaceComponent, loadOpts);
682
+ return workspaceComponent;
192
683
  }
193
- return this.executeLoadSlot(this.newComponentFromState(id, state), loadOpts);
684
+ const newComponent = this.newComponentFromState(id, state);
685
+ if (!loadOpts?.executeLoadSlot) {
686
+ return newComponent;
687
+ }
688
+ return this.executeLoadSlot(newComponent, loadOpts);
194
689
  }
195
690
 
196
691
  private saveInCache(component: Component, loadOpts?: ComponentLoadOptions): void {
@@ -205,9 +700,16 @@ export class WorkspaceComponentLoader {
205
700
  * as a result, when out-of-sync is happening and the id is changed to include scope-name in the
206
701
  * legacy-id, the component is the cache has the old id.
207
702
  */
208
- private getFromCache(id: ComponentID, loadOpts?: ComponentLoadOptions): Component | undefined {
703
+ private getFromCache(componentId: ComponentID, loadOpts?: ComponentLoadOptions): Component | undefined {
704
+ const bitIdWithVersion: ComponentID = this.resolveVersion(componentId);
705
+ const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
209
706
  const cacheKey = createComponentCacheKey(id, loadOpts);
210
- const fromCache = this.componentsCache.get(cacheKey);
707
+ // If we try to look for the cache without load extensions/ without execute load slot
708
+ // but there is an entry after the load, we want to use it as well.
709
+ // as we want the component, so if we already loaded it with everything, it's fine.
710
+ // this sometime relevant for cases with tiny cache size (during tag)
711
+ const cacheKeyWithTrueLoadOpts = createComponentCacheKey(id, { loadExtensions: true, executeLoadSlot: true });
712
+ const fromCache = this.componentsCache.get(cacheKey) || this.componentsCache.get(cacheKeyWithTrueLoadOpts);
211
713
  if (fromCache && fromCache.id.isEqual(id)) {
212
714
  return fromCache;
213
715
  }
@@ -313,7 +815,8 @@ export class WorkspaceComponentLoader {
313
815
  }
314
816
 
315
817
  function createComponentCacheKey(id: ComponentID, loadOpts?: ComponentLoadOptions): string {
316
- return `${id.toString()}:${JSON.stringify(sortKeys(loadOpts ?? {}))}`;
818
+ const relevantOpts = pick(loadOpts, ['loadExtensions', 'executeLoadSlot']);
819
+ return `${id.toString()}:${JSON.stringify(sortKeys(relevantOpts ?? {}))}`;
317
820
  }
318
821
 
319
822
  function sortKeys(obj: Object) {