@teambit/workspace 1.0.105 → 1.0.107

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,461 @@ 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
+ const nonCoreEnvs = groupedByIsCoreEnvs.false || [];
189
+ await this.populateScopeAndExtensionsCache(nonCoreEnvs, workspaceScopeIdsMap);
190
+ const allExtIds: Map<string, ComponentID> = new Map();
191
+ nonCoreEnvs.forEach((id) => {
192
+ const idStr = id.toString();
193
+ const fromCache = this.componentsExtensionsCache.get(idStr);
194
+ if (!fromCache || !fromCache.extensions) {
195
+ return;
196
+ }
197
+ fromCache.extensions.forEach((ext) => {
198
+ if (!allExtIds.has(ext.stringId) && ext.newExtensionId) {
199
+ allExtIds.set(ext.stringId, ext.newExtensionId);
200
+ }
201
+ });
202
+ });
203
+ const allExtCompIds = Array.from(allExtIds.values());
204
+ await this.populateScopeAndExtensionsCache(allExtCompIds || [], workspaceScopeIdsMap);
205
+
206
+ const allExtIdsStr = allExtCompIds.map((id) => id.toString());
207
+ const groupedByIsExtOfAnother = groupBy(nonCoreEnvs, (id) => {
208
+ return allExtIdsStr.includes(id.toString());
209
+ });
210
+ const extIdsFromTheList = (groupedByIsExtOfAnother.true || []).map((id) => id.toString());
211
+ const extsNotFromTheList: ComponentID[] = [];
212
+ for (const [, id] of allExtIds.entries()) {
213
+ if (!extIdsFromTheList.includes(id.toString())) {
214
+ extsNotFromTheList.push(id);
215
+ }
216
+ }
217
+
218
+ await this.groupAndUpdateIds(extsNotFromTheList, workspaceScopeIdsMap);
219
+
220
+ const layerdExtFromTheList = this.regroupExtIdsFromTheList(groupedByIsExtOfAnother.true);
221
+ const layerdExtGroups = layerdExtFromTheList.map((ids) => {
222
+ return {
223
+ ids,
224
+ core: false,
225
+ aspects: true,
226
+ seeders: true,
227
+ };
228
+ });
229
+
230
+ const groupsToHandle = [
231
+ // Always load first core envs
232
+ { ids: groupedByIsCoreEnvs.true || [], core: true, aspects: true, seeders: true },
233
+ { ids: extsNotFromTheList || [], core: false, aspects: true, seeders: false },
234
+ ...layerdExtGroups,
235
+ { ids: groupedByIsExtOfAnother.false || [], core: false, aspects: false, seeders: true },
236
+ ];
237
+ const groupsByWsScope = groupsToHandle.map((group) => {
238
+ const groupedByWsScope = groupBy(group.ids, (id) => {
239
+ return workspaceScopeIdsMap.workspaceIds.has(id.toString());
240
+ });
241
+ return {
242
+ workspaceIds: groupedByWsScope.true || [],
243
+ scopeIds: groupedByWsScope.false || [],
244
+ core: group.core,
245
+ aspects: group.aspects,
246
+ seeders: group.seeders,
247
+ };
248
+ });
249
+ return groupsByWsScope;
250
+ }
251
+
252
+ private regroupExtIdsFromTheList(ids: ComponentID[]): Array<ComponentID[]> {
253
+ // TODO: implement this function
254
+ // this should handle a case when you have:
255
+ // compA that has extA and that extA has extB
256
+ // in that case we now get the following group:
257
+ // ids: [extA, extB]
258
+ // while we need extB to be in a different group before extA
259
+ return [ids];
260
+ }
261
+
262
+ private async getAndLoadSlot(
263
+ workspaceIds: ComponentID[],
264
+ scopeIds: ComponentID[],
265
+ loadOpts: GetAndLoadSlotOpts,
266
+ throwOnFailure = true
267
+ ): Promise<GetManyRes> {
268
+ const { workspaceComponents, scopeComponents, invalidComponents } = await this.getComponentsWithoutLoadExtensions(
269
+ workspaceIds,
270
+ scopeIds,
271
+ loadOpts,
272
+ throwOnFailure
273
+ );
274
+
275
+ const components = workspaceComponents.concat(scopeComponents);
276
+
277
+ const allExtensions: ExtensionDataList[] = components.map((component) => {
278
+ return component.state._consumer.extensions;
279
+ });
280
+
281
+ // Ensure we won't load the same extension many times
282
+ // We don't want to ignore version here, as we do want to load different extensions with same id but different versions here
283
+ const mergedExtensions = ExtensionDataList.mergeConfigs(allExtensions, false);
284
+ await this.workspace.loadComponentsExtensions(mergedExtensions);
285
+ let wsComponentsWithAspects = workspaceComponents;
286
+ // if (loadOpts.seeders) {
287
+ wsComponentsWithAspects = await pMap(workspaceComponents, (component) => this.executeLoadSlot(component), {
288
+ concurrency: concurrentComponentsLimit(),
289
+ });
290
+ await this.warnAboutMisconfiguredEnvs(wsComponentsWithAspects);
291
+ // }
292
+
293
+ const withAspects = wsComponentsWithAspects.concat(scopeComponents);
294
+
295
+ // It's important to load the workspace components as aspects here
296
+ // otherwise the envs from the workspace won't be loaded at time
297
+ // so we will get wrong dependencies from component who uses envs from the workspace
298
+ if (loadOpts.loadSeedersAsAspects || (loadOpts.core && loadOpts.aspects)) {
299
+ await this.loadCompsAsAspects(workspaceComponents.concat(scopeComponents), {
300
+ loadApps: true,
301
+ loadEnvs: true,
302
+ loadAspects: loadOpts.aspects,
303
+ core: loadOpts.core,
304
+ seeders: loadOpts.seeders,
305
+ idsToNotLoadAsAspects: loadOpts.idsToNotLoadAsAspects,
306
+ });
307
+ }
308
+
309
+ return { components: withAspects, invalidComponents };
310
+ }
311
+
312
+ // TODO: this is similar to scope.main.runtime loadCompAspects func, we should merge them.
313
+ async loadCompsAsAspects(
314
+ components: Component[],
315
+ opts: LoadCompAsAspectsOptions = { loadApps: true, loadEnvs: true, loadAspects: true }
316
+ ): Promise<void> {
317
+ const aspectIds: string[] = [];
318
+ components.forEach((component) => {
319
+ const firstTimeToLoad = this.componentLoadedSelfAsAspects.get(component.id.toString()) === undefined;
320
+ const excluded = opts.idsToNotLoadAsAspects?.includes(component.id.toString());
321
+ const isCore = this.aspectLoader.isCoreAspect(component.id.toStringWithoutVersion());
322
+ const alreadyLoaded = this.aspectLoader.isAspectLoaded(component.id.toString());
323
+ const skipLoading = excluded || isCore || alreadyLoaded || !firstTimeToLoad;
324
+
325
+ if (skipLoading) {
326
+ return;
327
+ }
328
+ const idStr = component.id.toString();
329
+ const appData = component.state.aspects.get('teambit.harmony/application');
330
+ if (opts.loadApps && appData?.data?.appName) {
331
+ aspectIds.push(idStr);
332
+ this.componentLoadedSelfAsAspects.set(idStr, true);
333
+ }
334
+ const envsData = component.state.aspects.get(EnvsAspect.id);
335
+ if (opts.loadEnvs && (envsData?.data?.services || envsData?.data?.self || envsData?.data?.type === 'env')) {
336
+ aspectIds.push(idStr);
337
+ this.componentLoadedSelfAsAspects.set(idStr, true);
338
+ }
339
+ if (opts.loadAspects && envsData?.data?.type === 'aspect') {
340
+ aspectIds.push(idStr);
341
+ this.componentLoadedSelfAsAspects.set(idStr, true);
342
+ }
343
+ });
344
+ if (!aspectIds.length) return;
345
+
346
+ try {
347
+ await this.workspace.loadAspects(aspectIds, true, 'self loading aspects', {});
348
+ } catch (err: any) {
349
+ this.logger.warn(`failed loading components as aspects for components ${aspectIds.join(', ')}`, err);
350
+ // we ignore that errors at the moment
351
+ }
352
+ }
353
+
354
+ private async populateScopeAndExtensionsCache(ids: ComponentID[], workspaceScopeIdsMap: WorkspaceScopeIdsMap) {
355
+ return mapSeries(ids, async (id) => {
356
+ const idStr = id.toString();
357
+ let componentFromScope;
358
+ if (!this.scopeComponentsCache.has(idStr)) {
359
+ try {
360
+ // Do not import automatically if it's missing, it will throw an error later
361
+ componentFromScope = await this.workspace.scope.get(id, undefined, false);
362
+ if (componentFromScope) {
363
+ this.scopeComponentsCache.set(idStr, componentFromScope);
364
+ }
365
+ // This is fine here, as it will be handled later in the process
366
+ } catch (err: any) {
367
+ const wsAspectLoader = this.workspace.getWorkspaceAspectsLoader();
368
+ wsAspectLoader.throwWsJsoncAspectNotFoundError(err);
369
+ this.logger.warn(`populateScopeAndExtensionsCache - failed loading component ${idStr} from scope`, err);
370
+ }
371
+ }
372
+ if (!this.componentsExtensionsCache.has(idStr) && workspaceScopeIdsMap.workspaceIds.has(idStr)) {
373
+ componentFromScope = componentFromScope || this.scopeComponentsCache.get(idStr);
374
+ const { extensions, errors } = await this.workspace.componentExtensions(id, componentFromScope, undefined, {
375
+ loadExtensions: false,
376
+ });
377
+ this.componentsExtensionsCache.set(idStr, { extensions, errors });
378
+ }
379
+ });
380
+ }
381
+
382
+ private async warnAboutMisconfiguredEnvs(components: Component[]) {
383
+ const allIds = uniq(components.map((component) => this.envs.getEnvId(component)));
384
+ return Promise.all(allIds.map((envId) => this.workspace.warnAboutMisconfiguredEnv(envId)));
385
+ }
386
+
387
+ private async groupAndUpdateIds(
388
+ ids: ComponentID[],
389
+ existingGroups?: WorkspaceScopeIdsMap
390
+ ): Promise<WorkspaceScopeIdsMap> {
391
+ const result: WorkspaceScopeIdsMap = existingGroups || {
392
+ scopeIds: new Map(),
393
+ workspaceIds: new Map(),
394
+ };
395
+
396
+ await Promise.all(
397
+ ids.map(async (componentId) => {
398
+ const inWs = await this.isInWsIncludeDeleted(componentId);
399
+
400
+ if (!inWs) {
401
+ result.scopeIds.set(componentId.toString(), componentId);
402
+ return undefined;
403
+ }
404
+ const resolvedVersions = this.resolveVersion(componentId);
405
+ result.workspaceIds.set(resolvedVersions.toString(), resolvedVersions);
406
+ return undefined;
407
+ })
408
+ );
409
+ return result;
410
+ }
411
+
412
+ private async isInWsIncludeDeleted(componentId: ComponentID): Promise<boolean> {
413
+ const nonDeletedWsIds = await this.workspace.listIds();
414
+ const deletedWsIds = await this.workspace.locallyDeletedIds();
415
+ const allWsIds = nonDeletedWsIds.concat(deletedWsIds);
416
+ const inWs = allWsIds.find((id) => id.isEqual(componentId, { ignoreVersion: !componentId.hasVersion() }));
417
+ return !!inWs;
418
+ }
419
+
420
+ private async getComponentsWithoutLoadExtensions(
421
+ workspaceIds: ComponentID[],
422
+ scopeIds: ComponentID[],
423
+ loadOpts: GetAndLoadSlotOpts,
424
+ throwOnFailure = true
425
+ ) {
43
426
  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) => {
427
+ const errors: { id: ComponentID; err: Error }[] = [];
428
+ const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(
429
+ // We don't want to load extension or execute the load slot at this step
430
+ // we will do it later
431
+ // this important for better performance
432
+ // We don't want to store deps in fs cache, as at this point extensions are not loaded yet
433
+ // so it might save a wrong deps into the cache
434
+ { loadExtensions: false, executeLoadSlot: false },
435
+ loadOpts || {}
436
+ );
437
+
438
+ const idsIndex = {};
439
+
440
+ workspaceIds.forEach((id) => {
441
+ idsIndex[id.toString()] = id;
442
+ });
443
+
444
+ const {
445
+ components: legacyComponents,
446
+ invalidComponents: legacyInvalidComponents,
447
+ removedComponents,
448
+ } = await this.workspace.consumer.loadComponents(
449
+ ComponentIdList.fromArray(workspaceIds),
450
+ false,
451
+ loadOptsWithDefaults
452
+ );
453
+ const allLegacyComponents = legacyComponents.concat(removedComponents);
454
+ legacyInvalidComponents.forEach((invalidComponent) => {
455
+ const entry = { id: idsIndex[invalidComponent.id.toString()], err: invalidComponent.error };
456
+ if (ConsumerComponent.isComponentInvalidByErrorType(invalidComponent.error)) {
457
+ if (throwOnFailure) throw invalidComponent.error;
458
+ invalidComponents.push(entry);
459
+ }
460
+ if (
461
+ this.isComponentNotExistsError(invalidComponent.error) ||
462
+ invalidComponent.error instanceof ComponentNotFoundInPath
463
+ ) {
464
+ errors.push(entry);
465
+ }
466
+ });
467
+
468
+ const getWithCatch = (id, legacyComponent) => {
469
+ return this.get(id, legacyComponent, undefined, undefined, loadOptsWithDefaults).catch((err) => {
48
470
  if (ConsumerComponent.isComponentInvalidByErrorType(err) && !throwOnFailure) {
49
471
  invalidComponents.push({
50
472
  id,
@@ -61,16 +483,54 @@ export class WorkspaceComponentLoader {
61
483
  }
62
484
  throw err;
63
485
  });
64
- });
65
- const components = await componentsP;
486
+ };
487
+
488
+ // await this.getConsumerComponent(id, loadOpts)
489
+ const componentsP = pMap(
490
+ allLegacyComponents,
491
+ (legacyComponent) => {
492
+ // const componentsP = Promise.all(
493
+ // allLegacyComponents.map(async (legacyComponent) => {
494
+ let id = idsIndex[legacyComponent.id.toString()];
495
+ if (!id) {
496
+ const withoutVersion = idsIndex[legacyComponent.id.toStringWithoutVersion()] || legacyComponent.id;
497
+ if (withoutVersion) {
498
+ id = withoutVersion.changeVersion(legacyComponent.id.version);
499
+ idsIndex[legacyComponent.id.toString()] = id;
500
+ }
501
+ }
502
+ return getWithCatch(id, legacyComponent);
503
+ },
504
+ {
505
+ concurrency: concurrentComponentsLimit(),
506
+ }
507
+ );
508
+
66
509
  errors.forEach((err) => {
67
510
  this.logger.console(`failed loading component ${err.id.toString()}, see full error in debug.log file`);
68
511
  this.logger.warn(`failed loading component ${err.id.toString()}`, err.err);
69
512
  });
70
- // remove errored components
71
- const filteredComponents: Component[] = compact(components);
72
- longProcessLogger.end();
73
- return { components: filteredComponents, invalidComponents };
513
+ const components: Component[] = compact(await componentsP);
514
+
515
+ // Here we need to load many, otherwise we will get wrong overrides dependencies data
516
+ // as when loading the next batch of components (next group) we won't have the envs loaded
517
+
518
+ try {
519
+ // We don't want to load envs as part of this step, they will be loaded later
520
+ const scopeComponents = await this.workspace.scope.loadMany(scopeIds, undefined, {
521
+ loadApps: false,
522
+ loadEnvs: false,
523
+ });
524
+ return {
525
+ workspaceComponents: components,
526
+ scopeComponents,
527
+ invalidComponents,
528
+ };
529
+ } catch (err) {
530
+ const wsAspectLoader = this.workspace.getWorkspaceAspectsLoader();
531
+ wsAspectLoader.throwWsJsoncAspectNotFoundError(err);
532
+ throw err;
533
+ }
74
534
  }
75
535
 
76
536
  async getInvalid(ids: Array<ComponentID>): Promise<InvalidComponent[]> {
@@ -100,24 +560,30 @@ export class WorkspaceComponentLoader {
100
560
  legacyComponent?: ConsumerComponent,
101
561
  useCache = true,
102
562
  storeInCache = true,
103
- loadOpts?: ComponentLoadOptions
563
+ loadOpts?: ComponentLoadOptions,
564
+ getOpts: ComponentGetOneOptions = { resolveIdVersion: true }
104
565
  ): Promise<Component> {
105
- const bitIdWithVersion: ComponentID = getLatestVersionNumber(
106
- this.workspace.consumer.bitmapIdsFromCurrentLaneIncludeRemoved,
107
- componentId
566
+ const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(
567
+ { loadExtensions: true, executeLoadSlot: true },
568
+ loadOpts || {}
108
569
  );
109
- const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
110
- const fromCache = this.getFromCache(id, loadOpts);
570
+ const id = getOpts?.resolveIdVersion ? this.resolveVersion(componentId) : componentId;
571
+ const fromCache = this.getFromCache(componentId, loadOptsWithDefaults);
111
572
  if (fromCache && useCache) {
112
573
  return fromCache;
113
574
  }
114
- const consumerComponent = legacyComponent || (await this.getConsumerComponent(id, loadOpts));
575
+ let consumerComponent = legacyComponent;
576
+ const inWs = await this.isInWsIncludeDeleted(componentId);
577
+ if (inWs && !consumerComponent) {
578
+ consumerComponent = await this.getConsumerComponent(id, loadOptsWithDefaults);
579
+ }
580
+
115
581
  // in case of out-of-sync, the id may changed during the load process
116
582
  const updatedId = consumerComponent ? consumerComponent.id : id;
117
- const component = await this.loadOne(updatedId, consumerComponent, loadOpts);
583
+ const component = await this.loadOne(updatedId, consumerComponent, loadOptsWithDefaults);
118
584
  if (storeInCache) {
119
585
  this.addMultipleEnvsIssueIfNeeded(component); // it's in storeInCache block, otherwise, it wasn't fully loaded
120
- this.saveInCache(component, loadOpts);
586
+ this.saveInCache(component, loadOptsWithDefaults);
121
587
  }
122
588
  return component;
123
589
  }
@@ -133,6 +599,15 @@ export class WorkspaceComponentLoader {
133
599
  }
134
600
  }
135
601
 
602
+ private resolveVersion(componentId: ComponentID): ComponentID {
603
+ const bitIdWithVersion: ComponentID = getLatestVersionNumber(
604
+ this.workspace.consumer.bitmapIdsFromCurrentLaneIncludeRemoved,
605
+ componentId
606
+ );
607
+ const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
608
+ return id;
609
+ }
610
+
136
611
  private addMultipleEnvsIssueIfNeeded(component: Component) {
137
612
  const envs = this.envs.getAllEnvsConfiguredOnComponent(component);
138
613
  const envIds = uniq(envs.map((env) => env.id));
@@ -144,23 +619,45 @@ export class WorkspaceComponentLoader {
144
619
 
145
620
  clearCache() {
146
621
  this.componentsCache.deleteAll();
622
+ this.scopeComponentsCache.deleteAll();
623
+ this.componentsExtensionsCache.deleteAll();
624
+ this.componentLoadedSelfAsAspects.deleteAll();
147
625
  }
626
+
148
627
  clearComponentCache(id: ComponentID) {
149
628
  const idStr = id.toString();
150
- for (const cacheKey of this.componentsCache.keys()) {
151
- if (cacheKey === idStr || cacheKey.startsWith(`${idStr}:`)) {
152
- this.componentsCache.delete(cacheKey);
629
+ const cachesToClear = [
630
+ this.componentsCache,
631
+ this.scopeComponentsCache,
632
+ this.componentsExtensionsCache,
633
+ this.componentLoadedSelfAsAspects,
634
+ ];
635
+ cachesToClear.forEach((cache) => {
636
+ for (const cacheKey of cache.keys()) {
637
+ if (cacheKey === idStr || cacheKey.startsWith(`${idStr}:`)) {
638
+ cache.delete(cacheKey);
639
+ }
153
640
  }
154
- }
641
+ });
155
642
  }
156
643
 
157
644
  private async loadOne(id: ComponentID, consumerComponent?: ConsumerComponent, loadOpts?: ComponentLoadOptions) {
158
- const componentFromScope = await this.workspace.scope.get(id);
645
+ const idStr = id.toString();
646
+ const componentFromScope = this.scopeComponentsCache.has(idStr)
647
+ ? this.scopeComponentsCache.get(idStr)
648
+ : await this.workspace.scope.get(id);
159
649
  if (!consumerComponent) {
160
650
  if (!componentFromScope) throw new MissingBitMapComponent(id.toString());
161
651
  return componentFromScope;
162
652
  }
163
- const { extensions, errors } = await this.workspace.componentExtensions(id, componentFromScope);
653
+ const extErrorsFromCache = this.componentsExtensionsCache.has(idStr)
654
+ ? this.componentsExtensionsCache.get(idStr)
655
+ : undefined;
656
+ const { extensions, errors } =
657
+ extErrorsFromCache ||
658
+ (await this.workspace.componentExtensions(id, componentFromScope, undefined, {
659
+ loadExtensions: loadOpts?.loadExtensions,
660
+ }));
164
661
  if (errors?.some((err) => err instanceof MergeConfigConflict)) {
165
662
  consumerComponent.issues.getOrCreate(IssuesClasses.MergeConfigHasConflict).data = true;
166
663
  }
@@ -187,10 +684,17 @@ export class WorkspaceComponentLoader {
187
684
  componentFromScope.tags,
188
685
  this.workspace
189
686
  );
190
- const updatedComp = await this.executeLoadSlot(workspaceComponent, loadOpts);
191
- return updatedComp;
687
+ if (loadOpts?.executeLoadSlot) {
688
+ return this.executeLoadSlot(workspaceComponent, loadOpts);
689
+ }
690
+ // const updatedComp = await this.executeLoadSlot(workspaceComponent, loadOpts);
691
+ return workspaceComponent;
192
692
  }
193
- return this.executeLoadSlot(this.newComponentFromState(id, state), loadOpts);
693
+ const newComponent = this.newComponentFromState(id, state);
694
+ if (!loadOpts?.executeLoadSlot) {
695
+ return newComponent;
696
+ }
697
+ return this.executeLoadSlot(newComponent, loadOpts);
194
698
  }
195
699
 
196
700
  private saveInCache(component: Component, loadOpts?: ComponentLoadOptions): void {
@@ -205,9 +709,16 @@ export class WorkspaceComponentLoader {
205
709
  * as a result, when out-of-sync is happening and the id is changed to include scope-name in the
206
710
  * legacy-id, the component is the cache has the old id.
207
711
  */
208
- private getFromCache(id: ComponentID, loadOpts?: ComponentLoadOptions): Component | undefined {
712
+ private getFromCache(componentId: ComponentID, loadOpts?: ComponentLoadOptions): Component | undefined {
713
+ const bitIdWithVersion: ComponentID = this.resolveVersion(componentId);
714
+ const id = bitIdWithVersion.version ? componentId.changeVersion(bitIdWithVersion.version) : componentId;
209
715
  const cacheKey = createComponentCacheKey(id, loadOpts);
210
- const fromCache = this.componentsCache.get(cacheKey);
716
+ // If we try to look for the cache without load extensions/ without execute load slot
717
+ // but there is an entry after the load, we want to use it as well.
718
+ // as we want the component, so if we already loaded it with everything, it's fine.
719
+ // this sometime relevant for cases with tiny cache size (during tag)
720
+ const cacheKeyWithTrueLoadOpts = createComponentCacheKey(id, { loadExtensions: true, executeLoadSlot: true });
721
+ const fromCache = this.componentsCache.get(cacheKey) || this.componentsCache.get(cacheKeyWithTrueLoadOpts);
211
722
  if (fromCache && fromCache.id.isEqual(id)) {
212
723
  return fromCache;
213
724
  }
@@ -313,7 +824,8 @@ export class WorkspaceComponentLoader {
313
824
  }
314
825
 
315
826
  function createComponentCacheKey(id: ComponentID, loadOpts?: ComponentLoadOptions): string {
316
- return `${id.toString()}:${JSON.stringify(sortKeys(loadOpts ?? {}))}`;
827
+ const relevantOpts = pick(loadOpts, ['loadExtensions', 'executeLoadSlot']);
828
+ return `${id.toString()}:${JSON.stringify(sortKeys(relevantOpts ?? {}))}`;
317
829
  }
318
830
 
319
831
  function sortKeys(obj: Object) {