@teambit/scope 0.0.1002 → 0.0.1004

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.
@@ -6,12 +6,11 @@ import { CLIMain } from '@teambit/cli';
6
6
  import type { ComponentMain, ComponentMap, ResolveAspectsOptions } from '@teambit/component';
7
7
  import { Component, ComponentFactory, ComponentID, Snap, State } from '@teambit/component';
8
8
  import type { GraphqlMain } from '@teambit/graphql';
9
- import { Harmony, SlotRegistry, ExtensionManifest, Aspect } from '@teambit/harmony';
9
+ import { Harmony, SlotRegistry } from '@teambit/harmony';
10
10
  import { IsolatorMain } from '@teambit/isolator';
11
11
  import { LoggerMain, Logger } from '@teambit/logger';
12
12
  import { ExpressMain } from '@teambit/express';
13
13
  import type { UiMain } from '@teambit/ui';
14
- import { RequireableComponent } from '@teambit/harmony.modules.requireable-component';
15
14
  import { BitId } from '@teambit/legacy-bit-id';
16
15
  import { BitIds as ComponentsIds } from '@teambit/legacy/dist/bit-id';
17
16
  import { ModelComponent, Lane } from '@teambit/legacy/dist/scope/models';
@@ -24,13 +23,14 @@ import { CompIdGraph } from '@teambit/graph';
24
23
  import { Types } from '@teambit/legacy/dist/scope/object-registrar';
25
24
  import { FETCH_OPTIONS } from '@teambit/legacy/dist/api/scope/lib/fetch';
26
25
  import { ObjectList } from '@teambit/legacy/dist/scope/objects/object-list';
26
+ import { RequireableComponent } from '@teambit/harmony.modules.requireable-component';
27
27
  import { AuthData } from '@teambit/legacy/dist/scope/network/http/http';
28
28
  import ConsumerComponent from '@teambit/legacy/dist/consumer/component';
29
29
  import { ExtensionDataList } from '@teambit/legacy/dist/consumer/config';
30
30
  import { EnvsMain } from '@teambit/envs';
31
31
  import { ScopeComponentLoader } from './scope-component-loader';
32
32
  import { StagedConfig } from './staged-config';
33
- declare type ManifestOrAspect = ExtensionManifest | Aspect;
33
+ import { ScopeAspectsLoader, ScopeLoadAspectsOptions } from './scope-aspects-loader';
34
34
  declare type RemoteEventMetadata = {
35
35
  auth?: AuthData;
36
36
  headers?: {};
@@ -108,6 +108,7 @@ export declare class ScopeMain implements ComponentFactory {
108
108
  * slot registry for subscribing to build
109
109
  */
110
110
  config: ScopeConfig, postPutSlot: OnPostPutSlot, postDeleteSlot: OnPostDeleteSlot, postExportSlot: OnPostExportSlot, postObjectsPersist: OnPostObjectsPersistSlot, preFetchObjects: OnPreFetchObjectsSlot, isolator: IsolatorMain, aspectLoader: AspectLoaderMain, logger: Logger, envs: EnvsMain, dependencyResolver: DependencyResolverMain);
111
+ priority?: boolean | undefined;
111
112
  /**
112
113
  * name of the scope
113
114
  */
@@ -118,7 +119,15 @@ export declare class ScopeMain implements ComponentFactory {
118
119
  get path(): string;
119
120
  get isLegacy(): boolean;
120
121
  reloadAspectsWithNewVersion(components: ConsumerComponent[]): Promise<void>;
122
+ loadAspects(ids: string[], throwOnError?: boolean | undefined, neededFor?: string | undefined, lane?: Lane, opts?: ScopeLoadAspectsOptions): Promise<string[]>;
123
+ resolveAspects(runtimeName?: string | undefined, componentIds?: ComponentID[] | undefined, opts?: ResolveAspectsOptions | undefined): Promise<AspectDefinition[]>;
124
+ getResolvedAspects(components: Component[], opts?: {
125
+ skipIfExists?: boolean;
126
+ packageManagerConfigRootDir?: string;
127
+ }): Promise<RequireableComponent[]>;
128
+ getAspectCapsulePath(): string;
121
129
  getManyByLegacy(components: ConsumerComponent[]): Promise<Component[]>;
130
+ getScopeAspectsLoader(): ScopeAspectsLoader;
122
131
  clearCache(): void;
123
132
  builderDataMapToLegacyOnTagResults(builderDataComponentMap: ComponentMap<RawBuilderData>): LegacyOnTagResult[];
124
133
  /**
@@ -156,41 +165,6 @@ export declare class ScopeMain implements ComponentFactory {
156
165
  }, headers?: Record<string, any>): Promise<import("@teambit/legacy/dist/scope/removed-components").RemovedObjectSerialized>;
157
166
  toObjectList(types: Types): Promise<ObjectList>;
158
167
  private toJs;
159
- private parseLocalAspect;
160
- private findRuntime;
161
- private findAspectFile;
162
- private loadAspectFromPath;
163
- private localAspects;
164
- loadAspects(ids: string[], throwOnError?: boolean, neededFor?: string, lane?: Lane): Promise<string[]>;
165
- /**
166
- * This function get's a list of aspect ids and return them grouped by whether any of them is the env of other from the list
167
- * @param ids
168
- */
169
- groupAspectIdsByEnvOfTheList(ids: string[], lane?: Lane): Promise<{
170
- envs?: string[];
171
- other?: string[];
172
- }>;
173
- private getManifestsAndLoadAspects;
174
- getManifestsGraphRecursively(ids: string[], visited?: string[], throwOnError?: boolean, lane?: Lane, opts?: {
175
- packageManagerConfigRootDir?: string;
176
- }): Promise<{
177
- manifests: ManifestOrAspect[];
178
- potentialPluginsIds: string[];
179
- }>;
180
- private getNonLoadedAspects;
181
- private resolveLocalAspects;
182
- getResolvedAspects(components: Component[], opts?: {
183
- skipIfExists?: boolean;
184
- packageManagerConfigRootDir?: string;
185
- }): Promise<RequireableComponent[]>;
186
- private compileIfNoDist;
187
- private tryCompile;
188
- requireAspects(components: Component[], throwOnError?: boolean, opts?: {
189
- packageManagerConfigRootDir?: string;
190
- }): Promise<Array<ExtensionManifest | Aspect>>;
191
- getAspectCapsulePath(): string;
192
- private resolveUserAspects;
193
- resolveAspects(runtimeName?: string, componentIds?: ComponentID[], opts?: ResolveAspectsOptions): Promise<AspectDefinition[]>;
194
168
  getGraph(ids?: ComponentID[]): Promise<Graph<Component, string>>;
195
169
  getGraphIds(ids?: ComponentID[]): Promise<CompIdGraph>;
196
170
  private getSavedGraphOfComponentIfExist;
@@ -325,7 +299,7 @@ export declare class ScopeMain implements ComponentFactory {
325
299
  */
326
300
  static slots: (((registerFn: () => string) => SlotRegistry<OnPostPut>) | ((registerFn: () => string) => SlotRegistry<OnPostObjectsPersist>) | ((registerFn: () => string) => SlotRegistry<OnPreFetchObjects>))[];
327
301
  static runtime: import("@teambit/harmony").RuntimeDefinition;
328
- static dependencies: Aspect[];
302
+ static dependencies: import("@teambit/harmony").Aspect[];
329
303
  static defaultConfig: ScopeConfig;
330
304
  static provider([componentExt, ui, graphql, cli, isolator, aspectLoader, express, loggerMain, envs, depsResolver]: [
331
305
  ComponentMain,
@@ -3,10 +3,8 @@
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
4
  require("core-js/modules/es.symbol.description.js");
5
5
  require("core-js/modules/es.array.flat.js");
6
- require("core-js/modules/es.array.flat-map.js");
7
6
  require("core-js/modules/es.array.iterator.js");
8
7
  require("core-js/modules/es.array.unscopables.flat.js");
9
- require("core-js/modules/es.array.unscopables.flat-map.js");
10
8
  require("core-js/modules/es.promise.js");
11
9
  require("core-js/modules/es.regexp.exec.js");
12
10
  require("core-js/modules/es.string.replace.js");
@@ -57,20 +55,6 @@ function _builder() {
57
55
  };
58
56
  return data;
59
57
  }
60
- function _fsExtra() {
61
- const data = require("fs-extra");
62
- _fsExtra = function () {
63
- return data;
64
- };
65
- return data;
66
- }
67
- function _path() {
68
- const data = require("path");
69
- _path = function () {
70
- return data;
71
- };
72
- return data;
73
- }
74
58
  function _aspectLoader() {
75
59
  const data = require("@teambit/aspect-loader");
76
60
  _aspectLoader = function () {
@@ -134,13 +118,6 @@ function _ui() {
134
118
  };
135
119
  return data;
136
120
  }
137
- function _harmonyModules() {
138
- const data = require("@teambit/harmony.modules.requireable-component");
139
- _harmonyModules = function () {
140
- return data;
141
- };
142
- return data;
143
- }
144
121
  function _legacyBitId() {
145
122
  const data = require("@teambit/legacy-bit-id");
146
123
  _legacyBitId = function () {
@@ -169,13 +146,6 @@ function _scopeLoader() {
169
146
  };
170
147
  return data;
171
148
  }
172
- function _constants() {
173
- const data = require("@teambit/legacy/dist/constants");
174
- _constants = function () {
175
- return data;
176
- };
177
- return data;
178
- }
179
149
  function _actions() {
180
150
  const data = require("@teambit/legacy/dist/scope/actions");
181
151
  _actions = function () {
@@ -330,6 +300,13 @@ function _noIdMatchPattern() {
330
300
  };
331
301
  return data;
332
302
  }
303
+ function _scopeAspectsLoader() {
304
+ const data = require("./scope-aspects-loader");
305
+ _scopeAspectsLoader = function () {
306
+ return data;
307
+ };
308
+ return data;
309
+ }
333
310
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
334
311
  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; }
335
312
  class ScopeMain {
@@ -366,10 +343,9 @@ class ScopeMain {
366
343
  this.envs = envs;
367
344
  this.dependencyResolver = dependencyResolver;
368
345
  (0, _defineProperty2().default)(this, "componentLoader", void 0);
369
- (0, _defineProperty2().default)(this, "localAspects", []);
346
+ (0, _defineProperty2().default)(this, "priority", void 0);
370
347
  this.componentLoader = new (_scopeComponentLoader().ScopeComponentLoader)(this, this.logger);
371
348
  }
372
-
373
349
  /**
374
350
  * name of the scope
375
351
  */
@@ -429,9 +405,29 @@ class ScopeMain {
429
405
  const idsToLoad = await getAspectsByPreviouslyUsedVersion();
430
406
  await host.loadAspects(idsToLoad, false, 'scope.reloadAspectsWithNewVersion');
431
407
  }
408
+ loadAspects(ids, throwOnError, neededFor, lane, opts) {
409
+ const scopeAspectsLoader = this.getScopeAspectsLoader();
410
+ return scopeAspectsLoader.loadAspects(ids, throwOnError, neededFor, lane, opts);
411
+ }
412
+ resolveAspects(runtimeName, componentIds, opts) {
413
+ const scopeAspectsLoader = this.getScopeAspectsLoader();
414
+ return scopeAspectsLoader.resolveAspects(runtimeName, componentIds, opts);
415
+ }
416
+ async getResolvedAspects(components, opts) {
417
+ const scopeAspectsLoader = this.getScopeAspectsLoader();
418
+ return scopeAspectsLoader.getResolvedAspects(components, opts);
419
+ }
420
+ getAspectCapsulePath() {
421
+ const scopeAspectsLoader = this.getScopeAspectsLoader();
422
+ return scopeAspectsLoader.getAspectCapsulePath();
423
+ }
432
424
  getManyByLegacy(components) {
433
425
  return (0, _pMapSeries().default)(components, async component => this.getFromConsumerComponent(component));
434
426
  }
427
+ getScopeAspectsLoader() {
428
+ const scopeAspectsLoader = new (_scopeAspectsLoader().ScopeAspectsLoader)(this, this.aspectLoader, this.envs, this.isolator, this.logger);
429
+ return scopeAspectsLoader;
430
+ }
435
431
  clearCache() {
436
432
  this.logger.debug('clearing the components and the legacy cache');
437
433
  this.componentLoader.clearCache();
@@ -538,363 +534,6 @@ class ScopeMain {
538
534
  if (str.endsWith('.ts')) return str.replace('.ts', '.js');
539
535
  return str;
540
536
  }
541
- parseLocalAspect(localAspects) {
542
- const dirPaths = localAspects.map(localAspect => (0, _path().resolve)(localAspect.replace('file://', '')));
543
- const nonExistsDirPaths = dirPaths.filter(path => !(0, _fsExtra().existsSync)(path));
544
- nonExistsDirPaths.forEach(path => this.logger.warn(`no such file or directory: ${path}`));
545
- const existsDirPaths = dirPaths.filter(path => (0, _fsExtra().existsSync)(path));
546
- return existsDirPaths;
547
- }
548
- findRuntime(dirPath, runtime) {
549
- const files = (0, _fsExtra().readdirSync)((0, _path().join)(dirPath, 'dist'));
550
- return files.find(path => path.includes(`${runtime}.runtime.js`));
551
- }
552
- findAspectFile(dirPath) {
553
- const files = (0, _fsExtra().readdirSync)((0, _path().join)(dirPath, 'dist'));
554
- return files.find(path => path.includes(`.aspect.js`));
555
- }
556
- async loadAspectFromPath(localAspects) {
557
- const dirPaths = this.parseLocalAspect(localAspects);
558
- const manifests = dirPaths.map(dirPath => {
559
- const scopeRuntime = this.findRuntime(dirPath, 'scope');
560
- if (scopeRuntime) {
561
- // eslint-disable-next-line global-require, import/no-dynamic-require
562
- const module = require((0, _path().join)(dirPath, 'dist', scopeRuntime));
563
- return module.default || module;
564
- }
565
- // eslint-disable-next-line global-require, import/no-dynamic-require
566
- const module = require(dirPath);
567
- return module.default || module;
568
- });
569
- await this.aspectLoader.loadExtensionsByManifests(manifests, true);
570
- }
571
- async loadAspects(ids, throwOnError = false, neededFor, lane) {
572
- var _grouped$envs, _grouped$other;
573
- if (!ids.length) return [];
574
- // generate a random callId to be able to identify the call from the logs
575
- const callId = Math.floor(Math.random() * 1000);
576
- const loggerPrefix = `[${callId}] loadAspects,`;
577
- this.logger.info(`${loggerPrefix} loading ${ids.length} aspects.
578
- ids: ${ids.join(', ')}
579
- needed-for: ${neededFor || '<unknown>'}`);
580
- const grouped = await this.groupAspectIdsByEnvOfTheList(ids, lane);
581
- this.logger.info(`${loggerPrefix} getManifestsAndLoadAspects for grouped.envs, total ${((_grouped$envs = grouped.envs) === null || _grouped$envs === void 0 ? void 0 : _grouped$envs.length) || 0}`);
582
- const envsManifestsIds = await this.getManifestsAndLoadAspects(grouped.envs, throwOnError, lane);
583
- this.logger.info(`${loggerPrefix} getManifestsAndLoadAspects for grouped.other, total ${((_grouped$other = grouped.other) === null || _grouped$other === void 0 ? void 0 : _grouped$other.length) || 0}`);
584
- const otherManifestsIds = await this.getManifestsAndLoadAspects(grouped.other, throwOnError, lane);
585
- this.logger.debug(`${loggerPrefix} finish loading aspects`);
586
- return envsManifestsIds.concat(otherManifestsIds);
587
- }
588
-
589
- /**
590
- * This function get's a list of aspect ids and return them grouped by whether any of them is the env of other from the list
591
- * @param ids
592
- */
593
- async groupAspectIdsByEnvOfTheList(ids, lane) {
594
- const components = await this.getNonLoadedAspects(ids, lane);
595
- const envsIds = (0, _lodash().uniq)(components.map(component => this.envs.getEnvId(component)).filter(envId => !this.aspectLoader.isCoreEnv(envId)));
596
- const grouped = (0, _lodash().groupBy)(ids, id => {
597
- if (envsIds.includes(id)) return 'envs';
598
- return 'other';
599
- });
600
- return grouped;
601
- }
602
- async getManifestsAndLoadAspects(ids = [], throwOnError = false, lane) {
603
- const {
604
- manifests: scopeManifests,
605
- potentialPluginsIds
606
- } = await this.getManifestsGraphRecursively(ids, [], throwOnError, lane);
607
- await this.aspectLoader.loadExtensionsByManifests(scopeManifests);
608
- const {
609
- manifests: scopePluginsManifests
610
- } = await this.getManifestsGraphRecursively(potentialPluginsIds, [], throwOnError, lane);
611
- await this.aspectLoader.loadExtensionsByManifests(scopePluginsManifests);
612
- const allManifests = scopeManifests.concat(scopePluginsManifests);
613
- return (0, _lodash().compact)(allManifests.map(manifest => manifest.id));
614
- }
615
- async getManifestsGraphRecursively(ids, visited = [], throwOnError = false, lane, opts = {}) {
616
- ids = (0, _lodash().uniq)(ids);
617
- this.logger.debug(`getManifestsGraphRecursively, ids:\n${ids.join('\n')}`);
618
- const nonVisitedId = ids.filter(id => !visited.includes(id));
619
- if (!nonVisitedId.length) {
620
- return {
621
- manifests: [],
622
- potentialPluginsIds: []
623
- };
624
- }
625
- const components = await this.getNonLoadedAspects(nonVisitedId, lane);
626
- // Adding all the envs ids to the array to support case when one (or more) of the aspects has custom aspect env
627
- const customEnvsIds = components.map(component => this.envs.getEnvId(component)).filter(envId => !this.aspectLoader.isCoreEnv(envId));
628
- // In case there is custom env we need to load it right away, otherwise we will fail during the require aspects
629
- await this.getManifestsAndLoadAspects(customEnvsIds, undefined, lane);
630
- visited.push(...nonVisitedId);
631
- const manifests = await this.requireAspects(components, throwOnError, opts);
632
- const potentialPluginsIds = (0, _lodash().compact)(manifests.map((manifest, index) => {
633
- if (this.aspectLoader.isValidAspect(manifest)) return undefined;
634
- // return index;
635
- return components[index].id.toString();
636
- }));
637
- const depsToLoad = [];
638
- await (0, _pMapSeries().default)(manifests, async manifest => {
639
- depsToLoad.push(...(manifest.dependencies || []));
640
- // @ts-ignore
641
- (manifest._runtimes || []).forEach(runtime => {
642
- depsToLoad.push(...(runtime.dependencies || []));
643
- });
644
- const depIds = depsToLoad.map(d => d.id).filter(id => id);
645
- this.logger.debug(`getManifestsGraphRecursively, id: ${manifest.id || '<unknown>'}, found ${depIds.length}: ${depIds.join(', ')}`);
646
- const {
647
- manifests: loaded
648
- } = await this.getManifestsGraphRecursively(depIds, visited, throwOnError, lane);
649
- manifests.push(...loaded);
650
- });
651
- return {
652
- manifests,
653
- potentialPluginsIds
654
- };
655
- }
656
- async getNonLoadedAspects(ids, lane) {
657
- const notLoadedIds = ids.filter(id => !this.aspectLoader.isAspectLoaded(id));
658
- if (!notLoadedIds.length) return [];
659
- const coreAspectsStringIds = this.aspectLoader.getCoreAspectIds();
660
- const idsWithoutCore = (0, _lodash().difference)(ids, coreAspectsStringIds);
661
- const aspectIds = idsWithoutCore.filter(id => !id.startsWith('file://'));
662
- // TODO: use diff instead of filter twice
663
- const localAspects = ids.filter(id => id.startsWith('file://'));
664
- this.localAspects = this.localAspects.concat(localAspects);
665
- // load local aspects for debugging purposes.
666
- await this.loadAspectFromPath(localAspects);
667
- const componentIds = await this.resolveMultipleComponentIds(aspectIds);
668
- if (!componentIds || !componentIds.length) return [];
669
- const components = await this.import(componentIds, {
670
- reFetchUnBuiltVersion: false,
671
- preferDependencyGraph: true,
672
- lane
673
- });
674
- return components;
675
- }
676
- async resolveLocalAspects(ids, runtime) {
677
- const dirs = this.parseLocalAspect(ids);
678
- return dirs.map(dir => {
679
- const runtimeManifest = runtime ? this.findRuntime(dir, runtime) : undefined;
680
- const aspectFilePath = runtime ? this.findAspectFile(dir) : undefined;
681
- return new (_aspectLoader().AspectDefinition)(dir, aspectFilePath ? (0, _path().join)(dir, 'dist', aspectFilePath) : null, runtimeManifest ? (0, _path().join)(dir, 'dist', runtimeManifest) : null, undefined, undefined, true);
682
- });
683
- }
684
- async getResolvedAspects(components, opts) {
685
- var _opts$skipIfExists;
686
- if (!components || !components.length) return [];
687
- const network = await this.isolator.isolateComponents(components.map(c => c.id),
688
- // includeFromNestedHosts - to support case when you are in a workspace, trying to load aspect defined in the workspace.jsonc but not part of the workspace
689
- {
690
- baseDir: this.getAspectCapsulePath(),
691
- skipIfExists: (_opts$skipIfExists = opts === null || opts === void 0 ? void 0 : opts.skipIfExists) !== null && _opts$skipIfExists !== void 0 ? _opts$skipIfExists : true,
692
- seedersOnly: true,
693
- includeFromNestedHosts: true,
694
- installOptions: {
695
- copyPeerToRuntimeOnRoot: true,
696
- packageManagerConfigRootDir: opts === null || opts === void 0 ? void 0 : opts.packageManagerConfigRootDir,
697
- useNesting: true,
698
- copyPeerToRuntimeOnComponents: true,
699
- installPeersFromEnvs: true
700
- }
701
- }, this.legacyScope);
702
- const capsules = network.seedersCapsules;
703
- return capsules.map(capsule => {
704
- return new (_harmonyModules().RequireableComponent)(capsule.component, async () => {
705
- // eslint-disable-next-line global-require, import/no-dynamic-require
706
- const plugins = this.aspectLoader.getPlugins(capsule.component, capsule.path);
707
- if (plugins.has()) {
708
- await this.compileIfNoDist(capsule, capsule.component);
709
- return plugins.load(_cli().MainRuntime.name);
710
- }
711
- // eslint-disable-next-line global-require, import/no-dynamic-require
712
- const aspect = require(capsule.path);
713
- const scopeRuntime = await this.aspectLoader.getRuntimePath(capsule.component, capsule.path, 'scope');
714
- const mainRuntime = await this.aspectLoader.getRuntimePath(capsule.component, capsule.path, _cli().MainRuntime.name);
715
- const runtimePath = scopeRuntime || mainRuntime;
716
- // eslint-disable-next-line global-require, import/no-dynamic-require
717
- if (runtimePath) require(runtimePath);
718
- // eslint-disable-next-line global-require, import/no-dynamic-require
719
- return aspect;
720
- }, capsule);
721
- });
722
- }
723
- async compileIfNoDist(capsule, component) {
724
- const env = this.envs.getEnv(component);
725
- const compiler = env.env.getCompiler();
726
- const distDir = (compiler === null || compiler === void 0 ? void 0 : compiler.distDir) || _constants().DEFAULT_DIST_DIRNAME;
727
- const distExists = (0, _fsExtra().existsSync)((0, _path().join)(capsule.path, distDir));
728
- if (distExists) return;
729
- const compiledCode = component.filesystem.files.flatMap(file => {
730
- if (!compiler.isFileSupported(file.path)) {
731
- return [{
732
- outputText: file.contents.toString('utf8'),
733
- outputPath: file.path
734
- }];
735
- }
736
- if (compiler.transpileFile) {
737
- return compiler.transpileFile(file.contents.toString('utf8'), {
738
- filePath: file.path,
739
- componentDir: capsule.path
740
- });
741
- }
742
- return [];
743
- });
744
- await Promise.all((0, _lodash().compact)(compiledCode).map(compiledFile => {
745
- const path = compiler.getDistPathBySrcPath(compiledFile.outputPath);
746
- return capsule === null || capsule === void 0 ? void 0 : capsule.outputFile(path, compiledFile.outputText);
747
- }));
748
- }
749
- async tryCompile(requirableAspect) {
750
- if (requirableAspect.capsule) return this.compileIfNoDist(requirableAspect.capsule, requirableAspect.component);
751
- return undefined;
752
- }
753
- async requireAspects(components, throwOnError = false, opts = {}) {
754
- const requireableExtensions = await this.getResolvedAspects(components, opts);
755
- if (!requireableExtensions) {
756
- return [];
757
- }
758
- let error;
759
- let erroredId = '';
760
- const requireWithCatch = async requireableAspects => {
761
- error = undefined;
762
- try {
763
- const manifests = await (0, _pMapSeries().default)(requireableAspects, async requireableExtension => {
764
- try {
765
- return await this.aspectLoader.doRequire(requireableExtension);
766
- } catch (err) {
767
- erroredId = requireableExtension.component.id.toString();
768
- if (err.code === 'MODULE_NOT_FOUND') {
769
- try {
770
- await this.tryCompile(requireableExtension);
771
- return await this.aspectLoader.doRequire(requireableExtension);
772
- } catch (newErr) {
773
- error = newErr;
774
- throw newErr;
775
- }
776
- }
777
- error = err;
778
- throw err;
779
- }
780
- });
781
- return manifests;
782
- } catch (err) {
783
- return null;
784
- }
785
- };
786
- const manifests = await requireWithCatch(requireableExtensions);
787
- if (!error) {
788
- return (0, _lodash().compact)(manifests);
789
- }
790
- if (error.code === 'MODULE_NOT_FOUND') {
791
- this.logger.warn(`failed loading aspects from capsules due to MODULE_NOT_FOUND error, re-creating the capsules and trying again`);
792
- const resolvedAspectsAgain = await this.getResolvedAspects(components, _objectSpread(_objectSpread({}, opts), {}, {
793
- skipIfExists: false
794
- }));
795
- const manifestAgain = await requireWithCatch(resolvedAspectsAgain);
796
- if (!error) {
797
- return (0, _lodash().compact)(manifestAgain);
798
- }
799
- }
800
- this.aspectLoader.handleExtensionLoadingError(error, erroredId, throwOnError);
801
- return [];
802
- }
803
- getAspectCapsulePath() {
804
- return `${this.path}-aspects`;
805
- }
806
- async resolveUserAspects(runtimeName, userAspectsIds) {
807
- if (!userAspectsIds || !userAspectsIds.length) return [];
808
- const components = await this.getMany(userAspectsIds);
809
- const network = await this.isolator.isolateComponents(userAspectsIds, {
810
- baseDir: this.getAspectCapsulePath(),
811
- skipIfExists: true,
812
- // for some reason this needs to be false, otherwise tagging components in some workspaces
813
- // result in error during Preview task:
814
- // "No matching version found for <some-component-on-the-workspace>"
815
- seedersOnly: true,
816
- includeFromNestedHosts: true,
817
- installOptions: {
818
- copyPeerToRuntimeOnRoot: true,
819
- useNesting: true,
820
- copyPeerToRuntimeOnComponents: true,
821
- installPeersFromEnvs: true
822
- },
823
- host: this
824
- }, this.legacyScope);
825
- const capsules = network.seedersCapsules;
826
- const aspectDefs = await this.aspectLoader.resolveAspects(components, async component => {
827
- const capsule = capsules.getCapsule(component.id);
828
- if (!capsule) throw new Error(`failed loading aspect: ${component.id.toString()}`);
829
- const localPath = capsule.path;
830
- const runtimePath = runtimeName ? await this.aspectLoader.getRuntimePath(component, localPath, runtimeName) : null;
831
- const aspectFilePath = await this.aspectLoader.getAspectFilePath(component, localPath);
832
- this.logger.debug(`scope resolveUserAspects, resolving id: ${component.id.toString()}, localPath: ${localPath}, runtimePath: ${runtimePath}`);
833
- return {
834
- id: capsule.component.id,
835
- aspectPath: localPath,
836
- aspectFilePath,
837
- runtimePath
838
- };
839
- });
840
- return aspectDefs;
841
- }
842
- async resolveAspects(runtimeName, componentIds, opts) {
843
- const originalStringIds = componentIds === null || componentIds === void 0 ? void 0 : componentIds.map(id => id.toString());
844
- this.logger.debug(`scope resolveAspects, runtimeName: ${runtimeName}, componentIds: ${originalStringIds}`);
845
- const defaultOpts = {
846
- excludeCore: false,
847
- requestedOnly: false,
848
- filterByRuntime: true
849
- };
850
- const mergedOpts = _objectSpread(_objectSpread({}, defaultOpts), opts);
851
- const coreAspectsIds = this.aspectLoader.getCoreAspectIds();
852
- let userAspectsIds;
853
- let requestedCoreStringIds;
854
- if (componentIds && componentIds.length) {
855
- var _groupedByIsCore$true;
856
- const groupedByIsCore = (0, _lodash().groupBy)(componentIds, id => coreAspectsIds.includes(id.toString()));
857
- userAspectsIds = groupedByIsCore.false || [];
858
- requestedCoreStringIds = ((_groupedByIsCore$true = groupedByIsCore.true) === null || _groupedByIsCore$true === void 0 ? void 0 : _groupedByIsCore$true.map(id => id.toStringWithoutVersion())) || [];
859
- } else {
860
- userAspectsIds = await this.resolveMultipleComponentIds(this.aspectLoader.getUserAspects());
861
- }
862
- const withoutLocalAspects = userAspectsIds.filter(aspectId => {
863
- return !this.localAspects.find(localAspect => {
864
- return localAspect.includes(aspectId.fullName.replace('/', '.'));
865
- });
866
- });
867
- const userAspectsDefs = await this.resolveUserAspects(runtimeName, withoutLocalAspects);
868
- const localResolved = await this.resolveLocalAspects(this.localAspects, runtimeName);
869
- const coreAspectsDefs = await this.aspectLoader.getCoreAspectDefs(runtimeName);
870
- const allDefs = userAspectsDefs.concat(coreAspectsDefs).concat(localResolved);
871
- let afterExclusion = allDefs;
872
- if (mergedOpts.excludeCore) {
873
- const userAspectsIdsWithoutVersion = userAspectsIds.map(aspectId => aspectId.toStringWithoutVersion());
874
- const userAspectsIdsWithoutVersionAndCoreRequested = userAspectsIdsWithoutVersion.concat(requestedCoreStringIds);
875
- afterExclusion = allDefs.filter(def => {
876
- const id = _component().ComponentID.fromString(def.getId || '');
877
- const isTarget = userAspectsIdsWithoutVersionAndCoreRequested.includes(id.toStringWithoutVersion());
878
- // If it's core, but requested explicitly, keep it
879
- if (isTarget) return true;
880
- const isCore = coreAspectsDefs.find(coreId => def.getId === coreId.getId);
881
- return !isCore;
882
- });
883
- }
884
- const uniqDefs = (0, _lodash().uniqBy)(afterExclusion, def => `${def.aspectPath}-${def.runtimePath}`);
885
- let defs = uniqDefs;
886
- if (runtimeName && mergedOpts.filterByRuntime) {
887
- defs = defs.filter(def => def.runtimePath);
888
- }
889
- if (componentIds && componentIds.length && mergedOpts.requestedOnly) {
890
- const componentIdsString = componentIds.map(id => id.toString());
891
- defs = defs.filter(def => {
892
- var _def$component;
893
- return def.id && componentIdsString.includes(def.id) || def.component && componentIdsString.includes((_def$component = def.component) === null || _def$component === void 0 ? void 0 : _def$component.id.toString());
894
- });
895
- }
896
- return defs;
897
- }
898
537
  async getGraph(ids) {
899
538
  if (!ids || !ids.length) ids = (await this.list()).map(comp => comp.id) || [];
900
539
  const components = await this.getMany(ids);